@andorra-labs/code 0.1.9 → 0.1.11

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 (212) hide show
  1. package/README.md +28 -208
  2. package/THIRD_PARTY_NOTICES.md +15 -0
  3. package/dist/src/agent-execution.js +56 -0
  4. package/dist/src/app-server/protocol.d.ts +109 -1
  5. package/dist/src/app-server/protocol.js +8 -1
  6. package/dist/src/app-server.d.ts +59 -1
  7. package/dist/src/app-server.js +418 -63
  8. package/dist/src/auth/index.d.ts +1 -1
  9. package/dist/src/auth/index.js +1 -1
  10. package/dist/src/auth/store.d.ts +17 -1
  11. package/dist/src/auth/store.js +25 -2
  12. package/dist/src/automation-service.js +1 -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 +255 -33
  16. package/dist/src/browser-ui/index.html +9 -9
  17. package/dist/src/browser-ui/style.css +110 -65
  18. package/dist/src/browser-ui/tokens.css +27 -26
  19. package/dist/src/cli.js +10 -5
  20. package/dist/src/coding-tools.d.ts +24 -0
  21. package/dist/src/coding-tools.js +71 -8
  22. package/dist/src/command-screens.js +1 -1
  23. package/dist/src/commands.d.ts +1 -1
  24. package/dist/src/commands.js +2 -2
  25. package/dist/src/completion-gates.d.ts +42 -7
  26. package/dist/src/completion-gates.js +55 -9
  27. package/dist/src/completion.d.ts +9 -1
  28. package/dist/src/completion.js +20 -2
  29. package/dist/src/dashboard-view.js +2 -2
  30. package/dist/src/deadline.js +4 -0
  31. package/dist/src/decision/checks.js +1 -1
  32. package/dist/src/file-diff.d.ts +105 -0
  33. package/dist/src/file-diff.js +244 -0
  34. package/dist/src/graph-manager-chat.js +4 -4
  35. package/dist/src/graph-runner.js +39 -2
  36. package/dist/src/graph-sync.d.ts +8 -0
  37. package/dist/src/graph-sync.js +54 -3
  38. package/dist/src/graph-tool.js +1 -1
  39. package/dist/src/graph-ui/app.js +303 -129
  40. package/dist/src/graph-ui/controls.css +43 -22
  41. package/dist/src/graph-ui/controls.js +31 -1
  42. package/dist/src/graph-ui/embed.js +56 -7
  43. package/dist/src/graph-ui/icons.js +5 -0
  44. package/dist/src/graph-ui/index.html +3 -3
  45. package/dist/src/graph-ui/manager-state.js +2 -2
  46. package/dist/src/graph-ui/manager.css +19 -18
  47. package/dist/src/graph-ui/manager.js +5 -5
  48. package/dist/src/graph-ui/skill-picker.js +5 -5
  49. package/dist/src/graph-ui/studio-canvas.js +16 -16
  50. package/dist/src/graph-ui/studio.css +18 -15
  51. package/dist/src/graph-ui/studio.js +99 -42
  52. package/dist/src/graph-ui/style.css +125 -80
  53. package/dist/src/graph-ui/theme.js +2 -2
  54. package/dist/src/graph-ui/tokens.css +33 -29
  55. package/dist/src/graphs.d.ts +10 -3
  56. package/dist/src/graphs.js +15 -4
  57. package/dist/src/mcp.d.ts +75 -0
  58. package/dist/src/mcp.js +240 -8
  59. package/dist/src/membership-errors.d.ts +7 -1
  60. package/dist/src/membership-errors.js +9 -3
  61. package/dist/src/provider-keys.d.ts +5 -1
  62. package/dist/src/provider-keys.js +7 -3
  63. package/dist/src/provider-settings.d.ts +4 -1
  64. package/dist/src/provider-settings.js +46 -5
  65. package/dist/src/pull-requests.d.ts +42 -6
  66. package/dist/src/pull-requests.js +11 -3
  67. package/dist/src/qa/guidance.js +6 -19
  68. package/dist/src/qa/index.d.ts +0 -2
  69. package/dist/src/qa/index.js +0 -2
  70. package/dist/src/qa/profile/QaProfile.d.ts +5 -1
  71. package/dist/src/qa/profile/QaProfile.js +6 -2
  72. package/dist/src/qa/tools.d.ts +19 -1
  73. package/dist/src/qa/tools.js +20 -145
  74. package/dist/src/react-runtime.js +134 -16
  75. package/dist/src/read-document-doc.d.ts +20 -0
  76. package/dist/src/read-document-doc.js +524 -0
  77. package/dist/src/read-document-docx.d.ts +21 -0
  78. package/dist/src/read-document-docx.js +584 -0
  79. package/dist/src/read-document-text.d.ts +29 -0
  80. package/dist/src/read-document-text.js +67 -0
  81. package/dist/src/read-document-tool.d.ts +48 -0
  82. package/dist/src/read-document-tool.js +162 -0
  83. package/dist/src/read-document.d.ts +78 -0
  84. package/dist/src/read-document.js +353 -0
  85. package/dist/src/read-image.d.ts +29 -2
  86. package/dist/src/read-image.js +42 -17
  87. package/dist/src/remote/engine-pool.js +18 -6
  88. package/dist/src/runtime.d.ts +19 -0
  89. package/dist/src/runtime.js +10 -1
  90. package/dist/src/screen-selection.d.ts +38 -0
  91. package/dist/src/screen-selection.js +103 -0
  92. package/dist/src/session-changes.d.ts +122 -0
  93. package/dist/src/session-changes.js +804 -0
  94. package/dist/src/side-panel.d.ts +6 -1
  95. package/dist/src/side-panel.js +12 -10
  96. package/dist/src/skills/bundled/create-skill/SKILL.md +1 -1
  97. package/dist/src/skills/bundled/diagram/SKILL.md +1 -1
  98. package/dist/src/skills/bundled/graph-manager/SKILL.md +37 -3
  99. package/dist/src/skills/bundled/graph-manager/patterns.md +27 -0
  100. package/dist/src/skills/bundled/provenance.json +4 -4
  101. package/dist/src/skills/runtime-skills.js +3 -3
  102. package/dist/src/stall-recovery.d.ts +15 -0
  103. package/dist/src/stall-recovery.js +17 -0
  104. package/dist/src/telemetry/schema.d.ts +1 -1
  105. package/dist/src/telemetry/schema.js +1 -2
  106. package/dist/src/terminal-ui.d.ts +64 -20
  107. package/dist/src/terminal-ui.js +312 -82
  108. package/dist/src/time-limit.d.ts +53 -0
  109. package/dist/src/time-limit.js +79 -0
  110. package/dist/src/tool-diff-stats.d.ts +9 -0
  111. package/dist/src/tool-diff-stats.js +20 -0
  112. package/dist/src/tool-names.d.ts +1 -1
  113. package/dist/src/tool-result-filter.js +1 -1
  114. package/dist/src/tools.js +118 -9
  115. package/dist/src/transcript.d.ts +11 -0
  116. package/dist/src/transcript.js +15 -3
  117. package/dist/src/types.d.ts +12 -0
  118. package/dist/src/usage-analytics.d.ts +3 -1
  119. package/dist/src/usage-analytics.js +16 -2
  120. package/package.json +6 -26
  121. package/dist/src/qa/api/http-runner.d.ts +0 -3
  122. package/dist/src/qa/api/http-runner.js +0 -47
  123. package/dist/src/qa/git/ChangeDetector.d.ts +0 -26
  124. package/dist/src/qa/git/ChangeDetector.js +0 -177
  125. package/dist/src/qa/git/DiffReviewer.d.ts +0 -28
  126. package/dist/src/qa/git/DiffReviewer.js +0 -115
  127. package/dist/src/qa/orchestrator/ChangeClassifier.d.ts +0 -14
  128. package/dist/src/qa/orchestrator/ChangeClassifier.js +0 -28
  129. package/dist/src/qa/orchestrator/MergeGate.d.ts +0 -14
  130. package/dist/src/qa/orchestrator/MergeGate.js +0 -40
  131. package/dist/src/qa/orchestrator/QaOrchestrator.d.ts +0 -79
  132. package/dist/src/qa/orchestrator/QaOrchestrator.js +0 -373
  133. package/dist/src/qa/runners/CommandRunner.d.ts +0 -22
  134. package/dist/src/qa/runners/CommandRunner.js +0 -96
  135. package/dist/src/qa/runners/TestRunner.d.ts +0 -21
  136. package/dist/src/qa/runners/TestRunner.js +0 -66
  137. package/dist/src/qa/runtime/RuntimeSmoke.d.ts +0 -11
  138. package/dist/src/qa/runtime/RuntimeSmoke.js +0 -78
  139. package/dist/src/qa/runtime-detect.d.ts +0 -10
  140. package/dist/src/qa/runtime-detect.js +0 -72
  141. package/dist/src/qa/security/DependencyScanner.d.ts +0 -19
  142. package/dist/src/qa/security/DependencyScanner.js +0 -167
  143. package/dist/src/qa/security/SecretScanner.d.ts +0 -3
  144. package/dist/src/qa/security/SecretScanner.js +0 -55
  145. package/docs/README.md +0 -36
  146. package/docs/agents/README.md +0 -62
  147. package/docs/agents/install-for-agents.md +0 -56
  148. package/docs/agents/mcp-server.md +0 -212
  149. package/docs/agents/subagent-mode.md +0 -149
  150. package/docs/concepts/README.md +0 -47
  151. package/docs/concepts/jev-actionable-routing.md +0 -113
  152. package/docs/concepts/jev-decision-thresholds.md +0 -412
  153. package/docs/concepts/jev-efficiency.md +0 -217
  154. package/docs/concepts/jev-eval-2026-11-01.md +0 -78
  155. package/docs/concepts/limits.md +0 -52
  156. package/docs/concepts/memory.md +0 -10
  157. package/docs/concepts/security.md +0 -50
  158. package/docs/concepts/workspace-instructions.md +0 -29
  159. package/docs/getting-started/README.md +0 -82
  160. package/docs/getting-started/accounts.md +0 -78
  161. package/docs/getting-started/configure-providers.md +0 -132
  162. package/docs/guides/README.md +0 -13
  163. package/docs/guides/browser.md +0 -39
  164. package/docs/guides/desktop-app.md +0 -414
  165. package/docs/guides/extensions.md +0 -102
  166. package/docs/guides/graph-builder.md +0 -116
  167. package/docs/guides/headless.md +0 -46
  168. package/docs/guides/tui.md +0 -75
  169. package/docs/guides/update.md +0 -70
  170. package/docs/guides/web-search.md +0 -51
  171. package/docs/guides/windows-code-signing.md +0 -319
  172. package/docs/llms.txt +0 -45
  173. package/docs/reference/README.md +0 -7
  174. package/docs/reference/cli.md +0 -76
  175. package/docs/reference/config.md +0 -91
  176. package/docs/reference/slash-commands.md +0 -59
  177. package/docs/superpowers/plans/2026-11-01-claude-console-sign-in.md +0 -111
  178. package/docs/superpowers/plans/2026-11-01-jev-node-opt-in.md +0 -910
  179. package/docs/superpowers/plans/2026-11-02-workflow-pane.md +0 -398
  180. package/docs/superpowers/plans/2026-11-06-graph-soft-delete.md +0 -125
  181. package/docs/superpowers/plans/2026-11-09-orchestrator-delegation.md +0 -295
  182. package/docs/superpowers/plans/2026-11-13-graph-manager-chat.md +0 -203
  183. package/docs/superpowers/plans/2026-11-14-jev-fair-use-pricing.md +0 -79
  184. package/docs/superpowers/specs/2026-10-31-work-line-summary-design.md +0 -50
  185. package/docs/superpowers/specs/2026-11-01-claude-console-sign-in-design.md +0 -176
  186. package/docs/superpowers/specs/2026-11-01-jev-node-opt-in-design.md +0 -164
  187. package/docs/superpowers/specs/2026-11-01-pr-section-design.md +0 -111
  188. package/docs/superpowers/specs/2026-11-02-workflow-pane-design.md +0 -130
  189. package/docs/superpowers/specs/2026-11-06-bundled-skills-design.md +0 -206
  190. package/docs/superpowers/specs/2026-11-09-orchestrator-delegation-design.md +0 -291
  191. package/docs/superpowers/specs/2026-11-13-graph-manager-chat-design.md +0 -182
  192. package/docs/superpowers/specs/2026-11-14-jev-fair-use-pricing-design.md +0 -156
  193. package/scripts/jev-efficiency-eval.mjs +0 -187
  194. package/scripts/jev-efficiency-live.mjs +0 -193
  195. package/scripts/zcode-engine-replay.mjs +0 -223
  196. package/tests/agent-centric-mcp-test-plan.md +0 -208
  197. package/tests/analytics-settings-test-plan.md +0 -165
  198. package/tests/browser-cli-smoke.mjs +0 -276
  199. package/tests/browser-test-plan.md +0 -280
  200. package/tests/chat-side-panel-test-plan.md +0 -309
  201. package/tests/decision-engine-test-plan.md +0 -163
  202. package/tests/default-active-jev-test-plan.md +0 -85
  203. package/tests/harness-extensions-test-plan.md +0 -113
  204. package/tests/jev-all-decisions-test-plan.md +0 -156
  205. package/tests/jev-efficiency/criteria.json +0 -158
  206. package/tests/jev-efficiency/workloads.mjs +0 -242
  207. package/tests/jev-efficiency-test-plan.md +0 -198
  208. package/tests/permissions-sandbox-probe.mjs +0 -74
  209. package/tests/permissions-test-plan.md +0 -191
  210. package/tests/product-telemetry-test-plan.md +0 -536
  211. package/tests/thinking-stream-preview-test-plan.md +0 -136
  212. package/tests/zcode-react-engine-test-plan.md +0 -396
@@ -9,7 +9,7 @@ import { andorraIsContextOverflow } from '../vendor/engine/runtime/ai/utils/over
9
9
  import { toEngineResponse, engineModel } from './engine/protocol.js';
10
10
  import { ProviderRequestError } from './providers.js';
11
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';
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';
@@ -22,7 +22,7 @@ import { stat } from 'node:fs/promises';
22
22
  import { isAbsolute, relative, resolve } from 'node:path';
23
23
  import { createRunTelemetry, recordEdit, recordTestCommand, recordToolFailure, recordToolUse } from './telemetry/capture.js';
24
24
  import { isTestCommandLine } from './telemetry/classify.js';
25
- import { diffLineStats, fileDiffTarget, readFileSnapshot } from './tool-diff-stats.js';
25
+ import { callFileDiff, diffLineStats, fileDiffTarget, readFileSnapshot } from './tool-diff-stats.js';
26
26
  import { TodoStore } from './todos.js';
27
27
  import { WIDGET_VALUE_MAX_CHARS } from './widgets.js';
28
28
  import { PreparedSteps, PREPARE_STEPS, boundedDecisionText, permittedContinuation, preparedResponse, postToolGuidance, retrySafe } from './decision/PreparedSteps.js';
@@ -36,6 +36,7 @@ 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';
41
42
  const DEFAULT_AGENT_INSTRUCTIONS = `You are the Andorra Agent in Andorra Code's default graph.
@@ -46,6 +47,8 @@ Issue independent read-only calls together in one turn, and combine related shel
46
47
  Do mechanical or repetitive work by executing code (a shell one-liner or script), not through repeated model-driven edits.
47
48
  Keep tool output small: filter, count, select, or tail instead of feeding whole files or long listings back into context.
48
49
  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.
50
+ 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.
51
+ 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
52
  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
53
  If execution is blocked, report why and use focused static checks. Intake, research and non-runnable tasks follow their assigned scope.`;
51
54
  const SYSTEM = `Follow the configured Agent instruction and completion contract using only the granted capabilities.
@@ -70,6 +73,19 @@ function refusedRequest(error) {
70
73
  const status = typeof direct === 'number' ? direct : Number(/\(HTTP (\d{3})\)/.exec(error instanceof Error ? error.message : '')?.[1]);
71
74
  return [400, 404, 415, 422].includes(status);
72
75
  }
76
+ /** How much of a stopped command's output its observation keeps. */
77
+ const STEERED_OUTPUT_TAIL = 4_000;
78
+ /** The tools whose call a user steer stops: each waits on a process the user may be waiting out. */
79
+ const STEER_STOPPABLE = new Set(['Bash', 'PowerShell', 'PowerShellFast', 'NativeExec', 'bash', 'powershell', 'shell']);
80
+ function steerStoppable(name, args) {
81
+ return STEER_STOPPABLE.has(name) || (name === 'AsyncProcess' && args.action === 'wait');
82
+ }
83
+ /** The observation for a call a steer stopped: why it ended, and what it printed before. */
84
+ function steeredOutput(elapsedMs, printed) {
85
+ const seconds = Math.max(0, Math.round(elapsedMs / 100) / 10);
86
+ const tail = printed.trim();
87
+ 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.'}`;
88
+ }
73
89
  /** Canonical arguments prevent object-key order from disguising an identical side effect. */
74
90
  function actionFingerprint(name, args) {
75
91
  const canonical = (value) => Array.isArray(value) ? value.map(canonical)
@@ -383,6 +399,11 @@ export class AndorraAgentEngine {
383
399
  ? `\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
400
  : '';
385
401
  messages[0].content += completionContract + criteriaContract;
402
+ // A bounded attempt is told so, and told again as the time runs down (time-limit.ts). The
403
+ // default is no wall clock, in which case nothing is added.
404
+ const timeNotices = limits.wallTimeMs ? createTimeLimitNotices(limits.wallTimeMs) : undefined;
405
+ if (limits.wallTimeMs)
406
+ messages[0].content += `\n${timeLimitPrompt(limits.wallTimeMs)}`;
386
407
  // Retained turns render through the one shared renderer: a continued turn's stored task is the
387
408
  // stopped attempt's, the direction the user sent with the continuation is the message this turn
388
409
  // actually answers — dropped here, the CLI's next request would omit what they said — and a
@@ -422,6 +443,9 @@ export class AndorraAgentEngine {
422
443
  if (start >= 0 && end >= 0) {
423
444
  system.content = system.content.slice(0, start) + (options.instructions ? `${guidanceMarker}${options.instructions}` : '') + system.content.slice(end);
424
445
  }
446
+ // The restored prompt states the limit the stopped attempt began with; this one has what
447
+ // was left of it, or a limit configured since, or none.
448
+ system.content = withTimeLimitPrompt(system.content, limits.wallTimeMs);
425
449
  }
426
450
  }
427
451
  else if (!options.subagentId && options.previousConversation?.provider === options.provider && options.previousConversation.model === options.model) {
@@ -831,11 +855,35 @@ export class AndorraAgentEngine {
831
855
  };
832
856
  let prepared = [];
833
857
  let finalized = [];
858
+ // A user steer that lands while this turn's tools run. The model request is already cut off by
859
+ // its own watch (below); a tool batch had none, so a steer sent during `Start-Sleep 60` waited
860
+ // the whole minute before the model read it. While a batch runs, a steer stops the command in
861
+ // flight and skips the calls that have not started, and the next turn reads the message. Only a
862
+ // runtime that reads the shared steering queue listens: a delegated child never reads it.
863
+ let batchSteer;
864
+ const watchBatchSteer = () => {
865
+ if (batchSteer || !control || !options.getSteeringMessages || options.subagentId)
866
+ return;
867
+ const watch = { arrived: false, cut: new AbortController(), stop: () => { } };
868
+ watch.stop = control.onSteer(() => {
869
+ watch.arrived = true;
870
+ watch.cut.abort(new Error('Stopped to read a new message from the user.'));
871
+ });
872
+ batchSteer = watch;
873
+ };
874
+ const endBatchSteer = () => { batchSteer?.stop(); batchSteer = undefined; };
834
875
  let fatalError;
835
876
  let modelResponseReady = false;
836
877
  let completionRejectionEmitted = false;
837
878
  /** Times each final-answer gate has sent a handoff back in this run. */
838
879
  const gateAsks = {};
880
+ /**
881
+ * The unfinished gate has no ask limit while the agent works between its completions. What is
882
+ * counted is the opposite: send-backs in a row that it answered with no tool call at all,
883
+ * measured against the tool-call count at the last send-back.
884
+ */
885
+ let unfinishedIdleAsks = 0;
886
+ let unfinishedAskedAtToolCalls;
839
887
  const engineState = { stopHookContinuationCount: continuationState?.engineState?.stopHookContinuationCount ?? continuationState?.zcodeState?.stopHookContinuationCount ?? 0, outputTokenContinuationCount: continuationState?.engineState?.outputTokenContinuationCount ?? continuationState?.zcodeState?.outputTokenContinuationCount ?? 0 };
840
888
  let outputPartials = [...(continuationState?.outputPartials ?? [])];
841
889
  let overflowRecoveries = 0;
@@ -880,6 +928,7 @@ export class AndorraAgentEngine {
880
928
  prepared = [];
881
929
  finalized = [];
882
930
  executionCalls = 0;
931
+ endBatchSteer();
883
932
  response = { text: '', toolCalls: [], completionSource: 'final_text' };
884
933
  if (limits.maxIterations !== undefined && iteration > limits.maxIterations) {
885
934
  result.reason = 'maxIterations';
@@ -943,6 +992,12 @@ export class AndorraAgentEngine {
943
992
  replacePostflightGuidance(arrivedPostflight.guidance);
944
993
  arrivedPostflight = undefined;
945
994
  }
995
+ // Asked from the budget itself, so time the run spent waiting on a person is not counted.
996
+ const timeNotice = timeNotices?.next(budget.remainingMs());
997
+ if (timeNotice) {
998
+ messages.push({ role: 'user', content: timeNotice.text });
999
+ await emit('agent.time_limit.notice', { stage: timeNotice.stage, remainingMs: budget.remainingMs(), limitMs: limits.wallTimeMs });
1000
+ }
946
1001
  refreshTodoContext();
947
1002
  const prunedImages = pruneHistoricalImages(messages);
948
1003
  if (prunedImages)
@@ -1278,6 +1333,21 @@ export class AndorraAgentEngine {
1278
1333
  await emit('node.tool.skipped', { name: entry.call.name, toolCallId: entry.call.id, output });
1279
1334
  return { call: entry.call, output, isError: false };
1280
1335
  }
1336
+ if (batchSteer?.arrived) {
1337
+ if (isTodoCall(entry.call))
1338
+ todoCalls--;
1339
+ else if (isPreparedPlanCall(entry.call))
1340
+ preparedPlanCalls--;
1341
+ else if (isRestorationCall(entry.call))
1342
+ restorationCalls--;
1343
+ else if (isWidgetCall(entry.call))
1344
+ widgetCalls--;
1345
+ else if (options.budget)
1346
+ options.budget.toolCalls--;
1347
+ const output = 'Not executed: the user sent a new message before this call started. Read it, then decide whether this call is still needed.';
1348
+ await emit('node.tool.skipped', { name: entry.call.name, toolCallId: entry.call.id, output, reason: 'steer' });
1349
+ return { call: entry.call, output, isError: false, steered: true };
1350
+ }
1281
1351
  if (!isMetadataCall(entry.call)) {
1282
1352
  result.toolCalls++;
1283
1353
  recordToolUse(result.telemetry, entry.call.name, false);
@@ -1340,13 +1410,25 @@ export class AndorraAgentEngine {
1340
1410
  const commandTap = createCommandOutputTap(chunk => {
1341
1411
  void emit('node.tool.output', { name: entry.call.name, toolCallId: entry.call.id, output: chunk }).catch(() => { });
1342
1412
  });
1413
+ // Only a call that waits on a process is stopped by a steer: a shell command, a native
1414
+ // executable, or a wait on a background job (the job itself keeps running). A file edit
1415
+ // or a delegated subagent runs to its end, so a steer never leaves half-applied work.
1416
+ const steerCut = batchSteer !== undefined && steerStoppable(entry.call.name, args) ? batchSteer.cut.signal : undefined;
1417
+ const steerStartedAt = monotonicNow();
1418
+ let printed = '';
1419
+ const onCommandOutput = (chunk) => {
1420
+ if (steerCut)
1421
+ printed = (printed + chunk).slice(-STEERED_OUTPUT_TAIL);
1422
+ commandTap.push(chunk);
1423
+ };
1424
+ let steered = false;
1343
1425
  try {
1344
1426
  output = await tool.execute(args, {
1345
1427
  ...context,
1346
1428
  // A child invocation retains its lifetime; its own operations subscribe
1347
1429
  // to the same control and pause without discarding the child history.
1348
1430
  ...(entry.call.name === 'spawn_subagent' ? {} : {
1349
- signal: operationSignal,
1431
+ signal: steerCut ? AbortSignal.any([operationSignal, steerCut]) : operationSignal,
1350
1432
  userSignal: control ? AbortSignal.any([context.userSignal ?? signal, operationSignal]) : context.userSignal,
1351
1433
  }),
1352
1434
  onApprovalEvent: (type, data) => {
@@ -1377,7 +1459,7 @@ export class AndorraAgentEngine {
1377
1459
  beforeSnapshot = await readFileSnapshot(target);
1378
1460
  },
1379
1461
  } : {}),
1380
- onCommandOutput: commandTap.push,
1462
+ onCommandOutput,
1381
1463
  });
1382
1464
  // Claim invocation-owned image bytes before any hook or event sink
1383
1465
  // can suspend us. Only the original execution output can claim them.
@@ -1393,9 +1475,12 @@ export class AndorraAgentEngine {
1393
1475
  isError = true;
1394
1476
  if (error instanceof FileReadRequiredError)
1395
1477
  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'}`;
1478
+ steered = steerCut?.aborted === true && !operationSignal.aborted;
1479
+ output = steered
1480
+ ? steeredOutput(monotonicNow() - steerStartedAt, printed)
1481
+ : operationSignal.aborted
1482
+ ? `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'}`
1483
+ : `Tool error: ${error instanceof Error ? error.message : 'unknown error'}`;
1399
1484
  }
1400
1485
  commandTap.stop();
1401
1486
  signal.throwIfAborted();
@@ -1450,12 +1535,17 @@ export class AndorraAgentEngine {
1450
1535
  await emit('efficiency.tool_result.filtered', { name: entry.call.name, toolCallId: entry.call.id, format: filtered.format, originalChars: filtered.originalChars, keptChars: filtered.keptChars, omittedLines: filtered.omittedLines, reason: 'filtered' });
1451
1536
  // A failed call changed nothing measurable, so the figures belong to the completed event
1452
1537
  // alone — the row shows its error without a diff it did not make.
1538
+ const afterSnapshot = isError || snapshotTarget === undefined ? undefined : await readFileSnapshot(snapshotTarget);
1453
1539
  const diffStats = isError || snapshotTarget === undefined
1454
1540
  ? undefined
1455
- : diffLineStats(beforeSnapshot, await readFileSnapshot(snapshotTarget));
1541
+ : diffLineStats(beforeSnapshot, afterSnapshot);
1542
+ // The call's own change to the file, numbered on both sides, for the transcript row. Bounded: the row
1543
+ // shows the start of the diff and how much more there is, and the journal keeps the event.
1544
+ const editDiff = diffStats === undefined || beforeSnapshot === undefined || afterSnapshot === undefined
1545
+ ? undefined : callFileDiff(beforeSnapshot, afterSnapshot);
1456
1546
  // A stop that interrupted the call is not a reliability failure: the capture contract
1457
1547
  // excludes it, and counting it would blame the tool for the user's pause.
1458
- if (isError && !operationSignal.aborted)
1548
+ if (isError && !operationSignal.aborted && !steered)
1459
1549
  recordToolFailure(result.telemetry, entry.call.name);
1460
1550
  if (!isError && mutation !== undefined) {
1461
1551
  recordEdit(result.telemetry, mutation, !editExisted);
@@ -1464,7 +1554,7 @@ export class AndorraAgentEngine {
1464
1554
  }
1465
1555
  // A suite that ran and failed is still a test run: the category answers what the work was,
1466
1556
  // not whether it passed. Only a user interruption leaves the command unfinished.
1467
- if (!operationSignal.aborted && command !== undefined && isTestCommandLine(command))
1557
+ if (!operationSignal.aborted && !steered && command !== undefined && isTestCommandLine(command))
1468
1558
  recordTestCommand(result.telemetry);
1469
1559
  const workedMs = elapsedMs(startedAt);
1470
1560
  const waitedMs = closeUserWait();
@@ -1474,10 +1564,11 @@ export class AndorraAgentEngine {
1474
1564
  toolCallId: entry.call.id,
1475
1565
  durationMs: workedMs === undefined ? undefined : Math.max(0, workedMs - waitedMs),
1476
1566
  ...(diffStats === undefined ? {} : { linesAdded: diffStats.linesAdded, linesRemoved: diffStats.linesRemoved }),
1567
+ ...(editDiff === undefined ? {} : { fileDiff: editDiff }),
1477
1568
  });
1478
1569
  // A filtered observation is partial evidence by construction, so it is reported truncated:
1479
1570
  // no completion shortcut may rest on it, and the decision snapshot sees the real output.
1480
- 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 } : {}) };
1571
+ 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 } : {}) };
1481
1572
  };
1482
1573
  const finishTurn = async () => {
1483
1574
  if (fatalError || result.status === 'succeeded' || result.reason)
@@ -1729,6 +1820,11 @@ export class AndorraAgentEngine {
1729
1820
  // A bare "continue" got the same discarded call back three times in a row (run 8a245b0f):
1730
1821
  // say what this node can and cannot call, and require a tool call in the next response.
1731
1822
  const dropped = suspectedDroppedToolCall(response);
1823
+ // The reply is sent back, but what it said is still the user's to read: it is often a
1824
+ // request only they can act on (sign in, approve, answer), and a tool-calling turn shows
1825
+ // its text the same way. Without this the transcript held only the "Continuing" notice.
1826
+ if (response.text.trim())
1827
+ await emit('agent.message', { text: response.text });
1732
1828
  forceToolCall = true;
1733
1829
  stall = { toolCallDropped: dropped, forcedToolCall: true };
1734
1830
  const available = [...tools.filter(tool => tool.providerVisible !== false).map(tool => tool.name), COMPLETION_TOOL];
@@ -1768,18 +1864,38 @@ export class AndorraAgentEngine {
1768
1864
  // would end the run on `maxIterations` with no answer at all. Every gate is waived there.
1769
1865
  const lastIteration = limits.maxIterations !== undefined && iteration >= limits.maxIterations;
1770
1866
  const asked = lastIteration ? { summary: MAX_GATE_ASKS, todos: MAX_GATE_ASKS } : gateAsks;
1867
+ // Idle only if nothing ran since the last send-back for unfinished work; any tool call in
1868
+ // between is the agent still working, and the count starts again.
1869
+ const idleUnfinishedAsks = unfinishedAskedAtToolCalls === result.toolCalls ? unfinishedIdleAsks : 0;
1771
1870
  const gate = acted && parsedCompletion?.outcome !== undefined && options.finalAnswerOutcomes?.includes(parsedCompletion.outcome)
1772
- ? finalAnswerGate({ summaryStoodIn: coercionNotes.includes(OUTPUT_STOOD_IN_NOTE), todos: todoStore.snapshot(), asked }) : undefined;
1871
+ ? finalAnswerGate({
1872
+ summaryStoodIn: coercionNotes.includes(OUTPUT_STOOD_IN_NOTE), summary: parsedCompletion.summary, todos: todoStore.snapshot(), asked,
1873
+ ...(parsedCompletion.remaining ? { remaining: parsedCompletion.remaining } : {}),
1874
+ idleUnfinishedAsks: lastIteration ? MAX_IDLE_UNFINISHED_ASKS : idleUnfinishedAsks,
1875
+ timeLeftMs: budget.remainingMs(),
1876
+ }) : undefined;
1773
1877
  if (gate?.gates.length) {
1774
1878
  for (const id of gate.gates)
1775
- gateAsks[id] = (gateAsks[id] ?? 0) + 1;
1879
+ if (id !== 'unfinished')
1880
+ gateAsks[id] = (gateAsks[id] ?? 0) + 1;
1881
+ if (gate.gates.includes('unfinished')) {
1882
+ unfinishedIdleAsks = idleUnfinishedAsks + 1;
1883
+ unfinishedAskedAtToolCalls = result.toolCalls;
1884
+ }
1776
1885
  messages.push({ role: 'user', content: gate.message });
1777
1886
  await emit('agent.completion.rejected', { reason: gate.message, source: response.completionSource, gates: gate.gates });
1778
1887
  await emit('agent.turn.completed', { iteration, toolCalls: 0, continued: true });
1779
1888
  return { continue: true, guidanceInjected: true };
1780
1889
  }
1781
- if (gate?.waived.length)
1782
- await emit('agent.completion.gate.waived', { gates: gate.waived, source: response.completionSource, reason: lastIteration ? 'maxIterations' : 'asksSpent' });
1890
+ // A run that ends with work it reported as unfinished says so in its record, with why the
1891
+ // host let it end: nothing more it could do without the user, no time left, or no turn left.
1892
+ if (gate?.waived.length) {
1893
+ await emit('agent.completion.gate.waived', {
1894
+ gates: gate.waived, source: response.completionSource,
1895
+ reason: lastIteration ? 'maxIterations' : gate.unfinishedWaiver ?? 'asksSpent',
1896
+ ...(gate.waived.includes('unfinished') ? { remaining: parsedCompletion?.remaining?.length ?? 0, openTodos: todoStore.snapshot().filter(todo => todo.status !== 'completed').length } : {}),
1897
+ });
1898
+ }
1783
1899
  if (parsedCompletion && coercionNotes.length)
1784
1900
  await emit('agent.completion.coerced', { notes: coercionNotes, source: response.completionSource });
1785
1901
  const candidateText = !explicit ? [...outputPartials, response.text].join('') : response.text;
@@ -1900,9 +2016,10 @@ export class AndorraAgentEngine {
1900
2016
  }
1901
2017
  }
1902
2018
  try {
2019
+ watchBatchSteer();
1903
2020
  const item = await runPrepared(entry);
1904
2021
  finalized.push(item);
1905
- if (!operationSignal.aborted)
2022
+ if (!operationSignal.aborted && !item.steered)
1906
2023
  recordFailure(item);
1907
2024
  return { id: call.id, content: item.output, success: !item.isError, progress: item.executionSucceeded === true && !isMetadataCall(item.call) };
1908
2025
  }
@@ -1912,6 +2029,7 @@ export class AndorraAgentEngine {
1912
2029
  }
1913
2030
  },
1914
2031
  commitToolResults: async () => {
2032
+ endBatchSteer();
1915
2033
  finalized.sort((a, b) => response.toolCalls.indexOf(a.call) - response.toolCalls.indexOf(b.call));
1916
2034
  return finishTurn();
1917
2035
  },
@@ -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 {};