@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
@@ -6,9 +6,12 @@ import { promisify } from 'node:util';
6
6
  import { StringDecoder } from 'node:string_decoder';
7
7
  import { andorraCreateReadTool, andorraCreateWriteTool, andorraCreateEditTool, andorraCreateFindTool, andorraCreateGrepTool, andorraCreateLsTool, andorraCreateBashTool, andorraCreatePowerShellTool, } from '../vendor/engine/runtime/coding-agent/core/tools/index.js';
8
8
  import { andorraGetToolPath } from '../vendor/engine/runtime/coding-agent/utils/tools-manager.js';
9
+ import { registerEditArgumentPreparer } from './diff-preview.js';
10
+ import { stateKey } from './file-read-key.js';
9
11
  import { defaultShellKind, runShell, runNativeProcess } from './shell.js';
10
12
  import { commandTimingSummary } from './command-metrics.js';
11
13
  import { runPooledPowerShell } from './powershell-pool.js';
14
+ import { withStrayFileNotice } from './stray-files.js';
12
15
  import { assertNotHostKill, assertNotHostKillArgv, hostShellOf } from './host-process-guard.js';
13
16
  import { getQaProcessManager, PERSISTENT_JOBS_SUPPORTED } from './qa/runtime/ProcessManager.js';
14
17
  import { clipText } from './text.js';
@@ -17,7 +20,11 @@ import { FileReadRequiredError } from './tool-errors.js';
17
20
  import { permissionMode, PLAN_MODE_MUTATION_ERROR } from './permissions.js';
18
21
  import { withGrepRegex } from './grep-regex.js';
19
22
  import { claimReadImages, readImageObservation } from './read-image.js';
23
+ import { READ_PDF_RENDER_PAGES, legacyTextObservation, readDocumentObservation } from './read-document-tool.js';
20
24
  const execFileAsync = promisify(execFile);
25
+ // Edit previews use the executor's own argument normalizer. Construction only defines metadata;
26
+ // previewing never invokes the tool executor.
27
+ registerEditArgumentPreparer(andorraCreateEditTool('.').prepareArguments);
21
28
  const excluded = new Set(['.git', 'node_modules', '.andorracode']);
22
29
  const MAX_MODEL_OUTPUT = 24_000;
23
30
  /** Lines returned by one Read call: both the default and the accepted maximum for `limit`. */
@@ -26,6 +33,31 @@ const READ_MAX_LINES = 2000;
26
33
  const READ_MAX_LINE_CHARS = 2000;
27
34
  const SEARCH_FILE_LIMIT = 262_144;
28
35
  const SEARCH_SCAN_LIMIT = 16 * 1024 * 1024;
36
+ /**
37
+ * How long a foreground shell command may run when the call names no timeout.
38
+ *
39
+ * Thirty seconds, the earlier default, is shorter than an ordinary package install, compile or
40
+ * test run: the command was killed and the model had to notice, raise the timeout and start it
41
+ * again from nothing. Two minutes covers those without leaving a hung command unnoticed for long.
42
+ */
43
+ export const SHELL_DEFAULT_TIMEOUT_MS = 120_000;
44
+ export const SHELL_MAX_TIMEOUT_MS = 600_000;
45
+ /**
46
+ * What a timed-out command's error tells the model to do next.
47
+ *
48
+ * The bare "timed out after N ms" says the command was stopped but not that the work is lost, nor
49
+ * which of the two ways forward fits: a longer timeout while one is left to ask for, or a
50
+ * background job once the ceiling is reached.
51
+ */
52
+ export function shellTimeoutGuidance(message, timeout) {
53
+ const marker = /^Shell command timed out after \d+ ms/;
54
+ if (!marker.test(message))
55
+ return message;
56
+ const next = timeout < SHELL_MAX_TIMEOUT_MS
57
+ ? `The command was stopped and its work is not finished. If it only needs more time, run it again with a larger timeout (up to ${SHELL_MAX_TIMEOUT_MS}); for work that can exceed that, start it with AsyncProcess and wait on the job.`
58
+ : 'The command was stopped at the largest foreground timeout and its work is not finished. Start it with AsyncProcess instead and wait on the job.';
59
+ return message.replace(marker, found => `${found}. ${next}`);
60
+ }
29
61
  const sandboxFields = {
30
62
  sandbox_permissions: { type: 'string', enum: ['use_default', 'require_escalated'], description: 'Use the workspace sandbox by default; require_escalated requests host/network access with approval.' },
31
63
  justification: { type: 'string', description: 'Required explanation for an explicit escalation request.' },
@@ -152,10 +184,7 @@ const boolArg = (args, key) => {
152
184
  * entries under the key the canonical tools look up. It must be applied to a path normalized
153
185
  * the same way the policy's safePath normalizes it, or the entries never match.
154
186
  */
155
- export function stateKey(resolved) {
156
- const key = path.resolve(resolved);
157
- return process.platform === 'win32' ? key.toLowerCase() : key;
158
- }
187
+ export { stateKey };
159
188
  function state(context) {
160
189
  context.toolState ??= { fileReads: new Map() };
161
190
  return context.toolState;
@@ -221,8 +250,13 @@ async function requireFreshRead(policy, context, resolved, action) {
221
250
  if (!previous?.complete) {
222
251
  // A suggested offset is only meaningful for the content the model last saw. Re-read first so
223
252
  // a file that changed (or shrank) since that page cannot send the model past its end.
224
- if (!previous)
253
+ if (!previous) {
254
+ // A file the text tools cannot hold (a document, an image, text in another encoding) can be
255
+ // looked at with Read but never becomes a recorded read, so "Read it first" would send the
256
+ // model round in a circle. The strict reader's own refusal is the true answer for those.
257
+ await policy.read(context, resolved);
225
258
  throw new FileReadRequiredError(`${action} requires a complete Read (or complete CodeGraph source) of the existing file first. Read ${path.relative(context.workspace, resolved) || resolved} before modifying it.`);
259
+ }
226
260
  if (!matchesFileRead(previous, await policy.read(context, resolved))) {
227
261
  throw new FileReadRequiredError(`${action} refused a stale file: it changed since the last Read/CodeGraph snapshot. Read it again before modifying.`);
228
262
  }
@@ -444,23 +478,50 @@ export function createCodingTools(policy) {
444
478
  } }),
445
479
  };
446
480
  }
447
- const Read = { ...zTool('Read', `Read a UTF-8 workspace file up to 8 MiB with compact line numbers. One call returns at most ${READ_MAX_LINES} lines: for a longer file, continue with the offset the result reports until you have read the whole file. A complete Read — every line, across calls — is remembered so Write/Edit can reject stale or unseen existing files; do not re-read unchanged files after a successful mutation. An image file (PNG, JPEG, GIF, WebP or BMP, up to 20 MiB) is returned as an image you can see, downscaled when large; use this to look at a rendered frame, plot or screenshot instead of inferring it from pixel statistics. offset and limit do not apply to images.`, { type: 'object', properties: {
481
+ const Read = { ...zTool('Read', `Read a UTF-8 workspace file up to 8 MiB with compact line numbers. One call returns at most ${READ_MAX_LINES} lines: for a longer file, continue with the offset the result reports until you have read the whole file. A complete Read — every line, across calls — is remembered so Write/Edit can reject stale or unseen existing files; do not re-read unchanged files after a successful mutation. An image file (PNG, JPEG, GIF, WebP or BMP, up to 20 MiB) is returned as an image you can see, downscaled when large; use this to look at a rendered frame, plot or screenshot instead of inferring it from pixel statistics. offset and limit do not apply to images. A PDF or Word file (.docx, .doc; up to 64 MiB) is returned as its extracted text with line numbers, paged by offset and limit like a text file; for a PDF, pages selects pages and render: true returns those pages as images, which is how to read a scan, a figure or a page with no text layer. A text file that is not UTF-8 (UTF-16, Windows-1252) is shown decoded. Documents and decoded text are read-only: they are not remembered as a Read, and Edit/Write cannot change them.`, { type: 'object', properties: {
448
482
  file_path: { type: 'string', description: 'Workspace-relative or absolute path inside the workspace' },
449
483
  offset: { type: 'integer', minimum: 0, description: '1-based starting line; 0 is accepted as line 1' },
450
484
  limit: { type: 'integer', minimum: 1, maximum: READ_MAX_LINES, description: `Maximum lines to return, at most ${READ_MAX_LINES}` },
485
+ pages: { type: 'string', description: 'PDF only: the pages to read, such as "3", "2-5" or "1,4,7-9". Default: every page' },
486
+ render: { type: 'boolean', description: `PDF only: return the selected pages as images instead of their text, at most ${READ_PDF_RENDER_PAGES} pages per call. Use it for scans, figures, tables, forms and scores` },
451
487
  }, required: ['file_path'], additionalProperties: false }, 'parallel', async (args, context) => {
452
- if (Object.keys(args).some(key => !['file_path', 'offset', 'limit'].includes(key)))
488
+ if (Object.keys(args).some(key => !['file_path', 'offset', 'limit', 'pages', 'render'].includes(key)))
453
489
  throw new Error('Unknown Read argument');
454
490
  const filePath = stringArg(args, 'file_path');
455
491
  const offset = intArg(args, 'offset', { min: 0, max: Number.MAX_SAFE_INTEGER });
456
492
  const limit = intArg(args, 'limit', { min: 1, max: READ_MAX_LINES }) ?? READ_MAX_LINES;
493
+ const pages = stringArg(args, 'pages', true), render = boolArg(args, 'render') ?? false;
457
494
  const resolved = await policy.safePath(context, filePath);
458
495
  // An image is recognized by its signature and shown as pixels. It is not recorded as a
459
496
  // text read: Write and Edit cannot faithfully rewrite a file they only saw as a picture.
460
497
  const image = await policy.readImage?.(context, resolved);
461
498
  if (image)
462
499
  return readImageObservation(context, filePath, image);
463
- const content = await policy.read(context, resolved);
500
+ // A PDF or Word file is likewise recognized by its leading bytes and returned as what it
501
+ // says: its text, or for a PDF its pages as images. Neither is recorded as a text read.
502
+ const documentOptions = { offset, limit, ...(pages === undefined ? {} : { pages }), render, maxOutput: MAX_MODEL_OUTPUT, maxLineChars: READ_MAX_LINE_CHARS };
503
+ const documentBytes = await policy.readDocument?.(context, resolved);
504
+ if (documentBytes) {
505
+ const observation = await readDocumentObservation(context, filePath, documentBytes, documentOptions);
506
+ if (observation !== undefined)
507
+ return observation;
508
+ }
509
+ let content;
510
+ try {
511
+ content = await policy.read(context, resolved);
512
+ }
513
+ catch (error) {
514
+ // Text in an older encoding (UTF-16, Windows-1252) fails the strict UTF-8 reader that
515
+ // Edit depends on. It is still text a model can read, so it is shown decoded, read-only.
516
+ if (!(error instanceof Error) || !/not valid UTF-8|Binary files are not supported/.test(error.message))
517
+ throw error;
518
+ const decoded = await policy.readLegacyText?.(context, resolved);
519
+ if (!decoded)
520
+ throw error;
521
+ return legacyTextObservation(filePath, decoded, documentOptions);
522
+ }
523
+ if (pages !== undefined || render)
524
+ throw new Error('pages and render apply to PDF files only; page through a text file with offset and limit.');
464
525
  const lines = content.split('\n');
465
526
  if (content.endsWith('\n') || content === '')
466
527
  lines.pop();
@@ -667,7 +728,7 @@ export function createCodingTools(policy) {
667
728
  });
668
729
  return args;
669
730
  };
670
- const Glob = zTool('Glob', 'Find files by glob pattern inside the workspace. This replaces Andorra list_files and Pi find/ls with one bounded discovery tool.', { type: 'object', properties: {
731
+ const Glob = zTool('Glob', 'Find files by glob pattern inside the workspace. This replaces Andorra list_files and Pi find/ls with one bounded discovery tool. It matches names, not contents, so use it to find something by name (for example *deploy*) before searching file contents; raise head_limit when the result reaches the limit.', { type: 'object', properties: {
671
732
  pattern: { type: 'string', description: 'Glob pattern such as **/*.ts or src/**/*.spec.ts' },
672
733
  path: { type: 'string', description: 'Directory inside the workspace; defaults to .' },
673
734
  head_limit: { type: 'integer', minimum: 1, maximum: 1000, description: 'Maximum paths; default 100' },
@@ -848,17 +909,17 @@ export function createCodingTools(policy) {
848
909
  const canonicalShell = (name, kind) => {
849
910
  const actual = kind === 'powershell' ? 'PowerShell' : 'Bash';
850
911
  const syntax = kind === 'powershell'
851
- ? 'PowerShell syntax; use & before a quoted executable path. No cmd.exe substitution. Do not pipe a running child into Select-Object -First: it terminates the pipeline before the child completes and can cause exit 4294967295. Host output is already tail-bounded; use Select-Object -Last if further filtering is needed. Prefer file-written scripts over nested quoting for multiline Python/JavaScript. Prefer direct invocation (& $exe @args) for child processes: Windows PowerShell Start-Process -ArgumentList flattens arrays and can split a multi-word argument unless it is quoted manually. Windows PowerShell also alters what it hands a native program: piping a string into one (ssh, wsl, bash -s, docker exec) appends CRLF after the last line, so a remote shell runs that line with a stray \r, and double quotes inside a native argument are dropped. Send a multi-line script to a remote or POSIX shell as base64 instead: $b = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes(($script -replace "`r", "") + "`n")); & ssh host "echo $b | base64 -d | bash".'
912
+ ? 'PowerShell syntax; use & before a quoted executable path. No cmd.exe substitution. Do not pipe a running child into Select-Object -First: it terminates the pipeline before the child completes and can cause exit 4294967295. Host output is already tail-bounded; use Select-Object -Last if further filtering is needed. Prefer file-written scripts over nested quoting for multiline Python/JavaScript. Prefer direct invocation (& $exe @args) for child processes: Windows PowerShell Start-Process -ArgumentList flattens arrays and can split a multi-word argument unless it is quoted manually. Windows PowerShell also alters what it hands a native program: piping a string into one (ssh, wsl, bash -s, docker exec) appends CRLF after the last line, so a remote shell runs that line with a stray \r, and double quotes inside a native argument are dropped. Windows PowerShell binds the content of Set-Content or Add-Content as the file name when a switch such as -NoNewline comes before a positional path: name -Path and -Value, or use Write. Send a multi-line script to a remote or POSIX shell as base64 instead: $b = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes(($script -replace "`r", "") + "`n")); & ssh host "echo $b | base64 -d | bash".'
852
913
  : 'Bash syntax (Git Bash on Windows).';
853
914
  const tool = zTool(name, `Execute a foreground ${actual} command in the workspace. The working directory is the workspace; ${syntax} Output is tail-bounded. Commands follow the current workspace permissions. Restricted modes use the Codex OS sandbox and block network/outside writes; explicit escalation requires justification and approval. Credential environment variables are excluded; credential files remain accessible. This uses the compact command/timeout/description contract while retaining Pi/Andorra process-tree cleanup. Background execution is not exposed${kind === 'powershell' ? '' : ': a command that leaves a job running (cmd &) waits for that job, and the timeout then stops it'}. Start long-running work with AsyncProcess instead${PERSISTENT_JOBS_SUPPORTED ? ', with persist: true for a service the user needs left running after you finish' : ''}.`, { type: 'object', properties: {
854
915
  command: { type: 'string', description: 'Command to execute' },
855
- timeout: { type: 'integer', minimum: 1, maximum: 600000, description: 'Timeout in milliseconds; default 30000' },
916
+ timeout: { type: 'integer', minimum: 1, maximum: SHELL_MAX_TIMEOUT_MS, description: `Timeout in milliseconds; default ${SHELL_DEFAULT_TIMEOUT_MS}, at most ${SHELL_MAX_TIMEOUT_MS}. Set it for a build, install, download or test run you expect to take longer than the default` },
856
917
  description: { type: 'string', description: 'Short active-voice description of what the command does' },
857
918
  ...sandboxFields,
858
919
  }, required: ['command'], additionalProperties: false }, 'sequential', async (args, context) => {
859
920
  if (Object.keys(args).some(key => !['command', 'timeout', 'description', 'sandbox_permissions', 'justification'].includes(key)))
860
921
  throw new Error(`Unknown ${name} argument`);
861
- const command = stringArg(args, 'command'), timeout = intArg(args, 'timeout', { min: 1, max: 600000 }) ?? 30000;
922
+ const command = stringArg(args, 'command'), timeout = intArg(args, 'timeout', { min: 1, max: SHELL_MAX_TIMEOUT_MS }) ?? SHELL_DEFAULT_TIMEOUT_MS;
862
923
  if (args.description !== undefined)
863
924
  stringArg(args, 'description', true);
864
925
  // Before any approval is asked for: no permission mode, full access included, makes ending
@@ -897,15 +958,22 @@ export function createCodingTools(policy) {
897
958
  const current = kind === 'powershell'
898
959
  ? andorraCreatePowerShellTool(cwd, { operations, persistOutput: false, exposeSessionEnvironment: false })
899
960
  : andorraCreateBashTool(cwd, { operations, persistOutput: false, exposeSessionEnvironment: false });
900
- try {
901
- const result = await current.execute(randomUUID(), { command, timeout: timeout / 1000 }, context.signal);
902
- return nativeObservation(result.content.filter(part => part.type === 'text').map(part => part.text).join('\n'), true);
903
- }
904
- catch (error) {
905
- if (error instanceof Error && error.message.length > MAX_MODEL_OUTPUT)
906
- throw new Error(nativeObservation(error.message, true));
907
- throw error;
908
- }
961
+ return withStrayFileNotice(cwd, async () => {
962
+ try {
963
+ const result = await current.execute(randomUUID(), { command, timeout: timeout / 1000 }, context.signal);
964
+ return nativeObservation(result.content.filter(part => part.type === 'text').map(part => part.text).join('\n'), true);
965
+ }
966
+ catch (error) {
967
+ if (!(error instanceof Error))
968
+ throw error;
969
+ const message = shellTimeoutGuidance(error.message, timeout);
970
+ if (message.length > MAX_MODEL_OUTPUT)
971
+ throw new Error(nativeObservation(message, true));
972
+ if (message !== error.message)
973
+ throw new Error(message);
974
+ throw error;
975
+ }
976
+ });
909
977
  });
910
978
  // The vendored shell throws on any exit other than 0, so a return is a clean exit.
911
979
  return { ...tool, exitZeroOnReturn: true };
@@ -972,8 +1040,9 @@ export function createCodingTools(policy) {
972
1040
  const cwd = await policy.safePath(context, '.');
973
1041
  // Preserve the legacy observation formats: 'shell' keeps the runShell observation,
974
1042
  // while explicit 'powershell'/'bash' use native tail truncation and errors.
1043
+ const command = args.command;
975
1044
  if (name === 'shell')
976
- return nativeObservation(await runShell(args.command, cwd, timeout, context.signal, kind, undefined, undefined, launchPolicy), true);
1045
+ return withStrayFileNotice(cwd, async () => nativeObservation(await runShell(command, cwd, timeout, context.signal, kind, undefined, undefined, launchPolicy), true));
977
1046
  const operations = { exec: async (value, directory, options) => {
978
1047
  try {
979
1048
  await runShell(value, directory, timeout, context.signal, kind, options.onData, undefined, launchPolicy);
@@ -990,15 +1059,17 @@ export function createCodingTools(policy) {
990
1059
  const current = kind === 'powershell'
991
1060
  ? andorraCreatePowerShellTool(cwd, { operations, persistOutput: false, exposeSessionEnvironment: false })
992
1061
  : andorraCreateBashTool(cwd, { operations, persistOutput: false, exposeSessionEnvironment: false });
993
- try {
994
- const result = await current.execute(randomUUID(), { command: args.command, timeout: timeout / 1000 }, context.signal);
995
- return nativeObservation(result.content.filter(part => part.type === 'text').map(part => part.text).join('\n'), true);
996
- }
997
- catch (error) {
998
- if (error instanceof Error && error.message.length > 24_000)
999
- throw new Error(nativeObservation(error.message, true));
1000
- throw error;
1001
- }
1062
+ return withStrayFileNotice(cwd, async () => {
1063
+ try {
1064
+ const result = await current.execute(randomUUID(), { command, timeout: timeout / 1000 }, context.signal);
1065
+ return nativeObservation(result.content.filter(part => part.type === 'text').map(part => part.text).join('\n'), true);
1066
+ }
1067
+ catch (error) {
1068
+ if (error instanceof Error && error.message.length > 24_000)
1069
+ throw new Error(nativeObservation(error.message, true));
1070
+ throw error;
1071
+ }
1072
+ });
1002
1073
  },
1003
1074
  };
1004
1075
  });
@@ -1023,7 +1094,7 @@ export function createCodingTools(policy) {
1023
1094
  const executable = program === 'node' ? process.execPath : program === 'git' ? 'git' : andorraGetToolPath('rg');
1024
1095
  if (!executable)
1025
1096
  throw new Error('Native executable is not installed');
1026
- return nativeObservation(await runNativeProcess(executable, argv, cwd, timeout, context.signal, launchPolicy), true);
1097
+ return withStrayFileNotice(cwd, async () => nativeObservation(await runNativeProcess(executable, argv, cwd, timeout, context.signal, launchPolicy), true));
1027
1098
  });
1028
1099
  const AsyncProcess = zTool('AsyncProcess', `Start a shell command in the background and return immediately; inspect status/logs, wait for completion without polling, or stop it. Use for independent builds, test suites, and dev servers so other agent work can continue. Each job has a generated ID. ${PERSISTENT_JOBS_SUPPORTED
1029
1100
  ? 'Jobs are killed when the owning CLI exits unless started with persist: true. When the task is to leave a service running for the user (a web server, daemon or listener they will use after you finish), start it with persist: true and do not stop it before you finish.'
@@ -1079,7 +1150,7 @@ export function createCodingTools(policy) {
1079
1150
  const timeout = intArg(args, 'timeout', { min: 1, max: 600000 }) ?? 30000;
1080
1151
  const launchPolicy = await shellPermission(policy, 'PowerShellFast', args, context);
1081
1152
  const cwd = await policy.safePath(context, '.');
1082
- return nativeObservation(await runPooledPowerShell(command, cwd, timeout, context.signal, launchPolicy, context.onCommandOutput), true);
1153
+ return withStrayFileNotice(cwd, async () => nativeObservation(await runPooledPowerShell(command, cwd, timeout, context.signal, launchPolicy, context.onCommandOutput), true));
1083
1154
  });
1084
1155
  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()));
1085
1156
  const platformShell = process.platform === 'win32' ? canonicalShell('PowerShell', 'powershell') : canonicalShell('Bash', 'bash');
@@ -317,7 +317,7 @@ export async function runCommandScreen(line, state, ui, persist, signal, adapter
317
317
  id: DEFAULT_GRAPH.id,
318
318
  label: 'Default',
319
319
  description: 'Andorra Agent only. Reads project instructions and completes the task without an Orchestrator.',
320
- }, { id: ANDORRA_GRAPH_SELECTION, label: 'Andorra', description: free ? 'Premium workflow: Orchestrator -> Andorra Agent -> Done' : 'Paid workflow: Orchestrator -> Andorra Agent -> Done' }, ...withoutDeletedGraphs(saved).filter(graph => graph.id !== 'default').map(graph => ({ id: graph.id, label: `${graph.name} (${graph.id}@${graph.revision})`, description: 'Saved custom graph' })), { id: ':divider', label: '', separator: true }, { id: ':create', label: 'Create new graph', description: atLimit ? 'Free tier includes 1 custom graph. Upgrade to Premium for more graphs.' : 'Open the web graph builder' }, { id: ':edit', label: 'Edit Graphs', bold: true, description: 'Open saved graphs in the web graph builder' }];
320
+ }, { id: ANDORRA_GRAPH_SELECTION, label: 'Andorra', description: free ? 'Premium graph: Orchestrator -> Andorra Agent -> Done' : 'Paid graph: Orchestrator -> Andorra Agent -> Done' }, ...withoutDeletedGraphs(saved).filter(graph => graph.id !== 'default').map(graph => ({ id: graph.id, label: `${graph.name} (${graph.id}@${graph.revision})`, description: 'Saved custom graph' })), { id: ':divider', label: '', separator: true }, { id: ':create', label: 'Create new graph', description: atLimit ? 'Free tier includes 1 custom graph. Upgrade to Premium for more graphs.' : 'Open the web graph builder' }, { id: ':edit', label: 'Edit Graphs', bold: true, description: 'Open saved graphs in the web graph builder' }];
321
321
  while (!signal.aborted) {
322
322
  const selected = await ui.select('Graph', items, { selectedId: state.graph ?? DEFAULT_GRAPH.id, description: 'Choose and save your default graph for this account, or create one in the web builder. After saving, reopen /graph to select it.', signal });
323
323
  if (selected === undefined || signal.aborted)
@@ -474,7 +474,7 @@ export function handleCommand(line, state) {
474
474
  if (changed)
475
475
  return { text: 'Graph: Default (Andorra Agent)', clear: true };
476
476
  }
477
- return { text: 'Graph: Default - Andorra Agent only. Use the graph selector for the paid Andorra workflow or custom graphs.' };
477
+ return { text: 'Graph: Default - Andorra Agent only. Use the graph selector for the paid Andorra graph or custom graphs.' };
478
478
  case '/permissions':
479
479
  if (!arg)
480
480
  return { text: `Permissions: ${permissionLabel(state.permissions ?? (state.yolo ? 'full-access' : 'ask-for-approval'))}` };
@@ -8,28 +8,63 @@ import type { TodoItem } from './todos.js';
8
8
  * turn read as a run cut off halfway. Both conditions are facts the host already holds, so they are
9
9
  * checked in code rather than left to the prompt.
10
10
  *
11
- * Each gate sends the handoff back at most `MAX_GATE_ASKS` times and is waived after that. A gate
12
- * never spends a completion repair and never fails the run: a model that will not write a summary,
13
- * or that leaves a step open because it cannot be done, ends exactly as it did before the gates
14
- * existed, with the waiver recorded.
11
+ * The `summary` and `todos` gates each send the handoff back at most `MAX_GATE_ASKS` times and are
12
+ * waived after that. A gate never spends a completion repair and never fails the run.
13
+ *
14
+ * The `unfinished` gate is different in kind. It fires when the completion itself says the task is
15
+ * not done: a non-empty `remaining` list, or a "Not done" section in the summary. A run must not end
16
+ * on its own with work it can still do. In a benchmark trial with a fifteen-minute limit the agent
17
+ * had a build that booted but drew no frame, was told a quarter of its time was left, and completed
18
+ * two steps later with "frame output still missing" in its own summary and two minutes unused; the
19
+ * host accepted it, and the trial failed. So a completion that reports unfinished work is sent back
20
+ * to keep working for as long as the agent does work in between, with no cap on how often. It is
21
+ * accepted only when sending it back cannot help: the agent has twice in a row answered the
22
+ * send-back with the same report and no tool call (there is nothing more it can do without the
23
+ * user), the attempt's clock has all but run out, or it is on its last allowed iteration. Each of
24
+ * those is recorded as a waiver with its reason.
25
+ *
26
+ * Earlier the "Not done" section was the way a completion with open plan items got through at once.
27
+ * That made the honest report an exit, and the trial above took it.
15
28
  */
16
- export type FinalAnswerGateId = 'summary' | 'todos';
29
+ export type FinalAnswerGateId = 'summary' | 'todos' | 'unfinished';
17
30
  export declare const MAX_GATE_ASKS = 2;
31
+ /** Consecutive send-backs the agent may answer with no tool call before an unfinished report is accepted. */
32
+ export declare const MAX_IDLE_UNFINISHED_ASKS = 2;
33
+ /** With less than this left on the attempt's clock, another turn could not do any work. */
34
+ export declare const UNFINISHED_MIN_TIME_MS = 20000;
35
+ export type UnfinishedWaiver = 'noFurtherWork' | 'outOfTime';
18
36
  export interface FinalAnswerGateInput {
19
37
  /** The envelope had no summary, so the serialized output is what the user would read. */
20
38
  summaryStoodIn: boolean;
21
39
  /** The run's plan as it stands after any update sent beside the completion. */
22
40
  todos: readonly TodoItem[];
23
- /** How many times each gate has already sent a handoff back in this run. */
41
+ /** The summary as the user will read it; a "Not done" section in it reports unfinished work. */
42
+ summary?: string;
43
+ /** The completion's own list of what the task still lacks; empty or absent when it claims to be done. */
44
+ remaining?: readonly string[];
45
+ /** How many times the summary and plan gates have already sent a handoff back in this run. */
24
46
  asked?: Partial<Record<FinalAnswerGateId, number>>;
47
+ /** Send-backs for unfinished work, in a row, that the agent answered without running any tool. */
48
+ idleUnfinishedAsks?: number;
49
+ /** Time left on the attempt's wall clock; undefined when the attempt has none. */
50
+ timeLeftMs?: number;
25
51
  }
26
52
  export interface FinalAnswerGateResult {
27
53
  /** Gates that send this handoff back. Empty when every failed gate is waived. */
28
54
  gates: FinalAnswerGateId[];
29
- /** Gates that failed again after their asks were spent; the handoff is accepted despite them. */
55
+ /** Gates that failed but let the handoff through; the handoff is accepted despite them. */
30
56
  waived: FinalAnswerGateId[];
31
57
  /** What the model is told. Empty when nothing is sent back. */
32
58
  message: string;
59
+ /** Why an unfinished report was let through, when `waived` includes `unfinished`. */
60
+ unfinishedWaiver?: UnfinishedWaiver;
33
61
  }
62
+ /**
63
+ * Whether the summary has a section that reports unfinished work: a markdown heading, or a line
64
+ * that is only a bold or plain label, reading "Not done" (also "Not completed", "Not finished",
65
+ * "Unfinished", "Remaining work", "Incomplete"). A sentence that merely contains the words does not
66
+ * count: a summary may say "nothing was left not done".
67
+ */
68
+ export declare function declaresUnfinishedWork(summary: string | undefined): boolean;
34
69
  /** Undefined when the handoff passes every gate. */
35
70
  export declare function finalAnswerGate(input: FinalAnswerGateInput): FinalAnswerGateResult | undefined;
@@ -1,25 +1,71 @@
1
1
  export const MAX_GATE_ASKS = 2;
2
- /** Plan items named in the message; a longer plan is counted, not listed. */
2
+ /** Consecutive send-backs the agent may answer with no tool call before an unfinished report is accepted. */
3
+ export const MAX_IDLE_UNFINISHED_ASKS = 2;
4
+ /** With less than this left on the attempt's clock, another turn could not do any work. */
5
+ export const UNFINISHED_MIN_TIME_MS = 20_000;
6
+ /** Plan items and remaining items named in the message; a longer list is counted, not listed. */
3
7
  const MAX_NAMED_TODOS = 8;
8
+ const MAX_NAMED_REMAINING = 5;
9
+ const MAX_REMAINING_CHARS = 160;
10
+ const UNFINISHED_SECTION = /^[ \t]*(?:#{1,6}[ \t]+|\*\*|__)?(?:not (?:done|completed?|finished)|unfinished(?: work)?|remaining work|incomplete)(?:\*\*|__)?[ \t]*:?[ \t]*(?:\*\*|__)?[ \t]*$/im;
11
+ /**
12
+ * Whether the summary has a section that reports unfinished work: a markdown heading, or a line
13
+ * that is only a bold or plain label, reading "Not done" (also "Not completed", "Not finished",
14
+ * "Unfinished", "Remaining work", "Incomplete"). A sentence that merely contains the words does not
15
+ * count: a summary may say "nothing was left not done".
16
+ */
17
+ export function declaresUnfinishedWork(summary) {
18
+ return !!summary && UNFINISHED_SECTION.test(summary);
19
+ }
20
+ function timeLeftPhrase(ms) {
21
+ const seconds = Math.round(ms / 1000);
22
+ if (seconds < 90)
23
+ return `about ${Math.max(5, Math.round(seconds / 5) * 5)} seconds`;
24
+ const minutes = Math.round(seconds / 60);
25
+ return minutes < 90 ? `about ${minutes} minutes` : `about ${Math.round(minutes / 6) / 10} hours`;
26
+ }
4
27
  /** Undefined when the handoff passes every gate. */
5
28
  export function finalAnswerGate(input) {
6
- const unfinished = input.todos.filter(todo => todo.status !== 'completed');
7
- const failed = [...(input.summaryStoodIn ? ['summary'] : []), ...(unfinished.length ? ['todos'] : [])];
29
+ const open = input.todos.filter(todo => todo.status !== 'completed');
30
+ const remaining = (input.remaining ?? []).filter(item => item.trim());
31
+ // A stand-in summary is the serialized output, never the model's own account of the work.
32
+ const reportsUnfinished = !input.summaryStoodIn && (remaining.length > 0 || declaresUnfinishedWork(input.summary));
33
+ // Open plan items the completion accounts for as unfinished belong to the unfinished gate; the
34
+ // plan gate is for a plan left open under a completion that claims to be done.
35
+ const failed = [
36
+ ...(input.summaryStoodIn ? ['summary'] : []),
37
+ ...(reportsUnfinished ? ['unfinished'] : open.length ? ['todos'] : []),
38
+ ];
8
39
  if (!failed.length)
9
40
  return undefined;
10
- const gates = failed.filter(gate => (input.asked?.[gate] ?? 0) < MAX_GATE_ASKS);
41
+ const unfinishedWaiver = !reportsUnfinished ? undefined
42
+ : input.timeLeftMs !== undefined && input.timeLeftMs < UNFINISHED_MIN_TIME_MS ? 'outOfTime'
43
+ : (input.idleUnfinishedAsks ?? 0) >= MAX_IDLE_UNFINISHED_ASKS ? 'noFurtherWork' : undefined;
44
+ const gates = failed.filter(gate => gate === 'unfinished' ? unfinishedWaiver === undefined : (input.asked?.[gate] ?? 0) < MAX_GATE_ASKS);
11
45
  const waived = failed.filter(gate => !gates.includes(gate));
46
+ const waiver = unfinishedWaiver && waived.includes('unfinished') ? { unfinishedWaiver } : {};
12
47
  if (!gates.length)
13
- return { gates, waived, message: '' };
48
+ return { gates, waived, message: '', ...waiver };
14
49
  const parts = [];
15
50
  if (gates.includes('summary')) {
16
51
  parts.push('It has no summary. The summary is the final answer the user reads; without one they see only the raw output object. Send summary as markdown (the outcome first, then what changed, how it was verified, and anything not done) and tests as one line per check that ran, or [] when none did, beside outcome and output.');
17
52
  }
18
53
  if (gates.includes('todos')) {
19
54
  // Ids and statuses only: the plan's text is model-authored and is already in the todo snapshot.
20
- const named = unfinished.slice(0, MAX_NAMED_TODOS).map(todo => `${todo.id} (${todo.status})`).join(', ');
21
- const more = unfinished.length > MAX_NAMED_TODOS ? `, and ${unfinished.length - MAX_NAMED_TODOS} more` : '';
22
- parts.push(`The plan still lists ${unfinished.length} unfinished ${unfinished.length === 1 ? 'item' : 'items'}: ${named}${more}. Do the work that is left, using tools. For work that is already done, send update_todos with the true statuses in the same batch as complete_agent. If an item cannot be finished, or waits on something only the user can do or answer, leave it open, name it under "## Not done" in the summary, and say there what you need from the user.`);
55
+ const named = open.slice(0, MAX_NAMED_TODOS).map(todo => `${todo.id} (${todo.status})`).join(', ');
56
+ const more = open.length > MAX_NAMED_TODOS ? `, and ${open.length - MAX_NAMED_TODOS} more` : '';
57
+ parts.push(`The plan still lists ${open.length} unfinished ${open.length === 1 ? 'item' : 'items'}: ${named}${more}. Do the work that is left, using tools. For work that is already done, send update_todos with the true statuses in the same batch as complete_agent. Do not close an item, or ship a change you do not believe in, only to make the plan read as finished.`);
58
+ }
59
+ if (gates.includes('unfinished')) {
60
+ const named = remaining.slice(0, MAX_NAMED_REMAINING).map(item => {
61
+ const line = item.replace(/\s+/g, ' ').trim();
62
+ return line.length > MAX_REMAINING_CHARS ? `${line.slice(0, MAX_REMAINING_CHARS)}…` : line;
63
+ });
64
+ const what = named.length
65
+ ? ` (${named.join('; ')}${remaining.length > named.length ? `; and ${remaining.length - named.length} more` : ''})`
66
+ : '';
67
+ const time = input.timeLeftMs !== undefined ? ` ${timeLeftPhrase(input.timeLeftMs)} of this run's time limit remain, and time left unused is worth nothing.` : '';
68
+ parts.push(`You report the task as not finished${what}. A run does not end while there is work it can still do: stopping now leaves the task failed.${time} Keep working with tools on what is missing or failing, and if the current approach is stuck, try a different one instead of repeating it. Call complete_agent again when the task is done. Only if nothing more can be done without the user (a credential, a decision, access only they have), say exactly what you need from them under "## Not done" and call complete_agent again.`);
23
69
  }
24
- return { gates, waived, message: `Completion not accepted yet. ${parts.join(' ')} Then call complete_agent again.` };
70
+ return { gates, waived, message: `Completion not accepted yet. ${parts.join(' ')}${gates.includes('unfinished') ? '' : ' Then call complete_agent again.'}`, ...waiver };
25
71
  }
@@ -14,6 +14,14 @@ export declare const RESPONSE_STRUCTURE_GUIDANCE = "Write user-facing text, incl
14
14
  * breaks are wanted, next to the value they shape.
15
15
  */
16
16
  export declare const SUMMARY_DESCRIPTION = "Markdown shown to the user as the final answer. Write line breaks as \\n escapes: lead with the outcome, then short headings and bullet lists, and open and close each fenced code block on its own line. Never one unbroken paragraph.";
17
+ /** Entries kept from a completion's `remaining` list. */
18
+ export declare const REMAINING_LIMIT = 20;
19
+ /**
20
+ * The completion states, as data rather than somewhere in its prose, what the task still lacks.
21
+ * A summary that said "frame output still missing" ended a run with time on the clock, because
22
+ * nothing the host could read told it the task was unfinished (completion-gates.ts).
23
+ */
24
+ export declare const REMAINING_DESCRIPTION = "Everything the task asks for that is still missing, failing or unverified, one short entry each. [] only when every requirement is met and you have checked it. Be exact: this is read by the runtime, not only by the user.";
17
25
  export declare const COMPLETION_GUIDANCE = "Finish with complete_agent alone or final JSON. Todos/artifacts do not finish a node. Compare deliverables and verification evidence with acceptance criteria. Fulfill assigned requirements: intake/research nodes hand off downstream work; implementation nodes finish implementation and verification, not a progress checkpoint. Continue available work. For a concrete external blocker, report the blocker and unfinished work honestly. Use a blocked outcome if available; otherwise the sole outcome permits a terminal report, not a claim that the task is done. Only when this node is responsible for producing the final user answer, its summary must satisfy the user's response requirements: include complete requested files and exact formatting, including requested code fences, without abbreviation, path substitution, or offers to provide content later. Each fence opens and closes on its own line; a file written to the workspace that the user did not ask to see in the answer is named by path, not reproduced. Intermediate intake, research, and delegation nodes must instead keep a concise handoff and preserve these final-answer acceptance requirements in the downstream task instruction or output; do not implement or reproduce the final deliverable before handing off. Preserve required fields and valid JSON; escape quotes and Windows backslashes or use C:/repo/file.ts, and write each summary line break as \\n rather than dropping it. Never claim unperformed work.";
18
26
  /** Control-plane completion remains available when the execution-tool budget is exhausted. */
19
27
  export declare function completionTool(options: RunOptions): ToolSchema;
@@ -44,7 +52,8 @@ export declare function completionResponse(response: ModelResponse): ModelRespon
44
52
  * line breaks belong, and the transcript draws its markdown as one literal paragraph.
45
53
  *
46
54
  * Two shapes are decoded. A summary escaped throughout has no real line break and at least two
47
- * escaped paragraph breaks; every escape in it is undone. A model can also switch to the extra
55
+ * escaped paragraph breaks, or at least two escaped breaks outside code that open markdown
56
+ * structure (one paragraph break and a list is enough); every escape in it is undone. A model can also switch to the extra
48
57
  * escaping partway through, leaving a few real line breaks and the rest escaped: one `## heading`
49
58
  * then swallows everything after it. That mixed summary is decoded only when at least two escaped
50
59
  * breaks outside code open markdown structure (a heading, list item, quote, table, fence, or a
@@ -56,6 +65,47 @@ export declare function completionResponse(response: ModelResponse): ModelRespon
56
65
  * (`displayHistory` in sessions.ts).
57
66
  */
58
67
  export declare function decodeDoubleEscapedSummary(summary: string, notes?: string[]): string;
68
+ /**
69
+ * Replace a completion envelope a model wrote as message text, so the transcript never shows raw
70
+ * JSON. Two live shapes, both glm-5.3-flash on GX10:
71
+ * - Run 3a8378f0 ended a QA report with "Submitting the report." and then the whole envelope as
72
+ * text, `{"summary":"…\n\n## 1. Target…","tests":[…],"prUrl":"…"}`, about 12 KB, instead of
73
+ * calling complete_agent. The runtime rightly sent it back; the caller passes a `note` saying so,
74
+ * which stands in for the envelope (the report itself arrives later through complete_agent).
75
+ * - Session bbedcfbf narrated beside its tool calls as `{"summary":"Starting the PR comment fixer
76
+ * round…","tests":[]}`. With no `note`, the envelope's summary stands in for it, decoded like a
77
+ * completion's, so the narration still reads as prose.
78
+ *
79
+ * Only an envelope that ends the text is replaced: a JSON object whose `summary` is a string, which
80
+ * parses on its own from its opening brace to the end of the text (closing brackets the model left
81
+ * off are supplied, as for a completion), bare or as the whole of a final fenced block. One shown in
82
+ * inline code, one followed by more prose, and otherwise malformed JSON are left as written.
83
+ */
84
+ export declare function withoutTrailingEnvelope(text: string, note?: string): string;
85
+ /**
86
+ * Remove the completion fields a model copied into the end of its summary as text. Some models
87
+ * call complete_agent with every field set and then also write the same fields out under the
88
+ * answer:
89
+ *
90
+ * Browser is open.
91
+ *
92
+ * summary: Browser panel opened successfully on example.com.
93
+ * tests: none — no checks were required.
94
+ * outcome: completed
95
+ * output: {}
96
+ *
97
+ * The transcript draws the summary as the answer, so those lines reached the user as a raw field
98
+ * dump. Unlike an embedded JSON envelope (`rejectEmbeddedEnvelope`), the arguments themselves are
99
+ * intact, so there is nothing for a retry to repair: the trailing block is dropped and recorded.
100
+ *
101
+ * Only a block at the very end is touched, outside code, after a blank line (or making up the whole
102
+ * summary), in which every line is a field line or continues one, and which holds an `outcome:` line
103
+ * and at least one other field. When the completion carries an outcome, the echoed line must name
104
+ * that same outcome, so an answer that ends on "Tests: 12 passed" and "Output: dist/" is not an echo.
105
+ * A summary that shows the fields in a code block is left as written. When the block is the whole
106
+ * summary, its `summary:` field, with the lines under it, becomes the answer.
107
+ */
108
+ export declare function stripEchoedEnvelope(summary: string, outcome: string | undefined, notes?: string[]): string;
59
109
  /**
60
110
  * Parse one completion, accepting mechanically imperfect envelopes that are semantically correct.
61
111
  *