@moxt-ai/mobius 0.0.78 → 0.0.80

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/cli.js CHANGED
@@ -11,7 +11,7 @@ import { mkdir as mkdir6 } from "node:fs/promises";
11
11
  // package.json
12
12
  var package_default = {
13
13
  name: "@moxt-ai/mobius",
14
- version: "0.0.78",
14
+ version: "0.0.80",
15
15
  description: "Mobius CLI for pairing and running local AI agent services.",
16
16
  type: "module",
17
17
  bin: {
@@ -1435,6 +1435,20 @@ var AcpConfigurationValueUnavailableError = class extends AcpExecutionError {
1435
1435
  }
1436
1436
  };
1437
1437
 
1438
+ // src/acp/in-process/acp-endpoint.ts
1439
+ function acpEndpointTerminationError(termination) {
1440
+ switch (termination.kind) {
1441
+ case "failed":
1442
+ return termination.error;
1443
+ case "closed":
1444
+ return new AcpExecutionError("The ACP endpoint is closed", {}, "acp_endpoint_closed");
1445
+ default: {
1446
+ const unreachable = termination;
1447
+ return unreachable;
1448
+ }
1449
+ }
1450
+ }
1451
+
1438
1452
  // src/acp/codex/app-server-client.ts
1439
1453
  import { spawn as spawn2 } from "node:child_process";
1440
1454
 
@@ -21329,11 +21343,9 @@ var threadSettingsUpdatedSchema = external_exports.object({
21329
21343
  // src/acp/codex/app-server-client.ts
21330
21344
  var INITIALIZE_TIMEOUT_MILLISECONDS = 3e4;
21331
21345
  var OUTPUT_LIMIT_BYTES = 32 * 1024 * 1024;
21332
- var CodexAppServerError = class extends Error {
21333
- code;
21346
+ var CodexAppServerError = class extends AcpExecutionError {
21334
21347
  constructor(code, message, options = {}) {
21335
- super(message, options);
21336
- this.code = code;
21348
+ super(message, options, code);
21337
21349
  this.name = "CodexAppServerError";
21338
21350
  }
21339
21351
  };
@@ -21341,12 +21353,14 @@ var CodexAppServerClient = class {
21341
21353
  #child;
21342
21354
  #handlers;
21343
21355
  #pending = /* @__PURE__ */ new Map();
21344
- #processExit;
21345
- #failure = null;
21356
+ #termination = Promise.withResolvers();
21357
+ terminated = this.#termination.promise;
21358
+ #lifecycle = {
21359
+ kind: "open"
21360
+ };
21346
21361
  #nextRequestId = 1;
21347
21362
  #pendingBuffer = "";
21348
21363
  #receivedBytes = 0;
21349
- #closed = false;
21350
21364
  constructor(options) {
21351
21365
  this.#handlers = options.handlers;
21352
21366
  this.#child = spawn2(options.command, ["app-server"], {
@@ -21371,21 +21385,56 @@ var CodexAppServerClient = class {
21371
21385
  stderr.on("data", (chunk) => {
21372
21386
  process.stderr.write(`[codex-app-server] ${chunk}`);
21373
21387
  });
21374
- this.#processExit = new Promise((resolve7) => {
21375
- this.#child.once("error", resolve7);
21376
- this.#child.once("exit", resolve7);
21388
+ this.#child.once("error", (cause) => {
21389
+ this.#fail(
21390
+ new CodexAppServerError("codex_app_server_exited", "The Codex app-server could not run", { cause })
21391
+ );
21392
+ });
21393
+ this.#child.once("exit", (code, signal) => {
21394
+ this.#fail(
21395
+ new CodexAppServerError("codex_app_server_exited", "The Codex app-server stopped", {
21396
+ cause: { code, signal }
21397
+ })
21398
+ );
21399
+ });
21400
+ for (const stream of [stdin, stdout, stderr]) {
21401
+ stream.on("error", (cause) => {
21402
+ this.#fail(
21403
+ new CodexAppServerError("codex_app_server_io_error", "The Codex app-server connection failed", {
21404
+ cause
21405
+ })
21406
+ );
21407
+ });
21408
+ }
21409
+ stdout.once("end", () => {
21410
+ this.#fail(new CodexAppServerError("codex_app_server_exited", "The Codex app-server output closed"));
21377
21411
  });
21378
21412
  }
21379
21413
  child = () => this.#child;
21380
21414
  #fail = (error62) => {
21381
- this.#failure ??= error62;
21415
+ this.#terminate({ kind: "failed", error: error62 });
21416
+ };
21417
+ #terminate = (result) => {
21418
+ if (this.#lifecycle.kind === "terminated") {
21419
+ return;
21420
+ }
21421
+ this.#lifecycle = { kind: "terminated", result };
21422
+ this.#termination.resolve(result);
21423
+ const error62 = acpEndpointTerminationError(result);
21382
21424
  for (const [id, pending] of this.#pending) {
21383
21425
  this.#pending.delete(id);
21384
21426
  pending.completion.reject(error62);
21385
21427
  }
21386
21428
  };
21387
- #exitedFailure = (method) => this.#failure ?? new CodexAppServerError("codex_app_server_exited", `The Codex app-server stopped during ${method}`);
21429
+ #requireOpen = () => {
21430
+ if (this.#lifecycle.kind === "terminated") {
21431
+ throw acpEndpointTerminationError(this.#lifecycle.result);
21432
+ }
21433
+ };
21388
21434
  #consume = (chunk) => {
21435
+ if (this.#lifecycle.kind === "terminated") {
21436
+ return;
21437
+ }
21389
21438
  try {
21390
21439
  this.#receivedBytes += Buffer.byteLength(chunk);
21391
21440
  if (this.#receivedBytes > OUTPUT_LIMIT_BYTES) {
@@ -21414,7 +21463,6 @@ var CodexAppServerClient = class {
21414
21463
  { cause: error62 }
21415
21464
  )
21416
21465
  );
21417
- this.#child.kill("SIGKILL");
21418
21466
  }
21419
21467
  };
21420
21468
  // Handler failures are recorded as the app-server's terminal failure: an ACP client that cannot
@@ -21464,9 +21512,7 @@ var CodexAppServerClient = class {
21464
21512
  /** Sends a request and waits for its response, bounded by the caller's cancellation signal. */
21465
21513
  request = async (method, params, signal) => {
21466
21514
  signal.throwIfAborted();
21467
- if (this.#closed) {
21468
- throw new CodexAppServerError("codex_app_server_closed", "The Codex app-server is closed");
21469
- }
21515
+ this.#requireOpen();
21470
21516
  const id = this.#nextRequestId;
21471
21517
  this.#nextRequestId += 1;
21472
21518
  const completion = Promise.withResolvers();
@@ -21479,7 +21525,7 @@ var CodexAppServerClient = class {
21479
21525
  signal.addEventListener("abort", abort, { once: true });
21480
21526
  try {
21481
21527
  this.#write({ id, method, params });
21482
- return await Promise.race([completion.promise, this.#processExit.then(() => this.#exitedFailure(method))]);
21528
+ return await completion.promise;
21483
21529
  } finally {
21484
21530
  signal.removeEventListener("abort", abort);
21485
21531
  this.#pending.delete(id);
@@ -21495,12 +21541,12 @@ var CodexAppServerClient = class {
21495
21541
  this.#write({ error: { code, message }, id });
21496
21542
  };
21497
21543
  #write = (message) => {
21498
- if (this.#closed) {
21499
- return;
21500
- }
21544
+ this.#requireOpen();
21501
21545
  const stdin = this.#child.stdin;
21502
21546
  if (stdin === null || stdin.destroyed) {
21503
- throw new CodexAppServerError("codex_app_server_closed", "The Codex app-server input is closed");
21547
+ const error62 = new CodexAppServerError("codex_app_server_io_error", "The Codex app-server input is closed");
21548
+ this.#fail(error62);
21549
+ throw error62;
21504
21550
  }
21505
21551
  stdin.write(`${JSON.stringify(message)}
21506
21552
  `);
@@ -21523,15 +21569,7 @@ var CodexAppServerClient = class {
21523
21569
  * app-server and every tool subprocess it started.
21524
21570
  */
21525
21571
  detach = () => {
21526
- if (this.#closed) {
21527
- return;
21528
- }
21529
- this.#closed = true;
21530
- this.#fail(new CodexAppServerError("codex_app_server_closed", "The Codex app-server is closed"));
21531
- const stdin = this.#child.stdin;
21532
- if (stdin !== null && !stdin.destroyed) {
21533
- stdin.end();
21534
- }
21572
+ this.#terminate({ kind: "closed" });
21535
21573
  };
21536
21574
  };
21537
21575
 
@@ -21873,6 +21911,8 @@ function userInputSchema(questions) {
21873
21911
  var CodexAcpAgent = class {
21874
21912
  #app;
21875
21913
  #appServer;
21914
+ terminated;
21915
+ #closePromise = null;
21876
21916
  #connection = null;
21877
21917
  #models = [];
21878
21918
  #nativeSessionId = "";
@@ -21910,6 +21950,15 @@ var CodexAcpAgent = class {
21910
21950
  }
21911
21951
  }
21912
21952
  });
21953
+ this.terminated = this.#appServer.terminated;
21954
+ void this.terminated.then((termination) => {
21955
+ this.#turn?.completion.reject(acpEndpointTerminationError(termination));
21956
+ if (termination.kind === "failed") {
21957
+ void this.close().catch((cause) => {
21958
+ console.error("The failed Codex endpoint could not release its process tree", cause);
21959
+ });
21960
+ }
21961
+ });
21913
21962
  this.#app = createAgentApp({ name: "mobius-codex" }).onConnect((connection) => {
21914
21963
  this.#connection = connection;
21915
21964
  }).onRequest(methods.agent.initialize, async () => ({
@@ -22021,11 +22070,20 @@ var CodexAcpAgent = class {
22021
22070
  * Releases the app-server and every process it started. Mirrors the adapter path's teardown so a
22022
22071
  * cancelled or closed session cannot leak the tool subprocesses running under the app-server.
22023
22072
  */
22024
- close = async () => {
22025
- const child = this.#appServer.child();
22026
- const captured = await captureProcessTree(child);
22027
- this.#appServer.detach();
22028
- await stopProcessTree(child, captured);
22073
+ close = () => {
22074
+ if (this.#closePromise === null) {
22075
+ this.#appServer.detach();
22076
+ this.#closePromise = (async () => {
22077
+ const child = this.#appServer.child();
22078
+ try {
22079
+ const captured = await captureProcessTree(child);
22080
+ await stopProcessTree(child, captured);
22081
+ } finally {
22082
+ this.#connection?.close();
22083
+ }
22084
+ })();
22085
+ }
22086
+ return this.#closePromise;
22029
22087
  };
22030
22088
  /**
22031
22089
  * Reads the model catalog once per app-server. A failure leaves the catalog empty, which costs
@@ -22269,7 +22327,7 @@ var CodexAcpAgent = class {
22269
22327
  if (method === "turn/started") {
22270
22328
  const decoded = turnNotificationSchema.safeParse(params);
22271
22329
  if (decoded.success && decoded.data.threadId === this.#nativeSessionId && this.#turn !== null) {
22272
- this.#turn = { completion: this.#turn.completion, turn: { id: decoded.data.turn.id } };
22330
+ this.#turn.turn.id = decoded.data.turn.id;
22273
22331
  }
22274
22332
  return;
22275
22333
  }
@@ -22458,10 +22516,20 @@ var CodexAcpAgent = class {
22458
22516
  this.#appServer.respond(request.id, { action: response.action, content: content3 });
22459
22517
  };
22460
22518
  #runTurn = async (input2, signal) => {
22519
+ signal.throwIfAborted();
22461
22520
  if (this.#turn !== null) {
22462
22521
  throw new AcpExecutionError("Another prompt is already running in this conversation", {}, "session_busy");
22463
22522
  }
22464
22523
  const completion = Promise.withResolvers();
22524
+ void completion.promise.catch(() => {
22525
+ });
22526
+ const aborted2 = () => {
22527
+ completion.reject(signal.reason);
22528
+ void this.close().catch((cause) => {
22529
+ console.error("The cancelled Codex endpoint could not release its process tree", cause);
22530
+ });
22531
+ };
22532
+ signal.addEventListener("abort", aborted2, { once: true });
22465
22533
  const turn = { completion, turn: { id: "" } };
22466
22534
  this.#turn = turn;
22467
22535
  try {
@@ -22507,6 +22575,7 @@ var CodexAcpAgent = class {
22507
22575
  }
22508
22576
  return await completion.promise;
22509
22577
  } finally {
22578
+ signal.removeEventListener("abort", aborted2);
22510
22579
  if (this.#turn === turn) {
22511
22580
  this.#turn = null;
22512
22581
  }
@@ -22535,7 +22604,6 @@ var CodexAcpAgent = class {
22535
22604
  if (active === null) {
22536
22605
  return;
22537
22606
  }
22538
- this.#turn = null;
22539
22607
  await this.#updateTail;
22540
22608
  if (turn.status === "failed") {
22541
22609
  active.completion.reject(
@@ -23657,24 +23725,40 @@ async function probeInProcessReadiness(agent, environment, defaultWorkspace, con
23657
23725
  environment: { ...filterEnvironment(environment), ...agent.environment }
23658
23726
  });
23659
23727
  try {
23660
- await inProcess.initialize(controller.signal);
23661
23728
  const connection = createAcpClient(new DiscoveryAcpHandler()).connect(inProcess.app());
23662
- const initialized = await connection.agent.request(
23663
- methods6.agent.initialize,
23664
- {
23665
- clientCapabilities: {},
23666
- clientInfo: { name: "mobius", version: "0.0.3" },
23667
- protocolVersion: PROTOCOL_VERSION2
23668
- },
23669
- { cancellationSignal: controller.signal }
23670
- );
23671
- if (initialized.protocolVersion !== PROTOCOL_VERSION2) {
23672
- throw new AgentProbeError("acp_incompatible", "ACP agent selected an unsupported protocol version");
23729
+ try {
23730
+ return await Promise.race([
23731
+ (async () => {
23732
+ await inProcess.initialize(controller.signal);
23733
+ const initialized = await connection.agent.request(
23734
+ methods6.agent.initialize,
23735
+ {
23736
+ clientCapabilities: {},
23737
+ clientInfo: { name: "mobius", version: "0.0.3" },
23738
+ protocolVersion: PROTOCOL_VERSION2
23739
+ },
23740
+ { cancellationSignal: controller.signal }
23741
+ );
23742
+ if (initialized.protocolVersion !== PROTOCOL_VERSION2) {
23743
+ throw new AgentProbeError(
23744
+ "acp_incompatible",
23745
+ "ACP agent selected an unsupported protocol version"
23746
+ );
23747
+ }
23748
+ return new VerifiedAcpReadiness(
23749
+ normalizeVersionOutput(initialized.agentInfo?.version ?? ""),
23750
+ normalizeAcpCapabilities(initialized)
23751
+ );
23752
+ })(),
23753
+ inProcess.terminated.then((termination) => {
23754
+ throw new AgentProbeError("acp_incompatible", "The ACP endpoint stopped during initialization", {
23755
+ cause: acpEndpointTerminationError(termination)
23756
+ });
23757
+ })
23758
+ ]);
23759
+ } finally {
23760
+ connection.close();
23673
23761
  }
23674
- return new VerifiedAcpReadiness(
23675
- normalizeVersionOutput(initialized.agentInfo?.version ?? ""),
23676
- normalizeAcpCapabilities(initialized)
23677
- );
23678
23762
  } finally {
23679
23763
  await inProcess.close();
23680
23764
  }
@@ -25738,6 +25822,8 @@ var encodeRecordedSessionEvent = (event) => JSON.stringify(decodeRecordedSession
25738
25822
  // ../protocol/src/session-live-history.ts
25739
25823
  var SESSION_LIVE_HISTORY_LOAD_KIND = "session.live-history.load";
25740
25824
  var SESSION_LIVE_HISTORY_LOADED_KIND = "session.live-history.loaded";
25825
+ var SESSION_LIVE_HISTORY_PAGE_LOAD_KIND = "session.live-history.page.load";
25826
+ var SESSION_LIVE_HISTORY_PAGE_LOADED_KIND = "session.live-history.page.loaded";
25741
25827
  var identifier2 = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/);
25742
25828
  var directoryIdentifier = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,2047}$/);
25743
25829
  var sessionLiveHistoryLoadSchema = external_exports.strictObject({
@@ -25755,6 +25841,23 @@ var sessionLiveHistoryLoadedSchema = external_exports.strictObject({
25755
25841
  requestId: identifier2,
25756
25842
  sessionId: identifier2
25757
25843
  }).readonly();
25844
+ var sessionLiveHistoryPageLoadSchema = external_exports.strictObject({
25845
+ additionalDirectoryIds: external_exports.array(directoryIdentifier).max(16).readonly(),
25846
+ agentId: identifier2,
25847
+ bindingId: identifier2,
25848
+ cursor: external_exports.string().min(1).max(512).nullable(),
25849
+ directoryId: directoryIdentifier,
25850
+ kind: external_exports.literal(SESSION_LIVE_HISTORY_PAGE_LOAD_KIND),
25851
+ limit: external_exports.number().int().min(1).max(100),
25852
+ requestId: identifier2,
25853
+ sessionId: identifier2
25854
+ }).readonly();
25855
+ var sessionLiveHistoryPageLoadedSchema = external_exports.strictObject({
25856
+ kind: external_exports.literal(SESSION_LIVE_HISTORY_PAGE_LOADED_KIND),
25857
+ page: nativeMessagePageSchema,
25858
+ requestId: identifier2,
25859
+ sessionId: identifier2
25860
+ }).readonly();
25758
25861
  function decode6(schema, encoded) {
25759
25862
  try {
25760
25863
  const value = JSON.parse(encoded);
@@ -25767,6 +25870,10 @@ var decodeSessionLiveHistoryLoad = (encoded) => decode6(sessionLiveHistoryLoadSc
25767
25870
  var decodeSessionLiveHistoryLoaded = (encoded) => decode6(sessionLiveHistoryLoadedSchema, encoded);
25768
25871
  var encodeSessionLiveHistoryLoad = (value) => JSON.stringify(sessionLiveHistoryLoadSchema.parse(value));
25769
25872
  var encodeSessionLiveHistoryLoaded = (value) => JSON.stringify(sessionLiveHistoryLoadedSchema.parse(value));
25873
+ var decodeSessionLiveHistoryPageLoad = (encoded) => decode6(sessionLiveHistoryPageLoadSchema, encoded);
25874
+ var decodeSessionLiveHistoryPageLoaded = (encoded) => decode6(sessionLiveHistoryPageLoadedSchema, encoded);
25875
+ var encodeSessionLiveHistoryPageLoad = (value) => JSON.stringify(sessionLiveHistoryPageLoadSchema.parse(value));
25876
+ var encodeSessionLiveHistoryPageLoaded = (value) => JSON.stringify(sessionLiveHistoryPageLoadedSchema.parse(value));
25770
25877
 
25771
25878
  // ../protocol/src/daemon-transport.ts
25772
25879
  function defineMessageSignature(kind, encoder, decoder) {
@@ -25870,6 +25977,11 @@ var serviceToDaemonSignatures = {
25870
25977
  encodeSessionLiveHistoryLoad,
25871
25978
  decodeSessionLiveHistoryLoad
25872
25979
  ),
25980
+ [SESSION_LIVE_HISTORY_PAGE_LOAD_KIND]: defineMessageSignature(
25981
+ SESSION_LIVE_HISTORY_PAGE_LOAD_KIND,
25982
+ encodeSessionLiveHistoryPageLoad,
25983
+ decodeSessionLiveHistoryPageLoad
25984
+ ),
25873
25985
  [SESSION_PERMISSION_RESPOND_KIND]: defineMessageSignature(
25874
25986
  SESSION_PERMISSION_RESPOND_KIND,
25875
25987
  encodeSessionPermissionRespondCommand,
@@ -25980,6 +26092,11 @@ var daemonToServiceSignatures = {
25980
26092
  encodeSessionLiveHistoryLoaded,
25981
26093
  decodeSessionLiveHistoryLoaded
25982
26094
  ),
26095
+ [SESSION_LIVE_HISTORY_PAGE_LOADED_KIND]: defineMessageSignature(
26096
+ SESSION_LIVE_HISTORY_PAGE_LOADED_KIND,
26097
+ encodeSessionLiveHistoryPageLoaded,
26098
+ decodeSessionLiveHistoryPageLoaded
26099
+ ),
25983
26100
  [SESSION_READY_KIND]: defineMessageSignature(SESSION_READY_KIND, encodeSessionReadyEvent, decodeSessionReadyEvent),
25984
26101
  [WORKSPACE_ENTRIES_KIND]: defineMessageSignature(
25985
26102
  WORKSPACE_ENTRIES_KIND,
@@ -35490,6 +35607,29 @@ function sessionConfigProtocolForAgent(agentId) {
35490
35607
  }
35491
35608
 
35492
35609
  // src/acp/session-history.ts
35610
+ var HISTORY_ACTIVITY_FIELD_LIMIT = 1e5;
35611
+ var HISTORY_ACTIVITY_LIMIT = 100;
35612
+ function historyActivity(activity2) {
35613
+ return {
35614
+ activityId: activity2.activityId.slice(0, 128),
35615
+ activityType: activity2.activityType.slice(0, 128),
35616
+ content: activity2.content.slice(0, 100),
35617
+ input: activity2.input.slice(0, HISTORY_ACTIVITY_FIELD_LIMIT),
35618
+ locations: activity2.locations.slice(0, 100).map((location) => location.slice(0, 2048)),
35619
+ name: activity2.name.slice(0, 128),
35620
+ output: activity2.output.slice(0, HISTORY_ACTIVITY_FIELD_LIMIT),
35621
+ sequence: activity2.sequence,
35622
+ status: activity2.status.slice(0, 64),
35623
+ title: activity2.title.slice(0, 500),
35624
+ toolKind: activity2.toolKind.slice(0, 64)
35625
+ };
35626
+ }
35627
+ function historyContentCharacters(messages) {
35628
+ return messages.reduce(
35629
+ (total, message) => total + message.text.length + (message.role === "assistant" ? JSON.stringify(message.activities).length + JSON.stringify(message.content).length : 0),
35630
+ 0
35631
+ );
35632
+ }
35493
35633
  var AcpHistoryReplay = class {
35494
35634
  #activities = /* @__PURE__ */ new Map();
35495
35635
  #messages = [];
@@ -35596,33 +35736,45 @@ var AcpHistoryReplay = class {
35596
35736
  };
35597
35737
  snapshot = async () => {
35598
35738
  await this.#activityTracker.finish();
35739
+ const messages = this.#messages.map((message) => {
35740
+ if (message.role === "user") {
35741
+ return message;
35742
+ }
35743
+ const activities = message.activityIds.flatMap((id) => {
35744
+ const activity2 = this.#activities.get(id);
35745
+ return activity2 === void 0 ? [] : [historyActivity(activity2)];
35746
+ });
35747
+ if (activities.length > HISTORY_ACTIVITY_LIMIT) {
35748
+ this.#truncated = true;
35749
+ }
35750
+ return {
35751
+ role: "assistant",
35752
+ text: message.text,
35753
+ content: message.content.slice(0, 100),
35754
+ activities: activities.slice(-HISTORY_ACTIVITY_LIMIT)
35755
+ };
35756
+ });
35757
+ while (historyContentCharacters(messages) > SESSION_HISTORY_CHARACTER_LIMIT) {
35758
+ const richIndex = messages.findIndex(
35759
+ (message) => message.role === "assistant" && (message.activities.length > 0 || message.content.length > 0)
35760
+ );
35761
+ if (richIndex === -1) {
35762
+ messages.shift();
35763
+ } else {
35764
+ const message = messages[richIndex];
35765
+ if (message?.role === "assistant") {
35766
+ messages[richIndex] = {
35767
+ ...message,
35768
+ activities: message.activities.length > 0 ? message.activities.slice(1) : message.activities,
35769
+ content: message.activities.length === 0 && message.content.length > 0 ? message.content.slice(1) : message.content
35770
+ };
35771
+ }
35772
+ }
35773
+ this.#truncated = true;
35774
+ }
35599
35775
  return {
35600
35776
  status: "available",
35601
- messages: this.#messages.map(
35602
- (message) => message.role === "user" ? message : {
35603
- role: "assistant",
35604
- text: message.text,
35605
- content: message.content,
35606
- activities: message.activityIds.flatMap((id) => {
35607
- const activity2 = this.#activities.get(id);
35608
- return activity2 === void 0 ? [] : [
35609
- {
35610
- activityId: activity2.activityId,
35611
- activityType: activity2.activityType,
35612
- content: activity2.content,
35613
- input: activity2.input,
35614
- locations: activity2.locations,
35615
- name: activity2.name,
35616
- output: activity2.output,
35617
- sequence: activity2.sequence,
35618
- status: activity2.status,
35619
- title: activity2.title,
35620
- toolKind: activity2.toolKind
35621
- }
35622
- ];
35623
- })
35624
- }
35625
- ),
35777
+ messages,
35626
35778
  truncated: this.#truncated,
35627
35779
  coveredCommandIds: [],
35628
35780
  coveredMessageIds: []
@@ -36423,8 +36575,8 @@ var AcpProcessSession = class _AcpProcessSession {
36423
36575
  #pendingElicitations = /* @__PURE__ */ new Map();
36424
36576
  #pendingPermissions = /* @__PURE__ */ new Map();
36425
36577
  #preSessionUpdates = [];
36426
- // The adapter-process topology only. An in-process agent owns the app-server child itself.
36427
- #processExit;
36578
+ // Both topologies report a terminal outcome, even after a prompt's initial RPC is acknowledged.
36579
+ #termination;
36428
36580
  #runtimeChild;
36429
36581
  #metrics;
36430
36582
  #sessionConfigProtocol;
@@ -36468,8 +36620,7 @@ var AcpProcessSession = class _AcpProcessSession {
36468
36620
  });
36469
36621
  this.#inProcessAgent = inProcess;
36470
36622
  this.#runtimeChild = null;
36471
- this.#processExit = new Promise(() => {
36472
- });
36623
+ this.#termination = inProcess.terminated;
36473
36624
  this.#connection = createAcpClient(this).connect(inProcess.app());
36474
36625
  return;
36475
36626
  }
@@ -36493,9 +36644,16 @@ var AcpProcessSession = class _AcpProcessSession {
36493
36644
  stderr.on("data", (chunk) => {
36494
36645
  process.stderr.write(`[${agent.id}-acp] ${chunk}`);
36495
36646
  });
36496
- this.#processExit = new Promise((resolve7) => {
36497
- child.once("error", resolve7);
36498
- child.once("exit", resolve7);
36647
+ this.#termination = new Promise((resolve7) => {
36648
+ child.once("error", (cause) => {
36649
+ resolve7({ kind: "failed", error: new AcpExecutionError("The ACP process could not run", { cause }) });
36650
+ });
36651
+ child.once("exit", (code, signal) => {
36652
+ resolve7({
36653
+ kind: "failed",
36654
+ error: new AcpExecutionError("The ACP process stopped", { cause: { code, signal } })
36655
+ });
36656
+ });
36499
36657
  });
36500
36658
  const stream = ndJsonStream2(createWritableAcpStream(stdin), readableWebStream(stdout));
36501
36659
  this.#connection = createAcpClient(this).connect(stream);
@@ -37637,8 +37795,9 @@ var AcpProcessSession = class _AcpProcessSession {
37637
37795
  try {
37638
37796
  return await Promise.race([
37639
37797
  operation,
37640
- this.#processExit.then(() => {
37641
- throw new AcpExecutionError(exitMessage);
37798
+ this.#termination.then((termination) => {
37799
+ const cause = acpEndpointTerminationError(termination);
37800
+ throw new AcpExecutionError(exitMessage, { cause }, cause.code);
37642
37801
  }),
37643
37802
  aborted2
37644
37803
  ]);
@@ -43013,6 +43172,70 @@ async function executeSessionPrepare(publisher, socket, command, config2, direct
43013
43172
  reportOperationFailure(socket, command.requestId, command.sessionId, error62, metrics.snapshot());
43014
43173
  }
43015
43174
  }
43175
+ function liveHistoryCursor(sessionId, endIndex) {
43176
+ return Buffer.from(JSON.stringify({ endIndex, sessionId }), "utf8").toString("base64url");
43177
+ }
43178
+ function liveHistoryEndIndex(cursor, sessionId) {
43179
+ try {
43180
+ if (!/^[A-Za-z0-9_-]{1,512}$/u.test(cursor)) {
43181
+ throw new Error("Invalid cursor alphabet");
43182
+ }
43183
+ const value = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
43184
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
43185
+ throw new Error("Invalid cursor shape");
43186
+ }
43187
+ const record2 = Object.fromEntries(Object.entries(value));
43188
+ if (Object.keys(record2).sort().join(",") !== "endIndex,sessionId" || record2["sessionId"] !== sessionId || typeof record2["endIndex"] !== "number" || !Number.isSafeInteger(record2["endIndex"]) || record2["endIndex"] < 0) {
43189
+ throw new Error("Invalid cursor target");
43190
+ }
43191
+ return record2["endIndex"];
43192
+ } catch (cause) {
43193
+ throw new AcpExecutionError("The native Session history cursor is invalid", { cause }, "invalid_cursor");
43194
+ }
43195
+ }
43196
+ function liveHistoryCoveredTurnRanges(history) {
43197
+ const ranges = [];
43198
+ let historyIndex = history.messages.length;
43199
+ for (const commandId of history.coveredCommandIds) {
43200
+ let assistantStartIndex = historyIndex;
43201
+ while (assistantStartIndex > 0 && history.messages[assistantStartIndex - 1]?.role === "assistant") {
43202
+ assistantStartIndex -= 1;
43203
+ }
43204
+ const userIndex = assistantStartIndex - 1;
43205
+ if (assistantStartIndex === historyIndex || history.messages[userIndex]?.role !== "user") {
43206
+ break;
43207
+ }
43208
+ ranges.push({ assistantEndIndex: historyIndex, assistantStartIndex, commandId, userIndex });
43209
+ historyIndex = userIndex;
43210
+ }
43211
+ return ranges;
43212
+ }
43213
+ function paginateLiveSessionHistory(history, sessionId, cursor, limit) {
43214
+ if (history.status === "unavailable") {
43215
+ if (cursor !== null) {
43216
+ throw new AcpExecutionError("Unavailable native Session history has no cursor", {}, "invalid_cursor");
43217
+ }
43218
+ return { cause: history.cause, nextCursor: null, status: "unavailable" };
43219
+ }
43220
+ const endIndex = cursor === null ? history.messages.length : liveHistoryEndIndex(cursor, sessionId);
43221
+ if (endIndex > history.messages.length) {
43222
+ throw new AcpExecutionError("The native Session history cursor is invalid", {}, "invalid_cursor");
43223
+ }
43224
+ const startIndex = Math.max(0, endIndex - limit);
43225
+ const coveredMessageIds = new Set(history.coveredMessageIds);
43226
+ const ranges = liveHistoryCoveredTurnRanges(history);
43227
+ return {
43228
+ coveredCommandIds: ranges.filter((range) => range.userIndex >= startIndex && range.assistantEndIndex <= endIndex).map((range) => range.commandId),
43229
+ coveredMessageIds: ranges.flatMap((range) => [
43230
+ ...range.userIndex >= startIndex && range.userIndex < endIndex && coveredMessageIds.has(`${range.commandId}:user`) ? [`${range.commandId}:user`] : [],
43231
+ ...range.assistantStartIndex >= startIndex && range.assistantEndIndex <= endIndex && coveredMessageIds.has(`${range.commandId}:agent`) ? [`${range.commandId}:agent`] : []
43232
+ ]),
43233
+ messages: history.messages.slice(startIndex, endIndex),
43234
+ nextCursor: startIndex > 0 ? liveHistoryCursor(sessionId, startIndex) : null,
43235
+ status: "available",
43236
+ truncated: history.truncated
43237
+ };
43238
+ }
43016
43239
  async function executeSessionLiveHistoryLoad(socket, command, config2, directories, audit, sessions, signal) {
43017
43240
  try {
43018
43241
  const resolved = await resolveSessionDirectories(
@@ -43062,6 +43285,57 @@ async function executeSessionLiveHistoryLoad(socket, command, config2, directori
43062
43285
  });
43063
43286
  }
43064
43287
  }
43288
+ async function executeSessionLiveHistoryPageLoad(socket, command, config2, directories, audit, sessions, signal) {
43289
+ try {
43290
+ const resolved = await resolveSessionDirectories(
43291
+ directories,
43292
+ config2.bindingId,
43293
+ command.directoryId,
43294
+ command.additionalDirectoryIds,
43295
+ signal
43296
+ );
43297
+ const history = await sessions.loadSessionHistory({
43298
+ additionalDirectories: resolved.additionalDirectories,
43299
+ agent: config2.catalog.find(command.agentId),
43300
+ cwd: resolved.cwd,
43301
+ sessionId: command.sessionId,
43302
+ signal
43303
+ });
43304
+ signal.throwIfAborted();
43305
+ const page = paginateLiveSessionHistory(history, command.sessionId, command.cursor, command.limit);
43306
+ audit.record({
43307
+ commandId: command.requestId,
43308
+ event: "session_history_loaded",
43309
+ sessionId: command.sessionId
43310
+ });
43311
+ send(socket, {
43312
+ kind: "session.live-history.page.loaded",
43313
+ page,
43314
+ requestId: command.requestId,
43315
+ sessionId: command.sessionId
43316
+ });
43317
+ } catch (error62) {
43318
+ if (signal.aborted) {
43319
+ return;
43320
+ }
43321
+ audit.record({
43322
+ commandId: command.requestId,
43323
+ details: { code: operationErrorCode(error62) },
43324
+ event: "session_history_unavailable",
43325
+ sessionId: command.sessionId
43326
+ });
43327
+ send(socket, {
43328
+ kind: "session.live-history.page.loaded",
43329
+ page: {
43330
+ status: "unavailable",
43331
+ cause: { code: operationErrorCode(error62), message: operationErrorMessage(error62) },
43332
+ nextCursor: null
43333
+ },
43334
+ requestId: command.requestId,
43335
+ sessionId: command.sessionId
43336
+ });
43337
+ }
43338
+ }
43065
43339
  async function executeSessionConfigure(publisher, socket, command, config2, directories, audit, sessions, signal) {
43066
43340
  try {
43067
43341
  const resolved = await resolveSessionDirectories(
@@ -43921,6 +44195,19 @@ async function runRelayConnection(config2, directories, audit, sessions, install
43921
44195
  );
43922
44196
  return;
43923
44197
  }
44198
+ if (kind === SESSION_LIVE_HISTORY_PAGE_LOAD_KIND) {
44199
+ const command2 = decodeSessionLiveHistoryPageLoad(encoded);
44200
+ void executeSessionLiveHistoryPageLoad(
44201
+ socket,
44202
+ command2,
44203
+ config2,
44204
+ directories,
44205
+ audit,
44206
+ sessions,
44207
+ connectionController.signal
44208
+ );
44209
+ return;
44210
+ }
43924
44211
  if (kind === NATIVE_SESSION_CANCEL_KIND) {
43925
44212
  const command2 = message;
43926
44213
  const pending = nativeRequests.get(command2.requestId);