@andorra-labs/code 0.1.10 → 0.1.12

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 (238) hide show
  1. package/README.md +31 -205
  2. package/THIRD_PARTY_NOTICES.md +30 -0
  3. package/dist/src/agent-execution.js +50 -2
  4. package/dist/src/agent-mcp.js +5 -0
  5. package/dist/src/app-server/protocol.d.ts +9 -1
  6. package/dist/src/app-server/protocol.js +1 -1
  7. package/dist/src/app-server.d.ts +49 -1
  8. package/dist/src/app-server.js +353 -64
  9. package/dist/src/automation-service.js +1 -1
  10. package/dist/src/browser-panel-tool.d.ts +24 -3
  11. package/dist/src/browser-panel-tool.js +80 -6
  12. package/dist/src/browser-runner.js +3 -1
  13. package/dist/src/browser-session.d.ts +8 -0
  14. package/dist/src/browser-session.js +27 -1
  15. package/dist/src/browser-ui/app.js +237 -15
  16. package/dist/src/browser-ui/index.html +5 -5
  17. package/dist/src/browser-ui/style.css +110 -65
  18. package/dist/src/browser-ui/tokens.css +27 -26
  19. package/dist/src/browser-view.d.ts +16 -0
  20. package/dist/src/browser-view.js +38 -2
  21. package/dist/src/claude-provider.js +15 -2
  22. package/dist/src/cli.d.ts +2 -1
  23. package/dist/src/cli.js +175 -43
  24. package/dist/src/code-intelligence/CodeIntelligenceManager.js +1 -1
  25. package/dist/src/codex-provider.js +6 -3
  26. package/dist/src/coding-tools.d.ts +26 -1
  27. package/dist/src/coding-tools.js +104 -33
  28. package/dist/src/command-screens.js +1 -1
  29. package/dist/src/commands.js +1 -1
  30. package/dist/src/completion-gates.d.ts +42 -7
  31. package/dist/src/completion-gates.js +55 -9
  32. package/dist/src/completion.d.ts +51 -1
  33. package/dist/src/completion.js +164 -5
  34. package/dist/src/config.d.ts +1 -0
  35. package/dist/src/config.js +2 -0
  36. package/dist/src/dashboard-view.js +2 -2
  37. package/dist/src/deadline.js +4 -0
  38. package/dist/src/decision/PreparedSteps.js +1 -1
  39. package/dist/src/delegation-changes.js +19 -2
  40. package/dist/src/diff-preview.d.ts +1 -0
  41. package/dist/src/diff-preview.js +12 -3
  42. package/dist/src/engine-streams.d.ts +22 -0
  43. package/dist/src/engine-streams.js +16 -0
  44. package/dist/src/extensions.js +17 -6
  45. package/dist/src/file-read-key.d.ts +8 -0
  46. package/dist/src/file-read-key.js +12 -0
  47. package/dist/src/graph-editor-session.js +2 -1
  48. package/dist/src/graph-health.d.ts +21 -0
  49. package/dist/src/graph-health.js +46 -0
  50. package/dist/src/graph-manager-chat.d.ts +52 -3
  51. package/dist/src/graph-manager-chat.js +62 -17
  52. package/dist/src/graph-runner.js +62 -5
  53. package/dist/src/graph-server.d.ts +1 -1
  54. package/dist/src/graph-server.js +48 -27
  55. package/dist/src/graph-sync.d.ts +8 -0
  56. package/dist/src/graph-sync.js +54 -3
  57. package/dist/src/graph-tool.js +1 -1
  58. package/dist/src/graph-ui/app.js +362 -123
  59. package/dist/src/graph-ui/controls.css +95 -22
  60. package/dist/src/graph-ui/controls.js +31 -1
  61. package/dist/src/graph-ui/embed.js +62 -13
  62. package/dist/src/graph-ui/icons.js +7 -0
  63. package/dist/src/graph-ui/index.html +4 -4
  64. package/dist/src/graph-ui/manager-state.js +143 -5
  65. package/dist/src/graph-ui/manager.css +21 -20
  66. package/dist/src/graph-ui/manager.js +337 -75
  67. package/dist/src/graph-ui/model-picker.js +279 -0
  68. package/dist/src/graph-ui/provider-glyphs/alibaba-cloud.png +0 -0
  69. package/dist/src/graph-ui/provider-glyphs/anthropic.png +0 -0
  70. package/dist/src/graph-ui/provider-glyphs/aws-bedrock.png +0 -0
  71. package/dist/src/graph-ui/provider-glyphs/claude.png +0 -0
  72. package/dist/src/graph-ui/provider-glyphs/deepseek.png +0 -0
  73. package/dist/src/graph-ui/provider-glyphs/fireworks.png +0 -0
  74. package/dist/src/graph-ui/provider-glyphs/kimi.png +0 -0
  75. package/dist/src/graph-ui/provider-glyphs/minimax.png +0 -0
  76. package/dist/src/graph-ui/provider-glyphs/openai.png +0 -0
  77. package/dist/src/graph-ui/provider-glyphs/opencode.png +0 -0
  78. package/dist/src/graph-ui/provider-glyphs/openrouter.png +0 -0
  79. package/dist/src/graph-ui/provider-glyphs/xai.png +0 -0
  80. package/dist/src/graph-ui/provider-glyphs/xiaomi-mimo.png +0 -0
  81. package/dist/src/graph-ui/provider-glyphs/zai.png +0 -0
  82. package/dist/src/graph-ui/skill-picker.js +1 -1
  83. package/dist/src/graph-ui/studio-canvas.js +8 -8
  84. package/dist/src/graph-ui/studio.css +18 -15
  85. package/dist/src/graph-ui/studio.js +92 -35
  86. package/dist/src/graph-ui/style.css +122 -79
  87. package/dist/src/graph-ui/theme.js +2 -2
  88. package/dist/src/graph-ui/tokens.css +33 -29
  89. package/dist/src/graphs.d.ts +5 -2
  90. package/dist/src/graphs.js +10 -9
  91. package/dist/src/mcp.d.ts +52 -14
  92. package/dist/src/mcp.js +285 -128
  93. package/dist/src/membership-errors.d.ts +7 -1
  94. package/dist/src/membership-errors.js +9 -3
  95. package/dist/src/memory/ProjectMemory.d.ts +77 -0
  96. package/dist/src/memory/ProjectMemory.js +310 -0
  97. package/dist/src/memory/index.d.ts +1 -0
  98. package/dist/src/memory/index.js +1 -0
  99. package/dist/src/opencode-provider.js +5 -6
  100. package/dist/src/package-name.d.ts +3 -0
  101. package/dist/src/package-name.js +3 -0
  102. package/dist/src/provider-engine.js +2 -2
  103. package/dist/src/pull-requests.d.ts +42 -6
  104. package/dist/src/pull-requests.js +11 -3
  105. package/dist/src/qa/runtime/PtyManager.js +2 -1
  106. package/dist/src/react-runtime.js +137 -22
  107. package/dist/src/read-document-doc.d.ts +20 -0
  108. package/dist/src/read-document-doc.js +524 -0
  109. package/dist/src/read-document-docx.d.ts +21 -0
  110. package/dist/src/read-document-docx.js +584 -0
  111. package/dist/src/read-document-text.d.ts +29 -0
  112. package/dist/src/read-document-text.js +67 -0
  113. package/dist/src/read-document-tool.d.ts +48 -0
  114. package/dist/src/read-document-tool.js +162 -0
  115. package/dist/src/read-document.d.ts +78 -0
  116. package/dist/src/read-document.js +353 -0
  117. package/dist/src/read-image.d.ts +29 -2
  118. package/dist/src/read-image.js +42 -17
  119. package/dist/src/remote/cert.d.ts +1 -1
  120. package/dist/src/remote/cert.js +2 -7
  121. package/dist/src/remote/client.js +1 -1
  122. package/dist/src/remote/pem.d.ts +6 -0
  123. package/dist/src/remote/pem.js +11 -0
  124. package/dist/src/run-records.js +49 -10
  125. package/dist/src/runtime.d.ts +21 -0
  126. package/dist/src/runtime.js +10 -1
  127. package/dist/src/session-changes.d.ts +6 -1
  128. package/dist/src/session-changes.js +13 -5
  129. package/dist/src/sessions.d.ts +3 -1
  130. package/dist/src/sessions.js +5 -3
  131. package/dist/src/side-panel.d.ts +6 -1
  132. package/dist/src/side-panel.js +12 -10
  133. package/dist/src/sign-in-detection.d.ts +82 -0
  134. package/dist/src/sign-in-detection.js +197 -0
  135. package/dist/src/sign-in-offer.d.ts +35 -0
  136. package/dist/src/sign-in-offer.js +116 -0
  137. package/dist/src/skills/bundled/create-skill/SKILL.md +1 -1
  138. package/dist/src/skills/bundled/diagram/SKILL.md +1 -1
  139. package/dist/src/skills/bundled/graph-manager/SKILL.md +59 -7
  140. package/dist/src/skills/bundled/graph-manager/patterns.md +27 -0
  141. package/dist/src/skills/bundled/provenance.json +4 -4
  142. package/dist/src/skills/runtime-skills.d.ts +6 -0
  143. package/dist/src/skills/runtime-skills.js +16 -3
  144. package/dist/src/stall-recovery.d.ts +6 -2
  145. package/dist/src/stall-recovery.js +7 -2
  146. package/dist/src/stray-files.d.ts +14 -0
  147. package/dist/src/stray-files.js +81 -0
  148. package/dist/src/subagent-run.js +6 -1
  149. package/dist/src/terminal-ui.d.ts +1 -1
  150. package/dist/src/terminal-ui.js +11 -5
  151. package/dist/src/time-limit.d.ts +53 -0
  152. package/dist/src/time-limit.js +79 -0
  153. package/dist/src/tool-activity.js +1 -1
  154. package/dist/src/tool-schema-compatibility.d.ts +7 -2
  155. package/dist/src/tool-schema-compatibility.js +8 -4
  156. package/dist/src/tools.js +92 -7
  157. package/dist/src/transcript.d.ts +5 -0
  158. package/dist/src/transcript.js +12 -4
  159. package/dist/src/types.d.ts +8 -0
  160. package/dist/src/untracked-file-removal.d.ts +3 -0
  161. package/dist/src/untracked-file-removal.js +125 -0
  162. package/dist/src/update-check.js +1 -1
  163. package/dist/src/update.d.ts +11 -1
  164. package/dist/src/update.js +27 -5
  165. package/dist/src/usage-analytics.d.ts +3 -1
  166. package/dist/src/usage-analytics.js +16 -2
  167. package/dist/src/workspace-git-metadata.d.ts +15 -0
  168. package/dist/src/workspace-git-metadata.js +50 -1
  169. package/dist/src/workspace-instructions.js +1 -1
  170. package/package.json +6 -26
  171. package/docs/README.md +0 -36
  172. package/docs/agents/README.md +0 -62
  173. package/docs/agents/install-for-agents.md +0 -56
  174. package/docs/agents/mcp-server.md +0 -212
  175. package/docs/agents/subagent-mode.md +0 -149
  176. package/docs/concepts/README.md +0 -47
  177. package/docs/concepts/jev-actionable-routing.md +0 -113
  178. package/docs/concepts/jev-decision-thresholds.md +0 -412
  179. package/docs/concepts/jev-efficiency.md +0 -217
  180. package/docs/concepts/jev-eval-2026-11-01.md +0 -78
  181. package/docs/concepts/limits.md +0 -52
  182. package/docs/concepts/memory.md +0 -10
  183. package/docs/concepts/security.md +0 -50
  184. package/docs/concepts/workspace-instructions.md +0 -29
  185. package/docs/getting-started/README.md +0 -82
  186. package/docs/getting-started/accounts.md +0 -78
  187. package/docs/getting-started/configure-providers.md +0 -132
  188. package/docs/guides/README.md +0 -13
  189. package/docs/guides/browser.md +0 -39
  190. package/docs/guides/desktop-app.md +0 -414
  191. package/docs/guides/extensions.md +0 -102
  192. package/docs/guides/graph-builder.md +0 -116
  193. package/docs/guides/headless.md +0 -46
  194. package/docs/guides/tui.md +0 -75
  195. package/docs/guides/update.md +0 -70
  196. package/docs/guides/web-search.md +0 -51
  197. package/docs/guides/windows-code-signing.md +0 -319
  198. package/docs/llms.txt +0 -45
  199. package/docs/reference/README.md +0 -7
  200. package/docs/reference/cli.md +0 -76
  201. package/docs/reference/config.md +0 -91
  202. package/docs/reference/slash-commands.md +0 -59
  203. package/docs/superpowers/plans/2026-11-01-claude-console-sign-in.md +0 -111
  204. package/docs/superpowers/plans/2026-11-01-jev-node-opt-in.md +0 -910
  205. package/docs/superpowers/plans/2026-11-02-workflow-pane.md +0 -398
  206. package/docs/superpowers/plans/2026-11-06-graph-soft-delete.md +0 -125
  207. package/docs/superpowers/plans/2026-11-09-orchestrator-delegation.md +0 -295
  208. package/docs/superpowers/plans/2026-11-13-graph-manager-chat.md +0 -203
  209. package/docs/superpowers/plans/2026-11-14-jev-fair-use-pricing.md +0 -79
  210. package/docs/superpowers/specs/2026-10-31-work-line-summary-design.md +0 -50
  211. package/docs/superpowers/specs/2026-11-01-claude-console-sign-in-design.md +0 -176
  212. package/docs/superpowers/specs/2026-11-01-jev-node-opt-in-design.md +0 -164
  213. package/docs/superpowers/specs/2026-11-01-pr-section-design.md +0 -111
  214. package/docs/superpowers/specs/2026-11-02-workflow-pane-design.md +0 -130
  215. package/docs/superpowers/specs/2026-11-06-bundled-skills-design.md +0 -206
  216. package/docs/superpowers/specs/2026-11-09-orchestrator-delegation-design.md +0 -291
  217. package/docs/superpowers/specs/2026-11-13-graph-manager-chat-design.md +0 -182
  218. package/docs/superpowers/specs/2026-11-14-jev-fair-use-pricing-design.md +0 -156
  219. package/scripts/jev-efficiency-eval.mjs +0 -187
  220. package/scripts/jev-efficiency-live.mjs +0 -193
  221. package/scripts/zcode-engine-replay.mjs +0 -223
  222. package/tests/agent-centric-mcp-test-plan.md +0 -208
  223. package/tests/analytics-settings-test-plan.md +0 -165
  224. package/tests/browser-cli-smoke.mjs +0 -276
  225. package/tests/browser-test-plan.md +0 -280
  226. package/tests/chat-side-panel-test-plan.md +0 -309
  227. package/tests/decision-engine-test-plan.md +0 -163
  228. package/tests/default-active-jev-test-plan.md +0 -85
  229. package/tests/harness-extensions-test-plan.md +0 -113
  230. package/tests/jev-all-decisions-test-plan.md +0 -156
  231. package/tests/jev-efficiency/criteria.json +0 -158
  232. package/tests/jev-efficiency/workloads.mjs +0 -242
  233. package/tests/jev-efficiency-test-plan.md +0 -198
  234. package/tests/permissions-sandbox-probe.mjs +0 -74
  235. package/tests/permissions-test-plan.md +0 -191
  236. package/tests/product-telemetry-test-plan.md +0 -536
  237. package/tests/thinking-stream-preview-test-plan.md +0 -136
  238. package/tests/zcode-react-engine-test-plan.md +0 -396
@@ -8,8 +8,8 @@ import { validateInitialModelToolInput, getInitialInputValidationModelContent }
8
8
  import { andorraIsContextOverflow } from '../vendor/engine/runtime/ai/utils/overflow.js';
9
9
  import { toEngineResponse, engineModel } from './engine/protocol.js';
10
10
  import { ProviderRequestError } from './providers.js';
11
- import { COMPLETION_ALONE_ERROR, COMPLETION_TOOL, COMPLETION_GUIDANCE, FINAL_RESPONSE_GUIDANCE, OUTPUT_STOOD_IN_NOTE, RESPONSE_STRUCTURE_GUIDANCE, completionTool, completionResponse, parseCompletion } from './completion.js';
12
- import { MAX_GATE_ASKS, finalAnswerGate } from './completion-gates.js';
11
+ import { COMPLETION_ALONE_ERROR, COMPLETION_TOOL, COMPLETION_GUIDANCE, FINAL_RESPONSE_GUIDANCE, OUTPUT_STOOD_IN_NOTE, RESPONSE_STRUCTURE_GUIDANCE, completionTool, completionResponse, parseCompletion, withoutTrailingEnvelope } from './completion.js';
12
+ import { MAX_GATE_ASKS, MAX_IDLE_UNFINISHED_ASKS, finalAnswerGate } from './completion-gates.js';
13
13
  import { HistoryCompactor, CompactionRecoveryError, pinnedContextChars, PINNED_CONTEXT_GUIDANCE } from './context-compaction.js';
14
14
  import { createHash, randomUUID } from 'node:crypto';
15
15
  import { ToolFailureTracker } from './tool-failure-tracker.js';
@@ -36,16 +36,21 @@ import { commandLine, isCheckCall, isReplaySafeCheck } from './decision/checks.j
36
36
  import { stalledTurnGuidance, suspectedDroppedToolCall, unavailableHistoryTools, unavailableToolsSentence } from './stall-recovery.js';
37
37
  import { ClarificationRequiredError, DEFAULT_GRAPH, hasToolBudget, generateWithUsage, resolveLimits, withinToolBudget, turnModelTask, } from './runtime.js';
38
38
  import { bindUserWaits, createRuntimeBudget } from './deadline.js';
39
+ import { createTimeLimitNotices, timeLimitPrompt, withTimeLimitPrompt } from './time-limit.js';
39
40
  import { createCommandOutputTap } from './command-output-tap.js';
40
41
  import { advertisable } from './tool-availability.js';
42
+ /** Shown in place of a completion envelope a model wrote as text, which is sent back. */
43
+ const SENT_BACK_ENVELOPE_NOTE = '_Wrote its report as text instead of calling complete_agent; asked to send it through complete_agent._';
41
44
  const DEFAULT_AGENT_INSTRUCTIONS = `You are the Andorra Agent in Andorra Code's default graph.
42
45
  Handle the user's task end to end, whether it is a coding task or a general one: implement code and verify changes with appropriate tools, and answer general research, writing and analysis directly from the available sources.`;
43
46
  const IMPLEMENTATION_GUIDANCE = `Every model turn resends the whole conversation, so finish in the fewest turns that fully cover the task.
44
47
  Compose new or fully rewritten files in a single Write; reserve Edit for surgical changes to long existing files. Tool results already show the applied change, so never re-read a file just to confirm your own Write or Edit.
45
- Issue independent read-only calls together in one turn, and combine related shell checks into one labeled command.
48
+ Issue independent read-only calls together in one turn. Combine quick related shell checks into one labeled command, but give a search or scan that may be slow its own call: a timeout stops the whole command and loses the output of every check in it.
46
49
  Do mechanical or repetitive work by executing code (a shell one-liner or script), not through repeated model-driven edits.
47
- Keep tool output small: filter, count, select, or tail instead of feeding whole files or long listings back into context.
50
+ Keep tool output proportionate: filter, count, select, or tail large files, logs and command output instead of feeding them whole into context. Finding something is the exception. When the task names a thing you have not located (a host, service, project, tool or file), look for it by file and directory name before anything else: list the working directory in full, without a first-N or last-N cap, and search names as well as contents, because a file can be named for a thing its text never mentions. A listing you cut short, or a search that timed out or was stopped, is not evidence that the thing is absent: rerun it narrower or in its own call before concluding so or asking the user.
48
51
  Reuse unchanged evidence and known interfaces rather than rereading files. For runnable software, build the smallest integrated vertical slice first: entry point, initialization and one real interaction. Run a boot/syntax smoke check as soon as that slice exists, before broad subsystem inventories or polishing. Use observed failures to choose the next targeted inspection, and verify with the smallest check that can actually fail. Then complete every requested behavior and verification.
52
+ When the task says what a file must contain (an answer, a flag, a value, output in a stated format), write exactly that into the file and nothing else: no explanation, heading, label, notes or report. Whatever reads the file compares it with what was asked for, so added text turns a correct answer into a wrong one; explanations belong in your summary.
53
+ Before finishing, read the task statement again and check the result against each thing it states: file paths and names, formats, exact values, constraints, and what must stay unchanged. A check written from your own reading of the task only repeats that reading, so where the task names its own check, command or example, run that one.
49
54
  When browser.panel is available, use it for browsing: it drives the same tabs the session's Browser panel shows the user, so they can watch every step, and it shares that browser's cookies and login state, which persist in the project's browser profile. qa.browser_session is a separate headless browser the user cannot see; use it alongside browser.panel only for an operation the panel lacks (hold, move) or when the user asks for an isolated browser. When a check needs a fresh, signed-out browser (first-visit flows, sign-up, logged-out pages), call browser.incognito start first, then end it when done. When only qa.browser_session is available, use it directly for website navigation, tab management, screenshots and page interactions. Inspect the repository only when the requested work needs project context; do not inventory shell browser tooling or generate browser probes before trying the granted browser tool.
50
55
  If execution is blocked, report why and use focused static checks. Intake, research and non-runnable tasks follow their assigned scope.`;
51
56
  const SYSTEM = `Follow the configured Agent instruction and completion contract using only the granted capabilities.
@@ -70,6 +75,19 @@ function refusedRequest(error) {
70
75
  const status = typeof direct === 'number' ? direct : Number(/\(HTTP (\d{3})\)/.exec(error instanceof Error ? error.message : '')?.[1]);
71
76
  return [400, 404, 415, 422].includes(status);
72
77
  }
78
+ /** How much of a stopped command's output its observation keeps. */
79
+ const STEERED_OUTPUT_TAIL = 4_000;
80
+ /** The tools whose call a user steer stops: each waits on a process the user may be waiting out. */
81
+ const STEER_STOPPABLE = new Set(['Bash', 'PowerShell', 'PowerShellFast', 'NativeExec', 'bash', 'powershell', 'shell']);
82
+ function steerStoppable(name, args) {
83
+ return STEER_STOPPABLE.has(name) || (name === 'AsyncProcess' && args.action === 'wait');
84
+ }
85
+ /** The observation for a call a steer stopped: why it ended, and what it printed before. */
86
+ function steeredOutput(elapsedMs, printed) {
87
+ const seconds = Math.max(0, Math.round(elapsedMs / 100) / 10);
88
+ const tail = printed.trim();
89
+ return `Stopped after ${seconds}s: the user sent a new message while this call ran, so it was ended before it finished. Read the message before running it again.${tail ? `\nOutput before it stopped:\n${tail}` : '\nIt printed nothing before it stopped.'}`;
90
+ }
73
91
  /** Canonical arguments prevent object-key order from disguising an identical side effect. */
74
92
  function actionFingerprint(name, args) {
75
93
  const canonical = (value) => Array.isArray(value) ? value.map(canonical)
@@ -383,6 +401,11 @@ export class AndorraAgentEngine {
383
401
  ? `\nWritten outcome criteria: ${JSON.stringify(outcomeCriteria)}. Evaluate these written criteria against the evidence gathered during this node and use them to select exactly one declared outcome. Explain the selected outcome and supporting evidence in your summary. These are criteria for your judgment, not automatically executed checks. Do not claim a criterion is satisfied without evidence. If criteria overlap or none are satisfied, report that uncertainty honestly and select an appropriate declared fallback outcome when available; never invent an outcome. Outcomes without written criteria retain their meaning from the node instructions and confirmed task.`
384
402
  : '';
385
403
  messages[0].content += completionContract + criteriaContract;
404
+ // A bounded attempt is told so, and told again as the time runs down (time-limit.ts). The
405
+ // default is no wall clock, in which case nothing is added.
406
+ const timeNotices = limits.wallTimeMs ? createTimeLimitNotices(limits.wallTimeMs) : undefined;
407
+ if (limits.wallTimeMs)
408
+ messages[0].content += `\n${timeLimitPrompt(limits.wallTimeMs)}`;
386
409
  // Retained turns render through the one shared renderer: a continued turn's stored task is the
387
410
  // stopped attempt's, the direction the user sent with the continuation is the message this turn
388
411
  // actually answers — dropped here, the CLI's next request would omit what they said — and a
@@ -422,6 +445,9 @@ export class AndorraAgentEngine {
422
445
  if (start >= 0 && end >= 0) {
423
446
  system.content = system.content.slice(0, start) + (options.instructions ? `${guidanceMarker}${options.instructions}` : '') + system.content.slice(end);
424
447
  }
448
+ // The restored prompt states the limit the stopped attempt began with; this one has what
449
+ // was left of it, or a limit configured since, or none.
450
+ system.content = withTimeLimitPrompt(system.content, limits.wallTimeMs);
425
451
  }
426
452
  }
427
453
  else if (!options.subagentId && options.previousConversation?.provider === options.provider && options.previousConversation.model === options.model) {
@@ -831,11 +857,35 @@ export class AndorraAgentEngine {
831
857
  };
832
858
  let prepared = [];
833
859
  let finalized = [];
860
+ // A user steer that lands while this turn's tools run. The model request is already cut off by
861
+ // its own watch (below); a tool batch had none, so a steer sent during `Start-Sleep 60` waited
862
+ // the whole minute before the model read it. While a batch runs, a steer stops the command in
863
+ // flight and skips the calls that have not started, and the next turn reads the message. Only a
864
+ // runtime that reads the shared steering queue listens: a delegated child never reads it.
865
+ let batchSteer;
866
+ const watchBatchSteer = () => {
867
+ if (batchSteer || !control || !options.getSteeringMessages || options.subagentId)
868
+ return;
869
+ const watch = { arrived: false, cut: new AbortController(), stop: () => { } };
870
+ watch.stop = control.onSteer(() => {
871
+ watch.arrived = true;
872
+ watch.cut.abort(new Error('Stopped to read a new message from the user.'));
873
+ });
874
+ batchSteer = watch;
875
+ };
876
+ const endBatchSteer = () => { batchSteer?.stop(); batchSteer = undefined; };
834
877
  let fatalError;
835
878
  let modelResponseReady = false;
836
879
  let completionRejectionEmitted = false;
837
880
  /** Times each final-answer gate has sent a handoff back in this run. */
838
881
  const gateAsks = {};
882
+ /**
883
+ * The unfinished gate has no ask limit while the agent works between its completions. What is
884
+ * counted is the opposite: send-backs in a row that it answered with no tool call at all,
885
+ * measured against the tool-call count at the last send-back.
886
+ */
887
+ let unfinishedIdleAsks = 0;
888
+ let unfinishedAskedAtToolCalls;
839
889
  const engineState = { stopHookContinuationCount: continuationState?.engineState?.stopHookContinuationCount ?? continuationState?.zcodeState?.stopHookContinuationCount ?? 0, outputTokenContinuationCount: continuationState?.engineState?.outputTokenContinuationCount ?? continuationState?.zcodeState?.outputTokenContinuationCount ?? 0 };
840
890
  let outputPartials = [...(continuationState?.outputPartials ?? [])];
841
891
  let overflowRecoveries = 0;
@@ -880,6 +930,7 @@ export class AndorraAgentEngine {
880
930
  prepared = [];
881
931
  finalized = [];
882
932
  executionCalls = 0;
933
+ endBatchSteer();
883
934
  response = { text: '', toolCalls: [], completionSource: 'final_text' };
884
935
  if (limits.maxIterations !== undefined && iteration > limits.maxIterations) {
885
936
  result.reason = 'maxIterations';
@@ -943,6 +994,12 @@ export class AndorraAgentEngine {
943
994
  replacePostflightGuidance(arrivedPostflight.guidance);
944
995
  arrivedPostflight = undefined;
945
996
  }
997
+ // Asked from the budget itself, so time the run spent waiting on a person is not counted.
998
+ const timeNotice = timeNotices?.next(budget.remainingMs());
999
+ if (timeNotice) {
1000
+ messages.push({ role: 'user', content: timeNotice.text });
1001
+ await emit('agent.time_limit.notice', { stage: timeNotice.stage, remainingMs: budget.remainingMs(), limitMs: limits.wallTimeMs });
1002
+ }
946
1003
  refreshTodoContext();
947
1004
  const prunedImages = pruneHistoricalImages(messages);
948
1005
  if (prunedImages)
@@ -1229,8 +1286,11 @@ export class AndorraAgentEngine {
1229
1286
  todoCalls += metadataCalls;
1230
1287
  if (options.budget)
1231
1288
  options.budget.toolCalls += executionCalls;
1232
- if (response.text.trim())
1233
- await emit('agent.message', { text: response.text });
1289
+ // Narration a model wrapped in a completion envelope beside its tool calls is shown as its
1290
+ // summary text, not as raw JSON.
1291
+ const shown = withoutTrailingEnvelope(response.text);
1292
+ if (shown.trim())
1293
+ await emit('agent.message', { text: shown });
1234
1294
  prepared = [];
1235
1295
  for (const call of response.toolCalls) {
1236
1296
  signal.throwIfAborted();
@@ -1278,6 +1338,21 @@ export class AndorraAgentEngine {
1278
1338
  await emit('node.tool.skipped', { name: entry.call.name, toolCallId: entry.call.id, output });
1279
1339
  return { call: entry.call, output, isError: false };
1280
1340
  }
1341
+ if (batchSteer?.arrived) {
1342
+ if (isTodoCall(entry.call))
1343
+ todoCalls--;
1344
+ else if (isPreparedPlanCall(entry.call))
1345
+ preparedPlanCalls--;
1346
+ else if (isRestorationCall(entry.call))
1347
+ restorationCalls--;
1348
+ else if (isWidgetCall(entry.call))
1349
+ widgetCalls--;
1350
+ else if (options.budget)
1351
+ options.budget.toolCalls--;
1352
+ const output = 'Not executed: the user sent a new message before this call started. Read it, then decide whether this call is still needed.';
1353
+ await emit('node.tool.skipped', { name: entry.call.name, toolCallId: entry.call.id, output, reason: 'steer' });
1354
+ return { call: entry.call, output, isError: false, steered: true };
1355
+ }
1281
1356
  if (!isMetadataCall(entry.call)) {
1282
1357
  result.toolCalls++;
1283
1358
  recordToolUse(result.telemetry, entry.call.name, false);
@@ -1340,13 +1415,25 @@ export class AndorraAgentEngine {
1340
1415
  const commandTap = createCommandOutputTap(chunk => {
1341
1416
  void emit('node.tool.output', { name: entry.call.name, toolCallId: entry.call.id, output: chunk }).catch(() => { });
1342
1417
  });
1418
+ // Only a call that waits on a process is stopped by a steer: a shell command, a native
1419
+ // executable, or a wait on a background job (the job itself keeps running). A file edit
1420
+ // or a delegated subagent runs to its end, so a steer never leaves half-applied work.
1421
+ const steerCut = batchSteer !== undefined && steerStoppable(entry.call.name, args) ? batchSteer.cut.signal : undefined;
1422
+ const steerStartedAt = monotonicNow();
1423
+ let printed = '';
1424
+ const onCommandOutput = (chunk) => {
1425
+ if (steerCut)
1426
+ printed = (printed + chunk).slice(-STEERED_OUTPUT_TAIL);
1427
+ commandTap.push(chunk);
1428
+ };
1429
+ let steered = false;
1343
1430
  try {
1344
1431
  output = await tool.execute(args, {
1345
1432
  ...context,
1346
1433
  // A child invocation retains its lifetime; its own operations subscribe
1347
1434
  // to the same control and pause without discarding the child history.
1348
1435
  ...(entry.call.name === 'spawn_subagent' ? {} : {
1349
- signal: operationSignal,
1436
+ signal: steerCut ? AbortSignal.any([operationSignal, steerCut]) : operationSignal,
1350
1437
  userSignal: control ? AbortSignal.any([context.userSignal ?? signal, operationSignal]) : context.userSignal,
1351
1438
  }),
1352
1439
  onApprovalEvent: (type, data) => {
@@ -1377,7 +1464,7 @@ export class AndorraAgentEngine {
1377
1464
  beforeSnapshot = await readFileSnapshot(target);
1378
1465
  },
1379
1466
  } : {}),
1380
- onCommandOutput: commandTap.push,
1467
+ onCommandOutput,
1381
1468
  });
1382
1469
  // Claim invocation-owned image bytes before any hook or event sink
1383
1470
  // can suspend us. Only the original execution output can claim them.
@@ -1393,9 +1480,12 @@ export class AndorraAgentEngine {
1393
1480
  isError = true;
1394
1481
  if (error instanceof FileReadRequiredError)
1395
1482
  refusal = error.refusal;
1396
- output = operationSignal.aborted
1397
- ? `Interrupted by user. This tool may have partially completed; inspect its effects before retrying. It was not automatically replayed.\n${error instanceof Error ? error.message : 'Tool interrupted'}`
1398
- : `Tool error: ${error instanceof Error ? error.message : 'unknown error'}`;
1483
+ steered = steerCut?.aborted === true && !operationSignal.aborted;
1484
+ output = steered
1485
+ ? steeredOutput(monotonicNow() - steerStartedAt, printed)
1486
+ : operationSignal.aborted
1487
+ ? `Interrupted by user. This tool may have partially completed; inspect its effects before retrying. It was not automatically replayed.\n${error instanceof Error ? error.message : 'Tool interrupted'}`
1488
+ : `Tool error: ${error instanceof Error ? error.message : 'unknown error'}`;
1399
1489
  }
1400
1490
  commandTap.stop();
1401
1491
  signal.throwIfAborted();
@@ -1460,7 +1550,7 @@ export class AndorraAgentEngine {
1460
1550
  ? undefined : callFileDiff(beforeSnapshot, afterSnapshot);
1461
1551
  // A stop that interrupted the call is not a reliability failure: the capture contract
1462
1552
  // excludes it, and counting it would blame the tool for the user's pause.
1463
- if (isError && !operationSignal.aborted)
1553
+ if (isError && !operationSignal.aborted && !steered)
1464
1554
  recordToolFailure(result.telemetry, entry.call.name);
1465
1555
  if (!isError && mutation !== undefined) {
1466
1556
  recordEdit(result.telemetry, mutation, !editExisted);
@@ -1469,7 +1559,7 @@ export class AndorraAgentEngine {
1469
1559
  }
1470
1560
  // A suite that ran and failed is still a test run: the category answers what the work was,
1471
1561
  // not whether it passed. Only a user interruption leaves the command unfinished.
1472
- if (!operationSignal.aborted && command !== undefined && isTestCommandLine(command))
1562
+ if (!operationSignal.aborted && !steered && command !== undefined && isTestCommandLine(command))
1473
1563
  recordTestCommand(result.telemetry);
1474
1564
  const workedMs = elapsedMs(startedAt);
1475
1565
  const waitedMs = closeUserWait();
@@ -1483,7 +1573,7 @@ export class AndorraAgentEngine {
1483
1573
  });
1484
1574
  // A filtered observation is partial evidence by construction, so it is reported truncated:
1485
1575
  // no completion shortcut may rest on it, and the decision snapshot sees the real output.
1486
- return { call: entry.call, output: normalized, isError, executionSucceeded, ...(refusal ? { refusal } : {}), truncated: filtered !== undefined || rawOutput.length > 24_000 || publicOutput.length > 24_000 || publicOutput !== rawOutput, decisionOutput: boundedPublicOutput, ...(!isError && images?.length ? { images } : {}) };
1576
+ return { call: entry.call, output: normalized, isError, executionSucceeded, ...(steered ? { steered } : {}), ...(refusal ? { refusal } : {}), truncated: filtered !== undefined || rawOutput.length > 24_000 || publicOutput.length > 24_000 || publicOutput !== rawOutput, decisionOutput: boundedPublicOutput, ...(!isError && images?.length ? { images } : {}) };
1487
1577
  };
1488
1578
  const finishTurn = async () => {
1489
1579
  if (fatalError || result.status === 'succeeded' || result.reason)
@@ -1738,8 +1828,11 @@ export class AndorraAgentEngine {
1738
1828
  // The reply is sent back, but what it said is still the user's to read: it is often a
1739
1829
  // request only they can act on (sign in, approve, answer), and a tool-calling turn shows
1740
1830
  // its text the same way. Without this the transcript held only the "Continuing" notice.
1741
- if (response.text.trim())
1742
- await emit('agent.message', { text: response.text });
1831
+ // A completion written as text instead of complete_agent is sent back below; the transcript
1832
+ // shows what the model said and a note, never the envelope's raw JSON (run 3a8378f0).
1833
+ const shown = withoutTrailingEnvelope(response.text, SENT_BACK_ENVELOPE_NOTE);
1834
+ if (shown.trim())
1835
+ await emit('agent.message', { text: shown });
1743
1836
  forceToolCall = true;
1744
1837
  stall = { toolCallDropped: dropped, forcedToolCall: true };
1745
1838
  const available = [...tools.filter(tool => tool.providerVisible !== false).map(tool => tool.name), COMPLETION_TOOL];
@@ -1779,18 +1872,38 @@ export class AndorraAgentEngine {
1779
1872
  // would end the run on `maxIterations` with no answer at all. Every gate is waived there.
1780
1873
  const lastIteration = limits.maxIterations !== undefined && iteration >= limits.maxIterations;
1781
1874
  const asked = lastIteration ? { summary: MAX_GATE_ASKS, todos: MAX_GATE_ASKS } : gateAsks;
1875
+ // Idle only if nothing ran since the last send-back for unfinished work; any tool call in
1876
+ // between is the agent still working, and the count starts again.
1877
+ const idleUnfinishedAsks = unfinishedAskedAtToolCalls === result.toolCalls ? unfinishedIdleAsks : 0;
1782
1878
  const gate = acted && parsedCompletion?.outcome !== undefined && options.finalAnswerOutcomes?.includes(parsedCompletion.outcome)
1783
- ? finalAnswerGate({ summaryStoodIn: coercionNotes.includes(OUTPUT_STOOD_IN_NOTE), todos: todoStore.snapshot(), asked }) : undefined;
1879
+ ? finalAnswerGate({
1880
+ summaryStoodIn: coercionNotes.includes(OUTPUT_STOOD_IN_NOTE), summary: parsedCompletion.summary, todos: todoStore.snapshot(), asked,
1881
+ ...(parsedCompletion.remaining ? { remaining: parsedCompletion.remaining } : {}),
1882
+ idleUnfinishedAsks: lastIteration ? MAX_IDLE_UNFINISHED_ASKS : idleUnfinishedAsks,
1883
+ timeLeftMs: budget.remainingMs(),
1884
+ }) : undefined;
1784
1885
  if (gate?.gates.length) {
1785
1886
  for (const id of gate.gates)
1786
- gateAsks[id] = (gateAsks[id] ?? 0) + 1;
1887
+ if (id !== 'unfinished')
1888
+ gateAsks[id] = (gateAsks[id] ?? 0) + 1;
1889
+ if (gate.gates.includes('unfinished')) {
1890
+ unfinishedIdleAsks = idleUnfinishedAsks + 1;
1891
+ unfinishedAskedAtToolCalls = result.toolCalls;
1892
+ }
1787
1893
  messages.push({ role: 'user', content: gate.message });
1788
1894
  await emit('agent.completion.rejected', { reason: gate.message, source: response.completionSource, gates: gate.gates });
1789
1895
  await emit('agent.turn.completed', { iteration, toolCalls: 0, continued: true });
1790
1896
  return { continue: true, guidanceInjected: true };
1791
1897
  }
1792
- if (gate?.waived.length)
1793
- await emit('agent.completion.gate.waived', { gates: gate.waived, source: response.completionSource, reason: lastIteration ? 'maxIterations' : 'asksSpent' });
1898
+ // A run that ends with work it reported as unfinished says so in its record, with why the
1899
+ // host let it end: nothing more it could do without the user, no time left, or no turn left.
1900
+ if (gate?.waived.length) {
1901
+ await emit('agent.completion.gate.waived', {
1902
+ gates: gate.waived, source: response.completionSource,
1903
+ reason: lastIteration ? 'maxIterations' : gate.unfinishedWaiver ?? 'asksSpent',
1904
+ ...(gate.waived.includes('unfinished') ? { remaining: parsedCompletion?.remaining?.length ?? 0, openTodos: todoStore.snapshot().filter(todo => todo.status !== 'completed').length } : {}),
1905
+ });
1906
+ }
1794
1907
  if (parsedCompletion && coercionNotes.length)
1795
1908
  await emit('agent.completion.coerced', { notes: coercionNotes, source: response.completionSource });
1796
1909
  const candidateText = !explicit ? [...outputPartials, response.text].join('') : response.text;
@@ -1883,7 +1996,7 @@ export class AndorraAgentEngine {
1883
1996
  try {
1884
1997
  const normalized = entry.tool.prepareArguments ? entry.tool.prepareArguments(entry.args) : entry.args;
1885
1998
  const validatorTool = { ...entry.tool, parameters: entry.tool.validationParameters ?? entry.tool.parameters };
1886
- if (!validateExtendedToolSchema(validatorTool.parameters, normalized ?? {})) {
1999
+ if (!await validateExtendedToolSchema(validatorTool.parameters, normalized ?? {})) {
1887
2000
  const validation = validateInitialModelToolInput(normalized ?? {}, { metadata: { name: entry.tool.name }, inputSchema: validatorTool.parameters });
1888
2001
  if (validation)
1889
2002
  throw new Error(getInitialInputValidationModelContent(validation));
@@ -1911,9 +2024,10 @@ export class AndorraAgentEngine {
1911
2024
  }
1912
2025
  }
1913
2026
  try {
2027
+ watchBatchSteer();
1914
2028
  const item = await runPrepared(entry);
1915
2029
  finalized.push(item);
1916
- if (!operationSignal.aborted)
2030
+ if (!operationSignal.aborted && !item.steered)
1917
2031
  recordFailure(item);
1918
2032
  return { id: call.id, content: item.output, success: !item.isError, progress: item.executionSucceeded === true && !isMetadataCall(item.call) };
1919
2033
  }
@@ -1923,6 +2037,7 @@ export class AndorraAgentEngine {
1923
2037
  }
1924
2038
  },
1925
2039
  commitToolResults: async () => {
2040
+ endBatchSteer();
1926
2041
  finalized.sort((a, b) => response.toolCalls.indexOf(a.call) - response.toolCalls.indexOf(b.call));
1927
2042
  return finishTurn();
1928
2043
  },
@@ -0,0 +1,20 @@
1
+ interface CompoundEntry {
2
+ start: number;
3
+ size: number;
4
+ }
5
+ export interface CompoundFile {
6
+ /** Streams directly under the root storage, by name. */
7
+ streams: Map<string, CompoundEntry>;
8
+ read(entry: CompoundEntry): Buffer;
9
+ }
10
+ /** Open a Compound File Binary container. Throws when its structure cannot be followed. */
11
+ export declare function openCompoundFile(bytes: Buffer): CompoundFile;
12
+ /**
13
+ * Text of a legacy Word document, or undefined when the compound file holds something else
14
+ * (an `.xls`, a `.ppt`, an `.msi`), so the caller can report it as the binary file it is.
15
+ */
16
+ export declare function extractDoc(bytes: Buffer): {
17
+ text: string;
18
+ notes: string[];
19
+ } | undefined;
20
+ export {};