@bastani/atomic-acp 0.0.15 → 0.0.17

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 CHANGED
@@ -3,321 +3,16 @@
3
3
  // src/index.ts
4
4
  import { ndJsonStream } from "@agentclientprotocol/sdk";
5
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 record3 = value;
41
- for (const source of [record3, record3?.args, record3?.input, record3?.rawInput, record3?.toolInput, record3?.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 record3 = value;
49
- if (Array.isArray(record3?.content)) {
50
- const text = record3.content.map(
51
- (block) => block.type === "text" && typeof block.text === "string" ? block.text : ""
52
- ).join("");
53
- if (text) return text;
54
- }
55
- const details = record3?.details;
56
- const stdout = details?.stdout ?? record3?.stdout ?? details?.output ?? record3?.output;
57
- const stderr = details?.stderr ?? record3?.stderr;
58
- return [stdout, stderr].filter((part) => typeof part === "string" && part.length > 0).join("\n");
59
- }
60
- function bashExitCode(value, isError) {
61
- const record3 = value;
62
- const code = record3?.details?.exitCode ?? record3?.exitCode ?? record3?.details?.code ?? record3?.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
6
  // src/acp/agent.ts
7
+ import { spawnSync } from "child_process";
8
+ import { existsSync as existsSync3, readdirSync as readdirSync2, readFileSync as readFileSync5, realpathSync, statSync as statSync2 } from "fs";
9
+ import { basename as basename2, dirname as dirname2, isAbsolute as isAbsolute2, join as join5 } from "path";
82
10
  import {
83
11
  agent,
84
12
  methods as methods3,
85
13
  RequestError as RequestError4
86
14
  } from "@agentclientprotocol/sdk";
87
15
 
88
- // src/acp/auth.ts
89
- var ATOMIC_SETUP_METHOD_ID = "atomic_terminal_login";
90
- function getAuthMethods(opts) {
91
- const supportsTerminalAuthMeta = opts?.supportsTerminalAuthMeta ?? true;
92
- const method = {
93
- id: ATOMIC_SETUP_METHOD_ID,
94
- name: "Launch Atomic in the terminal",
95
- description: "Start Atomic in an interactive terminal to configure API keys or login",
96
- // Registry-required fields
97
- type: "terminal",
98
- args: ["--terminal-login"],
99
- env: {}
100
- };
101
- if (supportsTerminalAuthMeta) {
102
- const launch = terminalAuthLaunchSpec();
103
- method._meta = {
104
- ...method._meta ?? {},
105
- "terminal-auth": {
106
- ...launch,
107
- label: "Launch Atomic"
108
- }
109
- };
110
- }
111
- return [method];
112
- }
113
- function terminalAuthLaunchSpec() {
114
- const argv0 = process.argv[0] || "node";
115
- const argv1 = process.argv[1];
116
- if (argv1 && argv0) {
117
- const isNode = argv0.includes("node");
118
- const isJs = argv1.endsWith(".js");
119
- if (isNode && isJs) {
120
- return { command: argv0, args: [argv1, "--terminal-login"] };
121
- }
122
- }
123
- return { command: "atomic-acp", args: ["--terminal-login"] };
124
- }
125
-
126
- // src/acp/elicitation/extension-dialog.ts
127
- import {
128
- methods
129
- } from "@agentclientprotocol/sdk";
130
- var NO_CLIENT_ELICITATION_SUPPORT = {
131
- form: false,
132
- reason: "missing_client_capability"
133
- };
134
- function readClientElicitationSupport(params) {
135
- const form = params.clientCapabilities?.elicitation?.form;
136
- if (form !== null && typeof form === "object" && !Array.isArray(form)) {
137
- return { form: true };
138
- }
139
- return NO_CLIENT_ELICITATION_SUPPORT;
140
- }
141
- function requestExtensionDialog(conn, sessionId, ev, form, signal, onClientCannotAnswer) {
142
- const cancelled = {
143
- type: "extension_ui_response",
144
- id: String(ev.id),
145
- cancelled: true
146
- };
147
- if (signal?.aborted) return Promise.resolve(cancelled);
148
- return new Promise((resolve2) => {
149
- const finish = (response) => {
150
- signal?.removeEventListener("abort", abort);
151
- resolve2(response);
152
- };
153
- const abort = () => finish(cancelled);
154
- signal?.addEventListener("abort", abort, { once: true });
155
- void requestDialog(conn, sessionId, ev, form, onClientCannotAnswer).then(finish);
156
- });
157
- }
158
- async function requestDialog(conn, sessionId, ev, form, onClientCannotAnswer) {
159
- const id = String(ev.id);
160
- const cancelled = { type: "extension_ui_response", id, cancelled: true };
161
- const method = ev.method;
162
- if (method === "questionnaire") {
163
- if (!form) return cancelled;
164
- try {
165
- return await requestQuestionnaire(conn, sessionId, id, ev.questions);
166
- } catch {
167
- onClientCannotAnswer?.();
168
- return cancelled;
169
- }
170
- }
171
- const options = Array.isArray(ev.options) ? ev.options.map(String) : [];
172
- if (method === "select" && !options.length) return cancelled;
173
- const title = typeof ev.title === "string" ? ev.title : `Atomic ${method}`;
174
- try {
175
- if (form) {
176
- let property;
177
- if (method === "confirm") property = { type: "boolean", title };
178
- else if (method === "select") property = { type: "string", title, enum: options };
179
- else
180
- property = {
181
- type: "string",
182
- title,
183
- ...typeof ev.placeholder === "string" ? { description: ev.placeholder } : {},
184
- ...typeof ev.prefill === "string" ? { default: ev.prefill } : {}
185
- };
186
- const response2 = await conn.request(methods.client.elicitation.create, {
187
- sessionId,
188
- mode: "form",
189
- message: typeof ev.message === "string" ? `${title}
190
-
191
- ${ev.message}` : title,
192
- requestedSchema: { type: "object", properties: { value: property }, required: ["value"] },
193
- _meta: { atomicAcp: { kind: "extension_ui", method: String(method), atomicRequestId: id } }
194
- });
195
- if (response2.action !== "accept") return cancelled;
196
- const value = response2.content?.value;
197
- if (method === "confirm")
198
- return typeof value === "boolean" ? { type: "extension_ui_response", id, confirmed: value } : cancelled;
199
- if (typeof value !== "string" || method === "select" && !options.includes(value)) return cancelled;
200
- return { type: "extension_ui_response", id, value };
201
- }
202
- if (method !== "select" && method !== "confirm") return cancelled;
203
- const rawInput = { method };
204
- for (const key of ["title", "message", "options", "placeholder", "prefill"]) {
205
- if (Object.hasOwn(ev, key)) rawInput[key] = ev[key];
206
- }
207
- const response = await conn.request(methods.client.session.requestPermission, {
208
- sessionId,
209
- toolCall: { toolCallId: `atomic-ui-${id}`, title, kind: "other", status: "pending", rawInput },
210
- options: method === "confirm" ? [
211
- { optionId: "yes", name: "Yes", kind: "allow_once" },
212
- { optionId: "no", name: "No", kind: "reject_once" }
213
- ] : options.map((name, index2) => ({ optionId: `choice-${index2}`, name, kind: "allow_once" }))
214
- });
215
- if (response.outcome.outcome !== "selected") return cancelled;
216
- const optionId = response.outcome.optionId;
217
- if (method === "confirm")
218
- return optionId === "yes" || optionId === "no" ? { type: "extension_ui_response", id, confirmed: optionId === "yes" } : cancelled;
219
- const index = options.findIndex((_, index2) => optionId === `choice-${index2}`);
220
- return index < 0 ? cancelled : { type: "extension_ui_response", id, value: options[index] };
221
- } catch {
222
- onClientCannotAnswer?.();
223
- return cancelled;
224
- }
225
- }
226
- function readQuestions(value) {
227
- if (!Array.isArray(value) || value.length === 0) return void 0;
228
- const questions = [];
229
- for (const item of value) {
230
- const q = item;
231
- if (!q || typeof q.question !== "string" || !Array.isArray(q.options) || q.options.length === 0) return void 0;
232
- const options = q.options.filter(
233
- (option) => typeof option?.label === "string" && option.label !== ""
234
- );
235
- if (options.length !== q.options.length) return void 0;
236
- questions.push({
237
- question: q.question,
238
- ...typeof q.header === "string" ? { header: q.header } : {},
239
- multiSelect: q.multiSelect === true,
240
- options
241
- });
242
- }
243
- return questions;
244
- }
245
- async function requestQuestionnaire(conn, sessionId, id, rawQuestions) {
246
- const cancelled = { type: "extension_ui_response", id, cancelled: true };
247
- const questions = readQuestions(rawQuestions);
248
- if (!questions) return cancelled;
249
- const properties = {};
250
- questions.forEach((q, index) => {
251
- const labels = q.options.map((option) => option.label);
252
- const described = q.options.filter((option) => option.description);
253
- const description = [q.question, ...described.map((option) => `${option.label}: ${option.description}`)].join("\n");
254
- const title = q.header || q.question;
255
- properties[`q${index}`] = q.multiSelect ? { type: "array", title, description, minItems: 1, items: { type: "string", enum: labels } } : { type: "string", title, description, enum: labels };
256
- });
257
- const response = await conn.request(methods.client.elicitation.create, {
258
- sessionId,
259
- mode: "form",
260
- message: questions.length === 1 ? questions[0].question : "Atomic has some questions for you.",
261
- requestedSchema: { type: "object", properties, required: Object.keys(properties) },
262
- _meta: { atomicAcp: { kind: "extension_ui", method: "questionnaire", atomicRequestId: id } }
263
- });
264
- if (response.action !== "accept") return cancelled;
265
- const content = response.content ?? {};
266
- const answers = [];
267
- for (const [index, q] of questions.entries()) {
268
- const labels = q.options.map((option) => option.label);
269
- const value = content[`q${index}`];
270
- if (q.multiSelect) {
271
- if (!Array.isArray(value) || value.length === 0 || !value.every((v) => typeof v === "string" && labels.includes(v)))
272
- return cancelled;
273
- answers.push({ questionIndex: index, question: q.question, kind: "multi", answer: null, selected: value });
274
- } else {
275
- if (typeof value !== "string" || !labels.includes(value)) return cancelled;
276
- answers.push({ questionIndex: index, question: q.question, kind: "option", answer: value });
277
- }
278
- }
279
- return { type: "extension_ui_response", id, answers };
280
- }
281
-
282
- // src/acp/session.ts
283
- import { RequestError as RequestError3, methods as methods2 } from "@agentclientprotocol/sdk";
284
-
285
- // src/acp/auth-required.ts
286
- import { RequestError } from "@agentclientprotocol/sdk";
287
- function maybeAuthRequiredError(err) {
288
- const msg = String(err?.message ?? err ?? "");
289
- const s = msg.toLowerCase();
290
- const patterns = [
291
- "api key",
292
- "apikey",
293
- "missing key",
294
- "no key",
295
- "not configured",
296
- "unauthorized",
297
- "authentication",
298
- "permission denied",
299
- "forbidden",
300
- "401",
301
- "403"
302
- ];
303
- const hit = patterns.some((p) => s.includes(p));
304
- if (!hit) return null;
305
- return RequestError.authRequired(
306
- {
307
- authMethods: getAuthMethods()
308
- },
309
- "Configure an API key or log in with an OAuth provider."
310
- );
311
- }
312
-
313
- // src/acp/session.ts
314
- import { readFileSync as readFileSync3 } from "fs";
315
- import { isAbsolute, resolve as resolvePath } from "path";
316
-
317
- // src/atomic-rpc/process.ts
318
- import { spawn } from "child_process";
319
- import crossSpawn from "cross-spawn";
320
-
321
16
  // src/atomic-rpc/command.ts
322
17
  import { platform } from "os";
323
18
  function defaultAtomicCommand() {
@@ -400,6 +95,10 @@ function withExcludedTool(extraArgs, tool) {
400
95
  return [...args, "--exclude-tools", tool];
401
96
  }
402
97
 
98
+ // src/atomic-rpc/process.ts
99
+ import { spawn } from "child_process";
100
+ import crossSpawn from "cross-spawn";
101
+
403
102
  // src/atomic-rpc/adapter-extension.ts
404
103
  import { randomBytes } from "crypto";
405
104
  import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "fs";
@@ -720,6 +419,11 @@ var AtomicRpcProcess = class _AtomicRpcProcess {
720
419
  const res = await this.request({ type: "abort" });
721
420
  if (!res.success) throw new Error(`Atomic abort failed: ${res.error ?? JSON.stringify(res.data)}`);
722
421
  }
422
+ /** Take back the steering and follow-up messages Atomic has queued, so no later run reads them. */
423
+ async clearQueue() {
424
+ const res = await this.request({ type: "clear_queue" });
425
+ if (!res.success) throw new Error(`Atomic clear_queue failed: ${res.error ?? JSON.stringify(res.data)}`);
426
+ }
723
427
  writeExtensionUiResponse(response) {
724
428
  return this.writeJsonLine(response);
725
429
  }
@@ -802,7 +506,8 @@ var AtomicRpcProcess = class _AtomicRpcProcess {
802
506
  */
803
507
  async startPendingRecovery(reason) {
804
508
  const res = await this.request({ type: "start_pending_recovery", reason });
805
- if (!res.success) throw new Error(`Atomic start_pending_recovery failed: ${res.error ?? JSON.stringify(res.data)}`);
509
+ if (!res.success)
510
+ throw new Error(`Atomic start_pending_recovery failed: ${res.error ?? JSON.stringify(res.data)}`);
806
511
  return res.data;
807
512
  }
808
513
  async getMessages() {
@@ -816,7 +521,8 @@ var AtomicRpcProcess = class _AtomicRpcProcess {
816
521
  return res.data;
817
522
  }
818
523
  writeJsonLine(value) {
819
- const line = JSON.stringify(value) + "\n";
524
+ const line = `${JSON.stringify(value)}
525
+ `;
820
526
  return new Promise((resolve2, reject) => {
821
527
  try {
822
528
  this.child.stdin.write(line, (err) => {
@@ -828,17 +534,6 @@ var AtomicRpcProcess = class _AtomicRpcProcess {
828
534
  }
829
535
  });
830
536
  }
831
- async listWorkflowRuns(status) {
832
- const res = await this.request({ type: "list_workflow_runs", ...status ? { status } : {} });
833
- if (!res.success) throw new Error(`Atomic list_workflow_runs failed: ${res.error ?? JSON.stringify(res.data)}`);
834
- return res.data;
835
- }
836
- async getWorkflowRunSummary(runId) {
837
- const res = await this.request({ type: "get_workflow_run_summary", runId });
838
- if (!res.success)
839
- throw new Error(`Atomic get_workflow_run_summary failed: ${res.error ?? JSON.stringify(res.data)}`);
840
- return res.data;
841
- }
842
537
  request(cmd, opts) {
843
538
  if (this.exitError) return Promise.reject(this.exitError);
844
539
  const id = crypto.randomUUID();
@@ -879,39 +574,126 @@ var AtomicRpcProcess = class _AtomicRpcProcess {
879
574
  }
880
575
  };
881
576
 
882
- // src/acp/translate/atomic-tools.ts
883
- function toolResultToText(result) {
884
- if (!result) return "";
885
- const details = result.details;
886
- const diff = details?.diff;
887
- if (typeof diff === "string" && diff.trim()) return diff;
888
- const content = result.content;
889
- if (Array.isArray(content)) {
890
- const texts = content.map((c) => c?.type === "text" && typeof c.text === "string" ? c.text : "").filter(Boolean);
891
- if (texts.length) return texts.join("");
577
+ // src/acp/atomic-commands.ts
578
+ function describeFallback(c) {
579
+ const source = typeof c.source === "string" ? c.source : "";
580
+ const location = typeof c.location === "string" ? c.location : "";
581
+ const parts = [];
582
+ if (source) parts.push(source);
583
+ if (location) parts.push(location);
584
+ return parts.length ? `(${parts.join(":")})` : "(command)";
585
+ }
586
+ function toAvailableCommandsFromAtomicGetCommands(data, opts) {
587
+ const enableSkillCommands = opts?.enableSkillCommands ?? true;
588
+ const includeExtensionCommands = opts?.includeExtensionCommands ?? true;
589
+ const root = data;
590
+ const commandsRaw = Array.isArray(root?.commands) ? root.commands : Array.isArray(root?.data?.commands) ? root.data.commands : [];
591
+ const out = [];
592
+ for (const c of commandsRaw) {
593
+ const name = typeof c?.name === "string" ? c.name.trim() : "";
594
+ if (!name) continue;
595
+ const source = typeof c?.source === "string" ? c.source : "";
596
+ if (!includeExtensionCommands && source === "extension") continue;
597
+ if (!enableSkillCommands && name.startsWith("skill:")) continue;
598
+ const desc = typeof c?.description === "string" ? c.description.trim() : "";
599
+ const usage = desc.match(/Usage:\s*\/\S+\s+(.+)$/i)?.[1];
600
+ out.push({
601
+ name,
602
+ description: desc || describeFallback(c),
603
+ ...usage ? { input: { hint: usage } } : {}
604
+ });
892
605
  }
893
- 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);
894
- const stderr = (typeof details?.stderr === "string" ? details.stderr : void 0) ?? (typeof result?.stderr === "string" ? result.stderr : void 0);
895
- 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);
896
- if (typeof stdout === "string" && stdout.trim() || typeof stderr === "string" && stderr.trim()) {
897
- const parts = [];
898
- if (typeof stdout === "string" && stdout.trim()) parts.push(stdout);
899
- if (typeof stderr === "string" && stderr.trim()) parts.push(`stderr:
900
- ${stderr}`);
901
- if (typeof exitCode === "number") parts.push(`exit code: ${exitCode}`);
902
- return parts.join("\n\n").trimEnd();
606
+ return { commands: out, raw: commandsRaw };
607
+ }
608
+
609
+ // src/acp/translate/prompt.ts
610
+ function promptToSessionTitle(blocks) {
611
+ const normalized = blocks.filter((block) => block.type === "text").map((block) => block.text).join(" ").replace(/\s+/gu, " ").trim();
612
+ return normalized ? Array.from(normalized).slice(0, 80).join("") : null;
613
+ }
614
+ function promptToAtomicMessage(blocks) {
615
+ let message = "";
616
+ const images = [];
617
+ for (const b of blocks) {
618
+ switch (b.type) {
619
+ case "text":
620
+ message += b.text;
621
+ break;
622
+ case "resource_link":
623
+ message += `
624
+ [Context] ${b.uri}`;
625
+ break;
626
+ case "image": {
627
+ images.push({
628
+ type: "image",
629
+ mimeType: b.mimeType,
630
+ data: b.data
631
+ });
632
+ break;
633
+ }
634
+ case "resource": {
635
+ const r = b.resource;
636
+ const uri = typeof r?.uri === "string" ? r.uri : "(unknown)";
637
+ if (typeof r?.text === "string") {
638
+ const mime = typeof r?.mimeType === "string" ? r.mimeType : "text/plain";
639
+ message += `
640
+ [Embedded Context] ${uri} (${mime})
641
+ ${r.text}`;
642
+ } else if (typeof r?.blob === "string") {
643
+ const mime = typeof r?.mimeType === "string" ? r.mimeType : "application/octet-stream";
644
+ const bytes = Buffer.byteLength(r.blob, "base64");
645
+ message += `
646
+ [Embedded Context] ${uri} (${mime}, ${bytes} bytes)`;
647
+ } else {
648
+ message += `
649
+ [Embedded Context] ${uri}`;
650
+ }
651
+ break;
652
+ }
653
+ case "audio": {
654
+ const bytes = Buffer.byteLength(b.data, "base64");
655
+ message += `
656
+ [Audio] (${b.mimeType}, ${bytes} bytes) not supported by atomic-acp`;
657
+ break;
658
+ }
659
+ default:
660
+ break;
661
+ }
903
662
  }
904
- try {
905
- return JSON.stringify(result, null, 2);
906
- } catch {
907
- return String(result);
663
+ return { message, images };
664
+ }
665
+
666
+ // src/acp/atomic-sessions.ts
667
+ function str(value) {
668
+ return typeof value === "string" ? value : void 0;
669
+ }
670
+ function isoDate(value) {
671
+ const date = typeof value === "string" ? new Date(value) : null;
672
+ return date && Number.isFinite(date.getTime()) ? date.toISOString() : null;
673
+ }
674
+ function sessionTitle(info, messageCount) {
675
+ const name = str(info.name)?.trim();
676
+ if (name || info.hasName === true) return name ?? "";
677
+ const firstMessage = messageCount > 0 ? str(info.firstMessage) : void 0;
678
+ return firstMessage ? promptToSessionTitle([{ type: "text", text: firstMessage }]) : null;
679
+ }
680
+ function parseAtomicSessionList(data) {
681
+ const sessions = data?.sessions;
682
+ if (!Array.isArray(sessions)) return [];
683
+ const items = [];
684
+ for (const raw of sessions) {
685
+ const info = raw ?? {};
686
+ const sessionId = str(info.id);
687
+ const cwd = str(info.cwd);
688
+ if (sessionId === void 0 || !cwd) continue;
689
+ const messageCount = typeof info.messageCount === "number" ? info.messageCount : 0;
690
+ const title = sessionTitle(info, messageCount);
691
+ if (messageCount === 0 && title === null && info.summary === void 0) continue;
692
+ items.push({ sessionId, cwd, title, updatedAt: isoDate(info.modified) });
908
693
  }
694
+ return items.sort((a, b) => (b.updatedAt ?? "").localeCompare(a.updatedAt ?? ""));
909
695
  }
910
696
 
911
- // src/acp/slash-commands.ts
912
- import { existsSync as existsSync2, readdirSync, readFileSync as readFileSync2, statSync } from "fs";
913
- import { basename, join as join3 } from "path";
914
-
915
697
  // src/acp/atomic-settings.ts
916
698
  import { existsSync, readFileSync } from "fs";
917
699
  import { homedir } from "os";
@@ -943,90 +725,401 @@ function getFirstDefinedEnv(names) {
943
725
  const value = process.env[name];
944
726
  if (value !== void 0) return value;
945
727
  }
946
- return void 0;
728
+ return void 0;
729
+ }
730
+ function hasAgentDirOverride() {
731
+ return process.env.ATOMIC_CODING_AGENT_DIR !== void 0 || process.env.PI_CODING_AGENT_DIR !== void 0;
732
+ }
733
+ function readMergedJsonFiles(paths) {
734
+ let merged = {};
735
+ for (let i = paths.length - 1; i >= 0; i--) {
736
+ merged = deepMerge(merged, readJsonFile(paths[i]));
737
+ }
738
+ return merged;
739
+ }
740
+ function getSettingsWithLocations(cwd) {
741
+ const agentDirs = getAgentDirs();
742
+ const projectDirs = getProjectConfigDirs(cwd);
743
+ return [
744
+ {
745
+ location: "user",
746
+ baseDirs: agentDirs,
747
+ settings: readMergedJsonFiles(agentDirs.map((dir) => join2(dir, "settings.json")))
748
+ },
749
+ {
750
+ location: "project",
751
+ baseDirs: projectDirs,
752
+ settings: readMergedJsonFiles(projectDirs.map((dir) => join2(dir, "settings.json")))
753
+ }
754
+ ];
755
+ }
756
+ function getMergedSettings(cwd) {
757
+ const settings = getSettingsWithLocations(cwd);
758
+ return deepMerge(settings[0].settings, settings[1].settings);
759
+ }
760
+ function expandHomePath(value) {
761
+ if (value === "~") return homedir();
762
+ if (value.startsWith("~/")) return join2(homedir(), value.slice(2));
763
+ return value;
764
+ }
765
+ function resolveAtomicPath(value, relativeBase = process.cwd()) {
766
+ const expanded = expandHomePath(value);
767
+ return resolve(relativeBase, expanded);
768
+ }
769
+ function readMergedResourceSettings(cwd) {
770
+ const prompts = [];
771
+ for (const entry of [...getSettingsWithLocations(cwd)].reverse()) {
772
+ const rawPrompts = entry.settings.prompts;
773
+ if (!Array.isArray(rawPrompts)) continue;
774
+ for (const value of rawPrompts) {
775
+ if (typeof value === "string") prompts.push({ value, location: entry.location, baseDirs: entry.baseDirs });
776
+ }
777
+ }
778
+ return { prompts };
779
+ }
780
+ function getAgentDir() {
781
+ const override = getFirstDefinedEnv(["ATOMIC_CODING_AGENT_DIR", "PI_CODING_AGENT_DIR"])?.trim();
782
+ return override ? resolveAtomicPath(override) : join2(homedir(), ".atomic", "agent");
783
+ }
784
+ function getAgentDirs() {
785
+ const primary = getAgentDir();
786
+ if (hasAgentDirOverride()) return [primary];
787
+ const legacy = join2(homedir(), ".pi", "agent");
788
+ return legacy === primary ? [primary] : [primary, legacy];
789
+ }
790
+ function getProjectConfigDirs(cwd) {
791
+ const resolvedCwd = resolve(cwd);
792
+ return [resolve(resolvedCwd, ".atomic"), resolve(resolvedCwd, ".pi")];
793
+ }
794
+ function getEnableSkillCommands(cwd) {
795
+ const merged = getMergedSettings(cwd);
796
+ const direct = merged.enableSkillCommands;
797
+ if (typeof direct === "boolean") return direct;
798
+ const nested = isObject(merged.skills) ? merged.skills.enableSkillCommands : void 0;
799
+ if (typeof nested === "boolean") return nested;
800
+ return true;
801
+ }
802
+ function getQuietStartup(cwd) {
803
+ const merged = getMergedSettings(cwd);
804
+ const direct = merged.quietStartup;
805
+ if (typeof direct === "boolean") return direct;
806
+ const legacy = merged.quietStart;
807
+ if (typeof legacy === "boolean") return legacy;
808
+ return false;
809
+ }
810
+
811
+ // src/acp/auth.ts
812
+ var ATOMIC_SETUP_METHOD_ID = "atomic_terminal_login";
813
+ function getAuthMethods(opts) {
814
+ const supportsTerminalAuthMeta = opts?.supportsTerminalAuthMeta ?? true;
815
+ const method = {
816
+ id: ATOMIC_SETUP_METHOD_ID,
817
+ name: "Launch Atomic in the terminal",
818
+ description: "Start Atomic in an interactive terminal to configure API keys or login",
819
+ // Registry-required fields
820
+ type: "terminal",
821
+ args: ["--terminal-login"],
822
+ env: {}
823
+ };
824
+ if (supportsTerminalAuthMeta) {
825
+ const launch = terminalAuthLaunchSpec();
826
+ method._meta = {
827
+ ...method._meta ?? {},
828
+ "terminal-auth": {
829
+ ...launch,
830
+ label: "Launch Atomic"
831
+ }
832
+ };
833
+ }
834
+ return [method];
835
+ }
836
+ function terminalAuthLaunchSpec() {
837
+ const argv0 = process.argv[0] || "node";
838
+ const argv1 = process.argv[1];
839
+ if (argv1 && argv0) {
840
+ const isNode = argv0.includes("node");
841
+ const isJs = argv1.endsWith(".js");
842
+ if (isNode && isJs) {
843
+ return { command: argv0, args: [argv1, "--terminal-login"] };
844
+ }
845
+ }
846
+ return { command: "atomic-acp", args: ["--terminal-login"] };
847
+ }
848
+
849
+ // src/acp/auth-required.ts
850
+ import { RequestError } from "@agentclientprotocol/sdk";
851
+ function maybeAuthRequiredError(err) {
852
+ const msg = String(err?.message ?? err ?? "");
853
+ const s = msg.toLowerCase();
854
+ const patterns = [
855
+ "api key",
856
+ "apikey",
857
+ "missing key",
858
+ "no key",
859
+ "not configured",
860
+ "unauthorized",
861
+ "authentication",
862
+ "permission denied",
863
+ "forbidden",
864
+ "401",
865
+ "403"
866
+ ];
867
+ const hit = patterns.some((p) => s.includes(p));
868
+ if (!hit) return null;
869
+ return RequestError.authRequired(
870
+ {
871
+ authMethods: getAuthMethods()
872
+ },
873
+ "Configure an API key or log in with an OAuth provider."
874
+ );
875
+ }
876
+
877
+ // src/acp/elicitation/extension-dialog.ts
878
+ import {
879
+ methods
880
+ } from "@agentclientprotocol/sdk";
881
+ var NO_CLIENT_ELICITATION_SUPPORT = {
882
+ form: false,
883
+ reason: "missing_client_capability"
884
+ };
885
+ function readClientElicitationSupport(params) {
886
+ const form = params.clientCapabilities?.elicitation?.form;
887
+ if (form !== null && typeof form === "object" && !Array.isArray(form)) {
888
+ return { form: true };
889
+ }
890
+ return NO_CLIENT_ELICITATION_SUPPORT;
891
+ }
892
+ function requestExtensionDialog(conn, sessionId, ev, form, signal, onClientCannotAnswer) {
893
+ const cancelled = {
894
+ type: "extension_ui_response",
895
+ id: String(ev.id),
896
+ cancelled: true
897
+ };
898
+ if (signal?.aborted) return Promise.resolve(cancelled);
899
+ return new Promise((resolve2) => {
900
+ const finish = (response) => {
901
+ signal?.removeEventListener("abort", abort);
902
+ resolve2(response);
903
+ };
904
+ const abort = () => finish(cancelled);
905
+ signal?.addEventListener("abort", abort, { once: true });
906
+ void requestDialog(conn, sessionId, ev, form, onClientCannotAnswer).then(finish);
907
+ });
908
+ }
909
+ async function requestDialog(conn, sessionId, ev, form, onClientCannotAnswer) {
910
+ const id = String(ev.id);
911
+ const cancelled = { type: "extension_ui_response", id, cancelled: true };
912
+ const method = ev.method;
913
+ if (method === "questionnaire") {
914
+ if (!form) return cancelled;
915
+ try {
916
+ return await requestQuestionnaire(conn, sessionId, id, ev.questions);
917
+ } catch {
918
+ onClientCannotAnswer?.();
919
+ return cancelled;
920
+ }
921
+ }
922
+ const options = Array.isArray(ev.options) ? ev.options.map(String) : [];
923
+ if (method === "select" && !options.length) return cancelled;
924
+ const title = typeof ev.title === "string" ? ev.title : `Atomic ${method}`;
925
+ try {
926
+ if (form) {
927
+ let property;
928
+ if (method === "confirm") property = { type: "boolean", title };
929
+ else if (method === "select") property = { type: "string", title, enum: options };
930
+ else
931
+ property = {
932
+ type: "string",
933
+ title,
934
+ ...typeof ev.placeholder === "string" ? { description: ev.placeholder } : {},
935
+ ...typeof ev.prefill === "string" ? { default: ev.prefill } : {}
936
+ };
937
+ const response2 = await conn.request(methods.client.elicitation.create, {
938
+ sessionId,
939
+ mode: "form",
940
+ message: typeof ev.message === "string" ? `${title}
941
+
942
+ ${ev.message}` : title,
943
+ requestedSchema: { type: "object", properties: { value: property }, required: ["value"] },
944
+ _meta: { atomicAcp: { kind: "extension_ui", method: String(method), atomicRequestId: id } }
945
+ });
946
+ if (response2.action !== "accept") return cancelled;
947
+ const value = response2.content?.value;
948
+ if (method === "confirm")
949
+ return typeof value === "boolean" ? { type: "extension_ui_response", id, confirmed: value } : cancelled;
950
+ if (typeof value !== "string" || method === "select" && !options.includes(value)) return cancelled;
951
+ return { type: "extension_ui_response", id, value };
952
+ }
953
+ if (method !== "select" && method !== "confirm") return cancelled;
954
+ const rawInput = { method };
955
+ for (const key of ["title", "message", "options", "placeholder", "prefill"]) {
956
+ if (Object.hasOwn(ev, key)) rawInput[key] = ev[key];
957
+ }
958
+ const response = await conn.request(methods.client.session.requestPermission, {
959
+ sessionId,
960
+ toolCall: { toolCallId: `atomic-ui-${id}`, title, kind: "other", status: "pending", rawInput },
961
+ options: method === "confirm" ? [
962
+ { optionId: "yes", name: "Yes", kind: "allow_once" },
963
+ { optionId: "no", name: "No", kind: "reject_once" }
964
+ ] : options.map((name, index2) => ({ optionId: `choice-${index2}`, name, kind: "allow_once" }))
965
+ });
966
+ if (response.outcome.outcome !== "selected") return cancelled;
967
+ const optionId = response.outcome.optionId;
968
+ if (method === "confirm")
969
+ return optionId === "yes" || optionId === "no" ? { type: "extension_ui_response", id, confirmed: optionId === "yes" } : cancelled;
970
+ const index = options.findIndex((_, index2) => optionId === `choice-${index2}`);
971
+ return index < 0 ? cancelled : { type: "extension_ui_response", id, value: options[index] };
972
+ } catch {
973
+ onClientCannotAnswer?.();
974
+ return cancelled;
975
+ }
947
976
  }
948
- function hasAgentDirOverride() {
949
- return process.env.ATOMIC_CODING_AGENT_DIR !== void 0 || process.env.PI_CODING_AGENT_DIR !== void 0;
950
- }
951
- function readMergedJsonFiles(paths) {
952
- let merged = {};
953
- for (let i = paths.length - 1; i >= 0; i--) {
954
- merged = deepMerge(merged, readJsonFile(paths[i]));
977
+ function readQuestions(value) {
978
+ if (!Array.isArray(value) || value.length === 0) return void 0;
979
+ const questions = [];
980
+ for (const item of value) {
981
+ const q = item;
982
+ if (!q || typeof q.question !== "string" || !Array.isArray(q.options) || q.options.length === 0) return void 0;
983
+ const options = q.options.filter(
984
+ (option) => typeof option?.label === "string" && option.label !== ""
985
+ );
986
+ if (options.length !== q.options.length) return void 0;
987
+ questions.push({
988
+ question: q.question,
989
+ ...typeof q.header === "string" ? { header: q.header } : {},
990
+ multiSelect: q.multiSelect === true,
991
+ options
992
+ });
955
993
  }
956
- return merged;
994
+ return questions;
957
995
  }
958
- function getSettingsWithLocations(cwd) {
959
- const agentDirs = getAgentDirs();
960
- const projectDirs = getProjectConfigDirs(cwd);
961
- return [
962
- {
963
- location: "user",
964
- baseDirs: agentDirs,
965
- settings: readMergedJsonFiles(agentDirs.map((dir) => join2(dir, "settings.json")))
966
- },
967
- {
968
- location: "project",
969
- baseDirs: projectDirs,
970
- settings: readMergedJsonFiles(projectDirs.map((dir) => join2(dir, "settings.json")))
996
+ async function requestQuestionnaire(conn, sessionId, id, rawQuestions) {
997
+ const cancelled = { type: "extension_ui_response", id, cancelled: true };
998
+ const questions = readQuestions(rawQuestions);
999
+ if (!questions) return cancelled;
1000
+ const properties = {};
1001
+ questions.forEach((q, index) => {
1002
+ const labels = q.options.map((option) => option.label);
1003
+ const described = q.options.filter((option) => option.description);
1004
+ const description = [q.question, ...described.map((option) => `${option.label}: ${option.description}`)].join(
1005
+ "\n"
1006
+ );
1007
+ const title = q.header || q.question;
1008
+ properties[`q${index}`] = q.multiSelect ? { type: "array", title, description, minItems: 1, items: { type: "string", enum: labels } } : { type: "string", title, description, enum: labels };
1009
+ });
1010
+ const response = await conn.request(methods.client.elicitation.create, {
1011
+ sessionId,
1012
+ mode: "form",
1013
+ message: questions.length === 1 ? questions[0].question : "Atomic has some questions for you.",
1014
+ requestedSchema: { type: "object", properties, required: Object.keys(properties) },
1015
+ _meta: { atomicAcp: { kind: "extension_ui", method: "questionnaire", atomicRequestId: id } }
1016
+ });
1017
+ if (response.action !== "accept") return cancelled;
1018
+ const content = response.content ?? {};
1019
+ const answers = [];
1020
+ for (const [index, q] of questions.entries()) {
1021
+ const labels = q.options.map((option) => option.label);
1022
+ const value = content[`q${index}`];
1023
+ if (q.multiSelect) {
1024
+ if (!Array.isArray(value) || value.length === 0 || !value.every((v) => typeof v === "string" && labels.includes(v)))
1025
+ return cancelled;
1026
+ answers.push({ questionIndex: index, question: q.question, kind: "multi", answer: null, selected: value });
1027
+ } else {
1028
+ if (typeof value !== "string" || !labels.includes(value)) return cancelled;
1029
+ answers.push({ questionIndex: index, question: q.question, kind: "option", answer: value });
971
1030
  }
972
- ];
973
- }
974
- function getMergedSettings(cwd) {
975
- const settings = getSettingsWithLocations(cwd);
976
- return deepMerge(settings[0].settings, settings[1].settings);
1031
+ }
1032
+ return { type: "extension_ui_response", id, answers };
977
1033
  }
978
- function expandHomePath(value) {
979
- if (value === "~") return homedir();
980
- if (value.startsWith("~/")) return join2(homedir(), value.slice(2));
981
- return value;
1034
+
1035
+ // src/acp/headless.ts
1036
+ function isHeadlessFromEnv(env = process.env) {
1037
+ return /^(1|true)$/i.test(env.ATOMIC_ACP_HEADLESS?.trim() ?? "");
982
1038
  }
983
- function resolveAtomicPath(value, relativeBase = process.cwd()) {
984
- const expanded = expandHomePath(value);
985
- return resolve(relativeBase, expanded);
1039
+
1040
+ // src/acp/mcp-servers.ts
1041
+ import { RequestError as RequestError2 } from "@agentclientprotocol/sdk";
1042
+ var RESERVED_NAMES = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
1043
+ function toRecord(entries) {
1044
+ return Object.fromEntries(entries.map((entry) => [entry.name, entry.value]));
986
1045
  }
987
- function readMergedResourceSettings(cwd) {
988
- const prompts = [];
989
- for (const entry of [...getSettingsWithLocations(cwd)].reverse()) {
990
- const rawPrompts = entry.settings.prompts;
991
- if (!Array.isArray(rawPrompts)) continue;
992
- for (const value of rawPrompts) {
993
- if (typeof value === "string") prompts.push({ value, location: entry.location, baseDirs: entry.baseDirs });
1046
+ var HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
1047
+ var HEADER_VALUE_BREAK = /[\r\n\0]/;
1048
+ var URL_ENV_REFERENCE = /\$\{|\$env:/i;
1049
+ function assertUsable(server) {
1050
+ const refuse = (reason) => {
1051
+ throw RequestError2.invalidParams(void 0, `MCP server ${JSON.stringify(server.name)} refused: ${reason}`);
1052
+ };
1053
+ if ("type" in server && server.type === "http") {
1054
+ if (URL_ENV_REFERENCE.test(server.url)) refuse("its URL contains an environment reference (${...} or $env:)");
1055
+ for (const { name, value } of server.headers ?? []) {
1056
+ if (!HEADER_NAME.test(name)) refuse(`header name ${JSON.stringify(name)} is not a valid HTTP header name`);
1057
+ if (HEADER_VALUE_BREAK.test(value)) refuse(`header ${JSON.stringify(name)} has a CR, LF or NUL in its value`);
1058
+ }
1059
+ } else if ("command" in server) {
1060
+ for (const { name, value } of server.env ?? []) {
1061
+ if (value.includes("\0")) refuse(`env ${JSON.stringify(name)} has a NUL in its value`);
994
1062
  }
995
1063
  }
996
- return { prompts };
997
1064
  }
998
- function getAgentDir() {
999
- const override = getFirstDefinedEnv(["ATOMIC_CODING_AGENT_DIR", "PI_CODING_AGENT_DIR"])?.trim();
1000
- return override ? resolveAtomicPath(override) : join2(homedir(), ".atomic", "agent");
1065
+ function namespaceOf(name) {
1066
+ return name.replace(/-/g, "_");
1001
1067
  }
1002
- function getAgentDirs() {
1003
- const primary = getAgentDir();
1004
- if (hasAgentDirOverride()) return [primary];
1005
- const legacy = join2(homedir(), ".pi", "agent");
1006
- return legacy === primary ? [primary] : [primary, legacy];
1068
+ function uniqueServerName(requested, taken) {
1069
+ let base = requested.replace(/[^A-Za-z0-9_-]/g, "_") || "mcp";
1070
+ if (RESERVED_NAMES.has(base)) base = `${base}_`;
1071
+ let name = base;
1072
+ for (let n = 2; taken.has(namespaceOf(name)); n += 1) name = `${base}_${n}`;
1073
+ taken.add(namespaceOf(name));
1074
+ return name;
1007
1075
  }
1008
- function getProjectConfigDirs(cwd) {
1009
- const resolvedCwd = resolve(cwd);
1010
- return [resolve(resolvedCwd, ".atomic"), resolve(resolvedCwd, ".pi")];
1076
+ function toAtomicMcpServers(servers) {
1077
+ const out = /* @__PURE__ */ new Map();
1078
+ const warnings = [];
1079
+ const taken = /* @__PURE__ */ new Set();
1080
+ for (const server of servers) assertUsable(server);
1081
+ for (const server of servers) {
1082
+ if ("type" in server && server.type === "http") {
1083
+ out.set(uniqueServerName(server.name, taken), {
1084
+ url: server.url,
1085
+ headers: toRecord(server.headers ?? []),
1086
+ exposure: "direct"
1087
+ });
1088
+ } else if ("type" in server && server.type === "sse") {
1089
+ warnings.push(`MCP server "${server.name}" skipped: Atomic does not support the SSE transport`);
1090
+ } else if ("command" in server) {
1091
+ out.set(uniqueServerName(server.name, taken), {
1092
+ command: server.command,
1093
+ args: [...server.args ?? []],
1094
+ env: toRecord(server.env ?? []),
1095
+ exposure: "direct"
1096
+ });
1097
+ } else {
1098
+ const other = server;
1099
+ const type = "type" in other ? String(other.type) : "unknown";
1100
+ warnings.push(`MCP server "${other.name}" skipped: Atomic does not support the ${type} transport`);
1101
+ }
1102
+ }
1103
+ return { servers: Object.fromEntries(out), warnings };
1011
1104
  }
1012
- function getEnableSkillCommands(cwd) {
1013
- const merged = getMergedSettings(cwd);
1014
- const direct = merged.enableSkillCommands;
1015
- if (typeof direct === "boolean") return direct;
1016
- const nested = isObject(merged.skills) ? merged.skills.enableSkillCommands : void 0;
1017
- if (typeof nested === "boolean") return nested;
1018
- return true;
1105
+ function atomicMcpServersForSpawn(servers) {
1106
+ const { servers: mapped, warnings } = toAtomicMcpServers(servers ?? []);
1107
+ for (const warning of warnings) process.stderr.write(`atomic-acp: ${warning}
1108
+ `);
1109
+ return mapped;
1019
1110
  }
1020
- function getQuietStartup(cwd) {
1021
- const merged = getMergedSettings(cwd);
1022
- const direct = merged.quietStartup;
1023
- if (typeof direct === "boolean") return direct;
1024
- const legacy = merged.quietStart;
1025
- if (typeof legacy === "boolean") return legacy;
1026
- return false;
1111
+ function sameMcpServers(a, b) {
1112
+ return JSON.stringify(toAtomicMcpServers(a ?? []).servers) === JSON.stringify(toAtomicMcpServers(b ?? []).servers);
1027
1113
  }
1028
1114
 
1115
+ // src/acp/session.ts
1116
+ import { readFileSync as readFileSync3 } from "fs";
1117
+ import { isAbsolute, resolve as resolvePath } from "path";
1118
+ import { methods as methods2, RequestError as RequestError3 } from "@agentclientprotocol/sdk";
1119
+
1029
1120
  // src/acp/slash-commands.ts
1121
+ import { existsSync as existsSync2, readdirSync, readFileSync as readFileSync2, statSync } from "fs";
1122
+ import { basename, join as join3 } from "path";
1030
1123
  function parseFrontmatter(content) {
1031
1124
  const frontmatter = {};
1032
1125
  if (!content.startsWith("---")) return { frontmatter, content };
@@ -1212,144 +1305,85 @@ function expandSlashCommand(text, fileCommands) {
1212
1305
  return substituteArgs(cmd.content, args);
1213
1306
  }
1214
1307
 
1215
- // src/acp/mcp-servers.ts
1216
- import { RequestError as RequestError2 } from "@agentclientprotocol/sdk";
1217
- var RESERVED_NAMES = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
1218
- function toRecord(entries) {
1219
- return Object.fromEntries(entries.map((entry) => [entry.name, entry.value]));
1308
+ // src/acp/translate/atomic-tools.ts
1309
+ function toolResultToText(result) {
1310
+ if (!result) return "";
1311
+ const details = result.details;
1312
+ const diff = details?.diff;
1313
+ if (typeof diff === "string" && diff.trim()) return diff;
1314
+ const content = result.content;
1315
+ if (Array.isArray(content)) {
1316
+ const texts = content.map((c) => c?.type === "text" && typeof c.text === "string" ? c.text : "").filter(Boolean);
1317
+ if (texts.length) return texts.join("");
1318
+ }
1319
+ 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);
1320
+ const stderr = (typeof details?.stderr === "string" ? details.stderr : void 0) ?? (typeof result?.stderr === "string" ? result.stderr : void 0);
1321
+ 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);
1322
+ if (typeof stdout === "string" && stdout.trim() || typeof stderr === "string" && stderr.trim()) {
1323
+ const parts = [];
1324
+ if (typeof stdout === "string" && stdout.trim()) parts.push(stdout);
1325
+ if (typeof stderr === "string" && stderr.trim()) parts.push(`stderr:
1326
+ ${stderr}`);
1327
+ if (typeof exitCode === "number") parts.push(`exit code: ${exitCode}`);
1328
+ return parts.join("\n\n").trimEnd();
1329
+ }
1330
+ try {
1331
+ return JSON.stringify(result, null, 2);
1332
+ } catch {
1333
+ return String(result);
1334
+ }
1220
1335
  }
1221
- var HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
1222
- var HEADER_VALUE_BREAK = /[\r\n\0]/;
1223
- var URL_ENV_REFERENCE = /\$\{|\$env:/i;
1224
- function assertUsable(server) {
1225
- const refuse = (reason) => {
1226
- throw RequestError2.invalidParams(void 0, `MCP server ${JSON.stringify(server.name)} refused: ${reason}`);
1227
- };
1228
- if ("type" in server && server.type === "http") {
1229
- if (URL_ENV_REFERENCE.test(server.url)) refuse("its URL contains an environment reference (${...} or $env:)");
1230
- for (const { name, value } of server.headers ?? []) {
1231
- if (!HEADER_NAME.test(name)) refuse(`header name ${JSON.stringify(name)} is not a valid HTTP header name`);
1232
- if (HEADER_VALUE_BREAK.test(value)) refuse(`header ${JSON.stringify(name)} has a CR, LF or NUL in its value`);
1233
- }
1234
- } else if ("command" in server) {
1235
- for (const { name, value } of server.env ?? []) {
1236
- if (value.includes("\0")) refuse(`env ${JSON.stringify(name)} has a NUL in its value`);
1237
- }
1336
+
1337
+ // src/acp/translate/bash.ts
1338
+ function isBashTool(name) {
1339
+ return name.toLowerCase() === "bash";
1340
+ }
1341
+ function bashCommand(value) {
1342
+ const record = value;
1343
+ for (const source of [record, record?.args, record?.input, record?.rawInput, record?.toolInput, record?.details]) {
1344
+ const command = source?.command ?? source?.cmd;
1345
+ if (typeof command === "string" && command.trim()) return command;
1346
+ }
1347
+ return void 0;
1348
+ }
1349
+ function bashResultText(value) {
1350
+ const record = value;
1351
+ if (Array.isArray(record?.content)) {
1352
+ const text = record.content.map(
1353
+ (block) => block.type === "text" && typeof block.text === "string" ? block.text : ""
1354
+ ).join("");
1355
+ if (text) return text;
1238
1356
  }
1357
+ const details = record?.details;
1358
+ const stdout = details?.stdout ?? record?.stdout ?? details?.output ?? record?.output;
1359
+ const stderr = details?.stderr ?? record?.stderr;
1360
+ return [stdout, stderr].filter((part) => typeof part === "string" && part.length > 0).join("\n");
1239
1361
  }
1240
- function namespaceOf(name) {
1241
- return name.replace(/-/g, "_");
1362
+ function bashExitCode(value, isError) {
1363
+ const record = value;
1364
+ const code = record?.details?.exitCode ?? record?.exitCode ?? record?.details?.code ?? record?.code;
1365
+ return typeof code === "number" ? code : isError ? 1 : 0;
1242
1366
  }
1243
- function uniqueServerName(requested, taken) {
1244
- let base = requested.replace(/[^A-Za-z0-9_-]/g, "_") || "mcp";
1245
- if (RESERVED_NAMES.has(base)) base = `${base}_`;
1246
- let name = base;
1247
- for (let n = 2; taken.has(namespaceOf(name)); n += 1) name = `${base}_${n}`;
1248
- taken.add(namespaceOf(name));
1249
- return name;
1367
+ function bashOutputDelta(previous, next) {
1368
+ return next.startsWith(previous) ? next.slice(previous.length) : next;
1250
1369
  }
1251
- function toAtomicMcpServers(servers) {
1252
- const out = /* @__PURE__ */ new Map();
1253
- const warnings = [];
1254
- const taken = /* @__PURE__ */ new Set();
1255
- for (const server of servers) assertUsable(server);
1256
- for (const server of servers) {
1257
- if ("type" in server && server.type === "http") {
1258
- out.set(uniqueServerName(server.name, taken), {
1259
- url: server.url,
1260
- headers: toRecord(server.headers ?? []),
1261
- exposure: "direct"
1262
- });
1263
- } else if ("type" in server && server.type === "sse") {
1264
- warnings.push(`MCP server "${server.name}" skipped: Atomic does not support the SSE transport`);
1265
- } else if ("command" in server) {
1266
- out.set(uniqueServerName(server.name, taken), {
1267
- command: server.command,
1268
- args: [...server.args ?? []],
1269
- env: toRecord(server.env ?? []),
1270
- exposure: "direct"
1271
- });
1272
- } else {
1273
- const other = server;
1274
- const type = "type" in other ? String(other.type) : "unknown";
1275
- warnings.push(`MCP server "${other.name}" skipped: Atomic does not support the ${type} transport`);
1276
- }
1277
- }
1278
- return { servers: Object.fromEntries(out), warnings };
1370
+ function bashTerminalContent(id) {
1371
+ return [{ type: "terminal", terminalId: id }];
1279
1372
  }
1280
- function atomicMcpServersForSpawn(servers) {
1281
- const { servers: mapped, warnings } = toAtomicMcpServers(servers ?? []);
1282
- for (const warning of warnings) process.stderr.write(`atomic-acp: ${warning}
1283
- `);
1284
- return mapped;
1373
+ function bashTerminalInfoMeta(id, cwd) {
1374
+ return { terminal_info: { terminal_id: id, cwd } };
1285
1375
  }
1286
- function sameMcpServers(a, b) {
1287
- return JSON.stringify(toAtomicMcpServers(a ?? []).servers) === JSON.stringify(toAtomicMcpServers(b ?? []).servers);
1376
+ function bashTerminalOutputMeta(id, data) {
1377
+ return { terminal_output: { terminal_id: id, data } };
1288
1378
  }
1289
-
1290
- // src/acp/translate/workflow-events.ts
1291
- var TERMINAL_NOTICE_KINDS = /* @__PURE__ */ new Set(["completed", "failed", "blocked", "quit", "cancelled", "killed", "skipped"]);
1292
- function str(value) {
1293
- return typeof value === "string" && value ? value : void 0;
1294
- }
1295
- function record2(value) {
1296
- return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
1297
- }
1298
- function parseWorkflowEvent(ev) {
1299
- if (ev.type === "entry_appended") {
1300
- const entry = record2(ev.entry);
1301
- const data = record2(entry?.data);
1302
- const runId = str(data?.runId);
1303
- if (!entry || !data || !runId) return null;
1304
- switch (entry.customType) {
1305
- case "workflow.run.start":
1306
- return { kind: "run_start", runId, name: str(data.name) };
1307
- case "workflow.run.end":
1308
- return {
1309
- kind: "run_end",
1310
- runId,
1311
- status: str(data.status) ?? "completed",
1312
- ...data.result !== void 0 ? { result: data.result } : {},
1313
- ...str(data.error) ? { error: str(data.error) } : {}
1314
- };
1315
- case "workflow.run.blocked":
1316
- return { kind: "run_end", runId, status: "blocked", ...str(data.error) ? { error: str(data.error) } : {} };
1317
- case "workflow.stage.start":
1318
- return {
1319
- kind: "stage_start",
1320
- runId,
1321
- stageId: str(data.stageId),
1322
- name: str(data.name),
1323
- // Human-input prompt nodes (ctx.ui.input/confirm/select/editor/custom) use `prompt:` replay keys.
1324
- humanInput: str(data.replayKey)?.startsWith("prompt:") ?? false
1325
- };
1326
- case "workflow.stage.end":
1327
- return { kind: "stage_end", runId, stageId: str(data.stageId), status: str(data.status) };
1328
- default:
1329
- return null;
1330
- }
1331
- }
1332
- if (ev.type === "message_end") {
1333
- const message = record2(ev.message);
1334
- if (message?.role !== "custom" || message.customType !== "workflows:lifecycle-notice") return null;
1335
- const details = record2(message.details);
1336
- const runId = str(details?.runId);
1337
- const kind = str(details?.kind);
1338
- if (!runId || !kind || details?.scope === "stage") return null;
1339
- if (kind === "started") return { kind: "run_start", runId, name: str(details?.workflowName) };
1340
- if (TERMINAL_NOTICE_KINDS.has(kind)) return { kind: "run_end", runId, status: kind };
1341
- }
1342
- return null;
1379
+ function bashTerminalExitMeta(id, exitCode) {
1380
+ return { terminal_exit: { terminal_id: id, exit_code: exitCode, signal: null } };
1343
1381
  }
1344
1382
 
1345
1383
  // src/acp/session.ts
1346
1384
  function atomicExitReason(err) {
1347
1385
  return err instanceof AtomicProcessExitError ? `Atomic exited (code=${err.exitCode}, signal=${err.signal})` : `Atomic exited: ${err.message}`;
1348
1386
  }
1349
- var WORKFLOW_FOLLOW_UP_GRACE_MS = 3e3;
1350
- function waitForWorkflowsFromEnv() {
1351
- return !/^(0|false|no)$/i.test(process.env.ATOMIC_ACP_WAIT_FOR_WORKFLOWS?.trim() ?? "");
1352
- }
1353
1387
  function toUsageUpdate(stats) {
1354
1388
  const used = stats?.contextUsage?.tokens;
1355
1389
  const size = stats?.contextUsage?.contextWindow;
@@ -1370,11 +1404,11 @@ function findUniqueLineNumber(text, needle) {
1370
1404
  return line;
1371
1405
  }
1372
1406
  function getMutationPaths(args) {
1373
- const record3 = args;
1374
- const path = record3?.path ?? record3?.file_path;
1407
+ const record = args;
1408
+ const path = record?.path ?? record?.file_path;
1375
1409
  if (typeof path === "string") return [path];
1376
- if (typeof record3?.input !== "string") return [];
1377
- return [...record3.input.matchAll(/^\[(.+)#[0-9a-fA-F]{4}\]\s*$/gm)].map((match) => match[1]);
1410
+ if (typeof record?.input !== "string") return [];
1411
+ return [...record.input.matchAll(/^\[(.+)#[0-9a-fA-F]{4}\]\s*$/gm)].map((match) => match[1]);
1378
1412
  }
1379
1413
  function toToolCallLocations(args, cwd, line) {
1380
1414
  const paths = getMutationPaths(args);
@@ -1409,6 +1443,7 @@ var SessionManager = class {
1409
1443
  const s = this.sessions.get(sessionId);
1410
1444
  if (!s) return Promise.resolve();
1411
1445
  this.sessions.delete(sessionId);
1446
+ s.close();
1412
1447
  try {
1413
1448
  return Promise.resolve(s.proc.dispose?.()).catch(() => {
1414
1449
  });
@@ -1523,13 +1558,11 @@ var AtomicAcpSession = class {
1523
1558
  // Set once Atomic exits; every later prompt to this process fails with it.
1524
1559
  atomicExit = null;
1525
1560
  pendingExtensionDialogs = /* @__PURE__ */ new Map();
1526
- workflowRunNames = /* @__PURE__ */ new Map();
1527
- // Workflow runs started during the current prompt turn. The turn stays open until they end.
1528
- waitForWorkflows;
1529
- workflowFollowUpGraceMs;
1530
- turnWorkflowRuns = /* @__PURE__ */ new Map();
1531
- waitingForWorkflows = false;
1532
- workflowGraceTimer;
1561
+ // The turn whose settlement is under way, so a cancel does not settle it a second time.
1562
+ settlingTurn = null;
1563
+ // Set once the adapter closed this session: nothing more is sent for it.
1564
+ closed = false;
1565
+ detach = [];
1533
1566
  constructor(opts) {
1534
1567
  this.sessionId = opts.sessionId;
1535
1568
  this.cwd = opts.cwd;
@@ -1538,12 +1571,11 @@ var AtomicAcpSession = class {
1538
1571
  this.conn = opts.conn;
1539
1572
  this.clientElicitationSupport = opts.clientElicitationSupport ?? NO_CLIENT_ELICITATION_SUPPORT;
1540
1573
  this.headless = opts.headless ?? false;
1541
- this.waitForWorkflows = opts.waitForWorkflows ?? waitForWorkflowsFromEnv();
1542
- this.workflowFollowUpGraceMs = opts.workflowFollowUpGraceMs ?? WORKFLOW_FOLLOW_UP_GRACE_MS;
1543
1574
  this.fileCommands = opts.fileCommands ?? [];
1544
1575
  this.initialTitlePending = opts.autoTitle ?? false;
1545
- this.proc.onEvent((ev) => this.handleAtomicEvent(ev));
1546
- this.proc.onExit?.((err) => this.handleAtomicExit(err));
1576
+ this.detach.push(this.proc.onEvent((ev) => this.handleAtomicEvent(ev)));
1577
+ const offExit = this.proc.onExit?.((err) => this.handleAtomicExit(err));
1578
+ if (offExit) this.detach.push(offExit);
1547
1579
  }
1548
1580
  setStartupInfo(text) {
1549
1581
  this.startupInfo = text;
@@ -1592,6 +1624,10 @@ var AtomicAcpSession = class {
1592
1624
  });
1593
1625
  return turnPromise;
1594
1626
  }
1627
+ /**
1628
+ * Cancel the running prompt and the queued ones. Like Esc in Atomic, this stops the session's current
1629
+ * run only: subagents and background shells it launched keep running.
1630
+ */
1595
1631
  async cancel() {
1596
1632
  this.cancelRequested = true;
1597
1633
  if (this.turnQueue.length) {
@@ -1607,19 +1643,30 @@ var AtomicAcpSession = class {
1607
1643
  });
1608
1644
  }
1609
1645
  await this.cancelPendingExtensionDialogs();
1610
- for (const [runId, run] of this.turnWorkflowRuns) {
1611
- if (run.done) continue;
1612
- run.done = true;
1613
- run.status = "cancelled";
1614
- run.lines.push("run cancelled");
1615
- this.publishWorkflowRun(runId, run);
1616
- this.emitAgentText(`Quitting workflow "${run.name}" (run ${runId}).`);
1617
- void this.proc.prompt(`/workflow quit ${runId}`, [], "followUp").catch(() => {
1618
- this.emitAgentText(`Could not quit workflow run ${runId}.`);
1619
- });
1646
+ const target = this.pendingTurn;
1647
+ if (!target) {
1648
+ await this.proc.abort();
1649
+ return;
1620
1650
  }
1651
+ await target.accepted;
1652
+ if (this.pendingTurn !== target) return;
1653
+ await this.proc.clearQueue().catch(() => {
1654
+ });
1621
1655
  await this.proc.abort();
1622
- if (this.pendingTurn && this.waitingForWorkflows && !this.inAgentLoop) await this.settleTurn();
1656
+ if (this.pendingTurn === target && this.settlingTurn !== target && !this.inAgentLoop) await this.settleTurn();
1657
+ }
1658
+ /**
1659
+ * The adapter stopped this session's Atomic (a reload, another session, a delete): its prompts end as
1660
+ * cancelled now, and nothing more is sent for it, since a session loaded again keeps the same id.
1661
+ */
1662
+ close() {
1663
+ if (this.closed) return;
1664
+ this.closed = true;
1665
+ for (const off of this.detach.splice(0)) off();
1666
+ const turns = [this.pendingTurn, ...this.turnQueue.splice(0)];
1667
+ this.pendingTurn = null;
1668
+ for (const turn of turns) turn?.resolve("cancelled");
1669
+ void this.cancelPendingExtensionDialogs();
1623
1670
  }
1624
1671
  async setSessionName(name) {
1625
1672
  return this.enqueueTitleUpdate(async () => {
@@ -1662,6 +1709,7 @@ var AtomicAcpSession = class {
1662
1709
  }
1663
1710
  }
1664
1711
  emit(update) {
1712
+ if (this.closed) return;
1665
1713
  this.lastEmit = this.lastEmit.then(
1666
1714
  () => this.conn.notify(methods2.client.session.update, {
1667
1715
  sessionId: this.sessionId,
@@ -1718,21 +1766,24 @@ var AtomicAcpSession = class {
1718
1766
  }
1719
1767
  startTurn(t) {
1720
1768
  this.cancelRequested = false;
1721
- this.resetWorkflowWait();
1722
- this.pendingTurn = { resolve: t.resolve, reject: t.reject };
1769
+ let accept;
1770
+ const pending = {
1771
+ resolve: t.resolve,
1772
+ reject: t.reject,
1773
+ accepted: new Promise((resolve2) => {
1774
+ accept = resolve2;
1775
+ })
1776
+ };
1777
+ this.pendingTurn = pending;
1723
1778
  void this.maybeAutoTitle(t.title);
1724
1779
  this.emit({
1725
1780
  sessionUpdate: "session_info_update",
1726
1781
  _meta: { atomicAcp: { queueDepth: this.turnQueue.length, running: true } }
1727
1782
  });
1728
- const pending = this.pendingTurn;
1729
1783
  this.proc.prompt(t.message, t.images, "followUp").then(async (disposition) => {
1784
+ accept();
1730
1785
  if (disposition !== "handled" || this.pendingTurn !== pending) return;
1731
1786
  if (this.inAgentLoop) this.backgroundTurn = true;
1732
- if (this.shouldWaitForWorkflows()) {
1733
- this.beginWorkflowWait();
1734
- return;
1735
- }
1736
1787
  await this.publishContextUsage();
1737
1788
  if (this.pendingTurn !== pending) return;
1738
1789
  pending.resolve(this.cancelRequested ? "cancelled" : "end_turn");
@@ -1746,6 +1797,7 @@ var AtomicAcpSession = class {
1746
1797
  });
1747
1798
  }
1748
1799
  }).catch((err) => {
1800
+ accept();
1749
1801
  void this.finishActiveAndQueuedFromFailure(err);
1750
1802
  });
1751
1803
  }
@@ -1753,18 +1805,13 @@ var AtomicAcpSession = class {
1753
1805
  await this.cancelPendingExtensionDialogs();
1754
1806
  await this.flushEmits();
1755
1807
  if (!this.pendingTurn && this.turnQueue.length === 0) return;
1756
- const failure = maybeAuthRequiredError(err) ?? (this.cancelRequested ? null : this.promptFailure(err));
1808
+ const failure = maybeAuthRequiredError(err) ?? this.promptFailure(err);
1757
1809
  const queued = this.turnQueue.splice(0);
1758
- if (failure) {
1759
- this.pendingTurn?.reject(failure);
1760
- for (const queuedTurn of queued) queuedTurn.reject(failure);
1761
- } else {
1762
- this.pendingTurn?.resolve("cancelled");
1763
- for (const queuedTurn of queued) queuedTurn.resolve("cancelled");
1764
- }
1810
+ if (this.cancelRequested && !maybeAuthRequiredError(err)) this.pendingTurn?.resolve("cancelled");
1811
+ else this.pendingTurn?.reject(failure);
1812
+ for (const queuedTurn of queued) queuedTurn.reject(failure);
1765
1813
  this.pendingTurn = null;
1766
1814
  this.inAgentLoop = false;
1767
- this.resetWorkflowWait();
1768
1815
  this.emit({
1769
1816
  sessionUpdate: "session_info_update",
1770
1817
  _meta: { atomicAcp: { queueDepth: 0, running: false } }
@@ -1782,7 +1829,7 @@ var AtomicAcpSession = class {
1782
1829
  if (err instanceof RequestError3) return err;
1783
1830
  return RequestError3.internalError(void 0, err instanceof Error ? err.message : String(err));
1784
1831
  }
1785
- /** Close every tool call and workflow run still open, so none is left in progress after Atomic dies. */
1832
+ /** Close every tool call still open, so none is left in progress after Atomic dies. */
1786
1833
  failOpenToolCalls(reason) {
1787
1834
  for (const toolCallId of this.currentToolCalls.keys()) {
1788
1835
  const bash = this.bashToolCallIds.has(toolCallId);
@@ -1800,13 +1847,6 @@ var AtomicAcpSession = class {
1800
1847
  this.bashOutputSnapshots.clear();
1801
1848
  this.fileSnapshots.clear();
1802
1849
  this.fileMutationToolCallIds.clear();
1803
- for (const [runId, run] of this.turnWorkflowRuns) {
1804
- if (run.done) continue;
1805
- run.done = true;
1806
- run.status = "failed";
1807
- run.lines.push(reason);
1808
- this.publishWorkflowRun(runId, run);
1809
- }
1810
1850
  }
1811
1851
  handleAtomicExit(err) {
1812
1852
  this.atomicExit ??= err;
@@ -1889,12 +1929,13 @@ var AtomicAcpSession = class {
1889
1929
  await completion;
1890
1930
  }
1891
1931
  async settleTurn() {
1892
- this.resetWorkflowWait();
1932
+ this.settlingTurn = this.pendingTurn;
1893
1933
  await this.cancelPendingExtensionDialogs();
1894
1934
  await this.publishContextUsage();
1895
1935
  const reason = this.cancelRequested ? "cancelled" : "end_turn";
1896
1936
  this.pendingTurn?.resolve(reason);
1897
1937
  this.pendingTurn = null;
1938
+ this.settlingTurn = null;
1898
1939
  this.inAgentLoop = false;
1899
1940
  const next = this.turnQueue.shift();
1900
1941
  if (next) {
@@ -1910,117 +1951,8 @@ var AtomicAcpSession = class {
1910
1951
  });
1911
1952
  }
1912
1953
  }
1913
- shouldWaitForWorkflows() {
1914
- if (!this.waitForWorkflows || this.cancelRequested) return false;
1915
- return [...this.turnWorkflowRuns.values()].some((run) => !run.done);
1916
- }
1917
- beginWorkflowWait() {
1918
- if (this.waitingForWorkflows) return;
1919
- this.waitingForWorkflows = true;
1920
- const open = [...this.turnWorkflowRuns].filter(([, run]) => !run.done);
1921
- const list = open.map(([runId, run]) => `"${run.name}" (run ${runId})`).join(", ");
1922
- this.emitAgentText(`Waiting for workflow ${list} to finish.`);
1923
- }
1924
- clearWorkflowGraceTimer() {
1925
- if (this.workflowGraceTimer) clearTimeout(this.workflowGraceTimer);
1926
- this.workflowGraceTimer = void 0;
1927
- }
1928
- resetWorkflowWait() {
1929
- this.clearWorkflowGraceTimer();
1930
- this.turnWorkflowRuns.clear();
1931
- this.waitingForWorkflows = false;
1932
- }
1933
- /** Once every run has ended, end the turn after Atomic's follow-up turn, or after a short grace without one. */
1934
- maybeEndWorkflowWait() {
1935
- if (!this.waitingForWorkflows || !this.pendingTurn || this.shouldWaitForWorkflows()) return;
1936
- if (this.inAgentLoop) return;
1937
- this.clearWorkflowGraceTimer();
1938
- this.workflowGraceTimer = setTimeout(() => {
1939
- this.workflowGraceTimer = void 0;
1940
- if (this.waitingForWorkflows && this.pendingTurn && !this.inAgentLoop) void this.settleTurn();
1941
- }, this.workflowFollowUpGraceMs);
1942
- }
1943
- publishWorkflowRun(runId, run) {
1944
- const status = !run.done ? "in_progress" : run.status === "completed" || run.status === "skipped" ? "completed" : "failed";
1945
- this.emit({
1946
- sessionUpdate: "tool_call_update",
1947
- toolCallId: `workflow-run-${runId}`,
1948
- status,
1949
- content: [{ type: "content", content: { type: "text", text: run.lines.join("\n") } }]
1950
- });
1951
- }
1952
- trackWorkflowEvent(event) {
1953
- if (event.kind === "run_start") {
1954
- if (!this.waitForWorkflows || !this.pendingTurn || this.turnWorkflowRuns.has(event.runId)) return;
1955
- const name = event.name ?? this.workflowRunNames.get(event.runId) ?? "workflow";
1956
- this.turnWorkflowRuns.set(event.runId, {
1957
- name,
1958
- done: false,
1959
- lines: [`run ${event.runId} started`],
1960
- stageNames: /* @__PURE__ */ new Map(),
1961
- resultReported: false
1962
- });
1963
- this.emit({
1964
- sessionUpdate: "tool_call",
1965
- toolCallId: `workflow-run-${event.runId}`,
1966
- title: `Workflow ${name}`,
1967
- kind: "other",
1968
- status: "in_progress",
1969
- rawInput: { runId: event.runId, workflow: name }
1970
- });
1971
- return;
1972
- }
1973
- const run = this.turnWorkflowRuns.get(event.runId);
1974
- if (!run) return;
1975
- if (event.kind === "stage_start") {
1976
- const stage = event.name ?? event.stageId ?? "stage";
1977
- if (event.stageId) run.stageNames.set(event.stageId, stage);
1978
- run.lines.push(`stage ${stage} started`);
1979
- if (event.humanInput && !run.done) {
1980
- run.done = true;
1981
- run.status = "awaiting_input";
1982
- run.lines.push(`waiting for input at stage ${stage}`);
1983
- if (!this.headless) {
1984
- this.emitAgentText(
1985
- `Workflow "${run.name}" is waiting for input (stage ${stage}, run ${event.runId}). This turn won't wait for it; reply here to answer it.`
1986
- );
1987
- }
1988
- }
1989
- } else if (event.kind === "stage_end") {
1990
- const stage = (event.stageId && run.stageNames.get(event.stageId)) ?? event.stageId ?? "stage";
1991
- run.lines.push(`stage ${stage} ${event.status ?? "ended"}`);
1992
- } else {
1993
- if (!run.done || run.status === "awaiting_input") {
1994
- run.done = true;
1995
- run.status = event.status;
1996
- run.lines.push(`run ${event.status}`);
1997
- }
1998
- if (event.result !== void 0 && !run.resultReported) {
1999
- run.resultReported = true;
2000
- run.lines.push(`result: ${JSON.stringify(event.result)}`);
2001
- }
2002
- if (event.error) run.lines.push(`error: ${event.error}`);
2003
- }
2004
- this.publishWorkflowRun(event.runId, run);
2005
- this.maybeEndWorkflowWait();
2006
- }
2007
- handleWorkflowEvent(event) {
2008
- if (event.kind === "run_start" && event.name) this.workflowRunNames.set(event.runId, event.name);
2009
- this.trackWorkflowEvent(event);
2010
- if (event.kind === "stage_start" && event.humanInput && this.headless) {
2011
- const name = this.workflowRunNames.get(event.runId) ?? event.runId;
2012
- this.emitAgentText(
2013
- `No person is available to answer workflow "${name}" (stage ${event.name ?? event.stageId ?? "input"}), so run ${event.runId} is being quit.`
2014
- );
2015
- void this.proc.prompt(`/workflow quit ${event.runId}`, [], "followUp").catch(() => {
2016
- this.emitAgentText(`Could not quit workflow run ${event.runId}.`);
2017
- });
2018
- }
2019
- }
2020
1954
  handleAtomicEvent(ev) {
2021
1955
  const type = String(ev.type ?? "");
2022
- const workflowEvent = parseWorkflowEvent(ev);
2023
- if (workflowEvent) this.handleWorkflowEvent(workflowEvent);
2024
1956
  switch (type) {
2025
1957
  case "session_info_changed": {
2026
1958
  const name = ev.name;
@@ -2037,6 +1969,11 @@ var AtomicAcpSession = class {
2037
1969
  }
2038
1970
  break;
2039
1971
  }
1972
+ case "message_start": {
1973
+ const role = ev.message?.role;
1974
+ if (role === "user" && this.backgroundTurn && this.pendingTurn) this.backgroundTurn = false;
1975
+ break;
1976
+ }
2040
1977
  case "message_end": {
2041
1978
  const message = ev.message;
2042
1979
  if (message?.role === "custom" && message.display === true) {
@@ -2089,7 +2026,7 @@ var AtomicAcpSession = class {
2089
2026
  this.emit({
2090
2027
  sessionUpdate: "tool_call",
2091
2028
  toolCallId,
2092
- title: toolTitle(toolName, rawInput),
2029
+ title: toolName,
2093
2030
  kind: toToolKind(toolName),
2094
2031
  status,
2095
2032
  locations,
@@ -2099,7 +2036,6 @@ var AtomicAcpSession = class {
2099
2036
  this.emit({
2100
2037
  sessionUpdate: "tool_call_update",
2101
2038
  toolCallId,
2102
- ...toolName === "workflow" ? { title: toolTitle(toolName, rawInput), kind: toToolKind(toolName) } : {},
2103
2039
  status,
2104
2040
  locations,
2105
2041
  rawInput
@@ -2139,7 +2075,7 @@ var AtomicAcpSession = class {
2139
2075
  this.emit({
2140
2076
  sessionUpdate: "tool_call",
2141
2077
  toolCallId,
2142
- title: toolTitle(toolName, args),
2078
+ title: toolName,
2143
2079
  kind: toToolKind(toolName),
2144
2080
  status: "in_progress",
2145
2081
  locations,
@@ -2150,7 +2086,6 @@ var AtomicAcpSession = class {
2150
2086
  this.emit({
2151
2087
  sessionUpdate: "tool_call_update",
2152
2088
  toolCallId,
2153
- ...toolName === "workflow" ? { title: toolTitle(toolName, args), kind: toToolKind(toolName) } : {},
2154
2089
  status: "in_progress",
2155
2090
  locations,
2156
2091
  rawInput: args
@@ -2259,7 +2194,6 @@ var AtomicAcpSession = class {
2259
2194
  case "agent_start": {
2260
2195
  this.inAgentLoop = true;
2261
2196
  this.backgroundTurn = !this.pendingTurn;
2262
- this.clearWorkflowGraceTimer();
2263
2197
  break;
2264
2198
  }
2265
2199
  case "turn_end": {
@@ -2273,12 +2207,6 @@ var AtomicAcpSession = class {
2273
2207
  if (this.backgroundTurn || !this.pendingTurn) {
2274
2208
  this.backgroundTurn = false;
2275
2209
  this.inAgentLoop = false;
2276
- this.maybeEndWorkflowWait();
2277
- break;
2278
- }
2279
- if (this.shouldWaitForWorkflows()) {
2280
- this.inAgentLoop = false;
2281
- this.beginWorkflowWait();
2282
2210
  break;
2283
2211
  }
2284
2212
  void this.settleTurn();
@@ -2300,14 +2228,6 @@ function formatAutoRetryMessage(ev) {
2300
2228
  if (delayMs > 0 && delaySeconds === 0) delaySeconds = 1;
2301
2229
  return `Retrying (attempt ${attempt}/${maxAttempts}, waiting ${delaySeconds}s)...`;
2302
2230
  }
2303
- function toolTitle(name, input2) {
2304
- if (name !== "workflow") return name;
2305
- const args = input2;
2306
- const details = [args?.action ?? (args?.workflow ? "run" : void 0), args?.workflow ?? args?.runId].filter(
2307
- (value) => typeof value === "string" && value
2308
- );
2309
- return details.length ? `workflow: ${details.join(" ")}` : name;
2310
- }
2311
2231
  function toToolKind(toolName) {
2312
2232
  switch (toolName) {
2313
2233
  case "read":
@@ -2354,7 +2274,8 @@ function loadFile(path) {
2354
2274
  }
2355
2275
  function saveFile(path, data) {
2356
2276
  ensureParentDir(path);
2357
- writeFileSync2(path, JSON.stringify(data, null, 2) + "\n", "utf-8");
2277
+ writeFileSync2(path, `${JSON.stringify(data, null, 2)}
2278
+ `, "utf-8");
2358
2279
  }
2359
2280
  var SessionStore = class {
2360
2281
  path;
@@ -2387,99 +2308,6 @@ var SessionStore = class {
2387
2308
  }
2388
2309
  };
2389
2310
 
2390
- // src/acp/headless.ts
2391
- function isHeadlessFromEnv(env = process.env) {
2392
- return /^(1|true)$/i.test(env.ATOMIC_ACP_HEADLESS?.trim() ?? "");
2393
- }
2394
-
2395
- // src/acp/translate/prompt.ts
2396
- function promptToSessionTitle(blocks) {
2397
- const normalized = blocks.filter((block) => block.type === "text").map((block) => block.text).join(" ").replace(/\s+/gu, " ").trim();
2398
- return normalized ? Array.from(normalized).slice(0, 80).join("") : null;
2399
- }
2400
- function promptToAtomicMessage(blocks) {
2401
- let message = "";
2402
- const images = [];
2403
- for (const b of blocks) {
2404
- switch (b.type) {
2405
- case "text":
2406
- message += b.text;
2407
- break;
2408
- case "resource_link":
2409
- message += `
2410
- [Context] ${b.uri}`;
2411
- break;
2412
- case "image": {
2413
- images.push({
2414
- type: "image",
2415
- mimeType: b.mimeType,
2416
- data: b.data
2417
- });
2418
- break;
2419
- }
2420
- case "resource": {
2421
- const r = b.resource;
2422
- const uri = typeof r?.uri === "string" ? r.uri : "(unknown)";
2423
- if (typeof r?.text === "string") {
2424
- const mime = typeof r?.mimeType === "string" ? r.mimeType : "text/plain";
2425
- message += `
2426
- [Embedded Context] ${uri} (${mime})
2427
- ${r.text}`;
2428
- } else if (typeof r?.blob === "string") {
2429
- const mime = typeof r?.mimeType === "string" ? r.mimeType : "application/octet-stream";
2430
- const bytes = Buffer.byteLength(r.blob, "base64");
2431
- message += `
2432
- [Embedded Context] ${uri} (${mime}, ${bytes} bytes)`;
2433
- } else {
2434
- message += `
2435
- [Embedded Context] ${uri}`;
2436
- }
2437
- break;
2438
- }
2439
- case "audio": {
2440
- const bytes = Buffer.byteLength(b.data, "base64");
2441
- message += `
2442
- [Audio] (${b.mimeType}, ${bytes} bytes) not supported by atomic-acp`;
2443
- break;
2444
- }
2445
- default:
2446
- break;
2447
- }
2448
- }
2449
- return { message, images };
2450
- }
2451
-
2452
- // src/acp/atomic-sessions.ts
2453
- function str2(value) {
2454
- return typeof value === "string" ? value : void 0;
2455
- }
2456
- function isoDate(value) {
2457
- const date = typeof value === "string" ? new Date(value) : null;
2458
- return date && Number.isFinite(date.getTime()) ? date.toISOString() : null;
2459
- }
2460
- function sessionTitle(info, messageCount) {
2461
- const name = str2(info.name)?.trim();
2462
- if (name || info.hasName === true) return name ?? "";
2463
- const firstMessage = messageCount > 0 ? str2(info.firstMessage) : void 0;
2464
- return firstMessage ? promptToSessionTitle([{ type: "text", text: firstMessage }]) : null;
2465
- }
2466
- function parseAtomicSessionList(data) {
2467
- const sessions = data?.sessions;
2468
- if (!Array.isArray(sessions)) return [];
2469
- const items = [];
2470
- for (const raw of sessions) {
2471
- const info = raw ?? {};
2472
- const sessionId = str2(info.id);
2473
- const cwd = str2(info.cwd);
2474
- if (sessionId === void 0 || !cwd) continue;
2475
- const messageCount = typeof info.messageCount === "number" ? info.messageCount : 0;
2476
- const title = sessionTitle(info, messageCount);
2477
- if (messageCount === 0 && title === null && info.summary === void 0) continue;
2478
- items.push({ sessionId, cwd, title, updatedAt: isoDate(info.modified) });
2479
- }
2480
- return items.sort((a, b) => (b.updatedAt ?? "").localeCompare(a.updatedAt ?? ""));
2481
- }
2482
-
2483
2311
  // src/acp/translate/atomic-messages.ts
2484
2312
  function normalizeAtomicMessageText(content) {
2485
2313
  if (typeof content === "string") return content;
@@ -2491,50 +2319,12 @@ function normalizeAtomicAssistantText(content) {
2491
2319
  return content.map((c) => c?.type === "text" && typeof c.text === "string" ? c.text : "").filter(Boolean).join("");
2492
2320
  }
2493
2321
 
2494
- // src/acp/atomic-commands.ts
2495
- function describeFallback(c) {
2496
- const source = typeof c.source === "string" ? c.source : "";
2497
- const location = typeof c.location === "string" ? c.location : "";
2498
- const parts = [];
2499
- if (source) parts.push(source);
2500
- if (location) parts.push(location);
2501
- return parts.length ? `(${parts.join(":")})` : "(command)";
2502
- }
2503
- function toAvailableCommandsFromAtomicGetCommands(data, opts) {
2504
- const enableSkillCommands = opts?.enableSkillCommands ?? true;
2505
- const includeExtensionCommands = opts?.includeExtensionCommands ?? true;
2506
- const root = data;
2507
- const commandsRaw = Array.isArray(root?.commands) ? root.commands : Array.isArray(root?.data?.commands) ? root.data.commands : [];
2508
- const out = [];
2509
- for (const c of commandsRaw) {
2510
- const name = typeof c?.name === "string" ? c.name.trim() : "";
2511
- if (!name) continue;
2512
- const source = typeof c?.source === "string" ? c.source : "";
2513
- if (!includeExtensionCommands && source === "extension") continue;
2514
- if (!enableSkillCommands && name.startsWith("skill:")) continue;
2515
- const desc = typeof c?.description === "string" ? c.description.trim() : "";
2516
- const usage = desc.match(/Usage:\s*\/\S+\s+(.+)$/i)?.[1];
2517
- out.push({
2518
- name,
2519
- description: desc || describeFallback(c),
2520
- ...usage ? { input: { hint: usage } } : {}
2521
- });
2522
- }
2523
- return { commands: out, raw: commandsRaw };
2524
- }
2525
-
2526
2322
  // src/acp/agent.ts
2527
- import { isAbsolute as isAbsolute2 } from "path";
2528
- import { existsSync as existsSync3, readFileSync as readFileSync5, realpathSync, readdirSync as readdirSync2, statSync as statSync2 } from "fs";
2529
- import { join as join5, dirname as dirname2, basename as basename2 } from "path";
2530
- import { spawnSync } from "child_process";
2531
2323
  import { fileURLToPath } from "url";
2532
2324
  var MODEL_CONFIG_ID = "model";
2533
2325
  var THOUGHT_LEVEL_CONFIG_ID = "thought_level";
2534
2326
  function builtinAvailableCommands() {
2535
2327
  return [
2536
- { name: "workflow-runs", description: "List retained workflow runs", input: { hint: "[status]" } },
2537
- { name: "workflow-run", description: "Show a workflow run summary", input: { hint: "<runId>" } },
2538
2328
  {
2539
2329
  name: "compact",
2540
2330
  description: "Manually compact the session context",
@@ -2615,7 +2405,8 @@ var AtomicAcpAgent = class {
2615
2405
  try {
2616
2406
  proc = await AtomicRpcProcess.spawn({ cwd, atomicCommand: process.env.ATOMIC_ACP_ATOMIC_COMMAND });
2617
2407
  } catch (error) {
2618
- if (error instanceof AtomicRpcSpawnError) throw RequestError4.internalError({ code: error.code }, error.message);
2408
+ if (error instanceof AtomicRpcSpawnError)
2409
+ throw RequestError4.internalError({ code: error.code }, error.message);
2619
2410
  throw error;
2620
2411
  }
2621
2412
  try {
@@ -2667,7 +2458,8 @@ var AtomicAcpAgent = class {
2667
2458
  async restoreSessionImpl(sessionId, opts) {
2668
2459
  const existing = this.sessions.maybeGet(sessionId);
2669
2460
  if (existing) {
2670
- if (opts?.cwd && existing.cwd !== opts.cwd) throw RequestError4.invalidParams(`Unknown sessionId: ${sessionId}`);
2461
+ if (opts?.cwd && existing.cwd !== opts.cwd)
2462
+ throw RequestError4.invalidParams(`Unknown sessionId: ${sessionId}`);
2671
2463
  const sameServers = !opts?.mcpServers || sameMcpServers(existing.mcpServers, opts.mcpServers);
2672
2464
  if (sameServers && !existing.proc.hasExited) return existing;
2673
2465
  this.sessions.close(sessionId);
@@ -2687,7 +2479,8 @@ var AtomicAcpAgent = class {
2687
2479
  answersQuestionnaires: this.clientElicitationSupport.form
2688
2480
  });
2689
2481
  } catch (error) {
2690
- if (error instanceof AtomicRpcSpawnError) throw RequestError4.internalError({ code: error.code }, error.message);
2482
+ if (error instanceof AtomicRpcSpawnError)
2483
+ throw RequestError4.internalError({ code: error.code }, error.message);
2691
2484
  throw error;
2692
2485
  }
2693
2486
  try {
@@ -2827,7 +2620,8 @@ var AtomicAcpAgent = class {
2827
2620
  }
2828
2621
  const quietStartup = getQuietStartup(params.cwd);
2829
2622
  const updateNotice = buildUpdateNotice();
2830
- const preludeText = quietStartup ? updateNotice ? updateNotice + "\n" : "" : buildStartupInfo({
2623
+ const preludeText = quietStartup ? updateNotice ? `${updateNotice}
2624
+ ` : "" : buildStartupInfo({
2831
2625
  cwd: params.cwd,
2832
2626
  fileCommands,
2833
2627
  updateNotice
@@ -2887,27 +2681,6 @@ var AtomicAcpAgent = class {
2887
2681
  const cmd = space === -1 ? trimmed.slice(1) : trimmed.slice(1, space);
2888
2682
  const argsString = space === -1 ? "" : trimmed.slice(space + 1);
2889
2683
  const args = parseCommandArgs(argsString);
2890
- if (cmd === "workflow-runs" || cmd === "workflow-run") {
2891
- let text;
2892
- if (args.length > 1 || cmd === "workflow-run" && !args[0]) {
2893
- text = cmd === "workflow-run" ? "Usage: /workflow-run <runId>" : "Usage: /workflow-runs [status]";
2894
- } else {
2895
- try {
2896
- const data = cmd === "workflow-runs" ? await session.proc.listWorkflowRuns(args[0]) : await session.proc.getWorkflowRunSummary(args[0]);
2897
- text = renderWorkflowHistory(data, cmd === "workflow-runs");
2898
- } catch (error) {
2899
- text = `Could not read workflow history: ${error instanceof Error ? error.message : String(error)}`;
2900
- }
2901
- }
2902
- await this.conn.notify(methods3.client.session.update, {
2903
- sessionId: session.sessionId,
2904
- update: {
2905
- sessionUpdate: "agent_message_chunk",
2906
- content: { type: "text", text }
2907
- }
2908
- });
2909
- return { stopReason: "end_turn" };
2910
- }
2911
2684
  if (cmd === "compact") {
2912
2685
  const customInstructions = args.join(" ").trim() || void 0;
2913
2686
  const res = await session.proc.compact(customInstructions);
@@ -3121,7 +2894,9 @@ ${JSON.stringify(stats, null, 2)}`;
3121
2894
  return { stopReason: "end_turn" };
3122
2895
  }
3123
2896
  const maxChars = 2e4;
3124
- if (text.length > maxChars) text = text.slice(0, maxChars) + "\n\n...(truncated)...";
2897
+ if (text.length > maxChars) text = `${text.slice(0, maxChars)}
2898
+
2899
+ ...(truncated)...`;
3125
2900
  await this.conn.notify(methods3.client.session.update, {
3126
2901
  sessionId: session.sessionId,
3127
2902
  update: {
@@ -3139,7 +2914,10 @@ ${JSON.stringify(stats, null, 2)}`;
3139
2914
  sessionId: session.sessionId,
3140
2915
  update: {
3141
2916
  sessionUpdate: "agent_message_chunk",
3142
- content: { type: "text", text: "Nothing to export yet (no session messages). Send a prompt first." }
2917
+ content: {
2918
+ type: "text",
2919
+ text: "Nothing to export yet (no session messages). Send a prompt first."
2920
+ }
3143
2921
  }
3144
2922
  });
3145
2923
  return { stopReason: "end_turn" };
@@ -3485,7 +3263,10 @@ async function getThinkingState(proc, pre) {
3485
3263
  }
3486
3264
  async function getSessionConfiguration(proc, pre) {
3487
3265
  const state = pre?.state ?? await proc.getState();
3488
- const [models, modes] = await Promise.all([getModelState(proc, { ...pre, state }), getThinkingState(proc, { state })]);
3266
+ const [models, modes] = await Promise.all([
3267
+ getModelState(proc, { ...pre, state }),
3268
+ getThinkingState(proc, { state })
3269
+ ]);
3489
3270
  const configOptions = [
3490
3271
  {
3491
3272
  type: "select",
@@ -3744,7 +3525,8 @@ function buildStartupInfo(opts) {
3744
3525
  md.push(opts.updateNotice);
3745
3526
  md.push("");
3746
3527
  }
3747
- return md.join("\n").trim() + "\n";
3528
+ return `${md.join("\n").trim()}
3529
+ `;
3748
3530
  }
3749
3531
  function readNearestPackageJson(metaUrl) {
3750
3532
  try {