@andorra-labs/code 0.1.6 → 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 (108) hide show
  1. package/dist/src/agent-execution.js +404 -25
  2. package/dist/src/agent-mcp-catalog.d.ts +21 -0
  3. package/dist/src/agent-mcp-catalog.js +40 -0
  4. package/dist/src/agent-mcp.d.ts +19 -3
  5. package/dist/src/agent-mcp.js +18 -44
  6. package/dist/src/app-server/protocol.d.ts +25 -3
  7. package/dist/src/app-server/protocol.js +5 -1
  8. package/dist/src/app-server/workspace.d.ts +8 -1
  9. package/dist/src/app-server/workspace.js +43 -2
  10. package/dist/src/app-server.js +88 -3
  11. package/dist/src/auth/AuthManager.d.ts +33 -1
  12. package/dist/src/auth/AuthManager.js +138 -10
  13. package/dist/src/auth/callback-page.d.ts +4 -0
  14. package/dist/src/auth/callback-page.js +70 -0
  15. package/dist/src/auth/callback.d.ts +39 -0
  16. package/dist/src/auth/callback.js +146 -22
  17. package/dist/src/auth/index.d.ts +10 -6
  18. package/dist/src/auth/index.js +2 -2
  19. package/dist/src/auth/store.d.ts +142 -3
  20. package/dist/src/auth/store.js +334 -13
  21. package/dist/src/auth/types.d.ts +17 -1
  22. package/dist/src/auth-commands.d.ts +11 -2
  23. package/dist/src/auth-commands.js +14 -7
  24. package/dist/src/automation-tool.js +10 -2
  25. package/dist/src/automations.d.ts +5 -0
  26. package/dist/src/automations.js +10 -0
  27. package/dist/src/capabilities.d.ts +9 -3
  28. package/dist/src/capabilities.js +7 -3
  29. package/dist/src/cli.js +31 -4
  30. package/dist/src/codex-provider.js +12 -0
  31. package/dist/src/coding-tools.d.ts +5 -0
  32. package/dist/src/coding-tools.js +54 -48
  33. package/dist/src/commands.d.ts +5 -1
  34. package/dist/src/commands.js +7 -6
  35. package/dist/src/completion.js +46 -0
  36. package/dist/src/config.d.ts +48 -0
  37. package/dist/src/config.js +248 -10
  38. package/dist/src/context-budget.d.ts +7 -0
  39. package/dist/src/context-budget.js +18 -1
  40. package/dist/src/decision/FactContinuations.d.ts +41 -6
  41. package/dist/src/decision/FactContinuations.js +211 -64
  42. package/dist/src/decision/PreparedSteps.js +3 -1
  43. package/dist/src/decision/checks.d.ts +25 -0
  44. package/dist/src/decision/checks.js +77 -6
  45. package/dist/src/delegation-changes.d.ts +109 -0
  46. package/dist/src/delegation-changes.js +431 -0
  47. package/dist/src/graph-server.d.ts +1 -0
  48. package/dist/src/graph-server.js +15 -3
  49. package/dist/src/graph-sync.d.ts +15 -0
  50. package/dist/src/graph-sync.js +50 -1
  51. package/dist/src/graph-tool.d.ts +52 -0
  52. package/dist/src/graph-tool.js +136 -0
  53. package/dist/src/graph-ui/app.js +212 -43
  54. package/dist/src/graph-ui/controls.js +6 -0
  55. package/dist/src/graph-ui/drafts.js +39 -0
  56. package/dist/src/graph-ui/embed.js +1 -1
  57. package/dist/src/graph-ui/index.html +2 -2
  58. package/dist/src/graph-ui/studio.css +7 -5
  59. package/dist/src/graph-ui/style.css +46 -12
  60. package/dist/src/graphs.d.ts +15 -2
  61. package/dist/src/graphs.js +42 -13
  62. package/dist/src/hardened-runtime.d.ts +4 -4
  63. package/dist/src/hardened-runtime.js +109 -9
  64. package/dist/src/powershell-pool.d.ts +9 -0
  65. package/dist/src/powershell-pool.js +16 -0
  66. package/dist/src/provider-keys.d.ts +48 -0
  67. package/dist/src/provider-keys.js +121 -0
  68. package/dist/src/pull-requests.d.ts +14 -5
  69. package/dist/src/pull-requests.js +28 -10
  70. package/dist/src/qa/runtime/ProcessManager.d.ts +6 -0
  71. package/dist/src/qa/runtime/ProcessManager.js +16 -0
  72. package/dist/src/react-runtime.js +30 -2
  73. package/dist/src/read-image.d.ts +30 -0
  74. package/dist/src/read-image.js +97 -0
  75. package/dist/src/secret-redaction.d.ts +13 -0
  76. package/dist/src/secret-redaction.js +71 -0
  77. package/dist/src/session-summary.d.ts +10 -4
  78. package/dist/src/session-summary.js +14 -7
  79. package/dist/src/sessions.js +4 -1
  80. package/dist/src/skills/bundled/graph-manager/SKILL.md +14 -11
  81. package/dist/src/skills/bundled/provenance.json +1 -1
  82. package/dist/src/telemetry/schema.d.ts +1 -1
  83. package/dist/src/telemetry/schema.js +1 -1
  84. package/dist/src/terminal-ui.d.ts +9 -0
  85. package/dist/src/terminal-ui.js +14 -0
  86. package/dist/src/tool-dependencies.js +4 -0
  87. package/dist/src/tools.d.ts +9 -0
  88. package/dist/src/tools.js +116 -11
  89. package/dist/src/transcript.js +5 -0
  90. package/dist/src/types.d.ts +13 -0
  91. package/dist/src/web-search.d.ts +59 -0
  92. package/dist/src/web-search.js +216 -0
  93. package/docs/agents/README.md +2 -2
  94. package/docs/agents/mcp-server.md +15 -2
  95. package/docs/concepts/README.md +1 -1
  96. package/docs/concepts/security.md +2 -2
  97. package/docs/getting-started/accounts.md +15 -4
  98. package/docs/getting-started/configure-providers.md +1 -1
  99. package/docs/guides/README.md +1 -0
  100. package/docs/guides/desktop-app.md +1 -1
  101. package/docs/guides/graph-builder.md +1 -1
  102. package/docs/guides/web-search.md +47 -0
  103. package/docs/reference/cli.md +4 -3
  104. package/docs/reference/config.md +3 -3
  105. package/docs/reference/slash-commands.md +2 -1
  106. package/docs/superpowers/plans/2026-11-09-orchestrator-delegation.md +295 -0
  107. package/docs/superpowers/specs/2026-11-09-orchestrator-delegation-design.md +291 -0
  108. package/package.json +1 -1
@@ -3,11 +3,12 @@ import type { ModelAdapter } from './types.js';
3
3
  /**
4
4
  * Whether a title request can be bounded for this provider.
5
5
  *
6
- * The Codex adapter never reads `maxTokens`: a title request there is a full reasoning turn that
7
- * runs beside the real one until its signal deadline, so an unbounded auxiliary request would cost
8
- * more than the local name it replaces. Those sessions keep the local name.
6
+ * Every supported adapter bounds an auxiliary turn itself: the adapters that read `maxTokens`
7
+ * natively, and the Codex adapter by running the naming turn with minimal reasoning effort on a
8
+ * dedicated ephemeral thread (the installed Codex CLI exposes no token-level output bound), with
9
+ * this deadline as the outer bound. No provider has to keep the local word-slice name.
9
10
  */
10
- export declare const titleRequestSupported: (provider: Pick<ProviderConfig, "type">) => boolean;
11
+ export declare const titleRequestSupported: (_provider: Pick<ProviderConfig, "type">) => boolean;
11
12
  /**
12
13
  * How long a naming request may take. The session already carries its local name, so this is only
13
14
  * the wait before a slow provider's better name replaces it: a bound past the provider's own
@@ -21,6 +22,11 @@ export declare const MAX_SESSION_TITLE_CHARS = 80;
21
22
  * what the user asked for rather than the first words cut off. Resolves `''` whenever no usable
22
23
  * title came back — provider missing, offline, timeout, empty answer — and the caller keeps the
23
24
  * local name. The signal only cancels the request; a settled title is always safe to use.
25
+ *
26
+ * Credential material is redacted on both sides: the prompt is redacted before it leaves the
27
+ * process, so the naming request never carries a secret, and the answer is redacted before it
28
+ * becomes a title, so a model that echoed one back never puts it on the rail. A prompt or answer
29
+ * that redacts to nothing keeps the local name.
24
30
  */
25
31
  export declare function summarizeSessionPrompt(prompt: string, adapter: ModelAdapter, model: string, signal?: AbortSignal): Promise<string>;
26
32
  /** Normalize a model answer into one displayable line; `''` when nothing usable came back. */
@@ -1,12 +1,14 @@
1
1
  import { stripVTControlCharacters } from 'node:util';
2
+ import { redactSecrets } from './secret-redaction.js';
2
3
  /**
3
4
  * Whether a title request can be bounded for this provider.
4
5
  *
5
- * The Codex adapter never reads `maxTokens`: a title request there is a full reasoning turn that
6
- * runs beside the real one until its signal deadline, so an unbounded auxiliary request would cost
7
- * more than the local name it replaces. Those sessions keep the local name.
6
+ * Every supported adapter bounds an auxiliary turn itself: the adapters that read `maxTokens`
7
+ * natively, and the Codex adapter by running the naming turn with minimal reasoning effort on a
8
+ * dedicated ephemeral thread (the installed Codex CLI exposes no token-level output bound), with
9
+ * this deadline as the outer bound. No provider has to keep the local word-slice name.
8
10
  */
9
- export const titleRequestSupported = (provider) => provider.type !== 'codex';
11
+ export const titleRequestSupported = (_provider) => true;
10
12
  /**
11
13
  * How long a naming request may take. The session already carries its local name, so this is only
12
14
  * the wait before a slow provider's better name replaces it: a bound past the provider's own
@@ -21,6 +23,11 @@ const MAX_PROMPT_CHARS = 4_000;
21
23
  * what the user asked for rather than the first words cut off. Resolves `''` whenever no usable
22
24
  * title came back — provider missing, offline, timeout, empty answer — and the caller keeps the
23
25
  * local name. The signal only cancels the request; a settled title is always safe to use.
26
+ *
27
+ * Credential material is redacted on both sides: the prompt is redacted before it leaves the
28
+ * process, so the naming request never carries a secret, and the answer is redacted before it
29
+ * becomes a title, so a model that echoed one back never puts it on the rail. A prompt or answer
30
+ * that redacts to nothing keeps the local name.
24
31
  */
25
32
  export async function summarizeSessionPrompt(prompt, adapter, model, signal) {
26
33
  const clean = stripVTControlCharacters(prompt).trim();
@@ -30,11 +37,11 @@ export async function summarizeSessionPrompt(prompt, adapter, model, signal) {
30
37
  const response = await adapter.generate({
31
38
  model, signal: bounded, tools: [], maxTokens: 512,
32
39
  messages: [
33
- { role: 'system', content: 'You name coding sessions. Answer with the session title only: 3 to 8 words summarizing what the user asked for, in the same language as the prompt. No quotes, no preamble, no ending punctuation.' },
34
- { role: 'user', content: `A coding session starts with this prompt. Give it its title.\n\n${clean.slice(0, MAX_PROMPT_CHARS)}` },
40
+ { role: 'system', content: 'You name coding sessions. Answer with the session title only: 3 to 8 words summarizing what the user asked for, in the same language as the prompt. No quotes, no preamble, no ending punctuation. Never include a password, API key, token, or other credential in the title.' },
41
+ { role: 'user', content: `A coding session starts with this prompt. Give it its title.\n\n${redactSecrets(clean).slice(0, MAX_PROMPT_CHARS)}` },
35
42
  ],
36
43
  });
37
- return titleFromSummary(response.text);
44
+ return titleFromSummary(redactSecrets(response.text));
38
45
  }
39
46
  /** Normalize a model answer into one displayable line; `''` when nothing usable came back. */
40
47
  export function titleFromSummary(text) {
@@ -5,9 +5,12 @@ import { join, resolve } from 'node:path';
5
5
  import { stripVTControlCharacters } from 'node:util';
6
6
  import { setTimeout as delay } from 'node:timers/promises';
7
7
  import { decodeDoubleEscapedSummary } from './completion.js';
8
+ import { redactSecrets } from './secret-redaction.js';
8
9
  /** Extract a short local task label without a model request. */
9
10
  export const sessionName = (prompt) => {
10
- const clean = stripVTControlCharacters(prompt)
11
+ // The label is what the rail shows until a model title replaces it (and forever when naming
12
+ // fails), so credential material pasted beside the task must never survive into it.
13
+ const clean = redactSecrets(stripVTControlCharacters(prompt))
11
14
  .replace(/https?:\/\/\S+/gi, ' ')
12
15
  .replace(/[a-z]:[\\/][^\s"<>|]*/gi, ' ')
13
16
  .replace(/(?:^|\s)[/~][\w./-]+/g, ' ')
@@ -1,25 +1,28 @@
1
1
  ---
2
2
  name: graph-manager
3
- description: "Design, create, edit, delete or restore Andorra Code graphs (multi-agent workflows) from the user's requirements, through Andorra's graph MCP tools. Use when the user wants a new workflow, wants to change how an existing graph routes work, or wants a graph removed or brought back."
3
+ description: "Design, create, edit, delete or restore Andorra Code graphs (multi-agent workflows) from the user's requirements, through Andorra's graph tools. Use when the user wants a new workflow, wants to change how an existing graph routes work, or wants a graph removed or brought back."
4
4
  ---
5
5
 
6
6
  # Manage graphs
7
7
 
8
8
  A graph is a workflow of agent nodes connected by outcome routes: a plan step hands to a build step, a review
9
9
  routes `pass` to done and `fail` back to the build, and so on. Graphs are created and changed only through
10
- Andorra's graph MCP tools (`andorra_graph_*`), which validate every change and save immutable revisions that
10
+ Andorra's graph operations (`andorra_graph_*`), which validate every change and save immutable revisions that
11
11
  sync to the user's account. Never edit graph files on disk.
12
12
 
13
- ## 1. Check the tools are available
13
+ ## 1. Find the graph tools
14
14
 
15
- You need the `andorra_graph_*` tools (they may appear with a server prefix, such as
16
- `mcp__andorra__andorra_graphs_list`). If they are missing, the graph MCP server is not connected. Offer to
17
- connect it with the `manage-mcp` skill, as a stdio entry with `"command": "andorra"` and
18
- `"args": ["mcp-server", "--stdio"]`, and continue in a new task once the user agrees and it is connected.
19
- A stdio server receives only the variables its entry lists, so when Andorra runs with `ANDORRACODE_HOME` set,
20
- add `"env": { "ANDORRACODE_HOME": "${ANDORRACODE_HOME}" }`: without it the graph server reads `~/.andorracode`
21
- (another installation's providers and sign-in). Leave it out when the variable is not set, because an unset
22
- reference fails the connection.
15
+ Inside Andorra, every graph operation is an action of the built-in `graphs` tool: call it with `action` set
16
+ to the operation named in this skill and its arguments in `args`, for example
17
+ `{"action": "andorra_graph_begin", "args": {"mode": "create", "id": "qa-flow", "name": "QA Flow"}}`.
18
+ It needs no MCP server. If `graphs` is not in your tools, this node is not allowed to use it (it needs shell
19
+ permission, and delegated subagents never get it): tell the user to run the request from a top-level agent
20
+ with shell access, and stop. Do not write graph files instead.
21
+
22
+ Outside Andorra (Claude Code, Codex, another agent host), the same operations are separate MCP tools, possibly
23
+ with a server prefix such as `mcp__andorra__andorra_graphs_list`. If they are missing, the graph MCP server is
24
+ not connected: it is a stdio server with `"command": "andorra"` and `"args": ["mcp-server", "--stdio"]`,
25
+ which the host connects in its own MCP settings.
23
26
  Graph editing also needs the user to be signed in (`andorra auth status`); a free account may keep one custom
24
27
  graph of up to 3 nodes, without an Orchestrator.
25
28
 
@@ -714,7 +714,7 @@
714
714
  {
715
715
  "source": "src/skills/bundled/graph-manager/SKILL.md",
716
716
  "asset": "graph-manager/SKILL.md",
717
- "sha256": "51ec69c75768b6134b72f5fab0eeb04497eba95a40c0c6b3ef37596e230e281e"
717
+ "sha256": "b40f2e1e3b075033e70f3162eb197acf64ee027ad1d1ffb0dd266d702c3630cc"
718
718
  },
719
719
  {
720
720
  "source": "src/skills/bundled/graph-manager/errors.md",
@@ -35,7 +35,7 @@ export type TelemetryLanguage = typeof TELEMETRY_LANGUAGES[number];
35
35
  export declare const TELEMETRY_FRAMEWORKS: readonly ["react", "vue", "angular", "svelte", "nextjs", "nestjs", "express", "fastapi", "django", "flask", "spring", "rails", "laravel", "dotnet", "actix", "axum", "gin", "flutter", "electron", "tauri", "other"];
36
36
  export type TelemetryFramework = typeof TELEMETRY_FRAMEWORKS[number];
37
37
  /** Product-owned tool names, plus the three buckets user- or server-named tools collapse into. */
38
- export declare const TELEMETRY_TOOL_NAMES: readonly ["Read", "Write", "Edit", "Glob", "Grep", "Bash", "PowerShell", "git_read", "read_artifact", "write_artifact", "repo_explore", "memory_search", "set_timer", "pull_request", "read_skill_resource", "ask_user", "spawn_subagent", "qa.browser", "qa.browser_session", "qa.deep", "qa.fast", "qa.inspect_project", "qa.security", "qa.status", "qa.terminal", "qa.test", "browser.panel", "browser.incognito", "browser.solve_captcha", "mcp", "plugin", "other"];
38
+ export declare const TELEMETRY_TOOL_NAMES: readonly ["Read", "Write", "Edit", "Glob", "Grep", "Bash", "PowerShell", "git_read", "read_artifact", "write_artifact", "repo_explore", "memory_search", "set_timer", "pull_request", "read_skill_resource", "ask_user", "spawn_subagent", "qa.browser", "qa.browser_session", "qa.deep", "qa.fast", "qa.inspect_project", "qa.security", "qa.status", "qa.terminal", "qa.test", "browser.panel", "browser.incognito", "browser.solve_captcha", "web_search", "mcp", "plugin", "other"];
39
39
  export type TelemetryToolName = typeof TELEMETRY_TOOL_NAMES[number];
40
40
  /**
41
41
  * Public model ids a run may name. Provider configuration accepts a user-supplied string of up to
@@ -51,7 +51,7 @@ export const TELEMETRY_TOOL_NAMES = [
51
51
  'qa.browser', 'qa.browser_session', 'qa.deep', 'qa.fast', 'qa.inspect_project', 'qa.security',
52
52
  'qa.status', 'qa.terminal', 'qa.test',
53
53
  'browser.panel', 'browser.incognito',
54
- 'browser.solve_captcha',
54
+ 'browser.solve_captcha', 'web_search',
55
55
  'mcp', 'plugin', 'other',
56
56
  ];
57
57
  /**
@@ -702,6 +702,15 @@ export declare class TerminalUI extends EventEmitter {
702
702
  * The system writer is preferred; without one, or when it fails, an OSC 52 sequence asks
703
703
  * the terminal to set the clipboard instead.
704
704
  */
705
+ /**
706
+ * Put text on the clipboard of whoever is looking at this terminal.
707
+ *
708
+ * `terminalOnly` skips the system writer for an OSC 52 sequence alone: over SSH the system
709
+ * clipboard belongs to the remote host, while the terminal's is the one on the user's own machine.
710
+ */
711
+ copyText(text: string, options?: {
712
+ terminalOnly?: boolean;
713
+ }): void;
705
714
  private copySelection;
706
715
  private complete;
707
716
  /** Put `command ` in the composer and open its argument list, without submitting anything. */
@@ -2571,6 +2571,20 @@ export class TerminalUI extends EventEmitter {
2571
2571
  * The system writer is preferred; without one, or when it fails, an OSC 52 sequence asks
2572
2572
  * the terminal to set the clipboard instead.
2573
2573
  */
2574
+ /**
2575
+ * Put text on the clipboard of whoever is looking at this terminal.
2576
+ *
2577
+ * `terminalOnly` skips the system writer for an OSC 52 sequence alone: over SSH the system
2578
+ * clipboard belongs to the remote host, while the terminal's is the one on the user's own machine.
2579
+ */
2580
+ copyText(text, options = {}) {
2581
+ const osc52 = () => { if (this.started && !this.closed)
2582
+ this.output.write(`\x1b]52;c;${Buffer.from(text, 'utf8').toString('base64')}\x07`); };
2583
+ if (this.clipboardTextWriter && !options.terminalOnly)
2584
+ void this.clipboardTextWriter(text).catch(osc52);
2585
+ else
2586
+ osc52();
2587
+ }
2574
2588
  copySelection(cut) {
2575
2589
  const range = this.selectionRange();
2576
2590
  if (!range)
@@ -10,6 +10,10 @@ export function requiresToolBarrier(name, tool) {
10
10
  // The caller must explicitly classify only those actions as parallel.
11
11
  if (name === 'AsyncProcess' && tool?.executionMode === 'parallel')
12
12
  return false;
13
+ // web_search rides the browser capability for policy, but only sends a query to a search service:
14
+ // it changes no page, file or session, so independent searches may overlap each other and reads.
15
+ if (name === 'web_search' && tool?.executionMode === 'parallel')
16
+ return false;
13
17
  if (tool?.executionMode === 'sequential' || SEQUENTIAL.has(name))
14
18
  return true;
15
19
  return !!tool?.capability && !READ_CAPABILITIES.has(tool.capability);
@@ -1,3 +1,12 @@
1
1
  import type { Tool, ToolContext } from './types.js';
2
+ export declare function within(root: string, target: string): boolean;
3
+ /**
4
+ * The paths among `names` (relative to `base`) where a write needs approval under workspace rules:
5
+ * outside the workspace, or inside it under protected repository/runtime metadata.
6
+ */
7
+ export declare function classifyWorkspaceWrites(workspace: string, base: string, names: readonly string[]): Promise<{
8
+ outside: string[];
9
+ protected: string[];
10
+ }>;
2
11
  export declare function authorize(name: string, args: Record<string, unknown>, context: ToolContext): Promise<void>;
3
12
  export declare function createTools(): Tool[];
package/dist/src/tools.js CHANGED
@@ -7,9 +7,13 @@ import { createCodingTools } from './coding-tools.js';
7
7
  import { createQaTools } from './qa/index.js';
8
8
  import { createBrowserSessionTool } from './browser-session.js';
9
9
  import { createSolveCaptchaTool } from './browser-captcha-tool.js';
10
+ import { createWebSearchTool } from './web-search.js';
10
11
  import { createAutomationTool } from './automation-tool.js';
12
+ import { createGraphTool } from './graph-tool.js';
11
13
  import { andorraCreateWriteTool } from '../vendor/engine/runtime/coding-agent/core/tools/write.js';
12
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';
13
17
  import { clipText } from './text.js';
14
18
  import { pullRequestSettings } from './pull-requests.js';
15
19
  import { approveOperation } from './capabilities.js';
@@ -34,14 +38,61 @@ function validate(args, keys) {
34
38
  function samePath(left, right) {
35
39
  return process.platform === 'win32' ? path.resolve(left).toLowerCase() === path.resolve(right).toLowerCase() : left === right;
36
40
  }
37
- function within(root, target) {
41
+ export function within(root, target) {
38
42
  const relative = path.relative(root, target);
39
43
  return relative === '' || (!path.isAbsolute(relative) && relative !== '..' && !relative.startsWith(`..${path.sep}`));
40
44
  }
41
- /** 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. */
42
46
  function trustedAttachment(context, target) {
43
47
  return (context.attachmentRoots ?? []).some(root => within(root, target));
44
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
+ }
45
96
  async function safePath(context, name, missing = false, beforeProbe) {
46
97
  context.signal.throwIfAborted();
47
98
  if (permissionMode(context) !== 'full-access')
@@ -50,7 +101,11 @@ async function safePath(context, name, missing = false, beforeProbe) {
50
101
  const target = path.resolve(root, name);
51
102
  // An attachment spool is trusted under its canonical spelling too: realpath may re-spell a
52
103
  // path that legitimately points into the spool (a symlinked home, a differently cased root).
53
- 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;
54
109
  const assertProbeAllowed = () => {
55
110
  if (permissionMode(context) === 'full-access')
56
111
  return;
@@ -72,7 +127,8 @@ async function safePath(context, name, missing = false, beforeProbe) {
72
127
  const resolved = await realpath(ancestor);
73
128
  if (beforeProbe)
74
129
  await beforeProbe();
75
- const trusted = targetTrusted || trustedAttachment(context, resolved);
130
+ const trusted = attachmentTrusted || trustedAttachment(context, resolved)
131
+ || (delegationTrusted && (context.delegationRoots ?? []).some(delegationRoot => within(delegationRoot, resolved)));
76
132
  if (permissionMode(context) !== 'full-access' && !within(root, resolved) && !trusted)
77
133
  throw new Error('Symlink escapes workspace');
78
134
  const canonical = path.join(resolved, path.relative(ancestor, target));
@@ -145,6 +201,49 @@ async function read(context, name) {
145
201
  await handle.close();
146
202
  }
147
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
+ }
148
247
  function assertMutationPermission(context) {
149
248
  if (!context.pinFilePaths && !context.fileMutationApproval?.explicit && (permissionMode(context) === 'read-only' || permissionMode(context) === 'plan'))
150
249
  throw new Error('Permission denied: file mutation grant was revoked');
@@ -388,9 +487,10 @@ function filePermissionTool(tool) {
388
487
  let authorized;
389
488
  if (['write_file', 'edit_file', 'Write', 'Edit', 'write', 'edit'].includes(tool.name)) {
390
489
  context.toolState ??= { fileReads: new Map() };
391
- // The attachment spool carve-out is a READ trust: a mutation lands outside the workspace
392
- // and keeps the scoped approval these modes require, so the roots leave this call alone.
393
- 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 };
394
494
  }
395
495
  const selected = permissionMode(context);
396
496
  if (selected && selected !== 'full-access') {
@@ -402,8 +502,11 @@ function filePermissionTool(tool) {
402
502
  // An attachment spool holds content the user attached to this very turn, written by the
403
503
  // engine: reading it is as trusted as the workspace, and the outside-workspace approval
404
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.
405
507
  const attachmentTrusted = trustedAttachment(context, target)
406
- || 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);
407
510
  if (!attachmentTrusted) {
408
511
  const outside = !within(root, target);
409
512
  // Classify lexical metadata descendants before even lstat/readlink: their
@@ -513,6 +616,7 @@ function qaPermissionTool(tool) {
513
616
  export function createTools() {
514
617
  return [
515
618
  createAutomationTool(),
619
+ createGraphTool(),
516
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.', {
517
621
  path: property('Workspace-relative file path'),
518
622
  startLine: { type: 'integer', minimum: 1, description: 'First line, inclusive (default 1)' },
@@ -650,10 +754,10 @@ export function createTools() {
650
754
  context.wakesArmed?.push(timer.id);
651
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.`;
652
756
  }),
653
- { ...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 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.', {
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.', {
654
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' },
655
759
  url: property('The GitHub pull request URL (attach only)'),
656
- autoFix: { type: 'boolean', description: 'Wake this session when new review comments arrive, until the PR is merged or closed' },
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' },
657
761
  mergeWhenReady: { type: 'boolean', description: 'GitHub auto-merge once checks and reviews pass' },
658
762
  draft: { type: 'boolean', description: 'true converts to a draft, false marks it ready for review' },
659
763
  }, ['action'], async (args, context) => {
@@ -689,9 +793,10 @@ export function createTools() {
689
793
  default: throw new Error('action must be status, attach, update, or dismiss');
690
794
  }
691
795
  }), family: 'git', executionMode: 'sequential' },
692
- ...createCodingTools({ safePath, read, atomicWrite, authorize, files, fileLimit: FILE_LIMIT }),
796
+ ...createCodingTools({ safePath, read, readImage, atomicWrite, authorize, files, fileLimit: FILE_LIMIT }),
693
797
  ...createQaTools().map(qaPermissionTool),
694
798
  createBrowserSessionTool(authorize),
695
799
  createSolveCaptchaTool(authorize),
800
+ createWebSearchTool(),
696
801
  ].map(filePermissionTool);
697
802
  }
@@ -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;
@@ -164,6 +164,19 @@ export interface ToolContext {
164
164
  * cannot grant. Never model input; never widened beyond the engine's own spools.
165
165
  */
166
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[];
167
180
  /** Runtime-owned explicit file-mutation grant, scoped to one tool call. */
168
181
  fileMutationApproval?: {
169
182
  explicit: boolean;
@@ -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 {};