@moxt-ai/mobius 0.0.93 → 0.0.94

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.
Files changed (54) hide show
  1. package/dist/acp/activity.js +1 -1
  2. package/dist/acp/activity.js.map +1 -1
  3. package/dist/acp/codex/agent.d.ts.map +1 -1
  4. package/dist/acp/codex/agent.js +4 -8
  5. package/dist/acp/codex/agent.js.map +1 -1
  6. package/dist/acp/session-manager.d.ts +5 -3
  7. package/dist/acp/session-manager.d.ts.map +1 -1
  8. package/dist/acp/session-manager.js +77 -5
  9. package/dist/acp/session-manager.js.map +1 -1
  10. package/dist/acp/session-store.d.ts +3 -10
  11. package/dist/acp/session-store.d.ts.map +1 -1
  12. package/dist/acp/session-store.js +1 -131
  13. package/dist/acp/session-store.js.map +1 -1
  14. package/dist/audit/audit-store.d.ts +3 -4
  15. package/dist/audit/audit-store.d.ts.map +1 -1
  16. package/dist/audit/audit-store.js +10 -37
  17. package/dist/audit/audit-store.js.map +1 -1
  18. package/dist/cli.js +333 -326
  19. package/dist/cli.js.map +3 -3
  20. package/dist/config.d.ts +0 -2
  21. package/dist/config.d.ts.map +1 -1
  22. package/dist/config.js +0 -4
  23. package/dist/config.js.map +1 -1
  24. package/dist/daemon-manager.d.ts.map +1 -1
  25. package/dist/daemon-manager.js +13 -19
  26. package/dist/daemon-manager.js.map +1 -1
  27. package/dist/index.js +270 -264
  28. package/dist/index.js.map +3 -3
  29. package/dist/native-sessions/service.d.ts.map +1 -1
  30. package/dist/native-sessions/service.js +75 -4
  31. package/dist/native-sessions/service.js.map +1 -1
  32. package/dist/pairing/pair-local-machine.d.ts.map +1 -1
  33. package/dist/pairing/pair-local-machine.js +0 -1
  34. package/dist/pairing/pair-local-machine.js.map +1 -1
  35. package/dist/relay-connection/coalescing-narration-publisher.d.ts +1 -1
  36. package/dist/relay-connection/coalescing-narration-publisher.js +1 -1
  37. package/dist/relay-connection/coalescing-text-publisher.d.ts +1 -1
  38. package/dist/relay-connection/coalescing-text-publisher.js +1 -1
  39. package/dist/relay-connection/session-event-outbox.d.ts +4 -5
  40. package/dist/relay-connection/session-event-outbox.d.ts.map +1 -1
  41. package/dist/relay-connection/session-event-outbox.js +31 -21
  42. package/dist/relay-connection/session-event-outbox.js.map +1 -1
  43. package/dist/run-daemon.d.ts.map +1 -1
  44. package/dist/run-daemon.js +13 -19
  45. package/dist/run-daemon.js.map +1 -1
  46. package/dist/runtime.d.ts +0 -1
  47. package/dist/runtime.d.ts.map +1 -1
  48. package/dist/runtime.js +264 -256
  49. package/dist/runtime.js.map +3 -3
  50. package/dist/storage/runtime-installation-store.d.ts +0 -1
  51. package/dist/storage/runtime-installation-store.d.ts.map +1 -1
  52. package/dist/storage/runtime-installation-store.js +0 -1
  53. package/dist/storage/runtime-installation-store.js.map +1 -1
  54. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -7,7 +7,7 @@ var __export = (target, all2) => {
7
7
 
8
8
  // src/cli.ts
9
9
  import { constants as constants2 } from "node:fs";
10
- import { mkdir as mkdir6, open as open7 } from "node:fs/promises";
10
+ import { mkdir as mkdir6, open as open6 } from "node:fs/promises";
11
11
  import { resolve as resolve7 } from "node:path";
12
12
 
13
13
  // ../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/error.js
@@ -3381,7 +3381,7 @@ var program = new Command();
3381
3381
  // package.json
3382
3382
  var package_default = {
3383
3383
  name: "@moxt-ai/mobius",
3384
- version: "0.0.93",
3384
+ version: "0.0.94",
3385
3385
  description: "Mobius CLI for pairing and running local AI agent services.",
3386
3386
  type: "module",
3387
3387
  bin: {
@@ -25186,18 +25186,17 @@ function effortValues(model) {
25186
25186
  }
25187
25187
  function modelSetting(models, currentValue) {
25188
25188
  const values = modelValues(models);
25189
- const current = currentValue.length > 0 ? currentValue : models.find((model) => model.isDefault === true)?.id ?? values[0]?.value ?? "";
25189
+ const current = values.some((value) => value.value === currentValue) ? currentValue : models.find((model) => model.isDefault === true)?.id ?? values[0]?.value ?? "";
25190
25190
  if (current.length === 0) {
25191
25191
  return null;
25192
25192
  }
25193
- const options = values.some((value) => value.value === current) ? values : [{ description: "", name: current, value: current }, ...values];
25194
25193
  return {
25195
25194
  category: "model",
25196
25195
  currentValue: current,
25197
25196
  description: "Model Codex uses for the session",
25198
25197
  id: MODEL_SETTING_ID,
25199
25198
  name: "Model",
25200
- options,
25199
+ options: values,
25201
25200
  type: "select"
25202
25201
  };
25203
25202
  }
@@ -27154,41 +27153,41 @@ var DiscoveryAcpHandler = class {
27154
27153
  };
27155
27154
  function readableAcpStream(input2) {
27156
27155
  let byteLength = 0;
27157
- let open8 = true;
27156
+ let open7 = true;
27158
27157
  return new ReadableStream({
27159
27158
  start(controller) {
27160
27159
  input2.on("data", (chunk) => {
27161
- if (!open8) {
27160
+ if (!open7) {
27162
27161
  return;
27163
27162
  }
27164
27163
  if (!(chunk instanceof Uint8Array)) {
27165
- open8 = false;
27164
+ open7 = false;
27166
27165
  controller.error(new Error("ACP adapter produced invalid output"));
27167
27166
  return;
27168
27167
  }
27169
27168
  byteLength += chunk.byteLength;
27170
27169
  if (byteLength > ACP_OUTPUT_LIMIT_BYTES) {
27171
- open8 = false;
27170
+ open7 = false;
27172
27171
  controller.error(new Error("ACP adapter output limit exceeded"));
27173
27172
  return;
27174
27173
  }
27175
27174
  controller.enqueue(new Uint8Array(chunk));
27176
27175
  });
27177
27176
  input2.once("end", () => {
27178
- if (open8) {
27179
- open8 = false;
27177
+ if (open7) {
27178
+ open7 = false;
27180
27179
  controller.close();
27181
27180
  }
27182
27181
  });
27183
27182
  input2.once("error", (error62) => {
27184
- if (open8) {
27185
- open8 = false;
27183
+ if (open7) {
27184
+ open7 = false;
27186
27185
  controller.error(error62);
27187
27186
  }
27188
27187
  });
27189
27188
  },
27190
27189
  cancel() {
27191
- open8 = false;
27190
+ open7 = false;
27192
27191
  }
27193
27192
  });
27194
27193
  }
@@ -29127,6 +29126,8 @@ var nativeSessionTurnForkCommandSchema = external_exports.strictObject({
29127
29126
  title: external_exports.string().max(500)
29128
29127
  }).readonly();
29129
29128
  var nativeSessionRequestSchema = external_exports.discriminatedUnion("action", [
29129
+ external_exports.strictObject({ ...identity, action: external_exports.literal("create") }).readonly(),
29130
+ external_exports.strictObject({ ...identity, action: external_exports.literal("linked-history"), targetSessionId: identifier }).readonly(),
29130
29131
  external_exports.strictObject({ ...identity, action: external_exports.literal("preview"), entryId: identifier }).readonly(),
29131
29132
  external_exports.strictObject({ ...identity, action: external_exports.literal("history"), entryId: identifier }).readonly(),
29132
29133
  external_exports.strictObject({ ...identity, action: external_exports.literal("find"), nativeSessionId: identifier }).readonly(),
@@ -29148,6 +29149,8 @@ var nativeSessionRequestSchema = external_exports.discriminatedUnion("action", [
29148
29149
  }).readonly()
29149
29150
  ]);
29150
29151
  var nativeSessionCommandSchema = external_exports.discriminatedUnion("action", [
29152
+ external_exports.strictObject({ ...identity, action: external_exports.literal("create") }).readonly(),
29153
+ external_exports.strictObject({ ...identity, action: external_exports.literal("linked-history"), targetSessionId: identifier }).readonly(),
29151
29154
  external_exports.strictObject({ ...identity, action: external_exports.literal("preview"), entryId: identifier }).readonly(),
29152
29155
  external_exports.strictObject({ ...identity, action: external_exports.literal("history"), entryId: identifier }).readonly(),
29153
29156
  external_exports.strictObject({ ...identity, action: external_exports.literal("find"), nativeSessionId: identifier }).readonly(),
@@ -29176,7 +29179,7 @@ var nativeSessionCommandSchema = external_exports.discriminatedUnion("action", [
29176
29179
  ]);
29177
29180
  var nativeSessionEntrySchema = external_exports.strictObject({
29178
29181
  entryId: identifier,
29179
- mobiusSessionIds: external_exports.array(identifier).max(500).readonly(),
29182
+ nativeSessionId: identifier,
29180
29183
  title: external_exports.string().max(500),
29181
29184
  directoryId,
29182
29185
  directoryLabel: external_exports.string().min(1).max(2048),
@@ -29188,6 +29191,18 @@ var resultEnvelope = {
29188
29191
  kind: external_exports.literal(NATIVE_SESSION_RESULT_KIND)
29189
29192
  };
29190
29193
  var nativeSessionResultSchema = external_exports.discriminatedUnion("action", [
29194
+ external_exports.strictObject({ ...resultEnvelope, action: external_exports.literal("create"), nativeSessionId: identifier }).readonly(),
29195
+ external_exports.strictObject({
29196
+ ...resultEnvelope,
29197
+ action: external_exports.literal("linked-history"),
29198
+ targetSessionId: identifier,
29199
+ history: sessionHistorySchema
29200
+ }).readonly(),
29201
+ external_exports.strictObject({
29202
+ ...resultEnvelope,
29203
+ action: external_exports.literal("unlinked-history"),
29204
+ targetSessionId: identifier
29205
+ }).readonly(),
29191
29206
  external_exports.strictObject({
29192
29207
  ...resultEnvelope,
29193
29208
  action: external_exports.literal("find"),
@@ -29735,7 +29750,6 @@ function createDaemonConfig(connection, agents = [], installableAgents = [], loc
29735
29750
  return {
29736
29751
  agents: daemonAgents,
29737
29752
  defaultWorkspace: connection.defaultWorkspace,
29738
- auditDatabasePath: connection.auditDatabasePath,
29739
29753
  bindingId: "workspace",
29740
29754
  catalog: new LocalAgentCatalog(daemonAgents, installableAgents),
29741
29755
  channelId: connection.channelId,
@@ -29748,8 +29762,8 @@ function createDaemonConfig(connection, agents = [], installableAgents = [], loc
29748
29762
 
29749
29763
  // src/daemon-manager.ts
29750
29764
  import { spawn as spawn6 } from "node:child_process";
29751
- import { createHash as createHash5, randomBytes } from "node:crypto";
29752
- import { open as open6, readFile as readFile3, unlink as unlink2, writeFile as writeFile4 } from "node:fs/promises";
29765
+ import { createHash as createHash6, randomBytes } from "node:crypto";
29766
+ import { readFile as readFile3, unlink as unlink2, writeFile as writeFile4 } from "node:fs/promises";
29753
29767
  import { createConnection, createServer } from "node:net";
29754
29768
  import { tmpdir } from "node:os";
29755
29769
  import { join as join18 } from "node:path";
@@ -30167,7 +30181,6 @@ var RuntimeInstallationStore = class _RuntimeInstallationStore {
30167
30181
  return new _RuntimeInstallationStore(applicationId, storedInstallationId, stateDirectory);
30168
30182
  };
30169
30183
  connectionPath = (connectionId2) => join15(this.#connectionDirectory, `${validateConnectionId(connectionId2)}.json`);
30170
- auditDatabasePath = (connectionId2) => join15(this.stateDirectory, "audit", `${validateConnectionId(connectionId2)}.sqlite`);
30171
30184
  channelIndexPath = (channelId) => join15(this.#channelDirectory, channelIndexFileName(validateIdentifier(channelId, "invalid_channel_id")));
30172
30185
  readConnection = async (connectionId2, signal) => {
30173
30186
  const stored = decodeConnection(
@@ -30606,7 +30619,6 @@ function buildPairedDaemon(installation, connection, defaultWorkspace, inventory
30606
30619
  config: createDaemonConfig(
30607
30620
  {
30608
30621
  defaultWorkspace,
30609
- auditDatabasePath: installation.auditDatabasePath(connection.connectionId),
30610
30622
  channelId: connection.channelId,
30611
30623
  relayUrl
30612
30624
  },
@@ -30695,55 +30707,24 @@ async function resumeLocalMachine(arguments_, signal = new AbortController().sig
30695
30707
  }
30696
30708
 
30697
30709
  // src/audit/audit-store.ts
30698
- import { mkdirSync } from "node:fs";
30699
- import { dirname as dirname4 } from "node:path";
30700
- import { DatabaseSync } from "node:sqlite";
30710
+ var MAX_AUDIT_RECORDS = 1024;
30701
30711
  var AuditStore = class {
30702
- database;
30703
- constructor(path3) {
30704
- mkdirSync(dirname4(path3), { recursive: true });
30705
- this.database = new DatabaseSync(path3);
30706
- this.database.exec(`
30707
- CREATE TABLE IF NOT EXISTS audit_events (
30708
- id INTEGER PRIMARY KEY AUTOINCREMENT,
30709
- recorded_at TEXT NOT NULL,
30710
- event TEXT NOT NULL,
30711
- command_id TEXT NOT NULL,
30712
- session_id TEXT NOT NULL,
30713
- details_json TEXT NOT NULL DEFAULT '{}'
30714
- ) STRICT
30715
- `);
30716
- const columns = this.database.prepare("PRAGMA table_info(audit_events)").all();
30717
- if (!columns.some((column) => Reflect.get(column, "name") === "details_json")) {
30718
- this.database.exec("ALTER TABLE audit_events ADD COLUMN details_json TEXT NOT NULL DEFAULT '{}'");
30719
- }
30720
- }
30721
- record(record2) {
30722
- this.database.prepare(
30723
- `
30724
- INSERT INTO audit_events (
30725
- recorded_at,
30726
- event,
30727
- command_id,
30728
- session_id,
30729
- details_json
30730
- ) VALUES (?, ?, ?, ?, ?)
30731
- `
30732
- ).run(
30733
- (/* @__PURE__ */ new Date()).toISOString(),
30734
- record2.event,
30735
- record2.commandId,
30736
- record2.sessionId,
30737
- JSON.stringify(record2.details ?? {})
30712
+ #records = [];
30713
+ record = (record2) => {
30714
+ if (this.#records.length === MAX_AUDIT_RECORDS) {
30715
+ this.#records.shift();
30716
+ }
30717
+ this.#records.push(
30718
+ record2.details === void 0 ? { ...record2 } : { ...record2, details: { ...record2.details } }
30738
30719
  );
30739
- }
30740
- close() {
30741
- this.database.close();
30742
- }
30720
+ };
30721
+ close = () => {
30722
+ this.#records.length = 0;
30723
+ };
30743
30724
  };
30744
30725
 
30745
30726
  // src/run-daemon.ts
30746
- import { createHash as createHash4, randomUUID as randomUUID4 } from "node:crypto";
30727
+ import { createHash as createHash5, randomUUID as randomUUID4 } from "node:crypto";
30747
30728
  import { basename as basename7 } from "node:path";
30748
30729
  import { styleText } from "node:util";
30749
30730
  import { fetch as fetch5, WebSocket as WebSocket2 } from "undici";
@@ -34227,7 +34208,7 @@ var attention = {
34227
34208
  };
34228
34209
  function resolveAllAttention(events, context) {
34229
34210
  let index2 = -1;
34230
- let open8;
34211
+ let open7;
34231
34212
  let group;
34232
34213
  let text3;
34233
34214
  let openingSequence;
@@ -34237,16 +34218,16 @@ function resolveAllAttention(events, context) {
34237
34218
  let offset;
34238
34219
  while (++index2 < events.length) {
34239
34220
  if (events[index2][0] === "enter" && events[index2][1].type === "attentionSequence" && events[index2][1]._close) {
34240
- open8 = index2;
34241
- while (open8--) {
34242
- if (events[open8][0] === "exit" && events[open8][1].type === "attentionSequence" && events[open8][1]._open && // If the markers are the same:
34243
- context.sliceSerialize(events[open8][1]).charCodeAt(0) === context.sliceSerialize(events[index2][1]).charCodeAt(0)) {
34244
- if ((events[open8][1]._close || events[index2][1]._open) && (events[index2][1].end.offset - events[index2][1].start.offset) % 3 && !((events[open8][1].end.offset - events[open8][1].start.offset + events[index2][1].end.offset - events[index2][1].start.offset) % 3)) {
34221
+ open7 = index2;
34222
+ while (open7--) {
34223
+ if (events[open7][0] === "exit" && events[open7][1].type === "attentionSequence" && events[open7][1]._open && // If the markers are the same:
34224
+ context.sliceSerialize(events[open7][1]).charCodeAt(0) === context.sliceSerialize(events[index2][1]).charCodeAt(0)) {
34225
+ if ((events[open7][1]._close || events[index2][1]._open) && (events[index2][1].end.offset - events[index2][1].start.offset) % 3 && !((events[open7][1].end.offset - events[open7][1].start.offset + events[index2][1].end.offset - events[index2][1].start.offset) % 3)) {
34245
34226
  continue;
34246
34227
  }
34247
- use = events[open8][1].end.offset - events[open8][1].start.offset > 1 && events[index2][1].end.offset - events[index2][1].start.offset > 1 ? 2 : 1;
34228
+ use = events[open7][1].end.offset - events[open7][1].start.offset > 1 && events[index2][1].end.offset - events[index2][1].start.offset > 1 ? 2 : 1;
34248
34229
  const start = {
34249
- ...events[open8][1].end
34230
+ ...events[open7][1].end
34250
34231
  };
34251
34232
  const end = {
34252
34233
  ...events[index2][1].start
@@ -34257,7 +34238,7 @@ function resolveAllAttention(events, context) {
34257
34238
  type: use > 1 ? "strongSequence" : "emphasisSequence",
34258
34239
  start,
34259
34240
  end: {
34260
- ...events[open8][1].end
34241
+ ...events[open7][1].end
34261
34242
  }
34262
34243
  };
34263
34244
  closingSequence = {
@@ -34270,7 +34251,7 @@ function resolveAllAttention(events, context) {
34270
34251
  text3 = {
34271
34252
  type: use > 1 ? "strongText" : "emphasisText",
34272
34253
  start: {
34273
- ...events[open8][1].end
34254
+ ...events[open7][1].end
34274
34255
  },
34275
34256
  end: {
34276
34257
  ...events[index2][1].start
@@ -34285,18 +34266,18 @@ function resolveAllAttention(events, context) {
34285
34266
  ...closingSequence.end
34286
34267
  }
34287
34268
  };
34288
- events[open8][1].end = {
34269
+ events[open7][1].end = {
34289
34270
  ...openingSequence.start
34290
34271
  };
34291
34272
  events[index2][1].start = {
34292
34273
  ...closingSequence.end
34293
34274
  };
34294
34275
  nextEvents = [];
34295
- if (events[open8][1].end.offset - events[open8][1].start.offset) {
34296
- nextEvents = push(nextEvents, [["enter", events[open8][1], context], ["exit", events[open8][1], context]]);
34276
+ if (events[open7][1].end.offset - events[open7][1].start.offset) {
34277
+ nextEvents = push(nextEvents, [["enter", events[open7][1], context], ["exit", events[open7][1], context]]);
34297
34278
  }
34298
34279
  nextEvents = push(nextEvents, [["enter", group, context], ["enter", openingSequence, context], ["exit", openingSequence, context], ["enter", text3, context]]);
34299
- nextEvents = push(nextEvents, resolveAll(context.parser.constructs.insideSpan.null, events.slice(open8 + 1, index2), context));
34280
+ nextEvents = push(nextEvents, resolveAll(context.parser.constructs.insideSpan.null, events.slice(open7 + 1, index2), context));
34300
34281
  nextEvents = push(nextEvents, [["exit", text3, context], ["enter", closingSequence, context], ["exit", closingSequence, context], ["exit", group, context]]);
34301
34282
  if (events[index2][1].end.offset - events[index2][1].start.offset) {
34302
34283
  offset = 2;
@@ -34304,8 +34285,8 @@ function resolveAllAttention(events, context) {
34304
34285
  } else {
34305
34286
  offset = 0;
34306
34287
  }
34307
- splice(events, open8 - 1, index2 - open8 + 3, nextEvents);
34308
- index2 = open8 + nextEvents.length - offset - 2;
34288
+ splice(events, open7 - 1, index2 - open7 + 3, nextEvents);
34289
+ index2 = open7 + nextEvents.length - offset - 2;
34309
34290
  break;
34310
34291
  }
34311
34292
  }
@@ -34337,10 +34318,10 @@ function tokenizeAttention(effects, ok2) {
34337
34318
  }
34338
34319
  const token = effects.exit("attentionSequence");
34339
34320
  const after = classifyCharacter(code);
34340
- const open8 = !after || after === 2 && before || attentionMarkers2.includes(code);
34321
+ const open7 = !after || after === 2 && before || attentionMarkers2.includes(code);
34341
34322
  const close = !before || before === 2 && after || attentionMarkers2.includes(previous2);
34342
- token._open = Boolean(marker === 42 ? open8 : open8 && (before || !close));
34343
- token._close = Boolean(marker === 42 ? close : close && (after || !open8));
34323
+ token._open = Boolean(marker === 42 ? open7 : open7 && (before || !close));
34324
+ token._close = Boolean(marker === 42 ? close : close && (after || !open7));
34344
34325
  return ok2(code);
34345
34326
  }
34346
34327
  }
@@ -34364,9 +34345,9 @@ function tokenizeAutolink(effects, ok2, nok) {
34364
34345
  effects.consume(code);
34365
34346
  effects.exit("autolinkMarker");
34366
34347
  effects.enter("autolinkProtocol");
34367
- return open8;
34348
+ return open7;
34368
34349
  }
34369
- function open8(code) {
34350
+ function open7(code) {
34370
34351
  if (asciiAlpha(code)) {
34371
34352
  effects.consume(code);
34372
34353
  return schemeOrEmailAtext;
@@ -34566,9 +34547,9 @@ function tokenizeCharacterReference(effects, ok2, nok) {
34566
34547
  effects.enter("characterReferenceMarker");
34567
34548
  effects.consume(code);
34568
34549
  effects.exit("characterReferenceMarker");
34569
- return open8;
34550
+ return open7;
34570
34551
  }
34571
- function open8(code) {
34552
+ function open7(code) {
34572
34553
  if (code === 35) {
34573
34554
  effects.enter("characterReferenceMarkerNumeric");
34574
34555
  effects.consume(code);
@@ -35937,9 +35918,9 @@ function tokenizeHtmlFlow(effects, ok2, nok) {
35937
35918
  effects.enter("htmlFlow");
35938
35919
  effects.enter("htmlFlowData");
35939
35920
  effects.consume(code);
35940
- return open8;
35921
+ return open7;
35941
35922
  }
35942
- function open8(code) {
35923
+ function open7(code) {
35943
35924
  if (code === 33) {
35944
35925
  effects.consume(code);
35945
35926
  return declarationOpen;
@@ -36287,9 +36268,9 @@ function tokenizeHtmlText(effects, ok2, nok) {
36287
36268
  effects.enter("htmlText");
36288
36269
  effects.enter("htmlTextData");
36289
36270
  effects.consume(code);
36290
- return open8;
36271
+ return open7;
36291
36272
  }
36292
- function open8(code) {
36273
+ function open7(code) {
36293
36274
  if (code === 33) {
36294
36275
  effects.consume(code);
36295
36276
  return declarationOpen;
@@ -36615,12 +36596,12 @@ function resolveToLabelEnd(events, context) {
36615
36596
  let index2 = events.length;
36616
36597
  let offset = 0;
36617
36598
  let token;
36618
- let open8;
36599
+ let open7;
36619
36600
  let close;
36620
36601
  let media;
36621
36602
  while (index2--) {
36622
36603
  token = events[index2][1];
36623
- if (open8) {
36604
+ if (open7) {
36624
36605
  if (token.type === "link" || token.type === "labelLink" && token._inactive) {
36625
36606
  break;
36626
36607
  }
@@ -36629,7 +36610,7 @@ function resolveToLabelEnd(events, context) {
36629
36610
  }
36630
36611
  } else if (close) {
36631
36612
  if (events[index2][0] === "enter" && (token.type === "labelImage" || token.type === "labelLink") && !token._balanced) {
36632
- open8 = index2;
36613
+ open7 = index2;
36633
36614
  if (token.type !== "labelLink") {
36634
36615
  offset = 2;
36635
36616
  break;
@@ -36640,9 +36621,9 @@ function resolveToLabelEnd(events, context) {
36640
36621
  }
36641
36622
  }
36642
36623
  const group = {
36643
- type: events[open8][1].type === "labelLink" ? "link" : "image",
36624
+ type: events[open7][1].type === "labelLink" ? "link" : "image",
36644
36625
  start: {
36645
- ...events[open8][1].start
36626
+ ...events[open7][1].start
36646
36627
  },
36647
36628
  end: {
36648
36629
  ...events[events.length - 1][1].end
@@ -36651,7 +36632,7 @@ function resolveToLabelEnd(events, context) {
36651
36632
  const label = {
36652
36633
  type: "label",
36653
36634
  start: {
36654
- ...events[open8][1].start
36635
+ ...events[open7][1].start
36655
36636
  },
36656
36637
  end: {
36657
36638
  ...events[close][1].end
@@ -36660,20 +36641,20 @@ function resolveToLabelEnd(events, context) {
36660
36641
  const text3 = {
36661
36642
  type: "labelText",
36662
36643
  start: {
36663
- ...events[open8 + offset + 2][1].end
36644
+ ...events[open7 + offset + 2][1].end
36664
36645
  },
36665
36646
  end: {
36666
36647
  ...events[close - 2][1].start
36667
36648
  }
36668
36649
  };
36669
36650
  media = [["enter", group, context], ["enter", label, context]];
36670
- media = push(media, events.slice(open8 + 1, open8 + offset + 3));
36651
+ media = push(media, events.slice(open7 + 1, open7 + offset + 3));
36671
36652
  media = push(media, [["enter", text3, context]]);
36672
- media = push(media, resolveAll(context.parser.constructs.insideSpan.null, events.slice(open8 + offset + 4, close - 3), context));
36653
+ media = push(media, resolveAll(context.parser.constructs.insideSpan.null, events.slice(open7 + offset + 4, close - 3), context));
36673
36654
  media = push(media, [["exit", text3, context], events[close - 2], events[close - 1], ["exit", label, context]]);
36674
36655
  media = push(media, events.slice(close + 1));
36675
36656
  media = push(media, [["exit", group, context]]);
36676
- splice(events, open8, events.length, media);
36657
+ splice(events, open7, events.length, media);
36677
36658
  return events;
36678
36659
  }
36679
36660
  function tokenizeLabelEnd(effects, ok2, nok) {
@@ -36818,9 +36799,9 @@ function tokenizeLabelStartImage(effects, ok2, nok) {
36818
36799
  effects.enter("labelImageMarker");
36819
36800
  effects.consume(code);
36820
36801
  effects.exit("labelImageMarker");
36821
- return open8;
36802
+ return open7;
36822
36803
  }
36823
- function open8(code) {
36804
+ function open7(code) {
36824
36805
  if (code === 91) {
36825
36806
  effects.enter("labelMarker");
36826
36807
  effects.consume(code);
@@ -38124,8 +38105,8 @@ function compiler(options) {
38124
38105
  return length;
38125
38106
  }
38126
38107
  function opener(create, and) {
38127
- return open8;
38128
- function open8(token) {
38108
+ return open7;
38109
+ function open7(token) {
38129
38110
  enter.call(this, create(token), token);
38130
38111
  if (and) and.call(this, token);
38131
38112
  }
@@ -38157,18 +38138,18 @@ function compiler(options) {
38157
38138
  }
38158
38139
  function exit2(token, onExitError) {
38159
38140
  const node3 = this.stack.pop();
38160
- const open8 = this.tokenStack.pop();
38161
- if (!open8) {
38141
+ const open7 = this.tokenStack.pop();
38142
+ if (!open7) {
38162
38143
  throw new Error("Cannot close `" + token.type + "` (" + stringifyPosition({
38163
38144
  start: token.start,
38164
38145
  end: token.end
38165
38146
  }) + "): it\u2019s not open");
38166
- } else if (open8[0].type !== token.type) {
38147
+ } else if (open7[0].type !== token.type) {
38167
38148
  if (onExitError) {
38168
- onExitError.call(this, token, open8[0]);
38149
+ onExitError.call(this, token, open7[0]);
38169
38150
  } else {
38170
- const handler = open8[1] || defaultOnError;
38171
- handler.call(this, token, open8[0]);
38151
+ const handler = open7[1] || defaultOnError;
38152
+ handler.call(this, token, open7[0]);
38172
38153
  }
38173
38154
  }
38174
38155
  node3.position.end = point2(token.end);
@@ -39251,9 +39232,6 @@ var AcpHistoryReplay = class {
39251
39232
  };
39252
39233
 
39253
39234
  // src/acp/session-store.ts
39254
- import { mkdirSync as mkdirSync2 } from "node:fs";
39255
- import { dirname as dirname5 } from "node:path";
39256
- import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
39257
39235
  var AcpStoredSession = class {
39258
39236
  additionalDirectories;
39259
39237
  agentId;
@@ -39286,44 +39264,6 @@ var FoundAcpStoredSession = class extends AcpStoredSessionLookup {
39286
39264
  var DeletedAcpStoredSession = class extends AcpStoredSessionLookup {
39287
39265
  found = false;
39288
39266
  };
39289
- function readString3(value, field) {
39290
- if (typeof value !== "string" || value.length === 0) {
39291
- throw new Error(`Stored ACP session has an invalid ${field}`);
39292
- }
39293
- return value;
39294
- }
39295
- function readAdditionalDirectories(value) {
39296
- if (typeof value !== "string") {
39297
- throw new Error("Stored ACP session has invalid additional directories");
39298
- }
39299
- const decoded = JSON.parse(value);
39300
- if (!Array.isArray(decoded) || decoded.some((directory) => typeof directory !== "string")) {
39301
- throw new Error("Stored ACP session has invalid additional directories");
39302
- }
39303
- return decoded;
39304
- }
39305
- function readPrompted(value) {
39306
- if (value === 0) {
39307
- return false;
39308
- }
39309
- if (value === 1) {
39310
- return true;
39311
- }
39312
- throw new Error("Stored ACP session has an invalid prompted state");
39313
- }
39314
- function decodeSessionRow(row) {
39315
- if (typeof row !== "object" || row === null || Array.isArray(row)) {
39316
- throw new Error("Stored ACP session is not an object");
39317
- }
39318
- return new AcpStoredSession(
39319
- readString3(Reflect.get(row, "session_id"), "session ID"),
39320
- readString3(Reflect.get(row, "agent_id"), "agent ID"),
39321
- readString3(Reflect.get(row, "native_session_id"), "native session ID"),
39322
- readString3(Reflect.get(row, "cwd"), "working directory"),
39323
- readAdditionalDirectories(Reflect.get(row, "additional_directories_json")),
39324
- readPrompted(Reflect.get(row, "prompted"))
39325
- );
39326
- }
39327
39267
  var MemoryAcpSessionStore = class {
39328
39268
  #sessions = /* @__PURE__ */ new Map();
39329
39269
  #deleted = /* @__PURE__ */ new Set();
@@ -39352,106 +39292,6 @@ var MemoryAcpSessionStore = class {
39352
39292
  this.#sessions.set(session.sessionId, session);
39353
39293
  };
39354
39294
  };
39355
- var SqliteAcpSessionStore = class {
39356
- #database;
39357
- constructor(path3) {
39358
- mkdirSync2(dirname5(path3), { recursive: true });
39359
- this.#database = new DatabaseSync2(path3);
39360
- this.#database.exec(`
39361
- CREATE TABLE IF NOT EXISTS acp_deleted_sessions (session_id TEXT PRIMARY KEY) STRICT;
39362
- CREATE TABLE IF NOT EXISTS acp_sessions (
39363
- session_id TEXT PRIMARY KEY,
39364
- agent_id TEXT NOT NULL,
39365
- native_session_id TEXT NOT NULL,
39366
- cwd TEXT NOT NULL,
39367
- additional_directories_json TEXT NOT NULL,
39368
- prompted INTEGER NOT NULL DEFAULT 0 CHECK (prompted IN (0, 1)),
39369
- updated_at TEXT NOT NULL
39370
- ) STRICT
39371
- `);
39372
- const columns = this.#database.prepare("PRAGMA table_info(acp_sessions)").all();
39373
- const hasPromptedColumn = columns.some(
39374
- (column) => typeof column === "object" && column !== null && Reflect.get(column, "name") === "prompted"
39375
- );
39376
- if (!hasPromptedColumn) {
39377
- this.#database.exec(`
39378
- ALTER TABLE acp_sessions
39379
- ADD COLUMN prompted INTEGER NOT NULL DEFAULT 1 CHECK (prompted IN (0, 1))
39380
- `);
39381
- }
39382
- }
39383
- read = (sessionId) => {
39384
- if (this.#database.prepare("SELECT session_id FROM acp_deleted_sessions WHERE session_id = ?").get(sessionId) !== void 0) {
39385
- return new DeletedAcpStoredSession();
39386
- }
39387
- const row = this.#database.prepare(
39388
- `
39389
- SELECT
39390
- session_id,
39391
- agent_id,
39392
- native_session_id,
39393
- cwd,
39394
- additional_directories_json,
39395
- prompted
39396
- FROM acp_sessions
39397
- WHERE session_id = ?
39398
- `
39399
- ).get(sessionId);
39400
- return row === void 0 ? new MissingAcpStoredSession() : new FoundAcpStoredSession(decodeSessionRow(row));
39401
- };
39402
- remove = (sessionId) => {
39403
- this.#database.prepare("DELETE FROM acp_sessions WHERE session_id = ?").run(sessionId);
39404
- };
39405
- findNative = (agentId, nativeSessionId) => this.#database.prepare("SELECT * FROM acp_sessions WHERE agent_id = ? AND native_session_id = ?").all(agentId, nativeSessionId).map(decodeSessionRow);
39406
- markDeleted = (agentId, nativeSessionId) => {
39407
- const ids = this.findNative(agentId, nativeSessionId).map((session) => session.sessionId);
39408
- this.#database.exec("BEGIN");
39409
- try {
39410
- for (const id of ids) {
39411
- this.#database.prepare("INSERT OR IGNORE INTO acp_deleted_sessions (session_id) VALUES (?)").run(id);
39412
- this.remove(id);
39413
- }
39414
- this.#database.exec("COMMIT");
39415
- return ids;
39416
- } catch (error62) {
39417
- this.#database.exec("ROLLBACK");
39418
- throw error62;
39419
- }
39420
- };
39421
- write = (session) => {
39422
- this.#database.prepare(
39423
- `
39424
- INSERT INTO acp_sessions (
39425
- session_id,
39426
- agent_id,
39427
- native_session_id,
39428
- cwd,
39429
- additional_directories_json,
39430
- prompted,
39431
- updated_at
39432
- ) VALUES (?, ?, ?, ?, ?, ?, ?)
39433
- ON CONFLICT(session_id) DO UPDATE SET
39434
- agent_id = excluded.agent_id,
39435
- native_session_id = excluded.native_session_id,
39436
- cwd = excluded.cwd,
39437
- additional_directories_json = excluded.additional_directories_json,
39438
- prompted = excluded.prompted,
39439
- updated_at = excluded.updated_at
39440
- `
39441
- ).run(
39442
- session.sessionId,
39443
- session.agentId,
39444
- session.nativeSessionId,
39445
- session.cwd,
39446
- JSON.stringify(session.additionalDirectories),
39447
- session.prompted ? 1 : 0,
39448
- (/* @__PURE__ */ new Date()).toISOString()
39449
- );
39450
- };
39451
- close = () => {
39452
- this.#database.close();
39453
- };
39454
- };
39455
39295
 
39456
39296
  // src/acp/session-manager.ts
39457
39297
  var PROCESS_STOP_TIMEOUT_MILLISECONDS = 1e3;
@@ -39678,7 +39518,7 @@ function truncate4(value, maximumLength) {
39678
39518
  function isRecord9(value) {
39679
39519
  return typeof value === "object" && value !== null && !Array.isArray(value);
39680
39520
  }
39681
- function readString4(value, fallback = "") {
39521
+ function readString3(value, fallback = "") {
39682
39522
  return typeof value === "string" ? value : fallback;
39683
39523
  }
39684
39524
  function arraysEqual(left, right) {
@@ -39711,8 +39551,8 @@ function normalizeElicitationOptions(schema) {
39711
39551
  for (const option of oneOf) {
39712
39552
  if (isRecord9(option) && typeof option["const"] === "string") {
39713
39553
  normalized.push({
39714
- description: truncate4(readString4(option["description"]), 500),
39715
- label: truncate4(readString4(option["title"], option["const"]), 255),
39554
+ description: truncate4(readString3(option["description"]), 500),
39555
+ label: truncate4(readString3(option["title"], option["const"]), 255),
39716
39556
  value: truncate4(option["const"], 500)
39717
39557
  });
39718
39558
  }
@@ -39763,8 +39603,8 @@ function normalizeElicitationFields(requestedSchema) {
39763
39603
  defaultBooleanValue: typeof defaultValue === "boolean" ? defaultValue : false,
39764
39604
  defaultNumberValue: typeof defaultValue === "number" && Number.isFinite(defaultValue) ? defaultValue : 0,
39765
39605
  defaultStringValue: typeof defaultValue === "string" ? truncate4(defaultValue, 1e4) : Array.isArray(defaultValue) ? truncate4(JSON.stringify(defaultValue), 1e4) : "",
39766
- description: truncate4(readString4(property["description"]), 500),
39767
- format: truncate4(readString4(property["format"]), 64),
39606
+ description: truncate4(readString3(property["description"]), 500),
39607
+ format: truncate4(readString3(property["format"]), 64),
39768
39608
  hasDefaultValue: defaultValue !== void 0 && defaultValue !== null,
39769
39609
  maximum: numericString(property["maximum"]),
39770
39610
  maximumLength: numericString(property["maxLength"] ?? property["maxItems"]),
@@ -39772,9 +39612,9 @@ function normalizeElicitationFields(requestedSchema) {
39772
39612
  minimumLength: numericString(property["minLength"] ?? property["minItems"]),
39773
39613
  name: truncate4(name, 128),
39774
39614
  options,
39775
- pattern: truncate4(readString4(property["pattern"]), 500),
39615
+ pattern: truncate4(readString3(property["pattern"]), 500),
39776
39616
  required: required2.has(name),
39777
- title: truncate4(readString4(property["title"], name), 255),
39617
+ title: truncate4(readString3(property["title"], name), 255),
39778
39618
  type: normalizedType
39779
39619
  });
39780
39620
  }
@@ -40613,6 +40453,17 @@ var AcpProcessSession = class _AcpProcessSession {
40613
40453
  );
40614
40454
  };
40615
40455
  nativeSessionId = () => this.#nativeSessionId;
40456
+ adoptNativeSessionId = (sessionId) => {
40457
+ if (this.#prompted || this.#nativeSessionId !== sessionId) {
40458
+ throw new AcpExecutionError("The new Codex Session cannot be adopted", {}, "session_identity_mismatch");
40459
+ }
40460
+ const previousSessionId = this.#mobiusSessionId;
40461
+ this.#store.write(
40462
+ new AcpStoredSession(sessionId, this.#agentId, sessionId, this.#cwd, this.#additionalDirectories, false)
40463
+ );
40464
+ this.#store.remove(previousSessionId);
40465
+ this.#mobiusSessionId = sessionId;
40466
+ };
40616
40467
  configure = async (options) => {
40617
40468
  const existing = this.#configOptions.find((option) => option.id === options.configId);
40618
40469
  if (existing === void 0 || existing.type !== options.valueType) {
@@ -41006,7 +40857,7 @@ var AcpProcessSession = class _AcpProcessSession {
41006
40857
  message: truncate4(request.message, 2e3),
41007
40858
  mode: request.mode,
41008
40859
  sessionId: this.#mobiusSessionId,
41009
- url: request.mode === "url" && typeof Reflect.get(request, "url") === "string" ? truncate4(readString4(Reflect.get(request, "url")), 4096) : ""
40860
+ url: request.mode === "url" && typeof Reflect.get(request, "url") === "string" ? truncate4(readString3(Reflect.get(request, "url")), 4096) : ""
41010
40861
  });
41011
40862
  return await pending.completion.promise;
41012
40863
  } finally {
@@ -41366,16 +41217,17 @@ var AcpSessionManager = class {
41366
41217
  #transientProcessCount = 0;
41367
41218
  #store;
41368
41219
  #nativeHistoryReader;
41220
+ #sessionIdentity;
41369
41221
  #observer;
41370
- constructor(observer = new NullAcpSessionObserver(), store = new MemoryAcpSessionStore(), nativeHistoryReader = null) {
41222
+ constructor(observer = new NullAcpSessionObserver(), store = new MemoryAcpSessionStore(), nativeHistoryReader = null, sessionIdentity = "assigned") {
41371
41223
  this.#observer = observer;
41372
41224
  this.#store = store;
41373
41225
  this.#nativeHistoryReader = nativeHistoryReader;
41226
+ this.#sessionIdentity = sessionIdentity;
41374
41227
  }
41375
41228
  setObserver = (observer) => {
41376
41229
  this.#observer = observer;
41377
41230
  };
41378
- findLinkedSessions = (agentId, nativeSessionId) => this.#store.findNative(agentId, nativeSessionId);
41379
41231
  #notifyProcessCapacityChanged() {
41380
41232
  const changed = this.#processCapacityChanged;
41381
41233
  this.#processCapacityChanged = Promise.withResolvers();
@@ -41483,7 +41335,13 @@ var AcpSessionManager = class {
41483
41335
  if (retained) {
41484
41336
  this.#sessions.delete(sessionId);
41485
41337
  }
41486
- await this.#retireProcess(runtime, retained, close);
41338
+ try {
41339
+ await this.#retireProcess(runtime, retained, close);
41340
+ } finally {
41341
+ if (retained && this.#sessionIdentity === "native") {
41342
+ this.#store.remove(sessionId);
41343
+ }
41344
+ }
41487
41345
  }
41488
41346
  async #retireNativeBrowserProcess(sessionId, runtime, close) {
41489
41347
  const retained = this.#nativeBrowserSessions.get(sessionId) === runtime;
@@ -41630,7 +41488,14 @@ var AcpSessionManager = class {
41630
41488
  try {
41631
41489
  return await this.#startRetainedSessionProcess(
41632
41490
  options,
41633
- async () => await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics)
41491
+ async () => await AcpProcessSession.start(
41492
+ this.#sessionIdentity === "native" && options.agent.id === "codex" && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu.test(
41493
+ options.sessionId
41494
+ ) && this.#store.read(options.sessionId) instanceof MissingAcpStoredSession ? { ...options, origin: { kind: "import", nativeSessionId: options.sessionId } } : options,
41495
+ () => this.#observer,
41496
+ this.#store,
41497
+ metrics
41498
+ )
41634
41499
  );
41635
41500
  } finally {
41636
41501
  this.#preparing.delete(options.sessionId);
@@ -42053,6 +41918,45 @@ var AcpSessionManager = class {
42053
41918
  ]);
42054
41919
  };
42055
41920
  hasPreparedSession = (sessionId, agentId, cwd, additionalDirectories) => this.#sessions.get(sessionId)?.belongsTo(agentId, cwd, additionalDirectories) === true;
41921
+ createNativeSession = async (options) => {
41922
+ const temporarySessionId = `new-${crypto.randomUUID()}`;
41923
+ const temporaryOptions = { ...options, sessionId: temporarySessionId };
41924
+ this.#beginSessionUse(temporarySessionId);
41925
+ try {
41926
+ const runtime = await this.#startPreparation(temporaryOptions);
41927
+ let adopted = false;
41928
+ try {
41929
+ const nativeSessionId = runtime.nativeSessionId();
41930
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu.test(nativeSessionId) || this.#sessions.has(nativeSessionId) || !(this.#store.read(nativeSessionId) instanceof MissingAcpStoredSession)) {
41931
+ throw new AcpExecutionError(
41932
+ "Codex returned an invalid new Session ID",
41933
+ {},
41934
+ "invalid_native_session_response"
41935
+ );
41936
+ }
41937
+ runtime.adoptNativeSessionId(nativeSessionId);
41938
+ this.#sessions.delete(temporarySessionId);
41939
+ this.#sessions.set(nativeSessionId, runtime);
41940
+ this.#retainedProcesses.set(
41941
+ runtime,
41942
+ new FoundAcpSessionProcessEvictionCandidate(nativeSessionId, runtime)
41943
+ );
41944
+ adopted = true;
41945
+ return nativeSessionId;
41946
+ } finally {
41947
+ if (!adopted) {
41948
+ await this.#retireSessionProcess(
41949
+ temporarySessionId,
41950
+ runtime,
41951
+ async () => await runtime.closeProcess()
41952
+ );
41953
+ }
41954
+ }
41955
+ } finally {
41956
+ this.#store.remove(temporarySessionId);
41957
+ this.#endSessionUse(temporarySessionId);
41958
+ }
41959
+ };
42056
41960
  ensureSession = async (options) => {
42057
41961
  const existing = this.#sessions.get(options.sessionId);
42058
41962
  if (existing !== void 0) {
@@ -42146,6 +42050,25 @@ var AcpSessionManager = class {
42146
42050
  this.#endSessionUse(options.sessionId);
42147
42051
  }
42148
42052
  };
42053
+ loadLinkedSessionHistory = async (options) => {
42054
+ options.signal.throwIfAborted();
42055
+ const stored = this.#store.read(options.sessionId);
42056
+ if (!(stored instanceof FoundAcpStoredSession) || !stored.session.prompted) {
42057
+ return null;
42058
+ }
42059
+ const linked = stored.session;
42060
+ if (linked.agentId !== options.agent.id || linked.cwd !== options.cwd || linked.additionalDirectories.length !== options.additionalDirectories.length || linked.additionalDirectories.some((directory, index2) => directory !== options.additionalDirectories[index2])) {
42061
+ throw new AcpExecutionError(
42062
+ "The session belongs to another Agent or workspace",
42063
+ {},
42064
+ "session_identity_mismatch"
42065
+ );
42066
+ }
42067
+ if (this.#nativeHistoryReader === null) {
42068
+ return await this.loadSessionHistory(options);
42069
+ }
42070
+ return await this.#nativeHistoryReader.read(options, linked.nativeSessionId);
42071
+ };
42149
42072
  openNativeSession = async (options, origin, loadHistory) => {
42150
42073
  const key = `${options.agent.id}:${origin.nativeSessionId}`;
42151
42074
  if (this.#nativeOperations.has(key)) {
@@ -43209,7 +43132,7 @@ var LocalAuthorizationError = class extends Error {
43209
43132
  // src/authorization/workspace-directory.ts
43210
43133
  import { readdir as readdir3, realpath as realpath9, stat as stat8 } from "node:fs/promises";
43211
43134
  import { homedir as homedir2 } from "node:os";
43212
- import { basename as basename5, dirname as dirname6, isAbsolute as isAbsolute10, join as join16, normalize as normalize4, relative as relative4 } from "node:path";
43135
+ import { basename as basename5, dirname as dirname4, isAbsolute as isAbsolute10, join as join16, normalize as normalize4, relative as relative4 } from "node:path";
43213
43136
  var WorkspaceDirectoryListing = class {
43214
43137
  directoryId;
43215
43138
  directoryLabel;
@@ -43333,7 +43256,7 @@ var WorkspaceDirectoryService = class {
43333
43256
  }
43334
43257
  }
43335
43258
  entries.sort((a, b) => a.name.localeCompare(b.name));
43336
- const parent = dirname6(target);
43259
+ const parent = dirname4(target);
43337
43260
  return new WorkspaceDirectoryListing(
43338
43261
  id,
43339
43262
  this.label(target),
@@ -43358,7 +43281,7 @@ var WorkspaceDirectoryService = class {
43358
43281
  };
43359
43282
 
43360
43283
  // src/daemon-diagnostic-log.ts
43361
- import { appendFileSync, mkdirSync as mkdirSync3, readFileSync as readFileSync2, renameSync, statSync as statSync3, writeFileSync } from "node:fs";
43284
+ import { appendFileSync, mkdirSync, readFileSync as readFileSync2, renameSync, statSync as statSync3, writeFileSync } from "node:fs";
43362
43285
  import { join as join17 } from "node:path";
43363
43286
  var MAXIMUM_DAEMON_LOG_BYTES = 1 * 1024 * 1024;
43364
43287
  var DaemonDiagnosticLog = class {
@@ -43374,7 +43297,7 @@ var DaemonDiagnosticLog = class {
43374
43297
  const encoded = `${diagnostic.replace(/[\r\n]+/gu, " ").trim()}
43375
43298
  `;
43376
43299
  const encodedBytes = Buffer.byteLength(encoded);
43377
- mkdirSync3(this.#directory, { mode: 448, recursive: true });
43300
+ mkdirSync(this.#directory, { mode: 448, recursive: true });
43378
43301
  let existingBytes = 0;
43379
43302
  try {
43380
43303
  existingBytes = statSync3(this.#path).size;
@@ -43863,6 +43786,84 @@ var NativeSessionService = class {
43863
43786
  sessionId: command.sessionId,
43864
43787
  signal
43865
43788
  };
43789
+ if (command.action === "linked-history") {
43790
+ if (options.agent.id !== "codex") {
43791
+ const history = await this.#sessions.loadLinkedSessionHistory({
43792
+ ...options,
43793
+ sessionId: command.targetSessionId
43794
+ });
43795
+ this.record(command, "native_session_history_read");
43796
+ return history === null ? {
43797
+ action: "unlinked-history",
43798
+ kind: "native.session.result",
43799
+ requestId: command.requestId,
43800
+ sessionId: command.sessionId,
43801
+ targetSessionId: command.targetSessionId
43802
+ } : {
43803
+ action: "linked-history",
43804
+ history,
43805
+ kind: "native.session.result",
43806
+ requestId: command.requestId,
43807
+ sessionId: command.sessionId,
43808
+ targetSessionId: command.targetSessionId
43809
+ };
43810
+ }
43811
+ const nativeSessionId = nativeSessionIdSchema.parse(command.targetSessionId);
43812
+ if (this.#sessions.hasPreparedSession(nativeSessionId, options.agent.id, cwd, additionalDirectories) && await this.#sessions.loadLinkedSessionHistory({ ...options, sessionId: nativeSessionId }) === null) {
43813
+ this.record(command, "native_session_history_read");
43814
+ return {
43815
+ action: "linked-history",
43816
+ history: {
43817
+ status: "available",
43818
+ messages: [],
43819
+ truncated: false,
43820
+ coveredCommandIds: [],
43821
+ coveredMessageIds: []
43822
+ },
43823
+ kind: "native.session.result",
43824
+ requestId: command.requestId,
43825
+ sessionId: command.sessionId,
43826
+ targetSessionId: command.targetSessionId
43827
+ };
43828
+ }
43829
+ const snapshot = await readCodexFullHistory(options.agent, cwd, nativeSessionId, signal);
43830
+ const resolved = await this.#directories.identify(command.bindingId, snapshot.cwd, signal);
43831
+ if (snapshot.nativeSessionId !== nativeSessionId || resolved.path !== cwd) {
43832
+ throw new AcpExecutionError(
43833
+ "Codex returned history for a different session or workspace.",
43834
+ {},
43835
+ "invalid_native_session_response"
43836
+ );
43837
+ }
43838
+ this.record(command, "native_session_history_read");
43839
+ return {
43840
+ action: "linked-history",
43841
+ history: snapshot.history,
43842
+ kind: "native.session.result",
43843
+ requestId: command.requestId,
43844
+ sessionId: command.sessionId,
43845
+ targetSessionId: command.targetSessionId
43846
+ };
43847
+ }
43848
+ if (command.action === "create") {
43849
+ if (options.agent.id !== "codex") {
43850
+ throw new AcpExecutionError(
43851
+ "Native session creation is unavailable for this Agent",
43852
+ {},
43853
+ "native_session_unsupported"
43854
+ );
43855
+ }
43856
+ const nativeSessionId = await this.#sessions.createNativeSession(options);
43857
+ signal.throwIfAborted();
43858
+ this.record(command, "native_session_created");
43859
+ return {
43860
+ action: "create",
43861
+ kind: "native.session.result",
43862
+ nativeSessionId,
43863
+ requestId: command.requestId,
43864
+ sessionId: command.sessionId
43865
+ };
43866
+ }
43866
43867
  const prepared = await this.#sessions.prepareNativeSessionBrowser(options);
43867
43868
  if (!prepared.capabilities.listSessions) {
43868
43869
  throw new AcpExecutionError(
@@ -43890,7 +43891,7 @@ var NativeSessionService = class {
43890
43891
  });
43891
43892
  return {
43892
43893
  entryId,
43893
- mobiusSessionIds: this.#sessions.findLinkedSessions(command.agentId, info.sessionId).filter((session) => session.prompted && session.cwd === authorized.cwd).map((session) => session.sessionId),
43894
+ nativeSessionId: info.sessionId,
43894
43895
  title: info.title ?? "Untitled session",
43895
43896
  directoryId: authorized.directoryId,
43896
43897
  directoryLabel: authorized.directoryLabel,
@@ -44995,26 +44996,26 @@ var RelayConnectionLiveness = class {
44995
44996
  };
44996
44997
 
44997
44998
  // src/relay-connection/session-event-outbox.ts
44998
- import { mkdirSync as mkdirSync4 } from "node:fs";
44999
- import { dirname as dirname7 } from "node:path";
45000
- import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
44999
+ import { createHash as createHash4 } from "node:crypto";
45000
+ import { DatabaseSync } from "node:sqlite";
45001
45001
  var DEFAULT_OUTBOX_LIMITS = {
45002
45002
  criticalEventBytes: 136 * 1024 * 1024,
45003
45003
  runtimeDeliveryBytes: 64 * 1024 * 1024,
45004
45004
  runtimeDeliveryCount: 64,
45005
45005
  standardEventBytes: 128 * 1024 * 1024
45006
45006
  };
45007
+ var MAX_TERMINAL_RECEIPTS = 1024;
45007
45008
  var SessionEventOutboxCapacityError = class extends Error {
45008
45009
  code = "session_event_outbox_full";
45009
45010
  constructor() {
45010
- super("The durable Session event outbox is full");
45011
+ super("The in-memory Session event outbox is full");
45011
45012
  this.name = "SessionEventOutboxCapacityError";
45012
45013
  }
45013
45014
  };
45014
45015
  var RuntimeDeliveryInboxCapacityError = class extends Error {
45015
45016
  code = "runtime_delivery_inbox_full";
45016
45017
  constructor() {
45017
- super("The durable Runtime delivery inbox is full");
45018
+ super("The in-memory Runtime delivery inbox is full");
45018
45019
  this.name = "RuntimeDeliveryInboxCapacityError";
45019
45020
  }
45020
45021
  };
@@ -45059,11 +45060,10 @@ function rowString(row, field) {
45059
45060
  var SessionEventOutbox = class {
45060
45061
  #database;
45061
45062
  #limits;
45062
- constructor(path3, limits = DEFAULT_OUTBOX_LIMITS) {
45063
+ constructor(limits = DEFAULT_OUTBOX_LIMITS) {
45063
45064
  validateLimits(limits);
45064
45065
  this.#limits = limits;
45065
- mkdirSync4(dirname7(path3), { recursive: true });
45066
- this.#database = new DatabaseSync3(path3);
45066
+ this.#database = new DatabaseSync(":memory:");
45067
45067
  this.#database.exec(`
45068
45068
  CREATE TABLE IF NOT EXISTS relay_session_event_outbox (
45069
45069
  ordinal INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -45091,7 +45091,7 @@ var SessionEventOutbox = class {
45091
45091
  CREATE TABLE IF NOT EXISTS relay_turn_receipts (
45092
45092
  command_id TEXT PRIMARY KEY,
45093
45093
  session_id TEXT NOT NULL,
45094
- command_json TEXT NOT NULL,
45094
+ command_hash TEXT NOT NULL,
45095
45095
  attempt_id TEXT NOT NULL,
45096
45096
  state TEXT NOT NULL CHECK (
45097
45097
  state IN ('dispatching', 'running', 'succeeded', 'failed', 'cancelled')
@@ -45122,19 +45122,20 @@ var SessionEventOutbox = class {
45122
45122
  `);
45123
45123
  }
45124
45124
  claimExecution = (commandId, sessionId, commandJson) => {
45125
+ const commandHash = createHash4("sha256").update(commandJson).digest("hex");
45125
45126
  this.#database.exec("BEGIN IMMEDIATE");
45126
45127
  try {
45127
45128
  const existing = this.#database.prepare(
45128
- `SELECT session_id, command_json, attempt_id, state
45129
+ `SELECT session_id, command_hash, attempt_id, state
45129
45130
  FROM relay_turn_receipts WHERE command_id = ?`
45130
45131
  ).get(commandId);
45131
45132
  if (typeof existing === "object" && existing !== null) {
45132
45133
  const storedSessionId = Reflect.get(existing, "session_id");
45133
- const storedCommand = Reflect.get(existing, "command_json");
45134
+ const storedCommandHash = Reflect.get(existing, "command_hash");
45134
45135
  const attemptId2 = Reflect.get(existing, "attempt_id");
45135
45136
  const state = Reflect.get(existing, "state");
45136
- if (storedSessionId !== sessionId || storedCommand !== commandJson || typeof attemptId2 !== "string" || !isDaemonExecutionState(state)) {
45137
- throw new Error("The daemon command identity conflicts with its durable receipt");
45137
+ if (storedSessionId !== sessionId || storedCommandHash !== commandHash || typeof attemptId2 !== "string" || !isDaemonExecutionState(state)) {
45138
+ throw new Error("The daemon command identity conflicts with its in-memory receipt");
45138
45139
  }
45139
45140
  this.#database.exec("COMMIT");
45140
45141
  return { attemptId: attemptId2, commandId, kind: "duplicate", state };
@@ -45142,9 +45143,9 @@ var SessionEventOutbox = class {
45142
45143
  const attemptId = crypto.randomUUID();
45143
45144
  this.#database.prepare(
45144
45145
  `INSERT INTO relay_turn_receipts (
45145
- command_id, session_id, command_json, attempt_id, state
45146
+ command_id, session_id, command_hash, attempt_id, state
45146
45147
  ) VALUES (?, ?, ?, ?, 'dispatching')`
45147
- ).run(commandId, sessionId, commandJson, attemptId);
45148
+ ).run(commandId, sessionId, commandHash, attemptId);
45148
45149
  this.#database.exec("COMMIT");
45149
45150
  return {
45150
45151
  attemptId,
@@ -45171,11 +45172,21 @@ var SessionEventOutbox = class {
45171
45172
  throw new Error("The daemon execution transition is invalid");
45172
45173
  }
45173
45174
  this.#database.prepare(`UPDATE relay_turn_receipts SET state = ? WHERE command_id = ?`).run(state, commandId);
45175
+ if (state === "succeeded" || state === "failed" || state === "cancelled") {
45176
+ this.#database.prepare(
45177
+ `DELETE FROM relay_turn_receipts
45178
+ WHERE state IN ('succeeded', 'failed', 'cancelled')
45179
+ AND rowid NOT IN (
45180
+ SELECT rowid FROM relay_turn_receipts
45181
+ WHERE state IN ('succeeded', 'failed', 'cancelled')
45182
+ ORDER BY rowid DESC LIMIT ?
45183
+ )`
45184
+ ).run(MAX_TERMINAL_RECEIPTS);
45185
+ }
45174
45186
  };
45175
45187
  /**
45176
- * The Attempt this Runtime durably claimed for a command, when that Attempt never reached a
45177
- * terminal state. A restarted Runtime has no in-memory Turn for a command it was executing before
45178
- * the restart, so this is the only record of the Attempt identity the Relay is still waiting on.
45188
+ * The Attempt this live Runtime claimed for a command that has not reached a terminal state.
45189
+ * Receipts disappear when the daemon process exits.
45179
45190
  */
45180
45191
  findUnsettledAttemptId = (commandId, sessionId) => {
45181
45192
  const row = this.#database.prepare(`SELECT attempt_id, state FROM relay_turn_receipts WHERE command_id = ? AND session_id = ?`).get(commandId, sessionId);
@@ -45224,7 +45235,7 @@ var SessionEventOutbox = class {
45224
45235
  WHERE event_id = ? AND session_id = ?`
45225
45236
  ).run(rejection.eventId, rejection.sessionId);
45226
45237
  if (deletion.changes !== 1) {
45227
- throw new Error("The rejected session event could not be removed from the durable outbox");
45238
+ throw new Error("The rejected session event could not be removed from the in-memory outbox");
45228
45239
  }
45229
45240
  this.#decrementEventState(byteLength);
45230
45241
  this.#database.exec("COMMIT");
@@ -45243,7 +45254,7 @@ var SessionEventOutbox = class {
45243
45254
  enqueueCritical = (sessionId, payload, attemptId = "") => this.#enqueueBounded(sessionId, payload, attemptId, this.#limits.criticalEventBytes);
45244
45255
  /**
45245
45256
  * Bytes still available to standard Session events. The daemon uses this to shed
45246
- * superseded streaming events instead of filling the durable outbox, so a long Turn
45257
+ * superseded streaming events instead of filling the in-memory outbox, so a long Turn
45247
45258
  * behind a slow Relay cannot make the next enqueue throw.
45248
45259
  */
45249
45260
  standardCapacityRemaining = () => {
@@ -45268,7 +45279,7 @@ var SessionEventOutbox = class {
45268
45279
  const payload = rowString(existing, "payload_json");
45269
45280
  const state = runtimeDeliveryState(existing);
45270
45281
  if (sessionId !== delivery.sessionId || payload !== delivery.payload) {
45271
- throw new Error("The Runtime delivery identity conflicts with its durable receipt");
45282
+ throw new Error("The Runtime delivery identity conflicts with its in-memory receipt");
45272
45283
  }
45273
45284
  this.#database.exec("COMMIT");
45274
45285
  return new StoredRuntimeDelivery(delivery.deliveryId, sessionId, payload, state, true);
@@ -45436,7 +45447,7 @@ var SessionEventOutbox = class {
45436
45447
  WHERE event_id = ? AND session_id = ?`
45437
45448
  ).run(eventId, sessionId);
45438
45449
  if (deletion.changes !== 1) {
45439
- throw new Error("The acknowledged session event could not be removed from the durable outbox");
45450
+ throw new Error("The acknowledged session event could not be removed from the in-memory outbox");
45440
45451
  }
45441
45452
  this.#decrementEventState(byteLength);
45442
45453
  this.#database.exec("COMMIT");
@@ -45918,7 +45929,7 @@ var DaemonSessionEventPublisher = class {
45918
45929
  };
45919
45930
  /**
45920
45931
  * Enqueue a standard event, shedding it instead of ending the daemon when the
45921
- * durable outbox is full.
45932
+ * in-memory outbox is full.
45922
45933
  *
45923
45934
  * A capacity error used to escape the coalescing timer that publishes activities,
45924
45935
  * so the process exited and every restart died on the same retained backlog. A full
@@ -45961,7 +45972,7 @@ var DaemonSessionEventPublisher = class {
45961
45972
  return;
45962
45973
  }
45963
45974
  this.#shedEventKinds.add(kind);
45964
- console.warn(`Mobius daemon is dropping durable "${kind}" events because the Session event outbox is full`);
45975
+ console.warn(`Mobius daemon is dropping queued "${kind}" events because the Session event outbox is full`);
45965
45976
  };
45966
45977
  acknowledge = (acknowledgement) => {
45967
45978
  if (!this.#outbox.acknowledge(acknowledgement)) {
@@ -46475,7 +46486,7 @@ function settingsRevision(agent, reportedAgentVersion, settings, modelEffort) {
46475
46486
  unsupportedModelIds: modelEffort.unsupportedModelIds,
46476
46487
  valuesByModel: {}
46477
46488
  };
46478
- return createHash4("sha256").update(
46489
+ return createHash5("sha256").update(
46479
46490
  JSON.stringify({
46480
46491
  adapterVersion: agent.kind === "acp-adapter-process" ? agent.adapterVersion : agent.agentVersion,
46481
46492
  agentId: agent.id,
@@ -47470,7 +47481,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
47470
47481
  if (connectionController.signal.aborted) {
47471
47482
  return;
47472
47483
  }
47473
- console.error("Mobius daemon could not process a durable Runtime delivery", error62);
47484
+ console.error("Mobius daemon could not process a in-memory Runtime delivery", error62);
47474
47485
  failAndClose(
47475
47486
  new Error("Runtime delivery processing failed", { cause: error62 }),
47476
47487
  4008,
@@ -48273,8 +48284,8 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
48273
48284
  publishCatalog: async (installationSignal) => await publishAgentCatalog(config2, installationSignal),
48274
48285
  stateDirectory
48275
48286
  });
48276
- const sessionStore = new SqliteAcpSessionStore(config2.auditDatabasePath);
48277
- const outbox = new SessionEventOutbox(config2.auditDatabasePath);
48287
+ const sessionStore = new MemoryAcpSessionStore();
48288
+ const outbox = new SessionEventOutbox();
48278
48289
  const publisher = new DaemonSessionEventPublisher(outbox, timer);
48279
48290
  const activeTurns = /* @__PURE__ */ new Map();
48280
48291
  const activeAttemptIds = /* @__PURE__ */ new Map();
@@ -48286,9 +48297,14 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
48286
48297
  }
48287
48298
  publisher.recordAttempt(sessionId, event, attemptId);
48288
48299
  };
48289
- const sessions = new AcpSessionManager(new DaemonAcpObserver(recordSessionEvent), sessionStore, {
48290
- read: async (options2, nativeSessionId) => options2.agent.id === "codex" ? (await readCodexFullHistory(options2.agent, options2.cwd, nativeSessionId, options2.signal)).history : null
48291
- });
48300
+ const sessions = new AcpSessionManager(
48301
+ new DaemonAcpObserver(recordSessionEvent),
48302
+ sessionStore,
48303
+ {
48304
+ read: async (options2, nativeSessionId) => options2.agent.id === "codex" ? (await readCodexFullHistory(options2.agent, options2.cwd, nativeSessionId, options2.signal)).history : null
48305
+ },
48306
+ "native"
48307
+ );
48292
48308
  const directories = new WorkspaceDirectoryService(config2.bindingId, config2.defaultWorkspace);
48293
48309
  const installationObserver = new DaemonInstallationObserver();
48294
48310
  const diagnostics = new RelayConnectionDiagnostics(
@@ -48424,13 +48440,9 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
48424
48440
  await sessions.close();
48425
48441
  } finally {
48426
48442
  try {
48427
- sessionStore.close();
48443
+ publisher.close();
48428
48444
  } finally {
48429
- try {
48430
- publisher.close();
48431
- } finally {
48432
- outbox.close();
48433
- }
48445
+ outbox.close();
48434
48446
  }
48435
48447
  }
48436
48448
  }
@@ -48486,7 +48498,7 @@ var MobiusRuntimeEngine = class {
48486
48498
  }
48487
48499
  signal.throwIfAborted();
48488
48500
  this.#state = new RunningMobiusRuntimeState();
48489
- const audit = new AuditStore(this.#config.auditDatabasePath);
48501
+ const audit = new AuditStore();
48490
48502
  try {
48491
48503
  await runDaemon(this.#config, audit, signal, void 0, {
48492
48504
  ...this.#options.onConnectionStatus === void 0 ? {} : { onConnectionStatus: this.#options.onConnectionStatus },
@@ -48536,7 +48548,7 @@ function isRecord11(value) {
48536
48548
  return typeof value === "object" && value !== null && !Array.isArray(value);
48537
48549
  }
48538
48550
  function controlSocketPath(stateDirectory) {
48539
- const installationHash = createHash5("sha256").update(stateDirectory).digest("hex").slice(0, 32);
48551
+ const installationHash = createHash6("sha256").update(stateDirectory).digest("hex").slice(0, 32);
48540
48552
  return process.platform === "win32" ? `\\\\.\\pipe\\mobius-${installationHash}` : join18(tmpdir(), `mobius-${installationHash}.sock`);
48541
48553
  }
48542
48554
  function controlTokenPath(stateDirectory) {
@@ -48857,24 +48869,19 @@ async function sendControlRequest(stateDirectory, command, signal) {
48857
48869
  socket.destroy();
48858
48870
  }
48859
48871
  }
48860
- async function spawnManager(stateDirectory) {
48861
- const log = await open6(join18(stateDirectory, "manager.log"), "a", 384);
48862
- try {
48863
- const child = spawn6(process.execPath, [process.argv[1] ?? "", "__manager"], {
48864
- detached: true,
48865
- env: process.env,
48866
- stdio: ["ignore", log.fd, log.fd]
48867
- });
48868
- child.unref();
48869
- return child;
48870
- } finally {
48871
- await log.close();
48872
- }
48872
+ async function spawnManager() {
48873
+ const child = spawn6(process.execPath, [process.argv[1] ?? "", "__manager"], {
48874
+ detached: true,
48875
+ env: process.env,
48876
+ stdio: "ignore"
48877
+ });
48878
+ child.unref();
48879
+ return child;
48873
48880
  }
48874
- async function launchManager(stateDirectory, managerVersion) {
48881
+ async function launchManager(managerVersion) {
48875
48882
  process.stdout.write(`Starting mobius daemon ${managerVersion}
48876
48883
  `);
48877
- await spawnManager(stateDirectory);
48884
+ await spawnManager();
48878
48885
  }
48879
48886
  async function waitForManagerExit(stateDirectory, signal) {
48880
48887
  const deadline = AbortSignal.any([signal, AbortSignal.timeout(1e4)]);
@@ -48937,14 +48944,14 @@ async function ensureMatchingManager(stateDirectory, managerVersion, signal) {
48937
48944
  throw new Error("The Mobius manager returned an unexpected response");
48938
48945
  }
48939
48946
  await stopManager(stateDirectory, signal);
48940
- await launchManager(stateDirectory, managerVersion);
48947
+ await launchManager(managerVersion);
48941
48948
  managerStarted = true;
48942
48949
  } catch (cause) {
48943
48950
  if (!isNodeError2(cause, "ENOENT") && !isNodeError2(cause, "ECONNREFUSED")) {
48944
48951
  throw cause;
48945
48952
  }
48946
48953
  if (!managerStarted) {
48947
- await launchManager(stateDirectory, managerVersion);
48954
+ await launchManager(managerVersion);
48948
48955
  managerStarted = true;
48949
48956
  }
48950
48957
  await new Promise((resolve8, reject) => {
@@ -49121,7 +49128,7 @@ async function writePairList(path3, pairs) {
49121
49128
  shutdown.signal.throwIfAborted();
49122
49129
  let file2;
49123
49130
  try {
49124
- file2 = await open7(path3, constants2.O_WRONLY | constants2.O_NOFOLLOW);
49131
+ file2 = await open6(path3, constants2.O_WRONLY | constants2.O_NOFOLLOW);
49125
49132
  } catch (cause) {
49126
49133
  if (typeof cause === "object" && cause !== null && "code" in cause && cause.code === "ENOENT") {
49127
49134
  throw new Error("The JSON output file does not exist", { cause });