test-wuying-agentbay-sdk
Version:
TypeScript SDK for interacting with the Wuying AgentBay cloud runtime environment
276 lines (232 loc) ⢠9.38 kB
text/typescript
import { AgentBay, ContextSync, CreateSessionParams, newSyncPolicyWithDefaults } from 'wuying-agentbay-sdk';
/**
* Context Sync Dual-Mode Example for TypeScript SDK
*
* This example demonstrates the dual-mode context.sync() functionality:
* 1. Async mode with callback - immediate return, result handled via callback
* 2. Sync mode with await - waits for completion before returning
*/
async function contextSyncWithCallbackDemo(agentBay: AgentBay): Promise<void> {
console.log("š Starting context sync with callback demo...");
// Step 1: Create context for persistent storage
console.log("\nš¦ Creating context for persistent storage...");
const contextResult = await agentBay.context.get("sync-callback-demo", true);
if (!contextResult.success) {
throw new Error(`Context creation failed: ${contextResult.errorMessage}`);
}
const context = contextResult.context!;
console.log(`ā
Context created: ${context.id}`);
// Step 2: Create session with context sync
console.log("\nš¦ Creating session with context sync...");
const syncPolicy = newSyncPolicyWithDefaults();
const contextSync = new ContextSync(
context.id,
"/tmp/sync_data",
syncPolicy
);
const params: CreateSessionParams = {
contextSync: [contextSync]
};
const sessionResult = await agentBay.create(params);
if (!sessionResult.success) {
throw new Error(`Failed to create session: ${sessionResult.errorMessage}`);
}
const session = sessionResult.session!;
console.log(`ā
Session created: ${session.getSessionId()}`);
// Step 3: Create test data
console.log("\nš¾ Creating test data...");
await session.command.executeCommand("mkdir -p /tmp/sync_data/test_files");
const testFiles = [
{
path: "/tmp/sync_data/test_files/small.txt",
content: "Small test file content\n".repeat(10)
},
{
path: "/tmp/sync_data/test_files/medium.txt",
content: "Medium test file content\n".repeat(100)
},
{
path: "/tmp/sync_data/config.json",
content: JSON.stringify({
sync_demo: true,
created_at: new Date().toISOString(),
session_id: session.getSessionId()
}, null, 2)
}
];
let createdFiles = 0;
for (const file of testFiles) {
const writeResult = await session.fileSystem.writeFile(file.path, file.content);
if (writeResult.success) {
console.log(`ā
Created file: ${file.path}`);
createdFiles++;
} else {
console.log(`ā Failed to create file ${file.path}: ${writeResult.errorMessage}`);
}
}
console.log(`š Created ${createdFiles}/${testFiles.length} test files`);
try {
// Method 1: Async interface with callback
console.log("\nš Calling context.sync() with callback...");
const syncStartTime = Date.now();
// Use callback mode - function returns immediately
const syncResult = await session.context.sync(
undefined, // contextId
undefined, // path
undefined, // mode
(success: boolean) => {
console.log("Callback called ==============");
const callbackTime = Date.now();
const duration = callbackTime - syncStartTime;
if (success) {
console.log(`ā
Context sync completed successfully in ${duration}ms`);
} else {
console.log(`ā Context sync completed with failures in ${duration}ms`);
}
// Delete session in callback
console.log("šļø Deleting session from callback...");
session.delete(false) // Don't sync again since we already did
.then(() => {
console.log("ā
Session deleted successfully from callback");
})
.catch((error: any) => {
console.error("ā Failed to delete session from callback:", error);
});
}
);
console.log(`š¤ Sync initiation result: success=${syncResult.success}, requestId=${syncResult.requestId}`);
console.log("ā³ Waiting for callback to complete...");
// Wait a bit for the callback to complete
await new Promise(resolve => setTimeout(resolve, 10000));
} catch (error) {
console.error("ā Context sync with callback failed:", error);
// Clean up session
try {
await session.delete(false);
console.log("ā
Session cleaned up after error");
} catch (deleteError) {
console.error("ā Failed to clean up session:", deleteError);
}
}
}
async function contextSyncDemo(agentBay: AgentBay): Promise<void> {
console.log("š Starting context sync demo...");
// Step 1: Create context for persistent storage
console.log("\nš¦ Creating context for persistent storage...");
const contextResult = await agentBay.context.get("sync-await-demo", true);
if (!contextResult.success) {
throw new Error(`Context creation failed: ${contextResult.errorMessage}`);
}
const context = contextResult.context!;
console.log(`ā
Context created: ${context.id}`);
// Step 2: Create session with context sync
console.log("\nš¦ Creating session with context sync...");
const syncPolicy = newSyncPolicyWithDefaults();
const contextSync = new ContextSync(
context.id,
"/tmp/sync_data",
syncPolicy
);
const params: CreateSessionParams = {
contextSync: [contextSync]
};
const sessionResult = await agentBay.create(params);
if (!sessionResult.success) {
throw new Error(`Failed to create session: ${sessionResult.errorMessage}`);
}
const session = sessionResult.session!;
console.log(`ā
Session created: ${session.getSessionId()}`);
// Step 3: Create test data
console.log("\nš¾ Creating test data...");
await session.command.executeCommand("mkdir -p /tmp/sync_data/test_files");
const testFiles = [
{
path: "/tmp/sync_data/test_files/small.txt",
content: "Small test file content\n".repeat(10)
},
{
path: "/tmp/sync_data/test_files/medium.txt",
content: "Medium test file content\n".repeat(100)
},
{
path: "/tmp/sync_data/config.json",
content: JSON.stringify({
sync_demo: true,
created_at: new Date().toISOString(),
session_id: session.getSessionId()
}, null, 2)
}
];
let createdFiles = 0;
for (const file of testFiles) {
const writeResult = await session.fileSystem.writeFile(file.path, file.content);
if (writeResult.success) {
console.log(`ā
Created file: ${file.path}`);
createdFiles++;
} else {
console.log(`ā Failed to create file ${file.path}: ${writeResult.errorMessage}`);
}
}
console.log(`š Created ${createdFiles}/${testFiles.length} test files`);
try {
// Method 2: Sync interface with await
console.log("\nā³ Calling context.sync() with await...");
const syncStartTime = Date.now();
// Use await mode - function waits for completion
const syncResult = await session.context.sync();
const syncDuration = Date.now() - syncStartTime;
if (syncResult.success) {
console.log(`ā
Context sync completed successfully in ${syncDuration}ms`);
} else {
console.log(`ā Context sync completed with failures in ${syncDuration}ms`);
}
console.log(`š¤ Sync result: success=${syncResult.success}, requestId=${syncResult.requestId}`);
// Delete session
console.log("šļø Deleting session...");
await session.delete(false); // Don't sync again since we already did
console.log("ā
Session deleted successfully");
} catch (error) {
console.error("ā Context sync failed:", error);
// Clean up session
try {
await session.delete(false);
console.log("ā
Session cleaned up after error");
} catch (deleteError) {
console.error("ā Failed to clean up session:", deleteError);
}
}
}
async function main(): Promise<void> {
console.log("š AgentBay Context Sync Dual-Mode Example (TypeScript)");
// Initialize AgentBay client
const agentBay = new AgentBay();
try {
// Method 1: Async interface with callback
console.log("\n" + "=".repeat(60));
console.log("š Method 1: context_sync_with_callback (Async with callback)");
console.log("=".repeat(60));
// Start the first demo without waiting for it to complete
const callbackPromise = contextSyncWithCallbackDemo(agentBay);
console.log("contextSyncWithCallbackDemo started (not awaited)");
console.log("=".repeat(60));
// Sleep 3 seconds
console.log("\nā³ Sleeping 3 seconds before next demo...");
await new Promise(resolve => setTimeout(resolve, 3000));
// Method 2: Sync interface with await
console.log("\n" + "=".repeat(60));
console.log("š Method 2: context_sync (Sync with await)");
console.log("=".repeat(60));
await contextSyncDemo(agentBay); // With await
// Wait for the first demo to complete
console.log("\nā³ Waiting for callback demo to complete...");
await callbackPromise;
} catch (error) {
console.error("ā Example execution failed:", error);
}
console.log("ā
Context sync dual-mode example completed");
}
// Run the example
if (require.main === module) {
main().catch(console.error);
}
export { contextSyncDemo, contextSyncWithCallbackDemo, main };