@andorra-labs/code 0.1.5 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (224) hide show
  1. package/dist/src/account-presentation.js +3 -3
  2. package/dist/src/agent-execution.d.ts +2 -0
  3. package/dist/src/agent-execution.js +526 -41
  4. package/dist/src/agent-mcp-catalog.d.ts +21 -0
  5. package/dist/src/agent-mcp-catalog.js +40 -0
  6. package/dist/src/agent-mcp.d.ts +36 -3
  7. package/dist/src/agent-mcp.js +114 -45
  8. package/dist/src/app-server/protocol.d.ts +57 -5
  9. package/dist/src/app-server/protocol.js +18 -1
  10. package/dist/src/app-server/workspace.d.ts +9 -1
  11. package/dist/src/app-server/workspace.js +50 -3
  12. package/dist/src/app-server.d.ts +115 -41
  13. package/dist/src/app-server.js +1316 -221
  14. package/dist/src/auth/AuthManager.d.ts +33 -1
  15. package/dist/src/auth/AuthManager.js +138 -10
  16. package/dist/src/auth/callback-page.d.ts +4 -0
  17. package/dist/src/auth/callback-page.js +70 -0
  18. package/dist/src/auth/callback.d.ts +39 -0
  19. package/dist/src/auth/callback.js +146 -22
  20. package/dist/src/auth/index.d.ts +10 -6
  21. package/dist/src/auth/index.js +2 -2
  22. package/dist/src/auth/store.d.ts +142 -3
  23. package/dist/src/auth/store.js +334 -13
  24. package/dist/src/auth/types.d.ts +17 -1
  25. package/dist/src/auth-commands.d.ts +11 -2
  26. package/dist/src/auth-commands.js +14 -7
  27. package/dist/src/automation-runner.d.ts +9 -0
  28. package/dist/src/automation-runner.js +22 -1
  29. package/dist/src/automation-tool.js +18 -3
  30. package/dist/src/automations.d.ts +5 -0
  31. package/dist/src/automations.js +11 -1
  32. package/dist/src/browser-captcha-tool.d.ts +54 -0
  33. package/dist/src/browser-captcha-tool.js +374 -0
  34. package/dist/src/browser-panel-tool.d.ts +7 -0
  35. package/dist/src/browser-panel-tool.js +74 -3
  36. package/dist/src/browser-runner.js +19 -4
  37. package/dist/src/browser-server.js +21 -1
  38. package/dist/src/browser-session.d.ts +16 -0
  39. package/dist/src/browser-session.js +35 -0
  40. package/dist/src/browser-ui/app.js +193 -3
  41. package/dist/src/browser-ui/style.css +15 -1
  42. package/dist/src/browser-view.d.ts +72 -4
  43. package/dist/src/browser-view.js +229 -17
  44. package/dist/src/capabilities.d.ts +9 -3
  45. package/dist/src/capabilities.js +20 -5
  46. package/dist/src/capsolver.d.ts +60 -0
  47. package/dist/src/capsolver.js +101 -0
  48. package/dist/src/claude-provider.d.ts +6 -0
  49. package/dist/src/claude-provider.js +34 -3
  50. package/dist/src/cli-executable.d.ts +33 -0
  51. package/dist/src/cli-executable.js +64 -0
  52. package/dist/src/cli-process.d.ts +47 -0
  53. package/dist/src/cli-process.js +113 -0
  54. package/dist/src/cli-sign-in.d.ts +68 -0
  55. package/dist/src/cli-sign-in.js +224 -0
  56. package/dist/src/cli.js +84 -26
  57. package/dist/src/code-intelligence/CodeIntelligenceManager.d.ts +1 -1
  58. package/dist/src/code-intelligence/CodeIntelligenceManager.js +5 -5
  59. package/dist/src/codex-provider.js +12 -0
  60. package/dist/src/coding-tools.d.ts +5 -0
  61. package/dist/src/coding-tools.js +98 -53
  62. package/dist/src/command-output-tap.d.ts +16 -0
  63. package/dist/src/command-output-tap.js +45 -0
  64. package/dist/src/command-screens.js +3 -3
  65. package/dist/src/commands.d.ts +15 -2
  66. package/dist/src/commands.js +14 -13
  67. package/dist/src/completion.d.ts +23 -5
  68. package/dist/src/completion.js +380 -17
  69. package/dist/src/config.d.ts +61 -0
  70. package/dist/src/config.js +276 -12
  71. package/dist/src/context-budget.d.ts +7 -0
  72. package/dist/src/context-budget.js +18 -1
  73. package/dist/src/deadline.js +6 -0
  74. package/dist/src/decision/FactContinuations.d.ts +41 -6
  75. package/dist/src/decision/FactContinuations.js +211 -64
  76. package/dist/src/decision/PreparedSteps.js +3 -1
  77. package/dist/src/decision/checks.d.ts +25 -0
  78. package/dist/src/decision/checks.js +77 -6
  79. package/dist/src/delegation-changes.d.ts +109 -0
  80. package/dist/src/delegation-changes.js +431 -0
  81. package/dist/src/extensions.d.ts +1 -0
  82. package/dist/src/extensions.js +16 -3
  83. package/dist/src/graph-provider-portability.js +2 -2
  84. package/dist/src/graph-quota.d.ts +1 -1
  85. package/dist/src/graph-quota.js +1 -1
  86. package/dist/src/graph-runner.js +35 -21
  87. package/dist/src/graph-selection.d.ts +6 -0
  88. package/dist/src/graph-selection.js +10 -0
  89. package/dist/src/graph-server.d.ts +8 -0
  90. package/dist/src/graph-server.js +76 -6
  91. package/dist/src/graph-sync.d.ts +65 -0
  92. package/dist/src/graph-sync.js +433 -13
  93. package/dist/src/graph-tool.d.ts +52 -0
  94. package/dist/src/graph-tool.js +136 -0
  95. package/dist/src/graph-ui/app.js +272 -50
  96. package/dist/src/graph-ui/controls.js +6 -0
  97. package/dist/src/graph-ui/drafts.js +39 -0
  98. package/dist/src/graph-ui/embed.js +1 -1
  99. package/dist/src/graph-ui/icons.js +1 -0
  100. package/dist/src/graph-ui/index.html +2 -2
  101. package/dist/src/graph-ui/skill-picker.js +242 -0
  102. package/dist/src/graph-ui/studio.css +7 -5
  103. package/dist/src/graph-ui/style.css +65 -12
  104. package/dist/src/graphs.d.ts +60 -5
  105. package/dist/src/graphs.js +191 -37
  106. package/dist/src/grok-provider.d.ts +50 -0
  107. package/dist/src/grok-provider.js +186 -0
  108. package/dist/src/handoffs.d.ts +13 -0
  109. package/dist/src/handoffs.js +31 -1
  110. package/dist/src/hardened-runtime.d.ts +4 -4
  111. package/dist/src/hardened-runtime.js +109 -9
  112. package/dist/src/managed-sign-in.d.ts +38 -0
  113. package/dist/src/managed-sign-in.js +169 -0
  114. package/dist/src/markdown.d.ts +5 -0
  115. package/dist/src/markdown.js +5 -2
  116. package/dist/src/mcp.js +11 -0
  117. package/dist/src/membership.d.ts +8 -1
  118. package/dist/src/membership.js +15 -5
  119. package/dist/src/model-metadata.js +14 -2
  120. package/dist/src/model-override.d.ts +10 -0
  121. package/dist/src/model-override.js +20 -0
  122. package/dist/src/opencode-cli-provider.d.ts +122 -0
  123. package/dist/src/opencode-cli-provider.js +415 -0
  124. package/dist/src/opencode-provider.js +23 -8
  125. package/dist/src/palette.d.ts +2 -0
  126. package/dist/src/palette.js +2 -0
  127. package/dist/src/permissions.d.ts +19 -1
  128. package/dist/src/permissions.js +30 -1
  129. package/dist/src/powershell-pool.d.ts +11 -2
  130. package/dist/src/powershell-pool.js +34 -5
  131. package/dist/src/provider-connection.js +36 -0
  132. package/dist/src/provider-engine.d.ts +2 -1
  133. package/dist/src/provider-engine.js +64 -13
  134. package/dist/src/provider-import.js +6 -1
  135. package/dist/src/provider-keys.d.ts +48 -0
  136. package/dist/src/provider-keys.js +121 -0
  137. package/dist/src/provider-settings.js +22 -3
  138. package/dist/src/providers.d.ts +12 -1
  139. package/dist/src/providers.js +27 -8
  140. package/dist/src/pull-requests.d.ts +123 -20
  141. package/dist/src/pull-requests.js +334 -84
  142. package/dist/src/qa/qa-authorize.js +9 -1
  143. package/dist/src/qa/runtime/ProcessManager.d.ts +6 -0
  144. package/dist/src/qa/runtime/ProcessManager.js +16 -0
  145. package/dist/src/react-runtime.js +106 -7
  146. package/dist/src/read-image.d.ts +30 -0
  147. package/dist/src/read-image.js +97 -0
  148. package/dist/src/remote/engine-pool.js +1 -1
  149. package/dist/src/run-progress.js +6 -1
  150. package/dist/src/run-records.d.ts +133 -27
  151. package/dist/src/run-records.js +320 -40
  152. package/dist/src/runtime.d.ts +38 -1
  153. package/dist/src/runtime.js +27 -4
  154. package/dist/src/save-lock.d.ts +11 -0
  155. package/dist/src/save-lock.js +29 -2
  156. package/dist/src/secret-redaction.d.ts +13 -0
  157. package/dist/src/secret-redaction.js +71 -0
  158. package/dist/src/session-summary.d.ts +10 -4
  159. package/dist/src/session-summary.js +14 -7
  160. package/dist/src/sessions.js +8 -2
  161. package/dist/src/shell.js +4 -1
  162. package/dist/src/side-panel.d.ts +1 -1
  163. package/dist/src/side-panel.js +1 -1
  164. package/dist/src/skill-commands.d.ts +2 -0
  165. package/dist/src/skill-commands.js +2 -0
  166. package/dist/src/skills/bundled/create-agent/SKILL.md +81 -0
  167. package/dist/src/skills/bundled/create-skill/SKILL.md +81 -0
  168. package/dist/src/skills/bundled/doctor/SKILL.md +43 -0
  169. package/dist/src/skills/bundled/graph-manager/SKILL.md +100 -0
  170. package/dist/src/skills/bundled/graph-manager/errors.md +38 -0
  171. package/dist/src/skills/bundled/graph-manager/patterns.md +78 -0
  172. package/dist/src/skills/bundled/manage-mcp/SKILL.md +75 -0
  173. package/dist/src/skills/bundled/manage-mcp/probe.md +165 -0
  174. package/dist/src/skills/bundled/manage-skills/SKILL.md +67 -0
  175. package/dist/src/skills/bundled/provenance.json +50 -0
  176. package/dist/src/skills/bundled/write-instructions/SKILL.md +42 -0
  177. package/dist/src/skills/invocable-skills.d.ts +41 -0
  178. package/dist/src/skills/invocable-skills.js +49 -0
  179. package/dist/src/skills/prompt-skills.d.ts +1 -0
  180. package/dist/src/skills/prompt-skills.js +33 -0
  181. package/dist/src/skills/runtime-skills.d.ts +4 -0
  182. package/dist/src/skills/runtime-skills.js +21 -0
  183. package/dist/src/structured-step.d.ts +55 -0
  184. package/dist/src/structured-step.js +85 -0
  185. package/dist/src/subagent-run.d.ts +1 -1
  186. package/dist/src/subagent-run.js +29 -33
  187. package/dist/src/telemetry/schema.d.ts +2 -2
  188. package/dist/src/telemetry/schema.js +3 -2
  189. package/dist/src/terminal-ui.d.ts +38 -0
  190. package/dist/src/terminal-ui.js +126 -28
  191. package/dist/src/timers.d.ts +21 -2
  192. package/dist/src/timers.js +12 -4
  193. package/dist/src/tool-dependencies.js +4 -0
  194. package/dist/src/tool-names.d.ts +18 -0
  195. package/dist/src/tool-names.js +26 -0
  196. package/dist/src/tools.d.ts +9 -0
  197. package/dist/src/tools.js +159 -20
  198. package/dist/src/trajectory.js +32 -12
  199. package/dist/src/transcript.js +5 -0
  200. package/dist/src/types.d.ts +36 -0
  201. package/dist/src/web-search.d.ts +59 -0
  202. package/dist/src/web-search.js +216 -0
  203. package/docs/agents/README.md +2 -2
  204. package/docs/agents/mcp-server.md +28 -3
  205. package/docs/agents/subagent-mode.md +7 -4
  206. package/docs/concepts/README.md +1 -1
  207. package/docs/concepts/security.md +4 -2
  208. package/docs/getting-started/accounts.md +15 -4
  209. package/docs/getting-started/configure-providers.md +30 -3
  210. package/docs/guides/README.md +1 -0
  211. package/docs/guides/browser.md +12 -0
  212. package/docs/guides/desktop-app.md +11 -4
  213. package/docs/guides/graph-builder.md +9 -1
  214. package/docs/guides/web-search.md +47 -0
  215. package/docs/reference/cli.md +4 -3
  216. package/docs/reference/config.md +4 -4
  217. package/docs/reference/slash-commands.md +2 -1
  218. package/docs/superpowers/plans/2026-11-06-graph-soft-delete.md +125 -0
  219. package/docs/superpowers/plans/2026-11-09-orchestrator-delegation.md +295 -0
  220. package/docs/superpowers/specs/2026-11-01-pr-section-design.md +7 -0
  221. package/docs/superpowers/specs/2026-11-06-bundled-skills-design.md +206 -0
  222. package/docs/superpowers/specs/2026-11-09-orchestrator-delegation-design.md +291 -0
  223. package/package.json +1 -1
  224. package/tests/permissions-test-plan.md +2 -1
@@ -1,4 +1,5 @@
1
1
  import { validateJsonSchemaValue } from '../vendor/zcode/source/tool/json-schema.js';
2
+ import { interruptsParagraph } from './markdown.js';
2
3
  export const COMPLETION_TOOL = 'complete_agent';
3
4
  export const FINAL_RESPONSE_GUIDANCE = "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.";
4
5
  /**
@@ -30,8 +31,14 @@ function providerOutputSchema(schema) {
30
31
  /** Native JSON Schema checks plus Andorra's graph-specific artifact/integer contracts. */
31
32
  function validateCompletionOutput(schema, value) {
32
33
  const validation = validateJsonSchemaValue(value, providerOutputSchema(schema));
33
- if (!validation.valid)
34
- throw new Error(validation.errors.map(error => error.replace(/^\$/, 'Agent output')).join('; '));
34
+ if (!validation.valid) {
35
+ const errors = validation.errors.map(error => error.replace(/^\$/, 'Agent output'));
36
+ // "output.x is not allowed" names the mistake but not the fix, and a model told only that tends to
37
+ // resend the same object. Naming the fields the output does accept is the fix.
38
+ const declared = Object.keys(schema.properties ?? {});
39
+ const extra = errors.some(error => /^Agent output\.[^.\s[]+ is not allowed$/.test(error));
40
+ throw new Error(errors.join('; ') + (extra && declared.length ? `. The output object accepts only: ${declared.join(', ')}` : ''));
41
+ }
35
42
  const checkHostContracts = (node, item, path) => {
36
43
  if (node.type === 'integer' && !Number.isSafeInteger(item))
37
44
  throw new Error(`${path}: expected integer`);
@@ -74,40 +81,393 @@ export function completionTool(options) {
74
81
  },
75
82
  };
76
83
  }
77
- /** Only a direct, sole model control call can request completion, never a tool observation. */
84
+ export const COMPLETION_ALONE_ERROR = 'complete_agent must be called alone; no tools in this batch were executed.';
85
+ /**
86
+ * Only a direct, sole model control call can request completion, never a tool observation.
87
+ *
88
+ * The one companion allowed is `update_todos`: closing the plan and handing off in the same batch is
89
+ * the natural last move, and it changes no workspace state. Rejecting it threw the todo update away
90
+ * too, so every repair prompt then showed the model a plan that still said "in progress" for work it
91
+ * had finished, and the model spent its repairs arguing with that stale list. The todo calls are
92
+ * returned for the runtime to apply before it judges the handoff; anything else still voids the batch.
93
+ */
78
94
  export function completionResponse(response) {
79
95
  const call = response.toolCalls.find(call => call.name === COMPLETION_TOOL);
80
96
  if (!call)
81
97
  return { ...response, completionSource: 'final_text' };
82
- return { ...response, completionSource: 'complete_agent', toolCalls: [], text: call.arguments, ...(response.toolCalls.length === 1 ? {} : { completionError: 'complete_agent must be called alone; no tools in this batch were executed.' }) };
98
+ const others = response.toolCalls.filter(other => other !== call);
99
+ const todosOnly = others.length > 0 && others.every(other => other.name === 'update_todos');
100
+ return { ...response, completionSource: 'complete_agent', toolCalls: [], text: call.arguments,
101
+ ...(others.length === 0 ? {} : todosOnly ? { completionTodoCalls: others } : { completionError: COMPLETION_ALONE_ERROR }) };
102
+ }
103
+ /**
104
+ * The most closing brackets the host appends to a completion. Dropping the envelope's last `}`
105
+ * after closing `output`, or both of those, is a slip a model repeats on every retry; a longer
106
+ * open tail is an answer that stopped early, which the model has to send again.
107
+ */
108
+ const MAX_APPENDED_CLOSERS = 2;
109
+ /**
110
+ * Scan JSON text outside its strings and return the closers its still-open objects and arrays
111
+ * need, innermost first. Undefined when nothing is open, when the text ends inside a string, or
112
+ * when a closer does not match its opener: only a missing tail, never a misplaced bracket.
113
+ */
114
+ function missingClosers(text) {
115
+ const open = [];
116
+ let inString = false, escaped = false;
117
+ for (const char of text) {
118
+ if (inString) {
119
+ if (escaped)
120
+ escaped = false;
121
+ else if (char === '\\')
122
+ escaped = true;
123
+ else if (char === '"')
124
+ inString = false;
125
+ }
126
+ else if (char === '"')
127
+ inString = true;
128
+ else if (char === '{')
129
+ open.push('}');
130
+ else if (char === '[')
131
+ open.push(']');
132
+ else if ((char === '}' || char === ']') && open.pop() !== char)
133
+ return undefined;
134
+ }
135
+ return inString || !open.length ? undefined : open.reverse().join('');
136
+ }
137
+ /**
138
+ * The index just past the object that opens `text`, or undefined when the text does not open with
139
+ * an object or that object never closes. Brackets inside strings are not counted.
140
+ */
141
+ function envelopeEnd(text) {
142
+ const start = text.search(/\S/);
143
+ if (start < 0 || text[start] !== '{')
144
+ return undefined;
145
+ let depth = 0, inString = false, escaped = false;
146
+ for (let index = start; index < text.length; index += 1) {
147
+ const char = text[index];
148
+ if (inString) {
149
+ if (escaped)
150
+ escaped = false;
151
+ else if (char === '\\')
152
+ escaped = true;
153
+ else if (char === '"')
154
+ inString = false;
155
+ }
156
+ else if (char === '"')
157
+ inString = true;
158
+ else if (char === '{' || char === '[')
159
+ depth += 1;
160
+ else if ((char === '}' || char === ']') && --depth === 0)
161
+ return index + 1;
162
+ }
163
+ return undefined;
83
164
  }
165
+ const truncatedStop = (stopReason) => stopReason === 'length' || stopReason === 'max_tokens';
84
166
  /** Classify parser failures without echoing model text, paths, or private analysis. */
85
- function syntaxFailure(error) {
167
+ function syntaxFailure(error, text) {
86
168
  const message = error.message;
87
169
  const position = message.match(/at position (\d+)(?: \(line (\d+) column (\d+)\))?/);
88
170
  const location = position ? ` at position ${position[1]}${position[2] ? ` (line ${position[2]}, column ${position[3]})` : ''}` : '';
171
+ // V8 reports a missing final brace as "Expected ',' or '}' after property value" at the text's
172
+ // length, so the end of the text is located by position, not only by the "unexpected end" wording.
173
+ const atEnd = /unexpected end/i.test(message) || (position !== null && Number(position[1]) >= text.trimEnd().length);
89
174
  const category = /bad (?:escaped character|unicode escape)/i.test(message) ? 'invalidEscape'
90
175
  : /bad control character/i.test(message) ? 'unescapedControlCharacter'
91
176
  : /unterminated string/i.test(message) ? 'unterminatedString'
92
- : /unexpected end/i.test(message) ? 'unexpectedEnd'
177
+ : atEnd ? 'unexpectedEnd'
93
178
  : /unexpected token/i.test(message) ? 'unexpectedToken' : 'syntax';
94
- return `Invalid completion JSON [${category}]${location}. Both final text and complete_agent arguments must contain one complete JSON object, without analysis tags or surrounding prose. Use forward slashes for Windows paths (C:/repo/src/file.ts), or escape each backslash; escape quotes inside strings and write line breaks as \\n escapes, keeping the summary's markdown structure. Preserve the completion envelope and required fields. Keep the handoff concise by default, without repeating file contents or the intake transcript. ${FINAL_RESPONSE_GUIDANCE} Keep the enclosing completion valid JSON.`;
179
+ const closers = category === 'unexpectedEnd' ? missingClosers(text) : undefined;
180
+ const closes = (tail) => { try {
181
+ JSON.parse(text.trimEnd() + tail);
182
+ return true;
183
+ }
184
+ catch {
185
+ return false;
186
+ } };
187
+ // Name the one fix: a generic "keep it valid JSON" let a model drop the same brace five times.
188
+ const ending = category !== 'unexpectedEnd' ? ''
189
+ : closers && closers.length > MAX_APPENDED_CLOSERS ? ` The JSON ended before it was closed: ${closers.length} objects or arrays are still open, so the answer stopped early. Send the whole completion again, shorter, from its opening brace.`
190
+ : closers && closes(closers) ? ` The JSON ended before it was closed: add \`${closers}\` at the very end to close the completion envelope.`
191
+ : ' The JSON ended before it was closed: finish the last value, then close every open object and array.';
192
+ return `Invalid completion JSON [${category}]${location}.${ending} Both final text and complete_agent arguments must contain one complete JSON object, without analysis tags or surrounding prose. Use forward slashes for Windows paths (C:/repo/src/file.ts), or escape each backslash; escape quotes inside strings and write line breaks as \\n escapes, keeping the summary's markdown structure. Preserve the completion envelope and required fields. Keep the handoff concise by default, without repeating file contents or the intake transcript. ${FINAL_RESPONSE_GUIDANCE} Keep the enclosing completion valid JSON.`;
193
+ }
194
+ /**
195
+ * Parse completion JSON, appending the closing brackets a model left off its end. The live shape is
196
+ * a finished report ending `..."prUrl":"…"}`: output closed, the envelope's own `}` never written,
197
+ * and the same omission on every retry. The appended text must parse, and the result then faces
198
+ * every contract and schema check unchanged, so a member closed into the wrong object is still
199
+ * rejected. A response stopped by the output-token limit is never closed by the host.
200
+ *
201
+ * Text after a complete envelope is dropped. A model that misses its end of turn keeps generating
202
+ * past the closing brace: a sign-off, or an invented next task with a second completion for it.
203
+ * The envelope was whole when the turn should have ended, so it is judged alone, by every check
204
+ * that follows. A stray closing bracket there is a misplaced bracket instead, and stays an error.
205
+ */
206
+ function parseCompletionJson(text, stopReason, notes) {
207
+ try {
208
+ return JSON.parse(text);
209
+ }
210
+ catch (error) {
211
+ const end = envelopeEnd(text);
212
+ const runOn = end === undefined ? '' : text.slice(end).trim();
213
+ if (end !== undefined && runOn && !/^[}\]]/.test(runOn)) {
214
+ let envelope;
215
+ try {
216
+ envelope = JSON.parse(text.slice(0, end));
217
+ }
218
+ catch {
219
+ throw error;
220
+ }
221
+ notes?.push(`completion was followed by ${runOn.length} characters of text after its closing brace, dropped by the host`);
222
+ return envelope;
223
+ }
224
+ const closers = truncatedStop(stopReason) ? undefined : missingClosers(text);
225
+ if (!closers || closers.length > MAX_APPENDED_CLOSERS)
226
+ throw error;
227
+ let value;
228
+ try {
229
+ value = JSON.parse(text.trimEnd() + closers);
230
+ }
231
+ catch {
232
+ throw error;
233
+ }
234
+ notes?.push(`completion JSON ended without its last ${closers.length === 1 ? 'closing bracket' : `${closers.length} closing brackets`} (${closers}), appended by the host`);
235
+ return value;
236
+ }
95
237
  }
96
238
  /**
97
239
  * Undo one extra layer of string escaping in a summary. Some models JSON-escape the summary again
98
240
  * inside already-JSON tool arguments, so the parsed text holds a backslash and an "n" where its
99
- * line breaks belong, and the transcript draws its markdown as one literal paragraph. The decode
100
- * runs only when the text has no real line break and at least two escaped paragraph breaks, so a
101
- * summary that merely mentions an escape sequence, or a Windows path, is left as written.
241
+ * line breaks belong, and the transcript draws its markdown as one literal paragraph.
242
+ *
243
+ * Two shapes are decoded. A summary escaped throughout has no real line break and at least two
244
+ * escaped paragraph breaks; every escape in it is undone. A model can also switch to the extra
245
+ * escaping partway through, leaving a few real line breaks and the rest escaped: one `## heading`
246
+ * then swallows everything after it. That mixed summary is decoded only when at least two escaped
247
+ * breaks outside code open markdown structure (a heading, list item, quote, table, fence, or a
248
+ * paragraph break before text). Only its `\"` outside code, and its `\n` outside code on the lines
249
+ * holding that structure, are undone, so inline code, real fenced blocks and the lines the model
250
+ * wrote correctly keep the escapes and Windows paths they show. A summary that merely mentions an
251
+ * escape sequence, or a Windows path, is left as written.
102
252
  * Sessions saved before this decode ran still hold the escaped text, so their readers apply it too
103
253
  * (`displayHistory` in sessions.ts).
104
254
  */
105
255
  export function decodeDoubleEscapedSummary(summary, notes) {
106
- if (summary.includes('\n') || (summary.match(/\\n\\n/g)?.length ?? 0) < 2)
256
+ if (!summary.includes('\n')) {
257
+ if ((summary.match(/\\n\\n/g)?.length ?? 0) < 2)
258
+ return summary;
259
+ notes?.push('completion summary arrived with its newlines escaped twice and was decoded');
260
+ const decoded = { n: '\n', r: '\r', t: '\t', '"': '"', '\\': '\\' };
261
+ return summary.replace(/\\(["\\nrt])/g, (_, char) => decoded[char]);
262
+ }
263
+ // Without a literal backslash-n there is no escaped break to repair, and the scan below is skipped.
264
+ if (!summary.includes('\\n'))
107
265
  return summary;
108
- notes?.push('completion summary arrived with its newlines escaped twice and was decoded');
109
- const decoded = { n: '\n', r: '\r', t: '\t', '"': '"', '\\': '\\' };
110
- return summary.replace(/\\(["\\nrt])/g, (_, char) => decoded[char]);
266
+ // The escaped part is the real lines whose prose holds escaped structure. Breaks are decoded only
267
+ // there, so a Windows path on a line the model wrote correctly (`C:\new\tests`) keeps its
268
+ // separators; an escaped quote has no such reading and is decoded on every line.
269
+ const structuralLines = new Set();
270
+ let structural = 0;
271
+ mapOutsideCode(summary, (prose, line, beforeCode) => {
272
+ // Inline code right after the piece is the text a paragraph break opens; a backtick stands in for
273
+ // it, which no block-opener alternative matches on its own.
274
+ const count = (beforeCode ? `${prose}\`` : prose).match(ESCAPED_STRUCTURE)?.length ?? 0;
275
+ if (count > 0)
276
+ structuralLines.add(line);
277
+ structural += count;
278
+ return prose;
279
+ });
280
+ if (structural < 2)
281
+ return summary;
282
+ notes?.push('completion summary arrived with some of its newlines escaped twice and was decoded');
283
+ // `\\` is matched as a unit and kept, so an escaped backslash before an "n" is never read as a break.
284
+ return mapOutsideCode(summary, (prose, line) => prose.replace(/\\(\\|n|")/g, (escape, char) => char === '"' ? '"' : char === 'n' && structuralLines.has(line) ? '\n' : escape));
285
+ }
286
+ /**
287
+ * An escaped break that stands for markdown structure: a whole run of `\n` before a block opener,
288
+ * or a whole run of two or more before text. "Regex \n\n matches" (a run before a space) is prose,
289
+ * not layout; the run is matched from its start to its end, so its own last `\n` never counts as
290
+ * the text after it.
291
+ */
292
+ const ESCAPED_STRUCTURE = /(?<!\\n)(?:\\n)+(?=#{1,6} |[-*+] |\d+[.)] |> |\||```|~~~)|(?<!\\n)(?:\\n){2,}(?!\\n)(?=\S)/g;
293
+ function mapOutsideCode(text, transform) {
294
+ const lines = text.split('\n');
295
+ const code = codeBlockLines(lines);
296
+ const out = [];
297
+ for (let start = 0; start < lines.length;) {
298
+ if (code[start]) {
299
+ out.push(lines[start++]);
300
+ continue;
301
+ }
302
+ let end = start + 1;
303
+ while (end < lines.length && !code[end] && !interruptsParagraph(lines[end]))
304
+ end++;
305
+ out.push(mapProse(lines.slice(start, end).join('\n'), start, transform));
306
+ start = end;
307
+ }
308
+ return out.join('\n');
309
+ }
310
+ /**
311
+ * Whether the backtick run at `start` is a fence whose line breaks were escaped: one that follows an
312
+ * escaped break, or one followed by an info string and an escaped break (```` ```ts\n ````). An
313
+ * inline span of three backticks has prose or code after its run, not a bare word and a break.
314
+ */
315
+ function escapedFence(source, start, length) {
316
+ if (length < 3)
317
+ return false;
318
+ if (source.slice(Math.max(0, start - 2), start) === '\\n')
319
+ return true;
320
+ const info = /[\w+.#-]*\\n/y;
321
+ info.lastIndex = start + length;
322
+ return info.test(source);
323
+ }
324
+ /** Which lines belong to a fenced or indented code block. */
325
+ function codeBlockLines(lines) {
326
+ let fence;
327
+ let indented = false;
328
+ let previousBlank = true;
329
+ return lines.map(line => {
330
+ const blank = line.trim() === '';
331
+ const afterBlank = previousBlank;
332
+ previousBlank = blank;
333
+ if (fence !== undefined) {
334
+ const close = /^ {0,3}(`{3,}|~{3,})[ \t\r]*$/.exec(line)?.[1];
335
+ if (close !== undefined && close[0] === fence[0] && close.length >= fence.length)
336
+ fence = undefined;
337
+ return true;
338
+ }
339
+ indented = line.startsWith(' ') ? indented || afterBlank : indented && blank;
340
+ if (indented)
341
+ return true;
342
+ // A real opener as `openingFence` reads one: a backtick fence's info string holds no backtick.
343
+ // An escaped fence's layout is its run, at most a language word, then a literal break; a literal
344
+ // `\n` further along the info string (```` ```js title="\n" ````) leaves the opener real.
345
+ const open = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line);
346
+ if (open === null || (open[1][0] === '`' && open[2].includes('`')) || /^[\w+.#-]*\\n/.test(open[2]))
347
+ return false;
348
+ fence = open[1];
349
+ return true;
350
+ });
351
+ }
352
+ /**
353
+ * Whether a span body from `start` to `end` crosses a paragraph boundary, as `maskSegmentCodeSpans`
354
+ * reads a multi-line span. `firstBreak` is the first real line break at or after `start` (Infinity
355
+ * when there is none), which the caller tracks as it walks forward instead of searching again. A body on one real line never does, whatever markers it shows: the
356
+ * transcript renders it as a single-line span. Across lines, the paragraph has no interrupting line
357
+ * after its first, so only the body's first and last pieces (parts of their lines) can interrupt.
358
+ */
359
+ function crossesParagraph(source, start, end, firstBreak) {
360
+ if (firstBreak > end)
361
+ return false;
362
+ return interruptsParagraph(source.slice(start, firstBreak)) || interruptsParagraph(source.slice(source.lastIndexOf('\n', end) + 1, end));
363
+ }
364
+ /**
365
+ * Transform the prose of one paragraph, keeping its code spans. A backslash before punctuation is
366
+ * skipped as a pair, so an escaped backtick never opens a span, but the pair stays in the prose the
367
+ * transform sees (`\"` is one of the escapes it decodes). The search for a closer stops at the first
368
+ * run of the opener's length, and a length already searched for in vain from an earlier position is
369
+ * not searched for again, so no part of the paragraph is scanned twice for the same length. The next
370
+ * real line break is found once per line, not once per span, which keeps a line of many spans linear.
371
+ * A prose piece that ends where a span begins is passed with `beforeCode`, so a paragraph break
372
+ * escaped just before inline code can still be read as one.
373
+ */
374
+ function mapProse(source, firstLine, transform) {
375
+ let out = '';
376
+ let prose = '';
377
+ let line = firstLine;
378
+ let nextBreak = -1;
379
+ const unclosed = new Set();
380
+ const runs = /`+/g;
381
+ const closerFor = (from, length) => {
382
+ if (unclosed.has(length))
383
+ return undefined;
384
+ runs.lastIndex = from;
385
+ for (let run = runs.exec(source); run; run = runs.exec(source)) {
386
+ if (run[0].length === length && !escapedFence(source, run.index, length))
387
+ return run.index;
388
+ }
389
+ unclosed.add(length);
390
+ return undefined;
391
+ };
392
+ const flush = (beforeCode = false) => {
393
+ out += transform(prose, line, beforeCode);
394
+ prose = '';
395
+ };
396
+ for (let index = 0; index < source.length;) {
397
+ const char = source[index];
398
+ if (char === '\n') {
399
+ flush();
400
+ out += '\n';
401
+ line++;
402
+ index++;
403
+ continue;
404
+ }
405
+ if (char === '\\' && index + 1 < source.length && /[!-/:-@[-`{-~]/.test(source[index + 1])) {
406
+ prose += source.slice(index, index + 2);
407
+ index += 2;
408
+ continue;
409
+ }
410
+ if (char !== '`') {
411
+ prose += char;
412
+ index++;
413
+ continue;
414
+ }
415
+ runs.lastIndex = index;
416
+ const length = runs.exec(source)[0].length;
417
+ const closing = escapedFence(source, index, length) ? undefined : closerFor(index + length, length);
418
+ if (closing !== undefined && nextBreak !== Infinity && nextBreak < index) {
419
+ const found = source.indexOf('\n', index);
420
+ nextBreak = found === -1 ? Infinity : found;
421
+ }
422
+ if (closing === undefined || crossesParagraph(source, index + length, closing, nextBreak)) {
423
+ prose += '`'.repeat(length);
424
+ index += length;
425
+ continue;
426
+ }
427
+ flush(true);
428
+ const span = source.slice(index, closing + length);
429
+ out += span;
430
+ line += span.split('\n').length - 1;
431
+ index += span.length;
432
+ }
433
+ flush();
434
+ return out;
435
+ }
436
+ /** The envelope's own report fields, which a strict output schema that does not declare them refuses. */
437
+ const ENVELOPE_FIELDS = {
438
+ summary: (item) => typeof item === 'string' && item.trim().length > 0,
439
+ tests: (item) => Array.isArray(item) && item.every(entry => typeof entry === 'string'),
440
+ };
441
+ /**
442
+ * Move the envelope's `summary` and `tests` back out of `output`.
443
+ *
444
+ * The completion tool asks for `summary` and `tests` beside `output`, and a node's output schema
445
+ * often has look-alike fields of its own (`implementationSummary`, `testsRun`). Models copy the two
446
+ * envelope fields into `output` as well, and a strict schema then rejects the whole handoff with
447
+ * "output.summary is not allowed" — a live run spent every repair resending that same object after
448
+ * its work was done. The copy is the model's own text in the wrong place, so the host puts it where
449
+ * the envelope reads it (keeping the top-level copy when one is already usable) and records the
450
+ * move. Only undeclared fields under a schema that forbids extras are touched: a schema that
451
+ * declares `summary` or accepts extras gets the output exactly as sent.
452
+ */
453
+ function liftEnvelopeFields(envelope, output, schema, notes) {
454
+ if (!schema || schema.additionalProperties !== false)
455
+ return output;
456
+ const misplaced = Object.keys(ENVELOPE_FIELDS)
457
+ .filter(key => Object.hasOwn(output, key) && !Object.hasOwn(schema.properties ?? {}, key));
458
+ if (!misplaced.length)
459
+ return output;
460
+ const rest = { ...output };
461
+ for (const key of misplaced) {
462
+ const lifted = !ENVELOPE_FIELDS[key](envelope[key]);
463
+ if (lifted)
464
+ envelope[key] = rest[key];
465
+ delete rest[key];
466
+ notes?.push(lifted
467
+ ? `completion output carried the envelope's ${key}; it was moved to the top level`
468
+ : `completion output repeated the envelope's ${key}; the copy inside output was dropped`);
469
+ }
470
+ return rest;
111
471
  }
112
472
  /**
113
473
  * Parse one completion, accepting mechanically imperfect envelopes that are semantically correct.
@@ -119,9 +479,10 @@ export function decodeDoubleEscapedSummary(summary, notes) {
119
479
  * rejection for either burns a repair on a coin flip and can end a node whose work is already
120
480
  * done, so they are coerced and recorded instead.
121
481
  */
122
- export function parseCompletion(text, options, reject, notes) {
482
+ export function parseCompletion(text, options, reject, notes, stopReason) {
483
+ const body = text.replace(/^```(?:json)?\s*\n?/, '').replace(/\n?```\s*$/, '');
123
484
  try {
124
- const value = JSON.parse(text.replace(/^```(?:json)?\s*\n?/, '').replace(/\n?```\s*$/, ''));
485
+ const value = parseCompletionJson(body, stopReason, notes);
125
486
  if (options.completionPolicy && value && typeof value === 'object' && !Array.isArray(value)) {
126
487
  const policy = options.completionPolicy;
127
488
  const outcome = value.outcome ?? (policy.mode === 'single' ? policy.outcome : undefined);
@@ -142,6 +503,8 @@ export function parseCompletion(text, options, reject, notes) {
142
503
  }
143
504
  if (!output || typeof output !== 'object' || Array.isArray(output))
144
505
  throw new Error("Completion outcome or output does not match the declared contract");
506
+ if (value.output !== undefined)
507
+ output = liftEnvelopeFields(value, output, options.outputSchema, notes);
145
508
  if (options.canonicalTask !== undefined)
146
509
  output.originalTask = options.canonicalTask;
147
510
  if (options.outputSchema)
@@ -190,6 +553,6 @@ export function parseCompletion(text, options, reject, notes) {
190
553
  throw new Error("Completion needs a nonempty summary and a tests array of strings");
191
554
  }
192
555
  catch (error) {
193
- reject(error instanceof SyntaxError ? syntaxFailure(error) : error instanceof Error ? error.message : "Invalid completion JSON");
556
+ reject(error instanceof SyntaxError ? syntaxFailure(error, body) : error instanceof Error ? error.message : "Invalid completion JSON");
194
557
  }
195
558
  }
@@ -72,7 +72,62 @@ export interface Config {
72
72
  systemPromptOverride?: string;
73
73
  /** Days without activity after which a session is archived automatically; unset means never. */
74
74
  autoArchiveDays?: number;
75
+ /** Browser tool settings. */
76
+ browser?: BrowserConfig;
77
+ /** The web_search tool's backends and which one it uses. */
78
+ webSearch?: WebSearchConfig;
75
79
  }
80
+ /**
81
+ * Browser tool settings.
82
+ *
83
+ * `capsolverApiKey` is a secret like a provider's `apiKey`: the engine reports only whether one is
84
+ * present, never its value. `CAPSOLVER_API_KEY` in the environment is the fallback when it is unset.
85
+ */
86
+ export interface BrowserConfig {
87
+ capsolverApiKey?: string;
88
+ }
89
+ export declare const MAX_CAPSOLVER_API_KEY_LENGTH = 256;
90
+ export declare function validateBrowserConfig(value: unknown): BrowserConfig;
91
+ /** The search services the web_search tool can query, in the order "automatic" tries them. */
92
+ export declare const WEB_SEARCH_PROVIDERS: readonly ["brave", "tavily", "exa", "serper", "google", "searxng"];
93
+ export type WebSearchProviderId = typeof WEB_SEARCH_PROVIDERS[number];
94
+ /** The configuration field that holds each keyed service's API key. SearXNG takes a URL instead. */
95
+ export declare const WEB_SEARCH_KEY_FIELDS: {
96
+ readonly brave: "braveApiKey";
97
+ readonly tavily: "tavilyApiKey";
98
+ readonly exa: "exaApiKey";
99
+ readonly serper: "serperApiKey";
100
+ readonly google: "googleApiKey";
101
+ };
102
+ export type WebSearchKeyField = typeof WEB_SEARCH_KEY_FIELDS[keyof typeof WEB_SEARCH_KEY_FIELDS];
103
+ export declare const WEB_SEARCH_FIELDS: readonly [...("braveApiKey" | "tavilyApiKey" | "exaApiKey" | "serperApiKey" | "googleApiKey")[], "defaultProvider", "googleSearchEngineId", "searxngUrl"];
104
+ /**
105
+ * The web_search tool's settings.
106
+ *
107
+ * The API keys are secrets like a provider's `apiKey`: the engine reports only whether each is
108
+ * present, never its value. `googleSearchEngineId` (the Programmable Search Engine's `cx`) and
109
+ * `searxngUrl` are not secrets and are reported as saved. `defaultProvider` picks the service; unset
110
+ * means the first one in WEB_SEARCH_PROVIDERS that is configured.
111
+ */
112
+ export interface WebSearchConfig {
113
+ defaultProvider?: WebSearchProviderId;
114
+ braveApiKey?: string;
115
+ tavilyApiKey?: string;
116
+ exaApiKey?: string;
117
+ serperApiKey?: string;
118
+ googleApiKey?: string;
119
+ googleSearchEngineId?: string;
120
+ searxngUrl?: string;
121
+ }
122
+ export declare const MAX_WEB_SEARCH_API_KEY_LENGTH = 256;
123
+ export declare const MAX_WEB_SEARCH_URL_LENGTH = 2048;
124
+ /** A SearXNG base URL: HTTP(S), no credentials, query or fragment. Returns the normalized URL or an error message. */
125
+ export declare function checkSearxngUrl(value: string): {
126
+ url: string;
127
+ } | {
128
+ error: string;
129
+ };
130
+ export declare function validateWebSearchConfig(value: unknown): WebSearchConfig;
76
131
  /** The longest override the setting accepts: the same bound the workspace guide is clipped to. */
77
132
  export declare const MAX_SYSTEM_PROMPT_OVERRIDE = 16000;
78
133
  export declare const AUTO_ARCHIVE_MIN_DAYS = 1;
@@ -110,6 +165,12 @@ export declare function resolveConfiguredLimits(config: Pick<Config, 'limits'>):
110
165
  export declare function validateMemoryConfig(memory: unknown): void;
111
166
  /** Environment overrides win over config.json; nothing is persisted back. */
112
167
  export declare function resolveMemoryConfig(config: Config, env?: NodeJS.ProcessEnv): MemoryConfig;
168
+ /**
169
+ * The installation's configuration, with saved provider API keys read back from the OS credential
170
+ * store. A `config.json` that still holds keys in plaintext (written before keys moved to the
171
+ * store, or edited by hand) has them moved on this load; where that cannot happen, the keys stay in
172
+ * the file and the configuration loads exactly as before.
173
+ */
113
174
  export declare function loadConfig(directory?: string): Promise<Config>;
114
175
  /**
115
176
  * The anonymous-feedback preference this installation has saved right now.