@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/index.js CHANGED
@@ -21256,6 +21256,8 @@ var encodeRecordedSessionEvent = (event) => JSON.stringify(decodeRecordedSession
21256
21256
  // ../protocol/src/session-live-history.ts
21257
21257
  var SESSION_LIVE_HISTORY_LOAD_KIND = "session.live-history.load";
21258
21258
  var SESSION_LIVE_HISTORY_LOADED_KIND = "session.live-history.loaded";
21259
+ var SESSION_LIVE_HISTORY_PAGE_LOAD_KIND = "session.live-history.page.load";
21260
+ var SESSION_LIVE_HISTORY_PAGE_LOADED_KIND = "session.live-history.page.loaded";
21259
21261
  var identifier2 = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/);
21260
21262
  var directoryIdentifier = external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,2047}$/);
21261
21263
  var sessionLiveHistoryLoadSchema = external_exports.strictObject({
@@ -21273,6 +21275,23 @@ var sessionLiveHistoryLoadedSchema = external_exports.strictObject({
21273
21275
  requestId: identifier2,
21274
21276
  sessionId: identifier2
21275
21277
  }).readonly();
21278
+ var sessionLiveHistoryPageLoadSchema = external_exports.strictObject({
21279
+ additionalDirectoryIds: external_exports.array(directoryIdentifier).max(16).readonly(),
21280
+ agentId: identifier2,
21281
+ bindingId: identifier2,
21282
+ cursor: external_exports.string().min(1).max(512).nullable(),
21283
+ directoryId: directoryIdentifier,
21284
+ kind: external_exports.literal(SESSION_LIVE_HISTORY_PAGE_LOAD_KIND),
21285
+ limit: external_exports.number().int().min(1).max(100),
21286
+ requestId: identifier2,
21287
+ sessionId: identifier2
21288
+ }).readonly();
21289
+ var sessionLiveHistoryPageLoadedSchema = external_exports.strictObject({
21290
+ kind: external_exports.literal(SESSION_LIVE_HISTORY_PAGE_LOADED_KIND),
21291
+ page: nativeMessagePageSchema,
21292
+ requestId: identifier2,
21293
+ sessionId: identifier2
21294
+ }).readonly();
21276
21295
  function decode6(schema, encoded) {
21277
21296
  try {
21278
21297
  const value = JSON.parse(encoded);
@@ -21285,6 +21304,10 @@ var decodeSessionLiveHistoryLoad = (encoded) => decode6(sessionLiveHistoryLoadSc
21285
21304
  var decodeSessionLiveHistoryLoaded = (encoded) => decode6(sessionLiveHistoryLoadedSchema, encoded);
21286
21305
  var encodeSessionLiveHistoryLoad = (value) => JSON.stringify(sessionLiveHistoryLoadSchema.parse(value));
21287
21306
  var encodeSessionLiveHistoryLoaded = (value) => JSON.stringify(sessionLiveHistoryLoadedSchema.parse(value));
21307
+ var decodeSessionLiveHistoryPageLoad = (encoded) => decode6(sessionLiveHistoryPageLoadSchema, encoded);
21308
+ var decodeSessionLiveHistoryPageLoaded = (encoded) => decode6(sessionLiveHistoryPageLoadedSchema, encoded);
21309
+ var encodeSessionLiveHistoryPageLoad = (value) => JSON.stringify(sessionLiveHistoryPageLoadSchema.parse(value));
21310
+ var encodeSessionLiveHistoryPageLoaded = (value) => JSON.stringify(sessionLiveHistoryPageLoadedSchema.parse(value));
21288
21311
 
21289
21312
  // ../protocol/src/daemon-transport.ts
21290
21313
  function defineMessageSignature(kind, encoder, decoder) {
@@ -21388,6 +21411,11 @@ var serviceToDaemonSignatures = {
21388
21411
  encodeSessionLiveHistoryLoad,
21389
21412
  decodeSessionLiveHistoryLoad
21390
21413
  ),
21414
+ [SESSION_LIVE_HISTORY_PAGE_LOAD_KIND]: defineMessageSignature(
21415
+ SESSION_LIVE_HISTORY_PAGE_LOAD_KIND,
21416
+ encodeSessionLiveHistoryPageLoad,
21417
+ decodeSessionLiveHistoryPageLoad
21418
+ ),
21391
21419
  [SESSION_PERMISSION_RESPOND_KIND]: defineMessageSignature(
21392
21420
  SESSION_PERMISSION_RESPOND_KIND,
21393
21421
  encodeSessionPermissionRespondCommand,
@@ -21498,6 +21526,11 @@ var daemonToServiceSignatures = {
21498
21526
  encodeSessionLiveHistoryLoaded,
21499
21527
  decodeSessionLiveHistoryLoaded
21500
21528
  ),
21529
+ [SESSION_LIVE_HISTORY_PAGE_LOADED_KIND]: defineMessageSignature(
21530
+ SESSION_LIVE_HISTORY_PAGE_LOADED_KIND,
21531
+ encodeSessionLiveHistoryPageLoaded,
21532
+ decodeSessionLiveHistoryPageLoaded
21533
+ ),
21501
21534
  [SESSION_READY_KIND]: defineMessageSignature(SESSION_READY_KIND, encodeSessionReadyEvent, decodeSessionReadyEvent),
21502
21535
  [WORKSPACE_ENTRIES_KIND]: defineMessageSignature(
21503
21536
  WORKSPACE_ENTRIES_KIND,
@@ -23271,6 +23304,20 @@ var AcpActivityTracker = class {
23271
23304
  };
23272
23305
  };
23273
23306
 
23307
+ // src/acp/in-process/acp-endpoint.ts
23308
+ function acpEndpointTerminationError(termination) {
23309
+ switch (termination.kind) {
23310
+ case "failed":
23311
+ return termination.error;
23312
+ case "closed":
23313
+ return new AcpExecutionError("The ACP endpoint is closed", {}, "acp_endpoint_closed");
23314
+ default: {
23315
+ const unreachable = termination;
23316
+ return unreachable;
23317
+ }
23318
+ }
23319
+ }
23320
+
23274
23321
  // ../../node_modules/.pnpm/mdast-util-to-string@4.0.0/node_modules/mdast-util-to-string/lib/index.js
23275
23322
  var emptyOptions = {};
23276
23323
  function toString(value, options) {
@@ -30876,6 +30923,29 @@ function sessionConfigProtocolForAgent(agentId) {
30876
30923
  }
30877
30924
 
30878
30925
  // src/acp/session-history.ts
30926
+ var HISTORY_ACTIVITY_FIELD_LIMIT = 1e5;
30927
+ var HISTORY_ACTIVITY_LIMIT = 100;
30928
+ function historyActivity(activity2) {
30929
+ return {
30930
+ activityId: activity2.activityId.slice(0, 128),
30931
+ activityType: activity2.activityType.slice(0, 128),
30932
+ content: activity2.content.slice(0, 100),
30933
+ input: activity2.input.slice(0, HISTORY_ACTIVITY_FIELD_LIMIT),
30934
+ locations: activity2.locations.slice(0, 100).map((location) => location.slice(0, 2048)),
30935
+ name: activity2.name.slice(0, 128),
30936
+ output: activity2.output.slice(0, HISTORY_ACTIVITY_FIELD_LIMIT),
30937
+ sequence: activity2.sequence,
30938
+ status: activity2.status.slice(0, 64),
30939
+ title: activity2.title.slice(0, 500),
30940
+ toolKind: activity2.toolKind.slice(0, 64)
30941
+ };
30942
+ }
30943
+ function historyContentCharacters(messages) {
30944
+ return messages.reduce(
30945
+ (total, message) => total + message.text.length + (message.role === "assistant" ? JSON.stringify(message.activities).length + JSON.stringify(message.content).length : 0),
30946
+ 0
30947
+ );
30948
+ }
30879
30949
  var AcpHistoryReplay = class {
30880
30950
  #activities = /* @__PURE__ */ new Map();
30881
30951
  #messages = [];
@@ -30982,33 +31052,45 @@ var AcpHistoryReplay = class {
30982
31052
  };
30983
31053
  snapshot = async () => {
30984
31054
  await this.#activityTracker.finish();
31055
+ const messages = this.#messages.map((message) => {
31056
+ if (message.role === "user") {
31057
+ return message;
31058
+ }
31059
+ const activities = message.activityIds.flatMap((id) => {
31060
+ const activity2 = this.#activities.get(id);
31061
+ return activity2 === void 0 ? [] : [historyActivity(activity2)];
31062
+ });
31063
+ if (activities.length > HISTORY_ACTIVITY_LIMIT) {
31064
+ this.#truncated = true;
31065
+ }
31066
+ return {
31067
+ role: "assistant",
31068
+ text: message.text,
31069
+ content: message.content.slice(0, 100),
31070
+ activities: activities.slice(-HISTORY_ACTIVITY_LIMIT)
31071
+ };
31072
+ });
31073
+ while (historyContentCharacters(messages) > SESSION_HISTORY_CHARACTER_LIMIT) {
31074
+ const richIndex = messages.findIndex(
31075
+ (message) => message.role === "assistant" && (message.activities.length > 0 || message.content.length > 0)
31076
+ );
31077
+ if (richIndex === -1) {
31078
+ messages.shift();
31079
+ } else {
31080
+ const message = messages[richIndex];
31081
+ if (message?.role === "assistant") {
31082
+ messages[richIndex] = {
31083
+ ...message,
31084
+ activities: message.activities.length > 0 ? message.activities.slice(1) : message.activities,
31085
+ content: message.activities.length === 0 && message.content.length > 0 ? message.content.slice(1) : message.content
31086
+ };
31087
+ }
31088
+ }
31089
+ this.#truncated = true;
31090
+ }
30985
31091
  return {
30986
31092
  status: "available",
30987
- messages: this.#messages.map(
30988
- (message) => message.role === "user" ? message : {
30989
- role: "assistant",
30990
- text: message.text,
30991
- content: message.content,
30992
- activities: message.activityIds.flatMap((id) => {
30993
- const activity2 = this.#activities.get(id);
30994
- return activity2 === void 0 ? [] : [
30995
- {
30996
- activityId: activity2.activityId,
30997
- activityType: activity2.activityType,
30998
- content: activity2.content,
30999
- input: activity2.input,
31000
- locations: activity2.locations,
31001
- name: activity2.name,
31002
- output: activity2.output,
31003
- sequence: activity2.sequence,
31004
- status: activity2.status,
31005
- title: activity2.title,
31006
- toolKind: activity2.toolKind
31007
- }
31008
- ];
31009
- })
31010
- }
31011
- ),
31093
+ messages,
31012
31094
  truncated: this.#truncated,
31013
31095
  coveredCommandIds: [],
31014
31096
  coveredMessageIds: []
@@ -31809,8 +31891,8 @@ var AcpProcessSession = class _AcpProcessSession {
31809
31891
  #pendingElicitations = /* @__PURE__ */ new Map();
31810
31892
  #pendingPermissions = /* @__PURE__ */ new Map();
31811
31893
  #preSessionUpdates = [];
31812
- // The adapter-process topology only. An in-process agent owns the app-server child itself.
31813
- #processExit;
31894
+ // Both topologies report a terminal outcome, even after a prompt's initial RPC is acknowledged.
31895
+ #termination;
31814
31896
  #runtimeChild;
31815
31897
  #metrics;
31816
31898
  #sessionConfigProtocol;
@@ -31854,8 +31936,7 @@ var AcpProcessSession = class _AcpProcessSession {
31854
31936
  });
31855
31937
  this.#inProcessAgent = inProcess;
31856
31938
  this.#runtimeChild = null;
31857
- this.#processExit = new Promise(() => {
31858
- });
31939
+ this.#termination = inProcess.terminated;
31859
31940
  this.#connection = createAcpClient(this).connect(inProcess.app());
31860
31941
  return;
31861
31942
  }
@@ -31879,9 +31960,16 @@ var AcpProcessSession = class _AcpProcessSession {
31879
31960
  stderr.on("data", (chunk) => {
31880
31961
  process.stderr.write(`[${agent.id}-acp] ${chunk}`);
31881
31962
  });
31882
- this.#processExit = new Promise((resolve8) => {
31883
- child.once("error", resolve8);
31884
- child.once("exit", resolve8);
31963
+ this.#termination = new Promise((resolve8) => {
31964
+ child.once("error", (cause) => {
31965
+ resolve8({ kind: "failed", error: new AcpExecutionError("The ACP process could not run", { cause }) });
31966
+ });
31967
+ child.once("exit", (code, signal) => {
31968
+ resolve8({
31969
+ kind: "failed",
31970
+ error: new AcpExecutionError("The ACP process stopped", { cause: { code, signal } })
31971
+ });
31972
+ });
31885
31973
  });
31886
31974
  const stream = ndJsonStream(createWritableAcpStream(stdin), readableWebStream(stdout));
31887
31975
  this.#connection = createAcpClient(this).connect(stream);
@@ -33023,8 +33111,9 @@ var AcpProcessSession = class _AcpProcessSession {
33023
33111
  try {
33024
33112
  return await Promise.race([
33025
33113
  operation,
33026
- this.#processExit.then(() => {
33027
- throw new AcpExecutionError(exitMessage);
33114
+ this.#termination.then((termination) => {
33115
+ const cause = acpEndpointTerminationError(termination);
33116
+ throw new AcpExecutionError(exitMessage, { cause }, cause.code);
33028
33117
  }),
33029
33118
  aborted2
33030
33119
  ]);
@@ -34980,11 +35069,9 @@ var threadSettingsUpdatedSchema = external_exports.object({
34980
35069
  // src/acp/codex/app-server-client.ts
34981
35070
  var INITIALIZE_TIMEOUT_MILLISECONDS = 3e4;
34982
35071
  var OUTPUT_LIMIT_BYTES = 32 * 1024 * 1024;
34983
- var CodexAppServerError = class extends Error {
34984
- code;
35072
+ var CodexAppServerError = class extends AcpExecutionError {
34985
35073
  constructor(code, message, options = {}) {
34986
- super(message, options);
34987
- this.code = code;
35074
+ super(message, options, code);
34988
35075
  this.name = "CodexAppServerError";
34989
35076
  }
34990
35077
  };
@@ -34992,12 +35079,14 @@ var CodexAppServerClient = class {
34992
35079
  #child;
34993
35080
  #handlers;
34994
35081
  #pending = /* @__PURE__ */ new Map();
34995
- #processExit;
34996
- #failure = null;
35082
+ #termination = Promise.withResolvers();
35083
+ terminated = this.#termination.promise;
35084
+ #lifecycle = {
35085
+ kind: "open"
35086
+ };
34997
35087
  #nextRequestId = 1;
34998
35088
  #pendingBuffer = "";
34999
35089
  #receivedBytes = 0;
35000
- #closed = false;
35001
35090
  constructor(options) {
35002
35091
  this.#handlers = options.handlers;
35003
35092
  this.#child = spawn3(options.command, ["app-server"], {
@@ -35022,21 +35111,56 @@ var CodexAppServerClient = class {
35022
35111
  stderr.on("data", (chunk) => {
35023
35112
  process.stderr.write(`[codex-app-server] ${chunk}`);
35024
35113
  });
35025
- this.#processExit = new Promise((resolve8) => {
35026
- this.#child.once("error", resolve8);
35027
- this.#child.once("exit", resolve8);
35114
+ this.#child.once("error", (cause) => {
35115
+ this.#fail(
35116
+ new CodexAppServerError("codex_app_server_exited", "The Codex app-server could not run", { cause })
35117
+ );
35118
+ });
35119
+ this.#child.once("exit", (code, signal) => {
35120
+ this.#fail(
35121
+ new CodexAppServerError("codex_app_server_exited", "The Codex app-server stopped", {
35122
+ cause: { code, signal }
35123
+ })
35124
+ );
35125
+ });
35126
+ for (const stream of [stdin, stdout, stderr]) {
35127
+ stream.on("error", (cause) => {
35128
+ this.#fail(
35129
+ new CodexAppServerError("codex_app_server_io_error", "The Codex app-server connection failed", {
35130
+ cause
35131
+ })
35132
+ );
35133
+ });
35134
+ }
35135
+ stdout.once("end", () => {
35136
+ this.#fail(new CodexAppServerError("codex_app_server_exited", "The Codex app-server output closed"));
35028
35137
  });
35029
35138
  }
35030
35139
  child = () => this.#child;
35031
35140
  #fail = (error62) => {
35032
- this.#failure ??= error62;
35141
+ this.#terminate({ kind: "failed", error: error62 });
35142
+ };
35143
+ #terminate = (result) => {
35144
+ if (this.#lifecycle.kind === "terminated") {
35145
+ return;
35146
+ }
35147
+ this.#lifecycle = { kind: "terminated", result };
35148
+ this.#termination.resolve(result);
35149
+ const error62 = acpEndpointTerminationError(result);
35033
35150
  for (const [id, pending] of this.#pending) {
35034
35151
  this.#pending.delete(id);
35035
35152
  pending.completion.reject(error62);
35036
35153
  }
35037
35154
  };
35038
- #exitedFailure = (method) => this.#failure ?? new CodexAppServerError("codex_app_server_exited", `The Codex app-server stopped during ${method}`);
35155
+ #requireOpen = () => {
35156
+ if (this.#lifecycle.kind === "terminated") {
35157
+ throw acpEndpointTerminationError(this.#lifecycle.result);
35158
+ }
35159
+ };
35039
35160
  #consume = (chunk) => {
35161
+ if (this.#lifecycle.kind === "terminated") {
35162
+ return;
35163
+ }
35040
35164
  try {
35041
35165
  this.#receivedBytes += Buffer.byteLength(chunk);
35042
35166
  if (this.#receivedBytes > OUTPUT_LIMIT_BYTES) {
@@ -35065,7 +35189,6 @@ var CodexAppServerClient = class {
35065
35189
  { cause: error62 }
35066
35190
  )
35067
35191
  );
35068
- this.#child.kill("SIGKILL");
35069
35192
  }
35070
35193
  };
35071
35194
  // Handler failures are recorded as the app-server's terminal failure: an ACP client that cannot
@@ -35115,9 +35238,7 @@ var CodexAppServerClient = class {
35115
35238
  /** Sends a request and waits for its response, bounded by the caller's cancellation signal. */
35116
35239
  request = async (method, params, signal) => {
35117
35240
  signal.throwIfAborted();
35118
- if (this.#closed) {
35119
- throw new CodexAppServerError("codex_app_server_closed", "The Codex app-server is closed");
35120
- }
35241
+ this.#requireOpen();
35121
35242
  const id = this.#nextRequestId;
35122
35243
  this.#nextRequestId += 1;
35123
35244
  const completion = Promise.withResolvers();
@@ -35130,7 +35251,7 @@ var CodexAppServerClient = class {
35130
35251
  signal.addEventListener("abort", abort, { once: true });
35131
35252
  try {
35132
35253
  this.#write({ id, method, params });
35133
- return await Promise.race([completion.promise, this.#processExit.then(() => this.#exitedFailure(method))]);
35254
+ return await completion.promise;
35134
35255
  } finally {
35135
35256
  signal.removeEventListener("abort", abort);
35136
35257
  this.#pending.delete(id);
@@ -35146,12 +35267,12 @@ var CodexAppServerClient = class {
35146
35267
  this.#write({ error: { code, message }, id });
35147
35268
  };
35148
35269
  #write = (message) => {
35149
- if (this.#closed) {
35150
- return;
35151
- }
35270
+ this.#requireOpen();
35152
35271
  const stdin = this.#child.stdin;
35153
35272
  if (stdin === null || stdin.destroyed) {
35154
- throw new CodexAppServerError("codex_app_server_closed", "The Codex app-server input is closed");
35273
+ const error62 = new CodexAppServerError("codex_app_server_io_error", "The Codex app-server input is closed");
35274
+ this.#fail(error62);
35275
+ throw error62;
35155
35276
  }
35156
35277
  stdin.write(`${JSON.stringify(message)}
35157
35278
  `);
@@ -35174,15 +35295,7 @@ var CodexAppServerClient = class {
35174
35295
  * app-server and every tool subprocess it started.
35175
35296
  */
35176
35297
  detach = () => {
35177
- if (this.#closed) {
35178
- return;
35179
- }
35180
- this.#closed = true;
35181
- this.#fail(new CodexAppServerError("codex_app_server_closed", "The Codex app-server is closed"));
35182
- const stdin = this.#child.stdin;
35183
- if (stdin !== null && !stdin.destroyed) {
35184
- stdin.end();
35185
- }
35298
+ this.#terminate({ kind: "closed" });
35186
35299
  };
35187
35300
  };
35188
35301
 
@@ -35524,6 +35637,8 @@ function userInputSchema(questions) {
35524
35637
  var CodexAcpAgent = class {
35525
35638
  #app;
35526
35639
  #appServer;
35640
+ terminated;
35641
+ #closePromise = null;
35527
35642
  #connection = null;
35528
35643
  #models = [];
35529
35644
  #nativeSessionId = "";
@@ -35561,6 +35676,15 @@ var CodexAcpAgent = class {
35561
35676
  }
35562
35677
  }
35563
35678
  });
35679
+ this.terminated = this.#appServer.terminated;
35680
+ void this.terminated.then((termination) => {
35681
+ this.#turn?.completion.reject(acpEndpointTerminationError(termination));
35682
+ if (termination.kind === "failed") {
35683
+ void this.close().catch((cause) => {
35684
+ console.error("The failed Codex endpoint could not release its process tree", cause);
35685
+ });
35686
+ }
35687
+ });
35564
35688
  this.#app = createAgentApp({ name: "mobius-codex" }).onConnect((connection) => {
35565
35689
  this.#connection = connection;
35566
35690
  }).onRequest(methods4.agent.initialize, async () => ({
@@ -35672,11 +35796,20 @@ var CodexAcpAgent = class {
35672
35796
  * Releases the app-server and every process it started. Mirrors the adapter path's teardown so a
35673
35797
  * cancelled or closed session cannot leak the tool subprocesses running under the app-server.
35674
35798
  */
35675
- close = async () => {
35676
- const child = this.#appServer.child();
35677
- const captured = await captureProcessTree(child);
35678
- this.#appServer.detach();
35679
- await stopProcessTree(child, captured);
35799
+ close = () => {
35800
+ if (this.#closePromise === null) {
35801
+ this.#appServer.detach();
35802
+ this.#closePromise = (async () => {
35803
+ const child = this.#appServer.child();
35804
+ try {
35805
+ const captured = await captureProcessTree(child);
35806
+ await stopProcessTree(child, captured);
35807
+ } finally {
35808
+ this.#connection?.close();
35809
+ }
35810
+ })();
35811
+ }
35812
+ return this.#closePromise;
35680
35813
  };
35681
35814
  /**
35682
35815
  * Reads the model catalog once per app-server. A failure leaves the catalog empty, which costs
@@ -35920,7 +36053,7 @@ var CodexAcpAgent = class {
35920
36053
  if (method === "turn/started") {
35921
36054
  const decoded = turnNotificationSchema.safeParse(params);
35922
36055
  if (decoded.success && decoded.data.threadId === this.#nativeSessionId && this.#turn !== null) {
35923
- this.#turn = { completion: this.#turn.completion, turn: { id: decoded.data.turn.id } };
36056
+ this.#turn.turn.id = decoded.data.turn.id;
35924
36057
  }
35925
36058
  return;
35926
36059
  }
@@ -36109,10 +36242,20 @@ var CodexAcpAgent = class {
36109
36242
  this.#appServer.respond(request.id, { action: response.action, content: content3 });
36110
36243
  };
36111
36244
  #runTurn = async (input2, signal) => {
36245
+ signal.throwIfAborted();
36112
36246
  if (this.#turn !== null) {
36113
36247
  throw new AcpExecutionError("Another prompt is already running in this conversation", {}, "session_busy");
36114
36248
  }
36115
36249
  const completion = Promise.withResolvers();
36250
+ void completion.promise.catch(() => {
36251
+ });
36252
+ const aborted2 = () => {
36253
+ completion.reject(signal.reason);
36254
+ void this.close().catch((cause) => {
36255
+ console.error("The cancelled Codex endpoint could not release its process tree", cause);
36256
+ });
36257
+ };
36258
+ signal.addEventListener("abort", aborted2, { once: true });
36116
36259
  const turn = { completion, turn: { id: "" } };
36117
36260
  this.#turn = turn;
36118
36261
  try {
@@ -36158,6 +36301,7 @@ var CodexAcpAgent = class {
36158
36301
  }
36159
36302
  return await completion.promise;
36160
36303
  } finally {
36304
+ signal.removeEventListener("abort", aborted2);
36161
36305
  if (this.#turn === turn) {
36162
36306
  this.#turn = null;
36163
36307
  }
@@ -36186,7 +36330,6 @@ var CodexAcpAgent = class {
36186
36330
  if (active === null) {
36187
36331
  return;
36188
36332
  }
36189
- this.#turn = null;
36190
36333
  await this.#updateTail;
36191
36334
  if (turn.status === "failed") {
36192
36335
  active.completion.reject(
@@ -37268,24 +37411,40 @@ async function probeInProcessReadiness(agent, environment, defaultWorkspace, con
37268
37411
  environment: { ...filterEnvironment(environment), ...agent.environment }
37269
37412
  });
37270
37413
  try {
37271
- await inProcess.initialize(controller.signal);
37272
37414
  const connection = createAcpClient(new DiscoveryAcpHandler()).connect(inProcess.app());
37273
- const initialized = await connection.agent.request(
37274
- methods8.agent.initialize,
37275
- {
37276
- clientCapabilities: {},
37277
- clientInfo: { name: "mobius", version: "0.0.3" },
37278
- protocolVersion: PROTOCOL_VERSION3
37279
- },
37280
- { cancellationSignal: controller.signal }
37281
- );
37282
- if (initialized.protocolVersion !== PROTOCOL_VERSION3) {
37283
- throw new AgentProbeError("acp_incompatible", "ACP agent selected an unsupported protocol version");
37415
+ try {
37416
+ return await Promise.race([
37417
+ (async () => {
37418
+ await inProcess.initialize(controller.signal);
37419
+ const initialized = await connection.agent.request(
37420
+ methods8.agent.initialize,
37421
+ {
37422
+ clientCapabilities: {},
37423
+ clientInfo: { name: "mobius", version: "0.0.3" },
37424
+ protocolVersion: PROTOCOL_VERSION3
37425
+ },
37426
+ { cancellationSignal: controller.signal }
37427
+ );
37428
+ if (initialized.protocolVersion !== PROTOCOL_VERSION3) {
37429
+ throw new AgentProbeError(
37430
+ "acp_incompatible",
37431
+ "ACP agent selected an unsupported protocol version"
37432
+ );
37433
+ }
37434
+ return new VerifiedAcpReadiness(
37435
+ normalizeVersionOutput(initialized.agentInfo?.version ?? ""),
37436
+ normalizeAcpCapabilities(initialized)
37437
+ );
37438
+ })(),
37439
+ inProcess.terminated.then((termination) => {
37440
+ throw new AgentProbeError("acp_incompatible", "The ACP endpoint stopped during initialization", {
37441
+ cause: acpEndpointTerminationError(termination)
37442
+ });
37443
+ })
37444
+ ]);
37445
+ } finally {
37446
+ connection.close();
37284
37447
  }
37285
- return new VerifiedAcpReadiness(
37286
- normalizeVersionOutput(initialized.agentInfo?.version ?? ""),
37287
- normalizeAcpCapabilities(initialized)
37288
- );
37289
37448
  } finally {
37290
37449
  await inProcess.close();
37291
37450
  }
@@ -42933,6 +43092,70 @@ async function executeSessionPrepare(publisher, socket, command, config2, direct
42933
43092
  reportOperationFailure(socket, command.requestId, command.sessionId, error62, metrics.snapshot());
42934
43093
  }
42935
43094
  }
43095
+ function liveHistoryCursor(sessionId, endIndex) {
43096
+ return Buffer.from(JSON.stringify({ endIndex, sessionId }), "utf8").toString("base64url");
43097
+ }
43098
+ function liveHistoryEndIndex(cursor, sessionId) {
43099
+ try {
43100
+ if (!/^[A-Za-z0-9_-]{1,512}$/u.test(cursor)) {
43101
+ throw new Error("Invalid cursor alphabet");
43102
+ }
43103
+ const value = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"));
43104
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
43105
+ throw new Error("Invalid cursor shape");
43106
+ }
43107
+ const record2 = Object.fromEntries(Object.entries(value));
43108
+ if (Object.keys(record2).sort().join(",") !== "endIndex,sessionId" || record2["sessionId"] !== sessionId || typeof record2["endIndex"] !== "number" || !Number.isSafeInteger(record2["endIndex"]) || record2["endIndex"] < 0) {
43109
+ throw new Error("Invalid cursor target");
43110
+ }
43111
+ return record2["endIndex"];
43112
+ } catch (cause) {
43113
+ throw new AcpExecutionError("The native Session history cursor is invalid", { cause }, "invalid_cursor");
43114
+ }
43115
+ }
43116
+ function liveHistoryCoveredTurnRanges(history) {
43117
+ const ranges = [];
43118
+ let historyIndex = history.messages.length;
43119
+ for (const commandId of history.coveredCommandIds) {
43120
+ let assistantStartIndex = historyIndex;
43121
+ while (assistantStartIndex > 0 && history.messages[assistantStartIndex - 1]?.role === "assistant") {
43122
+ assistantStartIndex -= 1;
43123
+ }
43124
+ const userIndex = assistantStartIndex - 1;
43125
+ if (assistantStartIndex === historyIndex || history.messages[userIndex]?.role !== "user") {
43126
+ break;
43127
+ }
43128
+ ranges.push({ assistantEndIndex: historyIndex, assistantStartIndex, commandId, userIndex });
43129
+ historyIndex = userIndex;
43130
+ }
43131
+ return ranges;
43132
+ }
43133
+ function paginateLiveSessionHistory(history, sessionId, cursor, limit) {
43134
+ if (history.status === "unavailable") {
43135
+ if (cursor !== null) {
43136
+ throw new AcpExecutionError("Unavailable native Session history has no cursor", {}, "invalid_cursor");
43137
+ }
43138
+ return { cause: history.cause, nextCursor: null, status: "unavailable" };
43139
+ }
43140
+ const endIndex = cursor === null ? history.messages.length : liveHistoryEndIndex(cursor, sessionId);
43141
+ if (endIndex > history.messages.length) {
43142
+ throw new AcpExecutionError("The native Session history cursor is invalid", {}, "invalid_cursor");
43143
+ }
43144
+ const startIndex = Math.max(0, endIndex - limit);
43145
+ const coveredMessageIds = new Set(history.coveredMessageIds);
43146
+ const ranges = liveHistoryCoveredTurnRanges(history);
43147
+ return {
43148
+ coveredCommandIds: ranges.filter((range) => range.userIndex >= startIndex && range.assistantEndIndex <= endIndex).map((range) => range.commandId),
43149
+ coveredMessageIds: ranges.flatMap((range) => [
43150
+ ...range.userIndex >= startIndex && range.userIndex < endIndex && coveredMessageIds.has(`${range.commandId}:user`) ? [`${range.commandId}:user`] : [],
43151
+ ...range.assistantStartIndex >= startIndex && range.assistantEndIndex <= endIndex && coveredMessageIds.has(`${range.commandId}:agent`) ? [`${range.commandId}:agent`] : []
43152
+ ]),
43153
+ messages: history.messages.slice(startIndex, endIndex),
43154
+ nextCursor: startIndex > 0 ? liveHistoryCursor(sessionId, startIndex) : null,
43155
+ status: "available",
43156
+ truncated: history.truncated
43157
+ };
43158
+ }
42936
43159
  async function executeSessionLiveHistoryLoad(socket, command, config2, directories, audit, sessions, signal) {
42937
43160
  try {
42938
43161
  const resolved = await resolveSessionDirectories(
@@ -42982,6 +43205,57 @@ async function executeSessionLiveHistoryLoad(socket, command, config2, directori
42982
43205
  });
42983
43206
  }
42984
43207
  }
43208
+ async function executeSessionLiveHistoryPageLoad(socket, command, config2, directories, audit, sessions, signal) {
43209
+ try {
43210
+ const resolved = await resolveSessionDirectories(
43211
+ directories,
43212
+ config2.bindingId,
43213
+ command.directoryId,
43214
+ command.additionalDirectoryIds,
43215
+ signal
43216
+ );
43217
+ const history = await sessions.loadSessionHistory({
43218
+ additionalDirectories: resolved.additionalDirectories,
43219
+ agent: config2.catalog.find(command.agentId),
43220
+ cwd: resolved.cwd,
43221
+ sessionId: command.sessionId,
43222
+ signal
43223
+ });
43224
+ signal.throwIfAborted();
43225
+ const page = paginateLiveSessionHistory(history, command.sessionId, command.cursor, command.limit);
43226
+ audit.record({
43227
+ commandId: command.requestId,
43228
+ event: "session_history_loaded",
43229
+ sessionId: command.sessionId
43230
+ });
43231
+ send(socket, {
43232
+ kind: "session.live-history.page.loaded",
43233
+ page,
43234
+ requestId: command.requestId,
43235
+ sessionId: command.sessionId
43236
+ });
43237
+ } catch (error62) {
43238
+ if (signal.aborted) {
43239
+ return;
43240
+ }
43241
+ audit.record({
43242
+ commandId: command.requestId,
43243
+ details: { code: operationErrorCode(error62) },
43244
+ event: "session_history_unavailable",
43245
+ sessionId: command.sessionId
43246
+ });
43247
+ send(socket, {
43248
+ kind: "session.live-history.page.loaded",
43249
+ page: {
43250
+ status: "unavailable",
43251
+ cause: { code: operationErrorCode(error62), message: operationErrorMessage(error62) },
43252
+ nextCursor: null
43253
+ },
43254
+ requestId: command.requestId,
43255
+ sessionId: command.sessionId
43256
+ });
43257
+ }
43258
+ }
42985
43259
  async function executeSessionConfigure(publisher, socket, command, config2, directories, audit, sessions, signal) {
42986
43260
  try {
42987
43261
  const resolved = await resolveSessionDirectories(
@@ -43841,6 +44115,19 @@ async function runRelayConnection(config2, directories, audit, sessions, install
43841
44115
  );
43842
44116
  return;
43843
44117
  }
44118
+ if (kind === SESSION_LIVE_HISTORY_PAGE_LOAD_KIND) {
44119
+ const command2 = decodeSessionLiveHistoryPageLoad(encoded);
44120
+ void executeSessionLiveHistoryPageLoad(
44121
+ socket,
44122
+ command2,
44123
+ config2,
44124
+ directories,
44125
+ audit,
44126
+ sessions,
44127
+ connectionController.signal
44128
+ );
44129
+ return;
44130
+ }
43844
44131
  if (kind === NATIVE_SESSION_CANCEL_KIND) {
43845
44132
  const command2 = message;
43846
44133
  const pending = nativeRequests.get(command2.requestId);