@andorra-labs/code 0.1.14 → 0.1.16

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 (180) hide show
  1. package/dist/src/acp-agent.d.ts +54 -0
  2. package/dist/src/acp-agent.js +991 -0
  3. package/dist/src/agent-definitions.js +29 -6
  4. package/dist/src/agent-execution.js +8 -2
  5. package/dist/src/agent-mcp-catalog.js +2 -0
  6. package/dist/src/agent-mcp.d.ts +3 -1
  7. package/dist/src/agent-mcp.js +97 -11
  8. package/dist/src/andorra/entry.js +21 -3
  9. package/dist/src/andorra/hosted.d.ts +3 -0
  10. package/dist/src/andorra/hosted.js +5 -1
  11. package/dist/src/andorra/notices.d.ts +10 -1
  12. package/dist/src/andorra/notices.js +25 -2
  13. package/dist/src/andorra/terminal.d.ts +2 -0
  14. package/dist/src/andorra/terminal.js +2 -2
  15. package/dist/src/app-server/protocol.d.ts +9 -2
  16. package/dist/src/app-server/protocol.js +1 -1
  17. package/dist/src/app-server/workspace.d.ts +1 -0
  18. package/dist/src/app-server/workspace.js +141 -10
  19. package/dist/src/app-server.d.ts +115 -0
  20. package/dist/src/app-server.js +980 -63
  21. package/dist/src/auth/AuthManager.js +4 -4
  22. package/dist/src/auth/deployment.js +2 -2
  23. package/dist/src/browser-bridge.d.ts +1 -0
  24. package/dist/src/browser-bridge.js +5 -2
  25. package/dist/src/browser-external-app.d.ts +27 -0
  26. package/dist/src/browser-external-app.js +60 -0
  27. package/dist/src/browser-panel-tool.d.ts +6 -0
  28. package/dist/src/browser-panel-tool.js +36 -0
  29. package/dist/src/browser-runner.js +1 -0
  30. package/dist/src/browser-server.d.ts +5 -0
  31. package/dist/src/browser-server.js +27 -3
  32. package/dist/src/browser-ui/style.css +3 -3
  33. package/dist/src/browser-ui/tokens.css +27 -16
  34. package/dist/src/browser-view.d.ts +16 -0
  35. package/dist/src/browser-view.js +60 -2
  36. package/dist/src/bug-report.d.ts +81 -0
  37. package/dist/src/bug-report.js +235 -0
  38. package/dist/src/claude-provider.d.ts +2 -1
  39. package/dist/src/claude-provider.js +13 -9
  40. package/dist/src/cli-sign-in.d.ts +3 -1
  41. package/dist/src/cli-sign-in.js +4 -1
  42. package/dist/src/cli.js +184 -40
  43. package/dist/src/codex-errors.js +4 -1
  44. package/dist/src/coding-tools.js +7 -7
  45. package/dist/src/command-screens.d.ts +9 -2
  46. package/dist/src/command-screens.js +166 -97
  47. package/dist/src/commands.d.ts +3 -2
  48. package/dist/src/commands.js +1 -0
  49. package/dist/src/compaction-phrases.d.ts +4 -0
  50. package/dist/src/compaction-phrases.js +20 -0
  51. package/dist/src/completion-gates.d.ts +22 -0
  52. package/dist/src/completion-gates.js +11 -0
  53. package/dist/src/config.d.ts +5 -0
  54. package/dist/src/config.js +48 -0
  55. package/dist/src/context-compaction.js +2 -1
  56. package/dist/src/decision/DecisionManager.js +3 -2
  57. package/dist/src/decision/requestPhrases.d.ts +4 -0
  58. package/dist/src/decision/requestPhrases.js +23 -0
  59. package/dist/src/github-inbox.d.ts +55 -0
  60. package/dist/src/github-inbox.js +153 -0
  61. package/dist/src/google-provider.d.ts +31 -0
  62. package/dist/src/google-provider.js +153 -0
  63. package/dist/src/graph-health.js +8 -4
  64. package/dist/src/graph-manager-chat.js +6 -1
  65. package/dist/src/graph-provider-portability.js +32 -10
  66. package/dist/src/graph-quota.d.ts +29 -2
  67. package/dist/src/graph-quota.js +68 -10
  68. package/dist/src/graph-runner.js +24 -7
  69. package/dist/src/graph-server.d.ts +1 -1
  70. package/dist/src/graph-server.js +9 -7
  71. package/dist/src/graph-sync.d.ts +1 -0
  72. package/dist/src/graph-sync.js +93 -34
  73. package/dist/src/graph-tool.d.ts +2 -0
  74. package/dist/src/graph-tool.js +2 -2
  75. package/dist/src/graph-ui/app.js +177 -41
  76. package/dist/src/graph-ui/controls.css +1 -0
  77. package/dist/src/graph-ui/edge-router.js +121 -53
  78. package/dist/src/graph-ui/embed.js +2 -2
  79. package/dist/src/graph-ui/icons.js +1 -0
  80. package/dist/src/graph-ui/index.html +1 -1
  81. package/dist/src/graph-ui/manager.css +1 -1
  82. package/dist/src/graph-ui/manager.js +2 -2
  83. package/dist/src/graph-ui/sidebar.js +30 -0
  84. package/dist/src/graph-ui/studio-canvas.js +26 -13
  85. package/dist/src/graph-ui/studio.css +15 -7
  86. package/dist/src/graph-ui/studio.js +11 -4
  87. package/dist/src/graph-ui/style.css +77 -45
  88. package/dist/src/graph-ui/theme.js +3 -36
  89. package/dist/src/graph-ui/tokens.css +27 -19
  90. package/dist/src/graph-visibility.d.ts +31 -0
  91. package/dist/src/graph-visibility.js +102 -0
  92. package/dist/src/graphs.js +4 -3
  93. package/dist/src/live-model.d.ts +24 -0
  94. package/dist/src/live-model.js +37 -0
  95. package/dist/src/managed-sign-in.d.ts +1 -0
  96. package/dist/src/managed-sign-in.js +13 -0
  97. package/dist/src/membership-errors.d.ts +2 -0
  98. package/dist/src/membership-errors.js +5 -1
  99. package/dist/src/membership.d.ts +23 -1
  100. package/dist/src/membership.js +48 -6
  101. package/dist/src/model-health-cache.js +1 -1
  102. package/dist/src/model-metadata.d.ts +1 -1
  103. package/dist/src/model-metadata.js +12 -3
  104. package/dist/src/paged-transcript.d.ts +2 -0
  105. package/dist/src/paged-transcript.js +16 -0
  106. package/dist/src/plan-pass.d.ts +59 -0
  107. package/dist/src/plan-pass.js +165 -0
  108. package/dist/src/provider-connection.js +17 -0
  109. package/dist/src/provider-engine.d.ts +5 -0
  110. package/dist/src/provider-engine.js +6 -3
  111. package/dist/src/provider-import.js +3 -1
  112. package/dist/src/provider-settings.js +14 -2
  113. package/dist/src/providers.d.ts +33 -2
  114. package/dist/src/providers.js +101 -28
  115. package/dist/src/pull-request-checks.d.ts +26 -0
  116. package/dist/src/pull-request-checks.js +56 -0
  117. package/dist/src/pull-request-conversation.d.ts +134 -0
  118. package/dist/src/pull-request-conversation.js +221 -0
  119. package/dist/src/pull-request-create.d.ts +175 -0
  120. package/dist/src/pull-request-create.js +392 -0
  121. package/dist/src/pull-request-details.d.ts +242 -0
  122. package/dist/src/pull-request-details.js +614 -0
  123. package/dist/src/pull-request-edit.d.ts +23 -0
  124. package/dist/src/pull-request-edit.js +91 -0
  125. package/dist/src/pull-request-logs.d.ts +76 -0
  126. package/dist/src/pull-request-logs.js +172 -0
  127. package/dist/src/pull-request-merge.d.ts +112 -0
  128. package/dist/src/pull-request-merge.js +258 -0
  129. package/dist/src/pull-request-review.d.ts +137 -0
  130. package/dist/src/pull-request-review.js +401 -0
  131. package/dist/src/pull-requests.d.ts +43 -2
  132. package/dist/src/pull-requests.js +112 -21
  133. package/dist/src/react-runtime.js +58 -9
  134. package/dist/src/read-document-tool.d.ts +2 -0
  135. package/dist/src/read-document-tool.js +6 -6
  136. package/dist/src/remote/engine-pool.js +42 -6
  137. package/dist/src/run-control.d.ts +10 -0
  138. package/dist/src/run-control.js +24 -0
  139. package/dist/src/run-progress.d.ts +10 -0
  140. package/dist/src/run-progress.js +122 -0
  141. package/dist/src/run-records.d.ts +2 -2
  142. package/dist/src/runtime-environment.d.ts +1 -0
  143. package/dist/src/runtime-environment.js +13 -0
  144. package/dist/src/runtime.d.ts +5 -1
  145. package/dist/src/runtime.js +14 -2
  146. package/dist/src/save-lock.js +14 -7
  147. package/dist/src/session-title.d.ts +3 -0
  148. package/dist/src/session-title.js +5 -2
  149. package/dist/src/sign-in-detection.d.ts +1 -1
  150. package/dist/src/sign-in-detection.js +10 -3
  151. package/dist/src/sign-in-offer.js +1 -1
  152. package/dist/src/skill-commands.js +1 -1
  153. package/dist/src/skills/bundled/bug-report/SKILL.md +80 -0
  154. package/dist/src/skills/bundled/graph-manager/SKILL.md +9 -1
  155. package/dist/src/skills/bundled/graph-manager/errors.md +1 -0
  156. package/dist/src/skills/bundled/provenance.json +7 -2
  157. package/dist/src/skills/runtime-skills.js +1 -0
  158. package/dist/src/subagent-run.js +1 -0
  159. package/dist/src/telemetry/capture-core.d.ts +17 -0
  160. package/dist/src/telemetry/capture-core.js +59 -1
  161. package/dist/src/telemetry/classify.d.ts +3 -1
  162. package/dist/src/telemetry/classify.js +37 -0
  163. package/dist/src/telemetry/emitter.d.ts +2 -0
  164. package/dist/src/telemetry/emitter.js +42 -5
  165. package/dist/src/telemetry/schema.d.ts +22 -0
  166. package/dist/src/telemetry/schema.js +68 -1
  167. package/dist/src/telemetry/surface.d.ts +1 -0
  168. package/dist/src/telemetry/uploader.d.ts +12 -1
  169. package/dist/src/telemetry/uploader.js +30 -2
  170. package/dist/src/terminal-links.d.ts +16 -0
  171. package/dist/src/terminal-links.js +113 -0
  172. package/dist/src/terminal-ui.d.ts +8 -1
  173. package/dist/src/terminal-ui.js +40 -14
  174. package/dist/src/tool-catalog.js +1 -1
  175. package/dist/src/trajectory.js +6 -1
  176. package/dist/src/transcript.d.ts +2 -0
  177. package/dist/src/transcript.js +10 -3
  178. package/dist/src/types.d.ts +9 -0
  179. package/dist/src/usage-analytics.js +18 -10
  180. package/package.json +2 -1
@@ -0,0 +1,991 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { readFileSync, statSync } from 'node:fs';
3
+ import { isDeepStrictEqual } from 'node:util';
4
+ import { isAbsolute, relative, resolve } from 'node:path';
5
+ import { createInterface } from 'node:readline';
6
+ import { Readable, Writable } from 'node:stream';
7
+ import { agent, methods, ndJsonStream, PROTOCOL_VERSION, RequestError } from '@agentclientprotocol/sdk';
8
+ import { AppServer } from './app-server.js';
9
+ import { REASONING_EFFORTS, supportsReasoningEffort } from './providers.js';
10
+ import { sessionName } from './sessions.js';
11
+ import { canonicalCodingToolName } from './tool-names.js';
12
+ /** The one sign-in the agent offers: Andorra's own browser OAuth flow, run by the agent (ACP "Agent Auth"). */
13
+ export const ACP_AUTH_METHOD_ID = 'andorra-login';
14
+ /** Session configuration option ids. Clients read the category, not the id. */
15
+ export const ACP_MODEL_OPTION = 'model';
16
+ export const ACP_EFFORT_OPTION = 'reasoning_effort';
17
+ const EFFORT_DEFAULT = 'default';
18
+ /** The name the engine gives a session created without one. */
19
+ const UNTITLED_SESSION = 'New session';
20
+ const MAX_TOOL_OUTPUT_CHARS = 20_000;
21
+ const SESSION_PAGE_SIZE = 50;
22
+ /** Prompts beyond the in-process engine each run in their own engine process; this caps how many run at once. */
23
+ const MAX_EXTRA_ENGINES = 4;
24
+ const ENGINE_READY_TIMEOUT_MS = 60_000;
25
+ const ENGINE_STOP_GRACE_MS = 5_000;
26
+ /** Raised to an engine's listeners when its process ends. Never sent by an engine itself. */
27
+ const ENGINE_EXITED = 'acp.engine.exited';
28
+ /** Reads the app-server's line protocol: responses by id, everything else an event. */
29
+ class LineReader {
30
+ nextId = 1;
31
+ pending = new Map();
32
+ listeners = new Set();
33
+ onReady;
34
+ accept(line) {
35
+ if (!line.trim())
36
+ return;
37
+ let parsed;
38
+ try {
39
+ parsed = JSON.parse(line);
40
+ }
41
+ catch {
42
+ return;
43
+ }
44
+ if (typeof parsed.event === 'string') {
45
+ if (parsed.event === 'ready')
46
+ this.onReady?.();
47
+ for (const listener of [...this.listeners]) {
48
+ try {
49
+ listener(parsed.event, parsed.data ?? {});
50
+ }
51
+ catch { }
52
+ }
53
+ return;
54
+ }
55
+ if (typeof parsed.id !== 'number')
56
+ return;
57
+ const waiter = this.pending.get(parsed.id);
58
+ if (!waiter)
59
+ return;
60
+ this.pending.delete(parsed.id);
61
+ if (parsed.error) {
62
+ const failure = new Error(parsed.error.message ?? 'Engine request failed');
63
+ failure.code = parsed.error.code;
64
+ waiter.reject(failure);
65
+ }
66
+ else {
67
+ waiter.resolve((parsed.result ?? {}));
68
+ }
69
+ }
70
+ listen(listener) {
71
+ this.listeners.add(listener);
72
+ return () => { this.listeners.delete(listener); };
73
+ }
74
+ open() {
75
+ const id = this.nextId++;
76
+ const answered = new Promise((resolveAnswer, reject) => { this.pending.set(id, { resolve: resolveAnswer, reject }); });
77
+ return { id, answered };
78
+ }
79
+ failAll(error) {
80
+ for (const [, waiter] of [...this.pending])
81
+ waiter.reject(error);
82
+ this.pending.clear();
83
+ }
84
+ emit(event, data = {}) {
85
+ for (const listener of [...this.listeners]) {
86
+ try {
87
+ listener(event, data);
88
+ }
89
+ catch { }
90
+ }
91
+ }
92
+ }
93
+ /** The app-server in this process, spoken to the way the desktop app does: one JSON line per request. */
94
+ class InProcessEngine {
95
+ server;
96
+ alive = true;
97
+ buffer = '';
98
+ reader = new LineReader();
99
+ constructor(options) {
100
+ const output = new Writable({
101
+ decodeStrings: false,
102
+ write: (chunk, _encoding, done) => { this.accept(String(chunk)); done(); },
103
+ });
104
+ this.server = new AppServer({ ...options, output, error: options.error ?? process.stderr });
105
+ }
106
+ accept(text) {
107
+ this.buffer += text;
108
+ let index;
109
+ while ((index = this.buffer.indexOf('\n')) >= 0) {
110
+ const line = this.buffer.slice(0, index);
111
+ this.buffer = this.buffer.slice(index + 1);
112
+ this.reader.accept(line);
113
+ }
114
+ }
115
+ listen(listener) { return this.reader.listen(listener); }
116
+ async request(method, params = {}) {
117
+ const { id, answered } = this.reader.open();
118
+ await this.server.handle(JSON.stringify({ id, method, params }));
119
+ return answered;
120
+ }
121
+ close() { return this.server.close(); }
122
+ }
123
+ /** An app-server in its own process, so another prompt can run while the in-process engine is busy. */
124
+ class ChildEngine {
125
+ child;
126
+ reader = new LineReader();
127
+ stopped = false;
128
+ ready;
129
+ constructor(command, errorOutput) {
130
+ this.child = spawn(command[0], command.slice(1), { windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'], env: process.env });
131
+ this.ready = new Promise((resolveReady, reject) => {
132
+ const timer = setTimeout(() => reject(new Error('A new engine did not start in time.')), ENGINE_READY_TIMEOUT_MS);
133
+ timer.unref?.();
134
+ this.reader.onReady = () => { clearTimeout(timer); resolveReady(); };
135
+ this.child.once('exit', () => { clearTimeout(timer); reject(new Error('A new engine exited before it was ready.')); });
136
+ this.child.once('error', error => { clearTimeout(timer); reject(new Error(`A new engine could not start: ${error.message}`)); });
137
+ });
138
+ this.ready.catch(() => undefined);
139
+ this.child.once('exit', () => {
140
+ this.stopped = true;
141
+ this.reader.failAll(new Error('The engine running this prompt exited.'));
142
+ // A run in flight is waiting on events, not on a request: tell its listener the engine is gone.
143
+ this.reader.emit(ENGINE_EXITED);
144
+ });
145
+ this.child.on('error', () => undefined);
146
+ this.child.stdin?.on('error', () => undefined);
147
+ if (this.child.stdout)
148
+ createInterface({ input: this.child.stdout }).on('line', line => this.reader.accept(line));
149
+ // The engine's diagnostics are diagnostics here too; stdout stays protocol-only.
150
+ if (this.child.stderr)
151
+ createInterface({ input: this.child.stderr }).on('line', line => { if (line.trim())
152
+ errorOutput.write(`${line}\n`); });
153
+ }
154
+ get alive() { return !this.stopped; }
155
+ listen(listener) { return this.reader.listen(listener); }
156
+ request(method, params = {}) {
157
+ const stdin = this.child.stdin;
158
+ if (this.stopped || !stdin || stdin.destroyed)
159
+ return Promise.reject(new Error('The engine running this prompt is not running.'));
160
+ const { id, answered } = this.reader.open();
161
+ stdin.write(`${JSON.stringify({ id, method, params })}\n`);
162
+ return answered;
163
+ }
164
+ close() {
165
+ if (this.stopped)
166
+ return Promise.resolve();
167
+ this.stopped = true;
168
+ return new Promise(resolveClosed => {
169
+ const timer = setTimeout(() => { this.child.kill(); resolveClosed(); }, ENGINE_STOP_GRACE_MS);
170
+ timer.unref?.();
171
+ this.child.once('exit', () => { clearTimeout(timer); resolveClosed(); });
172
+ this.child.stdin?.end();
173
+ });
174
+ }
175
+ }
176
+ /** Hands each running prompt an engine of its own: the in-process one first, then extra engine processes. */
177
+ class EnginePool {
178
+ primary;
179
+ command;
180
+ errorOutput;
181
+ busy = new Set();
182
+ extra = [];
183
+ constructor(primary, command, errorOutput) {
184
+ this.primary = primary;
185
+ this.command = command;
186
+ this.errorOutput = errorOutput;
187
+ }
188
+ async acquire() {
189
+ if (!this.busy.has(this.primary)) {
190
+ this.busy.add(this.primary);
191
+ return this.primary;
192
+ }
193
+ for (let index = this.extra.length - 1; index >= 0; index--)
194
+ if (!this.extra[index].alive)
195
+ this.extra.splice(index, 1);
196
+ const idle = this.extra.find(engine => !this.busy.has(engine));
197
+ if (idle) {
198
+ this.busy.add(idle);
199
+ return idle;
200
+ }
201
+ if (this.extra.length >= MAX_EXTRA_ENGINES) {
202
+ throw RequestError.internalError(undefined, `Andorra Code is already running ${MAX_EXTRA_ENGINES + 1} prompts at once. Wait for one to finish.`);
203
+ }
204
+ const engine = new ChildEngine(this.command(), this.errorOutput);
205
+ this.extra.push(engine);
206
+ this.busy.add(engine);
207
+ try {
208
+ await engine.ready;
209
+ }
210
+ catch (error) {
211
+ this.busy.delete(engine);
212
+ this.extra.splice(this.extra.indexOf(engine), 1);
213
+ await engine.close();
214
+ throw error;
215
+ }
216
+ return engine;
217
+ }
218
+ release(engine) { this.busy.delete(engine); }
219
+ async close() {
220
+ await Promise.all(this.extra.splice(0).map(engine => engine.close()));
221
+ await this.primary.close();
222
+ }
223
+ }
224
+ export function promptText(blocks) {
225
+ const parts = [];
226
+ for (const block of blocks) {
227
+ if (block.type === 'text')
228
+ parts.push(block.text);
229
+ else if (block.type === 'resource_link')
230
+ parts.push(`[${block.name ?? block.uri}](${block.uri})`);
231
+ else if (block.type === 'resource') {
232
+ const resource = block.resource;
233
+ if (typeof resource.text === 'string')
234
+ parts.push(`<context uri="${resource.uri ?? ''}">\n${resource.text}\n</context>`);
235
+ else if (resource.uri)
236
+ parts.push(resource.uri);
237
+ }
238
+ }
239
+ return parts.join('\n\n').trim();
240
+ }
241
+ export function toolKind(name) {
242
+ const canonical = canonicalCodingToolName(name);
243
+ if (canonical === 'Read')
244
+ return 'read';
245
+ if (canonical === 'Write' || canonical === 'Edit')
246
+ return 'edit';
247
+ if (canonical === 'Grep' || canonical === 'Glob')
248
+ return 'search';
249
+ if (canonical === 'Bash' || canonical === 'PowerShell')
250
+ return 'execute';
251
+ const lower = name.toLowerCase();
252
+ if (lower.startsWith('read_') || lower === 'git_read' || lower === 'memory_read')
253
+ return 'read';
254
+ if (lower.includes('search'))
255
+ return 'search';
256
+ if (lower === 'nativeexec' || lower === 'asyncprocess' || lower.startsWith('qa.terminal'))
257
+ return 'execute';
258
+ if (lower.startsWith('browser.') || lower.startsWith('qa.browser'))
259
+ return 'fetch';
260
+ return 'other';
261
+ }
262
+ function oneLine(text, limit = 120) {
263
+ const first = text.split(/\r?\n/, 1)[0].trim();
264
+ return first.length > limit ? `${first.slice(0, limit - 1)}…` : first;
265
+ }
266
+ function toolPath(input) {
267
+ if (!input || typeof input !== 'object')
268
+ return undefined;
269
+ const value = input.file_path ?? input.path;
270
+ return typeof value === 'string' && value ? value : undefined;
271
+ }
272
+ /** A short, readable title for a tool call: what it reads, changes, searches for or runs. */
273
+ export function toolTitle(name, input, cwd) {
274
+ const args = input && typeof input === 'object' ? input : {};
275
+ const path = toolPath(input);
276
+ const shown = path === undefined ? undefined : (isAbsolute(path) ? (relative(cwd, path) || path) : path);
277
+ const pattern = typeof args.pattern === 'string' ? args.pattern : undefined;
278
+ switch (canonicalCodingToolName(name)) {
279
+ case 'Read': return shown ? `Read ${shown}` : name;
280
+ case 'Write': return shown ? `Write ${shown}` : name;
281
+ case 'Edit': return shown ? `Edit ${shown}` : name;
282
+ case 'Glob': return pattern ? `Find ${oneLine(pattern)}` : name;
283
+ case 'Grep': return pattern ? `Search for ${oneLine(pattern)}` : name;
284
+ case 'Bash':
285
+ case 'PowerShell': return typeof args.command === 'string' && args.command.trim() ? oneLine(args.command) : name;
286
+ default: return name;
287
+ }
288
+ }
289
+ /** Files larger than this are shown as a positioned text diff instead of whole before and after texts. */
290
+ const MAX_DIFF_FILE_BYTES = 1_000_000;
291
+ /** A text as lines that keep their own line endings. */
292
+ function snapshotLines(text) {
293
+ return text === null || text === '' ? [] : text.split(/(?<=\n)/);
294
+ }
295
+ function withoutLineEnding(line) {
296
+ return line.endsWith('\r\n') ? line.slice(0, -2) : line.endsWith('\n') ? line.slice(0, -1) : line;
297
+ }
298
+ /**
299
+ * Whether two snapshots of a file are exactly the two sides of the engine's line diff: every hunk's old lines sit at
300
+ * its position in the before text and its new lines at its position in the after text, and everything outside the
301
+ * hunks (before the first, between them, after the last) is identical in both, line endings included. A snapshot
302
+ * taken too late, or a file something else changed anywhere, fails this.
303
+ */
304
+ function snapshotsMatchDiff(diff, before, after) {
305
+ const oldLines = snapshotLines(before);
306
+ const newLines = snapshotLines(after);
307
+ let oldAt = 0;
308
+ let newAt = 0;
309
+ const sameStretch = (count) => {
310
+ for (let index = 0; index < count; index++)
311
+ if (oldLines[oldAt + index] !== newLines[newAt + index])
312
+ return false;
313
+ return true;
314
+ };
315
+ for (const hunk of diff.hunks) {
316
+ const oldSide = hunk.lines.filter(line => line.kind !== 'add');
317
+ const newSide = hunk.lines.filter(line => line.kind !== 'del');
318
+ if (oldSide.length !== hunk.oldLines || newSide.length !== hunk.newLines)
319
+ return false;
320
+ const oldStart = hunk.oldLines === 0 ? hunk.oldStart : hunk.oldStart - 1;
321
+ const newStart = hunk.newLines === 0 ? hunk.newStart : hunk.newStart - 1;
322
+ const unchanged = oldStart - oldAt;
323
+ if (unchanged < 0 || unchanged !== newStart - newAt || !sameStretch(unchanged))
324
+ return false;
325
+ if (oldStart + hunk.oldLines > oldLines.length || newStart + hunk.newLines > newLines.length)
326
+ return false;
327
+ if (oldSide.some((line, index) => withoutLineEnding(oldLines[oldStart + index]) !== line.text))
328
+ return false;
329
+ if (newSide.some((line, index) => withoutLineEnding(newLines[newStart + index]) !== line.text))
330
+ return false;
331
+ oldAt = oldStart + hunk.oldLines;
332
+ newAt = newStart + hunk.newLines;
333
+ }
334
+ const rest = oldLines.length - oldAt;
335
+ return rest === newLines.length - newAt && sameStretch(rest);
336
+ }
337
+ function positionedDiff(path, diff) {
338
+ const out = [`--- ${path}`, `+++ ${path}`];
339
+ for (const hunk of diff.hunks) {
340
+ out.push(`@@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines} @@`);
341
+ for (const line of hunk.lines) {
342
+ out.push(`${line.kind === 'add' ? '+' : line.kind === 'del' ? '-' : ' '}${line.text}${line.clipped ? ' […]' : ''}`);
343
+ if (line.noNewline)
344
+ out.push('\');
345
+ }
346
+ }
347
+ if (diff.hiddenLines > 0)
348
+ out.push(`[${diff.hiddenLines} more changed lines not shown]`);
349
+ return out.join('\n');
350
+ }
351
+ /**
352
+ * An edit as ACP content. With the file's own text from before and after the edit, and both agreeing with the
353
+ * engine's line diff, one ACP diff carrying the two texts exactly (line endings included), which is what the
354
+ * protocol's diff means. Otherwise (a large file, a clipped diff, a snapshot that does not match) the engine's hunks
355
+ * as a text diff with their line positions. Text is never reconstructed from the diff's display lines.
356
+ */
357
+ export function editContent(path, diff, before, after) {
358
+ const verifiable = before !== undefined && typeof after === 'string' && !diff.coarse && diff.hiddenLines === 0
359
+ && diff.hunks.every(hunk => hunk.lines.every(line => !line.clipped));
360
+ if (verifiable && snapshotsMatchDiff(diff, before, after))
361
+ return [{ type: 'diff', path, oldText: before, newText: after }];
362
+ return [{ type: 'content', content: { type: 'text', text: `\`\`\`diff\n${positionedDiff(path, diff)}\n\`\`\`` } }];
363
+ }
364
+ /** Read a file for a diff now, synchronously, so the text is the file's at this moment. */
365
+ function snapshotNow(path) {
366
+ try {
367
+ if (statSync(path).size > MAX_DIFF_FILE_BYTES)
368
+ return undefined;
369
+ const text = readFileSync(path, 'utf8');
370
+ return text.includes('\0') ? undefined : text;
371
+ }
372
+ catch (error) {
373
+ return error.code === 'ENOENT' ? null : undefined;
374
+ }
375
+ }
376
+ function toolInput(value) {
377
+ if (typeof value !== 'string')
378
+ return value;
379
+ try {
380
+ return JSON.parse(value);
381
+ }
382
+ catch {
383
+ return value;
384
+ }
385
+ }
386
+ function clip(value) {
387
+ const text = typeof value === 'string' ? value : value === undefined ? '' : JSON.stringify(value);
388
+ return text.length > MAX_TOOL_OUTPUT_CHARS ? `${text.slice(0, MAX_TOOL_OUTPUT_CHARS)}\n[output clipped]` : text;
389
+ }
390
+ function stopReasonFor(status) {
391
+ if (status === 'cancelled' || status === 'interrupted')
392
+ return 'cancelled';
393
+ if (status === 'exhausted')
394
+ return 'max_turn_requests';
395
+ return 'end_turn';
396
+ }
397
+ const EFFORT_NAMES = { none: 'None', minimal: 'Minimal', low: 'Low', medium: 'Medium', high: 'High', xhigh: 'Extra high', max: 'Max' };
398
+ /** A model option value: the provider id (no slashes), a slash, then the model id as the provider spells it. */
399
+ export function modelValue(pair) { return `${pair.provider}/${pair.model}`; }
400
+ function providerModels(provider) {
401
+ const listed = provider.models?.length ? [...provider.models] : [];
402
+ if (provider.model && !listed.includes(provider.model))
403
+ listed.unshift(provider.model);
404
+ return listed;
405
+ }
406
+ function modelName(provider, model) {
407
+ return provider.type === 'andorra' ? provider.modelNames?.[model] ?? model : model;
408
+ }
409
+ /** Find the model a client picked: a listed value, `provider/model` for a configured provider, or a model id one provider lists. */
410
+ export function resolveModelChoice(value, catalog) {
411
+ const slash = value.indexOf('/');
412
+ if (slash > 0) {
413
+ const provider = catalog.providers.find(item => item.id === value.slice(0, slash));
414
+ const model = value.slice(slash + 1);
415
+ if (provider && model && model.length <= 200)
416
+ return { provider: provider.id, model };
417
+ }
418
+ const matches = catalog.providers.flatMap(provider => providerModels(provider).filter(model => model === value).map(model => ({ provider: provider.id, model })));
419
+ return matches.length === 1 ? matches[0] : undefined;
420
+ }
421
+ function invalid(message) { return RequestError.invalidParams(undefined, message); }
422
+ function encodeCursor(offset) { return Buffer.from(JSON.stringify({ offset }), 'utf8').toString('base64url'); }
423
+ function decodeCursor(cursor) {
424
+ try {
425
+ const offset = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8')).offset;
426
+ if (typeof offset === 'number' && Number.isSafeInteger(offset) && offset >= 0)
427
+ return offset;
428
+ }
429
+ catch { }
430
+ throw invalid('The session list cursor is not valid.');
431
+ }
432
+ function defaultEngineCommand() {
433
+ const entry = process.argv[1];
434
+ if (!entry)
435
+ throw new Error('The ACP agent cannot locate its own CLI to start another engine.');
436
+ return [process.execPath, ...process.execArgv, entry, 'app-server', '--stdio'];
437
+ }
438
+ /** Serve Andorra Code as an ACP agent: JSON-RPC over stdio, one message per line. */
439
+ export async function runAcpAgent(options = {}) {
440
+ const { version = '0.0.0', input, protocolOutput, engineCommand, ...serverOptions } = options;
441
+ const errorOutput = serverOptions.error ?? process.stderr;
442
+ const primary = new InProcessEngine(serverOptions);
443
+ const pool = new EnginePool(primary, () => engineCommand ?? defaultEngineCommand(), errorOutput);
444
+ const sessions = new Map();
445
+ const authMethods = [{
446
+ id: ACP_AUTH_METHOD_ID,
447
+ name: 'Sign in to Andorra',
448
+ description: 'Opens your browser to sign in to your Andorra account. Optional: the agent also runs signed out with your own model providers.',
449
+ type: 'agent',
450
+ }];
451
+ const catalog = async () => {
452
+ const listed = await primary.request('providers.list');
453
+ const providers = Array.isArray(listed.providers) ? listed.providers : [];
454
+ return { providers, ...(typeof listed.active === 'string' ? { active: listed.active } : {}) };
455
+ };
456
+ const currentPair = (session, models) => {
457
+ if (session.selection)
458
+ return session.selection;
459
+ const active = models.providers.find(provider => provider.id === models.active) ?? models.providers[0];
460
+ return active ? { provider: active.id, model: active.model } : undefined;
461
+ };
462
+ const configOptions = async (session) => {
463
+ const models = await catalog();
464
+ const current = currentPair(session, models);
465
+ if (!current)
466
+ return [];
467
+ const choice = (provider, model) => ({
468
+ value: modelValue({ provider: provider.id, model }), name: modelName(provider, model),
469
+ ...(models.providers.length > 1 ? {} : { description: provider.label ?? provider.name ?? provider.id }),
470
+ });
471
+ const currentValue = modelValue(current);
472
+ const listedValues = new Set(models.providers.flatMap(provider => providerModels(provider).map(model => modelValue({ provider: provider.id, model }))));
473
+ const extra = listedValues.has(currentValue) ? undefined : current;
474
+ let options;
475
+ if (models.providers.length > 1) {
476
+ options = models.providers.map(provider => ({
477
+ group: provider.id,
478
+ name: provider.label ?? provider.name ?? provider.id,
479
+ options: [
480
+ ...providerModels(provider).map(model => choice(provider, model)),
481
+ ...(extra?.provider === provider.id ? [choice(provider, extra.model)] : []),
482
+ ],
483
+ }));
484
+ }
485
+ else {
486
+ const only = models.providers[0];
487
+ options = [...providerModels(only).map(model => choice(only, model)), ...(extra ? [choice(only, extra.model)] : [])];
488
+ }
489
+ const result = [{
490
+ id: ACP_MODEL_OPTION, name: 'Model', category: 'model', type: 'select', currentValue, options,
491
+ description: 'Choosing a model uses it for every step of the next prompt. Leave the default to let model routing decide.',
492
+ }];
493
+ const provider = models.providers.find(item => item.id === current.provider);
494
+ if (provider && supportsReasoningEffort(provider.type)) {
495
+ result.push({
496
+ id: ACP_EFFORT_OPTION, name: 'Thinking effort', category: 'thought_level', type: 'select',
497
+ currentValue: session.effort ?? EFFORT_DEFAULT,
498
+ options: [
499
+ { value: EFFORT_DEFAULT, name: provider.reasoningEffort ? `Default (${EFFORT_NAMES[provider.reasoningEffort] ?? provider.reasoningEffort})` : 'Provider default' },
500
+ ...REASONING_EFFORTS.map(effort => ({ value: effort, name: EFFORT_NAMES[effort] ?? effort })),
501
+ ],
502
+ });
503
+ }
504
+ return result;
505
+ };
506
+ const requireSession = (sessionId) => {
507
+ const session = sessions.get(sessionId);
508
+ if (!session)
509
+ throw invalid(`Unknown session: ${sessionId}. Load or resume it first.`);
510
+ return session;
511
+ };
512
+ const newSession = (cwd, title) => ({ cwd, cancelled: false, prompting: false, alwaysAllow: new Set(), ...(title === undefined ? {} : { title }) });
513
+ /** Attach a saved Andorra session to this connection (session/load and session/resume). */
514
+ const attach = async (sessionId, cwd) => {
515
+ if (!isAbsolute(cwd))
516
+ throw invalid('cwd must be an absolute path');
517
+ let record;
518
+ try {
519
+ record = (await primary.request('sessions.get', { id: sessionId })).session;
520
+ }
521
+ catch {
522
+ throw invalid(`Unknown session: ${sessionId}`);
523
+ }
524
+ let session = sessions.get(sessionId);
525
+ if (!session) {
526
+ session = newSession(record.workspace ?? cwd, record.name);
527
+ sessions.set(sessionId, session);
528
+ }
529
+ return { session, history: Array.isArray(record.history) ? record.history : [] };
530
+ };
531
+ const runPrompt = async (sessionId, session, engine, task, client, fallbackWindow) => {
532
+ let sending = Promise.resolve();
533
+ const update = (next) => {
534
+ sending = sending.then(() => client.notify(methods.client.session.update, { sessionId, update: next })).catch(() => undefined);
535
+ };
536
+ const say = (text) => { if (text.trim())
537
+ update({ sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: `${text}\n\n` } }); };
538
+ let lastMessage = '';
539
+ let runId;
540
+ let contextWindow = fallbackWindow;
541
+ const openTools = new Map();
542
+ const early = [];
543
+ let settle;
544
+ let fail;
545
+ const finished = new Promise((resolveFinished, reject) => { settle = resolveFinished; fail = reject; });
546
+ finished.catch(() => undefined);
547
+ const answerApproval = (id, approved) => engine.request('run.approve', { id, approved }).catch(() => undefined);
548
+ const approve = async (data) => {
549
+ const id = String(data.id);
550
+ // As with questions, the engine emits run.approval before it registers the approval: yield before answering.
551
+ await new Promise(next => setImmediate(next));
552
+ const name = typeof data.name === 'string' ? data.name : 'tool';
553
+ const key = canonicalCodingToolName(name) ?? name;
554
+ if (session.alwaysAllow.has(key)) {
555
+ await answerApproval(id, true);
556
+ return;
557
+ }
558
+ const rawInput = toolInput(data.arguments);
559
+ // The engine asks after the call has started: point the request at that call, so the client shows one item.
560
+ let matched;
561
+ for (const [toolCallId, open] of [...openTools].reverse()) {
562
+ if ((canonicalCodingToolName(open.name) ?? open.name) !== key)
563
+ continue;
564
+ if (matched === undefined)
565
+ matched = toolCallId;
566
+ if (isDeepStrictEqual(open.input, rawInput)) {
567
+ matched = toolCallId;
568
+ break;
569
+ }
570
+ }
571
+ const title = matched ? openTools.get(matched).title : toolTitle(name, rawInput, session.cwd);
572
+ let approved = false;
573
+ let always = false;
574
+ try {
575
+ const answer = await client.request(methods.client.session.requestPermission, {
576
+ sessionId,
577
+ toolCall: { toolCallId: matched ?? `approval-${id}`, title, kind: toolKind(name), status: 'pending', rawInput },
578
+ options: [
579
+ { optionId: 'allow', name: 'Allow', kind: 'allow_once' },
580
+ { optionId: 'allow-always', name: `Always allow ${key} in this session`, kind: 'allow_always' },
581
+ { optionId: 'reject', name: 'Reject', kind: 'reject_once' },
582
+ ],
583
+ });
584
+ if (answer.outcome.outcome === 'selected') {
585
+ always = answer.outcome.optionId === 'allow-always';
586
+ approved = always || answer.outcome.optionId === 'allow';
587
+ }
588
+ }
589
+ catch { }
590
+ if (always)
591
+ session.alwaysAllow.add(key);
592
+ if (matched && approved)
593
+ update({ sessionUpdate: 'tool_call_update', toolCallId: matched, status: 'in_progress' });
594
+ await answerApproval(id, approved);
595
+ };
596
+ const ask = async (data) => {
597
+ const id = String(data.id);
598
+ // The engine emits run.question before it registers the pending question, and this listener runs
599
+ // inside that emit. Yield first, or an immediate answer is refused as not pending and the run hangs.
600
+ await new Promise(next => setImmediate(next));
601
+ const question = typeof data.question === 'string' ? data.question : '';
602
+ const choices = Array.isArray(data.choices) ? data.choices.filter((choice) => typeof choice === 'string') : [];
603
+ let answer;
604
+ if (choices.length) {
605
+ try {
606
+ const picked = await client.request(methods.client.session.requestPermission, {
607
+ sessionId,
608
+ toolCall: { toolCallId: `question-${id}`, title: question, kind: 'other', status: 'pending' },
609
+ options: choices.map((choice, index) => ({ optionId: String(index), name: choice, kind: 'allow_once' })),
610
+ });
611
+ if (picked.outcome.outcome === 'selected')
612
+ answer = choices[Number(picked.outcome.optionId)];
613
+ }
614
+ catch { }
615
+ }
616
+ else {
617
+ // ACP v1 has no free-text question: show it and let the user answer with the next prompt.
618
+ say(question);
619
+ }
620
+ await engine.request('run.answer', { id, ...(answer === undefined ? {} : { answer }) }).catch(() => undefined);
621
+ };
622
+ const finishTool = (toolCallId, status, data) => {
623
+ const open = openTools.get(toolCallId);
624
+ openTools.delete(toolCallId);
625
+ const path = open ? toolPath(open.input) : undefined;
626
+ const diff = data.fileDiff;
627
+ const edited = path && diff && Array.isArray(diff.hunks) && diff.hunks.length ? { path: isAbsolute(path) ? path : resolve(session.cwd, path), diff } : undefined;
628
+ // Read the file now, while it still holds this edit. editContent checks both snapshots against the diff, so a
629
+ // read that came too late on either side gives the positioned text diff, never a wrong before or after text.
630
+ const content = edited ? editContent(edited.path, edited.diff, open?.before, snapshotNow(edited.path)) : [];
631
+ const output = clip(data.output);
632
+ if (output && !(content.length && status === 'completed'))
633
+ content.push({ type: 'content', content: { type: 'text', text: output } });
634
+ update({ sessionUpdate: 'tool_call_update', toolCallId, status, ...(content.length ? { content } : {}) });
635
+ };
636
+ const onRuntimeEvent = (event) => {
637
+ const data = event.data ?? {};
638
+ if (typeof data.subagentId === 'string')
639
+ return;
640
+ const toolCallId = typeof data.toolCallId === 'string' ? data.toolCallId : undefined;
641
+ const name = typeof data.name === 'string' ? data.name : 'tool';
642
+ switch (event.type) {
643
+ case 'agent.message':
644
+ if (typeof data.text === 'string') {
645
+ lastMessage = data.text.trim();
646
+ say(data.text);
647
+ }
648
+ return;
649
+ case 'agent.reasoning.delta':
650
+ if (typeof data.text === 'string' && data.text)
651
+ update({ sessionUpdate: 'agent_thought_chunk', content: { type: 'text', text: data.text } });
652
+ return;
653
+ case 'node.tool.started': {
654
+ if (!toolCallId)
655
+ return;
656
+ const rawInput = toolInput(data.arguments);
657
+ const path = toolPath(rawInput);
658
+ const title = toolTitle(name, rawInput, session.cwd);
659
+ // An edit's diff needs the file as it is before the call runs. The engine announces a call before running it.
660
+ const editing = path !== undefined && (canonicalCodingToolName(name) === 'Write' || canonicalCodingToolName(name) === 'Edit');
661
+ openTools.set(toolCallId, { name, input: rawInput, title, ...(editing ? { before: snapshotNow(isAbsolute(path) ? path : resolve(session.cwd, path)) } : {}) });
662
+ update({
663
+ sessionUpdate: 'tool_call', toolCallId, title, kind: toolKind(name), status: 'in_progress', rawInput,
664
+ ...(path === undefined ? {} : { locations: [{ path: isAbsolute(path) ? path : resolve(session.cwd, path) }] }),
665
+ });
666
+ return;
667
+ }
668
+ case 'node.tool.completed':
669
+ case 'node.tool.failed':
670
+ if (toolCallId)
671
+ finishTool(toolCallId, event.type === 'node.tool.completed' ? 'completed' : 'failed', data);
672
+ return;
673
+ case 'node.tool.skipped':
674
+ if (toolCallId)
675
+ finishTool(toolCallId, 'failed', data);
676
+ return;
677
+ case 'graph.todos.updated': {
678
+ const todos = Array.isArray(data.todos) ? data.todos : [];
679
+ const entries = todos.filter(todo => typeof todo.text === 'string' && todo.text).map(todo => ({
680
+ content: String(todo.text), priority: 'medium',
681
+ status: todo.status === 'completed' || todo.status === 'in_progress' ? todo.status : 'pending',
682
+ }));
683
+ update({ sessionUpdate: 'plan', entries });
684
+ return;
685
+ }
686
+ default:
687
+ }
688
+ };
689
+ const onEvent = (event, data) => {
690
+ if (data.runId !== runId)
691
+ return;
692
+ switch (event) {
693
+ case 'run.event':
694
+ onRuntimeEvent((data.event ?? {}));
695
+ return;
696
+ case 'run.approval':
697
+ void approve(data);
698
+ return;
699
+ case 'run.question':
700
+ void ask(data);
701
+ return;
702
+ case 'run.context':
703
+ if (typeof data.contextWindow === 'number' && data.contextWindow > 0)
704
+ contextWindow = data.contextWindow;
705
+ return;
706
+ case 'run.usage': {
707
+ const usage = (data.usage ?? {});
708
+ if (contextWindow === undefined)
709
+ return;
710
+ if (typeof usage.inputTokens === 'number' && usage.inputTokens > 0)
711
+ update({ sessionUpdate: 'usage_update', used: usage.inputTokens, size: contextWindow });
712
+ return;
713
+ }
714
+ case 'run.completed': {
715
+ const result = (data.result ?? {});
716
+ const summary = typeof result.completion?.summary === 'string' ? result.completion.summary.trim() : '';
717
+ // The summary often opens with the message that was just streamed: send only what is new.
718
+ if (summary && summary !== lastMessage)
719
+ say(lastMessage && summary.startsWith(lastMessage) ? summary.slice(lastMessage.length) : summary);
720
+ else if (!summary && result.status !== 'succeeded' && typeof result.reason === 'string')
721
+ say(result.reason);
722
+ for (const toolCallId of openTools.keys())
723
+ update({ sessionUpdate: 'tool_call_update', toolCallId, status: 'failed' });
724
+ openTools.clear();
725
+ settle(session.cancelled ? 'cancelled' : stopReasonFor(result.status));
726
+ return;
727
+ }
728
+ case 'run.failed':
729
+ if (session.cancelled)
730
+ settle('cancelled');
731
+ else
732
+ fail(new Error(typeof data.message === 'string' ? data.message : 'The run failed.'));
733
+ return;
734
+ default:
735
+ }
736
+ };
737
+ const stop = engine.listen((event, data) => {
738
+ if (event === ENGINE_EXITED) {
739
+ if (session.cancelled)
740
+ settle('cancelled');
741
+ else
742
+ fail(new Error('The engine running this prompt stopped unexpectedly. Send the prompt again.'));
743
+ return;
744
+ }
745
+ if (runId === undefined)
746
+ early.push({ event, data });
747
+ else
748
+ onEvent(event, data);
749
+ });
750
+ try {
751
+ session.engine = engine;
752
+ const started = await engine.request('run.start', {
753
+ workspace: session.cwd, task, sessionId, continueSession: true,
754
+ // A picked model replaces every node's own model, as the option's description says and as the desktop's
755
+ // "use for every step" does. Without a pick nothing is overridden.
756
+ ...(session.selection ? { provider: session.selection.provider, model: session.selection.model, overrideAllNodes: true } : {}),
757
+ ...(session.effort === undefined ? {} : { reasoningEffort: session.effort }),
758
+ });
759
+ runId = String(started.runId);
760
+ session.runId = runId;
761
+ if (session.cancelled)
762
+ await engine.request('run.cancel', { runId }).catch(() => undefined);
763
+ for (const entry of early.splice(0))
764
+ onEvent(entry.event, entry.data);
765
+ const reason = await finished;
766
+ await sending;
767
+ return reason;
768
+ }
769
+ finally {
770
+ stop();
771
+ if (session.runId === runId)
772
+ session.runId = undefined;
773
+ if (session.engine === engine)
774
+ session.engine = undefined;
775
+ }
776
+ };
777
+ /**
778
+ * The engine titles a session only when a run creates it, and ACP sessions exist before their first prompt.
779
+ * Name an untitled session after its first prompt, the way a thread list shows it.
780
+ */
781
+ const nameFromPrompt = async (sessionId, session, task) => {
782
+ if (session.title !== undefined && session.title !== UNTITLED_SESSION)
783
+ return undefined;
784
+ // sessionName is the engine's own prompt-to-name rule: it redacts credentials and drops paths and links.
785
+ const name = sessionName(task.replace(/<context uri="[^"]*">[\s\S]*?<\/context>/g, ' '));
786
+ if (!name || name === UNTITLED_SESSION)
787
+ return undefined;
788
+ try {
789
+ const renamed = (await primary.request('sessions.rename', { id: sessionId, name })).session;
790
+ session.title = renamed.name ?? name;
791
+ return session.title;
792
+ }
793
+ catch {
794
+ return undefined;
795
+ }
796
+ };
797
+ /** The context window the configuration states for a model, used until the run reports its own. */
798
+ const configuredWindow = async (session) => {
799
+ try {
800
+ const models = await catalog();
801
+ const current = currentPair(session, models);
802
+ const provider = models.providers.find(item => item.id === current?.provider);
803
+ const window = (current && provider?.modelContextWindows?.[current.model]) ?? provider?.contextWindow;
804
+ return typeof window === 'number' && window > 0 ? window : undefined;
805
+ }
806
+ catch {
807
+ return undefined;
808
+ }
809
+ };
810
+ const app = agent({ name: 'andorra-code' })
811
+ .onRequest(methods.agent.initialize, ({ params }) => ({
812
+ protocolVersion: Math.min(params.protocolVersion, PROTOCOL_VERSION),
813
+ agentCapabilities: {
814
+ loadSession: true,
815
+ promptCapabilities: { image: false, audio: false, embeddedContext: true },
816
+ sessionCapabilities: { list: {}, resume: {}, close: {} },
817
+ },
818
+ agentInfo: { name: 'andorra-code', title: 'Andorra Code', version },
819
+ authMethods,
820
+ }))
821
+ .onRequest(methods.agent.authenticate, async ({ params }) => {
822
+ if (params.methodId !== ACP_AUTH_METHOD_ID)
823
+ throw invalid(`Unknown authentication method: ${params.methodId}`);
824
+ // Without a usable browser the sign-in prints the address to open. Stdout is the protocol, so show it on stderr.
825
+ const stopMessages = primary.listen((event, data) => {
826
+ if (event === 'account.login.message' && typeof data.message === 'string')
827
+ errorOutput.write(`${data.message}\n`);
828
+ });
829
+ try {
830
+ await primary.request('account.login');
831
+ }
832
+ finally {
833
+ stopMessages();
834
+ }
835
+ return {};
836
+ })
837
+ .onRequest(methods.agent.session.new, async ({ params }) => {
838
+ if (!isAbsolute(params.cwd))
839
+ throw invalid('cwd must be an absolute path');
840
+ if (params.mcpServers?.length)
841
+ errorOutput.write('Andorra Code does not use MCP servers passed by the client; configure them in Andorra instead.\n');
842
+ const created = await primary.request('sessions.create', { workspace: params.cwd });
843
+ const record = created.session;
844
+ const session = newSession(record.workspace ?? params.cwd, record.name);
845
+ sessions.set(record.id, session);
846
+ return { sessionId: record.id, configOptions: await configOptions(session) };
847
+ })
848
+ .onRequest(methods.agent.session.load, async ({ params, client }) => {
849
+ const { session, history } = await attach(params.sessionId, params.cwd);
850
+ for (const turn of history) {
851
+ if (typeof turn.task === 'string' && turn.task) {
852
+ await client.notify(methods.client.session.update, { sessionId: params.sessionId, update: { sessionUpdate: 'user_message_chunk', content: { type: 'text', text: turn.task } } });
853
+ }
854
+ const summary = typeof turn.completion?.summary === 'string' ? turn.completion.summary : '';
855
+ if (summary.trim()) {
856
+ await client.notify(methods.client.session.update, { sessionId: params.sessionId, update: { sessionUpdate: 'agent_message_chunk', content: { type: 'text', text: summary } } });
857
+ }
858
+ }
859
+ return { configOptions: await configOptions(session) };
860
+ })
861
+ .onRequest(methods.agent.session.resume, async ({ params }) => {
862
+ const { session } = await attach(params.sessionId, params.cwd);
863
+ return { configOptions: await configOptions(session) };
864
+ })
865
+ .onRequest(methods.agent.session.list, async ({ params }) => {
866
+ const cwd = params.cwd ?? undefined;
867
+ if (cwd !== undefined && !isAbsolute(cwd))
868
+ throw invalid('cwd must be an absolute path');
869
+ const offset = params.cursor ? decodeCursor(params.cursor) : 0;
870
+ const listed = await primary.request('sessions.list', cwd === undefined ? {} : { workspace: cwd });
871
+ const all = (Array.isArray(listed.sessions) ? listed.sessions : [])
872
+ // The engine filters by folder itself and resolves symlinks doing it; comparing paths again here would undo that.
873
+ .filter(record => record.archived !== true)
874
+ .sort((left, right) => Date.parse(right.updatedAt ?? '') - Date.parse(left.updatedAt ?? ''));
875
+ const page = all.slice(offset, offset + SESSION_PAGE_SIZE);
876
+ return {
877
+ sessions: page.map(record => ({
878
+ // Answer in the client's own spelling of the folder it asked about (it may be a symlink to the saved path).
879
+ sessionId: record.id, cwd: cwd ?? record.workspace,
880
+ ...(record.name ? { title: record.name } : {}),
881
+ ...(record.updatedAt ? { updatedAt: record.updatedAt } : {}),
882
+ })),
883
+ ...(offset + SESSION_PAGE_SIZE < all.length ? { nextCursor: encodeCursor(offset + SESSION_PAGE_SIZE) } : {}),
884
+ };
885
+ })
886
+ .onRequest(methods.agent.session.close, async ({ params }) => {
887
+ const session = sessions.get(params.sessionId);
888
+ if (!session)
889
+ return {};
890
+ sessions.delete(params.sessionId);
891
+ session.cancelled = true;
892
+ if (session.runId && session.engine)
893
+ await session.engine.request('run.cancel', { runId: session.runId }).catch(() => undefined);
894
+ return {};
895
+ })
896
+ .onRequest(methods.agent.session.setConfigOption, async ({ params }) => {
897
+ const session = requireSession(params.sessionId);
898
+ if ('type' in params && params.type === 'boolean')
899
+ throw invalid(`${params.configId} is not a boolean option.`);
900
+ const value = String(params.value);
901
+ if (params.configId === ACP_MODEL_OPTION) {
902
+ const models = await catalog();
903
+ const pair = resolveModelChoice(value, models);
904
+ if (!pair)
905
+ throw invalid(`Unknown model: ${value}. Use a value from the model option, or provider/model for a configured provider.`);
906
+ // Picking the configured default again is "no override": the next prompt runs as a native run would.
907
+ const active = models.providers.find(item => item.id === models.active) ?? models.providers[0];
908
+ session.selection = active && pair.provider === active.id && pair.model === active.model ? undefined : pair;
909
+ const provider = models.providers.find(item => item.id === pair.provider);
910
+ if (!provider || !supportsReasoningEffort(provider.type))
911
+ session.effort = undefined;
912
+ }
913
+ else if (params.configId === ACP_EFFORT_OPTION) {
914
+ const models = await catalog();
915
+ const current = currentPair(session, models);
916
+ const provider = models.providers.find(item => item.id === current?.provider);
917
+ if (!provider || !supportsReasoningEffort(provider.type))
918
+ throw invalid('The selected model does not take a thinking effort.');
919
+ if (value === EFFORT_DEFAULT)
920
+ session.effort = undefined;
921
+ else if (REASONING_EFFORTS.includes(value))
922
+ session.effort = value;
923
+ else
924
+ throw invalid(`Unknown thinking effort: ${value}`);
925
+ }
926
+ else {
927
+ throw invalid(`Unknown configuration option: ${params.configId}`);
928
+ }
929
+ return { configOptions: await configOptions(session) };
930
+ })
931
+ .onRequest(methods.agent.session.prompt, async ({ params, client }) => {
932
+ const session = requireSession(params.sessionId);
933
+ const task = promptText(params.prompt);
934
+ if (!task)
935
+ throw invalid('The prompt has no text content.');
936
+ // Refuse an overlapping prompt before touching shared session state, so the running prompt keeps its run ID and can still be cancelled.
937
+ if (session.prompting)
938
+ throw invalid('This session is already running a prompt. Wait for it to finish or cancel it first.');
939
+ session.prompting = true;
940
+ // From here a cancel or close belongs to this prompt, including while an engine is still being started for it.
941
+ session.cancelled = false;
942
+ let engine;
943
+ try {
944
+ const title = await nameFromPrompt(params.sessionId, session, task);
945
+ if (title !== undefined) {
946
+ await client.notify(methods.client.session.update, { sessionId: params.sessionId, update: { sessionUpdate: 'session_info_update', title } }).catch(() => undefined);
947
+ }
948
+ engine = await pool.acquire();
949
+ if (session.cancelled || sessions.get(params.sessionId) !== session)
950
+ return { stopReason: 'cancelled' };
951
+ return { stopReason: await runPrompt(params.sessionId, session, engine, task, client, await configuredWindow(session)) };
952
+ }
953
+ catch (error) {
954
+ // Put the engine's own reason in the message clients show, not only in the error data.
955
+ throw error instanceof RequestError ? error : RequestError.internalError(undefined, error instanceof Error ? error.message : String(error));
956
+ }
957
+ finally {
958
+ session.prompting = false;
959
+ if (engine)
960
+ pool.release(engine);
961
+ }
962
+ })
963
+ .onNotification(methods.agent.session.cancel, async ({ params }) => {
964
+ const session = sessions.get(params.sessionId);
965
+ if (!session)
966
+ return;
967
+ session.cancelled = true;
968
+ if (session.runId && session.engine)
969
+ await session.engine.request('run.cancel', { runId: session.runId }).catch(() => undefined);
970
+ });
971
+ await primary.server.ready();
972
+ const stream = ndJsonStream(Writable.toWeb((protocolOutput ?? process.stdout)), Readable.toWeb((input ?? process.stdin)));
973
+ const connection = app.connect(stream);
974
+ const interrupt = () => connection.close();
975
+ process.once('SIGINT', interrupt);
976
+ process.once('SIGTERM', interrupt);
977
+ try {
978
+ await connection.closed;
979
+ }
980
+ finally {
981
+ process.removeListener('SIGINT', interrupt);
982
+ process.removeListener('SIGTERM', interrupt);
983
+ for (const [, session] of sessions) {
984
+ session.cancelled = true;
985
+ if (session.runId && session.engine)
986
+ await session.engine.request('run.cancel', { runId: session.runId }).catch(() => undefined);
987
+ }
988
+ await pool.close();
989
+ }
990
+ return 0;
991
+ }