acpx 0.13.2 → 0.14.0

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.
@@ -38,7 +38,12 @@ var SessionResolutionError = class extends AcpxOperationalError {};
38
38
  var AgentSpawnError = class extends AcpxOperationalError {
39
39
  agentCommand;
40
40
  constructor(agentCommand, cause) {
41
- super(`Failed to spawn agent command: ${agentCommand}`, { cause: cause instanceof Error ? cause : void 0 });
41
+ const spawnEnoent = (cause instanceof Error ? cause.code : void 0) === "ENOENT";
42
+ const message = spawnEnoent ? `Failed to spawn agent command: ${agentCommand}. The agent process could not start because a required executable, interpreter, working directory, or other launch path was not found. Check the command, effective PATH, and working directory, or verify the custom agent's configured argv.` : `Failed to spawn agent command: ${agentCommand}`;
43
+ super(message, {
44
+ cause: cause instanceof Error ? cause : void 0,
45
+ ...spawnEnoent ? { detailCode: "AGENT_SPAWN_ENOENT" } : {}
46
+ });
42
47
  this.agentCommand = agentCommand;
43
48
  }
44
49
  };
@@ -711,19 +716,17 @@ async function withInterrupt(run, onInterrupt) {
711
716
  process.off("SIGHUP", onSighup);
712
717
  cb();
713
718
  };
714
- const rejectInterrupted = () => {
715
- onInterrupt().finally(() => {
716
- finish(() => reject(new InterruptedError()));
717
- });
719
+ const rejectInterrupted = (signal) => {
720
+ onInterrupt(signal).then(() => finish(() => reject(new InterruptedError())), (error) => finish(() => reject(error)));
718
721
  };
719
722
  const onSigint = () => {
720
- rejectInterrupted();
723
+ rejectInterrupted("SIGINT");
721
724
  };
722
725
  const onSigterm = () => {
723
- rejectInterrupted();
726
+ rejectInterrupted("SIGTERM");
724
727
  };
725
728
  const onSighup = () => {
726
- rejectInterrupted();
729
+ rejectInterrupted("SIGHUP");
727
730
  };
728
731
  process.once("SIGINT", onSigint);
729
732
  process.once("SIGTERM", onSigterm);
@@ -1661,7 +1664,11 @@ const ZED_TAG_KEYS = /* @__PURE__ */ new Set([
1661
1664
  "RedactedThinking",
1662
1665
  "ToolUse"
1663
1666
  ]);
1664
- const MAP_OBJECT_PATHS = /* @__PURE__ */ new Set(["request_token_usage", "messages.Agent.tool_results"]);
1667
+ const MAP_OBJECT_PATHS = /* @__PURE__ */ new Set([
1668
+ "request_token_usage",
1669
+ "messages.Agent.tool_results",
1670
+ "acpx.session_options.env"
1671
+ ]);
1665
1672
  const OPAQUE_VALUE_PATHS = /* @__PURE__ */ new Set([
1666
1673
  "agent_capabilities",
1667
1674
  "messages.Agent.content.ToolUse.input",
@@ -2633,6 +2640,9 @@ function getAcpxVersion() {
2633
2640
  cachedVersion = resolveAcpxVersion();
2634
2641
  return cachedVersion;
2635
2642
  }
2643
+ //#endregion
2644
+ //#region src/acp/client-process.ts
2645
+ const PROCESS_HELPER_TIMEOUT_MS = 8e3;
2636
2646
  async function runTimedExecFile(command, args, options = {}) {
2637
2647
  const timeoutMs = Math.max(1, Math.round(options.timeoutMs ?? 8e3));
2638
2648
  return await new Promise((resolve, reject) => {
@@ -3399,6 +3409,7 @@ function waitMs(ms) {
3399
3409
  setTimeout(resolve, Math.max(0, ms));
3400
3410
  });
3401
3411
  }
3412
+ function onStreamError() {}
3402
3413
  var TerminalManager = class {
3403
3414
  cwd;
3404
3415
  permissionMode;
@@ -3464,6 +3475,8 @@ var TerminalManager = class {
3464
3475
  };
3465
3476
  proc.stdout.on("data", appendOutput);
3466
3477
  proc.stderr.on("data", appendOutput);
3478
+ proc.stdout.on("error", onStreamError);
3479
+ proc.stderr.on("error", onStreamError);
3467
3480
  proc.once("exit", (exitCode, signal) => {
3468
3481
  terminal.exitCode = exitCode;
3469
3482
  terminal.signal = signal;
@@ -3638,7 +3651,7 @@ var TerminalManager = class {
3638
3651
  } catch {
3639
3652
  return;
3640
3653
  }
3641
- await this.waitForCleanupAfterSignal(terminal);
3654
+ await this.waitForFinalCleanup(terminal);
3642
3655
  }
3643
3656
  async signalProcess(terminal, signal) {
3644
3657
  const pid = terminal.process.pid;
@@ -3655,10 +3668,10 @@ var TerminalManager = class {
3655
3668
  async signalWindowsProcessGroup(terminal, pid, signal) {
3656
3669
  await this.captureDescendantPids(terminal, pid);
3657
3670
  if (this.isRunning(terminal)) {
3658
- await killWindowsProcessTree(pid, signal);
3671
+ await killWindowsProcessTree(pid, signal, terminal.processHelperTimeoutMs);
3659
3672
  return;
3660
3673
  }
3661
- for (const descendantPid of terminal.descendantPids) await killWindowsProcessTree(descendantPid, signal);
3674
+ for (const descendantPid of terminal.descendantPids) await killWindowsProcessTree(descendantPid, signal, terminal.processHelperTimeoutMs);
3662
3675
  }
3663
3676
  async signalPosixProcessGroup(terminal, pid, signal) {
3664
3677
  await this.captureDescendantPids(terminal, pid);
@@ -3672,6 +3685,9 @@ var TerminalManager = class {
3672
3685
  if (!this.isRunning(terminal)) await terminal.processGroupSnapshotPromise?.catch(() => {});
3673
3686
  for (const descendantPid of await listDescendantPids(pid, terminal.processHelperTimeoutMs)) terminal.descendantPids.add(descendantPid);
3674
3687
  }
3688
+ async waitForFinalCleanup(terminal) {
3689
+ if (!await this.waitForCleanupAfterSignal(terminal) && process.platform === "win32") throw new Error("Terminal process cleanup did not finish after SIGKILL");
3690
+ }
3675
3691
  async waitForCleanupAfterSignal(terminal) {
3676
3692
  return await Promise.race([this.waitForTerminalAndTrackedDescendants(terminal).then(() => true), waitMs(this.killGraceMs).then(() => false)]);
3677
3693
  }
@@ -3803,25 +3819,19 @@ async function runWindowsProcessListCommand(timeoutMs) {
3803
3819
  windowsHide: true
3804
3820
  });
3805
3821
  }
3806
- async function killWindowsProcessTree(pid, signal) {
3822
+ async function killWindowsProcessTree(pid, signal, timeoutMs = PROCESS_HELPER_TIMEOUT_MS) {
3807
3823
  const args = [
3808
3824
  "/pid",
3809
3825
  String(pid),
3810
3826
  "/t"
3811
3827
  ];
3812
3828
  if (signal === "SIGKILL") args.push("/f");
3813
- await new Promise((resolve) => {
3814
- const child = spawn("taskkill", args, {
3815
- stdio: [
3816
- "ignore",
3817
- "ignore",
3818
- "ignore"
3819
- ],
3829
+ try {
3830
+ await runTimedExecFile("taskkill", args, {
3831
+ timeoutMs,
3820
3832
  windowsHide: true
3821
3833
  });
3822
- child.once("error", () => resolve());
3823
- child.once("close", () => resolve());
3824
- });
3834
+ } catch {}
3825
3835
  }
3826
3836
  function sendSignal(pid, signal) {
3827
3837
  try {
@@ -4361,9 +4371,8 @@ var AcpClient = class {
4361
4371
  const onAcpMessage = () => this.eventHandlers.onAcpMessage;
4362
4372
  const onAcpOutputMessage = () => this.eventHandlers.onAcpOutputMessage;
4363
4373
  const elicitationRequestIds = /* @__PURE__ */ new Set();
4364
- const bindPromptOwner = (owner) => {
4365
- this.bindPromptOwner(owner);
4366
- };
4374
+ const bindPromptOwner = (owner) => this.bindPromptOwner(owner);
4375
+ const onPromptRequestWritten = (active, owner) => this.onPromptRequestWritten(active, owner);
4367
4376
  const shouldSuppressInboundReplaySessionUpdate = (message) => {
4368
4377
  return this.suppressReplaySessionUpdateMessages && isSessionUpdateNotification(message);
4369
4378
  };
@@ -4397,7 +4406,7 @@ var AcpClient = class {
4397
4406
  } }),
4398
4407
  writable: new WritableStream({ async write(message) {
4399
4408
  const promptOwner = promptRequestOwner(message);
4400
- if (promptOwner) bindPromptOwner(promptOwner);
4409
+ const activePrompt = promptOwner ? bindPromptOwner(promptOwner) : void 0;
4401
4410
  const id = responseId(message);
4402
4411
  if (!(id !== void 0 && elicitationRequestIds.delete(id))) {
4403
4412
  onAcpOutputMessage()?.("outbound", message);
@@ -4409,6 +4418,7 @@ var AcpClient = class {
4409
4418
  } finally {
4410
4419
  writer.releaseLock();
4411
4420
  }
4421
+ if (activePrompt && promptOwner) onPromptRequestWritten(activePrompt, promptOwner);
4412
4422
  } })
4413
4423
  };
4414
4424
  }
@@ -4498,17 +4508,17 @@ var AcpClient = class {
4498
4508
  this.suppressSessionUpdates = previous.suppressSessionUpdates;
4499
4509
  this.suppressReplaySessionUpdateMessages = previous.suppressReplaySessionUpdateMessages;
4500
4510
  }
4501
- async prompt(sessionId, prompt, onRequestStarted, onElicitation) {
4511
+ async prompt(sessionId, prompt, onRequestWritten, onElicitation) {
4502
4512
  const connection = this.getConnection();
4503
4513
  const normalizedPrompt = this.normalizePromptForAgent(prompt);
4504
4514
  const restoreConsoleError = this.options.suppressSdkConsoleErrors ? installSdkConsoleErrorSuppression() : void 0;
4505
- const activePrompt = this.beginActivePrompt(sessionId, onElicitation);
4515
+ const activePrompt = this.beginActivePrompt(sessionId, onRequestWritten, onElicitation);
4506
4516
  let promptPromise;
4507
4517
  try {
4508
4518
  promptPromise = this.runConnectionRequest(() => connection.prompt({
4509
4519
  sessionId,
4510
4520
  prompt: normalizedPrompt
4511
- }), onRequestStarted, () => !connection.signal?.aborted);
4521
+ }));
4512
4522
  } catch (error) {
4513
4523
  this.clearActivePrompt(activePrompt);
4514
4524
  restoreConsoleError?.();
@@ -4528,11 +4538,12 @@ var AcpClient = class {
4528
4538
  this.promptPermissionFailures.delete(sessionId);
4529
4539
  }
4530
4540
  }
4531
- beginActivePrompt(sessionId, elicitationHandler) {
4541
+ beginActivePrompt(sessionId, onRequestWritten, elicitationHandler) {
4532
4542
  const previous = this.activePrompt;
4533
4543
  this.cancellingSessionIds.delete(sessionId);
4534
4544
  const active = {
4535
4545
  sessionId,
4546
+ onRequestWritten,
4536
4547
  elicitationHandler,
4537
4548
  elicitationController: new AbortController()
4538
4549
  };
@@ -4546,6 +4557,13 @@ var AcpClient = class {
4546
4557
  return candidate.requestId === void 0 && candidate.sessionId === owner.sessionId;
4547
4558
  });
4548
4559
  if (active) active.requestId = owner.requestId;
4560
+ return active;
4561
+ }
4562
+ onPromptRequestWritten(active, owner) {
4563
+ if (active.requestId !== owner.requestId || active.sessionId !== owner.sessionId) return;
4564
+ try {
4565
+ Promise.resolve(active.onRequestWritten?.()).catch(() => {});
4566
+ } catch {}
4549
4567
  }
4550
4568
  clearActivePrompt(active) {
4551
4569
  if (this.activePrompt === active) this.activePrompt = void 0;
@@ -5055,7 +5073,7 @@ var AcpClient = class {
5055
5073
  if (error) this.promptPermissionFailures.delete(sessionId);
5056
5074
  return error;
5057
5075
  }
5058
- async runConnectionRequest(run, onRequestStarted, canStartRequest = () => true) {
5076
+ async runConnectionRequest(run) {
5059
5077
  return await new Promise((resolve, reject) => {
5060
5078
  const pending = {
5061
5079
  settled: false,
@@ -5070,14 +5088,9 @@ var AcpClient = class {
5070
5088
  this.pendingConnectionRequests.add(pending);
5071
5089
  Promise.resolve().then(async () => {
5072
5090
  if (pending.settled) return { started: false };
5073
- const requestCanStart = canStartRequest();
5074
- const request = run();
5075
- if (requestCanStart) try {
5076
- Promise.resolve(onRequestStarted?.()).catch(() => {});
5077
- } catch {}
5078
5091
  return {
5079
5092
  started: true,
5080
- value: await request
5093
+ value: await run()
5081
5094
  };
5082
5095
  }).then((outcome) => {
5083
5096
  if (outcome.started) finish(() => resolve(outcome.value));
@@ -6471,7 +6484,7 @@ const SESSION_REPLY_IDLE_MS = 1e3;
6471
6484
  const SESSION_REPLY_DRAIN_TIMEOUT_MS = 5e3;
6472
6485
  async function runPromptTurn(params) {
6473
6486
  try {
6474
- const promptPromise = params.client.prompt(params.sessionId, params.prompt, params.onPromptRequestStarted, params.onElicitation);
6487
+ const promptPromise = params.client.prompt(params.sessionId, params.prompt, params.onPromptRequestWritten, params.onElicitation);
6475
6488
  await params.onPromptStarted?.();
6476
6489
  const response = await withTimeout(promptPromise, params.timeoutMs);
6477
6490
  await params.client.waitForSessionUpdatesIdle?.({
@@ -6552,4 +6565,4 @@ var LiveSessionCheckpoint = class {
6552
6565
  //#endregion
6553
6566
  export { formatPerfMetric as $, AgentSpawnError as $t, RequestedModelUnsupportedError as A, DEFAULT_AGENT_NAME as At, absolutePath as B, extractAcpError as Bt, sessionOptionsFromRecord as C, parsePromptSource as Ct, AcpClient as D, TimeoutError as Dt, reconcileAgentSessionId as E, InterruptedError as Et, runTimedExecFile as F, resolveCanonicalAgentName as Ft, listSessions as G, NON_INTERACTIVE_PERMISSION_POLICIES as Gt, findSession as H, toAcpErrorPayload as Ht, splitCommandLine as I, exitCodeForOutputErrorCode as It, pruneSessions as J, OUTPUT_FORMATS as Jt, listSessionsForAgent as K, OUTPUT_ERROR_CODES as Kt, getAcpxVersion as L, formatErrorMessage as Lt, modelStateFromConfigOptions as M, normalizeAgentName$1 as Mt, normalizeAgentCommandInput as N, resolveAgentArgv as Nt, REQUESTED_MODEL_UNSUPPORTED_ERROR_CODE as O, withInterrupt as Ot, renderArgvIdentity as P, resolveAgentCommand as Pt, assertPersistedKeyPolicy as Q, AcpxOperationalError as Qt, permissionModeSatisfies as R, isRetryablePromptError as Rt, persistSessionOptions as S, mergePromptSourceWithText as St, applyLifecycleSnapshotToRecord as T, textPrompt as Tt, findSessionByDirectoryWalk as U, AUTH_POLICIES as Ut, findGitRepositoryRoot as V, isAcpResourceNotFoundError as Vt, isoNow$2 as W, EXIT_CODES as Wt, writeSessionRecord as X, PERMISSION_POLICY_ACTIONS as Xt, resolveSessionRecord as Y, PERMISSION_MODES as Yt, createAtomicWriteTempPath as Z, SESSION_RECORD_SCHEMA as Zt, recordPromptSubmission as _, isAcpJsonRpcMessage as _t, applyConfigOptionSelection as a, setPerfGauge as at, advertisedModelState as b, PromptInputValidationError as bt, applyRequestedModelIfAdvertised as c, serializeSessionRecordForDisk as ct, setDesiredModeId as d, defaultSessionEventLog as dt, QueueConnectionError as en, getPerfMetricsSnapshot as et, syncAdvertisedModelState as f, sessionBaseDir$1 as ft, recordClientOperation as g, extractSessionUpdateNotification as gt, createSessionConversation as h, sessionEventSegmentPath as ht, connectAndLoadSession as i, resetPerfMetrics as it, isRequestedModelUnsupportedError as j, listBuiltInAgents as jt, REQUESTED_MODEL_UNSUPPORTED_REASONS as k, withTimeout as kt, currentModelIdFromSetModelResponse as l, normalizeRuntimeSessionId as lt, cloneSessionConversation as m, sessionEventLockPath as mt, runPromptTurn as n, measurePerf as nt, applyConfigOptionsToRecord as o, startPerfTimer as ot, cloneSessionAcpxState as p, sessionEventActivePath as pt, normalizeName as q, OUTPUT_ERROR_ORIGINS as qt, withConnectedSession as r, recordPerfDuration as rt, applyModelSelection as s, parseSessionRecord as st, LiveSessionCheckpoint as t, QueueProtocolError as tn, incrementPerfCounter as tt, setCurrentModelId as u, DEFAULT_EVENT_SEGMENT_MAX_BYTES as ut, recordSessionUpdate as v, parseJsonRpcErrorMessage as vt, applyConversation as w, promptToDisplayText as wt, mergeSessionOptions as x, isPromptInput as xt, trimConversationForRuntime as y, parsePromptStopReason as yt, DEFAULT_HISTORY_LIMIT as z, normalizeOutputError as zt };
6554
6567
 
6555
- //# sourceMappingURL=live-checkpoint-Gw2oGjhe.js.map
6568
+ //# sourceMappingURL=live-checkpoint-BW9JivEG.js.map