@browserbasehq/orca 3.6.0-gemini-cua → 3.7.0-preview.1

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 (85) hide show
  1. package/dist/cjs/lib/v3/agent/AgentClient.d.ts +2 -2
  2. package/dist/cjs/lib/v3/agent/AgentClient.js.map +1 -1
  3. package/dist/cjs/lib/v3/agent/AnthropicCUAClient.d.ts +4 -3
  4. package/dist/cjs/lib/v3/agent/AnthropicCUAClient.js +11 -9
  5. package/dist/cjs/lib/v3/agent/AnthropicCUAClient.js.map +1 -1
  6. package/dist/cjs/lib/v3/agent/GoogleCUAClient.d.ts +12 -3
  7. package/dist/cjs/lib/v3/agent/GoogleCUAClient.js +107 -22
  8. package/dist/cjs/lib/v3/agent/GoogleCUAClient.js.map +1 -1
  9. package/dist/cjs/lib/v3/agent/MicrosoftCUAClient.d.ts +2 -2
  10. package/dist/cjs/lib/v3/agent/MicrosoftCUAClient.js +2 -2
  11. package/dist/cjs/lib/v3/agent/MicrosoftCUAClient.js.map +1 -1
  12. package/dist/cjs/lib/v3/agent/OpenAICUAClient.d.ts +6 -3
  13. package/dist/cjs/lib/v3/agent/OpenAICUAClient.js +13 -7
  14. package/dist/cjs/lib/v3/agent/OpenAICUAClient.js.map +1 -1
  15. package/dist/cjs/lib/v3/agent/utils/handleDoneToolCall.d.ts +1 -0
  16. package/dist/cjs/lib/v3/agent/utils/handleDoneToolCall.js +40 -2
  17. package/dist/cjs/lib/v3/agent/utils/handleDoneToolCall.js.map +1 -1
  18. package/dist/cjs/lib/v3/handlers/v3AgentHandler.js +30 -7
  19. package/dist/cjs/lib/v3/handlers/v3AgentHandler.js.map +1 -1
  20. package/dist/cjs/lib/v3/handlers/v3CuaAgentHandler.js +32 -18
  21. package/dist/cjs/lib/v3/handlers/v3CuaAgentHandler.js.map +1 -1
  22. package/dist/cjs/lib/v3/index.d.ts +1 -0
  23. package/dist/cjs/lib/v3/llm/LLMProvider.d.ts +2 -2
  24. package/dist/cjs/lib/v3/llm/LLMProvider.js.map +1 -1
  25. package/dist/cjs/lib/v3/types/public/agent.d.ts +9 -0
  26. package/dist/cjs/lib/v3/types/public/agent.js.map +1 -1
  27. package/dist/cjs/lib/v3/types/public/context.d.ts +7 -0
  28. package/dist/cjs/lib/v3/types/public/context.js.map +1 -1
  29. package/dist/cjs/lib/v3/types/public/sdkErrors.d.ts +4 -0
  30. package/dist/cjs/lib/v3/types/public/sdkErrors.js +9 -1
  31. package/dist/cjs/lib/v3/types/public/sdkErrors.js.map +1 -1
  32. package/dist/cjs/lib/v3/understudy/cdp.d.ts +2 -0
  33. package/dist/cjs/lib/v3/understudy/cdp.js +26 -12
  34. package/dist/cjs/lib/v3/understudy/cdp.js.map +1 -1
  35. package/dist/cjs/lib/v3/understudy/context.d.ts +13 -1
  36. package/dist/cjs/lib/v3/understudy/context.js +284 -1
  37. package/dist/cjs/lib/v3/understudy/context.js.map +1 -1
  38. package/dist/cjs/lib/v3/understudy/domainPolicy.d.ts +25 -0
  39. package/dist/cjs/lib/v3/understudy/domainPolicy.js +162 -0
  40. package/dist/cjs/lib/v3/understudy/domainPolicy.js.map +1 -0
  41. package/dist/cjs/lib/v3/v3.js +4 -1
  42. package/dist/cjs/lib/v3/v3.js.map +1 -1
  43. package/dist/esm/lib/v3/agent/AgentClient.d.ts +2 -2
  44. package/dist/esm/lib/v3/agent/AgentClient.js.map +1 -1
  45. package/dist/esm/lib/v3/agent/AnthropicCUAClient.d.ts +4 -3
  46. package/dist/esm/lib/v3/agent/AnthropicCUAClient.js +11 -9
  47. package/dist/esm/lib/v3/agent/AnthropicCUAClient.js.map +1 -1
  48. package/dist/esm/lib/v3/agent/GoogleCUAClient.d.ts +12 -3
  49. package/dist/esm/lib/v3/agent/GoogleCUAClient.js +107 -22
  50. package/dist/esm/lib/v3/agent/GoogleCUAClient.js.map +1 -1
  51. package/dist/esm/lib/v3/agent/MicrosoftCUAClient.d.ts +2 -2
  52. package/dist/esm/lib/v3/agent/MicrosoftCUAClient.js +2 -2
  53. package/dist/esm/lib/v3/agent/MicrosoftCUAClient.js.map +1 -1
  54. package/dist/esm/lib/v3/agent/OpenAICUAClient.d.ts +6 -3
  55. package/dist/esm/lib/v3/agent/OpenAICUAClient.js +13 -7
  56. package/dist/esm/lib/v3/agent/OpenAICUAClient.js.map +1 -1
  57. package/dist/esm/lib/v3/agent/utils/handleDoneToolCall.d.ts +1 -0
  58. package/dist/esm/lib/v3/agent/utils/handleDoneToolCall.js +39 -2
  59. package/dist/esm/lib/v3/agent/utils/handleDoneToolCall.js.map +1 -1
  60. package/dist/esm/lib/v3/handlers/v3AgentHandler.js +30 -7
  61. package/dist/esm/lib/v3/handlers/v3AgentHandler.js.map +1 -1
  62. package/dist/esm/lib/v3/handlers/v3CuaAgentHandler.js +32 -18
  63. package/dist/esm/lib/v3/handlers/v3CuaAgentHandler.js.map +1 -1
  64. package/dist/esm/lib/v3/index.d.ts +1 -0
  65. package/dist/esm/lib/v3/llm/LLMProvider.d.ts +2 -2
  66. package/dist/esm/lib/v3/llm/LLMProvider.js.map +1 -1
  67. package/dist/esm/lib/v3/types/public/agent.d.ts +9 -0
  68. package/dist/esm/lib/v3/types/public/agent.js.map +1 -1
  69. package/dist/esm/lib/v3/types/public/context.d.ts +7 -0
  70. package/dist/esm/lib/v3/types/public/context.js.map +1 -1
  71. package/dist/esm/lib/v3/types/public/sdkErrors.d.ts +4 -0
  72. package/dist/esm/lib/v3/types/public/sdkErrors.js +7 -0
  73. package/dist/esm/lib/v3/types/public/sdkErrors.js.map +1 -1
  74. package/dist/esm/lib/v3/understudy/cdp.d.ts +2 -0
  75. package/dist/esm/lib/v3/understudy/cdp.js +26 -12
  76. package/dist/esm/lib/v3/understudy/cdp.js.map +1 -1
  77. package/dist/esm/lib/v3/understudy/context.d.ts +13 -1
  78. package/dist/esm/lib/v3/understudy/context.js +285 -2
  79. package/dist/esm/lib/v3/understudy/context.js.map +1 -1
  80. package/dist/esm/lib/v3/understudy/domainPolicy.d.ts +25 -0
  81. package/dist/esm/lib/v3/understudy/domainPolicy.js +158 -0
  82. package/dist/esm/lib/v3/understudy/domainPolicy.js.map +1 -0
  83. package/dist/esm/lib/v3/v3.js +4 -1
  84. package/dist/esm/lib/v3/v3.js.map +1 -1
  85. package/package.json +3 -3
@@ -171,6 +171,8 @@ export class GoogleCUAClient extends AgentClient {
171
171
  await this.initializeHistory(instruction);
172
172
  let totalInputTokens = 0;
173
173
  let totalOutputTokens = 0;
174
+ let totalReasoningTokens = 0;
175
+ let totalCachedInputTokens = 0;
174
176
  let totalInferenceTime = 0;
175
177
  try {
176
178
  // Execute steps until completion or max steps reached
@@ -184,6 +186,8 @@ export class GoogleCUAClient extends AgentClient {
184
186
  const result = await this.executeStep(logger);
185
187
  totalInputTokens += result.usage.input_tokens;
186
188
  totalOutputTokens += result.usage.output_tokens;
189
+ totalReasoningTokens += result.usage.reasoning_tokens;
190
+ totalCachedInputTokens += result.usage.cached_input_tokens;
187
191
  totalInferenceTime += result.usage.inference_time_ms;
188
192
  // Add actions to the list
189
193
  actions.push(...result.actions);
@@ -206,6 +210,8 @@ export class GoogleCUAClient extends AgentClient {
206
210
  usage: {
207
211
  input_tokens: totalInputTokens,
208
212
  output_tokens: totalOutputTokens,
213
+ reasoning_tokens: totalReasoningTokens,
214
+ cached_input_tokens: totalCachedInputTokens,
209
215
  inference_time_ms: totalInferenceTime,
210
216
  },
211
217
  };
@@ -225,6 +231,8 @@ export class GoogleCUAClient extends AgentClient {
225
231
  usage: {
226
232
  input_tokens: totalInputTokens,
227
233
  output_tokens: totalOutputTokens,
234
+ reasoning_tokens: totalReasoningTokens,
235
+ cached_input_tokens: totalCachedInputTokens,
228
236
  inference_time_ms: totalInferenceTime,
229
237
  },
230
238
  };
@@ -449,7 +457,7 @@ export class GoogleCUAClient extends AgentClient {
449
457
  level: 2,
450
458
  });
451
459
  const screenshot = await this.captureScreenshot();
452
- const base64Data = screenshot.replace(/^data:image\/png;base64,/, "");
460
+ const base64Data = screenshot.base64;
453
461
  // Create one function response for each computer use function call
454
462
  // Following Python SDK pattern: FunctionResponse with parts containing inline_data
455
463
  for (const functionCall of computerUseFunctionCalls) {
@@ -471,7 +479,7 @@ export class GoogleCUAClient extends AgentClient {
471
479
  parts: [
472
480
  {
473
481
  inlineData: {
474
- mimeType: "image/png",
482
+ mimeType: screenshot.mediaType,
475
483
  data: base64Data,
476
484
  },
477
485
  },
@@ -508,8 +516,14 @@ export class GoogleCUAClient extends AgentClient {
508
516
  message: result.message,
509
517
  completed: result.completed,
510
518
  usage: {
519
+ // promptTokenCount is the TOTAL input and already includes the
520
+ // cached portion; cachedContentTokenCount is the cache-hit subset
521
+ // (tracked separately for visibility, not additive). thoughtsTokenCount
522
+ // is Gemini's thinking/reasoning output.
511
523
  input_tokens: usageMetadata?.promptTokenCount || 0,
512
524
  output_tokens: usageMetadata?.candidatesTokenCount || 0,
525
+ reasoning_tokens: usageMetadata?.thoughtsTokenCount || 0,
526
+ cached_input_tokens: usageMetadata?.cachedContentTokenCount || 0,
513
527
  inference_time_ms: elapsedMs,
514
528
  },
515
529
  };
@@ -564,7 +578,7 @@ export class GoogleCUAClient extends AgentClient {
564
578
  level: 2,
565
579
  });
566
580
  // Convert function call to action(s)
567
- const action = this.convertFunctionCallToAction(part.functionCall);
581
+ const action = this.convertFunctionCallToAction(part.functionCall, logger);
568
582
  if (action) {
569
583
  // Special handling for type actions. gemini-2.5 type_text_at carries
570
584
  // coordinates (click the field first); gemini-3.x `type` has none and
@@ -637,7 +651,7 @@ export class GoogleCUAClient extends AgentClient {
637
651
  /**
638
652
  * Convert Google function call to Stagehand action
639
653
  */
640
- convertFunctionCallToAction(functionCall) {
654
+ convertFunctionCallToAction(functionCall, logger) {
641
655
  const { name: rawName } = functionCall;
642
656
  // Default args to an empty object so no-argument predefined functions
643
657
  // (e.g. take_screenshot, go_back) are not rejected by the guard below.
@@ -654,11 +668,15 @@ export class GoogleCUAClient extends AgentClient {
654
668
  // NOTE: click and take_screenshot are confirmed from live gemini-3.5-flash
655
669
  // traffic; the rest are inferred from the same drop-the-qualifier pattern
656
670
  // and are safe aliases (any unmapped name still hits the warning below).
671
+ // gemini-3.x renamed several predefined functions vs gemini-2.5. Alias the
672
+ // 3.x names whose behavior maps cleanly onto a 2.5 canonical handler. Click
673
+ // variants that carry distinct semantics (double/triple/right/middle click,
674
+ // move) are NOT aliased here — they have dedicated cases below so the click
675
+ // count and button are preserved. 2.5 never emits any of these names, so
676
+ // the 2.5 handlers are unaffected.
657
677
  const NAME_ALIASES = {
658
678
  click: "click_at",
659
679
  left_click: "click_at",
660
- double_click: "click_at",
661
- triple_click: "click_at",
662
680
  type: "type_text_at",
663
681
  type_text: "type_text_at",
664
682
  hover: "hover_at",
@@ -674,6 +692,16 @@ export class GoogleCUAClient extends AgentClient {
674
692
  wait: "wait_5_seconds",
675
693
  };
676
694
  const name = NAME_ALIASES[rawName] ?? rawName;
695
+ // Predefined computer-use tools take precedence over custom tools. If a
696
+ // custom tool was registered under a reserved (aliased) name, note that the
697
+ // predefined tool wins rather than silently dropping the custom one.
698
+ if (rawName in NAME_ALIASES && isCustomTool(functionCall, this.tools)) {
699
+ logger?.({
700
+ category: "agent",
701
+ message: `Custom tool "${rawName}" collides with a predefined Google CUA function; using the predefined tool. Rename the custom tool to avoid the conflict.`,
702
+ level: 2,
703
+ });
704
+ }
677
705
  switch (name) {
678
706
  case "open_web_browser":
679
707
  return {
@@ -690,6 +718,13 @@ export class GoogleCUAClient extends AgentClient {
690
718
  timestamp: Date.now(),
691
719
  };
692
720
  case "click_at": {
721
+ // x/y are required; reject a malformed call rather than normalizing
722
+ // undefined/NaN/Infinity into bad coordinates. (gemini-3.x `click`
723
+ // aliases here.)
724
+ if (!GoogleCUAClient.isFiniteCoord(args.x) ||
725
+ !GoogleCUAClient.isFiniteCoord(args.y)) {
726
+ return null;
727
+ }
693
728
  const { x, y } = this.normalizeCoordinates(args.x, args.y);
694
729
  return {
695
730
  type: "click",
@@ -698,7 +733,40 @@ export class GoogleCUAClient extends AgentClient {
698
733
  button: args.button || "left",
699
734
  };
700
735
  }
736
+ // gemini-3.x click family. The executor natively supports double/triple
737
+ // click and right/middle button, so preserve those semantics rather than
738
+ // collapsing to a single left click. All require integer coordinates;
739
+ // drop the call (return null) on a malformed payload so the executor is
740
+ // never handed NaN.
741
+ case "double_click":
742
+ case "triple_click":
743
+ case "right_click":
744
+ case "middle_click":
745
+ case "move": {
746
+ if (!GoogleCUAClient.isFiniteCoord(args.x) ||
747
+ !GoogleCUAClient.isFiniteCoord(args.y)) {
748
+ return null;
749
+ }
750
+ const { x, y } = this.normalizeCoordinates(args.x, args.y);
751
+ if (name === "move") {
752
+ return { type: "move", x, y };
753
+ }
754
+ if (name === "double_click" || name === "triple_click") {
755
+ return { type: name, x, y };
756
+ }
757
+ return {
758
+ type: "click",
759
+ x,
760
+ y,
761
+ button: name === "right_click" ? "right" : "middle",
762
+ };
763
+ }
701
764
  case "type_text_at": {
765
+ // text is required; reject a malformed call rather than typing
766
+ // "undefined". An empty string is valid (e.g. clear the field).
767
+ if (typeof args.text !== "string") {
768
+ return null;
769
+ }
702
770
  // press_enter and clear_before_typing are shared across generations.
703
771
  const pressEnter = args.press_enter ?? false;
704
772
  const clearBeforeTyping = args.clear_before_typing ?? true;
@@ -746,8 +814,10 @@ export class GoogleCUAClient extends AgentClient {
746
814
  };
747
815
  }
748
816
  case "scroll_at": {
749
- // A coordinate-less `scroll` alias (gemini-3.x) scrolls the document.
750
- if (typeof args.x !== "number" || typeof args.y !== "number") {
817
+ // A coordinate-less (or malformed) `scroll` alias (gemini-3.x) scrolls
818
+ // the document via PageUp/PageDown.
819
+ if (!GoogleCUAClient.isFiniteCoord(args.x) ||
820
+ !GoogleCUAClient.isFiniteCoord(args.y)) {
751
821
  const dir = (args.direction || "down").toLowerCase();
752
822
  return {
753
823
  type: "keypress",
@@ -757,9 +827,9 @@ export class GoogleCUAClient extends AgentClient {
757
827
  const { x, y } = this.normalizeCoordinates(args.x, args.y);
758
828
  const direction = (args.direction || "down").toLowerCase();
759
829
  // 2.5 uses `magnitude`; gemini-3.x `scroll` uses `magnitude_in_pixels`.
760
- const magnitude = typeof args.magnitude === "number"
830
+ const magnitude = GoogleCUAClient.isFiniteCoord(args.magnitude)
761
831
  ? args.magnitude
762
- : typeof args.magnitude_in_pixels === "number"
832
+ : GoogleCUAClient.isFiniteCoord(args.magnitude_in_pixels)
763
833
  ? args.magnitude_in_pixels
764
834
  : 800;
765
835
  let scroll_x = 0;
@@ -789,6 +859,11 @@ export class GoogleCUAClient extends AgentClient {
789
859
  };
790
860
  }
791
861
  case "navigate":
862
+ // url is required; reject a malformed call rather than navigating to
863
+ // "undefined".
864
+ if (typeof args.url !== "string" || args.url.length === 0) {
865
+ return null;
866
+ }
792
867
  return {
793
868
  type: "goto",
794
869
  url: args.url,
@@ -822,14 +897,14 @@ export class GoogleCUAClient extends AgentClient {
822
897
  case "drag_and_drop": {
823
898
  // 2.5 uses x/y + destination_x/destination_y; gemini-3.x `drag_and_drop`
824
899
  // uses start_x/start_y + end_x/end_y. Accept either.
825
- const sx = (args.x ?? args.start_x);
826
- const sy = (args.y ?? args.start_y);
827
- const ex = (args.destination_x ?? args.end_x);
828
- const ey = (args.destination_y ?? args.end_y);
829
- if (typeof sx !== "number" ||
830
- typeof sy !== "number" ||
831
- typeof ex !== "number" ||
832
- typeof ey !== "number") {
900
+ const sx = args.x ?? args.start_x;
901
+ const sy = args.y ?? args.start_y;
902
+ const ex = args.destination_x ?? args.end_x;
903
+ const ey = args.destination_y ?? args.end_y;
904
+ if (!GoogleCUAClient.isFiniteCoord(sx) ||
905
+ !GoogleCUAClient.isFiniteCoord(sy) ||
906
+ !GoogleCUAClient.isFiniteCoord(ex) ||
907
+ !GoogleCUAClient.isFiniteCoord(ey)) {
833
908
  return null;
834
909
  }
835
910
  const startPoint = this.normalizeCoordinates(sx, sy);
@@ -856,6 +931,14 @@ export class GoogleCUAClient extends AgentClient {
856
931
  return null;
857
932
  }
858
933
  }
934
+ /**
935
+ * True only for a usable coordinate/number: rejects undefined, non-numbers,
936
+ * and the numeric edge cases NaN and Infinity (both `typeof "number"`), so
937
+ * malformed function calls are dropped instead of normalizing into NaN.
938
+ */
939
+ static isFiniteCoord(value) {
940
+ return typeof value === "number" && Number.isFinite(value);
941
+ }
859
942
  /**
860
943
  * Normalize coordinates from Google's 0-1000 range to viewport dimensions
861
944
  */
@@ -874,13 +957,15 @@ export class GoogleCUAClient extends AgentClient {
874
957
  }
875
958
  // Use provided options if available
876
959
  if (options?.base64Image) {
877
- return `data:image/png;base64,${options.base64Image}`;
960
+ return {
961
+ base64: options.base64Image,
962
+ mediaType: options.mediaType ?? "image/png",
963
+ };
878
964
  }
879
965
  // Use the screenshot provider if available
880
966
  if (this.screenshotProvider) {
881
967
  try {
882
- const base64Image = await this.screenshotProvider();
883
- return `data:image/png;base64,${base64Image}`;
968
+ return await this.screenshotProvider();
884
969
  }
885
970
  catch (error) {
886
971
  console.error("Error capturing screenshot:", error);
@@ -888,7 +973,7 @@ export class GoogleCUAClient extends AgentClient {
888
973
  }
889
974
  }
890
975
  throw new AgentScreenshotProviderError("`screenshotProvider` has not been set. " +
891
- "Please call `setScreenshotProvider()` with a valid function that returns a base64-encoded image");
976
+ "Please call `setScreenshotProvider()` with a valid function that returns a base64-encoded image and media type");
892
977
  }
893
978
  }
894
979
  //# sourceMappingURL=GoogleCUAClient.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"GoogleCUAClient.js","sourceRoot":"","sources":["../../../../../lib/v3/agent/GoogleCUAClient.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,WAAW,GAQZ,MAAM,eAAe,CAAC;AAWvB,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EACL,4BAA4B,EAC5B,gBAAgB,EAChB,oBAAoB,GACrB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,0BAA0B,EAAE,MAAM,iBAAiB,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;YAChD,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,OAAO,CAAC,KAAK,CAAC,6BAA6B,EAAE,KAAK,CAAC,CAAC;gBACpD,MAAM,KAAK,CAAC;YACd,CAAC;QACH,CAAC;QAED,MAAM,IAAI,4BAA4B,CACpC,yCAAyC;YACvC,iGAAiG,CACpG,CAAC;IACJ,CAAC;CACF","sourcesContent":["import {\n GoogleGenAI,\n Content,\n Part,\n GenerateContentResponse,\n FunctionCall,\n GenerateContentConfig,\n Tool,\n GoogleGenAIOptions,\n} from \"@google/genai\";\nimport { LogLine } from \"../types/public/logs.js\";\nimport {\n AgentAction,\n AgentResult,\n AgentType,\n AgentExecutionOptions,\n SafetyCheck,\n SafetyConfirmationHandler,\n} from \"../types/public/agent.js\";\nimport { ClientOptions } from \"../types/public/model.js\";\nimport { AgentClient } from \"./AgentClient.js\";\nimport {\n AgentScreenshotProviderError,\n LLMResponseError,\n StagehandClosedError,\n} from \"../types/public/sdkErrors.js\";\nimport { buildGoogleCUASystemPrompt } from \"../../prompt.js\";\nimport { compressGoogleConversationImages } from \"./utils/imageCompression.js\";\nimport { mapKeyToPlaywright } from \"./utils/cuaKeyMapping.js\";\nimport {\n executeGoogleCustomTool,\n isCustomTool,\n convertToolSetToFunctionDeclarations,\n} from \"./utils/googleCustomToolHandler.js\";\nimport { ToolSet } from \"ai\";\nimport {\n FlowLogger,\n extractLlmCuaPromptSummary,\n extractLlmCuaResponseSummary,\n} from \"../flowlogger/FlowLogger.js\";\nimport { v7 as uuidv7 } from \"uuid\";\n\n/**\n * Client for Google's Computer Use Assistant API\n * This implementation uses the Google Generative AI SDK for Computer Use\n */\nexport class GoogleCUAClient extends AgentClient {\n private apiKey: string;\n private client: GoogleGenAI;\n private currentViewport = { width: 1288, height: 711 };\n private currentUrl?: string;\n private screenshotProvider?: () => Promise<string>;\n private actionHandler?: (action: AgentAction) => Promise<void>;\n private history: Content[] = [];\n private environment: \"ENVIRONMENT_BROWSER\" | \"ENVIRONMENT_DESKTOP\" =\n \"ENVIRONMENT_BROWSER\";\n private generateContentConfig: GenerateContentConfig;\n private tools?: ToolSet;\n private baseURL?: string;\n private safetyConfirmationHandler?: SafetyConfirmationHandler;\n constructor(\n type: AgentType,\n modelName: string,\n userProvidedInstructions?: string,\n clientOptions?: ClientOptions,\n tools?: ToolSet,\n ) {\n super(type, modelName, userProvidedInstructions);\n\n this.tools = tools;\n // Process client options\n this.apiKey =\n (clientOptions?.apiKey as string) ||\n process.env.GEMINI_API_KEY ||\n process.env.GOOGLE_GENERATIVE_AI_API_KEY ||\n process.env.GOOGLE_API_KEY ||\n \"\";\n this.baseURL = clientOptions?.baseURL as string | undefined;\n\n // Initialize the Google Generative AI client\n const genAIOptions: GoogleGenAIOptions = {\n apiKey: this.apiKey,\n ...(this.baseURL ? { httpOptions: { baseUrl: this.baseURL } } : {}),\n };\n this.client = new GoogleGenAI(genAIOptions);\n\n // Get environment if specified\n if (\n clientOptions?.environment &&\n typeof clientOptions.environment === \"string\"\n ) {\n this.environment = clientOptions.environment as typeof this.environment;\n }\n\n this.generateContentConfig = {\n temperature: 1,\n topP: 0.95,\n topK: 40,\n maxOutputTokens: 8192,\n // systemInstruction: this.userProvidedInstructions\n // ? { parts: [{ text: this.userProvidedInstructions }] }\n // : { parts: [{ text: buildGoogleCUASystemPrompt() }] },\n tools: [\n {\n computerUse: {\n environment: this.environment,\n },\n } as Tool,\n ],\n };\n\n // Store client options for reference\n this.clientOptions = {\n apiKey: this.apiKey,\n ...(this.baseURL ? { baseURL: this.baseURL } : {}),\n };\n\n // Initialize tools if provided\n if (this.tools && Object.keys(this.tools).length > 0) {\n this.updateGenerateContentConfig();\n }\n }\n\n public setViewport(width: number, height: number): void {\n this.currentViewport = { width, height };\n }\n\n setCurrentUrl(url: string): void {\n this.currentUrl = url;\n }\n\n setScreenshotProvider(provider: () => Promise<string>): void {\n this.screenshotProvider = provider;\n }\n\n setActionHandler(handler: (action: AgentAction) => Promise<void>): void {\n this.actionHandler = handler;\n }\n\n setTools(tools: ToolSet): void {\n this.tools = tools;\n this.updateGenerateContentConfig();\n }\n\n setSafetyConfirmationHandler(handler?: SafetyConfirmationHandler): void {\n this.safetyConfirmationHandler = handler;\n }\n\n private async handleSafetyConfirmation(\n safetyDecision: unknown,\n logger: (message: LogLine) => void,\n ): Promise<string | undefined> {\n const safetyMessage =\n typeof safetyDecision === \"object\"\n ? JSON.stringify(safetyDecision, null, 2)\n : String(safetyDecision);\n\n const safetyChecks: SafetyCheck[] = [\n {\n id: \"google-safety-decision\",\n code: \"safety_decision\",\n message: safetyMessage,\n },\n ];\n\n if (this.safetyConfirmationHandler) {\n logger({\n category: \"agent\",\n message: `Requesting safety confirmation for Google safety decision: ${safetyMessage}`,\n level: 1,\n });\n\n const response = await this.safetyConfirmationHandler(safetyChecks);\n\n if (response.acknowledged) {\n logger({\n category: \"agent\",\n message: `Safety decision acknowledged by user`,\n level: 1,\n });\n return \"true\";\n } else {\n logger({\n category: \"agent\",\n message: `Safety decision rejected by user`,\n level: 1,\n });\n return undefined;\n }\n }\n\n logger({\n category: \"agent\",\n message: `Auto-acknowledging Google safety decision`,\n level: 2,\n });\n return \"true\";\n }\n\n /**\n * Update the generateContentConfig with current tools\n */\n private updateGenerateContentConfig(): void {\n const functionDeclarations =\n this.tools && Object.keys(this.tools).length > 0\n ? convertToolSetToFunctionDeclarations(this.tools)\n : [];\n\n this.generateContentConfig = {\n ...this.generateContentConfig,\n tools: [\n {\n computerUse: {\n environment: this.environment,\n },\n ...(functionDeclarations.length > 0 ? { functionDeclarations } : {}),\n } as Tool,\n ],\n };\n }\n\n /**\n * Execute a task with the Google CUA\n * This is the main entry point for the agent\n * @implements AgentClient.execute\n */\n async execute(executionOptions: AgentExecutionOptions): Promise<AgentResult> {\n const { options, logger } = executionOptions;\n const { instruction } = options;\n const maxSteps = options.maxSteps || 10;\n\n let currentStep = 0;\n let completed = false;\n const actions: AgentAction[] = [];\n const messageList: string[] = [];\n let finalMessage = \"\";\n this.history = []; // Clear history for new execution\n\n // Start with the initial instruction\n await this.initializeHistory(instruction);\n\n let totalInputTokens = 0;\n let totalOutputTokens = 0;\n let totalInferenceTime = 0;\n\n try {\n // Execute steps until completion or max steps reached\n while (!completed && currentStep < maxSteps) {\n await this.preStepHook?.();\n\n logger({\n category: \"agent\",\n message: `Executing step ${currentStep + 1}/${maxSteps}`,\n level: 1,\n });\n\n const result = await this.executeStep(logger);\n totalInputTokens += result.usage.input_tokens;\n totalOutputTokens += result.usage.output_tokens;\n totalInferenceTime += result.usage.inference_time_ms;\n\n // Add actions to the list\n actions.push(...result.actions);\n\n // Update completion status\n completed = result.completed;\n\n // Record any message for this step\n if (result.message) {\n messageList.push(result.message);\n finalMessage = result.message;\n }\n\n // Increment step counter\n currentStep++;\n }\n\n // Return the final result\n return {\n success: completed,\n actions,\n message: finalMessage,\n completed,\n usage: {\n input_tokens: totalInputTokens,\n output_tokens: totalOutputTokens,\n inference_time_ms: totalInferenceTime,\n },\n };\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n logger({\n category: \"agent\",\n message: `Error executing agent task: ${errorMessage}`,\n level: 0,\n });\n\n return {\n success: false,\n actions,\n message: `Failed to execute task: ${errorMessage}`,\n completed: false,\n usage: {\n input_tokens: totalInputTokens,\n output_tokens: totalOutputTokens,\n inference_time_ms: totalInferenceTime,\n },\n };\n }\n }\n\n /**\n * Initialize conversation history with the initial instruction\n */\n private async initializeHistory(instruction: string): Promise<void> {\n const parts: Part[] = [{ text: instruction }];\n\n // Note: The Python implementation doesn't include the initial screenshot\n // Following the same pattern here\n\n const systemPromptContent = this.userProvidedInstructions\n ? this.userProvidedInstructions\n : buildGoogleCUASystemPrompt().content;\n\n this.history = [\n {\n role: \"user\",\n parts: [\n {\n text: \"System prompt: \" + systemPromptContent,\n },\n ],\n },\n {\n role: \"user\",\n parts,\n },\n ];\n }\n\n /**\n * Execute a single step of the agent\n */\n async executeStep(logger: (message: LogLine) => void): Promise<{\n actions: AgentAction[];\n message: string;\n completed: boolean;\n usage: {\n input_tokens: number;\n output_tokens: number;\n inference_time_ms: number;\n };\n }> {\n try {\n const startTime = Date.now();\n\n // Compress images in conversation history before sending to the model\n const compressedResult = compressGoogleConversationImages(\n this.history,\n 2,\n );\n const compressedHistory = compressedResult.items;\n\n // Use the SDK's generateContent method with retry logic (matching Python's get_model_response)\n const maxRetries = 5;\n const baseDelayS = 1;\n let lastError: Error | null = null;\n let response: GenerateContentResponse | null = null;\n\n // Log LLM request\n const llmRequestId = uuidv7();\n FlowLogger.logLlmRequest({\n requestId: llmRequestId,\n model: this.modelName,\n prompt: extractLlmCuaPromptSummary(compressedHistory),\n });\n\n for (let attempt = 0; attempt < maxRetries; attempt++) {\n try {\n // Add exponential backoff delay for retries\n if (attempt > 0) {\n const delay = baseDelayS * Math.pow(2, attempt) * 1000; // Convert to ms\n logger({\n category: \"agent\",\n message: `Generating content failed on attempt ${attempt + 1}. Retrying in ${delay / 1000} seconds...`,\n level: 2,\n });\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n\n // Use the SDK's generateContent method - following Python SDK pattern\n response = await this.client.models.generateContent({\n model: this.modelName,\n contents: compressedHistory,\n config: this.generateContentConfig,\n });\n\n // Check if we have valid response content\n if (!response.candidates || response.candidates.length === 0) {\n throw new LLMResponseError(\"agent\", \"Response has no candidates!\");\n }\n\n const candidate = response.candidates[0];\n if (!candidate.content || !candidate.content.parts) {\n const reason = candidate.finishReason || \"unknown\";\n throw new LLMResponseError(\n \"agent\",\n `Response has no content (finish reason: ${reason})`,\n );\n }\n\n // Success - we have a valid response\n break;\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n logger({\n category: \"agent\",\n message: `API call error: ${lastError.message}`,\n level: 2,\n });\n\n // If this was the last attempt, throw the error\n if (attempt === maxRetries - 1) {\n logger({\n category: \"agent\",\n message: `Generating content failed after ${maxRetries} attempts.`,\n level: 0,\n });\n throw lastError;\n }\n }\n }\n\n if (!response) {\n throw (\n lastError || new Error(\"Failed to get response after all retries\")\n );\n }\n\n const endTime = Date.now();\n const elapsedMs = endTime - startTime;\n const { usageMetadata } = response;\n\n // Log LLM response\n FlowLogger.logLlmResponse({\n requestId: llmRequestId,\n model: this.modelName,\n output: extractLlmCuaResponseSummary(response),\n inputTokens: usageMetadata?.promptTokenCount,\n outputTokens: usageMetadata?.candidatesTokenCount,\n });\n\n // Process the response\n const result = await this.processResponse(response, logger);\n\n // Add model response to history\n if (response.candidates && response.candidates[0]) {\n // Sanitize any out-of-range coordinates in function calls before adding to history\n const sanitizedContent = JSON.parse(\n JSON.stringify(response.candidates[0].content),\n );\n if (sanitizedContent.parts) {\n for (const part of sanitizedContent.parts) {\n if (part.functionCall?.args) {\n if (\n typeof part.functionCall.args.x === \"number\" &&\n part.functionCall.args.x > 999\n ) {\n part.functionCall.args.x = 999;\n }\n if (\n typeof part.functionCall.args.y === \"number\" &&\n part.functionCall.args.y > 999\n ) {\n part.functionCall.args.y = 999;\n }\n }\n }\n }\n this.history.push(sanitizedContent);\n }\n\n // Execute actions and collect function responses\n const functionResponses: Part[] = [];\n\n // Always process the model's response, even when it produced no\n // executable action (e.g. a standalone take_screenshot). The model\n // expects exactly one function response — a fresh screenshot — per\n // computer-use call; skipping it when there are 0 actions leaves the\n // model blind and it gives up after one empty turn.\n {\n let hasError = false;\n\n // Execute all actions (a no-op when there are none).\n for (let i = 0; i < result.actions.length; i++) {\n const action = result.actions[i];\n\n logger({\n category: \"agent\",\n message: `Executing action ${i + 1}/${result.actions.length}: ${action.type}`,\n level: 2,\n });\n\n // Special handling for open_web_browser - don't execute it\n if (action.type === \"open_web_browser\") {\n // Set pageUrl for open_web_browser since it doesn't go through action handler\n action.pageUrl = this.currentUrl;\n logger({\n category: \"agent\",\n message: \"Skipping open_web_browser action\",\n level: 2,\n });\n } else if (action.type === \"screenshot\") {\n // No interaction to perform — the screenshot captured below is\n // returned to the model as this call's function response.\n logger({\n category: \"agent\",\n message: \"take_screenshot: capturing current page\",\n level: 2,\n });\n } else if (action.type === \"custom_tool\") {\n const toolName = action.name as string;\n const toolArgs = action.arguments as Record<string, unknown>;\n\n if (this.tools && toolName in this.tools) {\n const correspondingFunctionCall = result.functionCalls.find(\n (fc) => fc.name === toolName,\n );\n\n if (correspondingFunctionCall) {\n const executionResult = await executeGoogleCustomTool(\n toolName,\n toolArgs,\n this.tools,\n correspondingFunctionCall,\n logger,\n );\n\n functionResponses.push(executionResult.functionResponse);\n\n if (!executionResult.success) {\n hasError = true;\n }\n }\n }\n } else if (this.actionHandler) {\n try {\n await this.actionHandler(action);\n\n // Add a delay between actions to ensure they complete properly\n // Longer delay for typing actions to ensure fields are ready\n if (i < result.actions.length - 1) {\n const nextAction = result.actions[i + 1];\n const isTypingAction =\n action.type === \"type\" || nextAction.type === \"type\";\n const delay = isTypingAction ? 500 : 200;\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n } catch (actionError) {\n if (actionError instanceof StagehandClosedError) {\n throw actionError;\n }\n logger({\n category: \"agent\",\n message: `Error executing action ${action.type}: ${actionError}`,\n level: 0,\n });\n hasError = true;\n // Continue processing other actions even if one fails\n }\n }\n }\n\n // Create function responses for computer use actions (non-custom tools)\n // We need exactly one response per function call, regardless of how many actions were generated\n if (result.functionCalls.length > 0 || hasError) {\n // Filter out custom tool function calls as they've already been handled\n const computerUseFunctionCalls = result.functionCalls.filter(\n (fc) => !isCustomTool(fc, this.tools),\n );\n\n if (computerUseFunctionCalls.length > 0) {\n try {\n logger({\n category: \"agent\",\n message: `Taking screenshot after executing ${result.actions.length} actions${hasError ? \" (with errors)\" : \"\"}`,\n level: 2,\n });\n\n const screenshot = await this.captureScreenshot();\n const base64Data = screenshot.replace(\n /^data:image\\/png;base64,/,\n \"\",\n );\n\n // Create one function response for each computer use function call\n // Following Python SDK pattern: FunctionResponse with parts containing inline_data\n for (const functionCall of computerUseFunctionCalls) {\n let safetyAcknowledgement: string | undefined;\n if (functionCall.args?.safety_decision) {\n safetyAcknowledgement = await this.handleSafetyConfirmation(\n functionCall.args.safety_decision,\n logger,\n );\n }\n\n const functionResponsePart: Part = {\n functionResponse: {\n name: functionCall.name,\n response: {\n url: this.currentUrl || \"\",\n ...(safetyAcknowledgement !== undefined\n ? {\n safety_acknowledgement: safetyAcknowledgement,\n }\n : {}),\n },\n parts: [\n {\n inlineData: {\n mimeType: \"image/png\",\n data: base64Data,\n },\n },\n ],\n },\n };\n functionResponses.push(functionResponsePart);\n }\n } catch (error) {\n logger({\n category: \"agent\",\n message: `Error capturing screenshot: ${error}`,\n level: 0,\n });\n }\n }\n }\n\n // Add all function responses to history in a single user message\n if (functionResponses.length > 0) {\n logger({\n category: \"agent\",\n message: `Adding ${functionResponses.length} function responses to history`,\n level: 2,\n });\n this.history.push({\n role: \"user\",\n parts: functionResponses,\n });\n }\n }\n\n return {\n actions: result.actions,\n message: result.message,\n completed: result.completed,\n usage: {\n input_tokens: usageMetadata?.promptTokenCount || 0,\n output_tokens: usageMetadata?.candidatesTokenCount || 0,\n inference_time_ms: elapsedMs,\n },\n };\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n logger({\n category: \"agent\",\n message: `Error executing step: ${errorMessage}`,\n level: 0,\n });\n\n throw error;\n }\n }\n\n /**\n * Process the response from Google's API\n */\n private async processResponse(\n response: GenerateContentResponse,\n logger: (message: LogLine) => void,\n ): Promise<{\n actions: AgentAction[];\n message: string;\n completed: boolean;\n functionCalls: FunctionCall[];\n }> {\n const actions: AgentAction[] = [];\n let message = \"\";\n const functionCalls: FunctionCall[] = [];\n\n if (!response.candidates || response.candidates.length === 0) {\n return {\n actions: [],\n message: \"No candidates in response\",\n completed: true,\n functionCalls: [],\n };\n }\n const candidate = response.candidates[0];\n\n // Log the raw response for debugging\n logger({\n category: \"agent\",\n message: `Raw response from Google: ${JSON.stringify(candidate.content, null, 2)}`,\n level: 2,\n });\n\n // Process all parts - Google can send multiple function calls\n for (const part of candidate.content.parts) {\n if (part.text) {\n message += part.text + \"\\n\";\n logger({\n category: \"agent\",\n message: `Reasoning: ${part.text}`,\n level: 1,\n });\n }\n if (part.functionCall) {\n functionCalls.push(part.functionCall);\n logger({\n category: \"agent\",\n message: `Found function call: ${part.functionCall.name} with args: ${JSON.stringify(part.functionCall.args)}`,\n level: 2,\n });\n\n // Convert function call to action(s)\n const action = this.convertFunctionCallToAction(part.functionCall);\n if (action) {\n // Special handling for type actions. gemini-2.5 type_text_at carries\n // coordinates (click the field first); gemini-3.x `type` has none and\n // types into the element the model already focused.\n if (action.type === \"type\") {\n logger({\n category: \"agent\",\n message: `Adding action: ${JSON.stringify(action)}`,\n level: 2,\n });\n // Click the target first only when coordinates are provided.\n if (typeof action.x === \"number\" && typeof action.y === \"number\") {\n actions.push({\n type: \"click\",\n x: action.x,\n y: action.y,\n button: \"left\",\n });\n }\n\n // If clear_before_typing is true (default), add a select all\n if (action.clearBeforeTyping) {\n // Select all text in the field\n actions.push({\n type: \"keypress\",\n keys: [\"ControlOrMeta+A\"],\n });\n actions.push({\n type: \"keypress\",\n keys: [\"Backspace\"],\n });\n }\n\n // Then add the type action\n actions.push(action);\n if (action.pressEnter) {\n actions.push({\n type: \"keypress\",\n keys: [\"Enter\"],\n });\n }\n } else {\n actions.push(action);\n }\n } else {\n logger({\n category: \"agent\",\n message: `Warning: Could not convert function call ${part.functionCall.name} to action`,\n level: 1,\n });\n }\n }\n }\n\n // Log summary of what we found\n logger({\n category: \"agent\",\n message: `Found ${functionCalls.length} function calls, converted to ${actions.length} actions`,\n level: 2,\n });\n\n // Check if task is completed\n const completed =\n functionCalls.length === 0 ||\n (candidate.finishReason && candidate.finishReason !== \"STOP\");\n\n return {\n actions,\n message: message.trim(),\n completed,\n functionCalls,\n };\n }\n\n /**\n * Convert Google function call to Stagehand action\n */\n private convertFunctionCallToAction(\n functionCall: FunctionCall,\n ): AgentAction | null {\n const { name: rawName } = functionCall;\n // Default args to an empty object so no-argument predefined functions\n // (e.g. take_screenshot, go_back) are not rejected by the guard below.\n const args = functionCall.args ?? {};\n\n if (!rawName) {\n return null;\n }\n\n // The gemini-3.x computer-use tool renamed several of the predefined\n // functions that gemini-2.5-computer-use-preview used, and adds a\n // descriptive `intent` arg to every call. The argument fields are otherwise\n // unchanged (confirmed for click/navigate). Normalize the 3.x names to the\n // canonical 2.5 names so a single set of handlers serves both generations;\n // `intent` is ignored since handlers only read the args they need.\n // NOTE: click and take_screenshot are confirmed from live gemini-3.5-flash\n // traffic; the rest are inferred from the same drop-the-qualifier pattern\n // and are safe aliases (any unmapped name still hits the warning below).\n const NAME_ALIASES: Record<string, string> = {\n click: \"click_at\",\n left_click: \"click_at\",\n double_click: \"click_at\",\n triple_click: \"click_at\",\n type: \"type_text_at\",\n type_text: \"type_text_at\",\n hover: \"hover_at\",\n scroll: \"scroll_at\",\n drag: \"drag_and_drop\",\n key: \"key_combination\",\n keys: \"key_combination\",\n key_press: \"key_combination\",\n press_key: \"key_combination\",\n press_keys: \"key_combination\",\n hotkey: \"key_combination\",\n screenshot: \"take_screenshot\",\n wait: \"wait_5_seconds\",\n };\n const name = NAME_ALIASES[rawName] ?? rawName;\n\n switch (name) {\n case \"open_web_browser\":\n return {\n type: \"open_web_browser\",\n timestamp: Date.now(),\n };\n\n case \"take_screenshot\":\n // No UI interaction. The step loop captures a fresh screenshot and\n // returns it to the model as this call's function response; marked as a\n // recognized action (not null) so it isn't dropped, and skipped in the\n // executor like open_web_browser.\n return {\n type: \"screenshot\",\n timestamp: Date.now(),\n };\n\n case \"click_at\": {\n const { x, y } = this.normalizeCoordinates(\n args.x as number,\n args.y as number,\n );\n return {\n type: \"click\",\n x,\n y,\n button: args.button || \"left\",\n };\n }\n\n case \"type_text_at\": {\n // press_enter and clear_before_typing are shared across generations.\n const pressEnter = (args.press_enter as boolean) ?? false;\n const clearBeforeTyping = (args.clear_before_typing as boolean) ?? true;\n const base = {\n type: \"type\" as const,\n text: args.text as string,\n pressEnter,\n clearBeforeTyping,\n };\n\n // gemini-2.5 type_text_at carries x/y (click the field, then type).\n // gemini-3.x `type` has no coordinates and types into the element the\n // model already focused with a preceding click. Only attach coords when\n // present so the executor doesn't click at NaN.\n if (typeof args.x === \"number\" && typeof args.y === \"number\") {\n const { x, y } = this.normalizeCoordinates(args.x, args.y);\n return { ...base, x, y };\n }\n return base;\n }\n\n case \"key_combination\": {\n // gemini-2.5 key_combination sends `keys` as a \"+\"-joined string;\n // gemini-3.x `hotkey` sends a `keys` array, and `press_key` sends a\n // single `key`. Accept all three.\n const raw = args.keys !== undefined ? args.keys : args.key;\n const parts = Array.isArray(raw)\n ? (raw as string[])\n : String(raw ?? \"\").split(\"+\");\n const keys = parts\n .map((key) => String(key).trim())\n .filter(Boolean)\n .map((key) => mapKeyToPlaywright(key));\n if (keys.length === 0) {\n return null;\n }\n return {\n type: \"keypress\",\n keys,\n };\n }\n\n case \"scroll_document\": {\n const direction = (args.direction as string).toLowerCase();\n return {\n type: \"keypress\",\n keys: [direction === \"up\" ? \"PageUp\" : \"PageDown\"],\n };\n }\n\n case \"scroll_at\": {\n // A coordinate-less `scroll` alias (gemini-3.x) scrolls the document.\n if (typeof args.x !== \"number\" || typeof args.y !== \"number\") {\n const dir = ((args.direction as string) || \"down\").toLowerCase();\n return {\n type: \"keypress\",\n keys: [dir === \"up\" ? \"PageUp\" : \"PageDown\"],\n };\n }\n const { x, y } = this.normalizeCoordinates(\n args.x as number,\n args.y as number,\n );\n const direction = ((args.direction as string) || \"down\").toLowerCase();\n // 2.5 uses `magnitude`; gemini-3.x `scroll` uses `magnitude_in_pixels`.\n const magnitude =\n typeof args.magnitude === \"number\"\n ? (args.magnitude as number)\n : typeof args.magnitude_in_pixels === \"number\"\n ? (args.magnitude_in_pixels as number)\n : 800;\n\n let scroll_x = 0;\n let scroll_y = 0;\n if (direction === \"up\") {\n scroll_y = -magnitude;\n } else if (direction === \"down\") {\n scroll_y = magnitude;\n } else if (direction === \"left\") {\n scroll_x = -magnitude;\n } else if (direction === \"right\") {\n scroll_x = magnitude;\n } else {\n // Default to down if unknown direction\n scroll_y = magnitude;\n }\n\n return {\n type: \"scroll\",\n x,\n y,\n scroll_x,\n scroll_y,\n };\n }\n\n case \"navigate\":\n return {\n type: \"goto\",\n url: args.url as string,\n };\n\n case \"go_back\":\n return {\n type: \"back\",\n };\n\n case \"go_forward\":\n return {\n type: \"forward\",\n };\n\n case \"wait_5_seconds\":\n return {\n type: \"wait\",\n timeMs: 5000, // Google CUA waits for 5 seconds\n };\n\n case \"hover_at\": {\n const { x, y } = this.normalizeCoordinates(\n args.x as number,\n args.y as number,\n );\n return {\n type: \"move\",\n x,\n y,\n };\n }\n\n case \"search\":\n return {\n type: \"goto\",\n url: \"https://www.google.com\",\n };\n\n case \"drag_and_drop\": {\n // 2.5 uses x/y + destination_x/destination_y; gemini-3.x `drag_and_drop`\n // uses start_x/start_y + end_x/end_y. Accept either.\n const sx = (args.x ?? args.start_x) as number;\n const sy = (args.y ?? args.start_y) as number;\n const ex = (args.destination_x ?? args.end_x) as number;\n const ey = (args.destination_y ?? args.end_y) as number;\n if (\n typeof sx !== \"number\" ||\n typeof sy !== \"number\" ||\n typeof ex !== \"number\" ||\n typeof ey !== \"number\"\n ) {\n return null;\n }\n const startPoint = this.normalizeCoordinates(sx, sy);\n const endPoint = this.normalizeCoordinates(ex, ey);\n return {\n type: \"drag\",\n path: [\n { x: startPoint.x, y: startPoint.y },\n { x: endPoint.x, y: endPoint.y },\n ],\n };\n }\n\n default:\n if (isCustomTool(functionCall, this.tools)) {\n return {\n type: \"custom_tool\",\n name,\n arguments: args,\n timestamp: Date.now(),\n pageUrl: this.currentUrl,\n };\n }\n console.warn(`Unsupported Google CUA function: ${name}`);\n return null;\n }\n }\n\n /**\n * Normalize coordinates from Google's 0-1000 range to viewport dimensions\n */\n private normalizeCoordinates(x: number, y: number): { x: number; y: number } {\n const clampedX = Math.min(999, Math.max(0, x));\n const clampedY = Math.min(999, Math.max(0, y));\n return {\n x: Math.floor((clampedX / 1000) * this.currentViewport.width),\n y: Math.floor((clampedY / 1000) * this.currentViewport.height),\n };\n }\n\n async captureScreenshot(options?: {\n base64Image?: string;\n currentUrl?: string;\n }): Promise<string> {\n // Update current URL if provided\n if (options?.currentUrl) {\n this.currentUrl = options.currentUrl;\n }\n\n // Use provided options if available\n if (options?.base64Image) {\n return `data:image/png;base64,${options.base64Image}`;\n }\n\n // Use the screenshot provider if available\n if (this.screenshotProvider) {\n try {\n const base64Image = await this.screenshotProvider();\n return `data:image/png;base64,${base64Image}`;\n } catch (error) {\n console.error(\"Error capturing screenshot:\", error);\n throw error;\n }\n }\n\n throw new AgentScreenshotProviderError(\n \"`screenshotProvider` has not been set. \" +\n \"Please call `setScreenshotProvider()` with a valid function that returns a base64-encoded image\",\n );\n }\n}\n"]}
1
+ {"version":3,"file":"GoogleCUAClient.js","sourceRoot":"","sources":["../../../../../lib/v3/agent/GoogleCUAClient.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,WAAW,GAQZ,MAAM,eAAe,CAAC;AAYvB,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EACL,4BAA4B,EAC5B,gBAAgB,EAChB,oBAAoB,GACrB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,0BAA0B,EAAE,MAAM,iBAAiB,CAAC;AAC7D,OAAO,EAAE,gCAAgC,EAAE,MAAM,6BAA6B,CAAC;AAC/E,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAC9D,OAAO,EACL,uBAAuB,EACvB,YAAY,EACZ,oCAAoC,GACrC,MAAM,oCAAoC,CAAC;AAE5C,OAAO,EACL,UAAU,EACV,0BAA0B,EAC1B,4BAA4B,GAC7B,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,EAAE,IAAI,MAAM,EAAE,MAAM,MAAM,CAAC;AAEpC;;;GAGG;AACH,MAAM,OAAO,eAAgB,SAAQ,WAAW;IACtC,MAAM,CAAS;IACf,MAAM,CAAc;IACpB,eAAe,GAAG,EAAE,KAAK,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@google/genai\";\nimport { LogLine } from \"../types/public/logs.js\";\nimport {\n AgentAction,\n AgentResult,\n AgentType,\n AgentExecutionOptions,\n SafetyCheck,\n SafetyConfirmationHandler,\n ScreenshotProviderResult,\n} from \"../types/public/agent.js\";\nimport { ClientOptions } from \"../types/public/model.js\";\nimport { AgentClient } from \"./AgentClient.js\";\nimport {\n AgentScreenshotProviderError,\n LLMResponseError,\n StagehandClosedError,\n} from \"../types/public/sdkErrors.js\";\nimport { buildGoogleCUASystemPrompt } from \"../../prompt.js\";\nimport { compressGoogleConversationImages } from \"./utils/imageCompression.js\";\nimport { mapKeyToPlaywright } from \"./utils/cuaKeyMapping.js\";\nimport {\n executeGoogleCustomTool,\n isCustomTool,\n convertToolSetToFunctionDeclarations,\n} from \"./utils/googleCustomToolHandler.js\";\nimport { ToolSet } from \"ai\";\nimport {\n FlowLogger,\n extractLlmCuaPromptSummary,\n extractLlmCuaResponseSummary,\n} from \"../flowlogger/FlowLogger.js\";\nimport { v7 as uuidv7 } from \"uuid\";\n\n/**\n * Client for Google's Computer Use Assistant API\n * This implementation uses the Google Generative AI SDK for Computer Use\n */\nexport class GoogleCUAClient extends AgentClient {\n private apiKey: string;\n private client: GoogleGenAI;\n private currentViewport = { width: 1288, height: 711 };\n private currentUrl?: string;\n private screenshotProvider?: () => Promise<ScreenshotProviderResult>;\n private actionHandler?: (action: AgentAction) => Promise<void>;\n private history: Content[] = [];\n private environment: \"ENVIRONMENT_BROWSER\" | \"ENVIRONMENT_DESKTOP\" =\n \"ENVIRONMENT_BROWSER\";\n private generateContentConfig: GenerateContentConfig;\n private tools?: ToolSet;\n private baseURL?: string;\n private safetyConfirmationHandler?: SafetyConfirmationHandler;\n constructor(\n type: AgentType,\n modelName: string,\n userProvidedInstructions?: string,\n clientOptions?: ClientOptions,\n tools?: ToolSet,\n ) {\n super(type, modelName, userProvidedInstructions);\n\n this.tools = tools;\n // Process client options\n this.apiKey =\n (clientOptions?.apiKey as string) ||\n process.env.GEMINI_API_KEY ||\n process.env.GOOGLE_GENERATIVE_AI_API_KEY ||\n process.env.GOOGLE_API_KEY ||\n \"\";\n this.baseURL = clientOptions?.baseURL as string | undefined;\n\n // Initialize the Google Generative AI client\n const genAIOptions: GoogleGenAIOptions = {\n apiKey: this.apiKey,\n ...(this.baseURL ? { httpOptions: { baseUrl: this.baseURL } } : {}),\n };\n this.client = new GoogleGenAI(genAIOptions);\n\n // Get environment if specified\n if (\n clientOptions?.environment &&\n typeof clientOptions.environment === \"string\"\n ) {\n this.environment = clientOptions.environment as typeof this.environment;\n }\n\n this.generateContentConfig = {\n temperature: 1,\n topP: 0.95,\n topK: 40,\n maxOutputTokens: 8192,\n // systemInstruction: this.userProvidedInstructions\n // ? { parts: [{ text: this.userProvidedInstructions }] }\n // : { parts: [{ text: buildGoogleCUASystemPrompt() }] },\n tools: [\n {\n computerUse: {\n environment: this.environment,\n },\n } as Tool,\n ],\n };\n\n // Store client options for reference\n this.clientOptions = {\n apiKey: this.apiKey,\n ...(this.baseURL ? { baseURL: this.baseURL } : {}),\n };\n\n // Initialize tools if provided\n if (this.tools && Object.keys(this.tools).length > 0) {\n this.updateGenerateContentConfig();\n }\n }\n\n public setViewport(width: number, height: number): void {\n this.currentViewport = { width, height };\n }\n\n setCurrentUrl(url: string): void {\n this.currentUrl = url;\n }\n\n setScreenshotProvider(\n provider: () => Promise<ScreenshotProviderResult>,\n ): void {\n this.screenshotProvider = provider;\n }\n\n setActionHandler(handler: (action: AgentAction) => Promise<void>): void {\n this.actionHandler = handler;\n }\n\n setTools(tools: ToolSet): void {\n this.tools = tools;\n this.updateGenerateContentConfig();\n }\n\n setSafetyConfirmationHandler(handler?: SafetyConfirmationHandler): void {\n this.safetyConfirmationHandler = handler;\n }\n\n private async handleSafetyConfirmation(\n safetyDecision: unknown,\n logger: (message: LogLine) => void,\n ): Promise<string | undefined> {\n const safetyMessage =\n typeof safetyDecision === \"object\"\n ? JSON.stringify(safetyDecision, null, 2)\n : String(safetyDecision);\n\n const safetyChecks: SafetyCheck[] = [\n {\n id: \"google-safety-decision\",\n code: \"safety_decision\",\n message: safetyMessage,\n },\n ];\n\n if (this.safetyConfirmationHandler) {\n logger({\n category: \"agent\",\n message: `Requesting safety confirmation for Google safety decision: ${safetyMessage}`,\n level: 1,\n });\n\n const response = await this.safetyConfirmationHandler(safetyChecks);\n\n if (response.acknowledged) {\n logger({\n category: \"agent\",\n message: `Safety decision acknowledged by user`,\n level: 1,\n });\n return \"true\";\n } else {\n logger({\n category: \"agent\",\n message: `Safety decision rejected by user`,\n level: 1,\n });\n return undefined;\n }\n }\n\n logger({\n category: \"agent\",\n message: `Auto-acknowledging Google safety decision`,\n level: 2,\n });\n return \"true\";\n }\n\n /**\n * Update the generateContentConfig with current tools\n */\n private updateGenerateContentConfig(): void {\n const functionDeclarations =\n this.tools && Object.keys(this.tools).length > 0\n ? convertToolSetToFunctionDeclarations(this.tools)\n : [];\n\n this.generateContentConfig = {\n ...this.generateContentConfig,\n tools: [\n {\n computerUse: {\n environment: this.environment,\n },\n ...(functionDeclarations.length > 0 ? { functionDeclarations } : {}),\n } as Tool,\n ],\n };\n }\n\n /**\n * Execute a task with the Google CUA\n * This is the main entry point for the agent\n * @implements AgentClient.execute\n */\n async execute(executionOptions: AgentExecutionOptions): Promise<AgentResult> {\n const { options, logger } = executionOptions;\n const { instruction } = options;\n const maxSteps = options.maxSteps || 10;\n\n let currentStep = 0;\n let completed = false;\n const actions: AgentAction[] = [];\n const messageList: string[] = [];\n let finalMessage = \"\";\n this.history = []; // Clear history for new execution\n\n // Start with the initial instruction\n await this.initializeHistory(instruction);\n\n let totalInputTokens = 0;\n let totalOutputTokens = 0;\n let totalReasoningTokens = 0;\n let totalCachedInputTokens = 0;\n let totalInferenceTime = 0;\n\n try {\n // Execute steps until completion or max steps reached\n while (!completed && currentStep < maxSteps) {\n await this.preStepHook?.();\n\n logger({\n category: \"agent\",\n message: `Executing step ${currentStep + 1}/${maxSteps}`,\n level: 1,\n });\n\n const result = await this.executeStep(logger);\n totalInputTokens += result.usage.input_tokens;\n totalOutputTokens += result.usage.output_tokens;\n totalReasoningTokens += result.usage.reasoning_tokens;\n totalCachedInputTokens += result.usage.cached_input_tokens;\n totalInferenceTime += result.usage.inference_time_ms;\n\n // Add actions to the list\n actions.push(...result.actions);\n\n // Update completion status\n completed = result.completed;\n\n // Record any message for this step\n if (result.message) {\n messageList.push(result.message);\n finalMessage = result.message;\n }\n\n // Increment step counter\n currentStep++;\n }\n\n // Return the final result\n return {\n success: completed,\n actions,\n message: finalMessage,\n completed,\n usage: {\n input_tokens: totalInputTokens,\n output_tokens: totalOutputTokens,\n reasoning_tokens: totalReasoningTokens,\n cached_input_tokens: totalCachedInputTokens,\n inference_time_ms: totalInferenceTime,\n },\n };\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n logger({\n category: \"agent\",\n message: `Error executing agent task: ${errorMessage}`,\n level: 0,\n });\n\n return {\n success: false,\n actions,\n message: `Failed to execute task: ${errorMessage}`,\n completed: false,\n usage: {\n input_tokens: totalInputTokens,\n output_tokens: totalOutputTokens,\n reasoning_tokens: totalReasoningTokens,\n cached_input_tokens: totalCachedInputTokens,\n inference_time_ms: totalInferenceTime,\n },\n };\n }\n }\n\n /**\n * Initialize conversation history with the initial instruction\n */\n private async initializeHistory(instruction: string): Promise<void> {\n const parts: Part[] = [{ text: instruction }];\n\n // Note: The Python implementation doesn't include the initial screenshot\n // Following the same pattern here\n\n const systemPromptContent = this.userProvidedInstructions\n ? this.userProvidedInstructions\n : buildGoogleCUASystemPrompt().content;\n\n this.history = [\n {\n role: \"user\",\n parts: [\n {\n text: \"System prompt: \" + systemPromptContent,\n },\n ],\n },\n {\n role: \"user\",\n parts,\n },\n ];\n }\n\n /**\n * Execute a single step of the agent\n */\n async executeStep(logger: (message: LogLine) => void): Promise<{\n actions: AgentAction[];\n message: string;\n completed: boolean;\n usage: {\n input_tokens: number;\n output_tokens: number;\n reasoning_tokens: number;\n cached_input_tokens: number;\n inference_time_ms: number;\n };\n }> {\n try {\n const startTime = Date.now();\n\n // Compress images in conversation history before sending to the model\n const compressedResult = compressGoogleConversationImages(\n this.history,\n 2,\n );\n const compressedHistory = compressedResult.items;\n\n // Use the SDK's generateContent method with retry logic (matching Python's get_model_response)\n const maxRetries = 5;\n const baseDelayS = 1;\n let lastError: Error | null = null;\n let response: GenerateContentResponse | null = null;\n\n // Log LLM request\n const llmRequestId = uuidv7();\n FlowLogger.logLlmRequest({\n requestId: llmRequestId,\n model: this.modelName,\n prompt: extractLlmCuaPromptSummary(compressedHistory),\n });\n\n for (let attempt = 0; attempt < maxRetries; attempt++) {\n try {\n // Add exponential backoff delay for retries\n if (attempt > 0) {\n const delay = baseDelayS * Math.pow(2, attempt) * 1000; // Convert to ms\n logger({\n category: \"agent\",\n message: `Generating content failed on attempt ${attempt + 1}. Retrying in ${delay / 1000} seconds...`,\n level: 2,\n });\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n\n // Use the SDK's generateContent method - following Python SDK pattern\n response = await this.client.models.generateContent({\n model: this.modelName,\n contents: compressedHistory,\n config: this.generateContentConfig,\n });\n\n // Check if we have valid response content\n if (!response.candidates || response.candidates.length === 0) {\n throw new LLMResponseError(\"agent\", \"Response has no candidates!\");\n }\n\n const candidate = response.candidates[0];\n if (!candidate.content || !candidate.content.parts) {\n const reason = candidate.finishReason || \"unknown\";\n throw new LLMResponseError(\n \"agent\",\n `Response has no content (finish reason: ${reason})`,\n );\n }\n\n // Success - we have a valid response\n break;\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n logger({\n category: \"agent\",\n message: `API call error: ${lastError.message}`,\n level: 2,\n });\n\n // If this was the last attempt, throw the error\n if (attempt === maxRetries - 1) {\n logger({\n category: \"agent\",\n message: `Generating content failed after ${maxRetries} attempts.`,\n level: 0,\n });\n throw lastError;\n }\n }\n }\n\n if (!response) {\n throw (\n lastError || new Error(\"Failed to get response after all retries\")\n );\n }\n\n const endTime = Date.now();\n const elapsedMs = endTime - startTime;\n const { usageMetadata } = response;\n\n // Log LLM response\n FlowLogger.logLlmResponse({\n requestId: llmRequestId,\n model: this.modelName,\n output: extractLlmCuaResponseSummary(response),\n inputTokens: usageMetadata?.promptTokenCount,\n outputTokens: usageMetadata?.candidatesTokenCount,\n });\n\n // Process the response\n const result = await this.processResponse(response, logger);\n\n // Add model response to history\n if (response.candidates && response.candidates[0]) {\n // Sanitize any out-of-range coordinates in function calls before adding to history\n const sanitizedContent = JSON.parse(\n JSON.stringify(response.candidates[0].content),\n );\n if (sanitizedContent.parts) {\n for (const part of sanitizedContent.parts) {\n if (part.functionCall?.args) {\n if (\n typeof part.functionCall.args.x === \"number\" &&\n part.functionCall.args.x > 999\n ) {\n part.functionCall.args.x = 999;\n }\n if (\n typeof part.functionCall.args.y === \"number\" &&\n part.functionCall.args.y > 999\n ) {\n part.functionCall.args.y = 999;\n }\n }\n }\n }\n this.history.push(sanitizedContent);\n }\n\n // Execute actions and collect function responses\n const functionResponses: Part[] = [];\n\n // Always process the model's response, even when it produced no\n // executable action (e.g. a standalone take_screenshot). The model\n // expects exactly one function response — a fresh screenshot — per\n // computer-use call; skipping it when there are 0 actions leaves the\n // model blind and it gives up after one empty turn.\n {\n let hasError = false;\n\n // Execute all actions (a no-op when there are none).\n for (let i = 0; i < result.actions.length; i++) {\n const action = result.actions[i];\n\n logger({\n category: \"agent\",\n message: `Executing action ${i + 1}/${result.actions.length}: ${action.type}`,\n level: 2,\n });\n\n // Special handling for open_web_browser - don't execute it\n if (action.type === \"open_web_browser\") {\n // Set pageUrl for open_web_browser since it doesn't go through action handler\n action.pageUrl = this.currentUrl;\n logger({\n category: \"agent\",\n message: \"Skipping open_web_browser action\",\n level: 2,\n });\n } else if (action.type === \"screenshot\") {\n // No interaction to perform — the screenshot captured below is\n // returned to the model as this call's function response.\n logger({\n category: \"agent\",\n message: \"take_screenshot: capturing current page\",\n level: 2,\n });\n } else if (action.type === \"custom_tool\") {\n const toolName = action.name as string;\n const toolArgs = action.arguments as Record<string, unknown>;\n\n if (this.tools && toolName in this.tools) {\n const correspondingFunctionCall = result.functionCalls.find(\n (fc) => fc.name === toolName,\n );\n\n if (correspondingFunctionCall) {\n const executionResult = await executeGoogleCustomTool(\n toolName,\n toolArgs,\n this.tools,\n correspondingFunctionCall,\n logger,\n );\n\n functionResponses.push(executionResult.functionResponse);\n\n if (!executionResult.success) {\n hasError = true;\n }\n }\n }\n } else if (this.actionHandler) {\n try {\n await this.actionHandler(action);\n\n // Add a delay between actions to ensure they complete properly\n // Longer delay for typing actions to ensure fields are ready\n if (i < result.actions.length - 1) {\n const nextAction = result.actions[i + 1];\n const isTypingAction =\n action.type === \"type\" || nextAction.type === \"type\";\n const delay = isTypingAction ? 500 : 200;\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n } catch (actionError) {\n if (actionError instanceof StagehandClosedError) {\n throw actionError;\n }\n logger({\n category: \"agent\",\n message: `Error executing action ${action.type}: ${actionError}`,\n level: 0,\n });\n hasError = true;\n // Continue processing other actions even if one fails\n }\n }\n }\n\n // Create function responses for computer use actions (non-custom tools)\n // We need exactly one response per function call, regardless of how many actions were generated\n if (result.functionCalls.length > 0 || hasError) {\n // Filter out custom tool function calls as they've already been handled\n const computerUseFunctionCalls = result.functionCalls.filter(\n (fc) => !isCustomTool(fc, this.tools),\n );\n\n if (computerUseFunctionCalls.length > 0) {\n try {\n logger({\n category: \"agent\",\n message: `Taking screenshot after executing ${result.actions.length} actions${hasError ? \" (with errors)\" : \"\"}`,\n level: 2,\n });\n\n const screenshot = await this.captureScreenshot();\n const base64Data = screenshot.base64;\n\n // Create one function response for each computer use function call\n // Following Python SDK pattern: FunctionResponse with parts containing inline_data\n for (const functionCall of computerUseFunctionCalls) {\n let safetyAcknowledgement: string | undefined;\n if (functionCall.args?.safety_decision) {\n safetyAcknowledgement = await this.handleSafetyConfirmation(\n functionCall.args.safety_decision,\n logger,\n );\n }\n\n const functionResponsePart: Part = {\n functionResponse: {\n name: functionCall.name,\n response: {\n url: this.currentUrl || \"\",\n ...(safetyAcknowledgement !== undefined\n ? {\n safety_acknowledgement: safetyAcknowledgement,\n }\n : {}),\n },\n parts: [\n {\n inlineData: {\n mimeType: screenshot.mediaType,\n data: base64Data,\n },\n },\n ],\n },\n };\n functionResponses.push(functionResponsePart);\n }\n } catch (error) {\n logger({\n category: \"agent\",\n message: `Error capturing screenshot: ${error}`,\n level: 0,\n });\n }\n }\n }\n\n // Add all function responses to history in a single user message\n if (functionResponses.length > 0) {\n logger({\n category: \"agent\",\n message: `Adding ${functionResponses.length} function responses to history`,\n level: 2,\n });\n this.history.push({\n role: \"user\",\n parts: functionResponses,\n });\n }\n }\n\n return {\n actions: result.actions,\n message: result.message,\n completed: result.completed,\n usage: {\n // promptTokenCount is the TOTAL input and already includes the\n // cached portion; cachedContentTokenCount is the cache-hit subset\n // (tracked separately for visibility, not additive). thoughtsTokenCount\n // is Gemini's thinking/reasoning output.\n input_tokens: usageMetadata?.promptTokenCount || 0,\n output_tokens: usageMetadata?.candidatesTokenCount || 0,\n reasoning_tokens: usageMetadata?.thoughtsTokenCount || 0,\n cached_input_tokens: usageMetadata?.cachedContentTokenCount || 0,\n inference_time_ms: elapsedMs,\n },\n };\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : String(error);\n logger({\n category: \"agent\",\n message: `Error executing step: ${errorMessage}`,\n level: 0,\n });\n\n throw error;\n }\n }\n\n /**\n * Process the response from Google's API\n */\n private async processResponse(\n response: GenerateContentResponse,\n logger: (message: LogLine) => void,\n ): Promise<{\n actions: AgentAction[];\n message: string;\n completed: boolean;\n functionCalls: FunctionCall[];\n }> {\n const actions: AgentAction[] = [];\n let message = \"\";\n const functionCalls: FunctionCall[] = [];\n\n if (!response.candidates || response.candidates.length === 0) {\n return {\n actions: [],\n message: \"No candidates in response\",\n completed: true,\n functionCalls: [],\n };\n }\n const candidate = response.candidates[0];\n\n // Log the raw response for debugging\n logger({\n category: \"agent\",\n message: `Raw response from Google: ${JSON.stringify(candidate.content, null, 2)}`,\n level: 2,\n });\n\n // Process all parts - Google can send multiple function calls\n for (const part of candidate.content.parts) {\n if (part.text) {\n message += part.text + \"\\n\";\n logger({\n category: \"agent\",\n message: `Reasoning: ${part.text}`,\n level: 1,\n });\n }\n if (part.functionCall) {\n functionCalls.push(part.functionCall);\n logger({\n category: \"agent\",\n message: `Found function call: ${part.functionCall.name} with args: ${JSON.stringify(part.functionCall.args)}`,\n level: 2,\n });\n\n // Convert function call to action(s)\n const action = this.convertFunctionCallToAction(\n part.functionCall,\n logger,\n );\n if (action) {\n // Special handling for type actions. gemini-2.5 type_text_at carries\n // coordinates (click the field first); gemini-3.x `type` has none and\n // types into the element the model already focused.\n if (action.type === \"type\") {\n logger({\n category: \"agent\",\n message: `Adding action: ${JSON.stringify(action)}`,\n level: 2,\n });\n // Click the target first only when coordinates are provided.\n if (typeof action.x === \"number\" && typeof action.y === \"number\") {\n actions.push({\n type: \"click\",\n x: action.x,\n y: action.y,\n button: \"left\",\n });\n }\n\n // If clear_before_typing is true (default), add a select all\n if (action.clearBeforeTyping) {\n // Select all text in the field\n actions.push({\n type: \"keypress\",\n keys: [\"ControlOrMeta+A\"],\n });\n actions.push({\n type: \"keypress\",\n keys: [\"Backspace\"],\n });\n }\n\n // Then add the type action\n actions.push(action);\n if (action.pressEnter) {\n actions.push({\n type: \"keypress\",\n keys: [\"Enter\"],\n });\n }\n } else {\n actions.push(action);\n }\n } else {\n logger({\n category: \"agent\",\n message: `Warning: Could not convert function call ${part.functionCall.name} to action`,\n level: 1,\n });\n }\n }\n }\n\n // Log summary of what we found\n logger({\n category: \"agent\",\n message: `Found ${functionCalls.length} function calls, converted to ${actions.length} actions`,\n level: 2,\n });\n\n // Check if task is completed\n const completed =\n functionCalls.length === 0 ||\n (candidate.finishReason && candidate.finishReason !== \"STOP\");\n\n return {\n actions,\n message: message.trim(),\n completed,\n functionCalls,\n };\n }\n\n /**\n * Convert Google function call to Stagehand action\n */\n private convertFunctionCallToAction(\n functionCall: FunctionCall,\n logger?: (message: LogLine) => void,\n ): AgentAction | null {\n const { name: rawName } = functionCall;\n // Default args to an empty object so no-argument predefined functions\n // (e.g. take_screenshot, go_back) are not rejected by the guard below.\n const args = functionCall.args ?? {};\n\n if (!rawName) {\n return null;\n }\n\n // The gemini-3.x computer-use tool renamed several of the predefined\n // functions that gemini-2.5-computer-use-preview used, and adds a\n // descriptive `intent` arg to every call. The argument fields are otherwise\n // unchanged (confirmed for click/navigate). Normalize the 3.x names to the\n // canonical 2.5 names so a single set of handlers serves both generations;\n // `intent` is ignored since handlers only read the args they need.\n // NOTE: click and take_screenshot are confirmed from live gemini-3.5-flash\n // traffic; the rest are inferred from the same drop-the-qualifier pattern\n // and are safe aliases (any unmapped name still hits the warning below).\n // gemini-3.x renamed several predefined functions vs gemini-2.5. Alias the\n // 3.x names whose behavior maps cleanly onto a 2.5 canonical handler. Click\n // variants that carry distinct semantics (double/triple/right/middle click,\n // move) are NOT aliased here — they have dedicated cases below so the click\n // count and button are preserved. 2.5 never emits any of these names, so\n // the 2.5 handlers are unaffected.\n const NAME_ALIASES: Record<string, string> = {\n click: \"click_at\",\n left_click: \"click_at\",\n type: \"type_text_at\",\n type_text: \"type_text_at\",\n hover: \"hover_at\",\n scroll: \"scroll_at\",\n drag: \"drag_and_drop\",\n key: \"key_combination\",\n keys: \"key_combination\",\n key_press: \"key_combination\",\n press_key: \"key_combination\",\n press_keys: \"key_combination\",\n hotkey: \"key_combination\",\n screenshot: \"take_screenshot\",\n wait: \"wait_5_seconds\",\n };\n const name = NAME_ALIASES[rawName] ?? rawName;\n\n // Predefined computer-use tools take precedence over custom tools. If a\n // custom tool was registered under a reserved (aliased) name, note that the\n // predefined tool wins rather than silently dropping the custom one.\n if (rawName in NAME_ALIASES && isCustomTool(functionCall, this.tools)) {\n logger?.({\n category: \"agent\",\n message: `Custom tool \"${rawName}\" collides with a predefined Google CUA function; using the predefined tool. Rename the custom tool to avoid the conflict.`,\n level: 2,\n });\n }\n\n switch (name) {\n case \"open_web_browser\":\n return {\n type: \"open_web_browser\",\n timestamp: Date.now(),\n };\n\n case \"take_screenshot\":\n // No UI interaction. The step loop captures a fresh screenshot and\n // returns it to the model as this call's function response; marked as a\n // recognized action (not null) so it isn't dropped, and skipped in the\n // executor like open_web_browser.\n return {\n type: \"screenshot\",\n timestamp: Date.now(),\n };\n\n case \"click_at\": {\n // x/y are required; reject a malformed call rather than normalizing\n // undefined/NaN/Infinity into bad coordinates. (gemini-3.x `click`\n // aliases here.)\n if (\n !GoogleCUAClient.isFiniteCoord(args.x) ||\n !GoogleCUAClient.isFiniteCoord(args.y)\n ) {\n return null;\n }\n const { x, y } = this.normalizeCoordinates(args.x, args.y);\n return {\n type: \"click\",\n x,\n y,\n button: args.button || \"left\",\n };\n }\n\n // gemini-3.x click family. The executor natively supports double/triple\n // click and right/middle button, so preserve those semantics rather than\n // collapsing to a single left click. All require integer coordinates;\n // drop the call (return null) on a malformed payload so the executor is\n // never handed NaN.\n case \"double_click\":\n case \"triple_click\":\n case \"right_click\":\n case \"middle_click\":\n case \"move\": {\n if (\n !GoogleCUAClient.isFiniteCoord(args.x) ||\n !GoogleCUAClient.isFiniteCoord(args.y)\n ) {\n return null;\n }\n const { x, y } = this.normalizeCoordinates(args.x, args.y);\n if (name === \"move\") {\n return { type: \"move\", x, y };\n }\n if (name === \"double_click\" || name === \"triple_click\") {\n return { type: name, x, y };\n }\n return {\n type: \"click\",\n x,\n y,\n button: name === \"right_click\" ? \"right\" : \"middle\",\n };\n }\n\n case \"type_text_at\": {\n // text is required; reject a malformed call rather than typing\n // \"undefined\". An empty string is valid (e.g. clear the field).\n if (typeof args.text !== \"string\") {\n return null;\n }\n // press_enter and clear_before_typing are shared across generations.\n const pressEnter = (args.press_enter as boolean) ?? false;\n const clearBeforeTyping = (args.clear_before_typing as boolean) ?? true;\n const base = {\n type: \"type\" as const,\n text: args.text as string,\n pressEnter,\n clearBeforeTyping,\n };\n\n // gemini-2.5 type_text_at carries x/y (click the field, then type).\n // gemini-3.x `type` has no coordinates and types into the element the\n // model already focused with a preceding click. Only attach coords when\n // present so the executor doesn't click at NaN.\n if (typeof args.x === \"number\" && typeof args.y === \"number\") {\n const { x, y } = this.normalizeCoordinates(args.x, args.y);\n return { ...base, x, y };\n }\n return base;\n }\n\n case \"key_combination\": {\n // gemini-2.5 key_combination sends `keys` as a \"+\"-joined string;\n // gemini-3.x `hotkey` sends a `keys` array, and `press_key` sends a\n // single `key`. Accept all three.\n const raw = args.keys !== undefined ? args.keys : args.key;\n const parts = Array.isArray(raw)\n ? (raw as string[])\n : String(raw ?? \"\").split(\"+\");\n const keys = parts\n .map((key) => String(key).trim())\n .filter(Boolean)\n .map((key) => mapKeyToPlaywright(key));\n if (keys.length === 0) {\n return null;\n }\n return {\n type: \"keypress\",\n keys,\n };\n }\n\n case \"scroll_document\": {\n const direction = (args.direction as string).toLowerCase();\n return {\n type: \"keypress\",\n keys: [direction === \"up\" ? \"PageUp\" : \"PageDown\"],\n };\n }\n\n case \"scroll_at\": {\n // A coordinate-less (or malformed) `scroll` alias (gemini-3.x) scrolls\n // the document via PageUp/PageDown.\n if (\n !GoogleCUAClient.isFiniteCoord(args.x) ||\n !GoogleCUAClient.isFiniteCoord(args.y)\n ) {\n const dir = ((args.direction as string) || \"down\").toLowerCase();\n return {\n type: \"keypress\",\n keys: [dir === \"up\" ? \"PageUp\" : \"PageDown\"],\n };\n }\n const { x, y } = this.normalizeCoordinates(args.x, args.y);\n const direction = ((args.direction as string) || \"down\").toLowerCase();\n // 2.5 uses `magnitude`; gemini-3.x `scroll` uses `magnitude_in_pixels`.\n const magnitude = GoogleCUAClient.isFiniteCoord(args.magnitude)\n ? args.magnitude\n : GoogleCUAClient.isFiniteCoord(args.magnitude_in_pixels)\n ? args.magnitude_in_pixels\n : 800;\n\n let scroll_x = 0;\n let scroll_y = 0;\n if (direction === \"up\") {\n scroll_y = -magnitude;\n } else if (direction === \"down\") {\n scroll_y = magnitude;\n } else if (direction === \"left\") {\n scroll_x = -magnitude;\n } else if (direction === \"right\") {\n scroll_x = magnitude;\n } else {\n // Default to down if unknown direction\n scroll_y = magnitude;\n }\n\n return {\n type: \"scroll\",\n x,\n y,\n scroll_x,\n scroll_y,\n };\n }\n\n case \"navigate\":\n // url is required; reject a malformed call rather than navigating to\n // \"undefined\".\n if (typeof args.url !== \"string\" || args.url.length === 0) {\n return null;\n }\n return {\n type: \"goto\",\n url: args.url,\n };\n\n case \"go_back\":\n return {\n type: \"back\",\n };\n\n case \"go_forward\":\n return {\n type: \"forward\",\n };\n\n case \"wait_5_seconds\":\n return {\n type: \"wait\",\n timeMs: 5000, // Google CUA waits for 5 seconds\n };\n\n case \"hover_at\": {\n const { x, y } = this.normalizeCoordinates(\n args.x as number,\n args.y as number,\n );\n return {\n type: \"move\",\n x,\n y,\n };\n }\n\n case \"search\":\n return {\n type: \"goto\",\n url: \"https://www.google.com\",\n };\n\n case \"drag_and_drop\": {\n // 2.5 uses x/y + destination_x/destination_y; gemini-3.x `drag_and_drop`\n // uses start_x/start_y + end_x/end_y. Accept either.\n const sx = args.x ?? args.start_x;\n const sy = args.y ?? args.start_y;\n const ex = args.destination_x ?? args.end_x;\n const ey = args.destination_y ?? args.end_y;\n if (\n !GoogleCUAClient.isFiniteCoord(sx) ||\n !GoogleCUAClient.isFiniteCoord(sy) ||\n !GoogleCUAClient.isFiniteCoord(ex) ||\n !GoogleCUAClient.isFiniteCoord(ey)\n ) {\n return null;\n }\n const startPoint = this.normalizeCoordinates(sx, sy);\n const endPoint = this.normalizeCoordinates(ex, ey);\n return {\n type: \"drag\",\n path: [\n { x: startPoint.x, y: startPoint.y },\n { x: endPoint.x, y: endPoint.y },\n ],\n };\n }\n\n default:\n if (isCustomTool(functionCall, this.tools)) {\n return {\n type: \"custom_tool\",\n name,\n arguments: args,\n timestamp: Date.now(),\n pageUrl: this.currentUrl,\n };\n }\n console.warn(`Unsupported Google CUA function: ${name}`);\n return null;\n }\n }\n\n /**\n * True only for a usable coordinate/number: rejects undefined, non-numbers,\n * and the numeric edge cases NaN and Infinity (both `typeof \"number\"`), so\n * malformed function calls are dropped instead of normalizing into NaN.\n */\n private static isFiniteCoord(value: unknown): value is number {\n return typeof value === \"number\" && Number.isFinite(value);\n }\n\n /**\n * Normalize coordinates from Google's 0-1000 range to viewport dimensions\n */\n private normalizeCoordinates(x: number, y: number): { x: number; y: number } {\n const clampedX = Math.min(999, Math.max(0, x));\n const clampedY = Math.min(999, Math.max(0, y));\n return {\n x: Math.floor((clampedX / 1000) * this.currentViewport.width),\n y: Math.floor((clampedY / 1000) * this.currentViewport.height),\n };\n }\n\n async captureScreenshot(options?: {\n base64Image?: string;\n mediaType?: \"image/png\" | \"image/jpeg\";\n currentUrl?: string;\n }): Promise<ScreenshotProviderResult> {\n // Update current URL if provided\n if (options?.currentUrl) {\n this.currentUrl = options.currentUrl;\n }\n\n // Use provided options if available\n if (options?.base64Image) {\n return {\n base64: options.base64Image,\n mediaType: options.mediaType ?? \"image/png\",\n };\n }\n\n // Use the screenshot provider if available\n if (this.screenshotProvider) {\n try {\n return await this.screenshotProvider();\n } catch (error) {\n console.error(\"Error capturing screenshot:\", error);\n throw error;\n }\n }\n\n throw new AgentScreenshotProviderError(\n \"`screenshotProvider` has not been set. \" +\n \"Please call `setScreenshotProvider()` with a valid function that returns a base64-encoded image and media type\",\n );\n }\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { AgentAction, AgentResult, AgentType, AgentExecutionOptions } from "../types/public/agent.js";
1
+ import { AgentAction, AgentResult, AgentType, AgentExecutionOptions, ScreenshotProviderResult } from "../types/public/agent.js";
2
2
  import { ClientOptions } from "../types/public/model.js";
3
3
  import { AgentClient } from "./AgentClient.js";
4
4
  /**
@@ -23,7 +23,7 @@ export declare class MicrosoftCUAClient extends AgentClient {
23
23
  constructor(type: AgentType, modelName: string, userProvidedInstructions?: string, clientOptions?: ClientOptions);
24
24
  setViewport(width: number, height: number): void;
25
25
  setCurrentUrl(url: string): void;
26
- setScreenshotProvider(provider: () => Promise<string>): void;
26
+ setScreenshotProvider(provider: () => Promise<ScreenshotProviderResult>): void;
27
27
  setActionHandler(handler: (action: AgentAction) => Promise<void>): void;
28
28
  /**
29
29
  * Smart resize algorithm from FARA
@@ -414,8 +414,8 @@ For each function call, return a json object with function name and arguments wi
414
414
  if (!this.screenshotProvider) {
415
415
  throw new AgentScreenshotProviderError("Screenshot provider not set");
416
416
  }
417
- const base64Screenshot = await this.screenshotProvider();
418
- return `data:image/png;base64,${base64Screenshot}`;
417
+ const screenshot = await this.screenshotProvider();
418
+ return `data:${screenshot.mediaType};base64,${screenshot.base64}`;
419
419
  }
420
420
  /**
421
421
  * Remove old screenshots from history