@andorra-labs/code 0.1.5 → 0.1.6

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 (164) hide show
  1. package/dist/src/account-presentation.js +3 -3
  2. package/dist/src/agent-execution.d.ts +2 -0
  3. package/dist/src/agent-execution.js +126 -20
  4. package/dist/src/agent-mcp.d.ts +18 -1
  5. package/dist/src/agent-mcp.js +103 -8
  6. package/dist/src/app-server/protocol.d.ts +33 -3
  7. package/dist/src/app-server/protocol.js +14 -1
  8. package/dist/src/app-server/workspace.d.ts +1 -0
  9. package/dist/src/app-server/workspace.js +7 -1
  10. package/dist/src/app-server.d.ts +115 -41
  11. package/dist/src/app-server.js +1229 -219
  12. package/dist/src/automation-runner.d.ts +9 -0
  13. package/dist/src/automation-runner.js +22 -1
  14. package/dist/src/automation-tool.js +8 -1
  15. package/dist/src/automations.js +1 -1
  16. package/dist/src/browser-captcha-tool.d.ts +54 -0
  17. package/dist/src/browser-captcha-tool.js +374 -0
  18. package/dist/src/browser-panel-tool.d.ts +7 -0
  19. package/dist/src/browser-panel-tool.js +74 -3
  20. package/dist/src/browser-runner.js +19 -4
  21. package/dist/src/browser-server.js +21 -1
  22. package/dist/src/browser-session.d.ts +16 -0
  23. package/dist/src/browser-session.js +35 -0
  24. package/dist/src/browser-ui/app.js +193 -3
  25. package/dist/src/browser-ui/style.css +15 -1
  26. package/dist/src/browser-view.d.ts +72 -4
  27. package/dist/src/browser-view.js +229 -17
  28. package/dist/src/capabilities.js +13 -2
  29. package/dist/src/capsolver.d.ts +60 -0
  30. package/dist/src/capsolver.js +101 -0
  31. package/dist/src/claude-provider.d.ts +6 -0
  32. package/dist/src/claude-provider.js +34 -3
  33. package/dist/src/cli-executable.d.ts +33 -0
  34. package/dist/src/cli-executable.js +64 -0
  35. package/dist/src/cli-process.d.ts +47 -0
  36. package/dist/src/cli-process.js +113 -0
  37. package/dist/src/cli-sign-in.d.ts +68 -0
  38. package/dist/src/cli-sign-in.js +224 -0
  39. package/dist/src/cli.js +53 -22
  40. package/dist/src/code-intelligence/CodeIntelligenceManager.d.ts +1 -1
  41. package/dist/src/code-intelligence/CodeIntelligenceManager.js +5 -5
  42. package/dist/src/coding-tools.js +44 -5
  43. package/dist/src/command-output-tap.d.ts +16 -0
  44. package/dist/src/command-output-tap.js +45 -0
  45. package/dist/src/command-screens.js +3 -3
  46. package/dist/src/commands.d.ts +10 -1
  47. package/dist/src/commands.js +7 -7
  48. package/dist/src/completion.d.ts +23 -5
  49. package/dist/src/completion.js +334 -17
  50. package/dist/src/config.d.ts +13 -0
  51. package/dist/src/config.js +28 -2
  52. package/dist/src/deadline.js +6 -0
  53. package/dist/src/extensions.d.ts +1 -0
  54. package/dist/src/extensions.js +16 -3
  55. package/dist/src/graph-provider-portability.js +2 -2
  56. package/dist/src/graph-quota.d.ts +1 -1
  57. package/dist/src/graph-quota.js +1 -1
  58. package/dist/src/graph-runner.js +35 -21
  59. package/dist/src/graph-selection.d.ts +6 -0
  60. package/dist/src/graph-selection.js +10 -0
  61. package/dist/src/graph-server.d.ts +7 -0
  62. package/dist/src/graph-server.js +61 -3
  63. package/dist/src/graph-sync.d.ts +50 -0
  64. package/dist/src/graph-sync.js +383 -12
  65. package/dist/src/graph-ui/app.js +61 -8
  66. package/dist/src/graph-ui/icons.js +1 -0
  67. package/dist/src/graph-ui/index.html +1 -1
  68. package/dist/src/graph-ui/skill-picker.js +242 -0
  69. package/dist/src/graph-ui/style.css +19 -0
  70. package/dist/src/graphs.d.ts +46 -4
  71. package/dist/src/graphs.js +152 -27
  72. package/dist/src/grok-provider.d.ts +50 -0
  73. package/dist/src/grok-provider.js +186 -0
  74. package/dist/src/handoffs.d.ts +13 -0
  75. package/dist/src/handoffs.js +31 -1
  76. package/dist/src/managed-sign-in.d.ts +38 -0
  77. package/dist/src/managed-sign-in.js +169 -0
  78. package/dist/src/markdown.d.ts +5 -0
  79. package/dist/src/markdown.js +5 -2
  80. package/dist/src/mcp.js +11 -0
  81. package/dist/src/membership.d.ts +8 -1
  82. package/dist/src/membership.js +15 -5
  83. package/dist/src/model-metadata.js +14 -2
  84. package/dist/src/model-override.d.ts +10 -0
  85. package/dist/src/model-override.js +20 -0
  86. package/dist/src/opencode-cli-provider.d.ts +122 -0
  87. package/dist/src/opencode-cli-provider.js +415 -0
  88. package/dist/src/opencode-provider.js +23 -8
  89. package/dist/src/palette.d.ts +2 -0
  90. package/dist/src/palette.js +2 -0
  91. package/dist/src/permissions.d.ts +19 -1
  92. package/dist/src/permissions.js +30 -1
  93. package/dist/src/powershell-pool.d.ts +2 -2
  94. package/dist/src/powershell-pool.js +18 -5
  95. package/dist/src/provider-connection.js +36 -0
  96. package/dist/src/provider-engine.d.ts +2 -1
  97. package/dist/src/provider-engine.js +64 -13
  98. package/dist/src/provider-import.js +6 -1
  99. package/dist/src/provider-settings.js +22 -3
  100. package/dist/src/providers.d.ts +12 -1
  101. package/dist/src/providers.js +27 -8
  102. package/dist/src/pull-requests.d.ts +111 -17
  103. package/dist/src/pull-requests.js +308 -76
  104. package/dist/src/qa/qa-authorize.js +9 -1
  105. package/dist/src/react-runtime.js +76 -5
  106. package/dist/src/remote/engine-pool.js +1 -1
  107. package/dist/src/run-progress.js +6 -1
  108. package/dist/src/run-records.d.ts +133 -27
  109. package/dist/src/run-records.js +320 -40
  110. package/dist/src/runtime.d.ts +38 -1
  111. package/dist/src/runtime.js +27 -4
  112. package/dist/src/save-lock.d.ts +11 -0
  113. package/dist/src/save-lock.js +29 -2
  114. package/dist/src/sessions.js +4 -1
  115. package/dist/src/shell.js +4 -1
  116. package/dist/src/side-panel.d.ts +1 -1
  117. package/dist/src/side-panel.js +1 -1
  118. package/dist/src/skill-commands.d.ts +2 -0
  119. package/dist/src/skill-commands.js +2 -0
  120. package/dist/src/skills/bundled/create-agent/SKILL.md +81 -0
  121. package/dist/src/skills/bundled/create-skill/SKILL.md +81 -0
  122. package/dist/src/skills/bundled/doctor/SKILL.md +43 -0
  123. package/dist/src/skills/bundled/graph-manager/SKILL.md +97 -0
  124. package/dist/src/skills/bundled/graph-manager/errors.md +38 -0
  125. package/dist/src/skills/bundled/graph-manager/patterns.md +78 -0
  126. package/dist/src/skills/bundled/manage-mcp/SKILL.md +75 -0
  127. package/dist/src/skills/bundled/manage-mcp/probe.md +165 -0
  128. package/dist/src/skills/bundled/manage-skills/SKILL.md +67 -0
  129. package/dist/src/skills/bundled/provenance.json +50 -0
  130. package/dist/src/skills/bundled/write-instructions/SKILL.md +42 -0
  131. package/dist/src/skills/invocable-skills.d.ts +41 -0
  132. package/dist/src/skills/invocable-skills.js +49 -0
  133. package/dist/src/skills/prompt-skills.d.ts +1 -0
  134. package/dist/src/skills/prompt-skills.js +33 -0
  135. package/dist/src/skills/runtime-skills.d.ts +4 -0
  136. package/dist/src/skills/runtime-skills.js +21 -0
  137. package/dist/src/structured-step.d.ts +55 -0
  138. package/dist/src/structured-step.js +85 -0
  139. package/dist/src/subagent-run.d.ts +1 -1
  140. package/dist/src/subagent-run.js +29 -33
  141. package/dist/src/telemetry/schema.d.ts +2 -2
  142. package/dist/src/telemetry/schema.js +3 -2
  143. package/dist/src/terminal-ui.d.ts +29 -0
  144. package/dist/src/terminal-ui.js +112 -28
  145. package/dist/src/timers.d.ts +21 -2
  146. package/dist/src/timers.js +12 -4
  147. package/dist/src/tool-names.d.ts +18 -0
  148. package/dist/src/tool-names.js +26 -0
  149. package/dist/src/tools.js +45 -11
  150. package/dist/src/trajectory.js +32 -12
  151. package/dist/src/types.d.ts +23 -0
  152. package/docs/agents/mcp-server.md +13 -1
  153. package/docs/agents/subagent-mode.md +7 -4
  154. package/docs/concepts/security.md +2 -0
  155. package/docs/getting-started/configure-providers.md +29 -2
  156. package/docs/guides/browser.md +12 -0
  157. package/docs/guides/desktop-app.md +10 -3
  158. package/docs/guides/graph-builder.md +8 -0
  159. package/docs/reference/config.md +2 -2
  160. package/docs/superpowers/plans/2026-11-06-graph-soft-delete.md +125 -0
  161. package/docs/superpowers/specs/2026-11-01-pr-section-design.md +7 -0
  162. package/docs/superpowers/specs/2026-11-06-bundled-skills-design.md +206 -0
  163. package/package.json +1 -1
  164. package/tests/permissions-test-plan.md +2 -1
@@ -3,5 +3,14 @@ export interface AutomationExecutionResult {
3
3
  sessionId?: string;
4
4
  runId?: string;
5
5
  }
6
+ /**
7
+ * The awareness an automation run carries. An unattended run has nobody to ask, so the context travels
8
+ * with the task on its own `run.start` channel: the agent learns which automation started it, whether
9
+ * another agent rather than the user created it, and that it should stop the automation when it turns
10
+ * out to be an accident or is no longer wanted instead of serving it forever. The stop is an update to
11
+ * `enabled: false` because a running occurrence cannot delete its own automation: the scheduler's claim
12
+ * refuses deletion until the run ends.
13
+ */
14
+ export declare function automationRunContext(job: Automation): string;
6
15
  /** Each trigger owns a new engine and never passes a sessionId to run.start. */
7
16
  export declare function executeAutomation(job: Automation, signal: AbortSignal, directory?: string): Promise<AutomationExecutionResult>;
@@ -4,6 +4,27 @@ import { createInterface } from 'node:readline';
4
4
  import { resolve } from 'node:path';
5
5
  import { configDirectory } from './config.js';
6
6
  import { stopAutomationWorker } from './automation-worker-shutdown.js';
7
+ /**
8
+ * The awareness an automation run carries. An unattended run has nobody to ask, so the context travels
9
+ * with the task on its own `run.start` channel: the agent learns which automation started it, whether
10
+ * another agent rather than the user created it, and that it should stop the automation when it turns
11
+ * out to be an accident or is no longer wanted instead of serving it forever. The stop is an update to
12
+ * `enabled: false` because a running occurrence cannot delete its own automation: the scheduler's claim
13
+ * refuses deletion until the run ends.
14
+ */
15
+ export function automationRunContext(job) {
16
+ const schedule = job.schedule.kind === 'cron'
17
+ ? `cron ${job.schedule.expression} in ${job.schedule.timeZone}`
18
+ : `daily at ${job.schedule.time} in ${job.schedule.timeZone}`;
19
+ const origin = job.source === 'agent'
20
+ ? 'It was created by a previous agent run, not by the user, so it may be an accident: treat it as unconfirmed.'
21
+ : 'The user created it.';
22
+ return [
23
+ '---',
24
+ `Automation context: this run was started by the scheduled automation "${job.name}" (id ${job.id}, schedule ${schedule}). ${origin}`,
25
+ `Before serving the task, evaluate the automation itself: if it is accidental, invented without an actual user request, obsolete, or its stop condition is met, stop it with the automations tool (action "update", id ${job.id}, enabled false) and report why you stopped it. A running occurrence cannot delete its own automation, because the scheduler's claim refuses deletion until the run ends, so disabling is the stop this run can perform; the user can delete it afterwards. If it is still wanted, continue with the task above. If this run cannot approve that change, say so in your report instead.`,
26
+ ].join('\n');
27
+ }
7
28
  /** Each trigger owns a new engine and never passes a sessionId to run.start. */
8
29
  export async function executeAutomation(job, signal, directory = configDirectory()) {
9
30
  signal.throwIfAborted();
@@ -59,7 +80,7 @@ export async function executeAutomation(job, signal, directory = configDirectory
59
80
  return;
60
81
  }
61
82
  send('run.start', {
62
- workspace: job.project, task: job.prompt,
83
+ workspace: job.project, task: job.prompt, automationContext: automationRunContext(job),
63
84
  ...(job.execution?.provider ? { provider: job.execution.provider } : {}),
64
85
  ...(job.execution?.model ? { model: job.execution.model } : {}),
65
86
  ...(job.execution?.graph ? { graph: job.execution.graph } : {}),
@@ -1,6 +1,6 @@
1
1
  import { AutomationStore } from './automations.js';
2
2
  import { approveOperation } from './capabilities.js';
3
- import { permissionMode } from './permissions.js';
3
+ import { permissionMode, assertPlanMutationAllowed } from './permissions.js';
4
4
  export function createAutomationTool() {
5
5
  return {
6
6
  name: 'automations', capability: 'external', executionMode: 'sequential',
@@ -24,15 +24,20 @@ export function createAutomationTool() {
24
24
  throw new Error('Choose list, create, update, delete or run');
25
25
  await approveOperation(context, 'automations', { ...args, warning: 'This changes durable future work or starts an unattended session.' });
26
26
  context.signal.throwIfAborted();
27
+ // A permission switch can settle an earlier approval; never dispatch a mutation
28
+ // using that stale grant, even if a different operation awaits afterwards.
29
+ assertPlanMutationAllowed(context);
27
30
  const id = args.id;
28
31
  if (args.action !== 'create' && (typeof id !== 'string' || !id))
29
32
  throw new Error('id is required');
30
33
  if (args.action === 'delete') {
34
+ assertPlanMutationAllowed(context);
31
35
  await store.delete(id);
32
36
  return JSON.stringify({ ok: true });
33
37
  }
34
38
  if (args.action === 'run') {
35
39
  const { executeAutomation } = await import('./automation-runner.js');
40
+ assertPlanMutationAllowed(context);
36
41
  return JSON.stringify({ automation: await store.runNow(id, (job, signal) => executeAutomation(job, signal, context.automationDirectory), context.signal, permissionMode(context) ?? 'ask-for-approval') });
37
42
  }
38
43
  const { action: _action, id: _id, ...input } = args;
@@ -41,8 +46,10 @@ export function createAutomationTool() {
41
46
  input.execution = { ...context.wakeCarry, permissions: permissionMode(context) ?? 'ask-for-approval' };
42
47
  // Only execution selections have meaning on a new session: omit wake-only input/state scope.
43
48
  input.execution = Object.fromEntries(Object.entries(input.execution).filter(([key]) => ['provider', 'model', 'graph', 'permissions', 'reasoningEffort'].includes(key)));
49
+ assertPlanMutationAllowed(context);
44
50
  return JSON.stringify({ automation: await store.create(input, 'agent') });
45
51
  }
52
+ assertPlanMutationAllowed(context);
46
53
  return JSON.stringify({ automation: await store.update(id, input, permissionMode(context) ?? 'ask-for-approval') });
47
54
  },
48
55
  };
@@ -63,7 +63,7 @@ function execution(value) {
63
63
  }
64
64
  function publicJob(job) { const { claim: _claim, ...result } = job; return result; }
65
65
  function assertPermissionCeiling(job, ceiling) {
66
- const ranks = { 'read-only': 0, 'ask-for-approval': 1, 'approve-for-me': 2, 'full-access': 3 };
66
+ const ranks = { 'read-only': 0, 'plan': 0, 'ask-for-approval': 1, 'approve-for-me': 2, 'full-access': 3 };
67
67
  if (ceiling && ranks[job.execution?.permissions ?? 'read-only'] > ranks[ceiling])
68
68
  throw new Error('A restricted agent cannot run or alter an automation with higher permissions. Ask the user to manage it in Automations.');
69
69
  }
@@ -0,0 +1,54 @@
1
+ import type { Tool, ToolContext } from './types.js';
2
+ import { type CapsolverKey, type CapsolverOptions, type CapsolverTask } from './capsolver.js';
3
+ export declare const SOLVE_CAPTCHA_TOOL = "browser.solve_captcha";
4
+ declare const TYPES: readonly ["auto", "recaptcha_v2", "recaptcha_v3", "turnstile", "image"];
5
+ type CaptchaType = typeof TYPES[number];
6
+ /** Captchas found on a page, read from its markup only. Keys are public values the page publishes. */
7
+ export interface DetectedCaptchas {
8
+ recaptcha: {
9
+ websiteKey: string;
10
+ invisible: boolean;
11
+ enterprise: boolean;
12
+ v3: boolean;
13
+ action?: string;
14
+ s?: string;
15
+ }[];
16
+ turnstile: {
17
+ websiteKey: string;
18
+ action?: string;
19
+ cdata?: string;
20
+ }[];
21
+ }
22
+ /** Runs in the page. Self-contained: Playwright serializes it, so it may not reference module scope. */
23
+ export declare const detectCaptchas: () => DetectedCaptchas;
24
+ export interface InjectionReport {
25
+ fields: number;
26
+ callbacks: number;
27
+ patchedApi: boolean;
28
+ }
29
+ /**
30
+ * Runs in the page: put a solved token where the solved widget would have, then tell the page.
31
+ *
32
+ * Only that widget is touched: its own response field, its own callback, its own loader clients.
33
+ * Other widgets on the page, of either provider, keep their fields, callbacks and API answers.
34
+ *
35
+ * The response fields are what a form submits; the callbacks are what script-driven pages wait for;
36
+ * and the patched `execute`/`getResponse` answer pages that ask the widget for the token later.
37
+ */
38
+ export declare const injectCaptchaToken: (input: {
39
+ kind: "recaptcha" | "turnstile";
40
+ token: string;
41
+ websiteKey: string;
42
+ }) => InjectionReport;
43
+ /** Pick the CapSolver task for what the page shows and what the caller asked for. */
44
+ export declare function chooseCaptchaTask(found: DetectedCaptchas, requested: Exclude<CaptchaType, 'image'>, websiteURL: string, websiteKey?: string, pageAction?: string): {
45
+ type: Exclude<CaptchaType, 'auto' | 'image'>;
46
+ task: CapsolverTask;
47
+ };
48
+ export interface SolveCaptchaDependencies {
49
+ /** The key to use; defaults to the saved configuration, then `CAPSOLVER_API_KEY`. */
50
+ resolveKey?: () => Promise<CapsolverKey | undefined>;
51
+ capsolver?: Omit<CapsolverOptions, 'signal'>;
52
+ }
53
+ export declare function createSolveCaptchaTool(authorize: (name: string, args: Record<string, unknown>, context: ToolContext) => Promise<void>, dependencies?: SolveCaptchaDependencies): Tool;
54
+ export {};
@@ -0,0 +1,374 @@
1
+ import { loadConfig } from './config.js';
2
+ import { borrowBrowserSession } from './browser-session.js';
3
+ import { assertPlanMutationAllowed } from './permissions.js';
4
+ import { CAPSOLVER_ENV, resolveCapsolverKey, solveCapsolverTask } from './capsolver.js';
5
+ export const SOLVE_CAPTCHA_TOOL = 'browser.solve_captcha';
6
+ const TYPES = ['auto', 'recaptcha_v2', 'recaptcha_v3', 'turnstile', 'image'];
7
+ const ARGUMENTS = ['sessionId', 'tabId', 'type', 'websiteKey', 'pageAction', 'imageSelector', 'inputSelector'];
8
+ /** CapSolver documents no size limit for ImageToText; a captcha image is small, so cap what is sent. */
9
+ const IMAGE_BYTES_LIMIT = 1024 * 1024;
10
+ /** Runs in the page. Self-contained: Playwright serializes it, so it may not reference module scope. */
11
+ export const detectCaptchas = () => {
12
+ const recaptcha = [];
13
+ const turnstile = [];
14
+ const validKey = (key) => !!key && /^[\w-]{10,100}$/.test(key);
15
+ const addRecaptcha = (entry) => {
16
+ const existing = recaptcha.find(item => item.websiteKey === entry.websiteKey);
17
+ if (!existing) {
18
+ recaptcha.push(entry);
19
+ return;
20
+ }
21
+ existing.v3 ||= entry.v3;
22
+ existing.enterprise ||= entry.enterprise;
23
+ existing.invisible ||= entry.invisible;
24
+ existing.action ??= entry.action;
25
+ existing.s ??= entry.s;
26
+ };
27
+ const addTurnstile = (entry) => {
28
+ const existing = turnstile.find(item => item.websiteKey === entry.websiteKey);
29
+ if (!existing)
30
+ turnstile.push(entry);
31
+ else {
32
+ existing.action ??= entry.action;
33
+ existing.cdata ??= entry.cdata;
34
+ }
35
+ };
36
+ const attribute = (element, name) => element.getAttribute(name)?.slice(0, 200) || undefined;
37
+ for (const element of Array.from(document.querySelectorAll('[data-sitekey]')).slice(0, 50)) {
38
+ const key = element.getAttribute('data-sitekey');
39
+ if (!validKey(key))
40
+ continue;
41
+ if (element.classList.contains('h-captcha'))
42
+ continue;
43
+ if (element.classList.contains('cf-turnstile') || key.startsWith('0x4'))
44
+ addTurnstile({ websiteKey: key, action: attribute(element, 'data-action'), cdata: attribute(element, 'data-cdata') });
45
+ else
46
+ addRecaptcha({ websiteKey: key, invisible: element.getAttribute('data-size') === 'invisible', enterprise: false, v3: false, action: attribute(element, 'data-action'), s: attribute(element, 'data-s') });
47
+ }
48
+ for (const frame of Array.from(document.querySelectorAll('iframe[src]')).slice(0, 50)) {
49
+ let url;
50
+ try {
51
+ url = new URL(frame.getAttribute('src'), location.href);
52
+ }
53
+ catch {
54
+ continue;
55
+ }
56
+ if (/\/recaptcha\/(api2|enterprise)\/anchor/.test(url.pathname)) {
57
+ const key = url.searchParams.get('k');
58
+ if (validKey(key))
59
+ addRecaptcha({ websiteKey: key, invisible: url.searchParams.get('size') === 'invisible', enterprise: url.pathname.includes('/enterprise/'), v3: false, action: url.searchParams.get('sa')?.slice(0, 200) || undefined });
60
+ }
61
+ else if (url.hostname === 'challenges.cloudflare.com') {
62
+ const key = url.pathname.match(/0x4[\w-]{10,90}/)?.[0];
63
+ if (validKey(key))
64
+ addTurnstile({ websiteKey: key });
65
+ }
66
+ }
67
+ // A score-based (v3) key is the one the loader script renders with, not "explicit".
68
+ for (const script of Array.from(document.querySelectorAll('script[src]')).slice(0, 200)) {
69
+ let url;
70
+ try {
71
+ url = new URL(script.getAttribute('src'), location.href);
72
+ }
73
+ catch {
74
+ continue;
75
+ }
76
+ if (!/\/recaptcha\/(api|enterprise)\.js$/.test(url.pathname))
77
+ continue;
78
+ const key = url.searchParams.get('render');
79
+ if (key !== 'explicit' && validKey(key))
80
+ addRecaptcha({ websiteKey: key, invisible: true, enterprise: url.pathname.endsWith('/enterprise.js'), v3: true });
81
+ }
82
+ return { recaptcha: recaptcha.slice(0, 10), turnstile: turnstile.slice(0, 10) };
83
+ };
84
+ /**
85
+ * Runs in the page: put a solved token where the solved widget would have, then tell the page.
86
+ *
87
+ * Only that widget is touched: its own response field, its own callback, its own loader clients.
88
+ * Other widgets on the page, of either provider, keep their fields, callbacks and API answers.
89
+ *
90
+ * The response fields are what a form submits; the callbacks are what script-driven pages wait for;
91
+ * and the patched `execute`/`getResponse` answer pages that ask the widget for the token later.
92
+ */
93
+ export const injectCaptchaToken = (input) => {
94
+ const { kind, token, websiteKey } = input;
95
+ const report = { fields: 0, callbacks: 0, patchedApi: false };
96
+ const w = window;
97
+ const setField = (field) => {
98
+ field.value = token;
99
+ if (field.tagName === 'TEXTAREA')
100
+ field.innerHTML = token;
101
+ field.dispatchEvent(new Event('input', { bubbles: true }));
102
+ field.dispatchEvent(new Event('change', { bubbles: true }));
103
+ report.fields++;
104
+ };
105
+ const called = new Set();
106
+ const invoke = (callback) => {
107
+ const fn = typeof callback === 'string' ? callback.split('.').reduce((owner, part) => owner == null ? undefined : owner[part], w) : callback;
108
+ if (typeof fn !== 'function' || called.has(fn))
109
+ return;
110
+ called.add(fn);
111
+ try {
112
+ fn(token);
113
+ report.callbacks++;
114
+ }
115
+ catch { /* The page's own handler failed; the fields are still set. */ }
116
+ };
117
+ // Every captcha widget on the page, as the element that roots it and the key it names.
118
+ const frameKey = (element) => {
119
+ let url;
120
+ try {
121
+ url = new URL(element.getAttribute('src') ?? '', location.href);
122
+ }
123
+ catch {
124
+ return undefined;
125
+ }
126
+ if (/\/recaptcha\/(api2|enterprise)\/anchor/.test(url.pathname))
127
+ return { kind: 'recaptcha', key: url.searchParams.get('k') ?? undefined };
128
+ if (url.hostname === 'challenges.cloudflare.com')
129
+ return { kind: 'turnstile', key: url.pathname.match(/0x4[\w-]{10,90}/)?.[0] };
130
+ return undefined;
131
+ };
132
+ const widgets = Array.from(document.querySelectorAll('[data-sitekey], iframe[src]')).flatMap(element => {
133
+ if (element.matches('[data-sitekey]')) {
134
+ if (element.classList.contains('h-captcha'))
135
+ return [];
136
+ const key = element.getAttribute('data-sitekey') ?? '';
137
+ return [{ element, key, kind: element.classList.contains('cf-turnstile') || key.startsWith('0x4') ? 'turnstile' : 'recaptcha' }];
138
+ }
139
+ // A frame inside a keyed container is that container's widget, not a second one.
140
+ const frame = frameKey(element);
141
+ return frame && !element.parentElement?.closest('[data-sitekey]') ? [{ element, key: frame.key ?? '', kind: frame.kind }] : [];
142
+ });
143
+ const target = widgets.find(widget => widget.kind === kind && widget.key === websiteKey);
144
+ const others = widgets.filter(widget => widget !== target);
145
+ const sameKind = widgets.filter(widget => widget.kind === kind);
146
+ const fieldSelector = kind === 'recaptcha' ? 'textarea[name="g-recaptcha-response"], textarea[id^="g-recaptcha-response"]' : 'input[name="cf-turnstile-response"]';
147
+ const ownedByOther = (field) => others.some(widget => widget.element.contains(field));
148
+ // The widget's response field sits in its container, beside the frame. Walk up from the widget
149
+ // until a field turns up, but never into an ancestor that holds another widget.
150
+ let fields = [];
151
+ for (let scope = target?.element ?? null; scope && scope !== document.body && !fields.length; scope = scope.parentElement) {
152
+ if (others.some(widget => scope.contains(widget.element)))
153
+ break;
154
+ fields = Array.from(scope.querySelectorAll(fieldSelector));
155
+ }
156
+ // A key the page shows no widget for (reCAPTCHA v3, or a key passed explicitly) may still have a
157
+ // page-level field, as long as no other widget owns it.
158
+ if (!target)
159
+ fields = Array.from(document.querySelectorAll(fieldSelector)).filter(field => !ownedByOther(field));
160
+ if (!fields.length && target && target.element.matches('[data-sitekey]')) {
161
+ const field = document.createElement(kind === 'recaptcha' ? 'textarea' : 'input');
162
+ field.name = kind === 'recaptcha' ? 'g-recaptcha-response' : 'cf-turnstile-response';
163
+ if (field instanceof HTMLInputElement)
164
+ field.type = 'hidden';
165
+ else
166
+ field.style.display = 'none';
167
+ target.element.appendChild(field);
168
+ fields.push(field);
169
+ }
170
+ fields.forEach(setField);
171
+ if (target?.element.matches('[data-callback]'))
172
+ invoke(target.element.getAttribute('data-callback'));
173
+ // Calls that name no widget mean the page's only (or first) one.
174
+ const onlyWidget = sameKind.length <= 1 && (!target || sameKind[0] === target);
175
+ if (kind === 'recaptcha') {
176
+ // Widgets rendered from script keep their callback in the loader's client table, keyed by widget id.
177
+ const clients = w.___grecaptcha_cfg?.clients;
178
+ const ours = new Set();
179
+ const walk = (value, depth, seen, onEntry) => {
180
+ if (!value || typeof value !== 'object' || depth > 5 || seen.has(value) || value instanceof Node)
181
+ return;
182
+ seen.add(value);
183
+ for (const key of Object.keys(value).slice(0, 100)) {
184
+ let entry;
185
+ try {
186
+ entry = value[key];
187
+ }
188
+ catch {
189
+ continue;
190
+ }
191
+ if (!onEntry(key, entry))
192
+ walk(entry, depth + 1, seen, onEntry);
193
+ }
194
+ };
195
+ if (clients && typeof clients === 'object') {
196
+ for (const [id, client] of Object.entries(clients)) {
197
+ let names = false;
198
+ walk(client, 0, new Set(), (_key, entry) => { if (entry === websiteKey)
199
+ names = true; return names; });
200
+ if (!names)
201
+ continue;
202
+ ours.add(id);
203
+ walk(client, 0, new Set(), (key, entry) => {
204
+ if (key !== 'callback' || (typeof entry !== 'function' && typeof entry !== 'string'))
205
+ return false;
206
+ invoke(entry);
207
+ return true;
208
+ });
209
+ }
210
+ }
211
+ const mine = (widget) => widget === websiteKey || (widget === undefined ? (ours.size ? ours.has('0') : onlyWidget) : ours.has(String(widget)));
212
+ for (const api of [w.grecaptcha, w.grecaptcha?.enterprise]) {
213
+ if (!api || typeof api !== 'object')
214
+ continue;
215
+ const execute = api.execute, getResponse = api.getResponse;
216
+ try {
217
+ api.execute = function (widget, ...rest) { return mine(widget) ? Promise.resolve(token) : execute?.call(this, widget, ...rest); };
218
+ api.getResponse = function (widget, ...rest) { return mine(widget) ? token : getResponse?.call(this, widget, ...rest); };
219
+ report.patchedApi = true;
220
+ }
221
+ catch { /* frozen API object */ }
222
+ }
223
+ }
224
+ else {
225
+ // Turnstile's widget ids cannot be tied to a key from outside, so its API answers for the
226
+ // solved widget only when it is the page's only one.
227
+ const api = w.turnstile;
228
+ if (onlyWidget && api && typeof api === 'object') {
229
+ try {
230
+ api.getResponse = () => token;
231
+ api.isExpired = () => false;
232
+ report.patchedApi = true;
233
+ }
234
+ catch { /* frozen API object */ }
235
+ }
236
+ }
237
+ return report;
238
+ };
239
+ function text(args, name, max) {
240
+ const value = args[name];
241
+ if (typeof value !== 'string' || !value || value.length > max)
242
+ throw new Error(`${name} must be a nonempty string of at most ${max} characters`);
243
+ return value;
244
+ }
245
+ /** Pick the CapSolver task for what the page shows and what the caller asked for. */
246
+ export function chooseCaptchaTask(found, requested, websiteURL, websiteKey, pageAction) {
247
+ const v2 = found.recaptcha.filter(item => !item.v3);
248
+ const v3 = found.recaptcha.filter(item => item.v3);
249
+ const type = requested !== 'auto' ? requested
250
+ : websiteKey ? (found.turnstile.some(item => item.websiteKey === websiteKey) ? 'turnstile' : v3.some(item => item.websiteKey === websiteKey) ? 'recaptcha_v3' : 'recaptcha_v2')
251
+ : found.turnstile.length ? 'turnstile' : v2.length ? 'recaptcha_v2' : v3.length ? 'recaptcha_v3' : undefined;
252
+ if (!type)
253
+ throw new Error("No reCAPTCHA or Turnstile widget was found on this page. Wait for the widget to load and retry, pass websiteKey and type if you know them, or use type 'image' with imageSelector and inputSelector for an image captcha.");
254
+ if (type === 'turnstile') {
255
+ const widget = websiteKey ? found.turnstile.find(item => item.websiteKey === websiteKey) : found.turnstile[0];
256
+ const key = websiteKey ?? widget?.websiteKey;
257
+ if (!key)
258
+ throw new Error('No Turnstile widget was found on this page; pass websiteKey if you know it.');
259
+ const metadata = { ...(widget?.action ? { action: widget.action } : {}), ...(widget?.cdata ? { cdata: widget.cdata } : {}) };
260
+ return { type, task: { type: 'AntiTurnstileTaskProxyLess', websiteURL, websiteKey: key, ...(Object.keys(metadata).length ? { metadata } : {}) } };
261
+ }
262
+ const pool = type === 'recaptcha_v3' ? v3 : v2;
263
+ const widget = websiteKey ? found.recaptcha.find(item => item.websiteKey === websiteKey) : pool[0];
264
+ const key = websiteKey ?? widget?.websiteKey;
265
+ if (!key)
266
+ throw new Error(`No ${type === 'recaptcha_v3' ? 'reCAPTCHA v3' : 'reCAPTCHA v2'} widget was found on this page; pass websiteKey if you know it.`);
267
+ const action = pageAction ?? widget?.action;
268
+ if (type === 'recaptcha_v3') {
269
+ return { type, task: { type: widget?.enterprise ? 'ReCaptchaV3EnterpriseTaskProxyLess' : 'ReCaptchaV3TaskProxyLess', websiteURL, websiteKey: key, ...(action ? { pageAction: action } : {}) } };
270
+ }
271
+ return { type, task: {
272
+ type: widget?.enterprise ? 'ReCaptchaV2EnterpriseTaskProxyLess' : 'ReCaptchaV2TaskProxyLess', websiteURL, websiteKey: key,
273
+ ...(widget?.invisible ? { isInvisible: true } : {}), ...(action ? { pageAction: action } : {}),
274
+ ...(widget?.s ? (widget.enterprise ? { enterprisePayload: { s: widget.s } } : { recaptchaDataSValue: widget.s }) : {}),
275
+ } };
276
+ }
277
+ async function configuredKey() {
278
+ // An unreadable configuration still leaves the environment's key usable.
279
+ return resolveCapsolverKey(await loadConfig().catch(() => undefined));
280
+ }
281
+ export function createSolveCaptchaTool(authorize, dependencies = {}) {
282
+ return {
283
+ name: SOLVE_CAPTCHA_TOOL, family: 'browser', capability: 'browser', executionMode: 'sequential',
284
+ description: `Solve a captcha on a page open in a qa.browser_session through the user's CapSolver account, and put the answer into the page. Supports reCAPTCHA v2 (checkbox and invisible), reCAPTCHA v3, Cloudflare Turnstile, and image-to-text captchas. With type auto (default) the widget and its site key are detected from the page; the token is written to the page's response field and the widget's callback is called. For an image captcha pass type image, imageSelector (the captcha image) and inputSelector (the answer box). Afterwards submit the form or continue with qa.browser_session and take a snapshot to confirm the page accepted it; tokens expire after about two minutes. Each solve spends CapSolver credit, and needs a CapSolver API key in Settings → Browser or ${CAPSOLVER_ENV}.`,
285
+ parameters: { type: 'object', properties: {
286
+ sessionId: { type: 'string', description: 'Open qa.browser_session sessionId' },
287
+ tabId: { type: 'string', description: 'Observed tab id; the selected tab by default' },
288
+ type: { type: 'string', enum: [...TYPES], description: 'Captcha kind; auto detects reCAPTCHA or Turnstile from the page' },
289
+ websiteKey: { type: 'string', description: 'Site key, when detection cannot find it (data-sitekey, or k= in the reCAPTCHA frame URL)' },
290
+ pageAction: { type: 'string', description: 'reCAPTCHA action, e.g. the action passed to grecaptcha.execute for v3' },
291
+ imageSelector: { type: 'string', description: 'Observed CSS selector of the captcha image (type image)' },
292
+ inputSelector: { type: 'string', description: 'Observed CSS selector of the answer input (type image)' },
293
+ }, required: ['sessionId'], additionalProperties: false },
294
+ // The recognized text is page content; events keep only what happened.
295
+ eventOutput: output => {
296
+ try {
297
+ const data = JSON.parse(output);
298
+ return JSON.stringify({ sessionId: data.sessionId, type: data.type, solved: data.solved });
299
+ }
300
+ catch {
301
+ return 'Captcha result (content omitted)';
302
+ }
303
+ },
304
+ execute: async (args, context) => {
305
+ if (Object.keys(args).some(key => !ARGUMENTS.includes(key)))
306
+ throw new Error(`Invalid argument; ${SOLVE_CAPTCHA_TOOL} accepts ${ARGUMENTS.join(', ')}`);
307
+ const type = (args.type ?? 'auto');
308
+ if (!TYPES.includes(type))
309
+ throw new Error(`type must be one of ${TYPES.join(', ')}`);
310
+ const image = type === 'image';
311
+ const imageSelector = image ? text(args, 'imageSelector', 1024) : undefined;
312
+ const inputSelector = image ? text(args, 'inputSelector', 1024) : undefined;
313
+ if (!image && (args.imageSelector !== undefined || args.inputSelector !== undefined))
314
+ throw new Error("imageSelector and inputSelector apply only to type 'image'");
315
+ if (image && (args.websiteKey !== undefined || args.pageAction !== undefined))
316
+ throw new Error("websiteKey and pageAction do not apply to type 'image'");
317
+ const websiteKey = args.websiteKey === undefined ? undefined : text(args, 'websiteKey', 100);
318
+ if (websiteKey !== undefined && !/^[\w-]{10,100}$/.test(websiteKey))
319
+ throw new Error('websiteKey must be the 10 to 100 character site key (letters, digits, _ and -)');
320
+ const pageAction = args.pageAction === undefined ? undefined : text(args, 'pageAction', 100);
321
+ if (type === 'turnstile' && pageAction !== undefined)
322
+ throw new Error('pageAction applies only to reCAPTCHA');
323
+ // Plan mode refuses before anything is spent or changed; a per-tool approval is not a plan approval.
324
+ assertPlanMutationAllowed(context);
325
+ const borrowed = borrowBrowserSession(args, context);
326
+ const key = await (dependencies.resolveKey ?? configuredKey)();
327
+ if (!key)
328
+ throw new Error(`CapSolver is not configured. Add an API key in Settings → Browser, or set ${CAPSOLVER_ENV}, then retry.`);
329
+ await authorize(SOLVE_CAPTCHA_TOOL, args, context);
330
+ context.signal.throwIfAborted();
331
+ assertPlanMutationAllowed(context);
332
+ const options = { ...dependencies.capsolver, signal: context.signal };
333
+ // The page is held for the whole solve, so nothing navigates it between reading the widget
334
+ // and writing its answer.
335
+ return await borrowed.use(async (page, tabId, bounded) => {
336
+ // The session queue may have waited across a live switch into Plan mode.
337
+ assertPlanMutationAllowed(context);
338
+ const websiteURL = page.url();
339
+ if (!/^https?:/.test(websiteURL))
340
+ throw new Error('Open an HTTP(S) page before solving its captcha');
341
+ if (image) {
342
+ const data = await bounded(page.locator(imageSelector).screenshot({ type: 'png', timeout: 10_000 }), 'Captcha image capture exceeded the 10-second timeout; session closed.');
343
+ if (data.length > IMAGE_BYTES_LIMIT)
344
+ throw new Error('The captcha image is larger than 1 MiB; select the image element itself');
345
+ const solution = await solveCapsolverTask(key.key, { type: 'ImageToTextTask', body: data.toString('base64'), websiteURL }, options);
346
+ const answer = typeof solution.text === 'string' ? solution.text : '';
347
+ if (!answer)
348
+ throw new Error('CapSolver returned no text for the image');
349
+ // A run paused or cancelled during the solve must not type into the page afterwards, and a
350
+ // fill waiting for its input must stop with the run rather than at Playwright's timeout.
351
+ context.signal.throwIfAborted();
352
+ assertPlanMutationAllowed(context);
353
+ await bounded(page.locator(inputSelector).fill(answer, { timeout: 10_000 }), 'Captcha answer entry exceeded the 10-second timeout; session closed.');
354
+ return JSON.stringify({ sessionId: borrowed.sessionId, tabId, type, solved: true, text: answer.slice(0, 200), filled: inputSelector });
355
+ }
356
+ const found = await bounded(page.evaluate(detectCaptchas), 'Captcha detection exceeded the 10-second timeout; session closed.');
357
+ const chosen = chooseCaptchaTask(found, type, websiteURL, websiteKey, pageAction);
358
+ const solution = await solveCapsolverTask(key.key, chosen.task, options);
359
+ const token = chosen.type === 'turnstile' ? solution.token : solution.gRecaptchaResponse;
360
+ if (typeof token !== 'string' || !token)
361
+ throw new Error('CapSolver returned no token');
362
+ context.signal.throwIfAborted();
363
+ // A solve takes seconds to minutes; a run switched to Plan mode meanwhile must not write the answer.
364
+ assertPlanMutationAllowed(context);
365
+ const injected = await bounded(page.evaluate(injectCaptchaToken, { kind: chosen.type === 'turnstile' ? 'turnstile' : 'recaptcha', token, websiteKey: chosen.task.websiteKey }), 'Captcha token injection exceeded the 10-second timeout; session closed.');
366
+ return JSON.stringify({
367
+ sessionId: borrowed.sessionId, tabId, type: chosen.type, websiteKey: chosen.task.websiteKey, solved: true,
368
+ fieldsFilled: injected.fields, callbacksInvoked: injected.callbacks, apiPatched: injected.patchedApi,
369
+ ...(injected.fields || injected.callbacks || injected.patchedApi ? {} : { warning: 'The token was solved but the page had no response field, callback or widget API to receive it.' }),
370
+ });
371
+ });
372
+ },
373
+ };
374
+ }
@@ -37,3 +37,10 @@ export type PanelBrowserRelay = (operation: string, args: Record<string, unknown
37
37
  * never appears there.
38
38
  */
39
39
  export declare function createBrowserPanelTool(views: BrowserViewManager, sessionId: string, relay?: PanelBrowserRelay): Tool;
40
+ /**
41
+ * The agent's switch between the project profile and a throwaway incognito
42
+ * browser in the session's Browser panel. A tool of its own rather than another
43
+ * `browser.panel` operation, so the agent sees plainly that a signed-out, fresh
44
+ * browser is available to it. It shares the panel tool's local and relayed paths.
45
+ */
46
+ export declare function createBrowserIncognitoTool(views: BrowserViewManager, sessionId: string, relay?: PanelBrowserRelay): Tool;