@bastani/atomic-acp 0.0.0-stage → 0.0.1

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.
package/dist/index.js ADDED
@@ -0,0 +1,3400 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/index.ts
4
+ import { AgentSideConnection, ndJsonStream } from "@agentclientprotocol/sdk";
5
+
6
+ // src/acp/workflow-history.ts
7
+ function record(value) {
8
+ return value !== null && typeof value === "object" ? value : {};
9
+ }
10
+ function renderRun(value) {
11
+ const run = record(value);
12
+ const title = [run.name, run.runId].filter((v) => typeof v === "string").join(" \u2014 ");
13
+ const heading = (title || "Workflow run").replace(/[\r\n\u2028\u2029]/g, " ").replace(/[\\`*_{}[\]()<>#+\-.!|&]/g, "\\$&");
14
+ const lines = [];
15
+ for (const key of ["status", "label", "identity", "summarizedThrough"]) {
16
+ if (run[key] !== void 0)
17
+ lines.push(`${key}: ${typeof run[key] === "object" ? JSON.stringify(run[key]) : String(run[key])}`);
18
+ }
19
+ if (run.summary !== void 0)
20
+ lines.push("", typeof run.summary === "string" ? run.summary : JSON.stringify(run.summary, null, 2));
21
+ const body = lines.join("\n");
22
+ const fence = "`".repeat(Math.max(3, ...[...body.matchAll(/`+/g)].map((match) => match[0].length + 1)));
23
+ return `## ${heading}
24
+
25
+ ${fence}text
26
+ ${body}
27
+ ${fence}`;
28
+ }
29
+ function renderWorkflowHistory(data, list) {
30
+ if (!list) return renderRun(data);
31
+ const runs = record(data).runs;
32
+ return Array.isArray(runs) && runs.length ? runs.map(renderRun).join("\n\n") : "No workflow runs found.";
33
+ }
34
+
35
+ // src/acp/translate/bash.ts
36
+ function isBashTool(name) {
37
+ return name.toLowerCase() === "bash";
38
+ }
39
+ function bashCommand(value) {
40
+ const record2 = value;
41
+ for (const source of [record2, record2?.args, record2?.input, record2?.rawInput, record2?.toolInput, record2?.details]) {
42
+ const command = source?.command ?? source?.cmd;
43
+ if (typeof command === "string" && command.trim()) return command;
44
+ }
45
+ return void 0;
46
+ }
47
+ function bashResultText(value) {
48
+ const record2 = value;
49
+ if (Array.isArray(record2?.content)) {
50
+ const text = record2.content.map(
51
+ (block) => block.type === "text" && typeof block.text === "string" ? block.text : ""
52
+ ).join("");
53
+ if (text) return text;
54
+ }
55
+ const details = record2?.details;
56
+ const stdout = details?.stdout ?? record2?.stdout ?? details?.output ?? record2?.output;
57
+ const stderr = details?.stderr ?? record2?.stderr;
58
+ return [stdout, stderr].filter((part) => typeof part === "string" && part.length > 0).join("\n");
59
+ }
60
+ function bashExitCode(value, isError) {
61
+ const record2 = value;
62
+ const code = record2?.details?.exitCode ?? record2?.exitCode ?? record2?.details?.code ?? record2?.code;
63
+ return typeof code === "number" ? code : isError ? 1 : 0;
64
+ }
65
+ function bashOutputDelta(previous, next) {
66
+ return next.startsWith(previous) ? next.slice(previous.length) : next;
67
+ }
68
+ function bashTerminalContent(id) {
69
+ return [{ type: "terminal", terminalId: id }];
70
+ }
71
+ function bashTerminalInfoMeta(id, cwd) {
72
+ return { terminal_info: { terminal_id: id, cwd } };
73
+ }
74
+ function bashTerminalOutputMeta(id, data) {
75
+ return { terminal_output: { terminal_id: id, data } };
76
+ }
77
+ function bashTerminalExitMeta(id, exitCode) {
78
+ return { terminal_exit: { terminal_id: id, exit_code: exitCode, signal: null } };
79
+ }
80
+
81
+ // src/acp/agent.ts
82
+ import {
83
+ RequestError as RequestError3
84
+ } from "@agentclientprotocol/sdk";
85
+
86
+ // src/acp/auth.ts
87
+ var ATOMIC_SETUP_METHOD_ID = "atomic_terminal_login";
88
+ function getAuthMethods(opts) {
89
+ const supportsTerminalAuthMeta = opts?.supportsTerminalAuthMeta ?? true;
90
+ const method = {
91
+ id: ATOMIC_SETUP_METHOD_ID,
92
+ name: "Launch Atomic in the terminal",
93
+ description: "Start Atomic in an interactive terminal to configure API keys or login",
94
+ // Registry-required fields
95
+ type: "terminal",
96
+ args: ["--terminal-login"],
97
+ env: {}
98
+ };
99
+ if (supportsTerminalAuthMeta) {
100
+ const launch = terminalAuthLaunchSpec();
101
+ method._meta = {
102
+ ...method._meta ?? {},
103
+ "terminal-auth": {
104
+ ...launch,
105
+ label: "Launch Atomic"
106
+ }
107
+ };
108
+ }
109
+ return [method];
110
+ }
111
+ function terminalAuthLaunchSpec() {
112
+ const argv0 = process.argv[0] || "node";
113
+ const argv1 = process.argv[1];
114
+ if (argv1 && argv0) {
115
+ const isNode = argv0.includes("node");
116
+ const isJs = argv1.endsWith(".js");
117
+ if (isNode && isJs) {
118
+ return { command: argv0, args: [argv1, "--terminal-login"] };
119
+ }
120
+ }
121
+ return { command: "atomic-acp", args: ["--terminal-login"] };
122
+ }
123
+
124
+ // src/acp/elicitation/extension-dialog.ts
125
+ var NO_CLIENT_ELICITATION_SUPPORT = {
126
+ form: false,
127
+ reason: "missing_client_capability"
128
+ };
129
+ function readClientElicitationSupport(params) {
130
+ const form = params.clientCapabilities?.elicitation?.form;
131
+ if (form !== null && typeof form === "object" && !Array.isArray(form)) {
132
+ return { form: true };
133
+ }
134
+ return NO_CLIENT_ELICITATION_SUPPORT;
135
+ }
136
+ function requestExtensionDialog(conn, sessionId, ev, form, signal) {
137
+ const cancelled = {
138
+ type: "extension_ui_response",
139
+ id: String(ev.id),
140
+ cancelled: true
141
+ };
142
+ if (signal?.aborted) return Promise.resolve(cancelled);
143
+ return new Promise((resolve3) => {
144
+ const finish = (response) => {
145
+ signal?.removeEventListener("abort", abort);
146
+ resolve3(response);
147
+ };
148
+ const abort = () => finish(cancelled);
149
+ signal?.addEventListener("abort", abort, { once: true });
150
+ void requestDialog(conn, sessionId, ev, form).then(finish);
151
+ });
152
+ }
153
+ async function requestDialog(conn, sessionId, ev, form) {
154
+ const id = String(ev.id);
155
+ const cancelled = { type: "extension_ui_response", id, cancelled: true };
156
+ const method = ev.method;
157
+ const options = Array.isArray(ev.options) ? ev.options.map(String) : [];
158
+ if (method === "select" && !options.length) return cancelled;
159
+ const title = typeof ev.title === "string" ? ev.title : `Atomic ${method}`;
160
+ try {
161
+ if (form) {
162
+ let property;
163
+ if (method === "confirm") property = { type: "boolean", title };
164
+ else if (method === "select") property = { type: "string", title, enum: options };
165
+ else
166
+ property = {
167
+ type: "string",
168
+ title,
169
+ ...typeof ev.placeholder === "string" ? { description: ev.placeholder } : {},
170
+ ...typeof ev.prefill === "string" ? { default: ev.prefill } : {}
171
+ };
172
+ const response2 = await conn.unstable_createElicitation({
173
+ sessionId,
174
+ mode: "form",
175
+ message: typeof ev.message === "string" ? `${title}
176
+
177
+ ${ev.message}` : title,
178
+ requestedSchema: { type: "object", properties: { value: property }, required: ["value"] },
179
+ _meta: { atomicAcp: { kind: "extension_ui", method: String(method), atomicRequestId: id } }
180
+ });
181
+ if (response2.action !== "accept") return cancelled;
182
+ const value = response2.content?.value;
183
+ if (method === "confirm")
184
+ return typeof value === "boolean" ? { type: "extension_ui_response", id, confirmed: value } : cancelled;
185
+ if (typeof value !== "string" || method === "select" && !options.includes(value)) return cancelled;
186
+ return { type: "extension_ui_response", id, value };
187
+ }
188
+ if (method !== "select" && method !== "confirm") return cancelled;
189
+ const rawInput = { method };
190
+ for (const key of ["title", "message", "options", "placeholder", "prefill"]) {
191
+ if (Object.hasOwn(ev, key)) rawInput[key] = ev[key];
192
+ }
193
+ const response = await conn.requestPermission({
194
+ sessionId,
195
+ toolCall: { toolCallId: `atomic-ui-${id}`, title, kind: "other", status: "pending", rawInput },
196
+ options: method === "confirm" ? [
197
+ { optionId: "yes", name: "Yes", kind: "allow_once" },
198
+ { optionId: "no", name: "No", kind: "reject_once" }
199
+ ] : options.map((name, index2) => ({ optionId: `choice-${index2}`, name, kind: "allow_once" }))
200
+ });
201
+ if (response.outcome.outcome !== "selected") return cancelled;
202
+ const optionId = response.outcome.optionId;
203
+ if (method === "confirm")
204
+ return optionId === "yes" || optionId === "no" ? { type: "extension_ui_response", id, confirmed: optionId === "yes" } : cancelled;
205
+ const index = options.findIndex((_, index2) => optionId === `choice-${index2}`);
206
+ return index < 0 ? cancelled : { type: "extension_ui_response", id, value: options[index] };
207
+ } catch {
208
+ return cancelled;
209
+ }
210
+ }
211
+
212
+ // src/acp/session.ts
213
+ import { RequestError as RequestError2 } from "@agentclientprotocol/sdk";
214
+
215
+ // src/acp/auth-required.ts
216
+ import { RequestError } from "@agentclientprotocol/sdk";
217
+ function maybeAuthRequiredError(err) {
218
+ const msg = String(err?.message ?? err ?? "");
219
+ const s = msg.toLowerCase();
220
+ const patterns = [
221
+ "api key",
222
+ "apikey",
223
+ "missing key",
224
+ "no key",
225
+ "not configured",
226
+ "unauthorized",
227
+ "authentication",
228
+ "permission denied",
229
+ "forbidden",
230
+ "401",
231
+ "403"
232
+ ];
233
+ const hit = patterns.some((p) => s.includes(p));
234
+ if (!hit) return null;
235
+ return RequestError.authRequired(
236
+ {
237
+ authMethods: getAuthMethods()
238
+ },
239
+ "Configure an API key or log in with an OAuth provider."
240
+ );
241
+ }
242
+
243
+ // src/acp/session.ts
244
+ import { readFileSync as readFileSync4 } from "fs";
245
+ import { isAbsolute, resolve as resolvePath } from "path";
246
+
247
+ // src/atomic-rpc/process.ts
248
+ import { spawn } from "child_process";
249
+ import crossSpawn from "cross-spawn";
250
+
251
+ // src/atomic-rpc/command.ts
252
+ import { platform } from "os";
253
+ function defaultAtomicCommand() {
254
+ return platform() === "win32" ? "atomic.cmd" : "atomic";
255
+ }
256
+ function getAtomicCommand(override) {
257
+ return override ?? defaultAtomicCommand();
258
+ }
259
+ function shouldUseShellForAtomicCommand(cmd) {
260
+ if (platform() !== "win32") return false;
261
+ const normalized = cmd.trim().toLowerCase();
262
+ return normalized.endsWith(".cmd") || normalized.endsWith(".bat");
263
+ }
264
+
265
+ // src/atomic-rpc/process.ts
266
+ var AtomicRpcSpawnError = class extends Error {
267
+ /** Underlying spawn error code, e.g. ENOENT, EACCES */
268
+ code;
269
+ constructor(message, opts) {
270
+ super(message);
271
+ this.name = "AtomicRpcSpawnError";
272
+ this.code = opts?.code;
273
+ this.cause = opts?.cause;
274
+ }
275
+ };
276
+ var ESC = String.fromCharCode(27);
277
+ var CSI = String.fromCharCode(155);
278
+ var ANSI_ESCAPE_REGEX = new RegExp(
279
+ `[${ESC}${CSI}][[\\]()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]`,
280
+ "g"
281
+ );
282
+ function stripAnsi(s) {
283
+ return s.replace(ANSI_ESCAPE_REGEX, "");
284
+ }
285
+ function splitLfJsonlChunk(buffer, chunk) {
286
+ const combined = buffer + chunk;
287
+ const parts = combined.split("\n");
288
+ return { lines: parts.slice(0, -1), buffer: parts.at(-1) ?? "" };
289
+ }
290
+ var SESSION_STATS_TIMEOUT_MS = 1e3;
291
+ var AtomicRpcProcess = class _AtomicRpcProcess {
292
+ child;
293
+ pending = /* @__PURE__ */ new Map();
294
+ eventHandlers = [];
295
+ exitHandlers = [];
296
+ preludeLines = [];
297
+ constructor(child) {
298
+ this.child = child;
299
+ let stdoutBuffer = "";
300
+ child.stdout.setEncoding("utf8");
301
+ child.stdout.on("data", (chunk) => {
302
+ const split = splitLfJsonlChunk(stdoutBuffer, String(chunk));
303
+ stdoutBuffer = split.buffer;
304
+ for (const line of split.lines) {
305
+ if (!line.trim()) continue;
306
+ let msg;
307
+ try {
308
+ msg = JSON.parse(line);
309
+ } catch {
310
+ const cleaned = stripAnsi(String(line)).trimEnd();
311
+ if (cleaned) this.preludeLines.push(cleaned);
312
+ continue;
313
+ }
314
+ if (msg?.type === "response") {
315
+ const id = typeof msg.id === "string" ? msg.id : void 0;
316
+ if (id !== void 0) this.pending.get(id)?.resolve(msg);
317
+ continue;
318
+ }
319
+ for (const h of this.eventHandlers) h(msg);
320
+ }
321
+ });
322
+ child.on("exit", (code, signal) => {
323
+ const err = new Error(`Atomic process exited (code=${code}, signal=${signal})`);
324
+ this.rejectPendingAndNotifyExit(err);
325
+ });
326
+ child.on("error", (err) => {
327
+ this.rejectPendingAndNotifyExit(err instanceof Error ? err : new Error(String(err)));
328
+ });
329
+ }
330
+ static async spawn(params) {
331
+ const cmd = getAtomicCommand(params.atomicCommand);
332
+ const args = ["--mode", "rpc", "--no-themes"];
333
+ if (params.sessionPath) args.push("--session", params.sessionPath);
334
+ const start = shouldUseShellForAtomicCommand(cmd) ? crossSpawn : spawn;
335
+ const child = start(cmd, args, {
336
+ cwd: params.cwd,
337
+ stdio: "pipe",
338
+ env: process.env
339
+ });
340
+ try {
341
+ await new Promise((resolve3, reject) => {
342
+ const onSpawn = () => {
343
+ cleanup();
344
+ resolve3();
345
+ };
346
+ const onError = (err) => {
347
+ cleanup();
348
+ reject(err);
349
+ };
350
+ const cleanup = () => {
351
+ child.off("spawn", onSpawn);
352
+ child.off("error", onError);
353
+ };
354
+ child.once("spawn", onSpawn);
355
+ child.once("error", onError);
356
+ });
357
+ } catch (e) {
358
+ const code = typeof e?.code === "string" ? e.code : void 0;
359
+ if (code === "ENOENT") {
360
+ throw new AtomicRpcSpawnError(
361
+ `Could not start Atomic: executable not found (command: ${cmd}). Atomic needs to be installed before it can run in ACP clients. Install it via \`npm install -g @bastani/atomic\` or ensure \`atomic\` is on your PATH. Then try again.`,
362
+ { code, cause: e }
363
+ );
364
+ }
365
+ if (code === "EACCES") {
366
+ throw new AtomicRpcSpawnError(`Could not start Atomic: permission denied (command: ${cmd}).`, {
367
+ code,
368
+ cause: e
369
+ });
370
+ }
371
+ throw new AtomicRpcSpawnError(`Could not start Atomic (command: ${cmd}).`, { code, cause: e });
372
+ }
373
+ child.stderr.on("data", () => {
374
+ });
375
+ const proc = new _AtomicRpcProcess(child);
376
+ try {
377
+ const state = await proc.getState();
378
+ const sessionFile = typeof state?.sessionFile === "string" ? state.sessionFile : null;
379
+ if (sessionFile) {
380
+ const { mkdirSync: mkdirSync2 } = await import("fs");
381
+ const { dirname: dirname3 } = await import("path");
382
+ mkdirSync2(dirname3(sessionFile), { recursive: true });
383
+ }
384
+ } catch {
385
+ }
386
+ return proc;
387
+ }
388
+ onEvent(handler) {
389
+ this.eventHandlers.push(handler);
390
+ return () => {
391
+ this.eventHandlers = this.eventHandlers.filter((h) => h !== handler);
392
+ };
393
+ }
394
+ onExit(handler) {
395
+ this.exitHandlers.push(handler);
396
+ return () => {
397
+ this.exitHandlers = this.exitHandlers.filter((h) => h !== handler);
398
+ };
399
+ }
400
+ rejectPendingAndNotifyExit(err) {
401
+ for (const [, p] of this.pending) p.reject(err);
402
+ this.pending.clear();
403
+ for (const h of this.exitHandlers) h(err);
404
+ }
405
+ dispose(signal = "SIGTERM") {
406
+ if (this.child.killed) return;
407
+ try {
408
+ this.child.kill(signal);
409
+ } catch {
410
+ }
411
+ }
412
+ /**
413
+ * Human-readable stdout lines emitted before RPC NDJSON begins (e.g. Context/Skills/Extensions info).
414
+ * Themes are typically noisy/less useful for ACP, so callers can filter as needed.
415
+ */
416
+ consumePreludeLines() {
417
+ const lines = this.preludeLines.splice(0, this.preludeLines.length);
418
+ return lines;
419
+ }
420
+ async prompt(message, images = [], streamingBehavior) {
421
+ const res = await this.request({
422
+ type: "prompt",
423
+ message,
424
+ images,
425
+ ...streamingBehavior ? { streamingBehavior } : {}
426
+ });
427
+ if (!res.success) throw new Error(`Atomic prompt failed: ${res.error ?? JSON.stringify(res.data)}`);
428
+ const disposition = res.data?.disposition;
429
+ return disposition === "started" || disposition === "queued" || disposition === "handled" ? disposition : void 0;
430
+ }
431
+ async abort() {
432
+ const res = await this.request({ type: "abort" });
433
+ if (!res.success) throw new Error(`Atomic abort failed: ${res.error ?? JSON.stringify(res.data)}`);
434
+ }
435
+ writeExtensionUiResponse(response) {
436
+ return this.writeJsonLine(response);
437
+ }
438
+ async getState() {
439
+ const res = await this.request({ type: "get_state" });
440
+ if (!res.success) throw new Error(`Atomic get_state failed: ${res.error ?? JSON.stringify(res.data)}`);
441
+ return res.data;
442
+ }
443
+ async getAvailableModels() {
444
+ const res = await this.request({ type: "get_available_models" });
445
+ if (!res.success) throw new Error(`Atomic get_available_models failed: ${res.error ?? JSON.stringify(res.data)}`);
446
+ return res.data;
447
+ }
448
+ async setModel(provider, modelId) {
449
+ const res = await this.request({ type: "set_model", provider, modelId });
450
+ if (!res.success) throw new Error(`Atomic set_model failed: ${res.error ?? JSON.stringify(res.data)}`);
451
+ return res.data;
452
+ }
453
+ async getAvailableThinkingLevels() {
454
+ const res = await this.request({ type: "get_available_thinking_levels" });
455
+ if (!res.success)
456
+ throw new Error(`Atomic get_available_thinking_levels failed: ${res.error ?? JSON.stringify(res.data)}`);
457
+ const data = res.data;
458
+ const levels = data && typeof data === "object" && "levels" in data ? data.levels : void 0;
459
+ if (!Array.isArray(levels) || levels.length === 0 || !levels.every((level) => typeof level === "string" && level.length > 0)) {
460
+ throw new Error("Atomic get_available_thinking_levels returned invalid levels");
461
+ }
462
+ return levels;
463
+ }
464
+ async setThinkingLevel(level) {
465
+ const res = await this.request({ type: "set_thinking_level", level });
466
+ if (!res.success) throw new Error(`Atomic set_thinking_level failed: ${res.error ?? JSON.stringify(res.data)}`);
467
+ }
468
+ async setFollowUpMode(mode) {
469
+ const res = await this.request({ type: "set_follow_up_mode", mode });
470
+ if (!res.success) throw new Error(`Atomic set_follow_up_mode failed: ${res.error ?? JSON.stringify(res.data)}`);
471
+ }
472
+ async setSteeringMode(mode) {
473
+ const res = await this.request({ type: "set_steering_mode", mode });
474
+ if (!res.success) throw new Error(`Atomic set_steering_mode failed: ${res.error ?? JSON.stringify(res.data)}`);
475
+ }
476
+ async compact(customInstructions) {
477
+ const res = await this.request({ type: "compact", customInstructions });
478
+ if (!res.success) throw new Error(`Atomic compact failed: ${res.error ?? JSON.stringify(res.data)}`);
479
+ return res.data;
480
+ }
481
+ async setAutoCompaction(enabled) {
482
+ const res = await this.request({ type: "set_auto_compaction", enabled });
483
+ if (!res.success) throw new Error(`Atomic set_auto_compaction failed: ${res.error ?? JSON.stringify(res.data)}`);
484
+ }
485
+ async getSessionStats(timeoutMs) {
486
+ const res = await this.request({ type: "get_session_stats" }, { timeoutMs });
487
+ if (!res.success) throw new Error(`Atomic get_session_stats failed: ${res.error ?? JSON.stringify(res.data)}`);
488
+ return res.data ?? {};
489
+ }
490
+ async setSessionName(name) {
491
+ const res = await this.request({ type: "set_session_name", name });
492
+ if (!res.success) throw new Error(`Atomic set_session_name failed: ${res.error ?? JSON.stringify(res.data)}`);
493
+ }
494
+ async exportHtml(outputPath) {
495
+ const res = await this.request({ type: "export_html", outputPath });
496
+ if (!res.success) throw new Error(`Atomic export_html failed: ${res.error ?? JSON.stringify(res.data)}`);
497
+ const data = res.data;
498
+ return { path: String(data?.path ?? "") };
499
+ }
500
+ async switchSession(sessionPath) {
501
+ const res = await this.request({ type: "switch_session", sessionPath });
502
+ if (!res.success) throw new Error(`Atomic switch_session failed: ${res.error ?? JSON.stringify(res.data)}`);
503
+ }
504
+ async getMessages() {
505
+ const res = await this.request({ type: "get_messages" });
506
+ if (!res.success) throw new Error(`Atomic get_messages failed: ${res.error ?? JSON.stringify(res.data)}`);
507
+ return res.data;
508
+ }
509
+ async getCommands() {
510
+ const res = await this.request({ type: "get_commands" });
511
+ if (!res.success) throw new Error(`Atomic get_commands failed: ${res.error ?? JSON.stringify(res.data)}`);
512
+ return res.data;
513
+ }
514
+ writeJsonLine(value) {
515
+ const line = JSON.stringify(value) + "\n";
516
+ return new Promise((resolve3, reject) => {
517
+ try {
518
+ this.child.stdin.write(line, (err) => {
519
+ if (err) reject(err);
520
+ else resolve3();
521
+ });
522
+ } catch (e) {
523
+ reject(e);
524
+ }
525
+ });
526
+ }
527
+ async listWorkflowRuns(status) {
528
+ const res = await this.request({ type: "list_workflow_runs", ...status ? { status } : {} });
529
+ if (!res.success) throw new Error(`Atomic list_workflow_runs failed: ${res.error ?? JSON.stringify(res.data)}`);
530
+ return res.data;
531
+ }
532
+ async getWorkflowRunSummary(runId) {
533
+ const res = await this.request({ type: "get_workflow_run_summary", runId });
534
+ if (!res.success)
535
+ throw new Error(`Atomic get_workflow_run_summary failed: ${res.error ?? JSON.stringify(res.data)}`);
536
+ return res.data;
537
+ }
538
+ request(cmd, opts) {
539
+ const id = crypto.randomUUID();
540
+ const withId = { ...cmd, id };
541
+ const timeoutMs = opts?.timeoutMs;
542
+ return new Promise((resolve3, reject) => {
543
+ let timer;
544
+ const drop = () => {
545
+ if (timer !== void 0) {
546
+ clearTimeout(timer);
547
+ timer = void 0;
548
+ }
549
+ return this.pending.delete(id);
550
+ };
551
+ this.pending.set(id, {
552
+ resolve: (res) => {
553
+ drop();
554
+ resolve3(res);
555
+ },
556
+ reject: (error) => {
557
+ drop();
558
+ reject(error);
559
+ }
560
+ });
561
+ if (timeoutMs !== void 0) {
562
+ timer = setTimeout(() => {
563
+ timer = void 0;
564
+ if (!this.pending.delete(id)) return;
565
+ reject(new Error(`Atomic ${cmd.type} timed out after ${timeoutMs}ms`));
566
+ }, timeoutMs);
567
+ timer.unref?.();
568
+ }
569
+ this.writeJsonLine(withId).catch((err) => {
570
+ if (!drop()) return;
571
+ reject(err);
572
+ });
573
+ });
574
+ }
575
+ };
576
+
577
+ // src/acp/session-store.ts
578
+ import { mkdirSync, readFileSync, writeFileSync } from "fs";
579
+ import { dirname } from "path";
580
+
581
+ // src/acp/paths.ts
582
+ import { homedir } from "os";
583
+ import { join } from "path";
584
+ function getAtomicAcpDir() {
585
+ return join(homedir(), ".atomic", "atomic-acp");
586
+ }
587
+ function getAtomicAcpSessionMapPath() {
588
+ return join(getAtomicAcpDir(), "session-map.json");
589
+ }
590
+
591
+ // src/acp/session-store.ts
592
+ function ensureParentDir(path) {
593
+ mkdirSync(dirname(path), { recursive: true });
594
+ }
595
+ function loadFile(path) {
596
+ try {
597
+ const raw = readFileSync(path, "utf-8");
598
+ const parsed = JSON.parse(raw);
599
+ if (parsed?.version !== 1 || typeof parsed.sessions !== "object" || !parsed.sessions) {
600
+ return { version: 1, sessions: {} };
601
+ }
602
+ return parsed;
603
+ } catch {
604
+ return { version: 1, sessions: {} };
605
+ }
606
+ }
607
+ function saveFile(path, data) {
608
+ ensureParentDir(path);
609
+ writeFileSync(path, JSON.stringify(data, null, 2) + "\n", "utf-8");
610
+ }
611
+ var SessionStore = class {
612
+ path;
613
+ constructor(path = getAtomicAcpSessionMapPath()) {
614
+ this.path = path;
615
+ }
616
+ get(sessionId) {
617
+ const db = loadFile(this.path);
618
+ return db.sessions[sessionId] ?? null;
619
+ }
620
+ upsert(entry) {
621
+ const db = loadFile(this.path);
622
+ db.sessions[entry.sessionId] = {
623
+ sessionId: entry.sessionId,
624
+ cwd: entry.cwd,
625
+ sessionFile: entry.sessionFile,
626
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
627
+ };
628
+ saveFile(this.path, db);
629
+ }
630
+ delete(sessionId) {
631
+ const db = loadFile(this.path);
632
+ if (!db.sessions[sessionId]) return;
633
+ delete db.sessions[sessionId];
634
+ saveFile(this.path, db);
635
+ }
636
+ };
637
+
638
+ // src/acp/translate/atomic-tools.ts
639
+ function toolResultToText(result) {
640
+ if (!result) return "";
641
+ const details = result.details;
642
+ const diff = details?.diff;
643
+ if (typeof diff === "string" && diff.trim()) return diff;
644
+ const content = result.content;
645
+ if (Array.isArray(content)) {
646
+ const texts = content.map((c) => c?.type === "text" && typeof c.text === "string" ? c.text : "").filter(Boolean);
647
+ if (texts.length) return texts.join("");
648
+ }
649
+ const stdout = (typeof details?.stdout === "string" ? details.stdout : void 0) ?? (typeof result?.stdout === "string" ? result.stdout : void 0) ?? (typeof details?.output === "string" ? details.output : void 0) ?? (typeof result?.output === "string" ? result.output : void 0);
650
+ const stderr = (typeof details?.stderr === "string" ? details.stderr : void 0) ?? (typeof result?.stderr === "string" ? result.stderr : void 0);
651
+ const exitCode = (typeof details?.exitCode === "number" ? details.exitCode : void 0) ?? (typeof result?.exitCode === "number" ? result.exitCode : void 0) ?? (typeof details?.code === "number" ? details.code : void 0) ?? (typeof result?.code === "number" ? result.code : void 0);
652
+ if (typeof stdout === "string" && stdout.trim() || typeof stderr === "string" && stderr.trim()) {
653
+ const parts = [];
654
+ if (typeof stdout === "string" && stdout.trim()) parts.push(stdout);
655
+ if (typeof stderr === "string" && stderr.trim()) parts.push(`stderr:
656
+ ${stderr}`);
657
+ if (typeof exitCode === "number") parts.push(`exit code: ${exitCode}`);
658
+ return parts.join("\n\n").trimEnd();
659
+ }
660
+ try {
661
+ return JSON.stringify(result, null, 2);
662
+ } catch {
663
+ return String(result);
664
+ }
665
+ }
666
+
667
+ // src/acp/slash-commands.ts
668
+ import { existsSync as existsSync2, readdirSync, readFileSync as readFileSync3, statSync } from "fs";
669
+ import { basename, join as join3 } from "path";
670
+
671
+ // src/acp/atomic-settings.ts
672
+ import { existsSync, readFileSync as readFileSync2 } from "fs";
673
+ import { homedir as homedir2 } from "os";
674
+ import { join as join2, resolve } from "path";
675
+ function isObject(x) {
676
+ return Boolean(x) && typeof x === "object" && !Array.isArray(x);
677
+ }
678
+ function deepMerge(a, b) {
679
+ const out = { ...a };
680
+ for (const [k, v] of Object.entries(b)) {
681
+ const av = out[k];
682
+ if (isObject(av) && isObject(v)) out[k] = deepMerge(av, v);
683
+ else out[k] = v;
684
+ }
685
+ return out;
686
+ }
687
+ function readJsonFile(path) {
688
+ try {
689
+ if (!existsSync(path)) return {};
690
+ const raw = readFileSync2(path, "utf-8");
691
+ const data = JSON.parse(raw.replace(/^\uFEFF/, ""));
692
+ return isObject(data) ? data : {};
693
+ } catch {
694
+ return {};
695
+ }
696
+ }
697
+ function getFirstDefinedEnv(names) {
698
+ for (const name of names) {
699
+ const value = process.env[name];
700
+ if (value !== void 0) return value;
701
+ }
702
+ return void 0;
703
+ }
704
+ function hasAgentDirOverride() {
705
+ return process.env.ATOMIC_CODING_AGENT_DIR !== void 0 || process.env.PI_CODING_AGENT_DIR !== void 0;
706
+ }
707
+ function readMergedJsonFiles(paths) {
708
+ let merged = {};
709
+ for (let i = paths.length - 1; i >= 0; i--) {
710
+ merged = deepMerge(merged, readJsonFile(paths[i]));
711
+ }
712
+ return merged;
713
+ }
714
+ function getSettingsWithLocations(cwd) {
715
+ const agentDirs = getAgentDirs();
716
+ const projectDirs = getProjectConfigDirs(cwd);
717
+ return [
718
+ {
719
+ location: "user",
720
+ baseDirs: agentDirs,
721
+ settings: readMergedJsonFiles(agentDirs.map((dir) => join2(dir, "settings.json")))
722
+ },
723
+ {
724
+ location: "project",
725
+ baseDirs: projectDirs,
726
+ settings: readMergedJsonFiles(projectDirs.map((dir) => join2(dir, "settings.json")))
727
+ }
728
+ ];
729
+ }
730
+ function getMergedSettings(cwd) {
731
+ const settings = getSettingsWithLocations(cwd);
732
+ return deepMerge(settings[0].settings, settings[1].settings);
733
+ }
734
+ function expandHomePath(value) {
735
+ if (value === "~") return homedir2();
736
+ if (value.startsWith("~/")) return join2(homedir2(), value.slice(2));
737
+ return value;
738
+ }
739
+ function resolveAtomicPath(value, relativeBase = process.cwd()) {
740
+ const expanded = expandHomePath(value);
741
+ return resolve(relativeBase, expanded);
742
+ }
743
+ function readMergedResourceSettings(cwd) {
744
+ const prompts = [];
745
+ for (const entry of [...getSettingsWithLocations(cwd)].reverse()) {
746
+ const rawPrompts = entry.settings.prompts;
747
+ if (!Array.isArray(rawPrompts)) continue;
748
+ for (const value of rawPrompts) {
749
+ if (typeof value === "string") prompts.push({ value, location: entry.location, baseDirs: entry.baseDirs });
750
+ }
751
+ }
752
+ return { prompts };
753
+ }
754
+ function getAgentDir() {
755
+ const override = getFirstDefinedEnv(["ATOMIC_CODING_AGENT_DIR", "PI_CODING_AGENT_DIR"])?.trim();
756
+ return override ? resolveAtomicPath(override) : join2(homedir2(), ".atomic", "agent");
757
+ }
758
+ function getAgentDirs() {
759
+ const primary = getAgentDir();
760
+ if (hasAgentDirOverride()) return [primary];
761
+ const legacy = join2(homedir2(), ".pi", "agent");
762
+ return legacy === primary ? [primary] : [primary, legacy];
763
+ }
764
+ function getProjectConfigDirs(cwd) {
765
+ const resolvedCwd = resolve(cwd);
766
+ return [resolve(resolvedCwd, ".atomic"), resolve(resolvedCwd, ".pi")];
767
+ }
768
+ function getEnableSkillCommands(cwd) {
769
+ const merged = getMergedSettings(cwd);
770
+ const direct = merged.enableSkillCommands;
771
+ if (typeof direct === "boolean") return direct;
772
+ const nested = isObject(merged.skills) ? merged.skills.enableSkillCommands : void 0;
773
+ if (typeof nested === "boolean") return nested;
774
+ return true;
775
+ }
776
+ function getQuietStartup(cwd) {
777
+ const merged = getMergedSettings(cwd);
778
+ const direct = merged.quietStartup;
779
+ if (typeof direct === "boolean") return direct;
780
+ const legacy = merged.quietStart;
781
+ if (typeof legacy === "boolean") return legacy;
782
+ return false;
783
+ }
784
+
785
+ // src/acp/slash-commands.ts
786
+ function parseFrontmatter(content) {
787
+ const frontmatter = {};
788
+ if (!content.startsWith("---")) return { frontmatter, content };
789
+ const endIndex = content.indexOf("\n---", 3);
790
+ if (endIndex === -1) return { frontmatter, content };
791
+ const frontmatterBlock = content.slice(4, endIndex);
792
+ const remaining = content.slice(endIndex + 4).trim();
793
+ for (const line of frontmatterBlock.split("\n")) {
794
+ const match = line.match(/^(\w+):\s*(.*)$/);
795
+ if (match) frontmatter[match[1]] = match[2].trim();
796
+ }
797
+ return { frontmatter, content: remaining };
798
+ }
799
+ function describeContent(content, frontmatter, sourceStr) {
800
+ let description = frontmatter.description || "";
801
+ if (!description) {
802
+ const firstLine = content.split("\n").find((l) => l.trim());
803
+ if (firstLine) {
804
+ description = firstLine.slice(0, 60);
805
+ if (firstLine.length > 60) description += "...";
806
+ }
807
+ }
808
+ return description ? `${description} ${sourceStr}` : sourceStr;
809
+ }
810
+ function loadCommandFromFile(path, sourceStr, name = basename(path, ".md")) {
811
+ try {
812
+ const rawContent = readFileSync3(path, "utf-8");
813
+ const { frontmatter, content } = parseFrontmatter(rawContent);
814
+ return {
815
+ name,
816
+ description: describeContent(content, frontmatter, sourceStr),
817
+ content,
818
+ source: sourceStr,
819
+ path
820
+ };
821
+ } catch {
822
+ return null;
823
+ }
824
+ }
825
+ function loadCommandsFromDir(dir, source, subdir = "") {
826
+ const commands = [];
827
+ if (!existsSync2(dir)) return commands;
828
+ try {
829
+ const entries = readdirSync(dir, { withFileTypes: true });
830
+ for (const entry of entries) {
831
+ if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
832
+ const fullPath = join3(dir, entry.name);
833
+ const sourceStr = source === "path" ? "(path)" : source === "user" ? subdir ? `(user:${subdir})` : "(user)" : subdir ? `(project:${subdir})` : "(project)";
834
+ const command = loadCommandFromFile(fullPath, sourceStr);
835
+ if (command) commands.push(command);
836
+ }
837
+ } catch {
838
+ }
839
+ return commands;
840
+ }
841
+ function settingSourceLabel(location) {
842
+ return location === "user" ? "(user:settings)" : "(project:settings)";
843
+ }
844
+ function resolvePromptSettingPaths(value, baseDirs) {
845
+ return baseDirs.map((baseDir) => resolveAtomicPath(value, baseDir));
846
+ }
847
+ function loadCommandsFromSettingPath(path, location) {
848
+ try {
849
+ const stat = statSync(path);
850
+ if (stat.isFile() && path.endsWith(".md")) {
851
+ const command = loadCommandFromFile(path, settingSourceLabel(location));
852
+ return command ? [command] : [];
853
+ }
854
+ if (stat.isDirectory()) return loadCommandsFromDir(path, "path");
855
+ } catch {
856
+ }
857
+ return [];
858
+ }
859
+ function filterExcluded(commands, excludedPaths) {
860
+ if (!excludedPaths.size) return commands;
861
+ return commands.filter((c) => !c.path || !excludedPaths.has(c.path));
862
+ }
863
+ function loadSlashCommands(cwd) {
864
+ const settings = readMergedResourceSettings(cwd);
865
+ const commands = [];
866
+ const excludedPaths = /* @__PURE__ */ new Set();
867
+ for (const entry of settings.prompts) {
868
+ const raw = entry.value.trim();
869
+ if (!raw) continue;
870
+ const marker = raw[0];
871
+ const isExclusion = marker === "-" || marker === "!";
872
+ const isForceInclude = marker === "+";
873
+ const pathText = isExclusion || isForceInclude ? raw.slice(1) : raw;
874
+ const resolvedPaths = resolvePromptSettingPaths(pathText, entry.baseDirs);
875
+ if (isExclusion) {
876
+ for (const resolved of resolvedPaths) excludedPaths.add(resolved);
877
+ continue;
878
+ }
879
+ for (const resolved of resolvedPaths) {
880
+ commands.push(...loadCommandsFromSettingPath(resolved, entry.location));
881
+ }
882
+ }
883
+ const projectDirs = getProjectConfigDirs(cwd).map((configDir) => join3(configDir, "prompts"));
884
+ const userDirs = getAgentDirs().map((agentDir) => join3(agentDir, "prompts"));
885
+ for (const projectDir of projectDirs) commands.push(...loadCommandsFromDir(projectDir, "project"));
886
+ for (const userDir of userDirs) commands.push(...loadCommandsFromDir(userDir, "user"));
887
+ return filterExcluded(commands, excludedPaths);
888
+ }
889
+ function loadSlashCommandsFromAtomicGetCommands(data) {
890
+ const root = data;
891
+ const commandsRaw = Array.isArray(root?.commands) ? root.commands : Array.isArray(root?.data?.commands) ? root.data.commands : [];
892
+ const out = [];
893
+ for (const c of commandsRaw) {
894
+ if (c?.source !== "prompt") continue;
895
+ const name = typeof c.name === "string" ? c.name.trim() : "";
896
+ const path = typeof c.path === "string" ? c.path : "";
897
+ if (!name || !path) continue;
898
+ const location = typeof c.location === "string" && c.location ? c.location : "path";
899
+ const sourceStr = `(${location})`;
900
+ const command = loadCommandFromFile(path, sourceStr, name);
901
+ if (!command) continue;
902
+ if (typeof c.description === "string" && c.description.trim()) command.description = c.description.trim();
903
+ out.push(command);
904
+ }
905
+ return out;
906
+ }
907
+ function toAvailableCommands(fileCommands) {
908
+ const seen = /* @__PURE__ */ new Set();
909
+ const out = [];
910
+ for (const c of fileCommands) {
911
+ if (seen.has(c.name)) continue;
912
+ seen.add(c.name);
913
+ out.push({
914
+ name: c.name,
915
+ description: c.description
916
+ // input: omitted for now (Atomic commands don't specify this)
917
+ });
918
+ }
919
+ return out;
920
+ }
921
+ function parseCommandArgs(argsString) {
922
+ const args = [];
923
+ let current = "";
924
+ let inQuote = null;
925
+ for (let i = 0; i < argsString.length; i++) {
926
+ const ch = argsString[i];
927
+ if (inQuote) {
928
+ if (ch === inQuote) inQuote = null;
929
+ else current += ch;
930
+ continue;
931
+ }
932
+ if (ch === '"' || ch === "'") {
933
+ inQuote = ch;
934
+ } else if (ch === " " || ch === " ") {
935
+ if (current) {
936
+ args.push(current);
937
+ current = "";
938
+ }
939
+ } else {
940
+ current += ch;
941
+ }
942
+ }
943
+ if (current) args.push(current);
944
+ return args;
945
+ }
946
+ function substituteArgs(content, args) {
947
+ const allArgs = args.join(" ");
948
+ return content.replace(/\$\{@:(\d+)(?::(\d+))?\}|\$ARGUMENTS|\$@|\$(\d+)/g, (match, start, length, num) => {
949
+ if (match === "$ARGUMENTS" || match === "$@") return allArgs;
950
+ if (num !== void 0) {
951
+ const idx = Number.parseInt(String(num), 10) - 1;
952
+ return args[idx] ?? "";
953
+ }
954
+ const startIndex = Math.max(Number.parseInt(String(start), 10) - 1, 0);
955
+ const count = length === void 0 ? void 0 : Number.parseInt(String(length), 10);
956
+ const selected = count === void 0 ? args.slice(startIndex) : args.slice(startIndex, startIndex + count);
957
+ return selected.join(" ");
958
+ });
959
+ }
960
+ function expandSlashCommand(text, fileCommands) {
961
+ if (!text.startsWith("/")) return text;
962
+ const spaceIndex = text.indexOf(" ");
963
+ const commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);
964
+ const argsString = spaceIndex === -1 ? "" : text.slice(spaceIndex + 1);
965
+ const cmd = fileCommands.find((c) => c.name === commandName);
966
+ if (!cmd) return text;
967
+ const args = parseCommandArgs(argsString);
968
+ return substituteArgs(cmd.content, args);
969
+ }
970
+
971
+ // src/acp/session.ts
972
+ function toUsageUpdate(stats) {
973
+ const used = stats?.contextUsage?.tokens;
974
+ const size = stats?.contextUsage?.contextWindow;
975
+ if (typeof used !== "number" || !Number.isSafeInteger(used) || used < 0) return null;
976
+ if (typeof size !== "number" || !Number.isSafeInteger(size) || size <= 0) return null;
977
+ return { sessionUpdate: "usage_update", used, size };
978
+ }
979
+ function findUniqueLineNumber(text, needle) {
980
+ if (!needle) return void 0;
981
+ const first = text.indexOf(needle);
982
+ if (first < 0) return void 0;
983
+ const second = text.indexOf(needle, first + needle.length);
984
+ if (second >= 0) return void 0;
985
+ let line = 1;
986
+ for (let i = 0; i < first; i += 1) {
987
+ if (text.charCodeAt(i) === 10) line += 1;
988
+ }
989
+ return line;
990
+ }
991
+ function getMutationPaths(args) {
992
+ const record2 = args;
993
+ const path = record2?.path ?? record2?.file_path;
994
+ if (typeof path === "string") return [path];
995
+ if (typeof record2?.input !== "string") return [];
996
+ return [...record2.input.matchAll(/^\[(.+)#[0-9a-fA-F]{4}\]\s*$/gm)].map((match) => match[1]);
997
+ }
998
+ function toToolCallLocations(args, cwd, line) {
999
+ const paths = getMutationPaths(args);
1000
+ if (!paths.length) return void 0;
1001
+ return paths.map((path) => ({
1002
+ path: isAbsolute(path) ? path : resolvePath(cwd, path),
1003
+ ...typeof line === "number" ? { line } : {}
1004
+ }));
1005
+ }
1006
+ var SessionManager = class {
1007
+ sessions = /* @__PURE__ */ new Map();
1008
+ store = new SessionStore();
1009
+ /** Dispose all sessions and their underlying Atomic subprocesses. */
1010
+ disposeAll() {
1011
+ for (const [id] of this.sessions) this.close(id);
1012
+ }
1013
+ /** Get a registered session if it exists (no throw). */
1014
+ maybeGet(sessionId) {
1015
+ return this.sessions.get(sessionId);
1016
+ }
1017
+ /**
1018
+ * Dispose a session's underlying Atomic process and remove it from the manager.
1019
+ * Used when clients explicitly reload a session and we want a fresh Atomic subprocess.
1020
+ */
1021
+ close(sessionId) {
1022
+ const s = this.sessions.get(sessionId);
1023
+ if (!s) return;
1024
+ try {
1025
+ s.proc.dispose?.();
1026
+ } catch {
1027
+ }
1028
+ this.sessions.delete(sessionId);
1029
+ }
1030
+ /** Close all sessions except the one with `keepSessionId`. */
1031
+ closeAllExcept(keepSessionId) {
1032
+ for (const [id] of this.sessions) {
1033
+ if (id === keepSessionId) continue;
1034
+ this.close(id);
1035
+ }
1036
+ }
1037
+ async create(params) {
1038
+ let proc;
1039
+ try {
1040
+ proc = await AtomicRpcProcess.spawn({
1041
+ cwd: params.cwd,
1042
+ atomicCommand: params.atomicCommand
1043
+ });
1044
+ } catch (e) {
1045
+ if (e instanceof AtomicRpcSpawnError) {
1046
+ throw RequestError2.internalError({ code: e.code }, e.message);
1047
+ }
1048
+ throw e;
1049
+ }
1050
+ let state = null;
1051
+ try {
1052
+ state = await proc.getState();
1053
+ } catch {
1054
+ state = null;
1055
+ }
1056
+ const sessionId = typeof state?.sessionId === "string" ? state.sessionId : crypto.randomUUID();
1057
+ const sessionFile = typeof state?.sessionFile === "string" ? state.sessionFile : null;
1058
+ if (sessionFile) {
1059
+ this.store.upsert({ sessionId, cwd: params.cwd, sessionFile });
1060
+ }
1061
+ const session = new AtomicAcpSession({
1062
+ sessionId,
1063
+ cwd: params.cwd,
1064
+ mcpServers: params.mcpServers,
1065
+ proc,
1066
+ conn: params.conn,
1067
+ fileCommands: params.fileCommands ?? [],
1068
+ autoTitle: true,
1069
+ clientElicitationSupport: params.clientElicitationSupport
1070
+ });
1071
+ this.sessions.set(sessionId, session);
1072
+ return session;
1073
+ }
1074
+ get(sessionId) {
1075
+ const s = this.sessions.get(sessionId);
1076
+ if (!s) throw RequestError2.invalidParams(`Unknown sessionId: ${sessionId}`);
1077
+ return s;
1078
+ }
1079
+ /**
1080
+ * Used by session/load: create a session object bound to an existing sessionId/proc
1081
+ * if it isn't already registered.
1082
+ */
1083
+ getOrCreate(sessionId, params) {
1084
+ const existing = this.sessions.get(sessionId);
1085
+ if (existing) return existing;
1086
+ const session = new AtomicAcpSession({
1087
+ sessionId,
1088
+ cwd: params.cwd,
1089
+ mcpServers: params.mcpServers,
1090
+ proc: params.proc,
1091
+ conn: params.conn,
1092
+ fileCommands: params.fileCommands ?? [],
1093
+ clientElicitationSupport: params.clientElicitationSupport
1094
+ });
1095
+ this.sessions.set(sessionId, session);
1096
+ return session;
1097
+ }
1098
+ };
1099
+ var AtomicAcpSession = class {
1100
+ sessionId;
1101
+ cwd;
1102
+ mcpServers;
1103
+ startupInfo = null;
1104
+ startupInfoSent = false;
1105
+ initialTitlePending;
1106
+ lastPublishedTitle;
1107
+ titleUpdateQueue = Promise.resolve();
1108
+ proc;
1109
+ conn;
1110
+ clientElicitationSupport;
1111
+ fileCommands;
1112
+ // Used to map abort semantics to ACP stopReason.
1113
+ // Applies to the currently running turn.
1114
+ cancelRequested = false;
1115
+ // Current in-flight turn (if any). Additional prompts are queued.
1116
+ pendingTurn = null;
1117
+ turnQueue = [];
1118
+ // Track tool call statuses and ensure they are monotonic (pending -> in_progress -> completed).
1119
+ // Some Atomic events can arrive out of order (e.g. late toolcall_* deltas after execution starts),
1120
+ // and clients may hide progress if we ever downgrade back to `pending`.
1121
+ currentToolCalls = /* @__PURE__ */ new Map();
1122
+ // Retries and queued continuations may emit multiple agent_end events before settlement.
1123
+ inAgentLoop = false;
1124
+ backgroundTurn = false;
1125
+ fileSnapshots = /* @__PURE__ */ new Map();
1126
+ fileMutationToolCallIds = /* @__PURE__ */ new Set();
1127
+ bashToolCallIds = /* @__PURE__ */ new Set();
1128
+ bashOutputSnapshots = /* @__PURE__ */ new Map();
1129
+ // Ensure `session/update` notifications are sent in order and can be awaited
1130
+ // before completing a `session/prompt` request.
1131
+ lastEmit = Promise.resolve();
1132
+ pendingExtensionDialogs = /* @__PURE__ */ new Map();
1133
+ constructor(opts) {
1134
+ this.sessionId = opts.sessionId;
1135
+ this.cwd = opts.cwd;
1136
+ this.mcpServers = opts.mcpServers;
1137
+ this.proc = opts.proc;
1138
+ this.conn = opts.conn;
1139
+ this.clientElicitationSupport = opts.clientElicitationSupport ?? NO_CLIENT_ELICITATION_SUPPORT;
1140
+ this.fileCommands = opts.fileCommands ?? [];
1141
+ this.initialTitlePending = opts.autoTitle ?? false;
1142
+ this.proc.onEvent((ev) => this.handleAtomicEvent(ev));
1143
+ this.proc.onExit?.((err) => this.handleAtomicExit(err));
1144
+ }
1145
+ setStartupInfo(text) {
1146
+ this.startupInfo = text;
1147
+ this.startupInfoSent = false;
1148
+ }
1149
+ setFileCommands(fileCommands) {
1150
+ this.fileCommands = fileCommands;
1151
+ }
1152
+ /**
1153
+ * Best-effort attempt to send startup info outside of a prompt turn.
1154
+ * Some clients (e.g. Zed) may only render agent messages once the UI is ready;
1155
+ * callers can invoke this shortly after session/new returns.
1156
+ */
1157
+ sendStartupInfoIfPending() {
1158
+ if (this.startupInfoSent || !this.startupInfo) return;
1159
+ this.startupInfoSent = true;
1160
+ this.emit({
1161
+ sessionUpdate: "agent_message_chunk",
1162
+ content: { type: "text", text: this.startupInfo }
1163
+ });
1164
+ }
1165
+ sendStartupInfoOnFirstPromptIfPending() {
1166
+ this.sendStartupInfoIfPending();
1167
+ }
1168
+ async prompt(message, images = [], title) {
1169
+ this.sendStartupInfoOnFirstPromptIfPending();
1170
+ const expandedMessage = expandSlashCommand(message, this.fileCommands);
1171
+ const turnPromise = new Promise((resolve3, reject) => {
1172
+ const queued = { message: expandedMessage, images, title, resolve: resolve3, reject };
1173
+ if (this.pendingTurn) {
1174
+ this.turnQueue.push(queued);
1175
+ this.emit({
1176
+ sessionUpdate: "agent_message_chunk",
1177
+ content: {
1178
+ type: "text",
1179
+ text: `Queued message (position ${this.turnQueue.length}).`
1180
+ }
1181
+ });
1182
+ this.emit({
1183
+ sessionUpdate: "session_info_update",
1184
+ _meta: { atomicAcp: { queueDepth: this.turnQueue.length, running: true } }
1185
+ });
1186
+ return;
1187
+ }
1188
+ this.startTurn(queued);
1189
+ });
1190
+ return turnPromise;
1191
+ }
1192
+ async cancel() {
1193
+ this.cancelRequested = true;
1194
+ if (this.turnQueue.length) {
1195
+ const queued = this.turnQueue.splice(0, this.turnQueue.length);
1196
+ for (const t of queued) t.resolve("cancelled");
1197
+ this.emit({
1198
+ sessionUpdate: "agent_message_chunk",
1199
+ content: { type: "text", text: "Cleared queued prompts." }
1200
+ });
1201
+ this.emit({
1202
+ sessionUpdate: "session_info_update",
1203
+ _meta: { atomicAcp: { queueDepth: 0, running: Boolean(this.pendingTurn) } }
1204
+ });
1205
+ }
1206
+ await this.cancelPendingExtensionDialogs();
1207
+ await this.proc.abort();
1208
+ }
1209
+ wasCancelRequested() {
1210
+ return this.cancelRequested;
1211
+ }
1212
+ async setSessionName(name) {
1213
+ return this.enqueueTitleUpdate(async () => {
1214
+ await this.proc.setSessionName(name);
1215
+ await this.publishTitle(name);
1216
+ });
1217
+ }
1218
+ enqueueTitleUpdate(update) {
1219
+ const result = this.titleUpdateQueue.then(update);
1220
+ this.titleUpdateQueue = result.catch(() => {
1221
+ });
1222
+ return result;
1223
+ }
1224
+ publishTitle(title, updatedAt = (/* @__PURE__ */ new Date()).toISOString()) {
1225
+ if (this.lastPublishedTitle === title) return this.lastEmit;
1226
+ this.lastPublishedTitle = title;
1227
+ this.emit({
1228
+ sessionUpdate: "session_info_update",
1229
+ title,
1230
+ ...updatedAt ? { updatedAt } : {}
1231
+ });
1232
+ return this.lastEmit;
1233
+ }
1234
+ async maybeAutoTitle(title) {
1235
+ if (!this.initialTitlePending || !title) return;
1236
+ this.initialTitlePending = false;
1237
+ try {
1238
+ await this.enqueueTitleUpdate(async () => {
1239
+ const state = await this.proc.getState();
1240
+ const currentTitle = typeof state?.sessionName === "string" ? state.sessionName.trim() : "";
1241
+ if (currentTitle) {
1242
+ await this.publishTitle(currentTitle);
1243
+ return;
1244
+ }
1245
+ if (this.lastPublishedTitle !== void 0) return;
1246
+ await this.proc.setSessionName(title);
1247
+ await this.publishTitle(title);
1248
+ });
1249
+ } catch {
1250
+ }
1251
+ }
1252
+ emit(update) {
1253
+ this.lastEmit = this.lastEmit.then(
1254
+ () => this.conn.sessionUpdate({
1255
+ sessionId: this.sessionId,
1256
+ update
1257
+ })
1258
+ ).catch(() => {
1259
+ });
1260
+ }
1261
+ emitAgentText(text) {
1262
+ this.emit({
1263
+ sessionUpdate: "agent_message_chunk",
1264
+ content: { type: "text", text }
1265
+ });
1266
+ }
1267
+ async flushEmits() {
1268
+ await this.lastEmit;
1269
+ }
1270
+ async publishContextUsage() {
1271
+ try {
1272
+ if (typeof this.proc.getSessionStats === "function") {
1273
+ const update = toUsageUpdate(await this.proc.getSessionStats(SESSION_STATS_TIMEOUT_MS));
1274
+ if (update) this.emit(update);
1275
+ }
1276
+ } catch {
1277
+ }
1278
+ await this.flushEmits();
1279
+ }
1280
+ emitBashToolCall(id, name, args, status) {
1281
+ const exists = this.currentToolCalls.has(id);
1282
+ this.currentToolCalls.set(id, status);
1283
+ this.bashToolCallIds.add(id);
1284
+ this.emit({
1285
+ sessionUpdate: exists ? "tool_call_update" : "tool_call",
1286
+ toolCallId: id,
1287
+ title: bashCommand(args) ?? name,
1288
+ kind: "execute",
1289
+ status,
1290
+ ...!exists ? { content: bashTerminalContent(id), _meta: bashTerminalInfoMeta(id, this.cwd) } : {}
1291
+ });
1292
+ }
1293
+ emitBashOutput(id, result, status, isError = false) {
1294
+ const text = bashResultText(result);
1295
+ const delta = bashOutputDelta(this.bashOutputSnapshots.get(id) ?? "", text);
1296
+ this.bashOutputSnapshots.set(id, text);
1297
+ this.emit({
1298
+ sessionUpdate: "tool_call_update",
1299
+ toolCallId: id,
1300
+ status,
1301
+ _meta: {
1302
+ ...delta ? bashTerminalOutputMeta(id, delta) : {},
1303
+ ...status !== "in_progress" ? bashTerminalExitMeta(id, bashExitCode(result, isError)) : {}
1304
+ }
1305
+ });
1306
+ }
1307
+ startTurn(t) {
1308
+ this.cancelRequested = false;
1309
+ this.pendingTurn = { resolve: t.resolve, reject: t.reject };
1310
+ void this.maybeAutoTitle(t.title);
1311
+ this.emit({
1312
+ sessionUpdate: "session_info_update",
1313
+ _meta: { atomicAcp: { queueDepth: this.turnQueue.length, running: true } }
1314
+ });
1315
+ const pending = this.pendingTurn;
1316
+ this.proc.prompt(t.message, t.images, "followUp").then(async (disposition) => {
1317
+ if (disposition !== "handled" || this.pendingTurn !== pending) return;
1318
+ if (this.inAgentLoop) this.backgroundTurn = true;
1319
+ await this.publishContextUsage();
1320
+ if (this.pendingTurn !== pending) return;
1321
+ pending.resolve(this.cancelRequested ? "cancelled" : "end_turn");
1322
+ this.pendingTurn = null;
1323
+ const next = this.turnQueue.shift();
1324
+ if (next) this.startTurn(next);
1325
+ else {
1326
+ this.emit({
1327
+ sessionUpdate: "session_info_update",
1328
+ _meta: { atomicAcp: { queueDepth: 0, running: false } }
1329
+ });
1330
+ }
1331
+ }).catch((err) => {
1332
+ void this.finishActiveAndQueuedFromFailure(err);
1333
+ });
1334
+ }
1335
+ async finishActiveAndQueuedFromFailure(err) {
1336
+ await this.cancelPendingExtensionDialogs();
1337
+ await this.flushEmits();
1338
+ if (!this.pendingTurn && this.turnQueue.length === 0) return;
1339
+ const authErr = maybeAuthRequiredError(err);
1340
+ const queued = this.turnQueue.splice(0);
1341
+ if (authErr) {
1342
+ this.pendingTurn?.reject(authErr);
1343
+ for (const queuedTurn of queued) queuedTurn.reject(authErr);
1344
+ } else {
1345
+ const reason = this.cancelRequested ? "cancelled" : "error";
1346
+ this.pendingTurn?.resolve(reason);
1347
+ for (const queuedTurn of queued) queuedTurn.resolve(reason);
1348
+ }
1349
+ this.pendingTurn = null;
1350
+ this.inAgentLoop = false;
1351
+ this.emit({
1352
+ sessionUpdate: "session_info_update",
1353
+ _meta: { atomicAcp: { queueDepth: 0, running: false } }
1354
+ });
1355
+ }
1356
+ handleAtomicExit(err) {
1357
+ void this.cancelPendingExtensionDialogs();
1358
+ if (!this.pendingTurn && this.turnQueue.length === 0) return;
1359
+ void this.finishActiveAndQueuedFromFailure(err);
1360
+ }
1361
+ async cancelPendingExtensionDialogs() {
1362
+ await Promise.all([...this.pendingExtensionDialogs.values()].map((cancel) => cancel()));
1363
+ }
1364
+ async writeExtensionUiResponse(response) {
1365
+ try {
1366
+ await this.proc.writeExtensionUiResponse(response);
1367
+ } catch {
1368
+ this.emitAgentText("Atomic could not receive a structured question response.");
1369
+ }
1370
+ }
1371
+ async handleExtensionUiRequest(ev) {
1372
+ const id = typeof ev.id === "string" ? ev.id : null;
1373
+ if (!id) return;
1374
+ const method = ev.method;
1375
+ if (method === "notify") {
1376
+ this.emit({
1377
+ sessionUpdate: "agent_message_chunk",
1378
+ content: { type: "text", text: typeof ev.message === "string" ? ev.message : "Atomic notification" },
1379
+ _meta: {
1380
+ atomicAcp: {
1381
+ notify: {
1382
+ level: ev.notifyType === "warning" || ev.notifyType === "error" ? ev.notifyType : "info"
1383
+ }
1384
+ }
1385
+ }
1386
+ });
1387
+ return;
1388
+ }
1389
+ if (!["select", "confirm", "input", "editor"].includes(String(method))) return;
1390
+ if (this.pendingExtensionDialogs.has(id)) return;
1391
+ if (!this.clientElicitationSupport.form && (method === "input" || method === "editor")) {
1392
+ this.emitAgentText(`Atomic ${method} UI request is not supported in ACP yet; cancelling it.`);
1393
+ }
1394
+ if (this.cancelRequested) {
1395
+ await this.writeExtensionUiResponse({ type: "extension_ui_response", id, cancelled: true });
1396
+ return;
1397
+ }
1398
+ const controller = new AbortController();
1399
+ let timer;
1400
+ const completion = Promise.resolve().then(async () => {
1401
+ try {
1402
+ const response = await requestExtensionDialog(
1403
+ this.conn,
1404
+ this.sessionId,
1405
+ ev,
1406
+ this.clientElicitationSupport.form,
1407
+ controller.signal
1408
+ );
1409
+ if (timer) clearTimeout(timer);
1410
+ await this.writeExtensionUiResponse(response);
1411
+ } finally {
1412
+ if (timer) clearTimeout(timer);
1413
+ this.pendingExtensionDialogs.delete(id);
1414
+ }
1415
+ });
1416
+ const cancel = async () => {
1417
+ controller.abort();
1418
+ await completion;
1419
+ };
1420
+ this.pendingExtensionDialogs.set(id, cancel);
1421
+ if (typeof ev.timeout === "number" && Number.isFinite(ev.timeout) && ev.timeout >= 0) {
1422
+ timer = setTimeout(() => controller.abort(), ev.timeout);
1423
+ }
1424
+ await completion;
1425
+ }
1426
+ handleAtomicEvent(ev) {
1427
+ const type = String(ev.type ?? "");
1428
+ switch (type) {
1429
+ case "session_info_changed": {
1430
+ const name = ev.name;
1431
+ if (typeof name === "string" || name === void 0) void this.publishTitle(name ?? null);
1432
+ break;
1433
+ }
1434
+ case "extension_ui_request": {
1435
+ void this.handleExtensionUiRequest(ev);
1436
+ if (ev.method === "setStatus" && typeof ev.statusText === "string" && ev.statusText) {
1437
+ this.emitAgentText(ev.statusText);
1438
+ } else if (ev.method === "setWidget" && Array.isArray(ev.widgetLines)) {
1439
+ const text = ev.widgetLines.filter((line) => typeof line === "string").join("\n");
1440
+ if (text) this.emitAgentText(text);
1441
+ }
1442
+ break;
1443
+ }
1444
+ case "message_end": {
1445
+ const message = ev.message;
1446
+ if (message?.role === "custom" && message.display === true) {
1447
+ const text = typeof message.content === "string" ? message.content : toolResultToText(message);
1448
+ if (text) this.emitAgentText(text);
1449
+ }
1450
+ break;
1451
+ }
1452
+ case "message_update": {
1453
+ const ame = ev.assistantMessageEvent;
1454
+ if (ame?.type === "text_delta" && typeof ame.delta === "string") {
1455
+ this.emit({
1456
+ sessionUpdate: "agent_message_chunk",
1457
+ content: { type: "text", text: ame.delta }
1458
+ });
1459
+ break;
1460
+ }
1461
+ if (ame?.type === "thinking_delta" && typeof ame.delta === "string") {
1462
+ this.emit({
1463
+ sessionUpdate: "agent_thought_chunk",
1464
+ content: { type: "text", text: ame.delta }
1465
+ });
1466
+ break;
1467
+ }
1468
+ if (ame?.type === "toolcall_start" || ame?.type === "toolcall_delta" || ame?.type === "toolcall_end") {
1469
+ const toolCall = (
1470
+ // Atomic sometimes includes the tool call directly on the event
1471
+ ame?.toolCall ?? // ...and always includes it in the partial assistant message at contentIndex
1472
+ ame?.partial?.content?.[ame?.contentIndex ?? 0]
1473
+ );
1474
+ const toolCallId = String(toolCall?.id ?? "");
1475
+ const toolName = String(toolCall?.name ?? "tool");
1476
+ if (toolCallId) {
1477
+ const rawInput = toolCall?.arguments && typeof toolCall.arguments === "object" ? toolCall.arguments : (() => {
1478
+ const s = String(toolCall?.partialArgs ?? "");
1479
+ if (!s) return void 0;
1480
+ try {
1481
+ return JSON.parse(s);
1482
+ } catch {
1483
+ return { partialArgs: s };
1484
+ }
1485
+ })();
1486
+ const locations = toToolCallLocations(rawInput, this.cwd);
1487
+ const existingStatus = this.currentToolCalls.get(toolCallId);
1488
+ const status = existingStatus ?? "pending";
1489
+ if (isBashTool(toolName)) {
1490
+ this.emitBashToolCall(toolCallId, toolName, rawInput, status);
1491
+ } else if (!existingStatus) {
1492
+ this.currentToolCalls.set(toolCallId, "pending");
1493
+ this.emit({
1494
+ sessionUpdate: "tool_call",
1495
+ toolCallId,
1496
+ title: toolTitle(toolName, rawInput),
1497
+ kind: toToolKind(toolName),
1498
+ status,
1499
+ locations,
1500
+ rawInput
1501
+ });
1502
+ } else {
1503
+ this.emit({
1504
+ sessionUpdate: "tool_call_update",
1505
+ toolCallId,
1506
+ ...toolName === "workflow" ? { title: toolTitle(toolName, rawInput), kind: toToolKind(toolName) } : {},
1507
+ status,
1508
+ locations,
1509
+ rawInput
1510
+ });
1511
+ }
1512
+ }
1513
+ break;
1514
+ }
1515
+ break;
1516
+ }
1517
+ case "tool_execution_start": {
1518
+ const toolCallId = String(ev.toolCallId ?? crypto.randomUUID());
1519
+ const toolName = String(ev.toolName ?? "tool");
1520
+ const args = ev.args;
1521
+ let line;
1522
+ if (isBashTool(toolName)) {
1523
+ this.emitBashToolCall(toolCallId, toolName, args, "in_progress");
1524
+ break;
1525
+ }
1526
+ if (toolName === "edit" || toolName === "write") {
1527
+ this.fileMutationToolCallIds.add(toolCallId);
1528
+ const snapshots = getMutationPaths(args).map((path) => {
1529
+ try {
1530
+ const oldText = readFileSync4(resolvePath(this.cwd, path), "utf8");
1531
+ if (typeof args?.oldText === "string") line = findUniqueLineNumber(oldText, args.oldText);
1532
+ return { path, oldText };
1533
+ } catch (error) {
1534
+ if (error.code === "ENOENT") return { path, oldText: null };
1535
+ return null;
1536
+ }
1537
+ }).filter((snapshot) => snapshot !== null);
1538
+ this.fileSnapshots.set(toolCallId, snapshots);
1539
+ }
1540
+ const locations = toToolCallLocations(args, this.cwd, line);
1541
+ if (!this.currentToolCalls.has(toolCallId)) {
1542
+ this.currentToolCalls.set(toolCallId, "in_progress");
1543
+ this.emit({
1544
+ sessionUpdate: "tool_call",
1545
+ toolCallId,
1546
+ title: toolTitle(toolName, args),
1547
+ kind: toToolKind(toolName),
1548
+ status: "in_progress",
1549
+ locations,
1550
+ rawInput: args
1551
+ });
1552
+ } else {
1553
+ this.currentToolCalls.set(toolCallId, "in_progress");
1554
+ this.emit({
1555
+ sessionUpdate: "tool_call_update",
1556
+ toolCallId,
1557
+ ...toolName === "workflow" ? { title: toolTitle(toolName, args), kind: toToolKind(toolName) } : {},
1558
+ status: "in_progress",
1559
+ locations,
1560
+ rawInput: args
1561
+ });
1562
+ }
1563
+ break;
1564
+ }
1565
+ case "tool_execution_update": {
1566
+ const toolCallId = String(ev.toolCallId ?? "");
1567
+ if (!toolCallId) break;
1568
+ const partial = ev.partialResult;
1569
+ if (this.bashToolCallIds.has(toolCallId)) {
1570
+ this.emitBashOutput(toolCallId, partial, "in_progress");
1571
+ break;
1572
+ }
1573
+ const text = this.fileMutationToolCallIds.has(toolCallId) ? "" : toolResultToText(partial);
1574
+ this.emit({
1575
+ sessionUpdate: "tool_call_update",
1576
+ toolCallId,
1577
+ status: "in_progress",
1578
+ content: text ? [{ type: "content", content: { type: "text", text } }] : void 0,
1579
+ ...this.fileMutationToolCallIds.has(toolCallId) ? {} : { rawOutput: partial }
1580
+ });
1581
+ break;
1582
+ }
1583
+ case "tool_execution_end": {
1584
+ const toolCallId = String(ev.toolCallId ?? "");
1585
+ if (!toolCallId) break;
1586
+ const result = ev.result;
1587
+ const isError = Boolean(ev.isError);
1588
+ if (this.bashToolCallIds.has(toolCallId)) {
1589
+ this.emitBashOutput(toolCallId, result, isError ? "failed" : "completed", isError);
1590
+ this.currentToolCalls.delete(toolCallId);
1591
+ this.bashToolCallIds.delete(toolCallId);
1592
+ this.bashOutputSnapshots.delete(toolCallId);
1593
+ break;
1594
+ }
1595
+ const text = toolResultToText(result);
1596
+ const snapshots = this.fileSnapshots.get(toolCallId) ?? [];
1597
+ let content;
1598
+ if (!isError) {
1599
+ for (const snapshot of snapshots) {
1600
+ try {
1601
+ const path = resolvePath(this.cwd, snapshot.path);
1602
+ const newText = readFileSync4(path, "utf8");
1603
+ if (newText !== snapshot.oldText) {
1604
+ content ??= [];
1605
+ content.push({ type: "diff", path, oldText: snapshot.oldText, newText });
1606
+ }
1607
+ } catch {
1608
+ }
1609
+ }
1610
+ }
1611
+ const hasStructuredDiff = Boolean(content?.length);
1612
+ if (!content && text) {
1613
+ content = [{ type: "content", content: { type: "text", text } }];
1614
+ }
1615
+ this.emit({
1616
+ sessionUpdate: "tool_call_update",
1617
+ toolCallId,
1618
+ status: isError ? "failed" : "completed",
1619
+ content,
1620
+ ...hasStructuredDiff ? {} : { rawOutput: result }
1621
+ });
1622
+ this.currentToolCalls.delete(toolCallId);
1623
+ this.fileSnapshots.delete(toolCallId);
1624
+ this.fileMutationToolCallIds.delete(toolCallId);
1625
+ break;
1626
+ }
1627
+ case "auto_retry_start": {
1628
+ this.emit({
1629
+ sessionUpdate: "agent_message_chunk",
1630
+ content: { type: "text", text: formatAutoRetryMessage(ev) }
1631
+ });
1632
+ break;
1633
+ }
1634
+ case "auto_retry_end": {
1635
+ this.emit({
1636
+ sessionUpdate: "agent_message_chunk",
1637
+ content: { type: "text", text: "Retry finished, resuming." }
1638
+ });
1639
+ break;
1640
+ }
1641
+ case "compaction_start":
1642
+ case "auto_compaction_start": {
1643
+ this.emit({
1644
+ sessionUpdate: "agent_message_chunk",
1645
+ content: {
1646
+ type: "text",
1647
+ text: "Compacting context..."
1648
+ }
1649
+ });
1650
+ break;
1651
+ }
1652
+ case "compaction_end":
1653
+ case "auto_compaction_end": {
1654
+ this.emit({
1655
+ sessionUpdate: "agent_message_chunk",
1656
+ content: {
1657
+ type: "text",
1658
+ text: "Context compaction finished."
1659
+ }
1660
+ });
1661
+ break;
1662
+ }
1663
+ case "agent_start": {
1664
+ this.inAgentLoop = true;
1665
+ this.backgroundTurn = !this.pendingTurn;
1666
+ break;
1667
+ }
1668
+ case "turn_end": {
1669
+ break;
1670
+ }
1671
+ case "agent_end": {
1672
+ this.inAgentLoop = false;
1673
+ break;
1674
+ }
1675
+ case "agent_settled": {
1676
+ if (this.backgroundTurn || !this.pendingTurn) {
1677
+ this.backgroundTurn = false;
1678
+ this.inAgentLoop = false;
1679
+ break;
1680
+ }
1681
+ void (async () => {
1682
+ await this.cancelPendingExtensionDialogs();
1683
+ await this.publishContextUsage();
1684
+ const reason = this.cancelRequested ? "cancelled" : "end_turn";
1685
+ this.pendingTurn?.resolve(reason);
1686
+ this.pendingTurn = null;
1687
+ this.inAgentLoop = false;
1688
+ const next = this.turnQueue.shift();
1689
+ if (next) {
1690
+ this.emit({
1691
+ sessionUpdate: "agent_message_chunk",
1692
+ content: { type: "text", text: `Starting queued message. (${this.turnQueue.length} remaining)` }
1693
+ });
1694
+ this.startTurn(next);
1695
+ } else {
1696
+ this.emit({
1697
+ sessionUpdate: "session_info_update",
1698
+ _meta: { atomicAcp: { queueDepth: 0, running: false } }
1699
+ });
1700
+ }
1701
+ })();
1702
+ break;
1703
+ }
1704
+ default:
1705
+ break;
1706
+ }
1707
+ }
1708
+ };
1709
+ function formatAutoRetryMessage(ev) {
1710
+ const attempt = Number(ev.attempt);
1711
+ const maxAttempts = Number(ev.maxAttempts);
1712
+ const delayMs = Number(ev.delayMs);
1713
+ if (!Number.isFinite(attempt) || !Number.isFinite(maxAttempts) || !Number.isFinite(delayMs)) {
1714
+ return "Retrying...";
1715
+ }
1716
+ let delaySeconds = Math.round(delayMs / 1e3);
1717
+ if (delayMs > 0 && delaySeconds === 0) delaySeconds = 1;
1718
+ return `Retrying (attempt ${attempt}/${maxAttempts}, waiting ${delaySeconds}s)...`;
1719
+ }
1720
+ function toolTitle(name, input2) {
1721
+ if (name !== "workflow") return name;
1722
+ const args = input2;
1723
+ const details = [args?.action ?? (args?.workflow ? "run" : void 0), args?.workflow ?? args?.runId].filter(
1724
+ (value) => typeof value === "string" && value
1725
+ );
1726
+ return details.length ? `workflow: ${details.join(" ")}` : name;
1727
+ }
1728
+ function toToolKind(toolName) {
1729
+ switch (toolName) {
1730
+ case "read":
1731
+ return "read";
1732
+ case "write":
1733
+ case "edit":
1734
+ return "edit";
1735
+ case "bash":
1736
+ return "execute";
1737
+ default:
1738
+ return "other";
1739
+ }
1740
+ }
1741
+
1742
+ // src/acp/atomic-sessions.ts
1743
+ import { readdirSync as readdirSync2, readFileSync as readFileSync5, statSync as statSync2, openSync, readSync, closeSync, existsSync as existsSync3 } from "fs";
1744
+ import { join as join4, resolve as resolve2 } from "path";
1745
+
1746
+ // src/acp/translate/prompt.ts
1747
+ function promptToSessionTitle(blocks) {
1748
+ const normalized = blocks.filter((block) => block.type === "text").map((block) => block.text).join(" ").replace(/\s+/gu, " ").trim();
1749
+ return normalized ? Array.from(normalized).slice(0, 80).join("") : null;
1750
+ }
1751
+ function promptToAtomicMessage(blocks) {
1752
+ let message = "";
1753
+ const images = [];
1754
+ for (const b of blocks) {
1755
+ switch (b.type) {
1756
+ case "text":
1757
+ message += b.text;
1758
+ break;
1759
+ case "resource_link":
1760
+ message += `
1761
+ [Context] ${b.uri}`;
1762
+ break;
1763
+ case "image": {
1764
+ images.push({
1765
+ type: "image",
1766
+ mimeType: b.mimeType,
1767
+ data: b.data
1768
+ });
1769
+ break;
1770
+ }
1771
+ case "resource": {
1772
+ const r = b.resource;
1773
+ const uri = typeof r?.uri === "string" ? r.uri : "(unknown)";
1774
+ if (typeof r?.text === "string") {
1775
+ const mime = typeof r?.mimeType === "string" ? r.mimeType : "text/plain";
1776
+ message += `
1777
+ [Embedded Context] ${uri} (${mime})
1778
+ ${r.text}`;
1779
+ } else if (typeof r?.blob === "string") {
1780
+ const mime = typeof r?.mimeType === "string" ? r.mimeType : "application/octet-stream";
1781
+ const bytes = Buffer.byteLength(r.blob, "base64");
1782
+ message += `
1783
+ [Embedded Context] ${uri} (${mime}, ${bytes} bytes)`;
1784
+ } else {
1785
+ message += `
1786
+ [Embedded Context] ${uri}`;
1787
+ }
1788
+ break;
1789
+ }
1790
+ case "audio": {
1791
+ const bytes = Buffer.byteLength(b.data, "base64");
1792
+ message += `
1793
+ [Audio] (${b.mimeType}, ${bytes} bytes) not supported by atomic-acp`;
1794
+ break;
1795
+ }
1796
+ default:
1797
+ break;
1798
+ }
1799
+ }
1800
+ return { message, images };
1801
+ }
1802
+
1803
+ // src/acp/atomic-sessions.ts
1804
+ var DEFAULT_TAIL_BYTES = 256 * 1024;
1805
+ var DEFAULT_HEAD_BYTES = 64 * 1024;
1806
+ function readSessionDirFromSettings(settingsPaths, cwd) {
1807
+ try {
1808
+ if (!settingsPaths.some((settingsPath) => existsSync3(settingsPath))) return null;
1809
+ const data = readMergedJsonFiles(settingsPaths);
1810
+ const sessionDir = data.sessionDir;
1811
+ if (typeof sessionDir !== "string" || !sessionDir.trim()) return null;
1812
+ return resolveAtomicPath(sessionDir, cwd);
1813
+ } catch {
1814
+ return null;
1815
+ }
1816
+ }
1817
+ function getAtomicSessionsDir(cwd) {
1818
+ const envSessionDir = process.env.ATOMIC_CODING_AGENT_SESSION_DIR?.trim() || process.env.PI_CODING_AGENT_SESSION_DIR?.trim();
1819
+ if (envSessionDir) {
1820
+ return resolveAtomicPath(envSessionDir, cwd ?? process.cwd());
1821
+ }
1822
+ const atomicCwd = cwd ? resolve2(cwd) : process.cwd();
1823
+ const agentDir = getAgentDir();
1824
+ const projectSessionDir = cwd ? readSessionDirFromSettings(
1825
+ getProjectConfigDirs(cwd).map((configDir) => join4(configDir, "settings.json")),
1826
+ atomicCwd
1827
+ ) : null;
1828
+ return projectSessionDir ?? readSessionDirFromSettings(
1829
+ getAgentDirs().map((configDir) => join4(configDir, "settings.json")),
1830
+ atomicCwd
1831
+ ) ?? join4(agentDir, "sessions");
1832
+ }
1833
+ function walkJsonlFiles(dir, out) {
1834
+ let entries;
1835
+ try {
1836
+ entries = readdirSync2(dir, { withFileTypes: true, encoding: "utf8" });
1837
+ } catch {
1838
+ return;
1839
+ }
1840
+ for (const e of entries) {
1841
+ const name = typeof e.name === "string" ? e.name : String(e.name);
1842
+ const p = join4(dir, name);
1843
+ if (e.isDirectory()) walkJsonlFiles(p, out);
1844
+ else if (e.isFile() && name.endsWith(".jsonl")) out.push(p);
1845
+ }
1846
+ }
1847
+ function readFirstLine(path) {
1848
+ const fd = openSync(path, "r");
1849
+ try {
1850
+ const buf = Buffer.alloc(DEFAULT_HEAD_BYTES);
1851
+ const n = readSync(fd, buf, 0, buf.length, 0);
1852
+ if (n <= 0) return null;
1853
+ const s = buf.subarray(0, n).toString("utf-8");
1854
+ const idx = s.indexOf("\n");
1855
+ return idx === -1 ? s.trim() : s.slice(0, idx).trim();
1856
+ } catch {
1857
+ return null;
1858
+ } finally {
1859
+ try {
1860
+ closeSync(fd);
1861
+ } catch {
1862
+ }
1863
+ }
1864
+ }
1865
+ function readTail(path, tailBytes = DEFAULT_TAIL_BYTES) {
1866
+ const st = statSync2(path);
1867
+ const start = Math.max(0, st.size - tailBytes);
1868
+ const len = st.size - start;
1869
+ const fd = openSync(path, "r");
1870
+ try {
1871
+ const buf = Buffer.alloc(len);
1872
+ const n = readSync(fd, buf, 0, buf.length, start);
1873
+ return buf.subarray(0, n).toString("utf-8");
1874
+ } finally {
1875
+ try {
1876
+ closeSync(fd);
1877
+ } catch {
1878
+ }
1879
+ }
1880
+ }
1881
+ function parseSessionHeader(firstLine) {
1882
+ try {
1883
+ const obj = JSON.parse(firstLine);
1884
+ if (obj?.type !== "session") return null;
1885
+ const sessionId = typeof obj?.id === "string" ? obj.id : null;
1886
+ const cwd = typeof obj?.cwd === "string" ? obj.cwd : null;
1887
+ if (!sessionId || !cwd) return null;
1888
+ return { sessionId, cwd };
1889
+ } catch {
1890
+ return null;
1891
+ }
1892
+ }
1893
+ function pickTitleFromTail(tail) {
1894
+ const lines = tail.split(/\r?\n/);
1895
+ for (let i = lines.length - 1; i >= 0; i--) {
1896
+ const line = lines[i].trim();
1897
+ if (!line) continue;
1898
+ try {
1899
+ const obj = JSON.parse(line);
1900
+ if (obj?.type === "session_info" && typeof obj?.name === "string") {
1901
+ return obj.name.trim();
1902
+ }
1903
+ } catch {
1904
+ }
1905
+ }
1906
+ return null;
1907
+ }
1908
+ function scanSessionInfoNameFromFile(path) {
1909
+ const fd = openSync(path, "r");
1910
+ try {
1911
+ const buf = Buffer.alloc(256 * 1024);
1912
+ let leftover = "";
1913
+ let offset = 0;
1914
+ let lastName = null;
1915
+ while (true) {
1916
+ const n = readSync(fd, buf, 0, buf.length, offset);
1917
+ if (n <= 0) break;
1918
+ offset += n;
1919
+ const chunk = leftover + buf.subarray(0, n).toString("utf8");
1920
+ const lines = chunk.split(/\r?\n/);
1921
+ leftover = lines.pop() ?? "";
1922
+ for (const line0 of lines) {
1923
+ const line = line0.trim();
1924
+ if (!line) continue;
1925
+ try {
1926
+ const obj = JSON.parse(line);
1927
+ if (obj?.type === "session_info" && typeof obj?.name === "string") {
1928
+ lastName = obj.name.trim();
1929
+ }
1930
+ } catch {
1931
+ }
1932
+ }
1933
+ }
1934
+ const tailLine = leftover.trim();
1935
+ if (tailLine) {
1936
+ try {
1937
+ const obj = JSON.parse(tailLine);
1938
+ if (obj?.type === "session_info" && typeof obj?.name === "string") {
1939
+ lastName = obj.name.trim();
1940
+ }
1941
+ } catch {
1942
+ }
1943
+ }
1944
+ return lastName;
1945
+ } catch {
1946
+ return null;
1947
+ } finally {
1948
+ try {
1949
+ closeSync(fd);
1950
+ } catch {
1951
+ }
1952
+ }
1953
+ }
1954
+ function pickUpdatedAtFromTail(tail) {
1955
+ const lines = tail.split(/\r?\n/);
1956
+ for (let i = lines.length - 1; i >= 0; i--) {
1957
+ const line = lines[i].trim();
1958
+ if (!line) continue;
1959
+ try {
1960
+ const obj = JSON.parse(line);
1961
+ if (obj?.type !== "message") continue;
1962
+ const ts = typeof obj?.timestamp === "string" ? obj.timestamp : null;
1963
+ if (!ts) continue;
1964
+ const d = new Date(ts);
1965
+ if (Number.isFinite(d.getTime())) return d.toISOString();
1966
+ } catch {
1967
+ }
1968
+ }
1969
+ for (let i = lines.length - 1; i >= 0; i--) {
1970
+ const line = lines[i].trim();
1971
+ if (!line) continue;
1972
+ try {
1973
+ const obj = JSON.parse(line);
1974
+ const ts = typeof obj?.timestamp === "string" ? obj.timestamp : null;
1975
+ if (!ts) continue;
1976
+ const d = new Date(ts);
1977
+ if (Number.isFinite(d.getTime())) return d.toISOString();
1978
+ } catch {
1979
+ }
1980
+ }
1981
+ return null;
1982
+ }
1983
+ function pickFallbackTitleFromHead(path) {
1984
+ try {
1985
+ const lines = readFileSync5(path, "utf8").split(/\r?\n/);
1986
+ for (const line of lines.slice(0, 2e3)) {
1987
+ if (!line.trim()) continue;
1988
+ try {
1989
+ const entry = JSON.parse(line);
1990
+ if (entry.type !== "message" || entry.message?.role !== "user") continue;
1991
+ const content = entry.message.content;
1992
+ const blocks = typeof content === "string" ? [{ type: "text", text: content }] : Array.isArray(content) ? content.filter(
1993
+ (block) => typeof block === "object" && block !== null && "type" in block && block.type === "text" && "text" in block && typeof block.text === "string"
1994
+ ) : [];
1995
+ const title = promptToSessionTitle(blocks);
1996
+ if (title) return title;
1997
+ } catch {
1998
+ }
1999
+ }
2000
+ } catch {
2001
+ }
2002
+ return null;
2003
+ }
2004
+ function readAtomicSessionTitle(path, tail) {
2005
+ try {
2006
+ const name = pickTitleFromTail(tail ?? readTail(path)) ?? scanSessionInfoNameFromFile(path);
2007
+ return name ?? pickFallbackTitleFromHead(path);
2008
+ } catch {
2009
+ return null;
2010
+ }
2011
+ }
2012
+ function listAtomicSessions(cwd) {
2013
+ const sessionsDir = getAtomicSessionsDir(cwd);
2014
+ const files = [];
2015
+ walkJsonlFiles(sessionsDir, files);
2016
+ const items = [];
2017
+ for (const file of files) {
2018
+ const first = readFirstLine(file);
2019
+ if (!first) continue;
2020
+ const header = parseSessionHeader(first);
2021
+ if (!header) continue;
2022
+ let updatedAt = null;
2023
+ let title = null;
2024
+ try {
2025
+ const tail = readTail(file);
2026
+ title = readAtomicSessionTitle(file, tail);
2027
+ updatedAt = pickUpdatedAtFromTail(tail);
2028
+ } catch {
2029
+ }
2030
+ if (!updatedAt) {
2031
+ try {
2032
+ updatedAt = statSync2(file).mtime.toISOString();
2033
+ } catch {
2034
+ updatedAt = null;
2035
+ }
2036
+ }
2037
+ items.push({
2038
+ sessionId: header.sessionId,
2039
+ cwd: header.cwd,
2040
+ title,
2041
+ updatedAt,
2042
+ sessionFile: file
2043
+ });
2044
+ }
2045
+ items.sort((a, b) => {
2046
+ const aa = a.updatedAt ?? "";
2047
+ const bb = b.updatedAt ?? "";
2048
+ return bb.localeCompare(aa);
2049
+ });
2050
+ return items;
2051
+ }
2052
+ function findAtomicSession(sessionId, cwd) {
2053
+ return listAtomicSessions(cwd).find((s) => s.sessionId === sessionId && (!cwd || s.cwd === cwd)) ?? null;
2054
+ }
2055
+
2056
+ // src/acp/translate/atomic-messages.ts
2057
+ function normalizeAtomicMessageText(content) {
2058
+ if (typeof content === "string") return content;
2059
+ if (!Array.isArray(content)) return "";
2060
+ return content.map((c) => c?.type === "text" && typeof c.text === "string" ? c.text : "").filter(Boolean).join("");
2061
+ }
2062
+ function normalizeAtomicAssistantText(content) {
2063
+ if (!Array.isArray(content)) return "";
2064
+ return content.map((c) => c?.type === "text" && typeof c.text === "string" ? c.text : "").filter(Boolean).join("");
2065
+ }
2066
+
2067
+ // src/acp/atomic-commands.ts
2068
+ function describeFallback(c) {
2069
+ const source = typeof c.source === "string" ? c.source : "";
2070
+ const location = typeof c.location === "string" ? c.location : "";
2071
+ const parts = [];
2072
+ if (source) parts.push(source);
2073
+ if (location) parts.push(location);
2074
+ return parts.length ? `(${parts.join(":")})` : "(command)";
2075
+ }
2076
+ function toAvailableCommandsFromAtomicGetCommands(data, opts) {
2077
+ const enableSkillCommands = opts?.enableSkillCommands ?? true;
2078
+ const includeExtensionCommands = opts?.includeExtensionCommands ?? true;
2079
+ const root = data;
2080
+ const commandsRaw = Array.isArray(root?.commands) ? root.commands : Array.isArray(root?.data?.commands) ? root.data.commands : [];
2081
+ const out = [];
2082
+ for (const c of commandsRaw) {
2083
+ const name = typeof c?.name === "string" ? c.name.trim() : "";
2084
+ if (!name) continue;
2085
+ const source = typeof c?.source === "string" ? c.source : "";
2086
+ if (!includeExtensionCommands && source === "extension") continue;
2087
+ if (!enableSkillCommands && name.startsWith("skill:")) continue;
2088
+ const desc = typeof c?.description === "string" ? c.description.trim() : "";
2089
+ const usage = desc.match(/Usage:\s*\/\S+\s+(.+)$/i)?.[1];
2090
+ out.push({
2091
+ name,
2092
+ description: desc || describeFallback(c),
2093
+ ...usage ? { input: { hint: usage } } : {}
2094
+ });
2095
+ }
2096
+ return { commands: out, raw: commandsRaw };
2097
+ }
2098
+
2099
+ // src/acp/agent.ts
2100
+ import { isAbsolute as isAbsolute2 } from "path";
2101
+ import { existsSync as existsSync4, readFileSync as readFileSync6, realpathSync, readdirSync as readdirSync3, statSync as statSync3, unlinkSync } from "fs";
2102
+ import { join as join5, dirname as dirname2, basename as basename2 } from "path";
2103
+ import { spawnSync } from "child_process";
2104
+ import { fileURLToPath } from "url";
2105
+ var MODEL_CONFIG_ID = "model";
2106
+ var THOUGHT_LEVEL_CONFIG_ID = "thought_level";
2107
+ function builtinAvailableCommands() {
2108
+ return [
2109
+ { name: "workflow-runs", description: "List retained workflow runs", input: { hint: "[status]" } },
2110
+ { name: "workflow-run", description: "Show a workflow run summary", input: { hint: "<runId>" } },
2111
+ {
2112
+ name: "compact",
2113
+ description: "Manually compact the session context",
2114
+ input: { hint: "optional custom instructions" }
2115
+ },
2116
+ {
2117
+ name: "autocompact",
2118
+ description: "Toggle automatic context compaction",
2119
+ input: { hint: "on|off|toggle" }
2120
+ },
2121
+ {
2122
+ name: "export",
2123
+ description: "Export session to an HTML file in the session cwd"
2124
+ },
2125
+ {
2126
+ name: "session",
2127
+ description: "Show session stats (messages, tokens, cost, session file)"
2128
+ },
2129
+ {
2130
+ name: "name",
2131
+ description: "Set session display name",
2132
+ input: { hint: "<name>" }
2133
+ },
2134
+ {
2135
+ name: "steering",
2136
+ description: "Get/set Atomic steering message delivery mode (how queued steering messages are delivered)",
2137
+ input: { hint: "(no args to show) all | one-at-a-time" }
2138
+ },
2139
+ {
2140
+ name: "follow-up",
2141
+ description: "Get/set Atomic follow-up message delivery mode (how queued follow-up messages are delivered)",
2142
+ input: { hint: "(no args to show) all | one-at-a-time" }
2143
+ },
2144
+ {
2145
+ name: "changelog",
2146
+ description: "Show Atomic changelog"
2147
+ }
2148
+ ];
2149
+ }
2150
+ function mergeCommands(a, b) {
2151
+ const out = [];
2152
+ const seen = /* @__PURE__ */ new Set();
2153
+ for (const c of [...a, ...b]) {
2154
+ if (seen.has(c.name)) continue;
2155
+ seen.add(c.name);
2156
+ out.push(c);
2157
+ }
2158
+ return out;
2159
+ }
2160
+ var pkg = readNearestPackageJson(import.meta.url);
2161
+ var AtomicAcpAgent = class {
2162
+ conn;
2163
+ sessions = new SessionManager();
2164
+ store = new SessionStore();
2165
+ sessionOperations = /* @__PURE__ */ new Map();
2166
+ clientElicitationSupport = NO_CLIENT_ELICITATION_SUPPORT;
2167
+ dispose() {
2168
+ this.sessions.disposeAll();
2169
+ }
2170
+ // Remember recent session cwd and use it as the default filter.
2171
+ lastSessionCwd = null;
2172
+ constructor(conn, _config) {
2173
+ this.conn = conn;
2174
+ void _config;
2175
+ }
2176
+ cleanupFailedNewSession(sessionId, state) {
2177
+ this.sessions.close(sessionId);
2178
+ const sessionFile = typeof state?.sessionFile === "string" && state.sessionFile.trim() ? state.sessionFile : this.store.get(sessionId)?.sessionFile;
2179
+ if (typeof sessionFile === "string" && sessionFile.trim()) {
2180
+ try {
2181
+ if (existsSync4(sessionFile)) unlinkSync(sessionFile);
2182
+ } catch {
2183
+ }
2184
+ }
2185
+ this.store.delete(sessionId);
2186
+ }
2187
+ findStoredSession(sessionId, cwd) {
2188
+ const stored = this.store.get(sessionId);
2189
+ if (stored?.cwd && stored.sessionFile && (!cwd || stored.cwd === cwd)) return stored;
2190
+ const discovered = findAtomicSession(sessionId, cwd);
2191
+ if (!discovered) return null;
2192
+ this.store.upsert({ sessionId, cwd: discovered.cwd, sessionFile: discovered.sessionFile });
2193
+ return discovered;
2194
+ }
2195
+ async withSessionOperation(sessionId, operation) {
2196
+ const previous = this.sessionOperations.get(sessionId) ?? Promise.resolve();
2197
+ const result = previous.then(operation);
2198
+ const settled = result.then(
2199
+ () => {
2200
+ },
2201
+ () => {
2202
+ }
2203
+ );
2204
+ this.sessionOperations.set(sessionId, settled);
2205
+ try {
2206
+ return await result;
2207
+ } finally {
2208
+ if (this.sessionOperations.get(sessionId) === settled) this.sessionOperations.delete(sessionId);
2209
+ }
2210
+ }
2211
+ restoreSession(sessionId) {
2212
+ return this.withSessionOperation(sessionId, () => this.restoreSessionImpl(sessionId));
2213
+ }
2214
+ async restoreSessionImpl(sessionId, opts) {
2215
+ const existing = this.sessions.maybeGet(sessionId);
2216
+ if (existing) {
2217
+ if (opts?.cwd && existing.cwd !== opts.cwd) throw RequestError3.invalidParams(`Unknown sessionId: ${sessionId}`);
2218
+ return existing;
2219
+ }
2220
+ const stored = this.findStoredSession(sessionId, opts?.cwd);
2221
+ if (!stored) throw RequestError3.invalidParams(`Unknown sessionId: ${sessionId}`);
2222
+ const cwd = opts?.cwd ?? stored.cwd;
2223
+ let proc;
2224
+ try {
2225
+ proc = await AtomicRpcProcess.spawn({
2226
+ cwd,
2227
+ sessionPath: stored.sessionFile,
2228
+ atomicCommand: process.env.ATOMIC_ACP_ATOMIC_COMMAND
2229
+ });
2230
+ } catch (error) {
2231
+ if (error instanceof AtomicRpcSpawnError) throw RequestError3.internalError({ code: error.code }, error.message);
2232
+ throw error;
2233
+ }
2234
+ try {
2235
+ const session = this.sessions.getOrCreate(sessionId, {
2236
+ cwd,
2237
+ mcpServers: opts?.mcpServers ?? [],
2238
+ conn: this.conn,
2239
+ proc,
2240
+ fileCommands: loadSlashCommands(cwd),
2241
+ clientElicitationSupport: this.clientElicitationSupport
2242
+ });
2243
+ this.lastSessionCwd = cwd;
2244
+ this.store.upsert({ sessionId, cwd, sessionFile: stored.sessionFile });
2245
+ const title = readAtomicSessionTitle(stored.sessionFile);
2246
+ if (!opts?.deferTitle && title !== null) await session.publishTitle(title || null, null);
2247
+ return session;
2248
+ } catch (error) {
2249
+ if (this.sessions.maybeGet(sessionId)?.proc === proc) this.sessions.close(sessionId);
2250
+ else proc.dispose();
2251
+ throw error;
2252
+ }
2253
+ }
2254
+ async initialize(params) {
2255
+ this.clientElicitationSupport = readClientElicitationSupport(params);
2256
+ const supportedVersion = 1;
2257
+ const requested = params.protocolVersion;
2258
+ return {
2259
+ protocolVersion: requested === supportedVersion ? requested : supportedVersion,
2260
+ agentInfo: {
2261
+ name: pkg.name ?? "atomic-acp",
2262
+ title: "Atomic ACP adapter",
2263
+ version: pkg.version ?? "0.0.0"
2264
+ },
2265
+ // Zed currently uses ClientCapabilities._meta["terminal-auth"] to decide whether to show
2266
+ // the "Authenticate" banner/button. If not supported, we still return the method for the registry.
2267
+ authMethods: getAuthMethods({
2268
+ supportsTerminalAuthMeta: params?.clientCapabilities?._meta?.["terminal-auth"] === true
2269
+ }),
2270
+ agentCapabilities: {
2271
+ loadSession: true,
2272
+ mcpCapabilities: { http: false, sse: false },
2273
+ promptCapabilities: {
2274
+ image: true,
2275
+ audio: false,
2276
+ embeddedContext: process.env.ATOMIC_ACP_ENABLE_EMBEDDED_CONTEXT === "true"
2277
+ },
2278
+ sessionCapabilities: {
2279
+ list: {},
2280
+ delete: {}
2281
+ }
2282
+ }
2283
+ };
2284
+ }
2285
+ async newSession(params) {
2286
+ if (!isAbsolute2(params.cwd)) {
2287
+ throw RequestError3.invalidParams(`cwd must be an absolute path: ${params.cwd}`);
2288
+ }
2289
+ this.lastSessionCwd = params.cwd;
2290
+ const fileCommands = loadSlashCommands(params.cwd);
2291
+ const enableSkillCommands = getEnableSkillCommands(params.cwd);
2292
+ const session = await this.sessions.create({
2293
+ cwd: params.cwd,
2294
+ mcpServers: params.mcpServers,
2295
+ conn: this.conn,
2296
+ fileCommands,
2297
+ atomicCommand: process.env.ATOMIC_ACP_ATOMIC_COMMAND,
2298
+ clientElicitationSupport: this.clientElicitationSupport
2299
+ });
2300
+ let state = null;
2301
+ let availableModels = null;
2302
+ let atomicCommands = null;
2303
+ let stateErr = null;
2304
+ let availableModelsErr = null;
2305
+ let atomicCommandsErr = null;
2306
+ await Promise.all([
2307
+ session.proc.getState().then((s) => {
2308
+ state = s;
2309
+ }).catch((err) => {
2310
+ stateErr = err;
2311
+ state = null;
2312
+ }),
2313
+ session.proc.getAvailableModels().then((m) => {
2314
+ availableModels = m;
2315
+ }).catch((err) => {
2316
+ availableModelsErr = err;
2317
+ availableModels = null;
2318
+ }),
2319
+ typeof session.proc.getCommands === "function" ? session.proc.getCommands().then((c) => {
2320
+ atomicCommands = c;
2321
+ }).catch((err) => {
2322
+ atomicCommandsErr = err;
2323
+ atomicCommands = null;
2324
+ }) : Promise.resolve()
2325
+ ]);
2326
+ const availableModelsAuthErr = maybeAuthRequiredError(availableModelsErr);
2327
+ if (availableModelsAuthErr) {
2328
+ this.cleanupFailedNewSession(session.sessionId, state);
2329
+ throw availableModelsAuthErr;
2330
+ }
2331
+ if (availableModelsErr) {
2332
+ this.cleanupFailedNewSession(session.sessionId, state);
2333
+ throw RequestError3.internalError({}, String(availableModelsErr?.message ?? availableModelsErr));
2334
+ }
2335
+ const rawModelsCount = Array.isArray(availableModels?.models) ? availableModels.models.length : 0;
2336
+ if (rawModelsCount === 0) {
2337
+ this.cleanupFailedNewSession(session.sessionId, state);
2338
+ throw RequestError3.authRequired(
2339
+ { authMethods: getAuthMethods() },
2340
+ "Configure an API key or log in with an OAuth provider."
2341
+ );
2342
+ }
2343
+ if (stateErr && maybeAuthRequiredError(stateErr)) {
2344
+ this.cleanupFailedNewSession(session.sessionId, state);
2345
+ throw RequestError3.authRequired(
2346
+ { authMethods: getAuthMethods() },
2347
+ "Configure an API key or log in with an OAuth provider."
2348
+ );
2349
+ }
2350
+ if (!atomicCommandsErr && atomicCommands) {
2351
+ session.setFileCommands(loadSlashCommandsFromAtomicGetCommands(atomicCommands));
2352
+ }
2353
+ let configuration;
2354
+ try {
2355
+ if (stateErr) throw stateErr;
2356
+ configuration = await getSessionConfiguration(session.proc, { state, availableModels });
2357
+ } catch (err) {
2358
+ this.cleanupFailedNewSession(session.sessionId, state);
2359
+ throw maybeAuthRequiredError(err) ?? RequestError3.internalError({}, String(err));
2360
+ }
2361
+ const { configOptions, models, modes } = configuration;
2362
+ const quietStartup = getQuietStartup(params.cwd);
2363
+ const updateNotice = buildUpdateNotice();
2364
+ const preludeText = quietStartup ? updateNotice ? updateNotice + "\n" : "" : buildStartupInfo({
2365
+ cwd: params.cwd,
2366
+ fileCommands,
2367
+ updateNotice
2368
+ });
2369
+ if (preludeText)
2370
+ session.setStartupInfo(preludeText);
2371
+ this.sessions.closeAllExcept?.(session.sessionId);
2372
+ const response = {
2373
+ sessionId: session.sessionId,
2374
+ configOptions,
2375
+ models,
2376
+ modes,
2377
+ _meta: {
2378
+ atomicAcp: {
2379
+ startupInfo: preludeText || null
2380
+ }
2381
+ }
2382
+ };
2383
+ if (preludeText) setTimeout(() => session.sendStartupInfoIfPending(), 0);
2384
+ setTimeout(() => {
2385
+ void (async () => {
2386
+ await session.publishContextUsage();
2387
+ try {
2388
+ if (atomicCommandsErr || !atomicCommands) throw atomicCommandsErr;
2389
+ const { commands } = toAvailableCommandsFromAtomicGetCommands(atomicCommands, {
2390
+ enableSkillCommands,
2391
+ includeExtensionCommands: true
2392
+ });
2393
+ await this.conn.sessionUpdate({
2394
+ sessionId: session.sessionId,
2395
+ update: {
2396
+ sessionUpdate: "available_commands_update",
2397
+ availableCommands: mergeCommands(builtinAvailableCommands(), commands)
2398
+ }
2399
+ });
2400
+ return;
2401
+ } catch {
2402
+ }
2403
+ await this.conn.sessionUpdate({
2404
+ sessionId: session.sessionId,
2405
+ update: {
2406
+ sessionUpdate: "available_commands_update",
2407
+ availableCommands: mergeCommands(builtinAvailableCommands(), toAvailableCommands(fileCommands))
2408
+ }
2409
+ });
2410
+ })();
2411
+ }, 0);
2412
+ return response;
2413
+ }
2414
+ async authenticate(_params) {
2415
+ return;
2416
+ }
2417
+ async prompt(params) {
2418
+ const session = await this.restoreSession(params.sessionId);
2419
+ const { message, images } = promptToAtomicMessage(params.prompt);
2420
+ if (images.length === 0 && message.trimStart().startsWith("/")) {
2421
+ const trimmed = message.trim();
2422
+ const space = trimmed.indexOf(" ");
2423
+ const cmd = space === -1 ? trimmed.slice(1) : trimmed.slice(1, space);
2424
+ const argsString = space === -1 ? "" : trimmed.slice(space + 1);
2425
+ const args = parseCommandArgs(argsString);
2426
+ if (cmd === "workflow-runs" || cmd === "workflow-run") {
2427
+ let text;
2428
+ if (args.length > 1 || cmd === "workflow-run" && !args[0]) {
2429
+ text = cmd === "workflow-run" ? "Usage: /workflow-run <runId>" : "Usage: /workflow-runs [status]";
2430
+ } else {
2431
+ try {
2432
+ const data = cmd === "workflow-runs" ? await session.proc.listWorkflowRuns(args[0]) : await session.proc.getWorkflowRunSummary(args[0]);
2433
+ text = renderWorkflowHistory(data, cmd === "workflow-runs");
2434
+ } catch (error) {
2435
+ text = `Could not read workflow history: ${error instanceof Error ? error.message : String(error)}`;
2436
+ }
2437
+ }
2438
+ await this.conn.sessionUpdate({
2439
+ sessionId: session.sessionId,
2440
+ update: {
2441
+ sessionUpdate: "agent_message_chunk",
2442
+ content: { type: "text", text }
2443
+ }
2444
+ });
2445
+ return { stopReason: "end_turn" };
2446
+ }
2447
+ if (cmd === "compact") {
2448
+ const customInstructions = args.join(" ").trim() || void 0;
2449
+ const res = await session.proc.compact(customInstructions);
2450
+ const r = res && typeof res === "object" ? res : null;
2451
+ const tokensBefore = typeof r?.tokensBefore === "number" ? r.tokensBefore : null;
2452
+ const summary = typeof r?.summary === "string" ? r.summary : null;
2453
+ const headerLines = [
2454
+ `Compaction completed.${customInstructions ? " (custom instructions applied)" : ""}`,
2455
+ tokensBefore !== null ? `Tokens before: ${tokensBefore}` : null
2456
+ ].filter(Boolean);
2457
+ const text = headerLines.join("\n") + (summary ? `
2458
+
2459
+ ${summary}` : "");
2460
+ await this.conn.sessionUpdate({
2461
+ sessionId: session.sessionId,
2462
+ update: {
2463
+ sessionUpdate: "agent_message_chunk",
2464
+ content: { type: "text", text }
2465
+ }
2466
+ });
2467
+ return { stopReason: "end_turn" };
2468
+ }
2469
+ if (cmd === "session") {
2470
+ const stats = await session.proc.getSessionStats();
2471
+ const lines = [];
2472
+ if (stats?.sessionId) lines.push(`Session: ${stats.sessionId}`);
2473
+ if (stats?.sessionFile) lines.push(`Session file: ${stats.sessionFile}`);
2474
+ if (typeof stats?.totalMessages === "number") lines.push(`Messages: ${stats.totalMessages}`);
2475
+ if (typeof stats?.cost === "number") lines.push(`Cost: ${stats.cost}`);
2476
+ const t = stats?.tokens;
2477
+ if (t && typeof t === "object") {
2478
+ const parts = [];
2479
+ if (typeof t.input === "number") parts.push(`in ${t.input}`);
2480
+ if (typeof t.output === "number") parts.push(`out ${t.output}`);
2481
+ if (typeof t.cacheRead === "number") parts.push(`cache read ${t.cacheRead}`);
2482
+ if (typeof t.cacheWrite === "number") parts.push(`cache write ${t.cacheWrite}`);
2483
+ if (typeof t.total === "number") parts.push(`total ${t.total}`);
2484
+ if (parts.length) lines.push(`Tokens: ${parts.join(", ")}`);
2485
+ }
2486
+ const text = lines.length ? lines.join("\n") : `Session stats:
2487
+ ${JSON.stringify(stats, null, 2)}`;
2488
+ await this.conn.sessionUpdate({
2489
+ sessionId: session.sessionId,
2490
+ update: {
2491
+ sessionUpdate: "agent_message_chunk",
2492
+ content: { type: "text", text }
2493
+ }
2494
+ });
2495
+ return { stopReason: "end_turn" };
2496
+ }
2497
+ if (cmd === "name") {
2498
+ const name = args.join(" ").trim();
2499
+ if (!name) {
2500
+ await this.conn.sessionUpdate({
2501
+ sessionId: session.sessionId,
2502
+ update: {
2503
+ sessionUpdate: "agent_message_chunk",
2504
+ content: { type: "text", text: "Usage: /name <name>" }
2505
+ }
2506
+ });
2507
+ return { stopReason: "end_turn" };
2508
+ }
2509
+ try {
2510
+ await session.setSessionName(name);
2511
+ } catch (e) {
2512
+ const msg = String(e?.message ?? e);
2513
+ const hint = /set_session_name/i.test(msg) ? " This requires a newer Atomic version that supports `set_session_name` in RPC mode." : "";
2514
+ await this.conn.sessionUpdate({
2515
+ sessionId: session.sessionId,
2516
+ update: {
2517
+ sessionUpdate: "agent_message_chunk",
2518
+ content: { type: "text", text: `Failed to set session name: ${msg}${hint}` }
2519
+ }
2520
+ });
2521
+ return { stopReason: "end_turn" };
2522
+ }
2523
+ await this.conn.sessionUpdate({
2524
+ sessionId: session.sessionId,
2525
+ update: {
2526
+ sessionUpdate: "agent_message_chunk",
2527
+ content: { type: "text", text: `Session name set: ${name}` }
2528
+ }
2529
+ });
2530
+ return { stopReason: "end_turn" };
2531
+ }
2532
+ if (cmd === "steering") {
2533
+ const modeRaw = String(args[0] ?? "").toLowerCase();
2534
+ const state = await session.proc.getState();
2535
+ const current = String(state?.steeringMode ?? "");
2536
+ if (!modeRaw) {
2537
+ await this.conn.sessionUpdate({
2538
+ sessionId: session.sessionId,
2539
+ update: {
2540
+ sessionUpdate: "agent_message_chunk",
2541
+ content: {
2542
+ type: "text",
2543
+ text: `Steering mode: ${current || "unknown"}`
2544
+ }
2545
+ }
2546
+ });
2547
+ return { stopReason: "end_turn" };
2548
+ }
2549
+ if (modeRaw !== "all" && modeRaw !== "one-at-a-time") {
2550
+ await this.conn.sessionUpdate({
2551
+ sessionId: session.sessionId,
2552
+ update: {
2553
+ sessionUpdate: "agent_message_chunk",
2554
+ content: {
2555
+ type: "text",
2556
+ text: "Usage: /steering all | /steering one-at-a-time"
2557
+ }
2558
+ }
2559
+ });
2560
+ return { stopReason: "end_turn" };
2561
+ }
2562
+ await session.proc.setSteeringMode(modeRaw);
2563
+ await this.conn.sessionUpdate({
2564
+ sessionId: session.sessionId,
2565
+ update: {
2566
+ sessionUpdate: "agent_message_chunk",
2567
+ content: { type: "text", text: `Steering mode set to: ${modeRaw}` }
2568
+ }
2569
+ });
2570
+ return { stopReason: "end_turn" };
2571
+ }
2572
+ if (cmd === "follow-up") {
2573
+ const modeRaw = String(args[0] ?? "").toLowerCase();
2574
+ const state = await session.proc.getState();
2575
+ const current = String(state?.followUpMode ?? "");
2576
+ if (!modeRaw) {
2577
+ await this.conn.sessionUpdate({
2578
+ sessionId: session.sessionId,
2579
+ update: {
2580
+ sessionUpdate: "agent_message_chunk",
2581
+ content: {
2582
+ type: "text",
2583
+ text: `Follow-up mode: ${current || "unknown"}`
2584
+ }
2585
+ }
2586
+ });
2587
+ return { stopReason: "end_turn" };
2588
+ }
2589
+ if (modeRaw !== "all" && modeRaw !== "one-at-a-time") {
2590
+ await this.conn.sessionUpdate({
2591
+ sessionId: session.sessionId,
2592
+ update: {
2593
+ sessionUpdate: "agent_message_chunk",
2594
+ content: {
2595
+ type: "text",
2596
+ text: "Usage: /follow-up all | /follow-up one-at-a-time"
2597
+ }
2598
+ }
2599
+ });
2600
+ return { stopReason: "end_turn" };
2601
+ }
2602
+ await session.proc.setFollowUpMode(modeRaw);
2603
+ await this.conn.sessionUpdate({
2604
+ sessionId: session.sessionId,
2605
+ update: {
2606
+ sessionUpdate: "agent_message_chunk",
2607
+ content: { type: "text", text: `Follow-up mode set to: ${modeRaw}` }
2608
+ }
2609
+ });
2610
+ return { stopReason: "end_turn" };
2611
+ }
2612
+ if (cmd === "changelog") {
2613
+ const findChangelog = () => {
2614
+ try {
2615
+ const atomicPath = resolveAtomicExecutablePath();
2616
+ if (atomicPath) {
2617
+ const resolved = realpathSync(atomicPath);
2618
+ const pkgRoot = dirname2(dirname2(resolved));
2619
+ const p = join5(pkgRoot, "CHANGELOG.md");
2620
+ if (existsSync4(p)) return p;
2621
+ }
2622
+ } catch {
2623
+ }
2624
+ try {
2625
+ const npmRoot = spawnSync("npm", ["root", "-g"], { encoding: "utf-8" });
2626
+ const root = String(npmRoot.stdout ?? "").trim();
2627
+ if (root) {
2628
+ const p = join5(root, "@bastani", "atomic", "CHANGELOG.md");
2629
+ if (existsSync4(p)) return p;
2630
+ }
2631
+ } catch {
2632
+ }
2633
+ return null;
2634
+ };
2635
+ const changelogPath = findChangelog();
2636
+ if (!changelogPath) {
2637
+ await this.conn.sessionUpdate({
2638
+ sessionId: session.sessionId,
2639
+ update: {
2640
+ sessionUpdate: "agent_message_chunk",
2641
+ content: { type: "text", text: "Changelog not found (couldn't locate Atomic installation)." }
2642
+ }
2643
+ });
2644
+ return { stopReason: "end_turn" };
2645
+ }
2646
+ let text = "";
2647
+ try {
2648
+ text = readFileSync6(changelogPath, "utf-8");
2649
+ } catch (e) {
2650
+ await this.conn.sessionUpdate({
2651
+ sessionId: session.sessionId,
2652
+ update: {
2653
+ sessionUpdate: "agent_message_chunk",
2654
+ content: { type: "text", text: `Failed to read changelog: ${String(e?.message ?? e)}` }
2655
+ }
2656
+ });
2657
+ return { stopReason: "end_turn" };
2658
+ }
2659
+ const maxChars = 2e4;
2660
+ if (text.length > maxChars) text = text.slice(0, maxChars) + "\n\n...(truncated)...";
2661
+ await this.conn.sessionUpdate({
2662
+ sessionId: session.sessionId,
2663
+ update: {
2664
+ sessionUpdate: "agent_message_chunk",
2665
+ content: { type: "text", text }
2666
+ }
2667
+ });
2668
+ return { stopReason: "end_turn" };
2669
+ }
2670
+ if (cmd === "export") {
2671
+ const state = await session.proc.getState();
2672
+ const sessionFile = typeof state?.sessionFile === "string" ? state.sessionFile : null;
2673
+ const messageCount = typeof state?.messageCount === "number" ? state.messageCount : 0;
2674
+ if (!sessionFile || messageCount === 0 || !existsSync4(sessionFile)) {
2675
+ await this.conn.sessionUpdate({
2676
+ sessionId: session.sessionId,
2677
+ update: {
2678
+ sessionUpdate: "agent_message_chunk",
2679
+ content: {
2680
+ type: "text",
2681
+ text: "Nothing to export yet (no session messages). Send a prompt first."
2682
+ }
2683
+ }
2684
+ });
2685
+ return { stopReason: "end_turn" };
2686
+ }
2687
+ try {
2688
+ const raw = readFileSync6(sessionFile, "utf-8");
2689
+ if (raw.trim().length === 0) {
2690
+ await this.conn.sessionUpdate({
2691
+ sessionId: session.sessionId,
2692
+ update: {
2693
+ sessionUpdate: "agent_message_chunk",
2694
+ content: {
2695
+ type: "text",
2696
+ text: "Nothing to export yet (empty session file). Send a prompt first."
2697
+ }
2698
+ }
2699
+ });
2700
+ return { stopReason: "end_turn" };
2701
+ }
2702
+ } catch {
2703
+ await this.conn.sessionUpdate({
2704
+ sessionId: session.sessionId,
2705
+ update: {
2706
+ sessionUpdate: "agent_message_chunk",
2707
+ content: {
2708
+ type: "text",
2709
+ text: "Couldn't read session file for export. Try sending a prompt first."
2710
+ }
2711
+ }
2712
+ });
2713
+ return { stopReason: "end_turn" };
2714
+ }
2715
+ const safeSessionId = session.sessionId.replace(/[^a-zA-Z0-9_-]/g, "_");
2716
+ const outputPath = join5(session.cwd, `atomic-session-${safeSessionId}.html`);
2717
+ let resultPath = "";
2718
+ try {
2719
+ const result2 = await session.proc.exportHtml(outputPath);
2720
+ resultPath = result2.path;
2721
+ } catch (e) {
2722
+ await this.conn.sessionUpdate({
2723
+ sessionId: session.sessionId,
2724
+ update: {
2725
+ sessionUpdate: "agent_message_chunk",
2726
+ content: {
2727
+ type: "text",
2728
+ text: `Export failed: ${String(e?.message ?? e)}`
2729
+ }
2730
+ }
2731
+ });
2732
+ return { stopReason: "end_turn" };
2733
+ }
2734
+ if (!resultPath) {
2735
+ await this.conn.sessionUpdate({
2736
+ sessionId: session.sessionId,
2737
+ update: {
2738
+ sessionUpdate: "agent_message_chunk",
2739
+ content: {
2740
+ type: "text",
2741
+ text: "Export failed: no output path returned by Atomic."
2742
+ }
2743
+ }
2744
+ });
2745
+ return { stopReason: "end_turn" };
2746
+ }
2747
+ const uri = `file://${resultPath}`;
2748
+ await this.conn.sessionUpdate({
2749
+ sessionId: session.sessionId,
2750
+ update: {
2751
+ sessionUpdate: "agent_message_chunk",
2752
+ content: {
2753
+ type: "text",
2754
+ text: "Session exported: "
2755
+ }
2756
+ }
2757
+ });
2758
+ await this.conn.sessionUpdate({
2759
+ sessionId: session.sessionId,
2760
+ update: {
2761
+ sessionUpdate: "agent_message_chunk",
2762
+ content: {
2763
+ type: "resource_link",
2764
+ name: `atomic-session-${safeSessionId}.html`,
2765
+ uri,
2766
+ mimeType: "text/html",
2767
+ title: "Session exported"
2768
+ }
2769
+ }
2770
+ });
2771
+ return { stopReason: "end_turn" };
2772
+ }
2773
+ if (cmd === "autocompact") {
2774
+ const mode = (args[0] ?? "toggle").toLowerCase();
2775
+ let enabled = null;
2776
+ if (mode === "on" || mode === "true" || mode === "enable" || mode === "enabled") enabled = true;
2777
+ else if (mode === "off" || mode === "false" || mode === "disable" || mode === "disabled") enabled = false;
2778
+ if (enabled === null) {
2779
+ const state = await session.proc.getState();
2780
+ const current = Boolean(state?.autoCompactionEnabled);
2781
+ enabled = !current;
2782
+ }
2783
+ await session.proc.setAutoCompaction(enabled);
2784
+ await this.conn.sessionUpdate({
2785
+ sessionId: session.sessionId,
2786
+ update: {
2787
+ sessionUpdate: "agent_message_chunk",
2788
+ content: {
2789
+ type: "text",
2790
+ text: `Auto-compaction ${enabled ? "enabled" : "disabled"}.`
2791
+ }
2792
+ }
2793
+ });
2794
+ return { stopReason: "end_turn" };
2795
+ }
2796
+ }
2797
+ const result = await session.prompt(message, images, promptToSessionTitle(params.prompt) ?? void 0);
2798
+ const stopReason = result === "error" ? session.wasCancelRequested() ? "cancelled" : "end_turn" : result;
2799
+ return { stopReason };
2800
+ }
2801
+ async cancel(params) {
2802
+ const session = this.sessions.maybeGet(params.sessionId);
2803
+ if (!session) return;
2804
+ await session.cancel();
2805
+ }
2806
+ async listSessions(params) {
2807
+ return this.listSessionsImpl(params);
2808
+ }
2809
+ async unstable_listSessions(params) {
2810
+ return this.listSessionsImpl(params);
2811
+ }
2812
+ async listSessionsImpl(params) {
2813
+ const effectiveCwd = params.cwd ?? this.lastSessionCwd;
2814
+ const all = listAtomicSessions(effectiveCwd ?? void 0);
2815
+ const filtered = effectiveCwd ? all.filter((s) => s.cwd === effectiveCwd) : all;
2816
+ const offset = params.cursor ? Number.parseInt(params.cursor, 10) : 0;
2817
+ const start = Number.isFinite(offset) && offset > 0 ? offset : 0;
2818
+ const PAGE_SIZE = 50;
2819
+ const page = filtered.slice(start, start + PAGE_SIZE);
2820
+ const sessions = page.map((s) => ({
2821
+ sessionId: s.sessionId,
2822
+ cwd: s.cwd,
2823
+ title: s.title,
2824
+ updatedAt: s.updatedAt
2825
+ }));
2826
+ const nextCursor = start + PAGE_SIZE < filtered.length ? String(start + PAGE_SIZE) : null;
2827
+ return { sessions, nextCursor, _meta: {} };
2828
+ }
2829
+ async loadSession(params) {
2830
+ return this.withSessionOperation(params.sessionId, () => this.loadSessionImpl(params));
2831
+ }
2832
+ async loadSessionImpl(params) {
2833
+ if (!isAbsolute2(params.cwd)) {
2834
+ throw RequestError3.invalidParams(`cwd must be an absolute path: ${params.cwd}`);
2835
+ }
2836
+ this.lastSessionCwd = params.cwd;
2837
+ const session = await this.restoreSessionImpl(params.sessionId, {
2838
+ cwd: params.cwd,
2839
+ mcpServers: params.mcpServers,
2840
+ deferTitle: true
2841
+ });
2842
+ const proc = session.proc;
2843
+ const fileCommands = loadSlashCommands(params.cwd);
2844
+ const enableSkillCommands = getEnableSkillCommands(params.cwd);
2845
+ let atomicCommands = null;
2846
+ let atomicCommandsErr = null;
2847
+ let state = null;
2848
+ let configuration;
2849
+ try {
2850
+ state = await proc.getState();
2851
+ configuration = await getSessionConfiguration(proc, { state });
2852
+ } catch (err) {
2853
+ this.sessions.close(params.sessionId);
2854
+ throw err;
2855
+ }
2856
+ const { configOptions, models, modes } = configuration;
2857
+ const stored = this.store.get(params.sessionId);
2858
+ const title = stored?.sessionFile ? readAtomicSessionTitle(stored.sessionFile) : null;
2859
+ if (title !== null) await session.publishTitle(title || null, null);
2860
+ try {
2861
+ if (typeof proc.getCommands === "function") atomicCommands = await proc.getCommands();
2862
+ } catch (err) {
2863
+ atomicCommandsErr = err;
2864
+ }
2865
+ session.setFileCommands(atomicCommands ? loadSlashCommandsFromAtomicGetCommands(atomicCommands) : fileCommands);
2866
+ this.sessions.closeAllExcept?.(session.sessionId);
2867
+ const data = await proc.getMessages();
2868
+ const messages = Array.isArray(data?.messages) ? data.messages : [];
2869
+ for (const m of messages) {
2870
+ const role = String(m?.role ?? "");
2871
+ if (role === "user") {
2872
+ const text = normalizeAtomicMessageText(m?.content);
2873
+ if (text) {
2874
+ await this.conn.sessionUpdate({
2875
+ sessionId: session.sessionId,
2876
+ update: {
2877
+ sessionUpdate: "user_message_chunk",
2878
+ content: { type: "text", text }
2879
+ }
2880
+ });
2881
+ }
2882
+ }
2883
+ if (role === "assistant") {
2884
+ const text = normalizeAtomicAssistantText(m?.content);
2885
+ if (text) {
2886
+ await this.conn.sessionUpdate({
2887
+ sessionId: session.sessionId,
2888
+ update: {
2889
+ sessionUpdate: "agent_message_chunk",
2890
+ content: { type: "text", text }
2891
+ }
2892
+ });
2893
+ }
2894
+ }
2895
+ if (role === "toolResult") {
2896
+ const toolName = String(m?.toolName ?? "tool");
2897
+ const toolCallId = String(m?.toolCallId ?? crypto.randomUUID());
2898
+ const isError = Boolean(m?.isError);
2899
+ if (isBashTool(toolName)) {
2900
+ const text2 = bashResultText(m);
2901
+ await this.conn.sessionUpdate({
2902
+ sessionId: session.sessionId,
2903
+ update: {
2904
+ sessionUpdate: "tool_call",
2905
+ toolCallId,
2906
+ title: bashCommand(m) ?? toolName,
2907
+ kind: "execute",
2908
+ status: "in_progress",
2909
+ content: bashTerminalContent(toolCallId),
2910
+ _meta: bashTerminalInfoMeta(toolCallId, params.cwd)
2911
+ }
2912
+ });
2913
+ await this.conn.sessionUpdate({
2914
+ sessionId: session.sessionId,
2915
+ update: {
2916
+ sessionUpdate: "tool_call_update",
2917
+ toolCallId,
2918
+ status: isError ? "failed" : "completed",
2919
+ _meta: {
2920
+ ...text2 ? bashTerminalOutputMeta(toolCallId, text2) : {},
2921
+ ...bashTerminalExitMeta(toolCallId, bashExitCode(m, isError))
2922
+ }
2923
+ }
2924
+ });
2925
+ continue;
2926
+ }
2927
+ await this.conn.sessionUpdate({
2928
+ sessionId: session.sessionId,
2929
+ update: {
2930
+ sessionUpdate: "tool_call",
2931
+ toolCallId,
2932
+ title: toolName,
2933
+ kind: toolName === "read" ? "read" : toolName === "write" || toolName === "edit" ? "edit" : "other",
2934
+ status: "completed",
2935
+ rawInput: null,
2936
+ rawOutput: m
2937
+ }
2938
+ });
2939
+ const text = toolResultToText(m);
2940
+ await this.conn.sessionUpdate({
2941
+ sessionId: session.sessionId,
2942
+ update: {
2943
+ sessionUpdate: "tool_call_update",
2944
+ toolCallId,
2945
+ status: isError ? "failed" : "completed",
2946
+ content: text ? [{ type: "content", content: { type: "text", text } }] : null,
2947
+ rawOutput: m
2948
+ }
2949
+ });
2950
+ }
2951
+ }
2952
+ const response = {
2953
+ configOptions,
2954
+ models,
2955
+ modes,
2956
+ _meta: {
2957
+ atomicAcp: {
2958
+ startupInfo: null
2959
+ }
2960
+ }
2961
+ };
2962
+ setTimeout(() => {
2963
+ void (async () => {
2964
+ await session.publishContextUsage();
2965
+ try {
2966
+ if (atomicCommandsErr || !atomicCommands) throw atomicCommandsErr;
2967
+ const { commands } = toAvailableCommandsFromAtomicGetCommands(atomicCommands, {
2968
+ enableSkillCommands,
2969
+ includeExtensionCommands: true
2970
+ });
2971
+ await this.conn.sessionUpdate({
2972
+ sessionId: session.sessionId,
2973
+ update: {
2974
+ sessionUpdate: "available_commands_update",
2975
+ availableCommands: mergeCommands(builtinAvailableCommands(), commands)
2976
+ }
2977
+ });
2978
+ return;
2979
+ } catch {
2980
+ }
2981
+ await this.conn.sessionUpdate({
2982
+ sessionId: session.sessionId,
2983
+ update: {
2984
+ sessionUpdate: "available_commands_update",
2985
+ availableCommands: mergeCommands(builtinAvailableCommands(), toAvailableCommands(fileCommands))
2986
+ }
2987
+ });
2988
+ })();
2989
+ }, 0);
2990
+ return response;
2991
+ }
2992
+ async deleteSession(params) {
2993
+ return this.withSessionOperation(params.sessionId, () => this.deleteSessionImpl(params));
2994
+ }
2995
+ async deleteSessionImpl(params) {
2996
+ const stored = this.store.get(params.sessionId);
2997
+ const discovered = findAtomicSession(params.sessionId);
2998
+ const sessionFile = stored?.sessionFile ?? discovered?.sessionFile;
2999
+ this.sessions.close(params.sessionId);
3000
+ if (sessionFile) {
3001
+ try {
3002
+ unlinkSync(sessionFile);
3003
+ } catch (error) {
3004
+ if (error.code !== "ENOENT") throw error;
3005
+ }
3006
+ }
3007
+ this.store.delete(params.sessionId);
3008
+ return {};
3009
+ }
3010
+ async unstable_setSessionModel(params) {
3011
+ const session = await this.restoreSession(params.sessionId);
3012
+ await setSessionModel(session.proc, params.modelId);
3013
+ await emitConfigOptionsUpdate(this.conn, session.sessionId, session.proc);
3014
+ await session.publishContextUsage();
3015
+ }
3016
+ async setSessionMode(params) {
3017
+ const session = await this.restoreSession(params.sessionId);
3018
+ if (typeof params.modeId !== "string" || params.modeId.length === 0) {
3019
+ throw RequestError3.invalidParams("Expected nonempty string modeId");
3020
+ }
3021
+ await session.proc.setThinkingLevel(params.modeId);
3022
+ await emitConfigOptionsUpdate(this.conn, session.sessionId, session.proc);
3023
+ return {};
3024
+ }
3025
+ async setSessionConfigOption(params) {
3026
+ const session = await this.restoreSession(params.sessionId);
3027
+ if (typeof params.value !== "string") {
3028
+ throw RequestError3.invalidParams(`Expected string value for config option: ${params.configId}`);
3029
+ }
3030
+ if (params.configId === MODEL_CONFIG_ID) {
3031
+ await setSessionModel(session.proc, params.value);
3032
+ } else if (params.configId === THOUGHT_LEVEL_CONFIG_ID) {
3033
+ if (params.value.length === 0) throw RequestError3.invalidParams("Expected nonempty thinking level");
3034
+ await session.proc.setThinkingLevel(params.value);
3035
+ } else {
3036
+ throw RequestError3.invalidParams(`Unknown config option: ${params.configId}`);
3037
+ }
3038
+ const configOptions = await emitConfigOptionsUpdate(this.conn, session.sessionId, session.proc);
3039
+ if (params.configId === MODEL_CONFIG_ID) await session.publishContextUsage();
3040
+ return { configOptions };
3041
+ }
3042
+ };
3043
+ async function getThinkingState(proc, pre) {
3044
+ const state = pre?.state ?? await proc.getState();
3045
+ const available = await proc.getAvailableThinkingLevels();
3046
+ const current = state && typeof state === "object" && "thinkingLevel" in state ? state.thinkingLevel : void 0;
3047
+ if (typeof current !== "string" || current.length === 0 || !available.includes(current)) {
3048
+ throw new Error("Atomic returned a thinking level absent from available levels");
3049
+ }
3050
+ return {
3051
+ currentModeId: current,
3052
+ availableModes: available.map((id) => ({
3053
+ id,
3054
+ name: `Thinking: ${id}`,
3055
+ description: null
3056
+ }))
3057
+ };
3058
+ }
3059
+ async function getSessionConfiguration(proc, pre) {
3060
+ const state = pre?.state ?? await proc.getState();
3061
+ const [models, modes] = await Promise.all([getModelState(proc, { ...pre, state }), getThinkingState(proc, { state })]);
3062
+ const configOptions = [
3063
+ {
3064
+ type: "select",
3065
+ id: THOUGHT_LEVEL_CONFIG_ID,
3066
+ category: "thought_level",
3067
+ name: "Thinking",
3068
+ description: "Set the reasoning effort for this session",
3069
+ currentValue: modes.currentModeId,
3070
+ options: modes.availableModes.map((mode) => ({
3071
+ value: mode.id,
3072
+ name: mode.name,
3073
+ description: mode.description ?? null
3074
+ }))
3075
+ }
3076
+ ];
3077
+ if (models?.availableModels.length) {
3078
+ configOptions.unshift({
3079
+ type: "select",
3080
+ id: MODEL_CONFIG_ID,
3081
+ category: "model",
3082
+ name: "Model",
3083
+ description: "Select the model for this session",
3084
+ currentValue: models.currentModelId,
3085
+ options: models.availableModels.map((model) => ({
3086
+ value: model.modelId,
3087
+ name: model.name,
3088
+ description: model.description ?? null
3089
+ }))
3090
+ });
3091
+ }
3092
+ return { configOptions, models, modes };
3093
+ }
3094
+ async function emitConfigOptionsUpdate(conn, sessionId, proc) {
3095
+ const { configOptions, modes } = await getSessionConfiguration(proc);
3096
+ await conn.sessionUpdate({
3097
+ sessionId,
3098
+ update: { sessionUpdate: "current_mode_update", currentModeId: modes.currentModeId }
3099
+ });
3100
+ await conn.sessionUpdate({ sessionId, update: { sessionUpdate: "config_option_update", configOptions } });
3101
+ return configOptions;
3102
+ }
3103
+ async function setSessionModel(proc, requestedModelId) {
3104
+ let provider = null;
3105
+ let modelId = requestedModelId;
3106
+ if (requestedModelId.includes("/")) {
3107
+ const [candidateProvider, ...rest] = requestedModelId.split("/");
3108
+ provider = candidateProvider;
3109
+ modelId = rest.join("/");
3110
+ } else {
3111
+ const data = await proc.getAvailableModels();
3112
+ const models = data && typeof data === "object" && "models" in data && Array.isArray(data.models) ? data.models : [];
3113
+ const found = models.find(
3114
+ (model) => Boolean(
3115
+ model && typeof model === "object" && "id" in model && model.id === modelId && "provider" in model && typeof model.provider === "string"
3116
+ )
3117
+ );
3118
+ if (found) provider = found.provider;
3119
+ }
3120
+ if (!provider || !modelId) throw RequestError3.invalidParams(`Unknown modelId: ${requestedModelId}`);
3121
+ await proc.setModel(provider, modelId);
3122
+ }
3123
+ async function getModelState(proc, pre) {
3124
+ let availableModels = [];
3125
+ const data = pre?.availableModels ?? await (async () => {
3126
+ try {
3127
+ return await proc.getAvailableModels();
3128
+ } catch {
3129
+ return null;
3130
+ }
3131
+ })();
3132
+ const models = Array.isArray(data?.models) ? data.models : [];
3133
+ availableModels = models.map((m) => {
3134
+ const provider = String(m?.provider ?? "").trim();
3135
+ const id = String(m?.id ?? "").trim();
3136
+ if (!provider || !id) return null;
3137
+ const name = String(m?.name ?? id);
3138
+ return {
3139
+ modelId: `${provider}/${id}`,
3140
+ name: `${provider}/${name}`,
3141
+ description: null
3142
+ };
3143
+ }).filter(Boolean);
3144
+ let currentModelId = null;
3145
+ const state = pre?.state ?? await (async () => {
3146
+ try {
3147
+ return await proc.getState();
3148
+ } catch {
3149
+ return null;
3150
+ }
3151
+ })();
3152
+ const model = state?.model;
3153
+ if (model && typeof model === "object") {
3154
+ const provider = String(model.provider ?? "").trim();
3155
+ const id = String(model.id ?? "").trim();
3156
+ if (provider && id) currentModelId = `${provider}/${id}`;
3157
+ }
3158
+ if (!availableModels.length && !currentModelId) return null;
3159
+ if (!currentModelId) currentModelId = availableModels[0]?.modelId ?? "default";
3160
+ return {
3161
+ availableModels,
3162
+ currentModelId
3163
+ };
3164
+ }
3165
+ function isSemver(v) {
3166
+ return /^\d+\.\d+\.\d+(?:[-+].+)?$/.test(v);
3167
+ }
3168
+ function compareSemver(a, b) {
3169
+ const pa = a.split(/[.-]/).slice(0, 3).map((n) => Number(n));
3170
+ const pb = b.split(/[.-]/).slice(0, 3).map((n) => Number(n));
3171
+ for (let i = 0; i < 3; i++) {
3172
+ const da = pa[i] ?? 0;
3173
+ const db = pb[i] ?? 0;
3174
+ if (da > db) return 1;
3175
+ if (da < db) return -1;
3176
+ }
3177
+ return 0;
3178
+ }
3179
+ function resolveAtomicExecutablePath() {
3180
+ const cmd = getAtomicCommand(process.env.ATOMIC_ACP_ATOMIC_COMMAND);
3181
+ if (cmd.includes("/") || process.platform === "win32" && /^[a-z]:[\\/]/i.test(cmd)) {
3182
+ return existsSync4(cmd) ? cmd : null;
3183
+ }
3184
+ const whichCmd = process.platform === "win32" ? "where" : "which";
3185
+ const which = spawnSync(whichCmd, [cmd], { encoding: "utf-8" });
3186
+ return String(which.stdout ?? "").split(/\r?\n/)[0]?.trim() || null;
3187
+ }
3188
+ function getAtomicVersionOutput() {
3189
+ const cmd = getAtomicCommand(process.env.ATOMIC_ACP_ATOMIC_COMMAND);
3190
+ const atomicVersion = spawnSync(cmd, ["--version"], {
3191
+ encoding: "utf-8",
3192
+ shell: shouldUseShellForAtomicCommand(cmd)
3193
+ });
3194
+ return String(atomicVersion.stdout ?? "").trim() || String(atomicVersion.stderr ?? "").trim();
3195
+ }
3196
+ function buildUpdateNotice() {
3197
+ try {
3198
+ const installed = getAtomicVersionOutput().replace(/^v/i, "");
3199
+ if (!installed || !isSemver(installed)) return null;
3200
+ const latestRes = spawnSync("npm", ["view", "@bastani/atomic", "version"], {
3201
+ encoding: "utf-8",
3202
+ timeout: 800
3203
+ });
3204
+ const latest = String(latestRes.stdout ?? "").trim().replace(/^v/i, "");
3205
+ if (!latest || !isSemver(latest)) return null;
3206
+ if (compareSemver(latest, installed) <= 0) return null;
3207
+ return `New version available: v${latest} (installed v${installed}). Run: \`npm i -g @bastani/atomic\``;
3208
+ } catch {
3209
+ return null;
3210
+ }
3211
+ }
3212
+ function buildStartupInfo(opts) {
3213
+ void opts.fileCommands;
3214
+ const md = [];
3215
+ try {
3216
+ const installed = getAtomicVersionOutput().replace(/^v/i, "");
3217
+ if (installed) {
3218
+ md.push(`Atomic v${installed}`);
3219
+ md.push("---");
3220
+ md.push("");
3221
+ }
3222
+ } catch {
3223
+ }
3224
+ const addSection = (title, items) => {
3225
+ const cleaned = items.map((s) => s.trim()).filter(Boolean);
3226
+ if (!cleaned.length) return;
3227
+ md.push(`## ${title}`);
3228
+ for (const item of cleaned) md.push(`- ${item}`);
3229
+ md.push("");
3230
+ };
3231
+ const contextItems = [];
3232
+ const contextPath = join5(opts.cwd, "AGENTS.md");
3233
+ if (existsSync4(contextPath)) contextItems.push(contextPath);
3234
+ addSection("Context", contextItems);
3235
+ const skillsItems = [];
3236
+ const pushSkillFromRoot = (root) => {
3237
+ try {
3238
+ for (const e of readdirSync3(root)) {
3239
+ const p = join5(root, e);
3240
+ try {
3241
+ const st = statSync3(p);
3242
+ if (st.isFile() && e.toLowerCase().endsWith(".md")) {
3243
+ skillsItems.push(p);
3244
+ }
3245
+ } catch {
3246
+ }
3247
+ }
3248
+ const stack = [root];
3249
+ while (stack.length) {
3250
+ const dir = stack.pop();
3251
+ let entries = [];
3252
+ try {
3253
+ entries = readdirSync3(dir);
3254
+ } catch {
3255
+ continue;
3256
+ }
3257
+ for (const name of entries) {
3258
+ if (name === "node_modules" || name === ".git") continue;
3259
+ const p = join5(dir, name);
3260
+ let st;
3261
+ try {
3262
+ st = statSync3(p);
3263
+ } catch {
3264
+ continue;
3265
+ }
3266
+ if (st.isDirectory()) {
3267
+ stack.push(p);
3268
+ } else if (st.isFile() && name === "SKILL.md") {
3269
+ skillsItems.push(p);
3270
+ }
3271
+ }
3272
+ }
3273
+ } catch {
3274
+ }
3275
+ };
3276
+ const globalSkillsDir = join5(getAgentDir(), "skills");
3277
+ pushSkillFromRoot(globalSkillsDir);
3278
+ const legacyAgentsSkillsDir = join5(process.env.HOME ?? "", ".agents", "skills");
3279
+ pushSkillFromRoot(legacyAgentsSkillsDir);
3280
+ const projectSkillsDir = join5(opts.cwd, ".atomic", "skills");
3281
+ pushSkillFromRoot(projectSkillsDir);
3282
+ addSection("Skills", skillsItems);
3283
+ const promptsItems = [];
3284
+ const agentDir = getAgentDir();
3285
+ const promptsDir = join5(agentDir, "prompts");
3286
+ try {
3287
+ const prompts = readdirSync3(promptsDir).filter((f) => f.endsWith(".md"));
3288
+ for (const f of prompts) promptsItems.push(`/${basename2(f, ".md")}`);
3289
+ } catch {
3290
+ }
3291
+ addSection("Prompts", promptsItems);
3292
+ const extItems = [];
3293
+ const extDir = join5(agentDir, "extensions");
3294
+ try {
3295
+ const exts = readdirSync3(extDir).filter((f) => f.endsWith(".ts") || f.endsWith(".js"));
3296
+ for (const f of exts) extItems.push(join5(extDir, f));
3297
+ } catch {
3298
+ }
3299
+ for (const settingsPath of [join5(agentDir, "settings.json"), join5(opts.cwd, ".atomic", "settings.json")]) {
3300
+ try {
3301
+ const settings = JSON.parse(readFileSync6(settingsPath, "utf-8"));
3302
+ const packages = Array.isArray(settings.packages) ? settings.packages : [];
3303
+ for (const pkg2 of packages) {
3304
+ const source = typeof pkg2 === "string" ? pkg2 : pkg2?.source;
3305
+ if (typeof source !== "string") continue;
3306
+ extItems.push(source.startsWith("npm:") ? `${source}
3307
+ - index.ts` : source);
3308
+ }
3309
+ } catch {
3310
+ }
3311
+ }
3312
+ addSection("Extensions", extItems);
3313
+ if (opts.updateNotice) {
3314
+ md.push("---");
3315
+ md.push(opts.updateNotice);
3316
+ md.push("");
3317
+ }
3318
+ return md.join("\n").trim() + "\n";
3319
+ }
3320
+ function readNearestPackageJson(metaUrl) {
3321
+ try {
3322
+ let dir = dirname2(fileURLToPath(metaUrl));
3323
+ for (let i = 0; i < 6; i++) {
3324
+ const p = join5(dir, "package.json");
3325
+ if (existsSync4(p)) {
3326
+ const json = JSON.parse(readFileSync6(p, "utf-8"));
3327
+ return { name: json?.name, version: json?.version };
3328
+ }
3329
+ dir = dirname2(dir);
3330
+ }
3331
+ } catch {
3332
+ }
3333
+ return { name: "atomic-acp", version: "0.0.0" };
3334
+ }
3335
+
3336
+ // src/index.ts
3337
+ if (process.argv.includes("--terminal-login")) {
3338
+ const { spawnSync: spawnSync2 } = await import("child_process");
3339
+ const cmd = getAtomicCommand(process.env.ATOMIC_ACP_ATOMIC_COMMAND);
3340
+ const res = spawnSync2(cmd, [], {
3341
+ stdio: "inherit",
3342
+ env: process.env,
3343
+ shell: shouldUseShellForAtomicCommand(cmd)
3344
+ });
3345
+ if (res.error && res.error.code === "ENOENT") {
3346
+ process.stderr.write(
3347
+ `atomic-acp: could not start Atomic (command not found: ${cmd}). Install it via \`npm install -g @bastani/atomic\` or ensure \`atomic\` is on your PATH.
3348
+ `
3349
+ );
3350
+ process.exit(1);
3351
+ }
3352
+ process.exit(typeof res.status === "number" ? res.status : 1);
3353
+ }
3354
+ var input = new WritableStream({
3355
+ write(chunk) {
3356
+ return new Promise((resolve3) => {
3357
+ if (process.stdout.destroyed || !process.stdout.writable) return resolve3();
3358
+ try {
3359
+ process.stdout.write(chunk, (err) => {
3360
+ void err;
3361
+ resolve3();
3362
+ });
3363
+ } catch {
3364
+ resolve3();
3365
+ }
3366
+ });
3367
+ }
3368
+ });
3369
+ var output = new ReadableStream({
3370
+ start(controller) {
3371
+ process.stdin.on("data", (chunk) => controller.enqueue(new Uint8Array(chunk)));
3372
+ process.stdin.on("end", () => controller.close());
3373
+ process.stdin.on("error", (err) => controller.error(err));
3374
+ }
3375
+ });
3376
+ var stream = ndJsonStream(input, output);
3377
+ var agent = new AgentSideConnection((conn) => new AtomicAcpAgent(conn), stream);
3378
+ function shutdown() {
3379
+ try {
3380
+ ;
3381
+ agent?.agent?.dispose?.();
3382
+ } catch {
3383
+ }
3384
+ try {
3385
+ process.exit(0);
3386
+ } catch {
3387
+ }
3388
+ }
3389
+ process.stdin.on("end", shutdown);
3390
+ process.stdin.on("close", shutdown);
3391
+ process.stdin.resume();
3392
+ process.on("SIGINT", shutdown);
3393
+ process.on("SIGTERM", shutdown);
3394
+ process.stdout.on("error", () => {
3395
+ try {
3396
+ process.exit(0);
3397
+ } catch {
3398
+ }
3399
+ });
3400
+ //# sourceMappingURL=index.js.map