@bastani/atomic-acp 0.0.1 → 0.0.3

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
@@ -37,29 +37,29 @@ function isBashTool(name) {
37
37
  return name.toLowerCase() === "bash";
38
38
  }
39
39
  function bashCommand(value) {
40
- const record2 = value;
41
- for (const source of [record2, record2?.args, record2?.input, record2?.rawInput, record2?.toolInput, record2?.details]) {
40
+ const record3 = value;
41
+ for (const source of [record3, record3?.args, record3?.input, record3?.rawInput, record3?.toolInput, record3?.details]) {
42
42
  const command = source?.command ?? source?.cmd;
43
43
  if (typeof command === "string" && command.trim()) return command;
44
44
  }
45
45
  return void 0;
46
46
  }
47
47
  function bashResultText(value) {
48
- const record2 = value;
49
- if (Array.isArray(record2?.content)) {
50
- const text = record2.content.map(
48
+ const record3 = value;
49
+ if (Array.isArray(record3?.content)) {
50
+ const text = record3.content.map(
51
51
  (block) => block.type === "text" && typeof block.text === "string" ? block.text : ""
52
52
  ).join("");
53
53
  if (text) return text;
54
54
  }
55
- const details = record2?.details;
56
- const stdout = details?.stdout ?? record2?.stdout ?? details?.output ?? record2?.output;
57
- const stderr = details?.stderr ?? record2?.stderr;
55
+ const details = record3?.details;
56
+ const stdout = details?.stdout ?? record3?.stdout ?? details?.output ?? record3?.output;
57
+ const stderr = details?.stderr ?? record3?.stderr;
58
58
  return [stdout, stderr].filter((part) => typeof part === "string" && part.length > 0).join("\n");
59
59
  }
60
60
  function bashExitCode(value, isError) {
61
- const record2 = value;
62
- const code = record2?.details?.exitCode ?? record2?.exitCode ?? record2?.details?.code ?? record2?.code;
61
+ const record3 = value;
62
+ const code = record3?.details?.exitCode ?? record3?.exitCode ?? record3?.details?.code ?? record3?.code;
63
63
  return typeof code === "number" ? code : isError ? 1 : 0;
64
64
  }
65
65
  function bashOutputDelta(previous, next) {
@@ -80,7 +80,7 @@ function bashTerminalExitMeta(id, exitCode) {
80
80
 
81
81
  // src/acp/agent.ts
82
82
  import {
83
- RequestError as RequestError3
83
+ RequestError as RequestError4
84
84
  } from "@agentclientprotocol/sdk";
85
85
 
86
86
  // src/acp/auth.ts
@@ -133,7 +133,7 @@ function readClientElicitationSupport(params) {
133
133
  }
134
134
  return NO_CLIENT_ELICITATION_SUPPORT;
135
135
  }
136
- function requestExtensionDialog(conn, sessionId, ev, form, signal) {
136
+ function requestExtensionDialog(conn, sessionId, ev, form, signal, onClientCannotAnswer) {
137
137
  const cancelled = {
138
138
  type: "extension_ui_response",
139
139
  id: String(ev.id),
@@ -147,10 +147,10 @@ function requestExtensionDialog(conn, sessionId, ev, form, signal) {
147
147
  };
148
148
  const abort = () => finish(cancelled);
149
149
  signal?.addEventListener("abort", abort, { once: true });
150
- void requestDialog(conn, sessionId, ev, form).then(finish);
150
+ void requestDialog(conn, sessionId, ev, form, onClientCannotAnswer).then(finish);
151
151
  });
152
152
  }
153
- async function requestDialog(conn, sessionId, ev, form) {
153
+ async function requestDialog(conn, sessionId, ev, form, onClientCannotAnswer) {
154
154
  const id = String(ev.id);
155
155
  const cancelled = { type: "extension_ui_response", id, cancelled: true };
156
156
  const method = ev.method;
@@ -205,12 +205,13 @@ ${ev.message}` : title,
205
205
  const index = options.findIndex((_, index2) => optionId === `choice-${index2}`);
206
206
  return index < 0 ? cancelled : { type: "extension_ui_response", id, value: options[index] };
207
207
  } catch {
208
+ onClientCannotAnswer?.();
208
209
  return cancelled;
209
210
  }
210
211
  }
211
212
 
212
213
  // src/acp/session.ts
213
- import { RequestError as RequestError2 } from "@agentclientprotocol/sdk";
214
+ import { RequestError as RequestError3 } from "@agentclientprotocol/sdk";
214
215
 
215
216
  // src/acp/auth-required.ts
216
217
  import { RequestError } from "@agentclientprotocol/sdk";
@@ -261,6 +262,146 @@ function shouldUseShellForAtomicCommand(cmd) {
261
262
  const normalized = cmd.trim().toLowerCase();
262
263
  return normalized.endsWith(".cmd") || normalized.endsWith(".bat");
263
264
  }
265
+ var RESERVED_ATOMIC_ARGS = /* @__PURE__ */ new Set([
266
+ "--",
267
+ "--mode",
268
+ "-p",
269
+ "--print",
270
+ "--session",
271
+ "--session-id",
272
+ "--session-dir",
273
+ "--no-session",
274
+ "-c",
275
+ "--continue",
276
+ "-r",
277
+ "--resume",
278
+ "--fork",
279
+ "--export",
280
+ "--list-models",
281
+ "-h",
282
+ "--help",
283
+ "-v",
284
+ "--version"
285
+ ]);
286
+ function validateAtomicArg(arg, source) {
287
+ if (arg.includes("\0")) throw new Error(`${source}: arguments must not contain NUL characters`);
288
+ const flag = arg.startsWith("--") ? arg.split("=", 1)[0] : arg;
289
+ if (RESERVED_ATOMIC_ARGS.has(flag)) throw new Error(`${source}: ${flag} is not allowed; atomic-acp manages it`);
290
+ return arg;
291
+ }
292
+ function parseAtomicExtraArgs(argv, env) {
293
+ const fromEnv = [];
294
+ const raw = env.ATOMIC_ACP_ATOMIC_ARGS;
295
+ if (raw !== void 0 && raw.trim() !== "") {
296
+ let parsed;
297
+ try {
298
+ parsed = JSON.parse(raw);
299
+ } catch {
300
+ throw new Error("ATOMIC_ACP_ATOMIC_ARGS must be a JSON array of strings");
301
+ }
302
+ if (!Array.isArray(parsed) || !parsed.every((arg) => typeof arg === "string")) {
303
+ throw new Error("ATOMIC_ACP_ATOMIC_ARGS must be a JSON array of strings");
304
+ }
305
+ fromEnv.push(...parsed.map((arg) => validateAtomicArg(arg, "ATOMIC_ACP_ATOMIC_ARGS")));
306
+ }
307
+ const separator2 = argv.indexOf("--", 2);
308
+ const fromArgv = separator2 < 0 ? [] : argv.slice(separator2 + 1).map((arg) => validateAtomicArg(arg, "arguments after --"));
309
+ return [...fromEnv, ...fromArgv];
310
+ }
311
+
312
+ // src/atomic-rpc/adapter-extension.ts
313
+ import { randomBytes } from "crypto";
314
+ import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "fs";
315
+ import { rm } from "fs/promises";
316
+ import { tmpdir } from "os";
317
+ import { join } from "path";
318
+ var RETRYABLE_RM_CODES = /* @__PURE__ */ new Set(["EBUSY", "EPERM", "ENOTEMPTY", "EMFILE", "ENFILE"]);
319
+ var RM_RETRY_DELAYS_MS = [50, 100, 200, 400, 800, 1600];
320
+ var liveDirs = /* @__PURE__ */ new Set();
321
+ var exitHookInstalled = false;
322
+ function removeDirNow(dir) {
323
+ try {
324
+ rmSync(dir, { recursive: true, force: true });
325
+ liveDirs.delete(dir);
326
+ } catch {
327
+ }
328
+ }
329
+ async function removeDir(dir, cleanup) {
330
+ const removeTree = cleanup.rm ?? ((path) => rm(path, { recursive: true, force: true }));
331
+ const delays = cleanup.retryDelaysMs ?? RM_RETRY_DELAYS_MS;
332
+ for (let attempt = 0; ; attempt++) {
333
+ try {
334
+ await removeTree(dir);
335
+ liveDirs.delete(dir);
336
+ return;
337
+ } catch (error) {
338
+ const delay = delays[attempt];
339
+ const code = error?.code;
340
+ if (delay === void 0 || code === void 0 || !RETRYABLE_RM_CODES.has(code)) return;
341
+ await new Promise((resolve3) => setTimeout(resolve3, delay));
342
+ }
343
+ }
344
+ }
345
+ function installExitHook() {
346
+ if (exitHookInstalled) return;
347
+ exitHookInstalled = true;
348
+ process.once("exit", () => {
349
+ for (const dir of [...liveDirs]) removeDirNow(dir);
350
+ });
351
+ }
352
+ function referenceSecretValues(servers) {
353
+ const env = {};
354
+ const reference = (values) => Object.fromEntries(
355
+ Object.entries(values).map(([key, value]) => {
356
+ if (value === "") return [key, ""];
357
+ const name = `ATOMIC_ACP_MCP_${randomBytes(12).toString("hex").toUpperCase()}`;
358
+ env[name] = value;
359
+ return [key, `\${${name}}`];
360
+ })
361
+ );
362
+ const out = Object.fromEntries(
363
+ Object.entries(servers).map(([name, config]) => [
364
+ name,
365
+ {
366
+ ...config,
367
+ ...config.env ? { env: reference(config.env) } : {},
368
+ ...config.headers ? { headers: reference(config.headers) } : {}
369
+ }
370
+ ])
371
+ );
372
+ return { servers: out, env };
373
+ }
374
+ function writeAdapterExtension(options, cleanup = {}) {
375
+ const { servers, env } = referenceSecretValues(options.mcpServers ?? {});
376
+ const askReason = options.askUserQuestionUnavailable;
377
+ if (Object.keys(servers).length === 0 && askReason === void 0) return void 0;
378
+ const dir = mkdtempSync(join(tmpdir(), "atomic-acp-ext-"));
379
+ liveDirs.add(dir);
380
+ installExitHook();
381
+ try {
382
+ chmodSync(dir, 448);
383
+ const path = join(dir, "atomic-acp.mjs");
384
+ const source = [
385
+ `const servers = ${JSON.stringify(servers)}`,
386
+ `const askUserQuestionUnavailable = ${JSON.stringify(askReason ?? null)}`,
387
+ "export default function (pi) {",
388
+ " for (const [name, config] of Object.entries(servers)) pi.registerMcpServer(name, config)",
389
+ " if (askUserQuestionUnavailable !== null) {",
390
+ ' pi.on("tool_call", event => {',
391
+ ' if (event.toolName === "ask_user_question") return { block: true, reason: askUserQuestionUnavailable }',
392
+ " })",
393
+ " }",
394
+ "}",
395
+ ""
396
+ ].join("\n");
397
+ writeFileSync(path, source, { mode: 384 });
398
+ let removal;
399
+ return { path, env, dispose: () => removal ??= removeDir(dir, cleanup) };
400
+ } catch (error) {
401
+ removeDirNow(dir);
402
+ throw error;
403
+ }
404
+ }
264
405
 
265
406
  // src/atomic-rpc/process.ts
266
407
  var AtomicRpcSpawnError = class extends Error {
@@ -273,6 +414,16 @@ var AtomicRpcSpawnError = class extends Error {
273
414
  this.cause = opts?.cause;
274
415
  }
275
416
  };
417
+ var AtomicProcessExitError = class extends Error {
418
+ exitCode;
419
+ signal;
420
+ constructor(exitCode, signal) {
421
+ super(`Atomic process exited (code=${exitCode}, signal=${signal})`);
422
+ this.name = "AtomicProcessExitError";
423
+ this.exitCode = exitCode;
424
+ this.signal = signal;
425
+ }
426
+ };
276
427
  var ESC = String.fromCharCode(27);
277
428
  var CSI = String.fromCharCode(155);
278
429
  var ANSI_ESCAPE_REGEX = new RegExp(
@@ -287,6 +438,8 @@ function splitLfJsonlChunk(buffer, chunk) {
287
438
  const parts = combined.split("\n");
288
439
  return { lines: parts.slice(0, -1), buffer: parts.at(-1) ?? "" };
289
440
  }
441
+ var NO_PERSON_FOR_ASK_USER_QUESTION = "No person is available to answer questions in this session: the ACP client is running headless. Do not ask again. In your final reply, state the question you needed answered and the assumption you made or would need, then stop.";
442
+ var DISPOSE_EXIT_WAIT_MS = 5e3;
290
443
  var SESSION_STATS_TIMEOUT_MS = 1e3;
291
444
  var AtomicRpcProcess = class _AtomicRpcProcess {
292
445
  child;
@@ -294,8 +447,13 @@ var AtomicRpcProcess = class _AtomicRpcProcess {
294
447
  eventHandlers = [];
295
448
  exitHandlers = [];
296
449
  preludeLines = [];
297
- constructor(child) {
450
+ adapterExtension;
451
+ exitError;
452
+ exited;
453
+ constructor(child, adapterExtension) {
298
454
  this.child = child;
455
+ this.adapterExtension = adapterExtension;
456
+ this.exited = new Promise((resolve3) => child.once("exit", () => resolve3()));
299
457
  let stdoutBuffer = "";
300
458
  child.stdout.setEncoding("utf8");
301
459
  child.stdout.on("data", (chunk) => {
@@ -320,8 +478,9 @@ var AtomicRpcProcess = class _AtomicRpcProcess {
320
478
  }
321
479
  });
322
480
  child.on("exit", (code, signal) => {
323
- const err = new Error(`Atomic process exited (code=${code}, signal=${signal})`);
324
- this.rejectPendingAndNotifyExit(err);
481
+ void this.adapterExtension?.dispose();
482
+ this.exitError = new AtomicProcessExitError(code, signal);
483
+ this.rejectPendingAndNotifyExit(this.exitError);
325
484
  });
326
485
  child.on("error", (err) => {
327
486
  this.rejectPendingAndNotifyExit(err instanceof Error ? err : new Error(String(err)));
@@ -329,14 +488,33 @@ var AtomicRpcProcess = class _AtomicRpcProcess {
329
488
  }
330
489
  static async spawn(params) {
331
490
  const cmd = getAtomicCommand(params.atomicCommand);
491
+ let extraArgs;
492
+ try {
493
+ extraArgs = params.extraArgs ?? parseAtomicExtraArgs(process.argv, process.env);
494
+ } catch (e) {
495
+ throw new AtomicRpcSpawnError(`Could not start Atomic: ${e.message}`, { cause: e });
496
+ }
332
497
  const args = ["--mode", "rpc", "--no-themes"];
333
498
  if (params.sessionPath) args.push("--session", params.sessionPath);
334
- const start = shouldUseShellForAtomicCommand(cmd) ? crossSpawn : spawn;
335
- const child = start(cmd, args, {
336
- cwd: params.cwd,
337
- stdio: "pipe",
338
- env: process.env
499
+ const adapterExtension = writeAdapterExtension({
500
+ mcpServers: params.mcpServers,
501
+ ...params.headless ? { askUserQuestionUnavailable: NO_PERSON_FOR_ASK_USER_QUESTION } : {}
339
502
  });
503
+ if (adapterExtension) args.push("-e", adapterExtension.path);
504
+ args.push(...extraArgs);
505
+ const start = shouldUseShellForAtomicCommand(cmd) ? crossSpawn : spawn;
506
+ let child;
507
+ try {
508
+ child = start(cmd, args, {
509
+ cwd: params.cwd,
510
+ stdio: "pipe",
511
+ // Atomic enables Node's on-disk compile cache, which would keep a copy of the extension.
512
+ env: adapterExtension ? { ...process.env, ...adapterExtension.env, NODE_DISABLE_COMPILE_CACHE: "1" } : process.env
513
+ });
514
+ } catch (e) {
515
+ await adapterExtension?.dispose();
516
+ throw e;
517
+ }
340
518
  try {
341
519
  await new Promise((resolve3, reject) => {
342
520
  const onSpawn = () => {
@@ -355,6 +533,7 @@ var AtomicRpcProcess = class _AtomicRpcProcess {
355
533
  child.once("error", onError);
356
534
  });
357
535
  } catch (e) {
536
+ await adapterExtension?.dispose();
358
537
  const code = typeof e?.code === "string" ? e.code : void 0;
359
538
  if (code === "ENOENT") {
360
539
  throw new AtomicRpcSpawnError(
@@ -372,7 +551,7 @@ var AtomicRpcProcess = class _AtomicRpcProcess {
372
551
  }
373
552
  child.stderr.on("data", () => {
374
553
  });
375
- const proc = new _AtomicRpcProcess(child);
554
+ const proc = new _AtomicRpcProcess(child, adapterExtension);
376
555
  try {
377
556
  const state = await proc.getState();
378
557
  const sessionFile = typeof state?.sessionFile === "string" ? state.sessionFile : null;
@@ -385,6 +564,10 @@ var AtomicRpcProcess = class _AtomicRpcProcess {
385
564
  }
386
565
  return proc;
387
566
  }
567
+ /** Whether the Atomic process has exited. A session whose Atomic exited needs a new process. */
568
+ get hasExited() {
569
+ return this.exitError !== void 0;
570
+ }
388
571
  onEvent(handler) {
389
572
  this.eventHandlers.push(handler);
390
573
  return () => {
@@ -402,12 +585,29 @@ var AtomicRpcProcess = class _AtomicRpcProcess {
402
585
  this.pending.clear();
403
586
  for (const h of this.exitHandlers) h(err);
404
587
  }
405
- dispose(signal = "SIGTERM") {
406
- if (this.child.killed) return;
407
- try {
408
- this.child.kill(signal);
409
- } catch {
588
+ /**
589
+ * Stop Atomic. Resolves once it has exited (or after a bounded wait) and its extension is removed;
590
+ * never rejects. Windows keeps the extension's directory busy while Atomic still runs.
591
+ */
592
+ async dispose(signal = "SIGTERM") {
593
+ if (!this.hasExited && !this.child.killed) {
594
+ try {
595
+ this.child.kill(signal);
596
+ } catch {
597
+ }
410
598
  }
599
+ if (!this.hasExited) {
600
+ let timer;
601
+ await Promise.race([
602
+ this.exited,
603
+ new Promise((resolve3) => {
604
+ timer = setTimeout(resolve3, DISPOSE_EXIT_WAIT_MS);
605
+ timer.unref?.();
606
+ })
607
+ ]);
608
+ clearTimeout(timer);
609
+ }
610
+ await this.adapterExtension?.dispose();
411
611
  }
412
612
  /**
413
613
  * Human-readable stdout lines emitted before RPC NDJSON begins (e.g. Context/Skills/Extensions info).
@@ -536,6 +736,7 @@ var AtomicRpcProcess = class _AtomicRpcProcess {
536
736
  return res.data;
537
737
  }
538
738
  request(cmd, opts) {
739
+ if (this.exitError) return Promise.reject(this.exitError);
539
740
  const id = crypto.randomUUID();
540
741
  const withId = { ...cmd, id };
541
742
  const timeoutMs = opts?.timeoutMs;
@@ -575,17 +776,17 @@ var AtomicRpcProcess = class _AtomicRpcProcess {
575
776
  };
576
777
 
577
778
  // src/acp/session-store.ts
578
- import { mkdirSync, readFileSync, writeFileSync } from "fs";
779
+ import { mkdirSync, readFileSync, writeFileSync as writeFileSync2 } from "fs";
579
780
  import { dirname } from "path";
580
781
 
581
782
  // src/acp/paths.ts
582
783
  import { homedir } from "os";
583
- import { join } from "path";
784
+ import { join as join2 } from "path";
584
785
  function getAtomicAcpDir() {
585
- return join(homedir(), ".atomic", "atomic-acp");
786
+ return join2(homedir(), ".atomic", "atomic-acp");
586
787
  }
587
788
  function getAtomicAcpSessionMapPath() {
588
- return join(getAtomicAcpDir(), "session-map.json");
789
+ return join2(getAtomicAcpDir(), "session-map.json");
589
790
  }
590
791
 
591
792
  // src/acp/session-store.ts
@@ -606,7 +807,7 @@ function loadFile(path) {
606
807
  }
607
808
  function saveFile(path, data) {
608
809
  ensureParentDir(path);
609
- writeFileSync(path, JSON.stringify(data, null, 2) + "\n", "utf-8");
810
+ writeFileSync2(path, JSON.stringify(data, null, 2) + "\n", "utf-8");
610
811
  }
611
812
  var SessionStore = class {
612
813
  path;
@@ -666,12 +867,12 @@ ${stderr}`);
666
867
 
667
868
  // src/acp/slash-commands.ts
668
869
  import { existsSync as existsSync2, readdirSync, readFileSync as readFileSync3, statSync } from "fs";
669
- import { basename, join as join3 } from "path";
870
+ import { basename, join as join4 } from "path";
670
871
 
671
872
  // src/acp/atomic-settings.ts
672
873
  import { existsSync, readFileSync as readFileSync2 } from "fs";
673
874
  import { homedir as homedir2 } from "os";
674
- import { join as join2, resolve } from "path";
875
+ import { join as join3, resolve } from "path";
675
876
  function isObject(x) {
676
877
  return Boolean(x) && typeof x === "object" && !Array.isArray(x);
677
878
  }
@@ -718,12 +919,12 @@ function getSettingsWithLocations(cwd) {
718
919
  {
719
920
  location: "user",
720
921
  baseDirs: agentDirs,
721
- settings: readMergedJsonFiles(agentDirs.map((dir) => join2(dir, "settings.json")))
922
+ settings: readMergedJsonFiles(agentDirs.map((dir) => join3(dir, "settings.json")))
722
923
  },
723
924
  {
724
925
  location: "project",
725
926
  baseDirs: projectDirs,
726
- settings: readMergedJsonFiles(projectDirs.map((dir) => join2(dir, "settings.json")))
927
+ settings: readMergedJsonFiles(projectDirs.map((dir) => join3(dir, "settings.json")))
727
928
  }
728
929
  ];
729
930
  }
@@ -733,7 +934,7 @@ function getMergedSettings(cwd) {
733
934
  }
734
935
  function expandHomePath(value) {
735
936
  if (value === "~") return homedir2();
736
- if (value.startsWith("~/")) return join2(homedir2(), value.slice(2));
937
+ if (value.startsWith("~/")) return join3(homedir2(), value.slice(2));
737
938
  return value;
738
939
  }
739
940
  function resolveAtomicPath(value, relativeBase = process.cwd()) {
@@ -753,12 +954,12 @@ function readMergedResourceSettings(cwd) {
753
954
  }
754
955
  function getAgentDir() {
755
956
  const override = getFirstDefinedEnv(["ATOMIC_CODING_AGENT_DIR", "PI_CODING_AGENT_DIR"])?.trim();
756
- return override ? resolveAtomicPath(override) : join2(homedir2(), ".atomic", "agent");
957
+ return override ? resolveAtomicPath(override) : join3(homedir2(), ".atomic", "agent");
757
958
  }
758
959
  function getAgentDirs() {
759
960
  const primary = getAgentDir();
760
961
  if (hasAgentDirOverride()) return [primary];
761
- const legacy = join2(homedir2(), ".pi", "agent");
962
+ const legacy = join3(homedir2(), ".pi", "agent");
762
963
  return legacy === primary ? [primary] : [primary, legacy];
763
964
  }
764
965
  function getProjectConfigDirs(cwd) {
@@ -829,7 +1030,7 @@ function loadCommandsFromDir(dir, source, subdir = "") {
829
1030
  const entries = readdirSync(dir, { withFileTypes: true });
830
1031
  for (const entry of entries) {
831
1032
  if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
832
- const fullPath = join3(dir, entry.name);
1033
+ const fullPath = join4(dir, entry.name);
833
1034
  const sourceStr = source === "path" ? "(path)" : source === "user" ? subdir ? `(user:${subdir})` : "(user)" : subdir ? `(project:${subdir})` : "(project)";
834
1035
  const command = loadCommandFromFile(fullPath, sourceStr);
835
1036
  if (command) commands.push(command);
@@ -880,8 +1081,8 @@ function loadSlashCommands(cwd) {
880
1081
  commands.push(...loadCommandsFromSettingPath(resolved, entry.location));
881
1082
  }
882
1083
  }
883
- const projectDirs = getProjectConfigDirs(cwd).map((configDir) => join3(configDir, "prompts"));
884
- const userDirs = getAgentDirs().map((agentDir) => join3(agentDir, "prompts"));
1084
+ const projectDirs = getProjectConfigDirs(cwd).map((configDir) => join4(configDir, "prompts"));
1085
+ const userDirs = getAgentDirs().map((agentDir) => join4(agentDir, "prompts"));
885
1086
  for (const projectDir of projectDirs) commands.push(...loadCommandsFromDir(projectDir, "project"));
886
1087
  for (const userDir of userDirs) commands.push(...loadCommandsFromDir(userDir, "user"));
887
1088
  return filterExcluded(commands, excludedPaths);
@@ -968,7 +1169,143 @@ function expandSlashCommand(text, fileCommands) {
968
1169
  return substituteArgs(cmd.content, args);
969
1170
  }
970
1171
 
1172
+ // src/acp/mcp-servers.ts
1173
+ import { RequestError as RequestError2 } from "@agentclientprotocol/sdk";
1174
+ var RESERVED_NAMES = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
1175
+ function toRecord(entries) {
1176
+ return Object.fromEntries(entries.map((entry) => [entry.name, entry.value]));
1177
+ }
1178
+ var HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
1179
+ var HEADER_VALUE_BREAK = /[\r\n\0]/;
1180
+ var URL_ENV_REFERENCE = /\$\{|\$env:/i;
1181
+ function assertUsable(server) {
1182
+ const refuse = (reason) => {
1183
+ throw RequestError2.invalidParams(void 0, `MCP server ${JSON.stringify(server.name)} refused: ${reason}`);
1184
+ };
1185
+ if ("type" in server && server.type === "http") {
1186
+ if (URL_ENV_REFERENCE.test(server.url)) refuse("its URL contains an environment reference (${...} or $env:)");
1187
+ for (const { name, value } of server.headers ?? []) {
1188
+ if (!HEADER_NAME.test(name)) refuse(`header name ${JSON.stringify(name)} is not a valid HTTP header name`);
1189
+ if (HEADER_VALUE_BREAK.test(value)) refuse(`header ${JSON.stringify(name)} has a CR, LF or NUL in its value`);
1190
+ }
1191
+ } else if ("command" in server) {
1192
+ for (const { name, value } of server.env ?? []) {
1193
+ if (value.includes("\0")) refuse(`env ${JSON.stringify(name)} has a NUL in its value`);
1194
+ }
1195
+ }
1196
+ }
1197
+ function namespaceOf(name) {
1198
+ return name.replace(/-/g, "_");
1199
+ }
1200
+ function uniqueServerName(requested, taken) {
1201
+ let base = requested.replace(/[^A-Za-z0-9_-]/g, "_") || "mcp";
1202
+ if (RESERVED_NAMES.has(base)) base = `${base}_`;
1203
+ let name = base;
1204
+ for (let n = 2; taken.has(namespaceOf(name)); n += 1) name = `${base}_${n}`;
1205
+ taken.add(namespaceOf(name));
1206
+ return name;
1207
+ }
1208
+ function toAtomicMcpServers(servers) {
1209
+ const out = /* @__PURE__ */ new Map();
1210
+ const warnings = [];
1211
+ const taken = /* @__PURE__ */ new Set();
1212
+ for (const server of servers) assertUsable(server);
1213
+ for (const server of servers) {
1214
+ if ("type" in server && server.type === "http") {
1215
+ out.set(uniqueServerName(server.name, taken), {
1216
+ url: server.url,
1217
+ headers: toRecord(server.headers ?? []),
1218
+ exposure: "direct"
1219
+ });
1220
+ } else if ("type" in server && server.type === "sse") {
1221
+ warnings.push(`MCP server "${server.name}" skipped: Atomic does not support the SSE transport`);
1222
+ } else if ("command" in server) {
1223
+ out.set(uniqueServerName(server.name, taken), {
1224
+ command: server.command,
1225
+ args: [...server.args ?? []],
1226
+ env: toRecord(server.env ?? []),
1227
+ exposure: "direct"
1228
+ });
1229
+ } else {
1230
+ const type = "type" in server ? String(server.type) : "unknown";
1231
+ warnings.push(`MCP server "${server.name}" skipped: Atomic does not support the ${type} transport`);
1232
+ }
1233
+ }
1234
+ return { servers: Object.fromEntries(out), warnings };
1235
+ }
1236
+ function atomicMcpServersForSpawn(servers) {
1237
+ const { servers: mapped, warnings } = toAtomicMcpServers(servers ?? []);
1238
+ for (const warning of warnings) process.stderr.write(`atomic-acp: ${warning}
1239
+ `);
1240
+ return mapped;
1241
+ }
1242
+ function sameMcpServers(a, b) {
1243
+ return JSON.stringify(toAtomicMcpServers(a ?? []).servers) === JSON.stringify(toAtomicMcpServers(b ?? []).servers);
1244
+ }
1245
+
1246
+ // src/acp/translate/workflow-events.ts
1247
+ var TERMINAL_NOTICE_KINDS = /* @__PURE__ */ new Set(["completed", "failed", "blocked", "quit", "cancelled", "killed", "skipped"]);
1248
+ function str(value) {
1249
+ return typeof value === "string" && value ? value : void 0;
1250
+ }
1251
+ function record2(value) {
1252
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
1253
+ }
1254
+ function parseWorkflowEvent(ev) {
1255
+ if (ev.type === "entry_appended") {
1256
+ const entry = record2(ev.entry);
1257
+ const data = record2(entry?.data);
1258
+ const runId = str(data?.runId);
1259
+ if (!entry || !data || !runId) return null;
1260
+ switch (entry.customType) {
1261
+ case "workflow.run.start":
1262
+ return { kind: "run_start", runId, name: str(data.name) };
1263
+ case "workflow.run.end":
1264
+ return {
1265
+ kind: "run_end",
1266
+ runId,
1267
+ status: str(data.status) ?? "completed",
1268
+ ...data.result !== void 0 ? { result: data.result } : {},
1269
+ ...str(data.error) ? { error: str(data.error) } : {}
1270
+ };
1271
+ case "workflow.run.blocked":
1272
+ return { kind: "run_end", runId, status: "blocked", ...str(data.error) ? { error: str(data.error) } : {} };
1273
+ case "workflow.stage.start":
1274
+ return {
1275
+ kind: "stage_start",
1276
+ runId,
1277
+ stageId: str(data.stageId),
1278
+ name: str(data.name),
1279
+ // Human-input prompt nodes (ctx.ui.input/confirm/select/editor/custom) use `prompt:` replay keys.
1280
+ humanInput: str(data.replayKey)?.startsWith("prompt:") ?? false
1281
+ };
1282
+ case "workflow.stage.end":
1283
+ return { kind: "stage_end", runId, stageId: str(data.stageId), status: str(data.status) };
1284
+ default:
1285
+ return null;
1286
+ }
1287
+ }
1288
+ if (ev.type === "message_end") {
1289
+ const message = record2(ev.message);
1290
+ if (message?.role !== "custom" || message.customType !== "workflows:lifecycle-notice") return null;
1291
+ const details = record2(message.details);
1292
+ const runId = str(details?.runId);
1293
+ const kind = str(details?.kind);
1294
+ if (!runId || !kind || details?.scope === "stage") return null;
1295
+ if (kind === "started") return { kind: "run_start", runId, name: str(details?.workflowName) };
1296
+ if (TERMINAL_NOTICE_KINDS.has(kind)) return { kind: "run_end", runId, status: kind };
1297
+ }
1298
+ return null;
1299
+ }
1300
+
971
1301
  // src/acp/session.ts
1302
+ function atomicExitReason(err) {
1303
+ return err instanceof AtomicProcessExitError ? `Atomic exited (code=${err.exitCode}, signal=${err.signal})` : `Atomic exited: ${err.message}`;
1304
+ }
1305
+ var WORKFLOW_FOLLOW_UP_GRACE_MS = 3e3;
1306
+ function waitForWorkflowsFromEnv() {
1307
+ return !/^(0|false|no)$/i.test(process.env.ATOMIC_ACP_WAIT_FOR_WORKFLOWS?.trim() ?? "");
1308
+ }
972
1309
  function toUsageUpdate(stats) {
973
1310
  const used = stats?.contextUsage?.tokens;
974
1311
  const size = stats?.contextUsage?.contextWindow;
@@ -989,11 +1326,11 @@ function findUniqueLineNumber(text, needle) {
989
1326
  return line;
990
1327
  }
991
1328
  function getMutationPaths(args) {
992
- const record2 = args;
993
- const path = record2?.path ?? record2?.file_path;
1329
+ const record3 = args;
1330
+ const path = record3?.path ?? record3?.file_path;
994
1331
  if (typeof path === "string") return [path];
995
- if (typeof record2?.input !== "string") return [];
996
- return [...record2.input.matchAll(/^\[(.+)#[0-9a-fA-F]{4}\]\s*$/gm)].map((match) => match[1]);
1332
+ if (typeof record3?.input !== "string") return [];
1333
+ return [...record3.input.matchAll(/^\[(.+)#[0-9a-fA-F]{4}\]\s*$/gm)].map((match) => match[1]);
997
1334
  }
998
1335
  function toToolCallLocations(args, cwd, line) {
999
1336
  const paths = getMutationPaths(args);
@@ -1039,11 +1376,13 @@ var SessionManager = class {
1039
1376
  try {
1040
1377
  proc = await AtomicRpcProcess.spawn({
1041
1378
  cwd: params.cwd,
1042
- atomicCommand: params.atomicCommand
1379
+ atomicCommand: params.atomicCommand,
1380
+ mcpServers: atomicMcpServersForSpawn(params.mcpServers),
1381
+ headless: params.headless
1043
1382
  });
1044
1383
  } catch (e) {
1045
1384
  if (e instanceof AtomicRpcSpawnError) {
1046
- throw RequestError2.internalError({ code: e.code }, e.message);
1385
+ throw RequestError3.internalError({ code: e.code }, e.message);
1047
1386
  }
1048
1387
  throw e;
1049
1388
  }
@@ -1066,14 +1405,15 @@ var SessionManager = class {
1066
1405
  conn: params.conn,
1067
1406
  fileCommands: params.fileCommands ?? [],
1068
1407
  autoTitle: true,
1069
- clientElicitationSupport: params.clientElicitationSupport
1408
+ clientElicitationSupport: params.clientElicitationSupport,
1409
+ headless: params.headless
1070
1410
  });
1071
1411
  this.sessions.set(sessionId, session);
1072
1412
  return session;
1073
1413
  }
1074
1414
  get(sessionId) {
1075
1415
  const s = this.sessions.get(sessionId);
1076
- if (!s) throw RequestError2.invalidParams(`Unknown sessionId: ${sessionId}`);
1416
+ if (!s) throw RequestError3.invalidParams(`Unknown sessionId: ${sessionId}`);
1077
1417
  return s;
1078
1418
  }
1079
1419
  /**
@@ -1090,7 +1430,8 @@ var SessionManager = class {
1090
1430
  proc: params.proc,
1091
1431
  conn: params.conn,
1092
1432
  fileCommands: params.fileCommands ?? [],
1093
- clientElicitationSupport: params.clientElicitationSupport
1433
+ clientElicitationSupport: params.clientElicitationSupport,
1434
+ headless: params.headless
1094
1435
  });
1095
1436
  this.sessions.set(sessionId, session);
1096
1437
  return session;
@@ -1108,6 +1449,7 @@ var AtomicAcpSession = class {
1108
1449
  proc;
1109
1450
  conn;
1110
1451
  clientElicitationSupport;
1452
+ headless;
1111
1453
  fileCommands;
1112
1454
  // Used to map abort semantics to ACP stopReason.
1113
1455
  // Applies to the currently running turn.
@@ -1129,7 +1471,16 @@ var AtomicAcpSession = class {
1129
1471
  // Ensure `session/update` notifications are sent in order and can be awaited
1130
1472
  // before completing a `session/prompt` request.
1131
1473
  lastEmit = Promise.resolve();
1474
+ // Set once Atomic exits; every later prompt to this process fails with it.
1475
+ atomicExit = null;
1132
1476
  pendingExtensionDialogs = /* @__PURE__ */ new Map();
1477
+ workflowRunNames = /* @__PURE__ */ new Map();
1478
+ // Workflow runs started during the current prompt turn. The turn stays open until they end.
1479
+ waitForWorkflows;
1480
+ workflowFollowUpGraceMs;
1481
+ turnWorkflowRuns = /* @__PURE__ */ new Map();
1482
+ waitingForWorkflows = false;
1483
+ workflowGraceTimer;
1133
1484
  constructor(opts) {
1134
1485
  this.sessionId = opts.sessionId;
1135
1486
  this.cwd = opts.cwd;
@@ -1137,6 +1488,9 @@ var AtomicAcpSession = class {
1137
1488
  this.proc = opts.proc;
1138
1489
  this.conn = opts.conn;
1139
1490
  this.clientElicitationSupport = opts.clientElicitationSupport ?? NO_CLIENT_ELICITATION_SUPPORT;
1491
+ this.headless = opts.headless ?? false;
1492
+ this.waitForWorkflows = opts.waitForWorkflows ?? waitForWorkflowsFromEnv();
1493
+ this.workflowFollowUpGraceMs = opts.workflowFollowUpGraceMs ?? WORKFLOW_FOLLOW_UP_GRACE_MS;
1140
1494
  this.fileCommands = opts.fileCommands ?? [];
1141
1495
  this.initialTitlePending = opts.autoTitle ?? false;
1142
1496
  this.proc.onEvent((ev) => this.handleAtomicEvent(ev));
@@ -1204,10 +1558,19 @@ var AtomicAcpSession = class {
1204
1558
  });
1205
1559
  }
1206
1560
  await this.cancelPendingExtensionDialogs();
1561
+ for (const [runId, run] of this.turnWorkflowRuns) {
1562
+ if (run.done) continue;
1563
+ run.done = true;
1564
+ run.status = "cancelled";
1565
+ run.lines.push("run cancelled");
1566
+ this.publishWorkflowRun(runId, run);
1567
+ this.emitAgentText(`Quitting workflow "${run.name}" (run ${runId}).`);
1568
+ void this.proc.prompt(`/workflow quit ${runId}`, [], "followUp").catch(() => {
1569
+ this.emitAgentText(`Could not quit workflow run ${runId}.`);
1570
+ });
1571
+ }
1207
1572
  await this.proc.abort();
1208
- }
1209
- wasCancelRequested() {
1210
- return this.cancelRequested;
1573
+ if (this.pendingTurn && this.waitingForWorkflows && !this.inAgentLoop) await this.settleTurn();
1211
1574
  }
1212
1575
  async setSessionName(name) {
1213
1576
  return this.enqueueTitleUpdate(async () => {
@@ -1306,6 +1669,7 @@ var AtomicAcpSession = class {
1306
1669
  }
1307
1670
  startTurn(t) {
1308
1671
  this.cancelRequested = false;
1672
+ this.resetWorkflowWait();
1309
1673
  this.pendingTurn = { resolve: t.resolve, reject: t.reject };
1310
1674
  void this.maybeAutoTitle(t.title);
1311
1675
  this.emit({
@@ -1316,6 +1680,10 @@ var AtomicAcpSession = class {
1316
1680
  this.proc.prompt(t.message, t.images, "followUp").then(async (disposition) => {
1317
1681
  if (disposition !== "handled" || this.pendingTurn !== pending) return;
1318
1682
  if (this.inAgentLoop) this.backgroundTurn = true;
1683
+ if (this.shouldWaitForWorkflows()) {
1684
+ this.beginWorkflowWait();
1685
+ return;
1686
+ }
1319
1687
  await this.publishContextUsage();
1320
1688
  if (this.pendingTurn !== pending) return;
1321
1689
  pending.resolve(this.cancelRequested ? "cancelled" : "end_turn");
@@ -1336,24 +1704,64 @@ var AtomicAcpSession = class {
1336
1704
  await this.cancelPendingExtensionDialogs();
1337
1705
  await this.flushEmits();
1338
1706
  if (!this.pendingTurn && this.turnQueue.length === 0) return;
1339
- const authErr = maybeAuthRequiredError(err);
1707
+ const failure = maybeAuthRequiredError(err) ?? (this.cancelRequested ? null : this.promptFailure(err));
1340
1708
  const queued = this.turnQueue.splice(0);
1341
- if (authErr) {
1342
- this.pendingTurn?.reject(authErr);
1343
- for (const queuedTurn of queued) queuedTurn.reject(authErr);
1709
+ if (failure) {
1710
+ this.pendingTurn?.reject(failure);
1711
+ for (const queuedTurn of queued) queuedTurn.reject(failure);
1344
1712
  } else {
1345
- const reason = this.cancelRequested ? "cancelled" : "error";
1346
- this.pendingTurn?.resolve(reason);
1347
- for (const queuedTurn of queued) queuedTurn.resolve(reason);
1713
+ this.pendingTurn?.resolve("cancelled");
1714
+ for (const queuedTurn of queued) queuedTurn.resolve("cancelled");
1348
1715
  }
1349
1716
  this.pendingTurn = null;
1350
1717
  this.inAgentLoop = false;
1718
+ this.resetWorkflowWait();
1351
1719
  this.emit({
1352
1720
  sessionUpdate: "session_info_update",
1353
1721
  _meta: { atomicAcp: { queueDepth: 0, running: false } }
1354
1722
  });
1355
1723
  }
1724
+ promptFailure(err) {
1725
+ if (this.atomicExit) {
1726
+ const exit = this.atomicExit;
1727
+ const data = exit instanceof AtomicProcessExitError ? { exitCode: exit.exitCode, signal: exit.signal } : void 0;
1728
+ return RequestError3.internalError(
1729
+ data,
1730
+ `${atomicExitReason(exit)} during the prompt. Send another prompt to restart it.`
1731
+ );
1732
+ }
1733
+ if (err instanceof RequestError3) return err;
1734
+ return RequestError3.internalError(void 0, err instanceof Error ? err.message : String(err));
1735
+ }
1736
+ /** Close every tool call and workflow run still open, so none is left in progress after Atomic dies. */
1737
+ failOpenToolCalls(reason) {
1738
+ for (const toolCallId of this.currentToolCalls.keys()) {
1739
+ const bash = this.bashToolCallIds.has(toolCallId);
1740
+ this.emit({
1741
+ sessionUpdate: "tool_call_update",
1742
+ toolCallId,
1743
+ status: "failed",
1744
+ // A bash call keeps its terminal; other calls show the reason.
1745
+ ...bash ? {} : { content: [{ type: "content", content: { type: "text", text: reason } }] },
1746
+ rawOutput: { error: reason }
1747
+ });
1748
+ }
1749
+ this.currentToolCalls.clear();
1750
+ this.bashToolCallIds.clear();
1751
+ this.bashOutputSnapshots.clear();
1752
+ this.fileSnapshots.clear();
1753
+ this.fileMutationToolCallIds.clear();
1754
+ for (const [runId, run] of this.turnWorkflowRuns) {
1755
+ if (run.done) continue;
1756
+ run.done = true;
1757
+ run.status = "failed";
1758
+ run.lines.push(reason);
1759
+ this.publishWorkflowRun(runId, run);
1760
+ }
1761
+ }
1356
1762
  handleAtomicExit(err) {
1763
+ this.atomicExit ??= err;
1764
+ this.failOpenToolCalls(atomicExitReason(err));
1357
1765
  void this.cancelPendingExtensionDialogs();
1358
1766
  if (!this.pendingTurn && this.turnQueue.length === 0) return;
1359
1767
  void this.finishActiveAndQueuedFromFailure(err);
@@ -1388,6 +1796,13 @@ var AtomicAcpSession = class {
1388
1796
  }
1389
1797
  if (!["select", "confirm", "input", "editor"].includes(String(method))) return;
1390
1798
  if (this.pendingExtensionDialogs.has(id)) return;
1799
+ const question = typeof ev.title === "string" && ev.title ? ev.title : `Atomic ${method}`;
1800
+ const noPersonAvailable = () => this.emitAgentText(`No person is available to answer "${question}", so Atomic was told it was cancelled.`);
1801
+ if (this.headless) {
1802
+ noPersonAvailable();
1803
+ await this.writeExtensionUiResponse({ type: "extension_ui_response", id, cancelled: true });
1804
+ return;
1805
+ }
1391
1806
  if (!this.clientElicitationSupport.form && (method === "input" || method === "editor")) {
1392
1807
  this.emitAgentText(`Atomic ${method} UI request is not supported in ACP yet; cancelling it.`);
1393
1808
  }
@@ -1404,7 +1819,8 @@ var AtomicAcpSession = class {
1404
1819
  this.sessionId,
1405
1820
  ev,
1406
1821
  this.clientElicitationSupport.form,
1407
- controller.signal
1822
+ controller.signal,
1823
+ noPersonAvailable
1408
1824
  );
1409
1825
  if (timer) clearTimeout(timer);
1410
1826
  await this.writeExtensionUiResponse(response);
@@ -1423,8 +1839,139 @@ var AtomicAcpSession = class {
1423
1839
  }
1424
1840
  await completion;
1425
1841
  }
1842
+ async settleTurn() {
1843
+ this.resetWorkflowWait();
1844
+ await this.cancelPendingExtensionDialogs();
1845
+ await this.publishContextUsage();
1846
+ const reason = this.cancelRequested ? "cancelled" : "end_turn";
1847
+ this.pendingTurn?.resolve(reason);
1848
+ this.pendingTurn = null;
1849
+ this.inAgentLoop = false;
1850
+ const next = this.turnQueue.shift();
1851
+ if (next) {
1852
+ this.emit({
1853
+ sessionUpdate: "agent_message_chunk",
1854
+ content: { type: "text", text: `Starting queued message. (${this.turnQueue.length} remaining)` }
1855
+ });
1856
+ this.startTurn(next);
1857
+ } else {
1858
+ this.emit({
1859
+ sessionUpdate: "session_info_update",
1860
+ _meta: { atomicAcp: { queueDepth: 0, running: false } }
1861
+ });
1862
+ }
1863
+ }
1864
+ shouldWaitForWorkflows() {
1865
+ if (!this.waitForWorkflows || this.cancelRequested) return false;
1866
+ return [...this.turnWorkflowRuns.values()].some((run) => !run.done);
1867
+ }
1868
+ beginWorkflowWait() {
1869
+ if (this.waitingForWorkflows) return;
1870
+ this.waitingForWorkflows = true;
1871
+ const open = [...this.turnWorkflowRuns].filter(([, run]) => !run.done);
1872
+ const list = open.map(([runId, run]) => `"${run.name}" (run ${runId})`).join(", ");
1873
+ this.emitAgentText(`Waiting for workflow ${list} to finish.`);
1874
+ }
1875
+ clearWorkflowGraceTimer() {
1876
+ if (this.workflowGraceTimer) clearTimeout(this.workflowGraceTimer);
1877
+ this.workflowGraceTimer = void 0;
1878
+ }
1879
+ resetWorkflowWait() {
1880
+ this.clearWorkflowGraceTimer();
1881
+ this.turnWorkflowRuns.clear();
1882
+ this.waitingForWorkflows = false;
1883
+ }
1884
+ /** Once every run has ended, end the turn after Atomic's follow-up turn, or after a short grace without one. */
1885
+ maybeEndWorkflowWait() {
1886
+ if (!this.waitingForWorkflows || !this.pendingTurn || this.shouldWaitForWorkflows()) return;
1887
+ if (this.inAgentLoop) return;
1888
+ this.clearWorkflowGraceTimer();
1889
+ this.workflowGraceTimer = setTimeout(() => {
1890
+ this.workflowGraceTimer = void 0;
1891
+ if (this.waitingForWorkflows && this.pendingTurn && !this.inAgentLoop) void this.settleTurn();
1892
+ }, this.workflowFollowUpGraceMs);
1893
+ }
1894
+ publishWorkflowRun(runId, run) {
1895
+ const status = !run.done ? "in_progress" : run.status === "completed" || run.status === "skipped" ? "completed" : "failed";
1896
+ this.emit({
1897
+ sessionUpdate: "tool_call_update",
1898
+ toolCallId: `workflow-run-${runId}`,
1899
+ status,
1900
+ content: [{ type: "content", content: { type: "text", text: run.lines.join("\n") } }]
1901
+ });
1902
+ }
1903
+ trackWorkflowEvent(event) {
1904
+ if (event.kind === "run_start") {
1905
+ if (!this.waitForWorkflows || !this.pendingTurn || this.turnWorkflowRuns.has(event.runId)) return;
1906
+ const name = event.name ?? this.workflowRunNames.get(event.runId) ?? "workflow";
1907
+ this.turnWorkflowRuns.set(event.runId, {
1908
+ name,
1909
+ done: false,
1910
+ lines: [`run ${event.runId} started`],
1911
+ stageNames: /* @__PURE__ */ new Map(),
1912
+ resultReported: false
1913
+ });
1914
+ this.emit({
1915
+ sessionUpdate: "tool_call",
1916
+ toolCallId: `workflow-run-${event.runId}`,
1917
+ title: `Workflow ${name}`,
1918
+ kind: "other",
1919
+ status: "in_progress",
1920
+ rawInput: { runId: event.runId, workflow: name }
1921
+ });
1922
+ return;
1923
+ }
1924
+ const run = this.turnWorkflowRuns.get(event.runId);
1925
+ if (!run) return;
1926
+ if (event.kind === "stage_start") {
1927
+ const stage = event.name ?? event.stageId ?? "stage";
1928
+ if (event.stageId) run.stageNames.set(event.stageId, stage);
1929
+ run.lines.push(`stage ${stage} started`);
1930
+ if (event.humanInput && !run.done) {
1931
+ run.done = true;
1932
+ run.status = "awaiting_input";
1933
+ run.lines.push(`waiting for input at stage ${stage}`);
1934
+ if (!this.headless) {
1935
+ this.emitAgentText(
1936
+ `Workflow "${run.name}" is waiting for input (stage ${stage}, run ${event.runId}). This turn won't wait for it; reply here to answer it.`
1937
+ );
1938
+ }
1939
+ }
1940
+ } else if (event.kind === "stage_end") {
1941
+ const stage = (event.stageId && run.stageNames.get(event.stageId)) ?? event.stageId ?? "stage";
1942
+ run.lines.push(`stage ${stage} ${event.status ?? "ended"}`);
1943
+ } else {
1944
+ if (!run.done || run.status === "awaiting_input") {
1945
+ run.done = true;
1946
+ run.status = event.status;
1947
+ run.lines.push(`run ${event.status}`);
1948
+ }
1949
+ if (event.result !== void 0 && !run.resultReported) {
1950
+ run.resultReported = true;
1951
+ run.lines.push(`result: ${JSON.stringify(event.result)}`);
1952
+ }
1953
+ if (event.error) run.lines.push(`error: ${event.error}`);
1954
+ }
1955
+ this.publishWorkflowRun(event.runId, run);
1956
+ this.maybeEndWorkflowWait();
1957
+ }
1958
+ handleWorkflowEvent(event) {
1959
+ if (event.kind === "run_start" && event.name) this.workflowRunNames.set(event.runId, event.name);
1960
+ this.trackWorkflowEvent(event);
1961
+ if (event.kind === "stage_start" && event.humanInput && this.headless) {
1962
+ const name = this.workflowRunNames.get(event.runId) ?? event.runId;
1963
+ this.emitAgentText(
1964
+ `No person is available to answer workflow "${name}" (stage ${event.name ?? event.stageId ?? "input"}), so run ${event.runId} is being quit.`
1965
+ );
1966
+ void this.proc.prompt(`/workflow quit ${event.runId}`, [], "followUp").catch(() => {
1967
+ this.emitAgentText(`Could not quit workflow run ${event.runId}.`);
1968
+ });
1969
+ }
1970
+ }
1426
1971
  handleAtomicEvent(ev) {
1427
1972
  const type = String(ev.type ?? "");
1973
+ const workflowEvent = parseWorkflowEvent(ev);
1974
+ if (workflowEvent) this.handleWorkflowEvent(workflowEvent);
1428
1975
  switch (type) {
1429
1976
  case "session_info_changed": {
1430
1977
  const name = ev.name;
@@ -1663,6 +2210,7 @@ var AtomicAcpSession = class {
1663
2210
  case "agent_start": {
1664
2211
  this.inAgentLoop = true;
1665
2212
  this.backgroundTurn = !this.pendingTurn;
2213
+ this.clearWorkflowGraceTimer();
1666
2214
  break;
1667
2215
  }
1668
2216
  case "turn_end": {
@@ -1676,29 +2224,15 @@ var AtomicAcpSession = class {
1676
2224
  if (this.backgroundTurn || !this.pendingTurn) {
1677
2225
  this.backgroundTurn = false;
1678
2226
  this.inAgentLoop = false;
2227
+ this.maybeEndWorkflowWait();
1679
2228
  break;
1680
2229
  }
1681
- void (async () => {
1682
- await this.cancelPendingExtensionDialogs();
1683
- await this.publishContextUsage();
1684
- const reason = this.cancelRequested ? "cancelled" : "end_turn";
1685
- this.pendingTurn?.resolve(reason);
1686
- this.pendingTurn = null;
2230
+ if (this.shouldWaitForWorkflows()) {
1687
2231
  this.inAgentLoop = false;
1688
- const next = this.turnQueue.shift();
1689
- if (next) {
1690
- this.emit({
1691
- sessionUpdate: "agent_message_chunk",
1692
- content: { type: "text", text: `Starting queued message. (${this.turnQueue.length} remaining)` }
1693
- });
1694
- this.startTurn(next);
1695
- } else {
1696
- this.emit({
1697
- sessionUpdate: "session_info_update",
1698
- _meta: { atomicAcp: { queueDepth: 0, running: false } }
1699
- });
1700
- }
1701
- })();
2232
+ this.beginWorkflowWait();
2233
+ break;
2234
+ }
2235
+ void this.settleTurn();
1702
2236
  break;
1703
2237
  }
1704
2238
  default:
@@ -1739,9 +2273,14 @@ function toToolKind(toolName) {
1739
2273
  }
1740
2274
  }
1741
2275
 
2276
+ // src/acp/headless.ts
2277
+ function isHeadlessFromEnv(env = process.env) {
2278
+ return /^(1|true)$/i.test(env.ATOMIC_ACP_HEADLESS?.trim() ?? "");
2279
+ }
2280
+
1742
2281
  // src/acp/atomic-sessions.ts
1743
2282
  import { readdirSync as readdirSync2, readFileSync as readFileSync5, statSync as statSync2, openSync, readSync, closeSync, existsSync as existsSync3 } from "fs";
1744
- import { join as join4, resolve as resolve2 } from "path";
2283
+ import { join as join5, resolve as resolve2 } from "path";
1745
2284
 
1746
2285
  // src/acp/translate/prompt.ts
1747
2286
  function promptToSessionTitle(blocks) {
@@ -1822,13 +2361,13 @@ function getAtomicSessionsDir(cwd) {
1822
2361
  const atomicCwd = cwd ? resolve2(cwd) : process.cwd();
1823
2362
  const agentDir = getAgentDir();
1824
2363
  const projectSessionDir = cwd ? readSessionDirFromSettings(
1825
- getProjectConfigDirs(cwd).map((configDir) => join4(configDir, "settings.json")),
2364
+ getProjectConfigDirs(cwd).map((configDir) => join5(configDir, "settings.json")),
1826
2365
  atomicCwd
1827
2366
  ) : null;
1828
2367
  return projectSessionDir ?? readSessionDirFromSettings(
1829
- getAgentDirs().map((configDir) => join4(configDir, "settings.json")),
2368
+ getAgentDirs().map((configDir) => join5(configDir, "settings.json")),
1830
2369
  atomicCwd
1831
- ) ?? join4(agentDir, "sessions");
2370
+ ) ?? join5(agentDir, "sessions");
1832
2371
  }
1833
2372
  function walkJsonlFiles(dir, out) {
1834
2373
  let entries;
@@ -1839,7 +2378,7 @@ function walkJsonlFiles(dir, out) {
1839
2378
  }
1840
2379
  for (const e of entries) {
1841
2380
  const name = typeof e.name === "string" ? e.name : String(e.name);
1842
- const p = join4(dir, name);
2381
+ const p = join5(dir, name);
1843
2382
  if (e.isDirectory()) walkJsonlFiles(p, out);
1844
2383
  else if (e.isFile() && name.endsWith(".jsonl")) out.push(p);
1845
2384
  }
@@ -2099,7 +2638,7 @@ function toAvailableCommandsFromAtomicGetCommands(data, opts) {
2099
2638
  // src/acp/agent.ts
2100
2639
  import { isAbsolute as isAbsolute2 } from "path";
2101
2640
  import { existsSync as existsSync4, readFileSync as readFileSync6, realpathSync, readdirSync as readdirSync3, statSync as statSync3, unlinkSync } from "fs";
2102
- import { join as join5, dirname as dirname2, basename as basename2 } from "path";
2641
+ import { join as join6, dirname as dirname2, basename as basename2 } from "path";
2103
2642
  import { spawnSync } from "child_process";
2104
2643
  import { fileURLToPath } from "url";
2105
2644
  var MODEL_CONFIG_ID = "model";
@@ -2214,31 +2753,37 @@ var AtomicAcpAgent = class {
2214
2753
  async restoreSessionImpl(sessionId, opts) {
2215
2754
  const existing = this.sessions.maybeGet(sessionId);
2216
2755
  if (existing) {
2217
- if (opts?.cwd && existing.cwd !== opts.cwd) throw RequestError3.invalidParams(`Unknown sessionId: ${sessionId}`);
2218
- return existing;
2756
+ if (opts?.cwd && existing.cwd !== opts.cwd) throw RequestError4.invalidParams(`Unknown sessionId: ${sessionId}`);
2757
+ const sameServers = !opts?.mcpServers || sameMcpServers(existing.mcpServers, opts.mcpServers);
2758
+ if (sameServers && !existing.proc.hasExited) return existing;
2759
+ this.sessions.close(sessionId);
2219
2760
  }
2761
+ const mcpServers = opts?.mcpServers ?? existing?.mcpServers;
2220
2762
  const stored = this.findStoredSession(sessionId, opts?.cwd);
2221
- if (!stored) throw RequestError3.invalidParams(`Unknown sessionId: ${sessionId}`);
2763
+ if (!stored) throw RequestError4.invalidParams(`Unknown sessionId: ${sessionId}`);
2222
2764
  const cwd = opts?.cwd ?? stored.cwd;
2223
2765
  let proc;
2224
2766
  try {
2225
2767
  proc = await AtomicRpcProcess.spawn({
2226
2768
  cwd,
2227
2769
  sessionPath: stored.sessionFile,
2228
- atomicCommand: process.env.ATOMIC_ACP_ATOMIC_COMMAND
2770
+ atomicCommand: process.env.ATOMIC_ACP_ATOMIC_COMMAND,
2771
+ mcpServers: atomicMcpServersForSpawn(mcpServers),
2772
+ headless: isHeadlessFromEnv()
2229
2773
  });
2230
2774
  } catch (error) {
2231
- if (error instanceof AtomicRpcSpawnError) throw RequestError3.internalError({ code: error.code }, error.message);
2775
+ if (error instanceof AtomicRpcSpawnError) throw RequestError4.internalError({ code: error.code }, error.message);
2232
2776
  throw error;
2233
2777
  }
2234
2778
  try {
2235
2779
  const session = this.sessions.getOrCreate(sessionId, {
2236
2780
  cwd,
2237
- mcpServers: opts?.mcpServers ?? [],
2781
+ mcpServers: mcpServers ?? [],
2238
2782
  conn: this.conn,
2239
2783
  proc,
2240
2784
  fileCommands: loadSlashCommands(cwd),
2241
- clientElicitationSupport: this.clientElicitationSupport
2785
+ clientElicitationSupport: this.clientElicitationSupport,
2786
+ headless: isHeadlessFromEnv()
2242
2787
  });
2243
2788
  this.lastSessionCwd = cwd;
2244
2789
  this.store.upsert({ sessionId, cwd, sessionFile: stored.sessionFile });
@@ -2269,7 +2814,7 @@ var AtomicAcpAgent = class {
2269
2814
  }),
2270
2815
  agentCapabilities: {
2271
2816
  loadSession: true,
2272
- mcpCapabilities: { http: false, sse: false },
2817
+ mcpCapabilities: { http: true, sse: false },
2273
2818
  promptCapabilities: {
2274
2819
  image: true,
2275
2820
  audio: false,
@@ -2284,7 +2829,7 @@ var AtomicAcpAgent = class {
2284
2829
  }
2285
2830
  async newSession(params) {
2286
2831
  if (!isAbsolute2(params.cwd)) {
2287
- throw RequestError3.invalidParams(`cwd must be an absolute path: ${params.cwd}`);
2832
+ throw RequestError4.invalidParams(`cwd must be an absolute path: ${params.cwd}`);
2288
2833
  }
2289
2834
  this.lastSessionCwd = params.cwd;
2290
2835
  const fileCommands = loadSlashCommands(params.cwd);
@@ -2295,7 +2840,8 @@ var AtomicAcpAgent = class {
2295
2840
  conn: this.conn,
2296
2841
  fileCommands,
2297
2842
  atomicCommand: process.env.ATOMIC_ACP_ATOMIC_COMMAND,
2298
- clientElicitationSupport: this.clientElicitationSupport
2843
+ clientElicitationSupport: this.clientElicitationSupport,
2844
+ headless: isHeadlessFromEnv()
2299
2845
  });
2300
2846
  let state = null;
2301
2847
  let availableModels = null;
@@ -2330,19 +2876,19 @@ var AtomicAcpAgent = class {
2330
2876
  }
2331
2877
  if (availableModelsErr) {
2332
2878
  this.cleanupFailedNewSession(session.sessionId, state);
2333
- throw RequestError3.internalError({}, String(availableModelsErr?.message ?? availableModelsErr));
2879
+ throw RequestError4.internalError({}, String(availableModelsErr?.message ?? availableModelsErr));
2334
2880
  }
2335
2881
  const rawModelsCount = Array.isArray(availableModels?.models) ? availableModels.models.length : 0;
2336
2882
  if (rawModelsCount === 0) {
2337
2883
  this.cleanupFailedNewSession(session.sessionId, state);
2338
- throw RequestError3.authRequired(
2884
+ throw RequestError4.authRequired(
2339
2885
  { authMethods: getAuthMethods() },
2340
2886
  "Configure an API key or log in with an OAuth provider."
2341
2887
  );
2342
2888
  }
2343
2889
  if (stateErr && maybeAuthRequiredError(stateErr)) {
2344
2890
  this.cleanupFailedNewSession(session.sessionId, state);
2345
- throw RequestError3.authRequired(
2891
+ throw RequestError4.authRequired(
2346
2892
  { authMethods: getAuthMethods() },
2347
2893
  "Configure an API key or log in with an OAuth provider."
2348
2894
  );
@@ -2356,7 +2902,7 @@ var AtomicAcpAgent = class {
2356
2902
  configuration = await getSessionConfiguration(session.proc, { state, availableModels });
2357
2903
  } catch (err) {
2358
2904
  this.cleanupFailedNewSession(session.sessionId, state);
2359
- throw maybeAuthRequiredError(err) ?? RequestError3.internalError({}, String(err));
2905
+ throw maybeAuthRequiredError(err) ?? RequestError4.internalError({}, String(err));
2360
2906
  }
2361
2907
  const { configOptions, models, modes } = configuration;
2362
2908
  const quietStartup = getQuietStartup(params.cwd);
@@ -2616,7 +3162,7 @@ ${JSON.stringify(stats, null, 2)}`;
2616
3162
  if (atomicPath) {
2617
3163
  const resolved = realpathSync(atomicPath);
2618
3164
  const pkgRoot = dirname2(dirname2(resolved));
2619
- const p = join5(pkgRoot, "CHANGELOG.md");
3165
+ const p = join6(pkgRoot, "CHANGELOG.md");
2620
3166
  if (existsSync4(p)) return p;
2621
3167
  }
2622
3168
  } catch {
@@ -2625,7 +3171,7 @@ ${JSON.stringify(stats, null, 2)}`;
2625
3171
  const npmRoot = spawnSync("npm", ["root", "-g"], { encoding: "utf-8" });
2626
3172
  const root = String(npmRoot.stdout ?? "").trim();
2627
3173
  if (root) {
2628
- const p = join5(root, "@bastani", "atomic", "CHANGELOG.md");
3174
+ const p = join6(root, "@bastani", "atomic", "CHANGELOG.md");
2629
3175
  if (existsSync4(p)) return p;
2630
3176
  }
2631
3177
  } catch {
@@ -2713,11 +3259,11 @@ ${JSON.stringify(stats, null, 2)}`;
2713
3259
  return { stopReason: "end_turn" };
2714
3260
  }
2715
3261
  const safeSessionId = session.sessionId.replace(/[^a-zA-Z0-9_-]/g, "_");
2716
- const outputPath = join5(session.cwd, `atomic-session-${safeSessionId}.html`);
3262
+ const outputPath = join6(session.cwd, `atomic-session-${safeSessionId}.html`);
2717
3263
  let resultPath = "";
2718
3264
  try {
2719
- const result2 = await session.proc.exportHtml(outputPath);
2720
- resultPath = result2.path;
3265
+ const result = await session.proc.exportHtml(outputPath);
3266
+ resultPath = result.path;
2721
3267
  } catch (e) {
2722
3268
  await this.conn.sessionUpdate({
2723
3269
  sessionId: session.sessionId,
@@ -2794,8 +3340,7 @@ ${JSON.stringify(stats, null, 2)}`;
2794
3340
  return { stopReason: "end_turn" };
2795
3341
  }
2796
3342
  }
2797
- const result = await session.prompt(message, images, promptToSessionTitle(params.prompt) ?? void 0);
2798
- const stopReason = result === "error" ? session.wasCancelRequested() ? "cancelled" : "end_turn" : result;
3343
+ const stopReason = await session.prompt(message, images, promptToSessionTitle(params.prompt) ?? void 0);
2799
3344
  return { stopReason };
2800
3345
  }
2801
3346
  async cancel(params) {
@@ -2831,7 +3376,7 @@ ${JSON.stringify(stats, null, 2)}`;
2831
3376
  }
2832
3377
  async loadSessionImpl(params) {
2833
3378
  if (!isAbsolute2(params.cwd)) {
2834
- throw RequestError3.invalidParams(`cwd must be an absolute path: ${params.cwd}`);
3379
+ throw RequestError4.invalidParams(`cwd must be an absolute path: ${params.cwd}`);
2835
3380
  }
2836
3381
  this.lastSessionCwd = params.cwd;
2837
3382
  const session = await this.restoreSessionImpl(params.sessionId, {
@@ -3016,7 +3561,7 @@ ${JSON.stringify(stats, null, 2)}`;
3016
3561
  async setSessionMode(params) {
3017
3562
  const session = await this.restoreSession(params.sessionId);
3018
3563
  if (typeof params.modeId !== "string" || params.modeId.length === 0) {
3019
- throw RequestError3.invalidParams("Expected nonempty string modeId");
3564
+ throw RequestError4.invalidParams("Expected nonempty string modeId");
3020
3565
  }
3021
3566
  await session.proc.setThinkingLevel(params.modeId);
3022
3567
  await emitConfigOptionsUpdate(this.conn, session.sessionId, session.proc);
@@ -3025,15 +3570,15 @@ ${JSON.stringify(stats, null, 2)}`;
3025
3570
  async setSessionConfigOption(params) {
3026
3571
  const session = await this.restoreSession(params.sessionId);
3027
3572
  if (typeof params.value !== "string") {
3028
- throw RequestError3.invalidParams(`Expected string value for config option: ${params.configId}`);
3573
+ throw RequestError4.invalidParams(`Expected string value for config option: ${params.configId}`);
3029
3574
  }
3030
3575
  if (params.configId === MODEL_CONFIG_ID) {
3031
3576
  await setSessionModel(session.proc, params.value);
3032
3577
  } else if (params.configId === THOUGHT_LEVEL_CONFIG_ID) {
3033
- if (params.value.length === 0) throw RequestError3.invalidParams("Expected nonempty thinking level");
3578
+ if (params.value.length === 0) throw RequestError4.invalidParams("Expected nonempty thinking level");
3034
3579
  await session.proc.setThinkingLevel(params.value);
3035
3580
  } else {
3036
- throw RequestError3.invalidParams(`Unknown config option: ${params.configId}`);
3581
+ throw RequestError4.invalidParams(`Unknown config option: ${params.configId}`);
3037
3582
  }
3038
3583
  const configOptions = await emitConfigOptionsUpdate(this.conn, session.sessionId, session.proc);
3039
3584
  if (params.configId === MODEL_CONFIG_ID) await session.publishContextUsage();
@@ -3117,7 +3662,7 @@ async function setSessionModel(proc, requestedModelId) {
3117
3662
  );
3118
3663
  if (found) provider = found.provider;
3119
3664
  }
3120
- if (!provider || !modelId) throw RequestError3.invalidParams(`Unknown modelId: ${requestedModelId}`);
3665
+ if (!provider || !modelId) throw RequestError4.invalidParams(`Unknown modelId: ${requestedModelId}`);
3121
3666
  await proc.setModel(provider, modelId);
3122
3667
  }
3123
3668
  async function getModelState(proc, pre) {
@@ -3229,14 +3774,14 @@ function buildStartupInfo(opts) {
3229
3774
  md.push("");
3230
3775
  };
3231
3776
  const contextItems = [];
3232
- const contextPath = join5(opts.cwd, "AGENTS.md");
3777
+ const contextPath = join6(opts.cwd, "AGENTS.md");
3233
3778
  if (existsSync4(contextPath)) contextItems.push(contextPath);
3234
3779
  addSection("Context", contextItems);
3235
3780
  const skillsItems = [];
3236
3781
  const pushSkillFromRoot = (root) => {
3237
3782
  try {
3238
3783
  for (const e of readdirSync3(root)) {
3239
- const p = join5(root, e);
3784
+ const p = join6(root, e);
3240
3785
  try {
3241
3786
  const st = statSync3(p);
3242
3787
  if (st.isFile() && e.toLowerCase().endsWith(".md")) {
@@ -3256,7 +3801,7 @@ function buildStartupInfo(opts) {
3256
3801
  }
3257
3802
  for (const name of entries) {
3258
3803
  if (name === "node_modules" || name === ".git") continue;
3259
- const p = join5(dir, name);
3804
+ const p = join6(dir, name);
3260
3805
  let st;
3261
3806
  try {
3262
3807
  st = statSync3(p);
@@ -3273,16 +3818,16 @@ function buildStartupInfo(opts) {
3273
3818
  } catch {
3274
3819
  }
3275
3820
  };
3276
- const globalSkillsDir = join5(getAgentDir(), "skills");
3821
+ const globalSkillsDir = join6(getAgentDir(), "skills");
3277
3822
  pushSkillFromRoot(globalSkillsDir);
3278
- const legacyAgentsSkillsDir = join5(process.env.HOME ?? "", ".agents", "skills");
3823
+ const legacyAgentsSkillsDir = join6(process.env.HOME ?? "", ".agents", "skills");
3279
3824
  pushSkillFromRoot(legacyAgentsSkillsDir);
3280
- const projectSkillsDir = join5(opts.cwd, ".atomic", "skills");
3825
+ const projectSkillsDir = join6(opts.cwd, ".atomic", "skills");
3281
3826
  pushSkillFromRoot(projectSkillsDir);
3282
3827
  addSection("Skills", skillsItems);
3283
3828
  const promptsItems = [];
3284
3829
  const agentDir = getAgentDir();
3285
- const promptsDir = join5(agentDir, "prompts");
3830
+ const promptsDir = join6(agentDir, "prompts");
3286
3831
  try {
3287
3832
  const prompts = readdirSync3(promptsDir).filter((f) => f.endsWith(".md"));
3288
3833
  for (const f of prompts) promptsItems.push(`/${basename2(f, ".md")}`);
@@ -3290,13 +3835,13 @@ function buildStartupInfo(opts) {
3290
3835
  }
3291
3836
  addSection("Prompts", promptsItems);
3292
3837
  const extItems = [];
3293
- const extDir = join5(agentDir, "extensions");
3838
+ const extDir = join6(agentDir, "extensions");
3294
3839
  try {
3295
3840
  const exts = readdirSync3(extDir).filter((f) => f.endsWith(".ts") || f.endsWith(".js"));
3296
- for (const f of exts) extItems.push(join5(extDir, f));
3841
+ for (const f of exts) extItems.push(join6(extDir, f));
3297
3842
  } catch {
3298
3843
  }
3299
- for (const settingsPath of [join5(agentDir, "settings.json"), join5(opts.cwd, ".atomic", "settings.json")]) {
3844
+ for (const settingsPath of [join6(agentDir, "settings.json"), join6(opts.cwd, ".atomic", "settings.json")]) {
3300
3845
  try {
3301
3846
  const settings = JSON.parse(readFileSync6(settingsPath, "utf-8"));
3302
3847
  const packages = Array.isArray(settings.packages) ? settings.packages : [];
@@ -3321,7 +3866,7 @@ function readNearestPackageJson(metaUrl) {
3321
3866
  try {
3322
3867
  let dir = dirname2(fileURLToPath(metaUrl));
3323
3868
  for (let i = 0; i < 6; i++) {
3324
- const p = join5(dir, "package.json");
3869
+ const p = join6(dir, "package.json");
3325
3870
  if (existsSync4(p)) {
3326
3871
  const json = JSON.parse(readFileSync6(p, "utf-8"));
3327
3872
  return { name: json?.name, version: json?.version };
@@ -3334,7 +3879,9 @@ function readNearestPackageJson(metaUrl) {
3334
3879
  }
3335
3880
 
3336
3881
  // src/index.ts
3337
- if (process.argv.includes("--terminal-login")) {
3882
+ var separator = process.argv.indexOf("--", 2);
3883
+ var adapterArgs = separator < 0 ? process.argv.slice(2) : process.argv.slice(2, separator);
3884
+ if (adapterArgs.includes("--terminal-login")) {
3338
3885
  const { spawnSync: spawnSync2 } = await import("child_process");
3339
3886
  const cmd = getAtomicCommand(process.env.ATOMIC_ACP_ATOMIC_COMMAND);
3340
3887
  const res = spawnSync2(cmd, [], {
@@ -3351,6 +3898,13 @@ if (process.argv.includes("--terminal-login")) {
3351
3898
  }
3352
3899
  process.exit(typeof res.status === "number" ? res.status : 1);
3353
3900
  }
3901
+ try {
3902
+ parseAtomicExtraArgs(process.argv, process.env);
3903
+ } catch (error) {
3904
+ process.stderr.write(`atomic-acp: ${error.message}
3905
+ `);
3906
+ process.exit(2);
3907
+ }
3354
3908
  var input = new WritableStream({
3355
3909
  write(chunk) {
3356
3910
  return new Promise((resolve3) => {