wuying-agentbay-sdk 0.10.2 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-BVWUCG4J.mjs +3402 -0
- package/dist/chunk-BVWUCG4J.mjs.map +1 -0
- package/dist/chunk-SL5GCAQE.cjs +3393 -0
- package/dist/chunk-SL5GCAQE.cjs.map +1 -0
- package/dist/index.cjs +4623 -3978
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.mts +3934 -1964
- package/dist/index.d.ts +3934 -1964
- package/dist/index.mjs +4601 -3956
- package/dist/index.mjs.map +1 -1
- package/dist/key-normalizer-AF7APGQZ.cjs +136 -0
- package/dist/key-normalizer-AF7APGQZ.cjs.map +1 -0
- package/dist/key-normalizer-QDBRLFHF.mjs +145 -0
- package/dist/key-normalizer-QDBRLFHF.mjs.map +1 -0
- package/dist/model-CNCGFWJH.cjs +200 -0
- package/dist/model-CNCGFWJH.cjs.map +1 -0
- package/dist/model-LGWQJWKQ.mjs +209 -0
- package/docs/api/README.md +26 -0
- package/docs/api/browser-use/browser.md +177 -0
- package/docs/api/browser-use/extension.md +284 -0
- package/docs/api/codespace/code.md +77 -0
- package/docs/api/common-features/advanced/agent.md +84 -0
- package/docs/api/common-features/advanced/oss.md +221 -0
- package/docs/api/common-features/basics/agentbay.md +277 -0
- package/docs/api/common-features/basics/command.md +83 -0
- package/docs/api/common-features/basics/context-manager.md +149 -0
- package/docs/api/common-features/basics/context-sync.md +51 -0
- package/docs/api/common-features/basics/context.md +348 -0
- package/docs/api/common-features/basics/filesystem.md +499 -0
- package/docs/api/common-features/basics/logging.md +77 -0
- package/docs/api/common-features/basics/session.md +542 -0
- package/docs/api/computer-use/computer.md +786 -0
- package/docs/api/mobile-use/mobile.md +395 -0
- package/docs/examples/README.md +332 -0
- package/docs/examples/basic-usage.ts +86 -0
- package/docs/examples/browser-use/browser/README.md +356 -0
- package/docs/examples/browser-use/browser/basic-usage.ts +136 -0
- package/docs/examples/browser-use/browser/browser-command-args.ts +117 -0
- package/docs/examples/browser-use/browser/browser-context-cookie-persistence.ts +348 -0
- package/docs/examples/browser-use/browser/browser-fingerprint-basic-usage.ts +121 -0
- package/docs/examples/browser-use/browser/browser-fingerprint-construct.ts +114 -0
- package/docs/examples/browser-use/browser/browser-fingerprint-local-sync.ts +98 -0
- package/docs/examples/browser-use/browser/browser-fingerprint-persistence.ts +242 -0
- package/docs/examples/browser-use/browser/browser-proxies.ts +149 -0
- package/docs/examples/browser-use/browser/browser-type-example.ts +266 -0
- package/docs/examples/browser-use/browser/browser-viewport.ts +129 -0
- package/docs/examples/browser-use/browser/call_for_user_jd.ts +184 -0
- package/docs/examples/browser-use/browser/captcha_tongcheng.ts +151 -0
- package/docs/examples/browser-use/browser/run-2048.ts +209 -0
- package/docs/examples/browser-use/browser/run-sudoku.ts +150 -0
- package/docs/examples/browser-use/browser/screenshot-example.ts +132 -0
- package/docs/examples/browser-use/extension-example/README.md +252 -0
- package/docs/examples/browser-use/extension-example/extension-example.ts +381 -0
- package/docs/examples/codespace/automation/automation-example.ts +322 -0
- package/docs/examples/common-features/advanced/agent-module-example/README.md +40 -0
- package/docs/examples/common-features/advanced/agent-module-example.ts +66 -0
- package/docs/examples/common-features/advanced/archive-upload-mode-example/README.md +212 -0
- package/docs/examples/common-features/advanced/archive-upload-mode-example/archive-upload-mode-example.ts +213 -0
- package/docs/examples/common-features/advanced/vpc-session-example/README.md +47 -0
- package/docs/examples/common-features/advanced/vpc-session-example.ts +106 -0
- package/docs/examples/common-features/basics/archive-upload-mode-example/README.md +236 -0
- package/docs/examples/common-features/basics/archive-upload-mode-example/main.ts +236 -0
- package/docs/examples/common-features/basics/command-example/README.md +47 -0
- package/docs/examples/common-features/basics/command-example/command-example.ts +153 -0
- package/docs/examples/common-features/basics/context-management/README.md +55 -0
- package/docs/examples/common-features/basics/context-management/context-management.ts +140 -0
- package/docs/examples/common-features/basics/data-persistence/README.md +129 -0
- package/docs/examples/common-features/basics/data-persistence/context-sync-demo.md +144 -0
- package/docs/examples/common-features/basics/data-persistence/context-sync-demo.ts +275 -0
- package/docs/examples/common-features/basics/data-persistence/data-persistence.ts +259 -0
- package/docs/examples/common-features/basics/data-persistence/recycle-policy-example.ts +294 -0
- package/docs/examples/common-features/basics/filesystem-example/README.md +57 -0
- package/docs/examples/common-features/basics/filesystem-example/filesystem-example.ts +164 -0
- package/docs/examples/common-features/basics/filesystem-example/filesystem-filetransfer-example.ts +153 -0
- package/docs/examples/common-features/basics/filesystem-example/watch-directory-example.ts +168 -0
- package/docs/examples/common-features/basics/get/README.md +136 -0
- package/docs/examples/common-features/basics/get/main.ts +79 -0
- package/docs/examples/common-features/basics/list_sessions/README.md +54 -0
- package/docs/examples/common-features/basics/list_sessions/main.ts +258 -0
- package/docs/examples/common-features/basics/mcp_tool_direct_call/README.md +142 -0
- package/docs/examples/common-features/basics/mcp_tool_direct_call/main.ts +135 -0
- package/docs/examples/common-features/basics/session-creation/README.md +28 -0
- package/docs/examples/common-features/basics/session-creation/session-creation.ts +295 -0
- package/docs/examples/common-features/basics/session-pause-resume/README.md +53 -0
- package/docs/examples/common-features/basics/session-pause-resume/session-pause-resume.ts +237 -0
- package/docs/examples/mobile-use/mobile-get-adb-url/README.md +92 -0
- package/docs/examples/mobile-use/mobile-get-adb-url/index.ts +80 -0
- package/docs/examples/mobile-use/mobile-get-adb-url/package-lock.json +279 -0
- package/docs/examples/mobile-use/mobile-get-adb-url/package.json +18 -0
- package/docs/examples/mobile-use/mobile-simulate-basic-usage.ts +202 -0
- package/docs/examples/mobile-use/mobile-simulate-with-ctx.ts +170 -0
- package/package.json +19 -12
- package/dist/application-KZWXH46T.mjs +0 -17
- package/dist/application-LMA7KSRH.cjs +0 -8
- package/dist/application-LMA7KSRH.cjs.map +0 -1
- package/dist/chunk-BQNGKBQF.mjs +0 -386
- package/dist/chunk-BQNGKBQF.mjs.map +0 -1
- package/dist/chunk-IOVGAAJL.cjs +0 -558
- package/dist/chunk-IOVGAAJL.cjs.map +0 -1
- package/dist/chunk-UF2TC2R4.mjs +0 -567
- package/dist/chunk-UF2TC2R4.mjs.map +0 -1
- package/dist/chunk-X6MS7Z5L.cjs +0 -377
- package/dist/chunk-X6MS7Z5L.cjs.map +0 -1
- package/dist/window-DH37ZDD5.mjs +0 -17
- package/dist/window-DH37ZDD5.mjs.map +0 -1
- package/dist/window-U7N3H735.cjs +0 -8
- package/dist/window-U7N3H735.cjs.map +0 -1
- /package/dist/{application-KZWXH46T.mjs.map → model-LGWQJWKQ.mjs.map} +0 -0
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
# Context Management Example
|
|
2
|
+
|
|
3
|
+
This example demonstrates how to use the Context Management features of the AgentBay SDK for TypeScript.
|
|
4
|
+
|
|
5
|
+
## Features Demonstrated
|
|
6
|
+
|
|
7
|
+
- Listing all contexts
|
|
8
|
+
- Getting or creating a context
|
|
9
|
+
- Creating a session with a context
|
|
10
|
+
- Updating a context
|
|
11
|
+
- Clearing context data (synchronous clear)
|
|
12
|
+
- Deleting a context
|
|
13
|
+
|
|
14
|
+
## Running the Example
|
|
15
|
+
|
|
16
|
+
1. Make sure you have installed the AgentBay SDK:
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
npm install wuying-agentbay-sdk
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
2. Set your API key as an environment variable (recommended):
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
export AGENTBAY_API_KEY=your_api_key_here
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
3. Compile and run the example:
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
# Compile TypeScript
|
|
32
|
+
cd context-management
|
|
33
|
+
npx ts-node context-management.ts
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Code Explanation
|
|
37
|
+
|
|
38
|
+
The example demonstrates a full lifecycle of context management:
|
|
39
|
+
|
|
40
|
+
1. Initialize the AgentBay client with an API key
|
|
41
|
+
2. List all existing contexts to see what's available
|
|
42
|
+
3. Get an existing context by name, or create it if it doesn't exist
|
|
43
|
+
4. Create a session using the context
|
|
44
|
+
5. Update the context's properties
|
|
45
|
+
6. Clear the context's persistent data (demonstrates synchronous clear method)
|
|
46
|
+
7. Clean up by deleting the session and context
|
|
47
|
+
|
|
48
|
+
Context management allows you to work with persistent storage areas that can be used across multiple sessions. This enables scenarios like:
|
|
49
|
+
|
|
50
|
+
- Preserving file system changes between sessions
|
|
51
|
+
- Maintaining application state across session restarts
|
|
52
|
+
- Sharing data between different sessions
|
|
53
|
+
- Creating templates for quick session initialization
|
|
54
|
+
|
|
55
|
+
For more details on context management, see the [Context API Reference](../../../../api/common-features/basics/context.md) and [Data Persistence Tutorial](../../../../../../docs/guides/common-features/basics/data-persistence.md).
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import { AgentBay, logError, log, ContextSync } from 'wuying-agentbay-sdk';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Context Management Example
|
|
5
|
+
*
|
|
6
|
+
* This example demonstrates how to use the Context API in TypeScript.
|
|
7
|
+
*/
|
|
8
|
+
async function main() {
|
|
9
|
+
try {
|
|
10
|
+
// Initialize the AgentBay client
|
|
11
|
+
// You can provide the API key as a parameter or set the AGENTBAY_API_KEY environment variable
|
|
12
|
+
const apiKey = process.env.AGENTBAY_API_KEY || 'akm-xxx'; // Replace with your actual API key
|
|
13
|
+
if (!process.env.AGENTBAY_API_KEY) {
|
|
14
|
+
log('Warning: Using placeholder API key. Set AGENTBAY_API_KEY environment variable for production use.');
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const agentBay = new AgentBay({ apiKey });
|
|
18
|
+
|
|
19
|
+
// Example 1: List all contexts
|
|
20
|
+
log('\nExample 1: Listing all contexts...');
|
|
21
|
+
try {
|
|
22
|
+
const listResult = await agentBay.context.list();
|
|
23
|
+
log(`Found ${listResult.contexts.length} contexts (RequestID: ${listResult.requestId}):`);
|
|
24
|
+
for (const ctx of listResult.contexts) {
|
|
25
|
+
log(`- ${ctx.name} (${ctx.id}): state=${ctx.state}, os=${ctx.osType}`);
|
|
26
|
+
}
|
|
27
|
+
} catch (error) {
|
|
28
|
+
log(`Error listing contexts: ${error}`);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// Example 2: Get a context (create if it doesn't exist)
|
|
32
|
+
log('\nExample 2: Getting a context (creating if it doesn\'t exist)...');
|
|
33
|
+
const contextName = 'my-test-context';
|
|
34
|
+
const getResult = await agentBay.context.get(contextName, true);
|
|
35
|
+
if (!getResult.contextId || getResult.contextId === '') {
|
|
36
|
+
log('Context not found and could not be created');
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
log(`Got context: ${getResult.context.name} (${getResult.contextId}) with RequestID: ${getResult.requestId}`);
|
|
41
|
+
|
|
42
|
+
// Use the Context object directly
|
|
43
|
+
const context = getResult.context;
|
|
44
|
+
|
|
45
|
+
// Example 3: Create a session with the context
|
|
46
|
+
log('\nExample 3: Creating a session with the context...');
|
|
47
|
+
const contextSync = new ContextSync(context.id, '/mnt/persistent');
|
|
48
|
+
const sessionResult = await agentBay.create({
|
|
49
|
+
contextSync: [contextSync],
|
|
50
|
+
labels: {
|
|
51
|
+
username: 'alice',
|
|
52
|
+
project: 'my-project'
|
|
53
|
+
}
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
if (!sessionResult.session) {
|
|
57
|
+
log('Error creating session');
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
log(`Session created with ID: ${sessionResult.session.sessionId} (RequestID: ${sessionResult.requestId})`);
|
|
62
|
+
log('Note: The create() method automatically monitored the context status');
|
|
63
|
+
log('and only returned after all context operations were complete or reached maximum retries.');
|
|
64
|
+
const session = sessionResult.session;
|
|
65
|
+
|
|
66
|
+
// Example 4: Update the context
|
|
67
|
+
log('\nExample 4: Updating the context...');
|
|
68
|
+
context.name = 'renamed-test-context';
|
|
69
|
+
try {
|
|
70
|
+
const updateResult = await agentBay.context.update(context);
|
|
71
|
+
if (!updateResult.success) {
|
|
72
|
+
log('Context update was not successful');
|
|
73
|
+
} else {
|
|
74
|
+
log(`Context updated successfully to: ${context.name} (RequestID: ${updateResult.requestId})`);
|
|
75
|
+
}
|
|
76
|
+
} catch (error) {
|
|
77
|
+
log(`Error updating context: ${error}`);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// Clean up
|
|
81
|
+
log('\nCleaning up...');
|
|
82
|
+
|
|
83
|
+
// Delete the session with context synchronization
|
|
84
|
+
try {
|
|
85
|
+
log('Deleting the session with context synchronization...');
|
|
86
|
+
const deleteSessionResult = await agentBay.delete(session, true); // Using syncContext=true
|
|
87
|
+
log(`Session deleted successfully with context synchronization (RequestID: ${deleteSessionResult.requestId})`);
|
|
88
|
+
log('Note: The delete() method synchronized the context before session deletion');
|
|
89
|
+
log('and monitored all context operations until completion.');
|
|
90
|
+
|
|
91
|
+
// Alternative method using session's delete method:
|
|
92
|
+
// const deleteSessionResult = await session.delete(true);
|
|
93
|
+
} catch (error) {
|
|
94
|
+
log(`Error deleting session: ${error}`);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// Example 5: Clear context data
|
|
98
|
+
log('\nExample 5: Clearing context data...');
|
|
99
|
+
log('Starting synchronous context clear (recommended approach)...');
|
|
100
|
+
try {
|
|
101
|
+
const clearResult = await agentBay.context.clear(context.id, 30, 2.0);
|
|
102
|
+
log(`Clear result: Success=${clearResult.success}, Status=${clearResult.status}, RequestID=${clearResult.requestId}`);
|
|
103
|
+
|
|
104
|
+
if (clearResult.success) {
|
|
105
|
+
log('✅ Context data cleared successfully');
|
|
106
|
+
log(` Context ID: ${clearResult.contextId}`);
|
|
107
|
+
log(` Final Status: ${clearResult.status}`);
|
|
108
|
+
} else {
|
|
109
|
+
log(`❌ Context data clearing failed: ${clearResult.errorMessage}`);
|
|
110
|
+
}
|
|
111
|
+
} catch (clearError: any) {
|
|
112
|
+
if (clearError.message.includes('timed out')) {
|
|
113
|
+
log(`⏱️ Clear timed out: ${clearError.message}`);
|
|
114
|
+
} else {
|
|
115
|
+
log(`❌ Error during context clear: ${clearError.message}`);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// Clean up
|
|
120
|
+
log('\nCleaning up...');
|
|
121
|
+
log('Note: Context data has been cleared, but the context itself still exists.');
|
|
122
|
+
|
|
123
|
+
// Delete the context
|
|
124
|
+
log('Deleting the context...');
|
|
125
|
+
try {
|
|
126
|
+
const deleteContextResult = await agentBay.context.delete(context);
|
|
127
|
+
log(`Context deleted successfully (RequestID: ${deleteContextResult.requestId})`);
|
|
128
|
+
} catch (error) {
|
|
129
|
+
log(`Error deleting context: ${error}`);
|
|
130
|
+
}
|
|
131
|
+
} catch (error) {
|
|
132
|
+
logError(`Error initializing AgentBay: ${error}`);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// Execute the main function
|
|
137
|
+
main().catch(error => {
|
|
138
|
+
logError('Error in main execution:', error);
|
|
139
|
+
process.exit(1);
|
|
140
|
+
});
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
# Data Persistence Examples
|
|
2
|
+
|
|
3
|
+
This directory contains examples demonstrating data persistence functionality in AgentBay SDK for TypeScript.
|
|
4
|
+
|
|
5
|
+
## Examples
|
|
6
|
+
|
|
7
|
+
### 1. `data-persistence.ts` - Basic Data Persistence
|
|
8
|
+
|
|
9
|
+
Demonstrates the fundamental data persistence features:
|
|
10
|
+
|
|
11
|
+
- Context creation for persistent storage
|
|
12
|
+
- File persistence across multiple sessions
|
|
13
|
+
- Context synchronization and file sharing
|
|
14
|
+
- Multi-session data verification
|
|
15
|
+
|
|
16
|
+
### 2. `context-sync-demo.ts` - Advanced Sync with Callbacks
|
|
17
|
+
|
|
18
|
+
Demonstrates the callback-based context synchronization:
|
|
19
|
+
|
|
20
|
+
- Async context sync operations
|
|
21
|
+
- Timing analysis and performance monitoring
|
|
22
|
+
- Status verification using `context.info()`
|
|
23
|
+
- Multiple sync operations and error handling
|
|
24
|
+
- Backward compatibility with traditional sync
|
|
25
|
+
|
|
26
|
+
### 3. `recycle-policy-example.ts` - Data Lifecycle Management
|
|
27
|
+
|
|
28
|
+
Demonstrates RecyclePolicy for controlling context data lifecycle:
|
|
29
|
+
|
|
30
|
+
- Using default RecyclePolicy (keeps data forever)
|
|
31
|
+
- Setting custom lifecycle durations (1 day, 3 days, etc.)
|
|
32
|
+
- Applying RecyclePolicy to specific paths
|
|
33
|
+
- Available lifecycle options
|
|
34
|
+
|
|
35
|
+
## Key Features
|
|
36
|
+
|
|
37
|
+
### Data Persistence
|
|
38
|
+
|
|
39
|
+
- **Context Creation**: Create persistent storage contexts
|
|
40
|
+
- **Cross-Session Persistence**: Data survives session deletion
|
|
41
|
+
- **File Synchronization**: Automatic sync of files to persistent storage
|
|
42
|
+
- **Multi-Session Access**: Access data from different sessions
|
|
43
|
+
|
|
44
|
+
### Context Sync Callbacks
|
|
45
|
+
|
|
46
|
+
- **Async Operations**: Non-blocking sync operations
|
|
47
|
+
- **Real-time Feedback**: Immediate notification on completion
|
|
48
|
+
- **Timing Information**: Detailed performance metrics
|
|
49
|
+
- **Error Handling**: Graceful handling of failures and timeouts
|
|
50
|
+
- **Status Monitoring**: Track sync progress and completion
|
|
51
|
+
|
|
52
|
+
### Data Lifecycle Management
|
|
53
|
+
|
|
54
|
+
- **RecyclePolicy**: Control how long context data is retained in the cloud
|
|
55
|
+
- **Lifecycle Options**: 1 day to forever (10 options available)
|
|
56
|
+
- **Path-Specific Policies**: Apply different lifecycles to different directories
|
|
57
|
+
- **Automatic Cleanup**: Data is automatically deleted after specified duration
|
|
58
|
+
- **Path Validation**: Ensures path safety (no wildcard patterns)
|
|
59
|
+
|
|
60
|
+
## Usage
|
|
61
|
+
|
|
62
|
+
### Basic Data Persistence
|
|
63
|
+
|
|
64
|
+
```bash
|
|
65
|
+
cd typescript/docs/examples/data-persistence
|
|
66
|
+
npx ts-node data-persistence.ts
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
### Context Sync Demo
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
cd typescript/docs/examples/data-persistence
|
|
73
|
+
npx ts-node context-sync-demo.ts
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
### RecyclePolicy Example
|
|
77
|
+
|
|
78
|
+
```bash
|
|
79
|
+
cd typescript/docs/examples/data-persistence
|
|
80
|
+
npx ts-node recycle-policy-example.ts
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
## Prerequisites
|
|
84
|
+
|
|
85
|
+
- AgentBay SDK installed
|
|
86
|
+
- Valid API key configured (via environment variable `AGENTBAY_API_KEY`)
|
|
87
|
+
- Network access to AgentBay services
|
|
88
|
+
- Node.js 16 or later
|
|
89
|
+
- TypeScript 4.5 or later
|
|
90
|
+
|
|
91
|
+
## Expected Behavior
|
|
92
|
+
|
|
93
|
+
All examples will:
|
|
94
|
+
|
|
95
|
+
1. Create a persistent context
|
|
96
|
+
2. Create a session with context synchronization
|
|
97
|
+
3. Write test data to the persistent storage
|
|
98
|
+
4. Demonstrate data persistence across sessions
|
|
99
|
+
5. Clean up resources
|
|
100
|
+
|
|
101
|
+
The callback example additionally shows:
|
|
102
|
+
|
|
103
|
+
- Async sync operations with timing
|
|
104
|
+
- Callback notifications
|
|
105
|
+
- Status monitoring
|
|
106
|
+
- Error handling scenarios
|
|
107
|
+
|
|
108
|
+
## Output
|
|
109
|
+
|
|
110
|
+
All examples provide detailed console output showing:
|
|
111
|
+
|
|
112
|
+
- Step-by-step progress
|
|
113
|
+
- Success/failure status for each operation
|
|
114
|
+
- Timing information (callback example)
|
|
115
|
+
- Data verification results
|
|
116
|
+
- Cleanup confirmation
|
|
117
|
+
|
|
118
|
+
## Notes
|
|
119
|
+
|
|
120
|
+
- Examples use temporary contexts that are cleaned up after execution
|
|
121
|
+
- File paths use `/tmp/` for demonstration purposes
|
|
122
|
+
- Timing may vary based on network conditions and file sizes
|
|
123
|
+
- The callback example includes timeout handling for robustness
|
|
124
|
+
|
|
125
|
+
## Related Documentation
|
|
126
|
+
|
|
127
|
+
- [Data Persistence Guide](../../../../../../docs/guides/common-features/basics/data-persistence.md) - Comprehensive guide on data persistence
|
|
128
|
+
- [Context Management](../context-management/README.md) - Context creation and management
|
|
129
|
+
- [File Operations](../filesystem-example/README.md) - File handling and management
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
# Context Sync Dual-Mode Example (TypeScript)
|
|
2
|
+
|
|
3
|
+
This example demonstrates the dual-mode `context.sync()` functionality in the TypeScript SDK, showing both asynchronous callback-based and synchronous await-based usage patterns.
|
|
4
|
+
|
|
5
|
+
## Features Demonstrated
|
|
6
|
+
|
|
7
|
+
- **Context Creation**: Creates persistent contexts for data storage
|
|
8
|
+
- **Test Data Generation**: Creates sample files and directories for sync testing
|
|
9
|
+
- **Dual-Mode Context Sync**: Shows both callback and await patterns
|
|
10
|
+
- **Session Management**: Proper session creation and cleanup
|
|
11
|
+
- **Error Handling**: Comprehensive error handling and cleanup
|
|
12
|
+
- **Timing Measurement**: Tracks sync operation duration
|
|
13
|
+
- **Concurrent Execution**: Demonstrates running multiple sync operations
|
|
14
|
+
|
|
15
|
+
## Usage Patterns
|
|
16
|
+
|
|
17
|
+
### 1. Async Mode with Callback
|
|
18
|
+
|
|
19
|
+
```typescript
|
|
20
|
+
// Immediate return with callback handling
|
|
21
|
+
const syncResult = await session.context.sync(
|
|
22
|
+
undefined, // contextId
|
|
23
|
+
undefined, // path
|
|
24
|
+
undefined, // mode
|
|
25
|
+
(success: boolean) => {
|
|
26
|
+
if (success) {
|
|
27
|
+
console.log("✅ Context sync completed successfully");
|
|
28
|
+
} else {
|
|
29
|
+
console.log("❌ Context sync completed with failures");
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
);
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
### 2. Sync Mode with Await
|
|
36
|
+
|
|
37
|
+
```typescript
|
|
38
|
+
// Wait for completion before returning
|
|
39
|
+
const syncResult = await session.context.sync();
|
|
40
|
+
if (syncResult.success) {
|
|
41
|
+
console.log("✅ Context sync completed successfully");
|
|
42
|
+
} else {
|
|
43
|
+
console.log("❌ Context sync completed with failures");
|
|
44
|
+
}
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
## Key Differences from Python Version
|
|
48
|
+
|
|
49
|
+
- **TypeScript/JavaScript**: Uses `Promise` and `async/await` instead of Python's `asyncio`
|
|
50
|
+
- **Callback Pattern**: Uses arrow functions for callbacks
|
|
51
|
+
- **Timing**: Uses `Date.now()` for millisecond precision timing
|
|
52
|
+
- **Error Handling**: Uses try/catch blocks with Promise-based error handling
|
|
53
|
+
|
|
54
|
+
## Running the Example
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
# From the typescript directory
|
|
58
|
+
npm run build
|
|
59
|
+
node dist/docs/examples/data-persistence/context-sync-demo.js
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## Expected Output
|
|
63
|
+
|
|
64
|
+
```
|
|
65
|
+
🔄 AgentBay Context Sync Dual-Mode Example (TypeScript)
|
|
66
|
+
|
|
67
|
+
============================================================
|
|
68
|
+
🔄 Method 1: context_sync_with_callback (Async with callback)
|
|
69
|
+
============================================================
|
|
70
|
+
🔄 Starting context sync with callback demo...
|
|
71
|
+
|
|
72
|
+
📦 Creating context for persistent storage...
|
|
73
|
+
✅ Context created: sync-callback-demo
|
|
74
|
+
|
|
75
|
+
📦 Creating session with context sync...
|
|
76
|
+
✅ Session created: session-123
|
|
77
|
+
|
|
78
|
+
💾 Creating test data...
|
|
79
|
+
✅ Created file: /tmp/sync_data/test_files/small.txt
|
|
80
|
+
✅ Created file: /tmp/sync_data/test_files/medium.txt
|
|
81
|
+
✅ Created file: /tmp/sync_data/config.json
|
|
82
|
+
📊 Created 3/3 test files
|
|
83
|
+
|
|
84
|
+
📞 Calling context.sync() with callback...
|
|
85
|
+
📤 Sync initiation result: success=true, requestId=req-456
|
|
86
|
+
⏳ Waiting for callback to complete...
|
|
87
|
+
✅ Context sync completed successfully in 2000ms
|
|
88
|
+
🗑️ Deleting session from callback...
|
|
89
|
+
✅ Session deleted successfully from callback
|
|
90
|
+
|
|
91
|
+
⏳ Sleeping 3 seconds before next demo...
|
|
92
|
+
|
|
93
|
+
============================================================
|
|
94
|
+
🔄 Method 2: context_sync (Sync with await)
|
|
95
|
+
============================================================
|
|
96
|
+
🔄 Starting context sync demo...
|
|
97
|
+
|
|
98
|
+
📦 Creating context for persistent storage...
|
|
99
|
+
✅ Context created: sync-await-demo
|
|
100
|
+
|
|
101
|
+
📦 Creating session with context sync...
|
|
102
|
+
✅ Session created: session-789
|
|
103
|
+
|
|
104
|
+
💾 Creating test data...
|
|
105
|
+
✅ Created file: /tmp/sync_data/test_files/small.txt
|
|
106
|
+
✅ Created file: /tmp/sync_data/test_files/medium.txt
|
|
107
|
+
✅ Created file: /tmp/sync_data/config.json
|
|
108
|
+
📊 Created 3/3 test files
|
|
109
|
+
|
|
110
|
+
⏳ Calling context.sync() with await...
|
|
111
|
+
✅ Context sync completed successfully in 1500ms
|
|
112
|
+
📤 Sync result: success=true, requestId=req-101
|
|
113
|
+
🗑️ Deleting session...
|
|
114
|
+
✅ Session deleted successfully
|
|
115
|
+
|
|
116
|
+
⏳ Waiting for callback demo to complete...
|
|
117
|
+
|
|
118
|
+
✅ Context sync dual-mode example completed
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
## Configuration
|
|
122
|
+
|
|
123
|
+
The example uses default configuration values:
|
|
124
|
+
|
|
125
|
+
- **Max Retries**: 150 attempts
|
|
126
|
+
- **Retry Interval**: 1500ms (1.5 seconds)
|
|
127
|
+
- **Timeout**: ~5 minutes (150 × 1.5s)
|
|
128
|
+
|
|
129
|
+
## Error Handling
|
|
130
|
+
|
|
131
|
+
The example includes comprehensive error handling:
|
|
132
|
+
|
|
133
|
+
- Sync operation failures
|
|
134
|
+
- Session creation failures
|
|
135
|
+
- Session deletion failures
|
|
136
|
+
- Automatic cleanup on errors
|
|
137
|
+
|
|
138
|
+
## Integration with Session Deletion
|
|
139
|
+
|
|
140
|
+
The example demonstrates how `context.sync()` integrates with session deletion:
|
|
141
|
+
|
|
142
|
+
- Callback mode: Session deletion happens in the callback
|
|
143
|
+
- Await mode: Session deletion happens after sync completion
|
|
144
|
+
- Both modes avoid double-syncing by passing `false` to `session.delete()`
|