@bastani/atomic-acp 0.0.14 → 0.0.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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() {
@@ -382,6 +77,27 @@ function parseAtomicExtraArgs(argv, env) {
382
77
  const fromArgv = separator < 0 ? [] : argv.slice(separator + 1).map((arg) => validateAtomicArg(arg, "arguments after --"));
383
78
  return [...fromEnv, ...fromArgv];
384
79
  }
80
+ var EXCLUDE_TOOLS_FLAGS = /* @__PURE__ */ new Set(["--exclude-tools", "-xt"]);
81
+ function withExcludedTool(extraArgs, tool) {
82
+ const args = [...extraArgs];
83
+ const joined = (list) => list.split(",").includes(tool) ? list : list ? `${list},${tool}` : tool;
84
+ for (let index = args.length - 1; index >= 0; index--) {
85
+ const arg = args[index];
86
+ if (arg.startsWith("--exclude-tools=")) {
87
+ args[index] = `--exclude-tools=${joined(arg.slice("--exclude-tools=".length))}`;
88
+ return args;
89
+ }
90
+ if (EXCLUDE_TOOLS_FLAGS.has(arg) && index + 1 < args.length) {
91
+ args[index + 1] = joined(args[index + 1]);
92
+ return args;
93
+ }
94
+ }
95
+ return [...args, "--exclude-tools", tool];
96
+ }
97
+
98
+ // src/atomic-rpc/process.ts
99
+ import { spawn } from "child_process";
100
+ import crossSpawn from "cross-spawn";
385
101
 
386
102
  // src/atomic-rpc/adapter-extension.ts
387
103
  import { randomBytes } from "crypto";
@@ -575,7 +291,7 @@ var AtomicRpcProcess = class _AtomicRpcProcess {
575
291
  ...params.headless ? { askUserQuestionUnavailable: NO_PERSON_FOR_ASK_USER_QUESTION } : {}
576
292
  });
577
293
  if (adapterExtension) args.push("-e", adapterExtension.path);
578
- args.push(...extraArgs);
294
+ args.push(...params.headless ? withExcludedTool(extraArgs, "ask_user_question") : extraArgs);
579
295
  const start = shouldUseShellForAtomicCommand(cmd) ? crossSpawn : spawn;
580
296
  let child;
581
297
  try {
@@ -785,7 +501,8 @@ var AtomicRpcProcess = class _AtomicRpcProcess {
785
501
  */
786
502
  async startPendingRecovery(reason) {
787
503
  const res = await this.request({ type: "start_pending_recovery", reason });
788
- if (!res.success) throw new Error(`Atomic start_pending_recovery failed: ${res.error ?? JSON.stringify(res.data)}`);
504
+ if (!res.success)
505
+ throw new Error(`Atomic start_pending_recovery failed: ${res.error ?? JSON.stringify(res.data)}`);
789
506
  return res.data;
790
507
  }
791
508
  async getMessages() {
@@ -799,7 +516,8 @@ var AtomicRpcProcess = class _AtomicRpcProcess {
799
516
  return res.data;
800
517
  }
801
518
  writeJsonLine(value) {
802
- const line = JSON.stringify(value) + "\n";
519
+ const line = `${JSON.stringify(value)}
520
+ `;
803
521
  return new Promise((resolve2, reject) => {
804
522
  try {
805
523
  this.child.stdin.write(line, (err) => {
@@ -862,39 +580,126 @@ var AtomicRpcProcess = class _AtomicRpcProcess {
862
580
  }
863
581
  };
864
582
 
865
- // src/acp/translate/atomic-tools.ts
866
- function toolResultToText(result) {
867
- if (!result) return "";
868
- const details = result.details;
869
- const diff = details?.diff;
870
- if (typeof diff === "string" && diff.trim()) return diff;
871
- const content = result.content;
872
- if (Array.isArray(content)) {
873
- const texts = content.map((c) => c?.type === "text" && typeof c.text === "string" ? c.text : "").filter(Boolean);
874
- if (texts.length) return texts.join("");
583
+ // src/acp/atomic-commands.ts
584
+ function describeFallback(c) {
585
+ const source = typeof c.source === "string" ? c.source : "";
586
+ const location = typeof c.location === "string" ? c.location : "";
587
+ const parts = [];
588
+ if (source) parts.push(source);
589
+ if (location) parts.push(location);
590
+ return parts.length ? `(${parts.join(":")})` : "(command)";
591
+ }
592
+ function toAvailableCommandsFromAtomicGetCommands(data, opts) {
593
+ const enableSkillCommands = opts?.enableSkillCommands ?? true;
594
+ const includeExtensionCommands = opts?.includeExtensionCommands ?? true;
595
+ const root = data;
596
+ const commandsRaw = Array.isArray(root?.commands) ? root.commands : Array.isArray(root?.data?.commands) ? root.data.commands : [];
597
+ const out = [];
598
+ for (const c of commandsRaw) {
599
+ const name = typeof c?.name === "string" ? c.name.trim() : "";
600
+ if (!name) continue;
601
+ const source = typeof c?.source === "string" ? c.source : "";
602
+ if (!includeExtensionCommands && source === "extension") continue;
603
+ if (!enableSkillCommands && name.startsWith("skill:")) continue;
604
+ const desc = typeof c?.description === "string" ? c.description.trim() : "";
605
+ const usage = desc.match(/Usage:\s*\/\S+\s+(.+)$/i)?.[1];
606
+ out.push({
607
+ name,
608
+ description: desc || describeFallback(c),
609
+ ...usage ? { input: { hint: usage } } : {}
610
+ });
875
611
  }
876
- 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);
877
- const stderr = (typeof details?.stderr === "string" ? details.stderr : void 0) ?? (typeof result?.stderr === "string" ? result.stderr : void 0);
878
- 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);
879
- if (typeof stdout === "string" && stdout.trim() || typeof stderr === "string" && stderr.trim()) {
880
- const parts = [];
881
- if (typeof stdout === "string" && stdout.trim()) parts.push(stdout);
882
- if (typeof stderr === "string" && stderr.trim()) parts.push(`stderr:
883
- ${stderr}`);
884
- if (typeof exitCode === "number") parts.push(`exit code: ${exitCode}`);
885
- return parts.join("\n\n").trimEnd();
612
+ return { commands: out, raw: commandsRaw };
613
+ }
614
+
615
+ // src/acp/translate/prompt.ts
616
+ function promptToSessionTitle(blocks) {
617
+ const normalized = blocks.filter((block) => block.type === "text").map((block) => block.text).join(" ").replace(/\s+/gu, " ").trim();
618
+ return normalized ? Array.from(normalized).slice(0, 80).join("") : null;
619
+ }
620
+ function promptToAtomicMessage(blocks) {
621
+ let message = "";
622
+ const images = [];
623
+ for (const b of blocks) {
624
+ switch (b.type) {
625
+ case "text":
626
+ message += b.text;
627
+ break;
628
+ case "resource_link":
629
+ message += `
630
+ [Context] ${b.uri}`;
631
+ break;
632
+ case "image": {
633
+ images.push({
634
+ type: "image",
635
+ mimeType: b.mimeType,
636
+ data: b.data
637
+ });
638
+ break;
639
+ }
640
+ case "resource": {
641
+ const r = b.resource;
642
+ const uri = typeof r?.uri === "string" ? r.uri : "(unknown)";
643
+ if (typeof r?.text === "string") {
644
+ const mime = typeof r?.mimeType === "string" ? r.mimeType : "text/plain";
645
+ message += `
646
+ [Embedded Context] ${uri} (${mime})
647
+ ${r.text}`;
648
+ } else if (typeof r?.blob === "string") {
649
+ const mime = typeof r?.mimeType === "string" ? r.mimeType : "application/octet-stream";
650
+ const bytes = Buffer.byteLength(r.blob, "base64");
651
+ message += `
652
+ [Embedded Context] ${uri} (${mime}, ${bytes} bytes)`;
653
+ } else {
654
+ message += `
655
+ [Embedded Context] ${uri}`;
656
+ }
657
+ break;
658
+ }
659
+ case "audio": {
660
+ const bytes = Buffer.byteLength(b.data, "base64");
661
+ message += `
662
+ [Audio] (${b.mimeType}, ${bytes} bytes) not supported by atomic-acp`;
663
+ break;
664
+ }
665
+ default:
666
+ break;
667
+ }
886
668
  }
887
- try {
888
- return JSON.stringify(result, null, 2);
889
- } catch {
890
- return String(result);
669
+ return { message, images };
670
+ }
671
+
672
+ // src/acp/atomic-sessions.ts
673
+ function str(value) {
674
+ return typeof value === "string" ? value : void 0;
675
+ }
676
+ function isoDate(value) {
677
+ const date = typeof value === "string" ? new Date(value) : null;
678
+ return date && Number.isFinite(date.getTime()) ? date.toISOString() : null;
679
+ }
680
+ function sessionTitle(info, messageCount) {
681
+ const name = str(info.name)?.trim();
682
+ if (name || info.hasName === true) return name ?? "";
683
+ const firstMessage = messageCount > 0 ? str(info.firstMessage) : void 0;
684
+ return firstMessage ? promptToSessionTitle([{ type: "text", text: firstMessage }]) : null;
685
+ }
686
+ function parseAtomicSessionList(data) {
687
+ const sessions = data?.sessions;
688
+ if (!Array.isArray(sessions)) return [];
689
+ const items = [];
690
+ for (const raw of sessions) {
691
+ const info = raw ?? {};
692
+ const sessionId = str(info.id);
693
+ const cwd = str(info.cwd);
694
+ if (sessionId === void 0 || !cwd) continue;
695
+ const messageCount = typeof info.messageCount === "number" ? info.messageCount : 0;
696
+ const title = sessionTitle(info, messageCount);
697
+ if (messageCount === 0 && title === null && info.summary === void 0) continue;
698
+ items.push({ sessionId, cwd, title, updatedAt: isoDate(info.modified) });
891
699
  }
700
+ return items.sort((a, b) => (b.updatedAt ?? "").localeCompare(a.updatedAt ?? ""));
892
701
  }
893
702
 
894
- // src/acp/slash-commands.ts
895
- import { existsSync as existsSync2, readdirSync, readFileSync as readFileSync2, statSync } from "fs";
896
- import { basename, join as join3 } from "path";
897
-
898
703
  // src/acp/atomic-settings.ts
899
704
  import { existsSync, readFileSync } from "fs";
900
705
  import { homedir } from "os";
@@ -918,98 +723,409 @@ function readJsonFile(path) {
918
723
  const data = JSON.parse(raw.replace(/^\uFEFF/, ""));
919
724
  return isObject(data) ? data : {};
920
725
  } catch {
921
- return {};
922
- }
923
- }
924
- function getFirstDefinedEnv(names) {
925
- for (const name of names) {
926
- const value = process.env[name];
927
- if (value !== void 0) return value;
726
+ return {};
727
+ }
728
+ }
729
+ function getFirstDefinedEnv(names) {
730
+ for (const name of names) {
731
+ const value = process.env[name];
732
+ if (value !== void 0) return value;
733
+ }
734
+ return void 0;
735
+ }
736
+ function hasAgentDirOverride() {
737
+ return process.env.ATOMIC_CODING_AGENT_DIR !== void 0 || process.env.PI_CODING_AGENT_DIR !== void 0;
738
+ }
739
+ function readMergedJsonFiles(paths) {
740
+ let merged = {};
741
+ for (let i = paths.length - 1; i >= 0; i--) {
742
+ merged = deepMerge(merged, readJsonFile(paths[i]));
743
+ }
744
+ return merged;
745
+ }
746
+ function getSettingsWithLocations(cwd) {
747
+ const agentDirs = getAgentDirs();
748
+ const projectDirs = getProjectConfigDirs(cwd);
749
+ return [
750
+ {
751
+ location: "user",
752
+ baseDirs: agentDirs,
753
+ settings: readMergedJsonFiles(agentDirs.map((dir) => join2(dir, "settings.json")))
754
+ },
755
+ {
756
+ location: "project",
757
+ baseDirs: projectDirs,
758
+ settings: readMergedJsonFiles(projectDirs.map((dir) => join2(dir, "settings.json")))
759
+ }
760
+ ];
761
+ }
762
+ function getMergedSettings(cwd) {
763
+ const settings = getSettingsWithLocations(cwd);
764
+ return deepMerge(settings[0].settings, settings[1].settings);
765
+ }
766
+ function expandHomePath(value) {
767
+ if (value === "~") return homedir();
768
+ if (value.startsWith("~/")) return join2(homedir(), value.slice(2));
769
+ return value;
770
+ }
771
+ function resolveAtomicPath(value, relativeBase = process.cwd()) {
772
+ const expanded = expandHomePath(value);
773
+ return resolve(relativeBase, expanded);
774
+ }
775
+ function readMergedResourceSettings(cwd) {
776
+ const prompts = [];
777
+ for (const entry of [...getSettingsWithLocations(cwd)].reverse()) {
778
+ const rawPrompts = entry.settings.prompts;
779
+ if (!Array.isArray(rawPrompts)) continue;
780
+ for (const value of rawPrompts) {
781
+ if (typeof value === "string") prompts.push({ value, location: entry.location, baseDirs: entry.baseDirs });
782
+ }
783
+ }
784
+ return { prompts };
785
+ }
786
+ function getAgentDir() {
787
+ const override = getFirstDefinedEnv(["ATOMIC_CODING_AGENT_DIR", "PI_CODING_AGENT_DIR"])?.trim();
788
+ return override ? resolveAtomicPath(override) : join2(homedir(), ".atomic", "agent");
789
+ }
790
+ function getAgentDirs() {
791
+ const primary = getAgentDir();
792
+ if (hasAgentDirOverride()) return [primary];
793
+ const legacy = join2(homedir(), ".pi", "agent");
794
+ return legacy === primary ? [primary] : [primary, legacy];
795
+ }
796
+ function getProjectConfigDirs(cwd) {
797
+ const resolvedCwd = resolve(cwd);
798
+ return [resolve(resolvedCwd, ".atomic"), resolve(resolvedCwd, ".pi")];
799
+ }
800
+ function getEnableSkillCommands(cwd) {
801
+ const merged = getMergedSettings(cwd);
802
+ const direct = merged.enableSkillCommands;
803
+ if (typeof direct === "boolean") return direct;
804
+ const nested = isObject(merged.skills) ? merged.skills.enableSkillCommands : void 0;
805
+ if (typeof nested === "boolean") return nested;
806
+ return true;
807
+ }
808
+ function getQuietStartup(cwd) {
809
+ const merged = getMergedSettings(cwd);
810
+ const direct = merged.quietStartup;
811
+ if (typeof direct === "boolean") return direct;
812
+ const legacy = merged.quietStart;
813
+ if (typeof legacy === "boolean") return legacy;
814
+ return false;
815
+ }
816
+
817
+ // src/acp/auth.ts
818
+ var ATOMIC_SETUP_METHOD_ID = "atomic_terminal_login";
819
+ function getAuthMethods(opts) {
820
+ const supportsTerminalAuthMeta = opts?.supportsTerminalAuthMeta ?? true;
821
+ const method = {
822
+ id: ATOMIC_SETUP_METHOD_ID,
823
+ name: "Launch Atomic in the terminal",
824
+ description: "Start Atomic in an interactive terminal to configure API keys or login",
825
+ // Registry-required fields
826
+ type: "terminal",
827
+ args: ["--terminal-login"],
828
+ env: {}
829
+ };
830
+ if (supportsTerminalAuthMeta) {
831
+ const launch = terminalAuthLaunchSpec();
832
+ method._meta = {
833
+ ...method._meta ?? {},
834
+ "terminal-auth": {
835
+ ...launch,
836
+ label: "Launch Atomic"
837
+ }
838
+ };
839
+ }
840
+ return [method];
841
+ }
842
+ function terminalAuthLaunchSpec() {
843
+ const argv0 = process.argv[0] || "node";
844
+ const argv1 = process.argv[1];
845
+ if (argv1 && argv0) {
846
+ const isNode = argv0.includes("node");
847
+ const isJs = argv1.endsWith(".js");
848
+ if (isNode && isJs) {
849
+ return { command: argv0, args: [argv1, "--terminal-login"] };
850
+ }
851
+ }
852
+ return { command: "atomic-acp", args: ["--terminal-login"] };
853
+ }
854
+
855
+ // src/acp/auth-required.ts
856
+ import { RequestError } from "@agentclientprotocol/sdk";
857
+ function maybeAuthRequiredError(err) {
858
+ const msg = String(err?.message ?? err ?? "");
859
+ const s = msg.toLowerCase();
860
+ const patterns = [
861
+ "api key",
862
+ "apikey",
863
+ "missing key",
864
+ "no key",
865
+ "not configured",
866
+ "unauthorized",
867
+ "authentication",
868
+ "permission denied",
869
+ "forbidden",
870
+ "401",
871
+ "403"
872
+ ];
873
+ const hit = patterns.some((p) => s.includes(p));
874
+ if (!hit) return null;
875
+ return RequestError.authRequired(
876
+ {
877
+ authMethods: getAuthMethods()
878
+ },
879
+ "Configure an API key or log in with an OAuth provider."
880
+ );
881
+ }
882
+
883
+ // src/acp/elicitation/extension-dialog.ts
884
+ import {
885
+ methods
886
+ } from "@agentclientprotocol/sdk";
887
+ var NO_CLIENT_ELICITATION_SUPPORT = {
888
+ form: false,
889
+ reason: "missing_client_capability"
890
+ };
891
+ function readClientElicitationSupport(params) {
892
+ const form = params.clientCapabilities?.elicitation?.form;
893
+ if (form !== null && typeof form === "object" && !Array.isArray(form)) {
894
+ return { form: true };
895
+ }
896
+ return NO_CLIENT_ELICITATION_SUPPORT;
897
+ }
898
+ function requestExtensionDialog(conn, sessionId, ev, form, signal, onClientCannotAnswer) {
899
+ const cancelled = {
900
+ type: "extension_ui_response",
901
+ id: String(ev.id),
902
+ cancelled: true
903
+ };
904
+ if (signal?.aborted) return Promise.resolve(cancelled);
905
+ return new Promise((resolve2) => {
906
+ const finish = (response) => {
907
+ signal?.removeEventListener("abort", abort);
908
+ resolve2(response);
909
+ };
910
+ const abort = () => finish(cancelled);
911
+ signal?.addEventListener("abort", abort, { once: true });
912
+ void requestDialog(conn, sessionId, ev, form, onClientCannotAnswer).then(finish);
913
+ });
914
+ }
915
+ async function requestDialog(conn, sessionId, ev, form, onClientCannotAnswer) {
916
+ const id = String(ev.id);
917
+ const cancelled = { type: "extension_ui_response", id, cancelled: true };
918
+ const method = ev.method;
919
+ if (method === "questionnaire") {
920
+ if (!form) return cancelled;
921
+ try {
922
+ return await requestQuestionnaire(conn, sessionId, id, ev.questions);
923
+ } catch {
924
+ onClientCannotAnswer?.();
925
+ return cancelled;
926
+ }
927
+ }
928
+ const options = Array.isArray(ev.options) ? ev.options.map(String) : [];
929
+ if (method === "select" && !options.length) return cancelled;
930
+ const title = typeof ev.title === "string" ? ev.title : `Atomic ${method}`;
931
+ try {
932
+ if (form) {
933
+ let property;
934
+ if (method === "confirm") property = { type: "boolean", title };
935
+ else if (method === "select") property = { type: "string", title, enum: options };
936
+ else
937
+ property = {
938
+ type: "string",
939
+ title,
940
+ ...typeof ev.placeholder === "string" ? { description: ev.placeholder } : {},
941
+ ...typeof ev.prefill === "string" ? { default: ev.prefill } : {}
942
+ };
943
+ const response2 = await conn.request(methods.client.elicitation.create, {
944
+ sessionId,
945
+ mode: "form",
946
+ message: typeof ev.message === "string" ? `${title}
947
+
948
+ ${ev.message}` : title,
949
+ requestedSchema: { type: "object", properties: { value: property }, required: ["value"] },
950
+ _meta: { atomicAcp: { kind: "extension_ui", method: String(method), atomicRequestId: id } }
951
+ });
952
+ if (response2.action !== "accept") return cancelled;
953
+ const value = response2.content?.value;
954
+ if (method === "confirm")
955
+ return typeof value === "boolean" ? { type: "extension_ui_response", id, confirmed: value } : cancelled;
956
+ if (typeof value !== "string" || method === "select" && !options.includes(value)) return cancelled;
957
+ return { type: "extension_ui_response", id, value };
958
+ }
959
+ if (method !== "select" && method !== "confirm") return cancelled;
960
+ const rawInput = { method };
961
+ for (const key of ["title", "message", "options", "placeholder", "prefill"]) {
962
+ if (Object.hasOwn(ev, key)) rawInput[key] = ev[key];
963
+ }
964
+ const response = await conn.request(methods.client.session.requestPermission, {
965
+ sessionId,
966
+ toolCall: { toolCallId: `atomic-ui-${id}`, title, kind: "other", status: "pending", rawInput },
967
+ options: method === "confirm" ? [
968
+ { optionId: "yes", name: "Yes", kind: "allow_once" },
969
+ { optionId: "no", name: "No", kind: "reject_once" }
970
+ ] : options.map((name, index2) => ({ optionId: `choice-${index2}`, name, kind: "allow_once" }))
971
+ });
972
+ if (response.outcome.outcome !== "selected") return cancelled;
973
+ const optionId = response.outcome.optionId;
974
+ if (method === "confirm")
975
+ return optionId === "yes" || optionId === "no" ? { type: "extension_ui_response", id, confirmed: optionId === "yes" } : cancelled;
976
+ const index = options.findIndex((_, index2) => optionId === `choice-${index2}`);
977
+ return index < 0 ? cancelled : { type: "extension_ui_response", id, value: options[index] };
978
+ } catch {
979
+ onClientCannotAnswer?.();
980
+ return cancelled;
928
981
  }
929
- return void 0;
930
- }
931
- function hasAgentDirOverride() {
932
- return process.env.ATOMIC_CODING_AGENT_DIR !== void 0 || process.env.PI_CODING_AGENT_DIR !== void 0;
933
982
  }
934
- function readMergedJsonFiles(paths) {
935
- let merged = {};
936
- for (let i = paths.length - 1; i >= 0; i--) {
937
- merged = deepMerge(merged, readJsonFile(paths[i]));
983
+ function readQuestions(value) {
984
+ if (!Array.isArray(value) || value.length === 0) return void 0;
985
+ const questions = [];
986
+ for (const item of value) {
987
+ const q = item;
988
+ if (!q || typeof q.question !== "string" || !Array.isArray(q.options) || q.options.length === 0) return void 0;
989
+ const options = q.options.filter(
990
+ (option) => typeof option?.label === "string" && option.label !== ""
991
+ );
992
+ if (options.length !== q.options.length) return void 0;
993
+ questions.push({
994
+ question: q.question,
995
+ ...typeof q.header === "string" ? { header: q.header } : {},
996
+ multiSelect: q.multiSelect === true,
997
+ options
998
+ });
938
999
  }
939
- return merged;
1000
+ return questions;
940
1001
  }
941
- function getSettingsWithLocations(cwd) {
942
- const agentDirs = getAgentDirs();
943
- const projectDirs = getProjectConfigDirs(cwd);
944
- return [
945
- {
946
- location: "user",
947
- baseDirs: agentDirs,
948
- settings: readMergedJsonFiles(agentDirs.map((dir) => join2(dir, "settings.json")))
949
- },
950
- {
951
- location: "project",
952
- baseDirs: projectDirs,
953
- settings: readMergedJsonFiles(projectDirs.map((dir) => join2(dir, "settings.json")))
1002
+ async function requestQuestionnaire(conn, sessionId, id, rawQuestions) {
1003
+ const cancelled = { type: "extension_ui_response", id, cancelled: true };
1004
+ const questions = readQuestions(rawQuestions);
1005
+ if (!questions) return cancelled;
1006
+ const properties = {};
1007
+ questions.forEach((q, index) => {
1008
+ const labels = q.options.map((option) => option.label);
1009
+ const described = q.options.filter((option) => option.description);
1010
+ const description = [q.question, ...described.map((option) => `${option.label}: ${option.description}`)].join(
1011
+ "\n"
1012
+ );
1013
+ const title = q.header || q.question;
1014
+ properties[`q${index}`] = q.multiSelect ? { type: "array", title, description, minItems: 1, items: { type: "string", enum: labels } } : { type: "string", title, description, enum: labels };
1015
+ });
1016
+ const response = await conn.request(methods.client.elicitation.create, {
1017
+ sessionId,
1018
+ mode: "form",
1019
+ message: questions.length === 1 ? questions[0].question : "Atomic has some questions for you.",
1020
+ requestedSchema: { type: "object", properties, required: Object.keys(properties) },
1021
+ _meta: { atomicAcp: { kind: "extension_ui", method: "questionnaire", atomicRequestId: id } }
1022
+ });
1023
+ if (response.action !== "accept") return cancelled;
1024
+ const content = response.content ?? {};
1025
+ const answers = [];
1026
+ for (const [index, q] of questions.entries()) {
1027
+ const labels = q.options.map((option) => option.label);
1028
+ const value = content[`q${index}`];
1029
+ if (q.multiSelect) {
1030
+ if (!Array.isArray(value) || value.length === 0 || !value.every((v) => typeof v === "string" && labels.includes(v)))
1031
+ return cancelled;
1032
+ answers.push({ questionIndex: index, question: q.question, kind: "multi", answer: null, selected: value });
1033
+ } else {
1034
+ if (typeof value !== "string" || !labels.includes(value)) return cancelled;
1035
+ answers.push({ questionIndex: index, question: q.question, kind: "option", answer: value });
954
1036
  }
955
- ];
956
- }
957
- function getMergedSettings(cwd) {
958
- const settings = getSettingsWithLocations(cwd);
959
- return deepMerge(settings[0].settings, settings[1].settings);
1037
+ }
1038
+ return { type: "extension_ui_response", id, answers };
960
1039
  }
961
- function expandHomePath(value) {
962
- if (value === "~") return homedir();
963
- if (value.startsWith("~/")) return join2(homedir(), value.slice(2));
964
- return value;
1040
+
1041
+ // src/acp/headless.ts
1042
+ function isHeadlessFromEnv(env = process.env) {
1043
+ return /^(1|true)$/i.test(env.ATOMIC_ACP_HEADLESS?.trim() ?? "");
965
1044
  }
966
- function resolveAtomicPath(value, relativeBase = process.cwd()) {
967
- const expanded = expandHomePath(value);
968
- return resolve(relativeBase, expanded);
1045
+
1046
+ // src/acp/mcp-servers.ts
1047
+ import { RequestError as RequestError2 } from "@agentclientprotocol/sdk";
1048
+ var RESERVED_NAMES = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
1049
+ function toRecord(entries) {
1050
+ return Object.fromEntries(entries.map((entry) => [entry.name, entry.value]));
969
1051
  }
970
- function readMergedResourceSettings(cwd) {
971
- const prompts = [];
972
- for (const entry of [...getSettingsWithLocations(cwd)].reverse()) {
973
- const rawPrompts = entry.settings.prompts;
974
- if (!Array.isArray(rawPrompts)) continue;
975
- for (const value of rawPrompts) {
976
- if (typeof value === "string") prompts.push({ value, location: entry.location, baseDirs: entry.baseDirs });
1052
+ var HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
1053
+ var HEADER_VALUE_BREAK = /[\r\n\0]/;
1054
+ var URL_ENV_REFERENCE = /\$\{|\$env:/i;
1055
+ function assertUsable(server) {
1056
+ const refuse = (reason) => {
1057
+ throw RequestError2.invalidParams(void 0, `MCP server ${JSON.stringify(server.name)} refused: ${reason}`);
1058
+ };
1059
+ if ("type" in server && server.type === "http") {
1060
+ if (URL_ENV_REFERENCE.test(server.url)) refuse("its URL contains an environment reference (${...} or $env:)");
1061
+ for (const { name, value } of server.headers ?? []) {
1062
+ if (!HEADER_NAME.test(name)) refuse(`header name ${JSON.stringify(name)} is not a valid HTTP header name`);
1063
+ if (HEADER_VALUE_BREAK.test(value)) refuse(`header ${JSON.stringify(name)} has a CR, LF or NUL in its value`);
1064
+ }
1065
+ } else if ("command" in server) {
1066
+ for (const { name, value } of server.env ?? []) {
1067
+ if (value.includes("\0")) refuse(`env ${JSON.stringify(name)} has a NUL in its value`);
977
1068
  }
978
1069
  }
979
- return { prompts };
980
1070
  }
981
- function getAgentDir() {
982
- const override = getFirstDefinedEnv(["ATOMIC_CODING_AGENT_DIR", "PI_CODING_AGENT_DIR"])?.trim();
983
- return override ? resolveAtomicPath(override) : join2(homedir(), ".atomic", "agent");
1071
+ function namespaceOf(name) {
1072
+ return name.replace(/-/g, "_");
984
1073
  }
985
- function getAgentDirs() {
986
- const primary = getAgentDir();
987
- if (hasAgentDirOverride()) return [primary];
988
- const legacy = join2(homedir(), ".pi", "agent");
989
- return legacy === primary ? [primary] : [primary, legacy];
1074
+ function uniqueServerName(requested, taken) {
1075
+ let base = requested.replace(/[^A-Za-z0-9_-]/g, "_") || "mcp";
1076
+ if (RESERVED_NAMES.has(base)) base = `${base}_`;
1077
+ let name = base;
1078
+ for (let n = 2; taken.has(namespaceOf(name)); n += 1) name = `${base}_${n}`;
1079
+ taken.add(namespaceOf(name));
1080
+ return name;
990
1081
  }
991
- function getProjectConfigDirs(cwd) {
992
- const resolvedCwd = resolve(cwd);
993
- return [resolve(resolvedCwd, ".atomic"), resolve(resolvedCwd, ".pi")];
1082
+ function toAtomicMcpServers(servers) {
1083
+ const out = /* @__PURE__ */ new Map();
1084
+ const warnings = [];
1085
+ const taken = /* @__PURE__ */ new Set();
1086
+ for (const server of servers) assertUsable(server);
1087
+ for (const server of servers) {
1088
+ if ("type" in server && server.type === "http") {
1089
+ out.set(uniqueServerName(server.name, taken), {
1090
+ url: server.url,
1091
+ headers: toRecord(server.headers ?? []),
1092
+ exposure: "direct"
1093
+ });
1094
+ } else if ("type" in server && server.type === "sse") {
1095
+ warnings.push(`MCP server "${server.name}" skipped: Atomic does not support the SSE transport`);
1096
+ } else if ("command" in server) {
1097
+ out.set(uniqueServerName(server.name, taken), {
1098
+ command: server.command,
1099
+ args: [...server.args ?? []],
1100
+ env: toRecord(server.env ?? []),
1101
+ exposure: "direct"
1102
+ });
1103
+ } else {
1104
+ const other = server;
1105
+ const type = "type" in other ? String(other.type) : "unknown";
1106
+ warnings.push(`MCP server "${other.name}" skipped: Atomic does not support the ${type} transport`);
1107
+ }
1108
+ }
1109
+ return { servers: Object.fromEntries(out), warnings };
994
1110
  }
995
- function getEnableSkillCommands(cwd) {
996
- const merged = getMergedSettings(cwd);
997
- const direct = merged.enableSkillCommands;
998
- if (typeof direct === "boolean") return direct;
999
- const nested = isObject(merged.skills) ? merged.skills.enableSkillCommands : void 0;
1000
- if (typeof nested === "boolean") return nested;
1001
- return true;
1111
+ function atomicMcpServersForSpawn(servers) {
1112
+ const { servers: mapped, warnings } = toAtomicMcpServers(servers ?? []);
1113
+ for (const warning of warnings) process.stderr.write(`atomic-acp: ${warning}
1114
+ `);
1115
+ return mapped;
1002
1116
  }
1003
- function getQuietStartup(cwd) {
1004
- const merged = getMergedSettings(cwd);
1005
- const direct = merged.quietStartup;
1006
- if (typeof direct === "boolean") return direct;
1007
- const legacy = merged.quietStart;
1008
- if (typeof legacy === "boolean") return legacy;
1009
- return false;
1117
+ function sameMcpServers(a, b) {
1118
+ return JSON.stringify(toAtomicMcpServers(a ?? []).servers) === JSON.stringify(toAtomicMcpServers(b ?? []).servers);
1010
1119
  }
1011
1120
 
1121
+ // src/acp/session.ts
1122
+ import { readFileSync as readFileSync3 } from "fs";
1123
+ import { isAbsolute, resolve as resolvePath } from "path";
1124
+ import { methods as methods2, RequestError as RequestError3 } from "@agentclientprotocol/sdk";
1125
+
1012
1126
  // src/acp/slash-commands.ts
1127
+ import { existsSync as existsSync2, readdirSync, readFileSync as readFileSync2, statSync } from "fs";
1128
+ import { basename, join as join3 } from "path";
1013
1129
  function parseFrontmatter(content) {
1014
1130
  const frontmatter = {};
1015
1131
  if (!content.startsWith("---")) return { frontmatter, content };
@@ -1194,132 +1310,137 @@ function expandSlashCommand(text, fileCommands) {
1194
1310
  const args = parseCommandArgs(argsString);
1195
1311
  return substituteArgs(cmd.content, args);
1196
1312
  }
1197
-
1198
- // src/acp/mcp-servers.ts
1199
- import { RequestError as RequestError2 } from "@agentclientprotocol/sdk";
1200
- var RESERVED_NAMES = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
1201
- function toRecord(entries) {
1202
- return Object.fromEntries(entries.map((entry) => [entry.name, entry.value]));
1313
+
1314
+ // src/acp/translate/atomic-tools.ts
1315
+ function toolResultToText(result) {
1316
+ if (!result) return "";
1317
+ const details = result.details;
1318
+ const diff = details?.diff;
1319
+ if (typeof diff === "string" && diff.trim()) return diff;
1320
+ const content = result.content;
1321
+ if (Array.isArray(content)) {
1322
+ const texts = content.map((c) => c?.type === "text" && typeof c.text === "string" ? c.text : "").filter(Boolean);
1323
+ if (texts.length) return texts.join("");
1324
+ }
1325
+ 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);
1326
+ const stderr = (typeof details?.stderr === "string" ? details.stderr : void 0) ?? (typeof result?.stderr === "string" ? result.stderr : void 0);
1327
+ 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);
1328
+ if (typeof stdout === "string" && stdout.trim() || typeof stderr === "string" && stderr.trim()) {
1329
+ const parts = [];
1330
+ if (typeof stdout === "string" && stdout.trim()) parts.push(stdout);
1331
+ if (typeof stderr === "string" && stderr.trim()) parts.push(`stderr:
1332
+ ${stderr}`);
1333
+ if (typeof exitCode === "number") parts.push(`exit code: ${exitCode}`);
1334
+ return parts.join("\n\n").trimEnd();
1335
+ }
1336
+ try {
1337
+ return JSON.stringify(result, null, 2);
1338
+ } catch {
1339
+ return String(result);
1340
+ }
1341
+ }
1342
+
1343
+ // src/acp/translate/bash.ts
1344
+ function isBashTool(name) {
1345
+ return name.toLowerCase() === "bash";
1346
+ }
1347
+ function bashCommand(value) {
1348
+ const record3 = value;
1349
+ for (const source of [record3, record3?.args, record3?.input, record3?.rawInput, record3?.toolInput, record3?.details]) {
1350
+ const command = source?.command ?? source?.cmd;
1351
+ if (typeof command === "string" && command.trim()) return command;
1352
+ }
1353
+ return void 0;
1203
1354
  }
1204
- var HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
1205
- var HEADER_VALUE_BREAK = /[\r\n\0]/;
1206
- var URL_ENV_REFERENCE = /\$\{|\$env:/i;
1207
- function assertUsable(server) {
1208
- const refuse = (reason) => {
1209
- throw RequestError2.invalidParams(void 0, `MCP server ${JSON.stringify(server.name)} refused: ${reason}`);
1210
- };
1211
- if ("type" in server && server.type === "http") {
1212
- if (URL_ENV_REFERENCE.test(server.url)) refuse("its URL contains an environment reference (${...} or $env:)");
1213
- for (const { name, value } of server.headers ?? []) {
1214
- if (!HEADER_NAME.test(name)) refuse(`header name ${JSON.stringify(name)} is not a valid HTTP header name`);
1215
- if (HEADER_VALUE_BREAK.test(value)) refuse(`header ${JSON.stringify(name)} has a CR, LF or NUL in its value`);
1216
- }
1217
- } else if ("command" in server) {
1218
- for (const { name, value } of server.env ?? []) {
1219
- if (value.includes("\0")) refuse(`env ${JSON.stringify(name)} has a NUL in its value`);
1220
- }
1355
+ function bashResultText(value) {
1356
+ const record3 = value;
1357
+ if (Array.isArray(record3?.content)) {
1358
+ const text = record3.content.map(
1359
+ (block) => block.type === "text" && typeof block.text === "string" ? block.text : ""
1360
+ ).join("");
1361
+ if (text) return text;
1221
1362
  }
1363
+ const details = record3?.details;
1364
+ const stdout = details?.stdout ?? record3?.stdout ?? details?.output ?? record3?.output;
1365
+ const stderr = details?.stderr ?? record3?.stderr;
1366
+ return [stdout, stderr].filter((part) => typeof part === "string" && part.length > 0).join("\n");
1222
1367
  }
1223
- function namespaceOf(name) {
1224
- return name.replace(/-/g, "_");
1368
+ function bashExitCode(value, isError) {
1369
+ const record3 = value;
1370
+ const code = record3?.details?.exitCode ?? record3?.exitCode ?? record3?.details?.code ?? record3?.code;
1371
+ return typeof code === "number" ? code : isError ? 1 : 0;
1225
1372
  }
1226
- function uniqueServerName(requested, taken) {
1227
- let base = requested.replace(/[^A-Za-z0-9_-]/g, "_") || "mcp";
1228
- if (RESERVED_NAMES.has(base)) base = `${base}_`;
1229
- let name = base;
1230
- for (let n = 2; taken.has(namespaceOf(name)); n += 1) name = `${base}_${n}`;
1231
- taken.add(namespaceOf(name));
1232
- return name;
1373
+ function bashOutputDelta(previous, next) {
1374
+ return next.startsWith(previous) ? next.slice(previous.length) : next;
1233
1375
  }
1234
- function toAtomicMcpServers(servers) {
1235
- const out = /* @__PURE__ */ new Map();
1236
- const warnings = [];
1237
- const taken = /* @__PURE__ */ new Set();
1238
- for (const server of servers) assertUsable(server);
1239
- for (const server of servers) {
1240
- if ("type" in server && server.type === "http") {
1241
- out.set(uniqueServerName(server.name, taken), {
1242
- url: server.url,
1243
- headers: toRecord(server.headers ?? []),
1244
- exposure: "direct"
1245
- });
1246
- } else if ("type" in server && server.type === "sse") {
1247
- warnings.push(`MCP server "${server.name}" skipped: Atomic does not support the SSE transport`);
1248
- } else if ("command" in server) {
1249
- out.set(uniqueServerName(server.name, taken), {
1250
- command: server.command,
1251
- args: [...server.args ?? []],
1252
- env: toRecord(server.env ?? []),
1253
- exposure: "direct"
1254
- });
1255
- } else {
1256
- const other = server;
1257
- const type = "type" in other ? String(other.type) : "unknown";
1258
- warnings.push(`MCP server "${other.name}" skipped: Atomic does not support the ${type} transport`);
1259
- }
1260
- }
1261
- return { servers: Object.fromEntries(out), warnings };
1376
+ function bashTerminalContent(id) {
1377
+ return [{ type: "terminal", terminalId: id }];
1262
1378
  }
1263
- function atomicMcpServersForSpawn(servers) {
1264
- const { servers: mapped, warnings } = toAtomicMcpServers(servers ?? []);
1265
- for (const warning of warnings) process.stderr.write(`atomic-acp: ${warning}
1266
- `);
1267
- return mapped;
1379
+ function bashTerminalInfoMeta(id, cwd) {
1380
+ return { terminal_info: { terminal_id: id, cwd } };
1268
1381
  }
1269
- function sameMcpServers(a, b) {
1270
- return JSON.stringify(toAtomicMcpServers(a ?? []).servers) === JSON.stringify(toAtomicMcpServers(b ?? []).servers);
1382
+ function bashTerminalOutputMeta(id, data) {
1383
+ return { terminal_output: { terminal_id: id, data } };
1384
+ }
1385
+ function bashTerminalExitMeta(id, exitCode) {
1386
+ return { terminal_exit: { terminal_id: id, exit_code: exitCode, signal: null } };
1271
1387
  }
1272
1388
 
1273
1389
  // src/acp/translate/workflow-events.ts
1274
1390
  var TERMINAL_NOTICE_KINDS = /* @__PURE__ */ new Set(["completed", "failed", "blocked", "quit", "cancelled", "killed", "skipped"]);
1275
- function str(value) {
1391
+ function str2(value) {
1276
1392
  return typeof value === "string" && value ? value : void 0;
1277
1393
  }
1278
- function record2(value) {
1394
+ function record(value) {
1279
1395
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
1280
1396
  }
1281
1397
  function parseWorkflowEvent(ev) {
1282
1398
  if (ev.type === "entry_appended") {
1283
- const entry = record2(ev.entry);
1284
- const data = record2(entry?.data);
1285
- const runId = str(data?.runId);
1399
+ const entry = record(ev.entry);
1400
+ const data = record(entry?.data);
1401
+ const runId = str2(data?.runId);
1286
1402
  if (!entry || !data || !runId) return null;
1287
1403
  switch (entry.customType) {
1288
1404
  case "workflow.run.start":
1289
- return { kind: "run_start", runId, name: str(data.name) };
1405
+ return { kind: "run_start", runId, name: str2(data.name) };
1290
1406
  case "workflow.run.end":
1291
1407
  return {
1292
1408
  kind: "run_end",
1293
1409
  runId,
1294
- status: str(data.status) ?? "completed",
1410
+ status: str2(data.status) ?? "completed",
1295
1411
  ...data.result !== void 0 ? { result: data.result } : {},
1296
- ...str(data.error) ? { error: str(data.error) } : {}
1412
+ ...str2(data.error) ? { error: str2(data.error) } : {}
1297
1413
  };
1298
1414
  case "workflow.run.blocked":
1299
- return { kind: "run_end", runId, status: "blocked", ...str(data.error) ? { error: str(data.error) } : {} };
1415
+ return {
1416
+ kind: "run_end",
1417
+ runId,
1418
+ status: "blocked",
1419
+ ...str2(data.error) ? { error: str2(data.error) } : {}
1420
+ };
1300
1421
  case "workflow.stage.start":
1301
1422
  return {
1302
1423
  kind: "stage_start",
1303
1424
  runId,
1304
- stageId: str(data.stageId),
1305
- name: str(data.name),
1425
+ stageId: str2(data.stageId),
1426
+ name: str2(data.name),
1306
1427
  // Human-input prompt nodes (ctx.ui.input/confirm/select/editor/custom) use `prompt:` replay keys.
1307
- humanInput: str(data.replayKey)?.startsWith("prompt:") ?? false
1428
+ humanInput: str2(data.replayKey)?.startsWith("prompt:") ?? false
1308
1429
  };
1309
1430
  case "workflow.stage.end":
1310
- return { kind: "stage_end", runId, stageId: str(data.stageId), status: str(data.status) };
1431
+ return { kind: "stage_end", runId, stageId: str2(data.stageId), status: str2(data.status) };
1311
1432
  default:
1312
1433
  return null;
1313
1434
  }
1314
1435
  }
1315
1436
  if (ev.type === "message_end") {
1316
- const message = record2(ev.message);
1437
+ const message = record(ev.message);
1317
1438
  if (message?.role !== "custom" || message.customType !== "workflows:lifecycle-notice") return null;
1318
- const details = record2(message.details);
1319
- const runId = str(details?.runId);
1320
- const kind = str(details?.kind);
1439
+ const details = record(message.details);
1440
+ const runId = str2(details?.runId);
1441
+ const kind = str2(details?.kind);
1321
1442
  if (!runId || !kind || details?.scope === "stage") return null;
1322
- if (kind === "started") return { kind: "run_start", runId, name: str(details?.workflowName) };
1443
+ if (kind === "started") return { kind: "run_start", runId, name: str2(details?.workflowName) };
1323
1444
  if (TERMINAL_NOTICE_KINDS.has(kind)) return { kind: "run_end", runId, status: kind };
1324
1445
  }
1325
1446
  return null;
@@ -2337,7 +2458,8 @@ function loadFile(path) {
2337
2458
  }
2338
2459
  function saveFile(path, data) {
2339
2460
  ensureParentDir(path);
2340
- writeFileSync2(path, JSON.stringify(data, null, 2) + "\n", "utf-8");
2461
+ writeFileSync2(path, `${JSON.stringify(data, null, 2)}
2462
+ `, "utf-8");
2341
2463
  }
2342
2464
  var SessionStore = class {
2343
2465
  path;
@@ -2370,99 +2492,6 @@ var SessionStore = class {
2370
2492
  }
2371
2493
  };
2372
2494
 
2373
- // src/acp/headless.ts
2374
- function isHeadlessFromEnv(env = process.env) {
2375
- return /^(1|true)$/i.test(env.ATOMIC_ACP_HEADLESS?.trim() ?? "");
2376
- }
2377
-
2378
- // src/acp/translate/prompt.ts
2379
- function promptToSessionTitle(blocks) {
2380
- const normalized = blocks.filter((block) => block.type === "text").map((block) => block.text).join(" ").replace(/\s+/gu, " ").trim();
2381
- return normalized ? Array.from(normalized).slice(0, 80).join("") : null;
2382
- }
2383
- function promptToAtomicMessage(blocks) {
2384
- let message = "";
2385
- const images = [];
2386
- for (const b of blocks) {
2387
- switch (b.type) {
2388
- case "text":
2389
- message += b.text;
2390
- break;
2391
- case "resource_link":
2392
- message += `
2393
- [Context] ${b.uri}`;
2394
- break;
2395
- case "image": {
2396
- images.push({
2397
- type: "image",
2398
- mimeType: b.mimeType,
2399
- data: b.data
2400
- });
2401
- break;
2402
- }
2403
- case "resource": {
2404
- const r = b.resource;
2405
- const uri = typeof r?.uri === "string" ? r.uri : "(unknown)";
2406
- if (typeof r?.text === "string") {
2407
- const mime = typeof r?.mimeType === "string" ? r.mimeType : "text/plain";
2408
- message += `
2409
- [Embedded Context] ${uri} (${mime})
2410
- ${r.text}`;
2411
- } else if (typeof r?.blob === "string") {
2412
- const mime = typeof r?.mimeType === "string" ? r.mimeType : "application/octet-stream";
2413
- const bytes = Buffer.byteLength(r.blob, "base64");
2414
- message += `
2415
- [Embedded Context] ${uri} (${mime}, ${bytes} bytes)`;
2416
- } else {
2417
- message += `
2418
- [Embedded Context] ${uri}`;
2419
- }
2420
- break;
2421
- }
2422
- case "audio": {
2423
- const bytes = Buffer.byteLength(b.data, "base64");
2424
- message += `
2425
- [Audio] (${b.mimeType}, ${bytes} bytes) not supported by atomic-acp`;
2426
- break;
2427
- }
2428
- default:
2429
- break;
2430
- }
2431
- }
2432
- return { message, images };
2433
- }
2434
-
2435
- // src/acp/atomic-sessions.ts
2436
- function str2(value) {
2437
- return typeof value === "string" ? value : void 0;
2438
- }
2439
- function isoDate(value) {
2440
- const date = typeof value === "string" ? new Date(value) : null;
2441
- return date && Number.isFinite(date.getTime()) ? date.toISOString() : null;
2442
- }
2443
- function sessionTitle(info, messageCount) {
2444
- const name = str2(info.name)?.trim();
2445
- if (name || info.hasName === true) return name ?? "";
2446
- const firstMessage = messageCount > 0 ? str2(info.firstMessage) : void 0;
2447
- return firstMessage ? promptToSessionTitle([{ type: "text", text: firstMessage }]) : null;
2448
- }
2449
- function parseAtomicSessionList(data) {
2450
- const sessions = data?.sessions;
2451
- if (!Array.isArray(sessions)) return [];
2452
- const items = [];
2453
- for (const raw of sessions) {
2454
- const info = raw ?? {};
2455
- const sessionId = str2(info.id);
2456
- const cwd = str2(info.cwd);
2457
- if (sessionId === void 0 || !cwd) continue;
2458
- const messageCount = typeof info.messageCount === "number" ? info.messageCount : 0;
2459
- const title = sessionTitle(info, messageCount);
2460
- if (messageCount === 0 && title === null && info.summary === void 0) continue;
2461
- items.push({ sessionId, cwd, title, updatedAt: isoDate(info.modified) });
2462
- }
2463
- return items.sort((a, b) => (b.updatedAt ?? "").localeCompare(a.updatedAt ?? ""));
2464
- }
2465
-
2466
2495
  // src/acp/translate/atomic-messages.ts
2467
2496
  function normalizeAtomicMessageText(content) {
2468
2497
  if (typeof content === "string") return content;
@@ -2474,43 +2503,36 @@ function normalizeAtomicAssistantText(content) {
2474
2503
  return content.map((c) => c?.type === "text" && typeof c.text === "string" ? c.text : "").filter(Boolean).join("");
2475
2504
  }
2476
2505
 
2477
- // src/acp/atomic-commands.ts
2478
- function describeFallback(c) {
2479
- const source = typeof c.source === "string" ? c.source : "";
2480
- const location = typeof c.location === "string" ? c.location : "";
2481
- const parts = [];
2482
- if (source) parts.push(source);
2483
- if (location) parts.push(location);
2484
- return parts.length ? `(${parts.join(":")})` : "(command)";
2506
+ // src/acp/workflow-history.ts
2507
+ function record2(value) {
2508
+ return value !== null && typeof value === "object" ? value : {};
2485
2509
  }
2486
- function toAvailableCommandsFromAtomicGetCommands(data, opts) {
2487
- const enableSkillCommands = opts?.enableSkillCommands ?? true;
2488
- const includeExtensionCommands = opts?.includeExtensionCommands ?? true;
2489
- const root = data;
2490
- const commandsRaw = Array.isArray(root?.commands) ? root.commands : Array.isArray(root?.data?.commands) ? root.data.commands : [];
2491
- const out = [];
2492
- for (const c of commandsRaw) {
2493
- const name = typeof c?.name === "string" ? c.name.trim() : "";
2494
- if (!name) continue;
2495
- const source = typeof c?.source === "string" ? c.source : "";
2496
- if (!includeExtensionCommands && source === "extension") continue;
2497
- if (!enableSkillCommands && name.startsWith("skill:")) continue;
2498
- const desc = typeof c?.description === "string" ? c.description.trim() : "";
2499
- const usage = desc.match(/Usage:\s*\/\S+\s+(.+)$/i)?.[1];
2500
- out.push({
2501
- name,
2502
- description: desc || describeFallback(c),
2503
- ...usage ? { input: { hint: usage } } : {}
2504
- });
2510
+ function renderRun(value) {
2511
+ const run = record2(value);
2512
+ const title = [run.name, run.runId].filter((v) => typeof v === "string").join(" \u2014 ");
2513
+ const heading = (title || "Workflow run").replace(/[\r\n\u2028\u2029]/g, " ").replace(/[\\`*_{}[\]()<>#+\-.!|&]/g, "\\$&");
2514
+ const lines = [];
2515
+ for (const key of ["status", "label", "identity", "summarizedThrough"]) {
2516
+ if (run[key] !== void 0)
2517
+ lines.push(`${key}: ${typeof run[key] === "object" ? JSON.stringify(run[key]) : String(run[key])}`);
2505
2518
  }
2506
- return { commands: out, raw: commandsRaw };
2519
+ if (run.summary !== void 0)
2520
+ lines.push("", typeof run.summary === "string" ? run.summary : JSON.stringify(run.summary, null, 2));
2521
+ const body = lines.join("\n");
2522
+ const fence = "`".repeat(Math.max(3, ...[...body.matchAll(/`+/g)].map((match) => match[0].length + 1)));
2523
+ return `## ${heading}
2524
+
2525
+ ${fence}text
2526
+ ${body}
2527
+ ${fence}`;
2528
+ }
2529
+ function renderWorkflowHistory(data, list) {
2530
+ if (!list) return renderRun(data);
2531
+ const runs = record2(data).runs;
2532
+ return Array.isArray(runs) && runs.length ? runs.map(renderRun).join("\n\n") : "No workflow runs found.";
2507
2533
  }
2508
2534
 
2509
2535
  // src/acp/agent.ts
2510
- import { isAbsolute as isAbsolute2 } from "path";
2511
- import { existsSync as existsSync3, readFileSync as readFileSync5, realpathSync, readdirSync as readdirSync2, statSync as statSync2 } from "fs";
2512
- import { join as join5, dirname as dirname2, basename as basename2 } from "path";
2513
- import { spawnSync } from "child_process";
2514
2536
  import { fileURLToPath } from "url";
2515
2537
  var MODEL_CONFIG_ID = "model";
2516
2538
  var THOUGHT_LEVEL_CONFIG_ID = "thought_level";
@@ -2598,7 +2620,8 @@ var AtomicAcpAgent = class {
2598
2620
  try {
2599
2621
  proc = await AtomicRpcProcess.spawn({ cwd, atomicCommand: process.env.ATOMIC_ACP_ATOMIC_COMMAND });
2600
2622
  } catch (error) {
2601
- if (error instanceof AtomicRpcSpawnError) throw RequestError4.internalError({ code: error.code }, error.message);
2623
+ if (error instanceof AtomicRpcSpawnError)
2624
+ throw RequestError4.internalError({ code: error.code }, error.message);
2602
2625
  throw error;
2603
2626
  }
2604
2627
  try {
@@ -2650,7 +2673,8 @@ var AtomicAcpAgent = class {
2650
2673
  async restoreSessionImpl(sessionId, opts) {
2651
2674
  const existing = this.sessions.maybeGet(sessionId);
2652
2675
  if (existing) {
2653
- if (opts?.cwd && existing.cwd !== opts.cwd) throw RequestError4.invalidParams(`Unknown sessionId: ${sessionId}`);
2676
+ if (opts?.cwd && existing.cwd !== opts.cwd)
2677
+ throw RequestError4.invalidParams(`Unknown sessionId: ${sessionId}`);
2654
2678
  const sameServers = !opts?.mcpServers || sameMcpServers(existing.mcpServers, opts.mcpServers);
2655
2679
  if (sameServers && !existing.proc.hasExited) return existing;
2656
2680
  this.sessions.close(sessionId);
@@ -2670,7 +2694,8 @@ var AtomicAcpAgent = class {
2670
2694
  answersQuestionnaires: this.clientElicitationSupport.form
2671
2695
  });
2672
2696
  } catch (error) {
2673
- if (error instanceof AtomicRpcSpawnError) throw RequestError4.internalError({ code: error.code }, error.message);
2697
+ if (error instanceof AtomicRpcSpawnError)
2698
+ throw RequestError4.internalError({ code: error.code }, error.message);
2674
2699
  throw error;
2675
2700
  }
2676
2701
  try {
@@ -2810,7 +2835,8 @@ var AtomicAcpAgent = class {
2810
2835
  }
2811
2836
  const quietStartup = getQuietStartup(params.cwd);
2812
2837
  const updateNotice = buildUpdateNotice();
2813
- const preludeText = quietStartup ? updateNotice ? updateNotice + "\n" : "" : buildStartupInfo({
2838
+ const preludeText = quietStartup ? updateNotice ? `${updateNotice}
2839
+ ` : "" : buildStartupInfo({
2814
2840
  cwd: params.cwd,
2815
2841
  fileCommands,
2816
2842
  updateNotice
@@ -3104,7 +3130,9 @@ ${JSON.stringify(stats, null, 2)}`;
3104
3130
  return { stopReason: "end_turn" };
3105
3131
  }
3106
3132
  const maxChars = 2e4;
3107
- if (text.length > maxChars) text = text.slice(0, maxChars) + "\n\n...(truncated)...";
3133
+ if (text.length > maxChars) text = `${text.slice(0, maxChars)}
3134
+
3135
+ ...(truncated)...`;
3108
3136
  await this.conn.notify(methods3.client.session.update, {
3109
3137
  sessionId: session.sessionId,
3110
3138
  update: {
@@ -3122,7 +3150,10 @@ ${JSON.stringify(stats, null, 2)}`;
3122
3150
  sessionId: session.sessionId,
3123
3151
  update: {
3124
3152
  sessionUpdate: "agent_message_chunk",
3125
- content: { type: "text", text: "Nothing to export yet (no session messages). Send a prompt first." }
3153
+ content: {
3154
+ type: "text",
3155
+ text: "Nothing to export yet (no session messages). Send a prompt first."
3156
+ }
3126
3157
  }
3127
3158
  });
3128
3159
  return { stopReason: "end_turn" };
@@ -3468,7 +3499,10 @@ async function getThinkingState(proc, pre) {
3468
3499
  }
3469
3500
  async function getSessionConfiguration(proc, pre) {
3470
3501
  const state = pre?.state ?? await proc.getState();
3471
- const [models, modes] = await Promise.all([getModelState(proc, { ...pre, state }), getThinkingState(proc, { state })]);
3502
+ const [models, modes] = await Promise.all([
3503
+ getModelState(proc, { ...pre, state }),
3504
+ getThinkingState(proc, { state })
3505
+ ]);
3472
3506
  const configOptions = [
3473
3507
  {
3474
3508
  type: "select",
@@ -3727,7 +3761,8 @@ function buildStartupInfo(opts) {
3727
3761
  md.push(opts.updateNotice);
3728
3762
  md.push("");
3729
3763
  }
3730
- return md.join("\n").trim() + "\n";
3764
+ return `${md.join("\n").trim()}
3765
+ `;
3731
3766
  }
3732
3767
  function readNearestPackageJson(metaUrl) {
3733
3768
  try {