wuying-agentbay-sdk 0.11.0 → 0.13.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.
Files changed (56) hide show
  1. package/dist/{chunk-E7QC5S76.mjs → chunk-P2CXYF4T.mjs} +650 -154
  2. package/dist/chunk-P2CXYF4T.mjs.map +1 -0
  3. package/dist/{chunk-ZUB35HKV.cjs → chunk-WVWGLZDT.cjs} +593 -97
  4. package/dist/chunk-WVWGLZDT.cjs.map +1 -0
  5. package/dist/index.cjs +7702 -687
  6. package/dist/index.cjs.map +1 -1
  7. package/dist/index.d.mts +2660 -1619
  8. package/dist/index.d.ts +2660 -1619
  9. package/dist/index.mjs +7514 -499
  10. package/dist/index.mjs.map +1 -1
  11. package/dist/{model-ZFTLKEMC.mjs → model-BRLR6F3P.mjs} +28 -2
  12. package/dist/model-KJHN3WYY.cjs +214 -0
  13. package/dist/{model-2G37RFQQ.cjs.map → model-KJHN3WYY.cjs.map} +1 -1
  14. package/docs/api/README.md +6 -0
  15. package/docs/api/browser-use/browser-agent.md +188 -0
  16. package/docs/api/browser-use/browser.md +1 -1
  17. package/docs/api/browser-use/fingerprint.md +154 -0
  18. package/docs/api/codespace/code.md +3 -0
  19. package/docs/api/common-features/advanced/agent.md +7 -63
  20. package/docs/api/common-features/advanced/browser-use-agent.md +118 -0
  21. package/docs/api/common-features/advanced/computer-use-agent.md +85 -0
  22. package/docs/api/common-features/basics/agentbay.md +99 -2
  23. package/docs/api/common-features/basics/command.md +35 -18
  24. package/docs/api/common-features/basics/context-manager.md +21 -2
  25. package/docs/api/common-features/basics/filesystem.md +36 -0
  26. package/docs/api/common-features/basics/session-params.md +382 -0
  27. package/docs/api/common-features/basics/session.md +130 -2
  28. package/docs/api/computer-use/computer.md +25 -25
  29. package/docs/api/mobile-use/mobile-simulate.md +135 -0
  30. package/docs/examples/browser-use/browser/basic-usage.ts +31 -24
  31. package/docs/examples/browser-use/browser/browser-type-example.ts +3 -4
  32. package/docs/examples/browser-use/browser/captcha_tongcheng.ts +60 -28
  33. package/docs/examples/browser-use/browser/run-2048.ts +47 -37
  34. package/docs/examples/browser-use/browser/run-sudoku.ts +55 -36
  35. package/docs/examples/browser-use/browser/screenshot-example.ts +6 -6
  36. package/docs/examples/codespace/enhanced_code/index.ts +86 -0
  37. package/docs/examples/common-features/advanced/agent-module-example.ts +1 -1
  38. package/docs/examples/common-features/advanced/archive-upload-mode-example/README.md +1 -1
  39. package/docs/examples/common-features/advanced/archive-upload-mode-example/archive-upload-mode-example.ts +5 -6
  40. package/docs/examples/common-features/basics/archive-upload-mode-example/README.md +1 -1
  41. package/docs/examples/common-features/basics/archive-upload-mode-example/main.ts +1 -1
  42. package/docs/examples/common-features/basics/filesystem-example/filesystem-example.ts +13 -0
  43. package/docs/examples/common-features/basics/filesystem-example/filesystem-filetransfer-example.ts +6 -7
  44. package/docs/examples/common-features/basics/filesystem-example/watch-directory-example.ts +1 -1
  45. package/docs/examples/common-features/basics/session-pause-resume/README.md +53 -0
  46. package/docs/examples/common-features/basics/session-pause-resume/session-pause-resume.ts +237 -0
  47. package/docs/examples/mobile-use/mobile-get-adb-url/index.ts +1 -1
  48. package/docs/examples/mobile-use/mobile-simulate-basic-usage.ts +202 -0
  49. package/docs/examples/mobile-use/mobile-simulate-with-ctx.ts +170 -0
  50. package/package.json +5 -5
  51. package/dist/chunk-E7QC5S76.mjs.map +0 -1
  52. package/dist/chunk-ZUB35HKV.cjs.map +0 -1
  53. package/dist/model-2G37RFQQ.cjs +0 -188
  54. package/docs/examples/mobile-use/mobile-get-adb-url/package-lock.json +0 -279
  55. package/docs/examples/mobile-use/mobile-get-adb-url/package.json +0 -18
  56. /package/dist/{model-ZFTLKEMC.mjs.map → model-BRLR6F3P.mjs.map} +0 -0
@@ -6,35 +6,29 @@
6
6
  * - Utilize PageUseAgent to run 2048 game
7
7
  */
8
8
 
9
- import { AgentBay, CreateSessionParams } from '../../../../typescript/src/agent-bay';
10
- import { BrowserOption, ExtractOptions, ActOptions } from '../../../../typescript/src/browser';
11
- // import { chromium } from 'playwright';
12
-
13
- class GameState {
14
- score?: number;
15
- highestTile?: number;
16
- grid: number[][] = [];
17
- }
9
+ import { AgentBay, CreateSessionParams } from "wuying-agentbay-sdk";
10
+ import { BrowserOption, ExtractOptions } from "wuying-agentbay-sdk";
11
+ import { z } from "zod";
18
12
 
19
- class MoveAnalysis {
20
- move?: number;
21
- confidence: number = 0;
22
- reasoning: string = "";
23
- }
13
+ const GameStateSchema = z.object({
14
+ score: z.number().optional(),
15
+ highestTile: z.number().optional(),
16
+ grid: z.array(z.array(z.number())),
17
+ });
24
18
 
25
19
  function transposeGrid(grid: number[][]): number[][] {
26
20
  if (!grid || grid.length === 0) {
27
21
  return [];
28
22
  }
29
- return grid[0].map((_, colIndex) => grid.map(row => row[colIndex]));
23
+ return grid[0].map((_, colIndex) => grid.map((row) => row[colIndex]));
30
24
  }
31
25
 
32
26
  function formatGridForLlmInstruction(gridData: number[][]): string {
33
27
  const formattedRows: string[] = [];
34
28
  for (let i = 0; i < gridData.length; i++) {
35
- formattedRows.push(`row${i + 1}: [${gridData[i].join(', ')}]`);
29
+ formattedRows.push(`row${i + 1}: [${gridData[i].join(", ")}]`);
36
30
  }
37
- return formattedRows.join('\n');
31
+ return formattedRows.join("\n");
38
32
  }
39
33
 
40
34
  async function main() {
@@ -66,17 +60,17 @@ async function main() {
66
60
  console.log("endpoint_url =", endpointUrl);
67
61
 
68
62
  // Note: Install playwright with: npm install playwright
69
- const { chromium } = require('playwright');
63
+ const { chromium } = require("playwright");
70
64
  const browser = await chromium.connectOverCDP(endpointUrl);
71
65
  let page = null;
72
66
 
73
67
  try {
74
- const context = browser.contexts()[0]
68
+ const context = browser.contexts()[0];
75
69
  page = await context.newPage();
76
70
  console.log("🌐 Navigating to 2048...");
77
71
  await page.goto("https://ovolve.github.io/2048-AI/", {
78
72
  waitUntil: "domcontentloaded",
79
- timeout: 180000
73
+ timeout: 180000,
80
74
  });
81
75
  console.log("🌐 Navigated to 2048 done");
82
76
  await page.waitForSelector(".grid-container", { timeout: 10000 });
@@ -87,11 +81,11 @@ async function main() {
87
81
 
88
82
  while (true) {
89
83
  console.log("🔄 Game loop iteration...");
90
- await new Promise(resolve => setTimeout(resolve, 300));
84
+ await new Promise((resolve) => setTimeout(resolve, 300));
91
85
 
92
86
  // Get current game state
93
87
  console.log("📊 Extracting game state...");
94
- const gameStateOptions: ExtractOptions<GameState> = {
88
+ const gameStateOptions: ExtractOptions<typeof GameStateSchema> = {
95
89
  instruction: `
96
90
  Extract the current game state:
97
91
  1. Score from the score counter
@@ -105,20 +99,25 @@ async function main() {
105
99
  For instance, if the only tiles present are the two above, the grid should be:[[0, 0, 0, 2], [0, 0, 0, 0], [0, 0, 0, 0], [2, 0, 0, 0]]
106
100
  3. Highest tile value present
107
101
  `,
108
- schema: GameState,
109
- use_text_extract: false
110
-
102
+ schema: GameStateSchema,
103
+ use_text_extract: false,
111
104
  };
112
105
 
113
- const [success, gameStates] = await session.browser.agent.extract(gameStateOptions, page);
114
- if (success && gameStates.length > 0) {
115
- const gameState = gameStates[0];
106
+ const [success, gameState] = await session.browser.agent.extract(
107
+ gameStateOptions,
108
+ page
109
+ );
110
+ if (success && gameState) {
116
111
  const transposedGrid = transposeGrid(gameState.grid);
117
112
  console.log(`transposed grid: ${JSON.stringify(transposedGrid)}`);
118
113
  console.log(`gameState: ${JSON.stringify(gameState)}`);
119
114
  const gridInstruction = formatGridForLlmInstruction(transposedGrid);
120
115
 
121
- if (lastTransposedGrid !== null && JSON.stringify(transposedGrid) === JSON.stringify(lastTransposedGrid)) {
116
+ if (
117
+ lastTransposedGrid !== null &&
118
+ JSON.stringify(transposedGrid) ===
119
+ JSON.stringify(lastTransposedGrid)
120
+ ) {
122
121
  transposedGridNotChangedTimes += 1;
123
122
  } else {
124
123
  transposedGridNotChangedTimes = 0;
@@ -144,22 +143,33 @@ async function main() {
144
143
 
145
144
  if (transposedGridNotChangedTimes >= 1) {
146
145
  instructionStr += `
147
- 9. Do not generate move value in ${JSON.stringify(lastMoveHistory)}
148
- 10. If last move value ${lastMoveHistory[lastMoveHistory.length - 1]} moves up or down, then generate move value with left or right direction, otherwise generate move value with up or down direction
146
+ 9. Do not generate move value in ${JSON.stringify(
147
+ lastMoveHistory
148
+ )}
149
+ 10. If last move value ${
150
+ lastMoveHistory[lastMoveHistory.length - 1]
151
+ } moves up or down, then generate move value with left or right direction, otherwise generate move value with up or down direction
149
152
  `;
150
153
  }
151
154
 
152
- const nextMoveOptions: ExtractOptions<MoveAnalysis> = {
155
+ const nextMoveOptions: ExtractOptions<any> = {
153
156
  instruction: instructionStr,
154
- schema: MoveAnalysis,
155
- use_text_extract: false
157
+ schema: z.object({
158
+ move: z.number().optional(),
159
+ confidence: z.number().optional(),
160
+ reasoning: z.string().optional(),
161
+ }),
162
+ use_text_extract: false,
156
163
  };
157
164
 
158
- const [moveSuccess, nextMove] = await session.browser.agent.extract(nextMoveOptions, page);
165
+ const [moveSuccess, nextMove] = await session.browser.agent.extract(
166
+ nextMoveOptions,
167
+ page
168
+ );
159
169
  let selectedMove = 4; // Default to no move
160
170
 
161
- if (moveSuccess && nextMove.length > 0) {
162
- selectedMove = nextMove[0].move ?? 4;
171
+ if (moveSuccess && nextMove && typeof nextMove === "object") {
172
+ selectedMove = (nextMove as any).move ?? 4;
163
173
  } else {
164
174
  console.log("❌ Failed to extract next move, retry observing");
165
175
  continue;
@@ -6,20 +6,28 @@
6
6
  * - Utilize PageUseAgent to run sudoku game
7
7
  */
8
8
 
9
- import { AgentBay, CreateSessionParams,BrowserOption, ExtractOptions, ActOptions } from 'wuying-agentbay-sdk';
10
-
11
- import { chromium } from 'playwright';
12
-
13
- class SudokuBoard {
14
- board: number[][] = [];
15
- }
16
-
17
- class SudokuSolution {
18
- solution: number[][] = [];
19
- }
20
-
9
+ import {
10
+ AgentBay,
11
+ CreateSessionParams,
12
+ BrowserOption,
13
+ ExtractOptions,
14
+ ActOptions,
15
+ } from "wuying-agentbay-sdk";
16
+
17
+ import { chromium } from "playwright";
18
+ import { z } from "zod";
19
+
20
+ const SudokuBoardSchema = z.object({
21
+ board: z.array(z.array(z.number())),
22
+ });
23
+ type SudokuBoardType = z.infer<typeof SudokuBoardSchema>;
24
+
25
+ const SudokuSolutionSchema = z.object({
26
+ solution: z.array(z.array(z.number())),
27
+ });
28
+ type SudokuSolutionType = z.infer<typeof SudokuSolutionSchema>;
21
29
  function formatBoardForLlm(board: number[][]): string {
22
- return board.map(row => ` [${row.join(', ')}]`).join('\n');
30
+ return board.map((row) => ` [${row.join(", ")}]`).join("\n");
23
31
  }
24
32
 
25
33
  async function main() {
@@ -52,7 +60,7 @@ async function main() {
52
60
 
53
61
  const browser = await chromium.connectOverCDP(endpointUrl);
54
62
  try {
55
- const context = browser.contexts()[0]
63
+ const context = browser.contexts()[0];
56
64
  const page = await context.newPage();
57
65
  console.log("🌐 Navigating to Sudoku site...");
58
66
  const url = "https://widget.websudoku.com/";
@@ -65,27 +73,31 @@ async function main() {
65
73
 
66
74
  while (!success) {
67
75
  console.log("📊 Extracting sudoku board...");
68
- const options: ExtractOptions<SudokuBoard> = {
69
- instruction: "Extract the current sudoku board as a 9x9 array. Each cell should be a number (1-9) if filled, or 0 if empty.",
70
- schema: SudokuBoard,
71
- use_text_extract: false
76
+ const options: ExtractOptions<typeof SudokuBoardSchema> = {
77
+ instruction:
78
+ "Extract the current sudoku board as a 9x9 array. Each cell should be a number (1-9) if filled, or 0 if empty.",
79
+ schema: SudokuBoardSchema,
80
+ use_text_extract: false,
72
81
  };
73
82
 
74
- const [extractSuccess, boardObjs] = await session.browser.agent.extract(options, page);
75
- if (extractSuccess && boardObjs.length > 0) {
83
+ const [extractSuccess, boardObj] =
84
+ await session.browser.agent.extract(options, page);
85
+ if (extractSuccess && boardObj) {
76
86
  success = true;
77
- board = boardObjs[0].board;
87
+ board = boardObj.board;
78
88
  } else {
79
89
  console.log("❌ Failed to extract sudoku board, retry extracting");
80
- await new Promise(resolve => setTimeout(resolve, 3000));
90
+ await new Promise((resolve) => setTimeout(resolve, 3000));
81
91
  }
82
92
  }
83
93
 
84
- console.log("Current Board:\n" + board.map(row => row.join(' ')).join('\n'));
85
- const originalBoard = board.map(row => [...row]);
94
+ console.log(
95
+ "Current Board:\n" + board.map((row) => row.join(" ")).join("\n")
96
+ );
97
+ const originalBoard = board.map((row) => [...row]);
86
98
 
87
99
  // 2. Solve the sudoku
88
- const solutionOptions: ExtractOptions<SudokuSolution> = {
100
+ const solutionOptions: ExtractOptions<typeof SudokuSolutionSchema> = {
89
101
  instruction: `You are an expert sudoku solver. Given the following sudoku board as a 9x9 array (0 means empty), solve the sudoku and return the completed 9x9 array as 'solution'.
90
102
 
91
103
  Sudoku rules:
@@ -103,39 +115,46 @@ Return:
103
115
  {
104
116
  solution: number[][] // 9x9, all filled, valid sudoku
105
117
  }`,
106
- schema: SudokuSolution,
107
- use_text_extract: false
118
+ schema: SudokuSolutionSchema,
119
+ use_text_extract: false,
108
120
  };
109
121
 
110
- const [solutionSuccess, solutionObjs] = await session.browser.agent.extract(solutionOptions, page);
111
- if (!solutionSuccess || solutionObjs.length === 0) {
122
+ const [solutionSuccess, solutionObj] =
123
+ await session.browser.agent.extract(solutionOptions, page);
124
+ if (!solutionSuccess || !solutionObj) {
112
125
  console.log("❌ Failed to solve sudoku");
113
126
  return;
114
127
  }
115
128
 
116
- const solution = solutionObjs[0].solution;
117
- console.log("Solved Board:\n" + solution.map((row:any) => row.join(' ')).join('\n'));
129
+ const solution = solutionObj.solution;
130
+ console.log(
131
+ "Solved Board:\n" +
132
+ solution.map((row: any) => row.join(" ")).join("\n")
133
+ );
118
134
 
119
135
  // 3. Fill the solution
120
136
  for (let row = 0; row < 9; row++) {
121
137
  for (let col = 0; col < 9; col++) {
122
138
  if (originalBoard[row][col] === 0) {
123
139
  const inputId = `f${col}${row}`;
124
- console.log(`Type '${solution[row][col]}' into the cell with id '${inputId}'`);
140
+ console.log(
141
+ `Type '${solution[row][col]}' into the cell with id '${inputId}'`
142
+ );
125
143
 
126
144
  // Use the act method for natural language action
127
145
  const actOptions: ActOptions = {
128
- action: `Enter '${solution[row][col]}' into the input element where the attribute id is exactly '${inputId}' (for example, if id='f53', you must match the full string 'f53', not just the number 53; do not split or extract numbers from the id)`
146
+ action: `Enter '${solution[row][col]}' into the input element where the attribute id is exactly '${inputId}' (for example, if id='f53', you must match the full string 'f53', not just the number 53; do not split or extract numbers from the id)`,
129
147
  };
130
148
 
131
149
  await session.browser.agent.act(actOptions, page);
132
- await new Promise(resolve => setTimeout(resolve, 500));
150
+ await new Promise((resolve) => setTimeout(resolve, 500));
133
151
  }
134
152
  }
135
153
  }
136
154
 
137
- console.log("✅ Finished! The board has been solved and filled in the browser.");
138
-
155
+ console.log(
156
+ "✅ Finished! The board has been solved and filled in the browser."
157
+ );
139
158
  } catch (error) {
140
159
  console.log(`❌ Error in game loop: ${error}`);
141
160
  }
@@ -75,8 +75,8 @@ async function main() {
75
75
  // console.log(`✅ Browser screenshot captured (${screenshotData.length} bytes)`);
76
76
 
77
77
  // Save the screenshot to a file
78
- // await writeFile("browser_screenshot.png", Buffer.from(screenshotData));
79
- // console.log("✅ Browser screenshot saved as browser_screenshot.png");
78
+ // await writeFile("temp_browser_screenshot.png", Buffer.from(screenshotData));
79
+ // console.log("✅ Browser screenshot saved as temp_browser_screenshot.png");
80
80
 
81
81
  // Take a full page screenshot with custom options
82
82
  // const fullPageData = await session.browser.screenshot(
@@ -90,8 +90,8 @@ async function main() {
90
90
  // console.log(`✅ Browser full page screenshot captured (${fullPageData.length} bytes)`);
91
91
 
92
92
  // Save the full page screenshot
93
- // await writeFile("browser_full_page_screenshot.jpg", Buffer.from(fullPageData));
94
- // console.log("✅ Browser full page screenshot saved as browser_full_page_screenshot.jpg");
93
+ // await writeFile("temp_browser_full_page_screenshot.jpg", Buffer.from(fullPageData));
94
+ // console.log("✅ Browser full page screenshot saved as temp_browser_full_page_screenshot.jpg");
95
95
 
96
96
  // Take a screenshot with custom viewport settings
97
97
  // const customScreenshot = await session.browser.screenshot(
@@ -105,8 +105,8 @@ async function main() {
105
105
  // console.log(`✅ Browser custom screenshot captured (${customScreenshot.length} bytes)`);
106
106
 
107
107
  // Save the custom screenshot
108
- // await writeFile("browser_custom_screenshot.png", Buffer.from(customScreenshot));
109
- // console.log("✅ Browser custom screenshot saved as browser_custom_screenshot.png");
108
+ // await writeFile("temp_browser_custom_screenshot.png", Buffer.from(customScreenshot));
109
+ // console.log("✅ Browser custom screenshot saved as temp_browser_custom_screenshot.png");
110
110
 
111
111
  await browser.close();
112
112
 
@@ -0,0 +1,86 @@
1
+ import { AgentBay } from 'wuying-agentbay-sdk';
2
+
3
+ async function main() {
4
+ const apiKey = process.env.AGENTBAY_API_KEY;
5
+ if (!apiKey) {
6
+ console.error("Please set AGENTBAY_API_KEY environment variable");
7
+ process.exit(1);
8
+ }
9
+
10
+ const agentBay = new AgentBay({ apiKey });
11
+
12
+ console.log("Creating session...");
13
+ const sessionResult = await agentBay.create({ imageId: "code_latest" });
14
+ if (!sessionResult.success || !sessionResult.session) {
15
+ console.error("Failed to create session:", sessionResult.errorMessage);
16
+ process.exit(1);
17
+ }
18
+
19
+ const session = sessionResult.session;
20
+ console.log(`Session created: ${session.sessionId}`);
21
+
22
+ try {
23
+ // 1. Logs Capture
24
+ console.log("\n--- Logs Capture Test ---");
25
+ const logsCode = `
26
+ import sys
27
+ print("This goes to stdout")
28
+ print("This goes to stderr", file=sys.stderr)
29
+ `;
30
+ const logsResult = await session.code.runCode(logsCode, "python");
31
+ printResult(logsResult);
32
+
33
+ // 2. Rich Output (HTML)
34
+ console.log("\n--- Rich Output (HTML) Test ---");
35
+ const htmlCode = `
36
+ from IPython.display import display, HTML
37
+ display(HTML("<h1>Hello from AgentBay</h1>"))
38
+ `;
39
+ const htmlResult = await session.code.runCode(htmlCode, "python");
40
+ printResult(htmlResult);
41
+
42
+ // 3. Error Handling
43
+ console.log("\n--- Error Handling Test ---");
44
+ const errorCode = `
45
+ raise ValueError("Something went wrong")
46
+ `;
47
+ const errorResult = await session.code.runCode(errorCode, "python");
48
+ printResult(errorResult);
49
+
50
+ } finally {
51
+ console.log("\nCleaning up...");
52
+ await session.delete();
53
+ }
54
+ }
55
+
56
+ function printResult(result: any) {
57
+ if (result.success) {
58
+ console.log("Success: true");
59
+ if (result.logs) {
60
+ if (result.logs.stdout.length > 0) {
61
+ console.log("Stdout:", JSON.stringify(result.logs.stdout));
62
+ }
63
+ if (result.logs.stderr.length > 0) {
64
+ console.log("Stderr:", JSON.stringify(result.logs.stderr));
65
+ }
66
+ }
67
+ if (result.results) {
68
+ console.log("Results count:", result.results.length);
69
+ result.results.forEach((item: any, index: number) => {
70
+ const types = Object.keys(item).filter(k => k !== 'isMainResult');
71
+ console.log(`Result [${index}] types:`, types.join(", "));
72
+ if (item.text) console.log(` Text: ${item.text.substring(0, 50)}...`);
73
+ if (item.html) console.log(` HTML: ${item.html.substring(0, 50)}...`);
74
+ });
75
+ }
76
+ } else {
77
+ console.log("Success: false");
78
+ console.log("Error Message:", result.errorMessage);
79
+ if (result.error) {
80
+ console.log("Error Details:", JSON.stringify(result.error));
81
+ }
82
+ }
83
+ }
84
+
85
+ main().catch(console.error);
86
+
@@ -33,7 +33,7 @@ async function main() {
33
33
  const taskDescription = "Calculate the square root of 144";
34
34
  console.log(`Executing task: ${taskDescription}`);
35
35
 
36
- const executionResult = await session.agent.executeTask(taskDescription, 5);
36
+ const executionResult = await session.agent.computer.executeTask(taskDescription, 5);
37
37
 
38
38
  if (executionResult.success) {
39
39
  console.log("Task completed successfully!");
@@ -45,7 +45,7 @@ const contextSync = newContextSync(
45
45
  ### Session Creation with Context Sync
46
46
 
47
47
  ```typescript
48
- const sessionParams: CreateSessionParams = {
48
+ const sessionParams = {
49
49
  labels: {
50
50
  example: `archive-mode-${uniqueId}`,
51
51
  type: "archive-upload-demo",
@@ -1,4 +1,4 @@
1
- import { AgentBay, CreateSessionParams, Session, newContextSync, newSyncPolicy, FileSystem } from "wuying-agentbay-sdk";
1
+ import { AgentBay, CreateSessionParams, Session, newContextSync, newSyncPolicy, FileSystem, UploadMode } from "wuying-agentbay-sdk";
2
2
 
3
3
  /**
4
4
  * Archive Upload Mode Context Sync Example
@@ -57,10 +57,9 @@ async function archiveUploadModeExample(): Promise<void> {
57
57
  // Step 2: Configure sync policy with Archive upload mode
58
58
  console.log("\n⚙️ Step 2: Configuring sync policy with Archive upload mode...");
59
59
  const syncPolicy = newSyncPolicy();
60
- syncPolicy.uploadPolicy!.uploadMode = "Archive"; // Set to Archive mode
61
-
62
- console.log(`✅ Sync policy configured with uploadMode: ${syncPolicy.uploadPolicy!.uploadMode}`);
60
+ syncPolicy.uploadPolicy!.uploadMode = UploadMode.Archive;
63
61
 
62
+ console.log(`✅ Sync policy configured with uploadMode: ${syncPolicy.uploadPolicy!.uploadMode}`);
64
63
  // Step 3: Create context sync configuration
65
64
  console.log("\n🔧 Step 3: Creating context sync configuration...");
66
65
  const contextSync = newContextSync(
@@ -76,7 +75,7 @@ async function archiveUploadModeExample(): Promise<void> {
76
75
 
77
76
  // Step 4: Create session with Archive mode context sync
78
77
  console.log("\n🏗️ Step 4: Creating session with Archive mode context sync...");
79
- const sessionParams: CreateSessionParams = {
78
+ const sessionParams = {
80
79
  labels: {
81
80
  example: `archive-mode-${uniqueId}`,
82
81
  type: "archive-upload-demo",
@@ -173,7 +172,7 @@ async function archiveUploadModeExample(): Promise<void> {
173
172
  console.log("\n🎉 Archive upload mode example completed successfully!");
174
173
  console.log("✅ All operations completed without errors.");
175
174
 
176
- } catch (error) {
175
+ } catch (error) {
177
176
  console.error("\n❌ Error occurred during example execution:");
178
177
  console.error(error);
179
178
  } finally {
@@ -48,7 +48,7 @@ const contextSync = newContextSync(
48
48
  ### Session Creation with Context Sync
49
49
 
50
50
  ```typescript
51
- const sessionParams: CreateSessionParams = {
51
+ const sessionParams = {
52
52
  labels: {
53
53
  example: `archive-mode-${uniqueId}`,
54
54
  type: "archive-upload-demo",
@@ -76,7 +76,7 @@ async function archiveUploadModeExample(): Promise<void> {
76
76
 
77
77
  // Step 4: Create session with Archive mode context sync
78
78
  console.log("\n🏗️ Step 4: Creating session with Archive mode context sync...");
79
- const sessionParams: CreateSessionParams = {
79
+ const sessionParams = {
80
80
  labels: {
81
81
  example: `archive-mode-${uniqueId}`,
82
82
  type: "archive-upload-demo",
@@ -145,6 +145,19 @@ async function main() {
145
145
  } catch (error) {
146
146
  log(`Error moving file: ${error}`);
147
147
  }
148
+
149
+ // 9. Delete file
150
+ log(`\nDeleting file: ${newFilePath}`);
151
+ try {
152
+ const deleteResponse = await session.fileSystem.deleteFile(newFilePath);
153
+ log(`File deleted successfully: ${deleteResponse.success}`);
154
+ log(`Delete File RequestId: ${deleteResponse.requestId}`);
155
+
156
+ const infoAfterDelete = await session.fileSystem.getFileInfo(newFilePath);
157
+ log(`Get File Info After Delete: success=${infoAfterDelete.success}`);
158
+ } catch (error) {
159
+ log(`Error deleting file: ${error}`);
160
+ }
148
161
  } finally {
149
162
  // Clean up by deleting the session when we're done
150
163
  log('\nDeleting the session...');
@@ -30,7 +30,7 @@ async function main() {
30
30
  const createResponse = await agentBay.create({
31
31
  imageId: 'code_latest'
32
32
  });
33
-
33
+
34
34
  if (!createResponse.success || !createResponse.session) {
35
35
  log(`Failed to create session: ${createResponse.errorMessage}`);
36
36
  return;
@@ -39,13 +39,12 @@ async function main() {
39
39
  const session = createResponse.session;
40
40
  log(`\nSession created with ID: ${session.sessionId}`);
41
41
  log(`Create Session RequestId: ${createResponse.requestId}`);
42
- log(`Session fileTransferContextId: ${session.fileTransferContextId}`);
43
42
 
44
43
  try {
45
44
  // 1. Upload a file
46
45
  const remotePath = '/tmp/file_transfer_test/uploaded-file.txt';
47
46
  log(`\nUploading file from ${localUploadPath} to ${remotePath}`);
48
-
47
+
49
48
  // Create the remote directory first
50
49
  const dirPath = path.dirname(remotePath);
51
50
  const createDirResult = await session.fileSystem.createDirectory(dirPath);
@@ -69,7 +68,7 @@ async function main() {
69
68
  log(`Bytes sent: ${uploadResult.bytesSent}`);
70
69
  log(`Request ID (upload URL): ${uploadResult.requestIdUploadUrl}`);
71
70
  log(`Request ID (sync): ${uploadResult.requestIdSync}`);
72
-
71
+
73
72
  // Verify the file exists in remote location
74
73
  const listResult = await session.fileSystem.listDirectory(dirPath);
75
74
  if (listResult.success) {
@@ -87,7 +86,7 @@ async function main() {
87
86
  // 2. Create a file in the remote location for download
88
87
  const remoteDownloadPath = '/tmp/file_transfer_test/download-test.txt';
89
88
  const downloadContent = "This is a test file for AgentBay FileTransfer download functionality.\n".repeat(15);
90
-
89
+
91
90
  log(`\nCreating remote file for download: ${remoteDownloadPath}`);
92
91
  const writeResult = await session.fileSystem.writeFile(remoteDownloadPath, downloadContent);
93
92
  if (writeResult.success) {
@@ -99,7 +98,7 @@ async function main() {
99
98
  // 3. Download the file
100
99
  const localDownloadPath = path.join(tempDir, 'downloaded-file.txt');
101
100
  log(`\nDownloading file from ${remoteDownloadPath} to ${localDownloadPath}`);
102
-
101
+
103
102
  const downloadResult = await session.fileSystem.downloadFile(
104
103
  remoteDownloadPath,
105
104
  localDownloadPath,
@@ -115,7 +114,7 @@ async function main() {
115
114
  log(`Bytes received: ${downloadResult.bytesReceived}`);
116
115
  log(`Request ID (download URL): ${downloadResult.requestIdDownloadUrl}`);
117
116
  log(`Request ID (sync): ${downloadResult.requestIdSync}`);
118
-
117
+
119
118
  // Verify downloaded file content
120
119
  const downloadedContent = fs.readFileSync(localDownloadPath, 'utf-8');
121
120
  if (downloadedContent === downloadContent) {
@@ -25,7 +25,7 @@ async function main(): Promise<void> {
25
25
  console.log("✅ AgentBay client initialized");
26
26
 
27
27
  // Create session with code_latest ImageId
28
- const sessionParams: CreateSessionParams = { imageId: "code_latest" };
28
+ const sessionParams = { imageId: "code_latest" };
29
29
  const sessionResult = await agentbay.create(sessionParams);
30
30
 
31
31
  if (!sessionResult.success) {
@@ -0,0 +1,53 @@
1
+ # Session Pause and Resume Example
2
+
3
+ This example demonstrates how to pause and resume sessions using the Wuying AgentBay SDK. Pausing a session puts it into a dormant state, consuming fewer resources while maintaining its state. Resuming a session brings it back to an active state.
4
+
5
+ ## Features Demonstrated
6
+
7
+ - Pausing and resuming sessions
8
+ - Handling non-existent session operations
9
+ - Using custom timeout and polling interval parameters
10
+ - Checking session status before and after operations
11
+ - Performing work in sessions before and after pause/resume cycles
12
+
13
+ ## Running the Example
14
+
15
+ ```bash
16
+ cd session-pause-resume
17
+ npx ts-node session-pause-resume.ts
18
+ ```
19
+
20
+ Make sure you have set the `AGENTBAY_API_KEY` environment variable or replace the placeholder in the code with your actual API key.
21
+
22
+ ## Prerequisites
23
+
24
+ - Node.js installed
25
+ - TypeScript installed
26
+ - ts-node installed (`npm install -g ts-node`)
27
+ - Required dependencies installed (`npm install`)
28
+
29
+ ## Understanding Session States
30
+
31
+ When working with pause and resume operations, sessions can be in different states:
32
+
33
+ 1. **RUNNING**: Session is active and ready to accept commands
34
+ 2. **PAUSING**: Session is transitioning to paused state
35
+ 3. **PAUSED**: Session is in dormant state, consuming fewer resources
36
+ 4. **RESUMING**: Session is transitioning back to running state
37
+
38
+ The pause and resume operations are asynchronous, meaning they initiate the state transition and then poll for completion.
39
+
40
+ ## Best Practices
41
+
42
+ 1. **Always check operation results**: Verify that pause and resume operations succeeded
43
+ 2. **Handle errors gracefully**: Non-existent sessions and other errors should be handled appropriately
44
+ 3. **Use appropriate timeouts**: Custom timeout values can be used based on your specific requirements
45
+ 4. **Verify session state**: Check session status before and after operations to ensure expected behavior
46
+ 5. **Clean up resources**: Always delete sessions when done to avoid resource leaks
47
+
48
+ ## Use Cases
49
+
50
+ - **Cost optimization**: Pause sessions during idle periods to reduce resource consumption
51
+ - **Long-running workflows**: Suspend sessions overnight or during maintenance windows
52
+ - **Development and testing**: Pause test environments when not actively working on them
53
+ - **Batch processing**: Pause and resume processing jobs based on system load