@bastani/atomic-acp 0.0.15 → 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() {
@@ -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";
@@ -802,7 +501,8 @@ var AtomicRpcProcess = class _AtomicRpcProcess {
802
501
  */
803
502
  async startPendingRecovery(reason) {
804
503
  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)}`);
504
+ if (!res.success)
505
+ throw new Error(`Atomic start_pending_recovery failed: ${res.error ?? JSON.stringify(res.data)}`);
806
506
  return res.data;
807
507
  }
808
508
  async getMessages() {
@@ -816,7 +516,8 @@ var AtomicRpcProcess = class _AtomicRpcProcess {
816
516
  return res.data;
817
517
  }
818
518
  writeJsonLine(value) {
819
- const line = JSON.stringify(value) + "\n";
519
+ const line = `${JSON.stringify(value)}
520
+ `;
820
521
  return new Promise((resolve2, reject) => {
821
522
  try {
822
523
  this.child.stdin.write(line, (err) => {
@@ -879,39 +580,126 @@ var AtomicRpcProcess = class _AtomicRpcProcess {
879
580
  }
880
581
  };
881
582
 
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("");
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
+ });
892
611
  }
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();
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
+ }
903
668
  }
904
- try {
905
- return JSON.stringify(result, null, 2);
906
- } catch {
907
- 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) });
908
699
  }
700
+ return items.sort((a, b) => (b.updatedAt ?? "").localeCompare(a.updatedAt ?? ""));
909
701
  }
910
702
 
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
703
  // src/acp/atomic-settings.ts
916
704
  import { existsSync, readFileSync } from "fs";
917
705
  import { homedir } from "os";
@@ -935,98 +723,409 @@ function readJsonFile(path) {
935
723
  const data = JSON.parse(raw.replace(/^\uFEFF/, ""));
936
724
  return isObject(data) ? data : {};
937
725
  } catch {
938
- return {};
939
- }
940
- }
941
- function getFirstDefinedEnv(names) {
942
- for (const name of names) {
943
- const value = process.env[name];
944
- 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;
945
981
  }
946
- return void 0;
947
- }
948
- function hasAgentDirOverride() {
949
- return process.env.ATOMIC_CODING_AGENT_DIR !== void 0 || process.env.PI_CODING_AGENT_DIR !== void 0;
950
982
  }
951
- function readMergedJsonFiles(paths) {
952
- let merged = {};
953
- for (let i = paths.length - 1; i >= 0; i--) {
954
- 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
+ });
955
999
  }
956
- return merged;
1000
+ return questions;
957
1001
  }
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")))
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 });
971
1036
  }
972
- ];
973
- }
974
- function getMergedSettings(cwd) {
975
- const settings = getSettingsWithLocations(cwd);
976
- return deepMerge(settings[0].settings, settings[1].settings);
1037
+ }
1038
+ return { type: "extension_ui_response", id, answers };
977
1039
  }
978
- function expandHomePath(value) {
979
- if (value === "~") return homedir();
980
- if (value.startsWith("~/")) return join2(homedir(), value.slice(2));
981
- 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() ?? "");
982
1044
  }
983
- function resolveAtomicPath(value, relativeBase = process.cwd()) {
984
- const expanded = expandHomePath(value);
985
- 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]));
986
1051
  }
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 });
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`);
994
1068
  }
995
1069
  }
996
- return { prompts };
997
1070
  }
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");
1071
+ function namespaceOf(name) {
1072
+ return name.replace(/-/g, "_");
1001
1073
  }
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];
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;
1007
1081
  }
1008
- function getProjectConfigDirs(cwd) {
1009
- const resolvedCwd = resolve(cwd);
1010
- 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 };
1011
1110
  }
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;
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;
1019
1116
  }
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;
1117
+ function sameMcpServers(a, b) {
1118
+ return JSON.stringify(toAtomicMcpServers(a ?? []).servers) === JSON.stringify(toAtomicMcpServers(b ?? []).servers);
1027
1119
  }
1028
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
+
1029
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";
1030
1129
  function parseFrontmatter(content) {
1031
1130
  const frontmatter = {};
1032
1131
  if (!content.startsWith("---")) return { frontmatter, content };
@@ -1211,132 +1310,137 @@ function expandSlashCommand(text, fileCommands) {
1211
1310
  const args = parseCommandArgs(argsString);
1212
1311
  return substituteArgs(cmd.content, args);
1213
1312
  }
1214
-
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]));
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;
1220
1354
  }
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
- }
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;
1238
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");
1239
1367
  }
1240
- function namespaceOf(name) {
1241
- 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;
1242
1372
  }
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;
1373
+ function bashOutputDelta(previous, next) {
1374
+ return next.startsWith(previous) ? next.slice(previous.length) : next;
1250
1375
  }
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 };
1376
+ function bashTerminalContent(id) {
1377
+ return [{ type: "terminal", terminalId: id }];
1279
1378
  }
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;
1379
+ function bashTerminalInfoMeta(id, cwd) {
1380
+ return { terminal_info: { terminal_id: id, cwd } };
1285
1381
  }
1286
- function sameMcpServers(a, b) {
1287
- 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 } };
1288
1387
  }
1289
1388
 
1290
1389
  // src/acp/translate/workflow-events.ts
1291
1390
  var TERMINAL_NOTICE_KINDS = /* @__PURE__ */ new Set(["completed", "failed", "blocked", "quit", "cancelled", "killed", "skipped"]);
1292
- function str(value) {
1391
+ function str2(value) {
1293
1392
  return typeof value === "string" && value ? value : void 0;
1294
1393
  }
1295
- function record2(value) {
1394
+ function record(value) {
1296
1395
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
1297
1396
  }
1298
1397
  function parseWorkflowEvent(ev) {
1299
1398
  if (ev.type === "entry_appended") {
1300
- const entry = record2(ev.entry);
1301
- const data = record2(entry?.data);
1302
- const runId = str(data?.runId);
1399
+ const entry = record(ev.entry);
1400
+ const data = record(entry?.data);
1401
+ const runId = str2(data?.runId);
1303
1402
  if (!entry || !data || !runId) return null;
1304
1403
  switch (entry.customType) {
1305
1404
  case "workflow.run.start":
1306
- return { kind: "run_start", runId, name: str(data.name) };
1405
+ return { kind: "run_start", runId, name: str2(data.name) };
1307
1406
  case "workflow.run.end":
1308
1407
  return {
1309
1408
  kind: "run_end",
1310
1409
  runId,
1311
- status: str(data.status) ?? "completed",
1410
+ status: str2(data.status) ?? "completed",
1312
1411
  ...data.result !== void 0 ? { result: data.result } : {},
1313
- ...str(data.error) ? { error: str(data.error) } : {}
1412
+ ...str2(data.error) ? { error: str2(data.error) } : {}
1314
1413
  };
1315
1414
  case "workflow.run.blocked":
1316
- 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
+ };
1317
1421
  case "workflow.stage.start":
1318
1422
  return {
1319
1423
  kind: "stage_start",
1320
1424
  runId,
1321
- stageId: str(data.stageId),
1322
- name: str(data.name),
1425
+ stageId: str2(data.stageId),
1426
+ name: str2(data.name),
1323
1427
  // Human-input prompt nodes (ctx.ui.input/confirm/select/editor/custom) use `prompt:` replay keys.
1324
- humanInput: str(data.replayKey)?.startsWith("prompt:") ?? false
1428
+ humanInput: str2(data.replayKey)?.startsWith("prompt:") ?? false
1325
1429
  };
1326
1430
  case "workflow.stage.end":
1327
- 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) };
1328
1432
  default:
1329
1433
  return null;
1330
1434
  }
1331
1435
  }
1332
1436
  if (ev.type === "message_end") {
1333
- const message = record2(ev.message);
1437
+ const message = record(ev.message);
1334
1438
  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);
1439
+ const details = record(message.details);
1440
+ const runId = str2(details?.runId);
1441
+ const kind = str2(details?.kind);
1338
1442
  if (!runId || !kind || details?.scope === "stage") return null;
1339
- 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) };
1340
1444
  if (TERMINAL_NOTICE_KINDS.has(kind)) return { kind: "run_end", runId, status: kind };
1341
1445
  }
1342
1446
  return null;
@@ -2354,7 +2458,8 @@ function loadFile(path) {
2354
2458
  }
2355
2459
  function saveFile(path, data) {
2356
2460
  ensureParentDir(path);
2357
- writeFileSync2(path, JSON.stringify(data, null, 2) + "\n", "utf-8");
2461
+ writeFileSync2(path, `${JSON.stringify(data, null, 2)}
2462
+ `, "utf-8");
2358
2463
  }
2359
2464
  var SessionStore = class {
2360
2465
  path;
@@ -2387,99 +2492,6 @@ var SessionStore = class {
2387
2492
  }
2388
2493
  };
2389
2494
 
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
2495
  // src/acp/translate/atomic-messages.ts
2484
2496
  function normalizeAtomicMessageText(content) {
2485
2497
  if (typeof content === "string") return content;
@@ -2491,43 +2503,36 @@ function normalizeAtomicAssistantText(content) {
2491
2503
  return content.map((c) => c?.type === "text" && typeof c.text === "string" ? c.text : "").filter(Boolean).join("");
2492
2504
  }
2493
2505
 
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)";
2506
+ // src/acp/workflow-history.ts
2507
+ function record2(value) {
2508
+ return value !== null && typeof value === "object" ? value : {};
2502
2509
  }
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
- });
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])}`);
2522
2518
  }
2523
- 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.";
2524
2533
  }
2525
2534
 
2526
2535
  // 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
2536
  import { fileURLToPath } from "url";
2532
2537
  var MODEL_CONFIG_ID = "model";
2533
2538
  var THOUGHT_LEVEL_CONFIG_ID = "thought_level";
@@ -2615,7 +2620,8 @@ var AtomicAcpAgent = class {
2615
2620
  try {
2616
2621
  proc = await AtomicRpcProcess.spawn({ cwd, atomicCommand: process.env.ATOMIC_ACP_ATOMIC_COMMAND });
2617
2622
  } catch (error) {
2618
- 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);
2619
2625
  throw error;
2620
2626
  }
2621
2627
  try {
@@ -2667,7 +2673,8 @@ var AtomicAcpAgent = class {
2667
2673
  async restoreSessionImpl(sessionId, opts) {
2668
2674
  const existing = this.sessions.maybeGet(sessionId);
2669
2675
  if (existing) {
2670
- 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}`);
2671
2678
  const sameServers = !opts?.mcpServers || sameMcpServers(existing.mcpServers, opts.mcpServers);
2672
2679
  if (sameServers && !existing.proc.hasExited) return existing;
2673
2680
  this.sessions.close(sessionId);
@@ -2687,7 +2694,8 @@ var AtomicAcpAgent = class {
2687
2694
  answersQuestionnaires: this.clientElicitationSupport.form
2688
2695
  });
2689
2696
  } catch (error) {
2690
- 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);
2691
2699
  throw error;
2692
2700
  }
2693
2701
  try {
@@ -2827,7 +2835,8 @@ var AtomicAcpAgent = class {
2827
2835
  }
2828
2836
  const quietStartup = getQuietStartup(params.cwd);
2829
2837
  const updateNotice = buildUpdateNotice();
2830
- const preludeText = quietStartup ? updateNotice ? updateNotice + "\n" : "" : buildStartupInfo({
2838
+ const preludeText = quietStartup ? updateNotice ? `${updateNotice}
2839
+ ` : "" : buildStartupInfo({
2831
2840
  cwd: params.cwd,
2832
2841
  fileCommands,
2833
2842
  updateNotice
@@ -3121,7 +3130,9 @@ ${JSON.stringify(stats, null, 2)}`;
3121
3130
  return { stopReason: "end_turn" };
3122
3131
  }
3123
3132
  const maxChars = 2e4;
3124
- 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)...`;
3125
3136
  await this.conn.notify(methods3.client.session.update, {
3126
3137
  sessionId: session.sessionId,
3127
3138
  update: {
@@ -3139,7 +3150,10 @@ ${JSON.stringify(stats, null, 2)}`;
3139
3150
  sessionId: session.sessionId,
3140
3151
  update: {
3141
3152
  sessionUpdate: "agent_message_chunk",
3142
- 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
+ }
3143
3157
  }
3144
3158
  });
3145
3159
  return { stopReason: "end_turn" };
@@ -3485,7 +3499,10 @@ async function getThinkingState(proc, pre) {
3485
3499
  }
3486
3500
  async function getSessionConfiguration(proc, pre) {
3487
3501
  const state = pre?.state ?? await proc.getState();
3488
- 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
+ ]);
3489
3506
  const configOptions = [
3490
3507
  {
3491
3508
  type: "select",
@@ -3744,7 +3761,8 @@ function buildStartupInfo(opts) {
3744
3761
  md.push(opts.updateNotice);
3745
3762
  md.push("");
3746
3763
  }
3747
- return md.join("\n").trim() + "\n";
3764
+ return `${md.join("\n").trim()}
3765
+ `;
3748
3766
  }
3749
3767
  function readNearestPackageJson(metaUrl) {
3750
3768
  try {