@andorra-labs/code 0.1.5 → 0.1.7

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 (224) 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 +526 -41
  4. package/dist/src/agent-mcp-catalog.d.ts +21 -0
  5. package/dist/src/agent-mcp-catalog.js +40 -0
  6. package/dist/src/agent-mcp.d.ts +36 -3
  7. package/dist/src/agent-mcp.js +114 -45
  8. package/dist/src/app-server/protocol.d.ts +57 -5
  9. package/dist/src/app-server/protocol.js +18 -1
  10. package/dist/src/app-server/workspace.d.ts +9 -1
  11. package/dist/src/app-server/workspace.js +50 -3
  12. package/dist/src/app-server.d.ts +115 -41
  13. package/dist/src/app-server.js +1316 -221
  14. package/dist/src/auth/AuthManager.d.ts +33 -1
  15. package/dist/src/auth/AuthManager.js +138 -10
  16. package/dist/src/auth/callback-page.d.ts +4 -0
  17. package/dist/src/auth/callback-page.js +70 -0
  18. package/dist/src/auth/callback.d.ts +39 -0
  19. package/dist/src/auth/callback.js +146 -22
  20. package/dist/src/auth/index.d.ts +10 -6
  21. package/dist/src/auth/index.js +2 -2
  22. package/dist/src/auth/store.d.ts +142 -3
  23. package/dist/src/auth/store.js +334 -13
  24. package/dist/src/auth/types.d.ts +17 -1
  25. package/dist/src/auth-commands.d.ts +11 -2
  26. package/dist/src/auth-commands.js +14 -7
  27. package/dist/src/automation-runner.d.ts +9 -0
  28. package/dist/src/automation-runner.js +22 -1
  29. package/dist/src/automation-tool.js +18 -3
  30. package/dist/src/automations.d.ts +5 -0
  31. package/dist/src/automations.js +11 -1
  32. package/dist/src/browser-captcha-tool.d.ts +54 -0
  33. package/dist/src/browser-captcha-tool.js +374 -0
  34. package/dist/src/browser-panel-tool.d.ts +7 -0
  35. package/dist/src/browser-panel-tool.js +74 -3
  36. package/dist/src/browser-runner.js +19 -4
  37. package/dist/src/browser-server.js +21 -1
  38. package/dist/src/browser-session.d.ts +16 -0
  39. package/dist/src/browser-session.js +35 -0
  40. package/dist/src/browser-ui/app.js +193 -3
  41. package/dist/src/browser-ui/style.css +15 -1
  42. package/dist/src/browser-view.d.ts +72 -4
  43. package/dist/src/browser-view.js +229 -17
  44. package/dist/src/capabilities.d.ts +9 -3
  45. package/dist/src/capabilities.js +20 -5
  46. package/dist/src/capsolver.d.ts +60 -0
  47. package/dist/src/capsolver.js +101 -0
  48. package/dist/src/claude-provider.d.ts +6 -0
  49. package/dist/src/claude-provider.js +34 -3
  50. package/dist/src/cli-executable.d.ts +33 -0
  51. package/dist/src/cli-executable.js +64 -0
  52. package/dist/src/cli-process.d.ts +47 -0
  53. package/dist/src/cli-process.js +113 -0
  54. package/dist/src/cli-sign-in.d.ts +68 -0
  55. package/dist/src/cli-sign-in.js +224 -0
  56. package/dist/src/cli.js +84 -26
  57. package/dist/src/code-intelligence/CodeIntelligenceManager.d.ts +1 -1
  58. package/dist/src/code-intelligence/CodeIntelligenceManager.js +5 -5
  59. package/dist/src/codex-provider.js +12 -0
  60. package/dist/src/coding-tools.d.ts +5 -0
  61. package/dist/src/coding-tools.js +98 -53
  62. package/dist/src/command-output-tap.d.ts +16 -0
  63. package/dist/src/command-output-tap.js +45 -0
  64. package/dist/src/command-screens.js +3 -3
  65. package/dist/src/commands.d.ts +15 -2
  66. package/dist/src/commands.js +14 -13
  67. package/dist/src/completion.d.ts +23 -5
  68. package/dist/src/completion.js +380 -17
  69. package/dist/src/config.d.ts +61 -0
  70. package/dist/src/config.js +276 -12
  71. package/dist/src/context-budget.d.ts +7 -0
  72. package/dist/src/context-budget.js +18 -1
  73. package/dist/src/deadline.js +6 -0
  74. package/dist/src/decision/FactContinuations.d.ts +41 -6
  75. package/dist/src/decision/FactContinuations.js +211 -64
  76. package/dist/src/decision/PreparedSteps.js +3 -1
  77. package/dist/src/decision/checks.d.ts +25 -0
  78. package/dist/src/decision/checks.js +77 -6
  79. package/dist/src/delegation-changes.d.ts +109 -0
  80. package/dist/src/delegation-changes.js +431 -0
  81. package/dist/src/extensions.d.ts +1 -0
  82. package/dist/src/extensions.js +16 -3
  83. package/dist/src/graph-provider-portability.js +2 -2
  84. package/dist/src/graph-quota.d.ts +1 -1
  85. package/dist/src/graph-quota.js +1 -1
  86. package/dist/src/graph-runner.js +35 -21
  87. package/dist/src/graph-selection.d.ts +6 -0
  88. package/dist/src/graph-selection.js +10 -0
  89. package/dist/src/graph-server.d.ts +8 -0
  90. package/dist/src/graph-server.js +76 -6
  91. package/dist/src/graph-sync.d.ts +65 -0
  92. package/dist/src/graph-sync.js +433 -13
  93. package/dist/src/graph-tool.d.ts +52 -0
  94. package/dist/src/graph-tool.js +136 -0
  95. package/dist/src/graph-ui/app.js +272 -50
  96. package/dist/src/graph-ui/controls.js +6 -0
  97. package/dist/src/graph-ui/drafts.js +39 -0
  98. package/dist/src/graph-ui/embed.js +1 -1
  99. package/dist/src/graph-ui/icons.js +1 -0
  100. package/dist/src/graph-ui/index.html +2 -2
  101. package/dist/src/graph-ui/skill-picker.js +242 -0
  102. package/dist/src/graph-ui/studio.css +7 -5
  103. package/dist/src/graph-ui/style.css +65 -12
  104. package/dist/src/graphs.d.ts +60 -5
  105. package/dist/src/graphs.js +191 -37
  106. package/dist/src/grok-provider.d.ts +50 -0
  107. package/dist/src/grok-provider.js +186 -0
  108. package/dist/src/handoffs.d.ts +13 -0
  109. package/dist/src/handoffs.js +31 -1
  110. package/dist/src/hardened-runtime.d.ts +4 -4
  111. package/dist/src/hardened-runtime.js +109 -9
  112. package/dist/src/managed-sign-in.d.ts +38 -0
  113. package/dist/src/managed-sign-in.js +169 -0
  114. package/dist/src/markdown.d.ts +5 -0
  115. package/dist/src/markdown.js +5 -2
  116. package/dist/src/mcp.js +11 -0
  117. package/dist/src/membership.d.ts +8 -1
  118. package/dist/src/membership.js +15 -5
  119. package/dist/src/model-metadata.js +14 -2
  120. package/dist/src/model-override.d.ts +10 -0
  121. package/dist/src/model-override.js +20 -0
  122. package/dist/src/opencode-cli-provider.d.ts +122 -0
  123. package/dist/src/opencode-cli-provider.js +415 -0
  124. package/dist/src/opencode-provider.js +23 -8
  125. package/dist/src/palette.d.ts +2 -0
  126. package/dist/src/palette.js +2 -0
  127. package/dist/src/permissions.d.ts +19 -1
  128. package/dist/src/permissions.js +30 -1
  129. package/dist/src/powershell-pool.d.ts +11 -2
  130. package/dist/src/powershell-pool.js +34 -5
  131. package/dist/src/provider-connection.js +36 -0
  132. package/dist/src/provider-engine.d.ts +2 -1
  133. package/dist/src/provider-engine.js +64 -13
  134. package/dist/src/provider-import.js +6 -1
  135. package/dist/src/provider-keys.d.ts +48 -0
  136. package/dist/src/provider-keys.js +121 -0
  137. package/dist/src/provider-settings.js +22 -3
  138. package/dist/src/providers.d.ts +12 -1
  139. package/dist/src/providers.js +27 -8
  140. package/dist/src/pull-requests.d.ts +123 -20
  141. package/dist/src/pull-requests.js +334 -84
  142. package/dist/src/qa/qa-authorize.js +9 -1
  143. package/dist/src/qa/runtime/ProcessManager.d.ts +6 -0
  144. package/dist/src/qa/runtime/ProcessManager.js +16 -0
  145. package/dist/src/react-runtime.js +106 -7
  146. package/dist/src/read-image.d.ts +30 -0
  147. package/dist/src/read-image.js +97 -0
  148. package/dist/src/remote/engine-pool.js +1 -1
  149. package/dist/src/run-progress.js +6 -1
  150. package/dist/src/run-records.d.ts +133 -27
  151. package/dist/src/run-records.js +320 -40
  152. package/dist/src/runtime.d.ts +38 -1
  153. package/dist/src/runtime.js +27 -4
  154. package/dist/src/save-lock.d.ts +11 -0
  155. package/dist/src/save-lock.js +29 -2
  156. package/dist/src/secret-redaction.d.ts +13 -0
  157. package/dist/src/secret-redaction.js +71 -0
  158. package/dist/src/session-summary.d.ts +10 -4
  159. package/dist/src/session-summary.js +14 -7
  160. package/dist/src/sessions.js +8 -2
  161. package/dist/src/shell.js +4 -1
  162. package/dist/src/side-panel.d.ts +1 -1
  163. package/dist/src/side-panel.js +1 -1
  164. package/dist/src/skill-commands.d.ts +2 -0
  165. package/dist/src/skill-commands.js +2 -0
  166. package/dist/src/skills/bundled/create-agent/SKILL.md +81 -0
  167. package/dist/src/skills/bundled/create-skill/SKILL.md +81 -0
  168. package/dist/src/skills/bundled/doctor/SKILL.md +43 -0
  169. package/dist/src/skills/bundled/graph-manager/SKILL.md +100 -0
  170. package/dist/src/skills/bundled/graph-manager/errors.md +38 -0
  171. package/dist/src/skills/bundled/graph-manager/patterns.md +78 -0
  172. package/dist/src/skills/bundled/manage-mcp/SKILL.md +75 -0
  173. package/dist/src/skills/bundled/manage-mcp/probe.md +165 -0
  174. package/dist/src/skills/bundled/manage-skills/SKILL.md +67 -0
  175. package/dist/src/skills/bundled/provenance.json +50 -0
  176. package/dist/src/skills/bundled/write-instructions/SKILL.md +42 -0
  177. package/dist/src/skills/invocable-skills.d.ts +41 -0
  178. package/dist/src/skills/invocable-skills.js +49 -0
  179. package/dist/src/skills/prompt-skills.d.ts +1 -0
  180. package/dist/src/skills/prompt-skills.js +33 -0
  181. package/dist/src/skills/runtime-skills.d.ts +4 -0
  182. package/dist/src/skills/runtime-skills.js +21 -0
  183. package/dist/src/structured-step.d.ts +55 -0
  184. package/dist/src/structured-step.js +85 -0
  185. package/dist/src/subagent-run.d.ts +1 -1
  186. package/dist/src/subagent-run.js +29 -33
  187. package/dist/src/telemetry/schema.d.ts +2 -2
  188. package/dist/src/telemetry/schema.js +3 -2
  189. package/dist/src/terminal-ui.d.ts +38 -0
  190. package/dist/src/terminal-ui.js +126 -28
  191. package/dist/src/timers.d.ts +21 -2
  192. package/dist/src/timers.js +12 -4
  193. package/dist/src/tool-dependencies.js +4 -0
  194. package/dist/src/tool-names.d.ts +18 -0
  195. package/dist/src/tool-names.js +26 -0
  196. package/dist/src/tools.d.ts +9 -0
  197. package/dist/src/tools.js +159 -20
  198. package/dist/src/trajectory.js +32 -12
  199. package/dist/src/transcript.js +5 -0
  200. package/dist/src/types.d.ts +36 -0
  201. package/dist/src/web-search.d.ts +59 -0
  202. package/dist/src/web-search.js +216 -0
  203. package/docs/agents/README.md +2 -2
  204. package/docs/agents/mcp-server.md +28 -3
  205. package/docs/agents/subagent-mode.md +7 -4
  206. package/docs/concepts/README.md +1 -1
  207. package/docs/concepts/security.md +4 -2
  208. package/docs/getting-started/accounts.md +15 -4
  209. package/docs/getting-started/configure-providers.md +30 -3
  210. package/docs/guides/README.md +1 -0
  211. package/docs/guides/browser.md +12 -0
  212. package/docs/guides/desktop-app.md +11 -4
  213. package/docs/guides/graph-builder.md +9 -1
  214. package/docs/guides/web-search.md +47 -0
  215. package/docs/reference/cli.md +4 -3
  216. package/docs/reference/config.md +4 -4
  217. package/docs/reference/slash-commands.md +2 -1
  218. package/docs/superpowers/plans/2026-11-06-graph-soft-delete.md +125 -0
  219. package/docs/superpowers/plans/2026-11-09-orchestrator-delegation.md +295 -0
  220. package/docs/superpowers/specs/2026-11-01-pr-section-design.md +7 -0
  221. package/docs/superpowers/specs/2026-11-06-bundled-skills-design.md +206 -0
  222. package/docs/superpowers/specs/2026-11-09-orchestrator-delegation-design.md +291 -0
  223. package/package.json +1 -1
  224. package/tests/permissions-test-plan.md +2 -1
package/dist/src/tools.js CHANGED
@@ -2,13 +2,18 @@ import { open, opendir, realpath, stat, lstat, mkdir, rename, unlink } from 'nod
2
2
  import { constants } from 'node:fs';
3
3
  import { randomUUID } from 'node:crypto';
4
4
  import path from 'node:path';
5
- import { permissionMode, protectedPermissionRoots, assertLocalFilePath, inspectLocalFileResolution as inspectFileResolution, canonicalProtectedRoots as fileProtectedRoots } from './permissions.js';
5
+ import { permissionMode, protectedPermissionRoots, assertLocalFilePath, inspectLocalFileResolution as inspectFileResolution, canonicalProtectedRoots as fileProtectedRoots, PLAN_MODE_MUTATION_ERROR } from './permissions.js';
6
6
  import { createCodingTools } from './coding-tools.js';
7
7
  import { createQaTools } from './qa/index.js';
8
8
  import { createBrowserSessionTool } from './browser-session.js';
9
+ import { createSolveCaptchaTool } from './browser-captcha-tool.js';
10
+ import { createWebSearchTool } from './web-search.js';
9
11
  import { createAutomationTool } from './automation-tool.js';
12
+ import { createGraphTool } from './graph-tool.js';
10
13
  import { andorraCreateWriteTool } from '../vendor/engine/runtime/coding-agent/core/tools/write.js';
11
14
  import { andorraWithFileMutationQueue } from '../vendor/engine/runtime/coding-agent/core/tools/file-mutation-queue.js';
15
+ import { andorraDetectSupportedImageMimeType } from '../vendor/engine/runtime/coding-agent/utils/mime.js';
16
+ import { READ_IMAGE_FILE_LIMIT } from './read-image.js';
12
17
  import { clipText } from './text.js';
13
18
  import { pullRequestSettings } from './pull-requests.js';
14
19
  import { approveOperation } from './capabilities.js';
@@ -33,14 +38,61 @@ function validate(args, keys) {
33
38
  function samePath(left, right) {
34
39
  return process.platform === 'win32' ? path.resolve(left).toLowerCase() === path.resolve(right).toLowerCase() : left === right;
35
40
  }
36
- function within(root, target) {
41
+ export function within(root, target) {
37
42
  const relative = path.relative(root, target);
38
43
  return relative === '' || (!path.isAbsolute(relative) && relative !== '..' && !relative.startsWith(`..${path.sep}`));
39
44
  }
40
- /** Engine-written attachment spools: the user attached this content, so reads are trusted. */
45
+ /** Engine-written attachment spools: the user attached the content, so reads under them are trusted. */
41
46
  function trustedAttachment(context, target) {
42
47
  return (context.attachmentRoots ?? []).some(root => within(root, target));
43
48
  }
49
+ /**
50
+ * Whether a read stays inside the worktree of a delegated subagent awaiting review.
51
+ *
52
+ * Unlike an attachment spool, a worktree is written by a subagent that has a shell, so it can hold
53
+ * a symbolic link or junction to anywhere on the host. It is therefore an additional workspace root
54
+ * rather than a trusted prefix: a path spelled under it counts only when no link lies on the way
55
+ * and its real location is still inside the same worktree. Anything else falls through to the
56
+ * ordinary outside-the-workspace rules, which prompt or refuse.
57
+ */
58
+ async function insideDelegationRoot(context, target) {
59
+ const roots = context.delegationRoots ?? [];
60
+ if (!roots.length)
61
+ return false;
62
+ const lexical = roots.find(root => within(root, target));
63
+ if (lexical && (await inspectFileResolution(lexical, target)).approvalRequired)
64
+ return false;
65
+ for (let ancestor = target;; ancestor = path.dirname(ancestor)) {
66
+ try {
67
+ const resolved = await realpath(ancestor);
68
+ // A spelling outside every root (a short 8.3 name, a differently cased drive) still counts
69
+ // when it resolves into one; a spelling inside a root must resolve into that same root.
70
+ return lexical ? within(lexical, resolved) : ancestor === target && roots.some(root => within(root, resolved));
71
+ }
72
+ catch (error) {
73
+ // A file that does not exist yet is judged by the deepest folder that does.
74
+ if (!lexical || !['ENOENT', 'ENOTDIR'].includes(error.code ?? '') || samePath(ancestor, lexical) || path.dirname(ancestor) === ancestor)
75
+ return false;
76
+ }
77
+ }
78
+ }
79
+ /**
80
+ * The paths among `names` (relative to `base`) where a write needs approval under workspace rules:
81
+ * outside the workspace, or inside it under protected repository/runtime metadata.
82
+ */
83
+ export async function classifyWorkspaceWrites(workspace, base, names) {
84
+ const root = await realpath(workspace);
85
+ const guarded = [...protectedPermissionRoots(root).map(protectedRoot => path.resolve(protectedRoot)), ...await fileProtectedRoots(root)];
86
+ const outside = [], metadata = [];
87
+ for (const name of names) {
88
+ const target = path.resolve(base, name);
89
+ if (!within(root, target))
90
+ outside.push(name);
91
+ else if (guarded.some(protectedRoot => within(protectedRoot, target)))
92
+ metadata.push(name);
93
+ }
94
+ return { outside, protected: metadata };
95
+ }
44
96
  async function safePath(context, name, missing = false, beforeProbe) {
45
97
  context.signal.throwIfAborted();
46
98
  if (permissionMode(context) !== 'full-access')
@@ -49,7 +101,11 @@ async function safePath(context, name, missing = false, beforeProbe) {
49
101
  const target = path.resolve(root, name);
50
102
  // An attachment spool is trusted under its canonical spelling too: realpath may re-spell a
51
103
  // path that legitimately points into the spool (a symlinked home, a differently cased root).
52
- const targetTrusted = trustedAttachment(context, target) || await realpath(target).then(resolved => trustedAttachment(context, resolved)).catch(() => false);
104
+ const attachmentTrusted = trustedAttachment(context, target) || await realpath(target).then(resolved => trustedAttachment(context, resolved)).catch(() => false);
105
+ // A delegated worktree is a second workspace root: the path is accepted there only while its real
106
+ // location stays inside a worktree, which the resolution below checks again.
107
+ const delegationTrusted = !attachmentTrusted && await insideDelegationRoot(context, target);
108
+ const targetTrusted = attachmentTrusted || delegationTrusted;
53
109
  const assertProbeAllowed = () => {
54
110
  if (permissionMode(context) === 'full-access')
55
111
  return;
@@ -71,7 +127,8 @@ async function safePath(context, name, missing = false, beforeProbe) {
71
127
  const resolved = await realpath(ancestor);
72
128
  if (beforeProbe)
73
129
  await beforeProbe();
74
- const trusted = targetTrusted || trustedAttachment(context, resolved);
130
+ const trusted = attachmentTrusted || trustedAttachment(context, resolved)
131
+ || (delegationTrusted && (context.delegationRoots ?? []).some(delegationRoot => within(delegationRoot, resolved)));
75
132
  if (permissionMode(context) !== 'full-access' && !within(root, resolved) && !trusted)
76
133
  throw new Error('Symlink escapes workspace');
77
134
  const canonical = path.join(resolved, path.relative(ancestor, target));
@@ -144,13 +201,60 @@ async function read(context, name) {
144
201
  await handle.close();
145
202
  }
146
203
  }
204
+ /**
205
+ * The bytes of an image file, or undefined when the file's signature is not a supported image.
206
+ * The type comes from the leading bytes, never the name, so a text file called `x.png` still
207
+ * reads as text and a renamed screenshot is still shown as an image.
208
+ */
209
+ async function readImage(context, name) {
210
+ const resolved = await safePath(context, name);
211
+ // Anything that is not a regular file is left to the text reader, which owns that error.
212
+ if (!(await stat(resolved)).isFile())
213
+ return undefined;
214
+ context.signal.throwIfAborted();
215
+ const handle = await open(resolved, constants.O_RDONLY | (process.platform === 'win32' ? 0 : constants.O_NONBLOCK));
216
+ try {
217
+ const info = await handle.stat();
218
+ if (!info.isFile())
219
+ return undefined;
220
+ const head = Buffer.alloc(4100);
221
+ const sniffed = await handle.read(head, 0, head.length, 0);
222
+ const mimeType = andorraDetectSupportedImageMimeType(head.subarray(0, sniffed.bytesRead));
223
+ if (!mimeType)
224
+ return undefined;
225
+ if (info.size > READ_IMAGE_FILE_LIMIT)
226
+ throw new Error(`Image file exceeds the ${READ_IMAGE_FILE_LIMIT / (1024 * 1024)} MiB image read limit`);
227
+ const chunks = [];
228
+ let size = 0;
229
+ while (size <= READ_IMAGE_FILE_LIMIT) {
230
+ context.signal.throwIfAborted();
231
+ // One extra byte rejects growth after fstat; chunks bound cancellation latency.
232
+ const chunk = Buffer.alloc(Math.min(256 * 1024, READ_IMAGE_FILE_LIMIT + 1 - size));
233
+ const result = await handle.read(chunk, 0, chunk.length, size);
234
+ if (!result.bytesRead)
235
+ break;
236
+ size += result.bytesRead;
237
+ chunks.push(chunk.subarray(0, result.bytesRead));
238
+ }
239
+ if (size > READ_IMAGE_FILE_LIMIT)
240
+ throw new Error('Image file grew beyond the image read limit');
241
+ return { mimeType, bytes: Buffer.concat(chunks, size) };
242
+ }
243
+ finally {
244
+ await handle.close();
245
+ }
246
+ }
147
247
  function assertMutationPermission(context) {
148
- if (!context.pinFilePaths && !context.fileMutationApproval?.explicit && permissionMode(context) === 'read-only')
248
+ if (!context.pinFilePaths && !context.fileMutationApproval?.explicit && (permissionMode(context) === 'read-only' || permissionMode(context) === 'plan'))
149
249
  throw new Error('Permission denied: file mutation grant was revoked');
150
250
  }
151
251
  async function mutationPermission(context, name) {
152
252
  if (context.pinFilePaths || context.fileMutationApproval?.explicit)
153
253
  return;
254
+ // Plan mode refuses mutations outright: an approval prompt would ask the user to pre-approve an
255
+ // edit no plan has been shown for, which is exactly what the mode exists to prevent.
256
+ if (permissionMode(context) === 'plan')
257
+ throw new Error(PLAN_MODE_MUTATION_ERROR);
154
258
  if (permissionMode(context) === 'read-only')
155
259
  await authorize('Write', { path: name, warning: 'Read Only requires approval for this file mutation.' }, context);
156
260
  }
@@ -215,20 +319,34 @@ async function atomicWrite(context, name, content, expectedContent) {
215
319
  }
216
320
  export async function authorize(name, args, context) {
217
321
  context.signal.throwIfAborted();
322
+ const fileMutationName = ['write_file', 'edit_file', 'Write', 'Edit', 'write', 'edit'].includes(name);
323
+ // File writes, unsandboxed QA and MCP execution cannot use an ordinary tool approval
324
+ // in place of presenting a plan. Recheck after every await: a pending approval can
325
+ // be settled by a live permission switch into Plan mode.
326
+ // Solving a captcha spends CapSolver credit and writes into a page, so it waits for the plan too.
327
+ const planRestricted = fileMutationName || name.startsWith('qa.') || name === 'browser.solve_captcha' || (name.startsWith('mcp_') && name !== 'mcp_connect');
328
+ const assertPlanAllowed = () => {
329
+ if (planRestricted && permissionMode(context) === 'plan')
330
+ throw new Error(PLAN_MODE_MUTATION_ERROR);
331
+ };
332
+ assertPlanAllowed();
218
333
  if (context.pinFilePaths)
219
334
  return;
220
- const mutation = ['write_file', 'edit_file', 'Write', 'Edit', 'write', 'edit'].includes(name) && !args.resolvedPath;
335
+ const mutation = fileMutationName && !args.resolvedPath;
221
336
  const automatic = () => mutation && ['ask-for-approval', 'approve-for-me'].includes(permissionMode(context) ?? '');
222
337
  const liveMode = () => automatic() ? 'workspace-policy' : permissionMode(context) === 'full-access' ? 'yolo' : context.approvalMode ?? 'interactive';
223
338
  while (true) {
224
339
  context.signal.throwIfAborted();
340
+ assertPlanAllowed();
225
341
  await context.onApprovalEvent?.('node.tool.approval.requested', { name, arguments: args, mode: liveMode() });
226
342
  // Both audit hooks may yield while the user changes live permissions.
343
+ assertPlanAllowed();
227
344
  let mode = liveMode();
228
345
  let answer = false;
229
346
  while (mode === 'interactive') {
230
347
  answer = await context.approve(name, args, context.userSignal ?? context.signal);
231
348
  context.signal.throwIfAborted();
349
+ assertPlanAllowed();
232
350
  if (answer !== 'policy-changed')
233
351
  break;
234
352
  mode = liveMode();
@@ -240,9 +358,11 @@ export async function authorize(name, args, context) {
240
358
  if (!approved)
241
359
  throw new Error('Permission denied');
242
360
  context.signal.throwIfAborted();
361
+ assertPlanAllowed();
243
362
  // Only explicit user approval survives a mode change. Reacquire automatic
244
363
  // grants through the live policy before returning control to the operation.
245
364
  if (!policyGrant || liveMode() === mode) {
365
+ assertPlanAllowed();
246
366
  if (mutation && context.fileMutationApproval)
247
367
  context.fileMutationApproval.explicit = !policyGrant;
248
368
  return;
@@ -367,9 +487,10 @@ function filePermissionTool(tool) {
367
487
  let authorized;
368
488
  if (['write_file', 'edit_file', 'Write', 'Edit', 'write', 'edit'].includes(tool.name)) {
369
489
  context.toolState ??= { fileReads: new Map() };
370
- // The attachment spool carve-out is a READ trust: a mutation lands outside the workspace
371
- // and keeps the scoped approval these modes require, so the roots leave this call alone.
372
- context = { ...context, fileMutationApproval: { explicit: false }, attachmentRoots: undefined };
490
+ // The attachment spool and delegation worktree carve-outs are a READ trust: a mutation lands
491
+ // outside the workspace and keeps the scoped approval these modes require, so the roots
492
+ // leave this call alone.
493
+ context = { ...context, fileMutationApproval: { explicit: false }, attachmentRoots: undefined, delegationRoots: undefined };
373
494
  }
374
495
  const selected = permissionMode(context);
375
496
  if (selected && selected !== 'full-access') {
@@ -381,8 +502,11 @@ function filePermissionTool(tool) {
381
502
  // An attachment spool holds content the user attached to this very turn, written by the
382
503
  // engine: reading it is as trusted as the workspace, and the outside-workspace approval
383
504
  // this classification would demand is one a headless run cannot grant.
505
+ // A delegated worktree awaiting review is read like the workspace, but only where the path
506
+ // really stays inside it: a link out of it is classified below like any outside path.
384
507
  const attachmentTrusted = trustedAttachment(context, target)
385
- || await realpath(target).then(resolved => trustedAttachment(context, resolved)).catch(() => false);
508
+ || await realpath(target).then(resolved => trustedAttachment(context, resolved)).catch(() => false)
509
+ || await insideDelegationRoot(context, target);
386
510
  if (!attachmentTrusted) {
387
511
  const outside = !within(root, target);
388
512
  // Classify lexical metadata descendants before even lstat/readlink: their
@@ -456,12 +580,22 @@ function qaPermissionTool(tool) {
456
580
  return { ...tool, execute: async (args, context) => {
457
581
  const selected = permissionMode(context);
458
582
  const readOnlyTerminal = tool.name === 'qa.terminal' && ['read', 'status', 'wait', 'resize'].includes(String(args.action));
583
+ // Host execution under plan mode is a change no plan has been approved for: an approved QA
584
+ // grant spawns an unsandboxed process whose commands can write the workspace, so the call is
585
+ // refused with the plan guidance rather than prompted. Reading a terminal that already exists
586
+ // changes nothing and stays available.
587
+ const assertPlanAllowed = () => {
588
+ if (!readOnlyTerminal && permissionMode(context) === 'plan')
589
+ throw new Error(PLAN_MODE_MUTATION_ERROR);
590
+ };
591
+ assertPlanAllowed();
459
592
  if (selected && !readOnlyTerminal) {
460
593
  let explicitlyApproved = false;
461
594
  do {
462
595
  await authorize(tool.name, { ...args, warning: 'UNSANDBOXED QA: this tool call can access the entire host filesystem and network.' }, {
463
596
  ...context, approve: async (...approval) => {
464
597
  const allowed = await context.approve(...approval);
598
+ assertPlanAllowed();
465
599
  if (allowed === true)
466
600
  explicitlyApproved = true;
467
601
  return allowed;
@@ -469,16 +603,20 @@ function qaPermissionTool(tool) {
469
603
  });
470
604
  // Decision-event delivery can also yield to a live-mode downgrade.
471
605
  // An automatic Full Access decision never becomes a scoped user grant.
606
+ assertPlanAllowed();
472
607
  } while (!explicitlyApproved && permissionMode(context) !== 'full-access');
473
608
  if (explicitlyApproved)
474
609
  context = { ...context, qaHostApproved: true };
475
610
  }
611
+ // Never dispatch an unsandboxed QA operation on a grant from before Plan was selected.
612
+ assertPlanAllowed();
476
613
  return tool.execute(args, context);
477
614
  } };
478
615
  }
479
616
  export function createTools() {
480
617
  return [
481
618
  createAutomationTool(),
619
+ createGraphTool(),
482
620
  legacyTool('read_file', 'Read a UTF-8 workspace file (8 MiB maximum). Optional 1-based inclusive startLine/endLine select a range; omitted bounds mean first/last line. Range reads return line metadata, up to 20000 content characters and a continuation hint; individual longer lines truncate. Use ranges to inspect tails of truncated files. Path-only reads return original content capped at 32768 characters.', {
483
621
  path: property('Workspace-relative file path'),
484
622
  startLine: { type: 'integer', minimum: 1, description: 'First line, inclusive (default 1)' },
@@ -602,7 +740,7 @@ export function createTools() {
602
740
  return `Updated ${name}`;
603
741
  });
604
742
  }),
605
- tool('set_timer', 'Arm a self-wake timer. After the delay your prompt is delivered back to you as a user message. A session that is idle, or a run this process drives between its turns, takes it at the next turn boundary; a run that is still working when the deadline passes takes it when that run ends, as a new task in this session under the same graph, model, and thinking effort it was armed under. Use it to check on slow background work instead of polling it. Timers are held in the running session only: they fire at most once, they are lost when the process exits, and they are unavailable where no session can deliver a follow-up prompt.', {
743
+ tool('set_timer', 'Arm a self-wake timer. Only call this when the user explicitly asked you to set a timer, a reminder, or to check back after a delay. Never arm one on your own initiative, for example to wait on a test run, a build, or other background work you started: wait on that work with the tool that runs it, or report its state and stop. After the delay your prompt is delivered back to you as a reminder (marked [Timer]) for the work you are doing now. While you are still working it arrives at your next turn boundary. If your run stops before you finish (out of budget, failed, or interrupted), the reminder continues that run from where you left off. It is dropped, never started as a new task, once you have finished your work, the run has finished, the user stopped it, or a newer turn replaced it. In the terminal CLI, a session that is idle takes it as its next prompt. Timers are held in the running session only: they fire at most once, they are lost when the process exits, and they are unavailable where no session can deliver a follow-up prompt.', {
606
744
  prompt: property('The message delivered to you when the timer fires'),
607
745
  seconds: { type: 'integer', minimum: 1, maximum: 86_400, description: 'Delay before delivery, in seconds (1 to 86400)' },
608
746
  }, ['prompt', 'seconds'], async (args, context) => {
@@ -610,18 +748,17 @@ export function createTools() {
610
748
  throw new Error('set_timer is unavailable in this session; no session surface can deliver a follow-up prompt here.');
611
749
  if (typeof args.seconds !== 'number' || !Number.isSafeInteger(args.seconds))
612
750
  throw new Error('seconds must be an integer');
613
- const timer = context.timers.arm(args.seconds, string(args, 'prompt'), context.sessionScope, context.wakeCarry);
751
+ const timer = context.timers.arm(args.seconds, string(args, 'prompt'), context.sessionScope, context.wakeCarry, context.wakeOrigin);
614
752
  // Recorded for the run that made it: a wake is this turn's promise, and a turn that fails to be saved has
615
753
  // only its own to lose.
616
754
  context.wakesArmed?.push(timer.id);
617
755
  return `Timer ${timer.id.slice(0, 8)} armed: your prompt will be delivered in ${args.seconds} second${args.seconds === 1 ? '' : 's'}, at ${new Date(timer.fireAt).toISOString()}. It fires once.`;
618
756
  }),
619
- { ...tool('pull_request', 'Show or change the pull request this session tracks in the desktop Plan card. A PR you open with `gh pr create` is attached automatically; use attach for one opened another way. update changes its settings when the user asks: mergeWhenReady enables GitHub auto-merge (gh pr merge --auto), draft converts to a draft or marks it ready, autoFix wakes you with a prompt when new review comments arrive, autoArchive archives this session once the PR is merged or closed. dismiss removes it from the card. Only change a setting the user asked you to change.', {
757
+ { ...tool('pull_request', 'Show or change the pull request this session tracks in the desktop Plan card. A PR you open with `gh pr create` is attached automatically; use attach for one opened another way. update changes its settings when the user asks: mergeWhenReady enables GitHub auto-merge (gh pr merge --auto), draft converts to a draft or marks it ready, autoFix wakes you with a prompt when a code-review bot (Codex, CodeRabbit, Greptile, Copilot) comments and switches itself off once the PR is merged or closed. dismiss removes it from the card. Only change a setting the user asked you to change.', {
620
758
  action: { type: 'string', enum: ['status', 'attach', 'update', 'dismiss'], description: 'status shows the tracked PR; attach starts tracking url; update changes settings; dismiss stops tracking' },
621
759
  url: property('The GitHub pull request URL (attach only)'),
622
- autoFix: { type: 'boolean', description: 'Wake this session when new review comments arrive' },
760
+ autoFix: { type: 'boolean', description: 'Wake this session when a code-review bot (Codex, CodeRabbit, Greptile, Copilot) comments, until the PR is merged or closed' },
623
761
  mergeWhenReady: { type: 'boolean', description: 'GitHub auto-merge once checks and reviews pass' },
624
- autoArchive: { type: 'boolean', description: 'Archive this session when the PR is merged or closed' },
625
762
  draft: { type: 'boolean', description: 'true converts to a draft, false marks it ready for review' },
626
763
  }, ['action'], async (args, context) => {
627
764
  const control = context.pullRequests;
@@ -629,10 +766,10 @@ export function createTools() {
629
766
  throw new Error('pull_request is unavailable here; no session tracks a pull request for this run.');
630
767
  const settings = pullRequestSettings(args);
631
768
  // A setting is a change on GitHub (auto-merge, draft) or to what the engine will do unattended (Auto-fix
632
- // runs, archiving), so it goes through the run's approval like any other host operation; a full-access
769
+ // runs), so it goes through the run's approval like any other host operation; a full-access
633
770
  // run approves it by policy. Reading the PR and dismissing it change neither.
634
771
  const approve = () => approveOperation(context, 'pull_request', { ...args, warning: 'Changes the pull request on GitHub, or what Andorra does on its own when the PR changes.' });
635
- const describe = (pr) => `${pr.url} (${pr.state})${pr.title ? ` "${pr.title}"` : ''}: autoFix ${pr.autoFix ? 'on' : 'off'}, mergeWhenReady ${pr.mergeWhenReady ? 'on' : 'off'}, autoArchive ${pr.autoArchive ? 'on' : 'off'}`;
772
+ const describe = (pr) => `${pr.url} (${pr.state})${pr.title ? ` "${pr.title}"` : ''}: autoFix ${pr.autoFix ? 'on' : 'off'}, mergeWhenReady ${pr.mergeWhenReady ? 'on' : 'off'}`;
636
773
  switch (args.action) {
637
774
  case 'status': {
638
775
  const pr = await control.status();
@@ -646,7 +783,7 @@ export function createTools() {
646
783
  }
647
784
  case 'update': {
648
785
  if (!Object.keys(settings).length)
649
- throw new Error('update needs at least one of autoFix, mergeWhenReady, autoArchive, draft');
786
+ throw new Error('update needs at least one of autoFix, mergeWhenReady, draft');
650
787
  await approve();
651
788
  return `Updated ${describe(await control.update(settings))}`;
652
789
  }
@@ -656,8 +793,10 @@ export function createTools() {
656
793
  default: throw new Error('action must be status, attach, update, or dismiss');
657
794
  }
658
795
  }), family: 'git', executionMode: 'sequential' },
659
- ...createCodingTools({ safePath, read, atomicWrite, authorize, files, fileLimit: FILE_LIMIT }),
796
+ ...createCodingTools({ safePath, read, readImage, atomicWrite, authorize, files, fileLimit: FILE_LIMIT }),
660
797
  ...createQaTools().map(qaPermissionTool),
661
798
  createBrowserSessionTool(authorize),
799
+ createSolveCaptchaTool(authorize),
800
+ createWebSearchTool(),
662
801
  ].map(filePermissionTool);
663
802
  }
@@ -6,6 +6,29 @@ import { isDeepStrictEqual } from 'node:util';
6
6
  import { redactSecrets } from './memory/redaction.js';
7
7
  import { browserEventArguments, isBrowserToolName } from './browser-session.js';
8
8
  const credentialKey = /(?:api[_-]?key|token|secret|password|passwd|authorization|cookie|credential|private[_-]?key)/i;
9
+ /** `MAX_OUTPUT_TOKENS` and the like hold counts, as the `*Tokens` record keys below do. */
10
+ const tokenCountKey = /tokens$/i;
11
+ /**
12
+ * Values that switch a setting on or off, or mark a credential as absent, rather than hold
13
+ * one: Chromium reads `GOOGLE_API_KEY=no`, local model servers accept `OPENAI_API_KEY=EMPTY`.
14
+ * No source treats them as secrets; redacting them rewrote ordinary words in every record.
15
+ */
16
+ const flagValues = new Set(['y', 'n', 'yes', 'no', 'true', 'false', 'on', 'off', '0', '1',
17
+ 'none', 'null', 'nil', 'undefined', 'unset', 'empty', 'disabled', 'enabled', 'dummy', 'placeholder']);
18
+ /**
19
+ * The shortest environment or configured value treated as a secret. A credential-named value
20
+ * shorter than this is a flag or a placeholder; substituting it can neither hide it (the
21
+ * surrounding text gives a word-length value away) nor avoid matching unrelated text.
22
+ * Browser inputs have no floor: what a model types into a page can be a short PIN.
23
+ */
24
+ const MIN_CONFIGURED_SECRET_LENGTH = 4;
25
+ /** A flag, a placeholder, or text with no letter or digit (a typed space, bare punctuation). */
26
+ function isFlagValue(value) {
27
+ return flagValues.has(value.trim().toLowerCase()) || !/[\p{L}\p{N}]/u.test(value);
28
+ }
29
+ function configuredSecrets(values) {
30
+ return values.filter(value => value.trim().length >= MIN_CONFIGURED_SECRET_LENGTH && !isFlagValue(value));
31
+ }
9
32
  const privateReasoningKey = /^(?:reasoningContent|reasoning_content|reasoning|thinking|signature|thinkingSignature|providerContinuation)$/i;
10
33
  const MAX_STRUCTURE_DEPTH = 64;
11
34
  const STRUCTURE_LIMIT = '[REDACTED: structure exceeds sanitization limit]';
@@ -92,16 +115,18 @@ export async function createSessionTrajectory(options = {}) {
92
115
  const modulePath = await realpath(fileURLToPath(import.meta.url));
93
116
  const directory = options.directory ?? join(resolve(dirname(modulePath), '..', '..'), '.andorracode', 'trajectories');
94
117
  const path = join(directory, `${sessionId}.jsonl`);
95
- let secrets = [...new Set([
96
- ...Object.entries(process.env).filter(([key]) => credentialKey.test(key)).map(([, value]) => value ?? ''),
118
+ let secrets = [...new Set(configuredSecrets([
119
+ ...Object.entries(process.env).filter(([key]) => credentialKey.test(key) && !tokenCountKey.test(key)).map(([, value]) => value ?? ''),
97
120
  ...(options.secrets ?? []),
98
- ].filter(Boolean))].sort((a, b) => b.length - a.length);
121
+ ]))].sort((a, b) => b.length - a.length);
99
122
  // Browser inputs are private even when they are too short for the ambient
100
123
  // credential heuristics. Keep them local to this conversation, never global.
124
+ // A flag-like answer ("no", "0") is still removed from the recorded call by
125
+ // the argument projection; only its echoes in other text are left alone.
101
126
  const browserSecrets = new Set();
102
127
  const browserInputSecrets = new Set();
103
128
  function rememberBrowserSecret(value) {
104
- if (!value || browserInputSecrets.has(value))
129
+ if (!value || isFlagValue(value) || browserInputSecrets.has(value))
105
130
  return;
106
131
  browserInputSecrets.add(value);
107
132
  // A model can quote an input inside prose/code fences, where whole-string
@@ -278,13 +303,8 @@ export async function createSessionTrajectory(options = {}) {
278
303
  return redactBrowserSecrets(serializeSanitizedJson(value, parsed, sanitize(parsed, jsonDepth + 1, structureDepth + 1)));
279
304
  }
280
305
  let text = redactBrowserSecrets(value);
281
- for (const secret of secrets) {
282
- // Short placeholder env values (e.g. "no") must not corrupt identifiers.
283
- if (secret.length < 4)
284
- text = text.replace(new RegExp(`(?<![A-Za-z0-9_])${secret.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(?![A-Za-z0-9_])`, 'g'), '[REDACTED]');
285
- else
286
- text = text.split(secret).join('[REDACTED]');
287
- }
306
+ for (const secret of secrets)
307
+ text = text.split(secret).join('[REDACTED]');
288
308
  return redactSecrets(text).text;
289
309
  }
290
310
  if (value && typeof value === 'object') {
@@ -387,7 +407,7 @@ export async function createSessionTrajectory(options = {}) {
387
407
  return {
388
408
  sessionId, path,
389
409
  sanitize,
390
- addSecrets(values) { secrets = [...new Set([...secrets, ...values.filter(Boolean)])].sort((a, b) => b.length - a.length); },
410
+ addSecrets(values) { secrets = [...new Set([...secrets, ...configuredSecrets(values)])].sort((a, b) => b.length - a.length); },
391
411
  recordEvent: event => record('runtime.event', { event }),
392
412
  record: (type, data) => record(type, data),
393
413
  flush: () => pending,
@@ -201,6 +201,11 @@ export function formatEvent(event) {
201
201
  return { text: `• Started ${line(data.role)} (${line(data.subagentId)})` };
202
202
  if (event.type === 'subagent.completed')
203
203
  return { text: `• ${line(data.role)} ${line(data.status)}` };
204
+ if (event.type === 'subagent.change') {
205
+ const words = data.state === 'pending' ? 'awaiting review' : line(data.state);
206
+ const files = Array.isArray(data.files) ? line(data.files.filter(file => typeof file === 'string').join(', ')) : '';
207
+ return { text: `• Change ${line(data.changeId)} ${words}${files ? `: ${files}` : ''}` };
208
+ }
204
209
  if (event.type === 'codeintel.state') {
205
210
  if (data.state === 'ready' || data.state === 'uninitialized')
206
211
  return undefined;
@@ -48,6 +48,10 @@ export interface Usage {
48
48
  cacheRead?: number;
49
49
  cacheWrite?: number;
50
50
  decodeMs?: number;
51
+ /** Input tokens on local model requests that explicitly reported cache reads (including zero). */
52
+ localCacheInputTokens?: number;
53
+ /** Cache-read tokens for those same local requests, summed across local model switches. */
54
+ localCacheReadTokens?: number;
51
55
  }
52
56
  export interface ToolSchema {
53
57
  name: string;
@@ -160,6 +164,19 @@ export interface ToolContext {
160
164
  * cannot grant. Never model input; never widened beyond the engine's own spools.
161
165
  */
162
166
  attachmentRoots?: readonly string[];
167
+ /**
168
+ * Worktrees of this node's delegated writing subagents that hold a change awaiting review,
169
+ * realpath-resolved.
170
+ *
171
+ * The run made them from its own snapshot of the workspace, so the Orchestrator reads inside them
172
+ * as it reads its workspace, without an "outside the workspace" prompt. They are additional
173
+ * workspace roots, not trusted prefixes: a subagent with a shell wrote them, so a read counts as
174
+ * inside only when its real path stays in the worktree and no symbolic link or junction lies on
175
+ * the way; anything else is classified like any other outside path. Read access only: mutations
176
+ * drop these roots together with `attachmentRoots`. Runtime-owned; never model input, and no
177
+ * subagent's context carries them, delegated or not.
178
+ */
179
+ delegationRoots?: readonly string[];
163
180
  /** Runtime-owned explicit file-mutation grant, scoped to one tool call. */
164
181
  fileMutationApproval?: {
165
182
  explicit: boolean;
@@ -172,9 +189,21 @@ export interface ToolContext {
172
189
  approve: (name: string, args: Record<string, unknown>, signal: AbortSignal) => Promise<boolean | 'policy-changed'>;
173
190
  /** Runtime-owned clarification channel; undefined answers decline the current intake. */
174
191
  askUser?: (question: string, signal: AbortSignal, choices?: readonly string[]) => Promise<string | undefined>;
192
+ /**
193
+ * Runtime-owned plan approval: flips the run out of plan mode once the user approves, without
194
+ * touching the saved workspace default, and answers the mode the run continues in. Absent on
195
+ * surfaces with no live permission control, where presenting a plan cannot proceed.
196
+ */
197
+ approvePlan?: () => Promise<import('./permissions.js').PermissionMode>;
175
198
  onApprovalEvent?: (type: string, data: Record<string, unknown>) => void | Promise<void>;
176
199
  /** Browser lifecycle observations, scoped to the current coding session, never a tool-supplied identity. */
177
200
  onBrowserEvent?: (type: string, data: Record<string, unknown>) => void | Promise<void>;
201
+ /**
202
+ * Live output from a command tool that is still running: the runtime forwards it to the
203
+ * transcript as throttled `node.tool.output` events, so a running call's row shows what the
204
+ * command has printed. Display-only; the call's own observation remains the authoritative record.
205
+ */
206
+ onCommandOutput?: (chunk: string) => void;
178
207
  /**
179
208
  * Called by the file permission wrapper once a mutation's path has been authorized and
180
209
  * canonicalized, immediately before the tool executes.
@@ -194,6 +223,13 @@ export interface ToolContext {
194
223
  * effort or scope. Surfaces with no run of their own leave it unset.
195
224
  */
196
225
  wakeCarry?: import('./timers.js').WakeCarry;
226
+ /**
227
+ * The attempt and graph node a wake armed from this context belongs to, set by the agent node executor.
228
+ *
229
+ * A wake is delivered back to the work of the node that armed it - never as a new task that starts the
230
+ * graph over - so the node is part of the wake. A subagent's context inherits its host node's.
231
+ */
232
+ wakeOrigin?: import('./timers.js').WakeOrigin;
197
233
  /**
198
234
  * Filled in with the id of every wake this run arms, so a run can tell its own wakes from the session's.
199
235
  *
@@ -0,0 +1,59 @@
1
+ import { type Config, type WebSearchProviderId } from './config.js';
2
+ import type { Tool } from './types.js';
3
+ /**
4
+ * The native web_search tool and the search services behind it.
5
+ *
6
+ * Each service is one HTTPS request: the API key goes only in that request's header or body, never
7
+ * in an error message or the tool's output. SearXNG is the one keyless backend; it takes the address
8
+ * of an instance the user runs or trusts, and that instance must have the JSON output format enabled.
9
+ */
10
+ export declare const WEB_SEARCH_TOOL = "web_search";
11
+ export declare const WEB_SEARCH_LABELS: Record<WebSearchProviderId, string>;
12
+ /** Environment fallbacks, used when the configuration holds no value for that field. */
13
+ export declare const WEB_SEARCH_ENV: {
14
+ readonly brave: "BRAVE_API_KEY";
15
+ readonly tavily: "TAVILY_API_KEY";
16
+ readonly exa: "EXA_API_KEY";
17
+ readonly serper: "SERPER_API_KEY";
18
+ readonly google: "GOOGLE_SEARCH_API_KEY";
19
+ readonly googleSearchEngineId: "GOOGLE_SEARCH_ENGINE_ID";
20
+ readonly searxng: "SEARXNG_URL";
21
+ };
22
+ /** A usable backend: its credentials and whether they came from the configuration or the environment. */
23
+ export interface ResolvedWebSearchProvider {
24
+ id: WebSearchProviderId;
25
+ source: 'config' | 'env';
26
+ key?: string;
27
+ engineId?: string;
28
+ url?: string;
29
+ }
30
+ /** The provider's credentials when it has everything it needs, otherwise undefined. */
31
+ export declare function resolveWebSearchProvider(id: WebSearchProviderId, config: Pick<Config, 'webSearch'> | undefined, env?: NodeJS.ProcessEnv): ResolvedWebSearchProvider | undefined;
32
+ /**
33
+ * The backend a search uses: the default provider when one is chosen, otherwise the first configured
34
+ * one. A chosen default that is not configured is an error rather than a silent switch, so the user
35
+ * learns their choice is not in effect.
36
+ */
37
+ export declare function chooseWebSearchProvider(config: Pick<Config, 'webSearch'> | undefined, env?: NodeJS.ProcessEnv): ResolvedWebSearchProvider;
38
+ export interface WebSearchResult {
39
+ title: string;
40
+ url: string;
41
+ snippet: string;
42
+ }
43
+ type Fetch = typeof fetch;
44
+ /** Text a model can read: tags removed, the common entities decoded, whitespace collapsed, clipped. */
45
+ export declare function plainSnippet(value: unknown, limit?: number): string;
46
+ export interface WebSearchDependencies {
47
+ loadConfig?: () => Promise<Pick<Config, 'webSearch'> | undefined>;
48
+ fetch?: Fetch;
49
+ env?: NodeJS.ProcessEnv;
50
+ }
51
+ /** Run one search with the chosen backend. */
52
+ export declare function webSearch(query: string, count: number, signal: AbortSignal, dependencies?: WebSearchDependencies): Promise<{
53
+ provider: ResolvedWebSearchProvider;
54
+ results: WebSearchResult[];
55
+ }>;
56
+ /** The tool's text: a numbered list a model reads and the desktop scans for the sites it found. */
57
+ export declare function formatWebSearchResults(query: string, label: string, found: WebSearchResult[]): string;
58
+ export declare function createWebSearchTool(dependencies?: WebSearchDependencies): Tool;
59
+ export {};