@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
@@ -0,0 +1,224 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { mkdtemp, rm } from 'node:fs/promises';
3
+ import { tmpdir } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { CliUnavailableError } from './cli-executable.js';
6
+ import { runBoundedCli, stopProcessTree } from './cli-process.js';
7
+ import { resolveTrustedTaskkill } from './shell.js';
8
+ function validAttempt(id) { return typeof id === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(id); }
9
+ /** The first sign-in page and device code in what the CLI printed, held to the allowed hosts. */
10
+ export function readSignInPrompt(output, pageHosts) {
11
+ const plain = output.replace(/\u001b\[[0-9;]*m/g, '');
12
+ let authUrl;
13
+ for (const match of plain.matchAll(/https:\/\/[^\s"'<>]+/g)) {
14
+ try {
15
+ const url = new URL(match[0]);
16
+ if (url.username || url.password || url.port || !pageHosts.some(host => url.hostname === host || url.hostname.endsWith(`.${host}`)))
17
+ continue;
18
+ authUrl = url.href;
19
+ break;
20
+ }
21
+ catch { /* not a URL */ }
22
+ }
23
+ const userCode = plain.match(/^\s*([A-Z0-9]{4,5}-[A-Z0-9]{4,5})\s*$/m)?.[1];
24
+ return { ...(authUrl ? { authUrl } : {}), ...(userCode ? { userCode } : {}) };
25
+ }
26
+ const OUTPUT_LIMIT = 64 * 1024;
27
+ /** How long a start waits for the CLI to print its sign-in page before answering. */
28
+ const PROMPT_WAIT_MS = 15_000;
29
+ /**
30
+ * Runs one vendor CLI's own login command and reports what it left behind.
31
+ *
32
+ * The browser ceremony and the tokens belong to the vendor CLI, which stores them where it always
33
+ * does; Andorra never reads or copies them. This class starts the command, surfaces the page and
34
+ * code it prints, forwards a pasted code, stops it on cancel, and asks the CLI who is signed in.
35
+ */
36
+ export class CliSignIn {
37
+ spec;
38
+ attempt;
39
+ closed = false;
40
+ constructor(spec) {
41
+ this.spec = spec;
42
+ }
43
+ failed(message) { return `${this.spec.product} sign-in did not complete. ${message}`.trim(); }
44
+ async start(attemptId) {
45
+ if (!validAttempt(attemptId))
46
+ return { state: 'error', reason: 'unsupported', message: 'A valid sign-in attempt ID is required.' };
47
+ if (this.closed)
48
+ return { state: 'error', reason: 'unavailable', attemptId, message: `The ${this.spec.product} sign-in service has closed.` };
49
+ const current = this.attempt;
50
+ if (current?.id === attemptId)
51
+ return { ...current.view };
52
+ if (current?.live)
53
+ return { state: 'error', reason: 'busy', attemptId, message: `Another ${this.spec.product} sign-in is already in progress. Finish or cancel it first.` };
54
+ let finish;
55
+ const finished = new Promise(resolve => { finish = resolve; });
56
+ const attempt = { id: attemptId, view: { state: 'starting', attemptId }, live: true, output: '', finished, finish };
57
+ this.attempt = attempt;
58
+ const abandon = (view) => {
59
+ if (attempt.live)
60
+ attempt.view = view;
61
+ attempt.live = false;
62
+ finish();
63
+ return { ...attempt.view };
64
+ };
65
+ let executable;
66
+ try {
67
+ executable = await this.spec.resolveExecutable();
68
+ }
69
+ catch (error) {
70
+ return abandon({ state: 'error', reason: 'unavailable', attemptId, message: error instanceof CliUnavailableError ? error.message : this.failed('Check the CLI and try again.') });
71
+ }
72
+ if (!attempt.live)
73
+ return { ...attempt.view };
74
+ try {
75
+ attempt.cwd = await mkdtemp(join(tmpdir(), 'andorra-signin-'));
76
+ }
77
+ catch {
78
+ return abandon({ state: 'error', reason: 'unavailable', attemptId, message: this.failed('Try again.') });
79
+ }
80
+ const env = this.spec.env();
81
+ if (process.platform === 'win32')
82
+ attempt.taskkill = await resolveTrustedTaskkill(attempt.cwd).catch(() => undefined);
83
+ if (!attempt.live) {
84
+ await rm(attempt.cwd, { recursive: true, force: true }).catch(() => { });
85
+ return { ...attempt.view };
86
+ }
87
+ attempt.view = { state: 'waiting', attemptId, ...(this.spec.acceptsCode ? { acceptsCode: true } : {}) };
88
+ const child = spawn(executable.command, [...executable.args, ...this.spec.loginArgs], {
89
+ cwd: attempt.cwd, env, shell: false, windowsHide: true, detached: process.platform !== 'win32', stdio: ['pipe', 'pipe', 'pipe'],
90
+ });
91
+ attempt.child = child;
92
+ let prompted;
93
+ const promptSeen = new Promise(resolve => { prompted = resolve; });
94
+ const read = (chunk) => {
95
+ if (attempt.output.length >= OUTPUT_LIMIT)
96
+ return;
97
+ attempt.output += chunk.toString('utf8').slice(0, OUTPUT_LIMIT - attempt.output.length);
98
+ const prompt = readSignInPrompt(attempt.output, this.spec.pageHosts);
99
+ // A device code is shown to the person anyway, so the attempt keeps it for its own status
100
+ // answers; it often prints a moment after the page.
101
+ if (prompt.userCode && attempt.live && attempt.view.state === 'waiting' && !attempt.view.userCode)
102
+ attempt.view = { ...attempt.view, userCode: prompt.userCode };
103
+ if (prompt.authUrl)
104
+ prompted();
105
+ };
106
+ child.stdout.on('data', read);
107
+ child.stderr.on('data', read);
108
+ child.stdin.on('error', () => { });
109
+ let settled = false;
110
+ const settle = async (code) => {
111
+ if (settled)
112
+ return;
113
+ settled = true;
114
+ prompted();
115
+ clearTimeout(attempt.timer);
116
+ if (attempt.live && attempt.view.state === 'waiting') {
117
+ const account = code === 0 ? await this.spec.status(AbortSignal.timeout(30_000)).catch(() => undefined) : undefined;
118
+ attempt.view = account?.signedIn
119
+ ? { state: 'signedIn', attemptId, ...(account.email ? { email: account.email } : {}), ...(account.planType ? { planType: account.planType } : {}) }
120
+ : { state: 'error', reason: code === 0 ? 'unverified' : 'denied', attemptId, message: this.failed('Try again.') };
121
+ }
122
+ attempt.live = false;
123
+ if (attempt.cwd)
124
+ await rm(attempt.cwd, { recursive: true, force: true }).catch(() => { });
125
+ finish();
126
+ };
127
+ child.once('error', () => {
128
+ if (attempt.view.state === 'waiting')
129
+ attempt.view = { state: 'error', reason: 'unavailable', attemptId, message: this.failed('The CLI could not be started.') };
130
+ if (child.pid === undefined)
131
+ void settle(null);
132
+ });
133
+ child.once('close', code => { void settle(code); });
134
+ attempt.timer = setTimeout(() => { void this.stop(attempt, { state: 'error', reason: 'timeout', attemptId, message: `${this.spec.product} sign-in timed out. Try signing in again.` }); }, this.spec.timeoutMs ?? 10 * 60_000);
135
+ // The page is the one thing the person needs from this answer, so the start waits briefly for
136
+ // the CLI to print it. Later status answers never repeat it.
137
+ await Promise.race([promptSeen, new Promise(resolve => setTimeout(resolve, PROMPT_WAIT_MS).unref?.())]);
138
+ // A device-code CLI prints the code just after the page; give it a moment to arrive.
139
+ for (let waited = 0; this.spec.deviceCode && attempt.live && !readSignInPrompt(attempt.output, this.spec.pageHosts).userCode && waited < 3000; waited += 100) {
140
+ await new Promise(resolve => setTimeout(resolve, 100));
141
+ }
142
+ const prompt = readSignInPrompt(attempt.output, this.spec.pageHosts);
143
+ if (attempt.live && attempt.view.state === 'waiting' && prompt.userCode)
144
+ attempt.view = { ...attempt.view, userCode: prompt.userCode };
145
+ return { ...attempt.view, ...(attempt.live && prompt.authUrl ? { authUrl: prompt.authUrl } : {}) };
146
+ }
147
+ /** Forward a code the sign-in page showed to the waiting CLI. */
148
+ async submitCode(attemptId, code) {
149
+ const attempt = this.attempt;
150
+ if (!validAttempt(attemptId) || attempt?.id !== attemptId)
151
+ return { state: 'cancelled', attemptId, message: `This ${this.spec.product} sign-in attempt is no longer active.` };
152
+ if (!this.spec.acceptsCode || !attempt.live || !attempt.child?.stdin?.writable)
153
+ return { ...attempt.view };
154
+ const value = code.trim();
155
+ if (!value || value.length > 2000 || /[\s\u0000-\u001f\u007f]/.test(value))
156
+ return { ...attempt.view, message: 'That code is not valid. Copy the whole code from the sign-in page.' };
157
+ attempt.child.stdin.write(`${value}\n`);
158
+ return { ...attempt.view };
159
+ }
160
+ async status(attemptId) {
161
+ if (attemptId !== undefined && !validAttempt(attemptId))
162
+ return { state: 'error', reason: 'unsupported', message: 'A valid sign-in attempt ID is required.' };
163
+ const attempt = this.attempt;
164
+ if (attemptId !== undefined) {
165
+ if (attempt?.id !== attemptId)
166
+ return { state: 'cancelled', attemptId, message: `This ${this.spec.product} sign-in attempt is no longer active.` };
167
+ return { ...attempt.view };
168
+ }
169
+ if (attempt?.live)
170
+ return { ...attempt.view };
171
+ try {
172
+ const account = await this.spec.status(AbortSignal.timeout(30_000));
173
+ return account.signedIn ? { state: 'signedIn', ...(account.email ? { email: account.email } : {}), ...(account.planType ? { planType: account.planType } : {}) } : { state: 'signedOut' };
174
+ }
175
+ catch (error) {
176
+ return { state: 'error', reason: 'unavailable', message: error instanceof CliUnavailableError ? error.message : `${this.spec.product} sign-in status is unavailable. Check the CLI and try again.` };
177
+ }
178
+ }
179
+ async cancel(attemptId) {
180
+ if (!validAttempt(attemptId))
181
+ return { state: 'error', reason: 'unsupported', message: 'A valid sign-in attempt ID is required.' };
182
+ const attempt = this.attempt;
183
+ if (attempt?.id !== attemptId)
184
+ return { state: 'cancelled', attemptId, message: `This ${this.spec.product} sign-in attempt is no longer active.` };
185
+ if (attempt.live)
186
+ await this.stop(attempt, { state: 'cancelled', attemptId, message: `${this.spec.product} sign-in cancelled.` });
187
+ return { ...attempt.view };
188
+ }
189
+ /** Run the CLI's own sign-out, then report what its stored login now says. */
190
+ async logout() {
191
+ if (this.attempt?.live)
192
+ return { state: 'error', reason: 'busy', message: `A ${this.spec.product} sign-in is in progress. Finish or cancel it before signing out.` };
193
+ try {
194
+ const executable = await this.spec.resolveExecutable();
195
+ await runBoundedCli(executable, () => [...this.spec.logoutArgs], AbortSignal.timeout(60_000), { env: this.spec.env(), label: `${this.spec.product} CLI`, acceptedExitCodes: [0, 1] });
196
+ const account = await this.spec.status(AbortSignal.timeout(30_000));
197
+ if (account.signedIn)
198
+ return { state: 'error', reason: 'logoutFailed', message: `${this.spec.product} is still signed in. Sign out with its CLI and refresh.` };
199
+ this.attempt = undefined;
200
+ return { state: 'signedOut' };
201
+ }
202
+ catch (error) {
203
+ return { state: 'error', reason: 'logoutFailed', message: error instanceof CliUnavailableError ? error.message : `${this.spec.product} sign-out could not be completed. Refresh status and try again.` };
204
+ }
205
+ }
206
+ async stop(attempt, view) {
207
+ if (attempt.live)
208
+ attempt.view = view;
209
+ attempt.live = false;
210
+ clearTimeout(attempt.timer);
211
+ if (attempt.child)
212
+ attempt.stopping ??= stopProcessTree(attempt.child, attempt.taskkill);
213
+ else
214
+ attempt.finish();
215
+ await attempt.stopping;
216
+ await attempt.finished;
217
+ }
218
+ async close() {
219
+ this.closed = true;
220
+ const attempt = this.attempt;
221
+ if (attempt?.live)
222
+ await this.stop(attempt, { state: 'cancelled', attemptId: attempt.id, message: `${this.spec.product} sign-in cancelled.` });
223
+ }
224
+ }
package/dist/src/cli.js CHANGED
@@ -18,7 +18,7 @@ import { QA_SYSTEM_GUIDANCE, disposeAllQaProcesses, disposeAllQaPtys, getQaPtyMa
18
18
  import { disposePooledPowerShell } from './powershell-pool.js';
19
19
  import { loadWorkspaceInstructions } from './workspace-instructions.js';
20
20
  import { runGraph, stopReasonPhrase } from './runtime.js';
21
- import { validateGraph } from './graphs.js';
21
+ import { GraphDeletedError, validateGraph } from './graphs.js';
22
22
  import { checkGraphModelHealth, formatGraphHealthFailure } from './graph-health.js';
23
23
  import { getMembership, loadAccessibleGraph, PaidMembershipRequiredError } from './membership.js';
24
24
  import { configuredSurface, createRunHandle, drainTelemetry, graphShape, reportInterruptedRuns, reportRunFinished, reportRunStarted, reportSessionStarted } from './telemetry/surface.js';
@@ -28,8 +28,11 @@ import { GraphProviderUnavailableError } from './graph-provider-portability.js';
28
28
  import { MAX_SUBAGENT_TASK_CHARS, SubagentInvalidArgumentError, SubagentProviderNotSetError, SubagentRunInProgressError, SubagentRunner, SubagentSelectionError } from './subagent-run.js';
29
29
  /** Shown when a saved per-account graph selection is denied account access at launch or refresh. */
30
30
  const GRAPH_FALLBACK_NOTICE = 'The selected graph needs paid account access, which is currently unavailable. Starting with the local Default graph; once access is restored, switch back with /graph.';
31
- /** The free allowance names its own reason; any other membership refusal is an access outage. */
32
- const graphFallbackReason = (error) => error instanceof FreeTierLimitError ? `${error.message} Starting with the local Default graph.` : GRAPH_FALLBACK_NOTICE;
31
+ const missingSavedGraph = (error) => error?.code === 'ENOENT';
32
+ /** A stale saved choice should not abort startup after a crash between graph removal and config reset. */
33
+ const graphFallbackReason = (error) => error instanceof FreeTierLimitError || error instanceof GraphDeletedError
34
+ ? `${error.message} Starting with the local Default graph.`
35
+ : missingSavedGraph(error) ? 'The selected graph is no longer stored locally. Starting with the Default graph; use /graph to choose another.' : GRAPH_FALLBACK_NOTICE;
33
36
  import { configuredGraphSelection, currentGraphSubject } from './graph-selection.js';
34
37
  import { launchGraphEditor } from './graph-server.js';
35
38
  import { createGraphEditorSession } from './graph-editor-session.js';
@@ -38,6 +41,13 @@ import { updateInstallation } from './update.js';
38
41
  import { RunControl } from './run-control.js';
39
42
  import { TimerRegistry } from './timers.js';
40
43
  import { TerminalUI } from './terminal-ui.js';
44
+ import { listInvocableSkills } from './skills/invocable-skills.js';
45
+ /** Give the `/` popup the skills a person can type. Best effort: a failed read leaves the popup on the built-in commands. */
46
+ function offerSkillCommands(terminal, config, directory) {
47
+ if (!terminal)
48
+ return;
49
+ void listInvocableSkills(config, undefined, directory).then(skills => terminal.setSkillCommands(skills), () => { });
50
+ }
41
51
  import { meterStreamedRequest } from './token-rate.js';
42
52
  import { attachmentLabel, attachmentReadRoots, attachmentReferenceBlock, pruneAttachments, readClipboardImage, resolveAttachments, writeClipboardText } from './attachments.js';
43
53
  import { describeTool, formatEvent, formatRunResult } from './transcript.js';
@@ -53,7 +63,7 @@ import { isBuiltinSlashCommand } from './skill-commands.js';
53
63
  import { executeAuthCommand } from './auth-commands.js';
54
64
  import { setAuthSignOutReporter } from './auth/index.js';
55
65
  import { getAccountPresentation } from './account-presentation.js';
56
- import { acquireSessionMutationLock, clearOpenRunClaim, noteCheckpointWriteFailure, removeRunCheckpoint, RUNNING_TURN_SUMMARY, reconcileInterruptedRuns, runRecordPath, runRecordsDirectory, writeOpenRunRecord, writeRunCheckpoint, writeStudioRunSummary } from './run-records.js';
66
+ import { acquireSessionMutationLock, clearOpenRunClaim, createCheckpointFailureTracker, removeRunCheckpoint, RUNNING_TURN_SUMMARY, reconcileInterruptedRuns, runRecordPath, runRecordsDirectory, writeOpenRunRecord, writeRunCheckpoint, writeStudioRunSummary } from './run-records.js';
57
67
  import { gitChangeSummary } from './git-summary.js';
58
68
  import { writeActivity } from './activity.js';
59
69
  import { TodoStore } from './todos.js';
@@ -495,7 +505,7 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
495
505
  } }));
496
506
  // A saved per-account graph selection re-checks membership on every launch, so a transient
497
507
  // account-service failure or a membership lapse must not deny the whole session: fall back
498
- // to the local Software Engineer graph and say so. A selection whose providers this machine
508
+ // to the local Andorra Agent graph and say so. A selection whose providers this machine
499
509
  // cannot serve stays selected instead — the session refresh reports it and the header asks for
500
510
  // the model override that runs it, so /model is one command away rather than a re-selection.
501
511
  // An explicit --graph flag still fails fast because the caller asked for that exact graph.
@@ -516,7 +526,7 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
516
526
  // binding failure and sets the override hint, so the reason and the way out arrive together.
517
527
  if (error instanceof GraphProviderUnavailableError && values.graph === undefined)
518
528
  return;
519
- if (values.graph !== undefined || !(error instanceof PaidMembershipRequiredError))
529
+ if (values.graph !== undefined || (!(error instanceof PaidMembershipRequiredError || error instanceof GraphDeletedError) && !missingSavedGraph(error)))
520
530
  throw error;
521
531
  state.graph = 'default';
522
532
  graphFallbackNotice = graphFallbackReason(error);
@@ -819,8 +829,9 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
819
829
  await startupGuard(async () => {
820
830
  const selected = config.providers.find(p => p.id === config.provider);
821
831
  const codeIntelState = codeIntelLabel((await codeIntel.getStatus()).state);
822
- terminal = new TerminalUI({ account: { label: 'Checking account...', notice: 'Checking member access. Local Software Engineer remains available.' }, workspace, provider: selected?.id ?? 'No provider', model: selected?.model ?? '/providers to configure', providerModels: Object.fromEntries(config.providers.map(p => [p.id, p.model])), reasoningEffort: selected?.reasoningEffort, contextWindow: selected?.contextWindow, version: await cliVersion(), branch: await gitBranch(workspace), yolo: state.yolo, permissions: permissionLabel(state.permissions), graphSelection: state.graph ?? 'default', // The refresh below reads the definition of a graph that cannot bind, so construction must not depend on binding it.
832
+ terminal = new TerminalUI({ account: { label: 'Checking account...', notice: 'Checking member access. Local Andorra Agent remains available.' }, workspace, provider: selected?.id ?? 'No provider', model: selected?.model ?? '/providers to configure', providerModels: Object.fromEntries(config.providers.map(p => [p.id, p.model])), reasoningEffort: selected?.reasoningEffort, contextWindow: selected?.contextWindow, version: await cliVersion(), branch: await gitBranch(workspace), yolo: state.yolo, permissions: permissionLabel(state.permissions), graphSelection: state.graph ?? 'default', // The refresh below reads the definition of a graph that cannot bind, so construction must not depend on binding it.
823
833
  graph: startupGraph ?? await loadGraph(state.graph ?? 'default').catch(() => undefined), ...(codeIntelState ? { codeIntel: codeIntelState } : {}), clipboardImageProbe: readClipboardImage, clipboardTextWriter: writeClipboardText });
834
+ offerSkillCommands(terminal, state.config, directory);
824
835
  terminal.setLocalCommandHandler((input, mode, durationMs) => {
825
836
  // Local view commands never reach either CLI command loop.
826
837
  void debugRecord('command.started', { input, mode });
@@ -878,7 +889,7 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
878
889
  // The refresh path applies the same membership fallback as startup: without it the
879
890
  // denial would only print here while state.graph stays on the paid graph and the first
880
891
  // task retries the denied selection.
881
- if (values.graph !== undefined || (state.graph ?? 'default') === 'default' || !(error instanceof PaidMembershipRequiredError))
892
+ if (values.graph !== undefined || (state.graph ?? 'default') === 'default' || (!(error instanceof PaidMembershipRequiredError || error instanceof GraphDeletedError) && !missingSavedGraph(error)))
882
893
  throw error;
883
894
  state.graph = 'default';
884
895
  graphFallbackNotice = graphFallbackReason(error);
@@ -1106,11 +1117,11 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1106
1117
  // state. It is written into the open record so recovery can still join a crash's pair.
1107
1118
  const telemetryRunId = randomUUID();
1108
1119
  const startedAt = new Date().toISOString();
1109
- // Whether a checkpoint could not be written. A checkpoint is the conversation a resume
1110
- // re-enters the node with, so a run whose checkpoint failed is one no resume may replay: the
1111
- // resume would re-enter the node from its opening task and repeat the tool calls it had
1112
- // already made. The failure is marked, and the record carries it past a crash.
1113
- let checkpointFailed = false;
1120
+ // Which nodes' newest checkpoint could not be written. A checkpoint is the conversation a
1121
+ // resume re-enters the node with, so the node is marked until one of its later writes lands,
1122
+ // and the record carries the mark past a crash: a resume of the attempt warns that the node may
1123
+ // repeat work.
1124
+ const checkpointHealth = createCheckpointFailureTracker(directory, runId);
1114
1125
  // The selector this attempt runs on, captured at start. Every record the attempt writes
1115
1126
  // carries it: the result's own `graph` is the pinned graph object, whose id is the bundled
1116
1127
  // harness's id rather than the selection that loaded it ('default' loads `software-engineer`),
@@ -1181,7 +1192,7 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1181
1192
  endedAt: new Date().toISOString(),
1182
1193
  // The flag a resume consults before it trusts this attempt's conversation: a checkpoint
1183
1194
  // that could not be written leaves the node to be re-entered from its opening task.
1184
- ...(checkpointFailed ? { checkpointIntegrity: 'failed' } : {}),
1195
+ ...(checkpointHealth.intact ? {} : { checkpointIntegrity: 'failed', checkpointFailures: checkpointHealth.failures }),
1185
1196
  ...(runInput === undefined ? {} : { runInput }), ...(runState === undefined ? {} : { runState }) };
1186
1197
  try {
1187
1198
  await writeFile(runRecordPath(directory, runId, 'json'), JSON.stringify(record, null, 2) + '\n', { mode: 0o600 });
@@ -1273,9 +1284,8 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1273
1284
  const persistCheckpoint = (nodeId, messages, state, meta) => {
1274
1285
  checkpointWrites = checkpointWrites
1275
1286
  .then(() => writeRunCheckpoint(directory, runId, { nodeId, messages, state, revision: state.directionRevision, savedAt: new Date().toISOString(), ...(meta?.generation === undefined ? {} : { generation: meta.generation }), ...(meta?.provider === undefined ? {} : { provider: meta.provider }), ...(meta?.model === undefined ? {} : { model: meta.model }), ...(meta?.routedFrom === undefined ? {} : { routedFrom: meta.routedFrom }) }))
1276
- .catch(async (error) => {
1277
- checkpointFailed = true;
1278
- await noteCheckpointWriteFailure(directory, runId, error instanceof Error ? error.message : String(error));
1287
+ .then(() => checkpointHealth.succeeded({ nodeId, generation: meta?.generation }), async (error) => {
1288
+ await checkpointHealth.failed({ nodeId, generation: meta?.generation }, error);
1279
1289
  process.stderr.write(`Could not write the run checkpoint: ${error instanceof Error ? error.message : String(error)}\n`);
1280
1290
  });
1281
1291
  // The write is handed back so the runtime can await it: the checkpoint is the conversation a
@@ -1709,7 +1719,7 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1709
1719
  terminal?.noteGeneratedTokens(usage.outputTokens, origin?.invocationId, origin?.final === true, usage.decodeMs);
1710
1720
  terminal?.setStatus(sessionUsage());
1711
1721
  },
1712
- adapter: tracedAdapter(runtimeProvider(selected)), tools: [...createTools(), ...snapshot.tools, ...mcp.tools], history: state.history, instructions, codeIntel, ...decisionPolicy,
1722
+ adapter: tracedAdapter(runtimeProvider(selected)), tools: [...createTools(), ...snapshot.tools, ...mcp.tools], installedSkillClaims: snapshot.claimsSkillName, history: state.history, instructions, codeIntel, ...decisionPolicy,
1713
1723
  // Installation-wide bounds. Nothing is set by default, which leaves the run with no
1714
1724
  // wall clock and no iteration ceiling; a graph or node bound still narrows these.
1715
1725
  limits: resolveConfiguredLimits(config),
@@ -1774,6 +1784,25 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1774
1784
  await runResumed();
1775
1785
  }
1776
1786
  } : undefined,
1787
+ // Approving a plan flips this session only, the way the engine's own flip does: the saved
1788
+ // workspace default keeps planning the next task, so the footer follows the live mode and
1789
+ // the configuration is never touched. The control is updated with the state, exactly as
1790
+ // `/permissions` does mid-run — `permissionMode()` reads the control first, so a flip of
1791
+ // the state alone would leave every tool still refused.
1792
+ approvePlan: terminal ? async () => {
1793
+ const saved = state.config.workspacePermissions?.[workspacePermissionKey(workspace)];
1794
+ const next = saved === 'ask-for-approval' || saved === 'approve-for-me' || saved === 'full-access' ? saved : 'ask-for-approval';
1795
+ state.permissions = next;
1796
+ state.yolo = next === 'full-access';
1797
+ if (runControl) {
1798
+ runControl.yolo = state.yolo;
1799
+ runControl.permissions = state.permissions;
1800
+ }
1801
+ // An editing mode by construction, so the index resumes if plan mode had suspended it.
1802
+ await state.codeIntel?.setPermissions(next);
1803
+ terminal.setStatus({ permissions: permissionLabel(state.permissions), ...sessionUsage() });
1804
+ return next;
1805
+ } : undefined,
1777
1806
  approve: async (name, args, signal) => {
1778
1807
  if (!terminal || exiting)
1779
1808
  return false;
@@ -1821,7 +1850,7 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
1821
1850
  endedAt: new Date().toISOString(),
1822
1851
  // The flag a resume consults before it trusts this attempt's conversation: a checkpoint
1823
1852
  // that could not be written leaves the node to be re-entered from its opening task.
1824
- ...(checkpointFailed ? { checkpointIntegrity: 'failed' } : {}),
1853
+ ...(checkpointHealth.intact ? {} : { checkpointIntegrity: 'failed', checkpointFailures: checkpointHealth.failures }),
1825
1854
  ...(runInput === undefined ? {} : { runInput }), ...(runState === undefined ? {} : { runState }) };
1826
1855
  await writeFile(runRecordPath(directory, result.id, 'json'), JSON.stringify(finishedRecord, null, 2) + '\n', { mode: 0o600 });
1827
1856
  finishTelemetry(result.status, result.reason, result);
@@ -2232,6 +2261,8 @@ export async function main(argv = process.argv.slice(2), dependencies = {}) {
2232
2261
  }
2233
2262
  if (/^\/graph(?:\s|$)/.test(line) || result.clear && /^\/(providers|model)(?:\s|$)/.test(line))
2234
2263
  await refreshGraphStatus();
2264
+ if (/^\/(skills|plugins)(?:\s|$)/.test(line))
2265
+ offerSkillCommands(terminal, state.config, directory);
2235
2266
  trajectory.addSecrets(providerSecrets(config.providers));
2236
2267
  refreshStatus();
2237
2268
  }
@@ -2404,7 +2435,7 @@ export function subagentExitCode(outcome, signals) {
2404
2435
  /**
2405
2436
  * `andorra subagent`: one Andorra run driven by an external host (Claude CLI, Codex CLI).
2406
2437
  *
2407
- * The graph is always the bundled Software Engineer harness and the provider/model is mandatory:
2438
+ * The graph is always the bundled Andorra Agent harness and the provider/model is mandatory:
2408
2439
  * the call's own flags win, the saved `/subagent` setting is next, and with neither the command
2409
2440
  * answers on stdout with the PROVIDER_NOT_SET envelope carrying every configured provider and
2410
2441
  * model, so a Bash-spawning host can ask its user and retry with the pick. Stdout stays reserved
@@ -2428,7 +2459,7 @@ async function runSubagentCommand(argv) {
2428
2459
  continue;
2429
2460
  const name = argument.split('=')[0];
2430
2461
  if (!accepted.includes(name)) {
2431
- fail('INVALID_ARGUMENTS', `Unknown option ${name}. andorra subagent accepts --prompt, --provider, --model, --read-only and --cwd, and always runs the Software Engineer default graph.`);
2462
+ fail('INVALID_ARGUMENTS', `Unknown option ${name}. andorra subagent accepts --prompt, --provider, --model, --read-only and --cwd, and always runs the Andorra Agent default graph.`);
2432
2463
  return 1;
2433
2464
  }
2434
2465
  if (valued.has(name) && !argument.includes('='))
@@ -2452,7 +2483,7 @@ async function runSubagentCommand(argv) {
2452
2483
  }
2453
2484
  if (values.help) {
2454
2485
  process.stdout.write('Usage: andorra subagent --prompt "task" [--provider id] [--model id] [--read-only] [--cwd path]\n'
2455
- + 'Runs the built-in Software Engineer graph once and prints the run result as one JSON line on stdout.\n'
2486
+ + 'Runs the built-in Andorra Agent graph once and prints the run result as one JSON line on stdout.\n'
2456
2487
  + 'Provider/model is mandatory: pass --provider/--model, or set it in Andorra with /subagent. Without either,\n'
2457
2488
  + 'the output is a PROVIDER_NOT_SET error listing every configured provider and model — show that list to\n'
2458
2489
  + 'the user, ask which pair to use, and retry with --provider and --model.\n'
@@ -102,7 +102,7 @@ export declare class CodeIntelligenceManager {
102
102
  setEnabled(enabled: boolean): Promise<void>;
103
103
  rebuild(signal?: AbortSignal): Promise<void>;
104
104
  dispose(): Promise<void>;
105
- /** Suspend cache writers before publishing Read Only; retain the user's CodeGraph preference. */
105
+ /** Suspend cache writers before publishing Read Only or Plan; retain the user's CodeGraph preference. */
106
106
  setPermissions(permissions: PermissionMode | undefined): Promise<void>;
107
107
  }
108
108
  export {};
@@ -132,9 +132,9 @@ export class CodeIntelligenceManager {
132
132
  : (config.enabledRepos ?? []).includes(repositoryId);
133
133
  const manager = new CodeIntelligenceManager(options.workspace, repositoryRoot, options.readinessMs ?? 10_000, options.onEvent, enabled, options.syncTimeoutMs);
134
134
  manager.providerFactory = options.providerFactory ?? (() => new CodeGraphProvider({ onEvent: event => manager.onProviderEvent(event) }));
135
- manager.readOnly = options.permissions === 'read-only';
135
+ manager.readOnly = options.permissions === 'read-only' || options.permissions === 'plan';
136
136
  if (manager.readOnly) {
137
- await manager.emit('codeintel.state', { state: 'uninitialized', available: false, detail: 'Code intelligence is suspended in Read Only mode because its cache requires writes' });
137
+ await manager.emit('codeintel.state', { state: 'uninitialized', available: false, detail: options.permissions === 'plan' ? 'Code intelligence is suspended in Plan mode because its cache requires writes' : 'Code intelligence is suspended in Read Only mode because its cache requires writes' });
138
138
  return manager;
139
139
  }
140
140
  if (!enabled) {
@@ -597,14 +597,14 @@ export class CodeIntelligenceManager {
597
597
  for (const entry of entries)
598
598
  await entry.provider.dispose().catch(() => { });
599
599
  }
600
- /** Suspend cache writers before publishing Read Only; retain the user's CodeGraph preference. */
600
+ /** Suspend cache writers before publishing Read Only or Plan; retain the user's CodeGraph preference. */
601
601
  async setPermissions(permissions) {
602
- if (permissions === 'read-only') {
602
+ if (permissions === 'read-only' || permissions === 'plan') {
603
603
  this.readOnly = true;
604
604
  for (const entry of this.entries.values())
605
605
  await entry.provider.dispose({ requireIdle: true });
606
606
  this.entries.clear();
607
- await this.emit('codeintel.state', { state: 'uninitialized', available: false, detail: 'Code intelligence is suspended in Read Only mode because its cache requires writes' });
607
+ await this.emit('codeintel.state', { state: 'uninitialized', available: false, detail: permissions === 'plan' ? 'Code intelligence is suspended in Plan mode because its cache requires writes' : 'Code intelligence is suspended in Read Only mode because its cache requires writes' });
608
608
  return;
609
609
  }
610
610
  if (!this.readOnly)
@@ -3,6 +3,7 @@ import path from 'node:path';
3
3
  import { randomUUID } from 'node:crypto';
4
4
  import { execFile } from 'node:child_process';
5
5
  import { promisify } from 'node:util';
6
+ import { StringDecoder } from 'node:string_decoder';
6
7
  import { andorraCreateReadTool, andorraCreateWriteTool, andorraCreateEditTool, andorraCreateFindTool, andorraCreateGrepTool, andorraCreateLsTool, andorraCreateBashTool, andorraCreatePowerShellTool, } from '../vendor/engine/runtime/coding-agent/core/tools/index.js';
7
8
  import { andorraGetToolPath } from '../vendor/engine/runtime/coding-agent/utils/tools-manager.js';
8
9
  import { defaultShellKind, runShell, runNativeProcess } from './shell.js';
@@ -12,7 +13,7 @@ import { getQaProcessManager } from './qa/runtime/ProcessManager.js';
12
13
  import { clipText } from './text.js';
13
14
  import { matchesFileRead, storeFileRead } from './file-read-state.js';
14
15
  import { FileReadRequiredError } from './tool-errors.js';
15
- import { permissionMode } from './permissions.js';
16
+ import { permissionMode, PLAN_MODE_MUTATION_ERROR } from './permissions.js';
16
17
  import { withGrepRegex } from './grep-regex.js';
17
18
  const execFileAsync = promisify(execFile);
18
19
  const excluded = new Set(['.git', 'node_modules', '.andorracode']);
@@ -37,31 +38,54 @@ async function shellPermission(policy, name, args, context) {
37
38
  throw new Error('Escalation requires a nonempty justification');
38
39
  const mode = permissionMode(context);
39
40
  let explicitlyApproved = false;
41
+ let escalationAuthorized = false;
42
+ // Plan mode researches read-only: an escalation (host and network access) would be a change no
43
+ // plan has been approved for, so it is refused with the same guidance as a file mutation.
44
+ if (mode === 'plan' && requested === 'require_escalated')
45
+ throw new Error(PLAN_MODE_MUTATION_ERROR);
40
46
  if (!mode || mode === 'full-access' || requested === 'require_escalated') {
41
47
  await policy.authorize(name, { ...args, warning: 'UNSANDBOXED: entire host and network access.' }, {
42
48
  ...context, approve: async (...approval) => {
43
49
  const approved = await context.approve(...approval);
50
+ // A live permission switch settles outstanding prompts with policy-changed. Never
51
+ // allow an old escalation request to be re-approved after the run enters Plan.
52
+ if (requested === 'require_escalated' && permissionMode(context) === 'plan')
53
+ throw new Error(PLAN_MODE_MUTATION_ERROR);
44
54
  if (approved === true)
45
55
  explicitlyApproved = true;
46
56
  return approved;
47
57
  },
48
58
  });
59
+ // Authorization may have awaited other hooks while the run switched modes.
60
+ if (requested === 'require_escalated' && permissionMode(context) === 'plan')
61
+ throw new Error(PLAN_MODE_MUTATION_ERROR);
62
+ escalationAuthorized = requested === 'require_escalated';
49
63
  }
50
64
  // Evaluate synchronously at spawn, after filesystem/launcher discovery awaits.
51
65
  // Only a real per-call user grant can preserve unsandboxed execution when a
52
66
  // previously automatic Full Access grant has since been revoked.
53
67
  return () => {
54
68
  const live = permissionMode(context);
69
+ // Spawn-time recheck is essential: even a previously granted escalation cannot
70
+ // escape the read-only boundary if the run switched into Plan in the meantime.
71
+ if (requested === 'require_escalated' && live === 'plan')
72
+ throw new Error(PLAN_MODE_MUTATION_ERROR);
55
73
  if (explicitlyApproved)
56
74
  return undefined;
75
+ // An escalation this call's own authorization granted is an audited host grant: a shell is never a
76
+ // workspace-policy mutation, so without an explicit answer the journaled decision was Full Access
77
+ // policy — typically the user switching the run to Full Access while this prompt was open. It holds
78
+ // while Full Access is still in force at spawn; a revocation since then falls through below.
79
+ if (escalationAuthorized && live === 'full-access')
80
+ return undefined;
57
81
  // A later Full Access selection cannot create an unaudited host grant.
58
82
  // Keep an initially restricted call restricted; a subsequent call can
59
83
  // acquire Full Access through authorize and its journal events.
60
84
  if (mode && mode !== 'full-access' && live === 'full-access')
61
- return mode === 'read-only' ? 'read-only' : 'workspace-write';
85
+ return mode === 'read-only' || mode === 'plan' ? 'read-only' : 'workspace-write';
62
86
  if (!live || live === 'full-access')
63
87
  return undefined;
64
- return live === 'read-only' ? 'read-only' : 'workspace-write';
88
+ return live === 'read-only' || live === 'plan' ? 'read-only' : 'workspace-write';
65
89
  };
66
90
  }
67
91
  function nativeObservation(text, shell = false) {
@@ -679,8 +703,18 @@ export function createCodingTools(policy) {
679
703
  const launchPolicy = await shellPermission(policy, name, args, context);
680
704
  const cwd = await policy.safePath(context, '.');
681
705
  const operations = { exec: async (value, directory, options) => {
706
+ // The same chunks that feed the vendored tool's accumulator also feed the live transcript:
707
+ // a reader who expands the running call sees the command's output as it prints. The
708
+ // decoder keeps a chunk boundary from splitting a multi-byte character on the way
709
+ // through; the observation the tool builds remains the authoritative text.
710
+ const decoder = new StringDecoder('utf8');
711
+ const report = options.onData;
712
+ const onData = (data) => {
713
+ report(data);
714
+ context.onCommandOutput?.(decoder.write(data));
715
+ };
682
716
  try {
683
- await runShell(value, directory, timeout, context.signal, kind, options.onData, undefined, launchPolicy);
717
+ await runShell(value, directory, timeout, context.signal, kind, onData, undefined, launchPolicy);
684
718
  return { exitCode: 0 };
685
719
  }
686
720
  catch (error) {
@@ -690,6 +724,11 @@ export function createCodingTools(policy) {
690
724
  return { exitCode: Number(code[1]) };
691
725
  throw error;
692
726
  }
727
+ finally {
728
+ const tail = decoder.end();
729
+ if (tail)
730
+ context.onCommandOutput?.(tail);
731
+ }
693
732
  } };
694
733
  const current = kind === 'powershell'
695
734
  ? andorraCreatePowerShellTool(cwd, { operations, persistOutput: false, exposeSessionEnvironment: false })
@@ -867,7 +906,7 @@ export function createCodingTools(policy) {
867
906
  const timeout = intArg(args, 'timeout', { min: 1, max: 600000 }) ?? 30000;
868
907
  const launchPolicy = await shellPermission(policy, 'PowerShellFast', args, context);
869
908
  const cwd = await policy.safePath(context, '.');
870
- return nativeObservation(await runPooledPowerShell(command, cwd, timeout, context.signal, launchPolicy), true);
909
+ return nativeObservation(await runPooledPowerShell(command, cwd, timeout, context.signal, launchPolicy, context.onCommandOutput), true);
871
910
  });
872
911
  const ShellMetrics = zTool('ShellMetrics', 'Return bounded per-process command timing statistics (p50/p95/p99), startup/validation, execution, first-output and cleanup phases without leaking command arguments.', { type: 'object', properties: {}, additionalProperties: false }, 'parallel', async () => JSON.stringify(commandTimingSummary()));
873
912
  const platformShell = process.platform === 'win32' ? canonicalShell('PowerShell', 'powershell') : canonicalShell('Bash', 'bash');
@@ -0,0 +1,16 @@
1
+ /**
2
+ * The live-output tap for one running command tool call.
3
+ *
4
+ * A shell command's row in the transcript shows its output while the command still runs, not only
5
+ * after it exits: the tool forwards every chunk as the command prints it (the pooled worker's
6
+ * stream, a foreground shell's `onData`), and this tap turns that firehose into the throttled
7
+ * `node.tool.output` events the timeline reads. At most one event per interval, plus a trailing
8
+ * flush, keeps a chatty suite from flooding the journal; the call's own completion remains the
9
+ * authoritative record, and `stop` retires the tap the moment execution settles so a late chunk
10
+ * can never append to a row the completion already closed.
11
+ */
12
+ export interface CommandOutputTap {
13
+ push(chunk: string): void;
14
+ stop(): void;
15
+ }
16
+ export declare function createCommandOutputTap(emit: (chunk: string) => void, now?: () => number): CommandOutputTap;