@moxt-ai/mobius 0.0.92 → 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 (58) 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 +4 -1
  7. package/dist/acp/session-manager.d.ts.map +1 -1
  8. package/dist/acp/session-manager.js +77 -4
  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 +417 -330
  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 +354 -268
  28. package/dist/index.js.map +3 -3
  29. package/dist/native-sessions/codex-history.d.ts.map +1 -1
  30. package/dist/native-sessions/codex-history.js +38 -8
  31. package/dist/native-sessions/codex-history.js.map +1 -1
  32. package/dist/native-sessions/service.d.ts +1 -0
  33. package/dist/native-sessions/service.d.ts.map +1 -1
  34. package/dist/native-sessions/service.js +99 -1
  35. package/dist/native-sessions/service.js.map +1 -1
  36. package/dist/pairing/pair-local-machine.d.ts.map +1 -1
  37. package/dist/pairing/pair-local-machine.js +0 -1
  38. package/dist/pairing/pair-local-machine.js.map +1 -1
  39. package/dist/relay-connection/coalescing-narration-publisher.d.ts +1 -1
  40. package/dist/relay-connection/coalescing-narration-publisher.js +1 -1
  41. package/dist/relay-connection/coalescing-text-publisher.d.ts +1 -1
  42. package/dist/relay-connection/coalescing-text-publisher.js +1 -1
  43. package/dist/relay-connection/session-event-outbox.d.ts +4 -5
  44. package/dist/relay-connection/session-event-outbox.d.ts.map +1 -1
  45. package/dist/relay-connection/session-event-outbox.js +31 -21
  46. package/dist/relay-connection/session-event-outbox.js.map +1 -1
  47. package/dist/run-daemon.d.ts.map +1 -1
  48. package/dist/run-daemon.js +13 -19
  49. package/dist/run-daemon.js.map +1 -1
  50. package/dist/runtime.d.ts +0 -1
  51. package/dist/runtime.d.ts.map +1 -1
  52. package/dist/runtime.js +348 -260
  53. package/dist/runtime.js.map +3 -3
  54. package/dist/storage/runtime-installation-store.d.ts +0 -1
  55. package/dist/storage/runtime-installation-store.d.ts.map +1 -1
  56. package/dist/storage/runtime-installation-store.js +0 -1
  57. package/dist/storage/runtime-installation-store.js.map +1 -1
  58. package/package.json +1 -1
package/dist/runtime.js CHANGED
@@ -6,7 +6,7 @@ var __export = (target, all2) => {
6
6
 
7
7
  // src/runtime.ts
8
8
  import { mkdir as mkdir6, realpath as realpath10, stat as stat9 } from "node:fs/promises";
9
- import { dirname as dirname8, join as join18, resolve as resolve7 } from "node:path";
9
+ import { resolve as resolve7 } from "node:path";
10
10
 
11
11
  // src/agent-catalog/local-agent.ts
12
12
  import { realpathSync, statSync } from "node:fs";
@@ -21687,18 +21687,17 @@ function effortValues(model) {
21687
21687
  }
21688
21688
  function modelSetting(models, currentValue) {
21689
21689
  const values = modelValues(models);
21690
- const current = currentValue.length > 0 ? currentValue : models.find((model) => model.isDefault === true)?.id ?? values[0]?.value ?? "";
21690
+ const current = values.some((value) => value.value === currentValue) ? currentValue : models.find((model) => model.isDefault === true)?.id ?? values[0]?.value ?? "";
21691
21691
  if (current.length === 0) {
21692
21692
  return null;
21693
21693
  }
21694
- const options = values.some((value) => value.value === current) ? values : [{ description: "", name: current, value: current }, ...values];
21695
21694
  return {
21696
21695
  category: "model",
21697
21696
  currentValue: current,
21698
21697
  description: "Model Codex uses for the session",
21699
21698
  id: MODEL_SETTING_ID,
21700
21699
  name: "Model",
21701
- options,
21700
+ options: values,
21702
21701
  type: "select"
21703
21702
  };
21704
21703
  }
@@ -24324,51 +24323,20 @@ async function discoverLocalAgentInventory(options) {
24324
24323
  }
24325
24324
 
24326
24325
  // src/audit/audit-store.ts
24327
- import { mkdirSync } from "node:fs";
24328
- import { dirname as dirname3 } from "node:path";
24329
- import { DatabaseSync } from "node:sqlite";
24326
+ var MAX_AUDIT_RECORDS = 1024;
24330
24327
  var AuditStore = class {
24331
- database;
24332
- constructor(path2) {
24333
- mkdirSync(dirname3(path2), { recursive: true });
24334
- this.database = new DatabaseSync(path2);
24335
- this.database.exec(`
24336
- CREATE TABLE IF NOT EXISTS audit_events (
24337
- id INTEGER PRIMARY KEY AUTOINCREMENT,
24338
- recorded_at TEXT NOT NULL,
24339
- event TEXT NOT NULL,
24340
- command_id TEXT NOT NULL,
24341
- session_id TEXT NOT NULL,
24342
- details_json TEXT NOT NULL DEFAULT '{}'
24343
- ) STRICT
24344
- `);
24345
- const columns = this.database.prepare("PRAGMA table_info(audit_events)").all();
24346
- if (!columns.some((column) => Reflect.get(column, "name") === "details_json")) {
24347
- this.database.exec("ALTER TABLE audit_events ADD COLUMN details_json TEXT NOT NULL DEFAULT '{}'");
24348
- }
24349
- }
24350
- record(record2) {
24351
- this.database.prepare(
24352
- `
24353
- INSERT INTO audit_events (
24354
- recorded_at,
24355
- event,
24356
- command_id,
24357
- session_id,
24358
- details_json
24359
- ) VALUES (?, ?, ?, ?, ?)
24360
- `
24361
- ).run(
24362
- (/* @__PURE__ */ new Date()).toISOString(),
24363
- record2.event,
24364
- record2.commandId,
24365
- record2.sessionId,
24366
- JSON.stringify(record2.details ?? {})
24328
+ #records = [];
24329
+ record = (record2) => {
24330
+ if (this.#records.length === MAX_AUDIT_RECORDS) {
24331
+ this.#records.shift();
24332
+ }
24333
+ this.#records.push(
24334
+ record2.details === void 0 ? { ...record2 } : { ...record2, details: { ...record2.details } }
24367
24335
  );
24368
- }
24369
- close() {
24370
- this.database.close();
24371
- }
24336
+ };
24337
+ close = () => {
24338
+ this.#records.length = 0;
24339
+ };
24372
24340
  };
24373
24341
 
24374
24342
  // src/config.ts
@@ -25676,7 +25644,10 @@ var nativeSessionTurnForkCommandSchema = external_exports.strictObject({
25676
25644
  title: external_exports.string().max(500)
25677
25645
  }).readonly();
25678
25646
  var nativeSessionRequestSchema = external_exports.discriminatedUnion("action", [
25647
+ external_exports.strictObject({ ...identity, action: external_exports.literal("create") }).readonly(),
25648
+ external_exports.strictObject({ ...identity, action: external_exports.literal("linked-history"), targetSessionId: identifier }).readonly(),
25679
25649
  external_exports.strictObject({ ...identity, action: external_exports.literal("preview"), entryId: identifier }).readonly(),
25650
+ external_exports.strictObject({ ...identity, action: external_exports.literal("history"), entryId: identifier }).readonly(),
25680
25651
  external_exports.strictObject({ ...identity, action: external_exports.literal("find"), nativeSessionId: identifier }).readonly(),
25681
25652
  external_exports.strictObject({
25682
25653
  ...identity,
@@ -25696,7 +25667,10 @@ var nativeSessionRequestSchema = external_exports.discriminatedUnion("action", [
25696
25667
  }).readonly()
25697
25668
  ]);
25698
25669
  var nativeSessionCommandSchema = external_exports.discriminatedUnion("action", [
25670
+ external_exports.strictObject({ ...identity, action: external_exports.literal("create") }).readonly(),
25671
+ external_exports.strictObject({ ...identity, action: external_exports.literal("linked-history"), targetSessionId: identifier }).readonly(),
25699
25672
  external_exports.strictObject({ ...identity, action: external_exports.literal("preview"), entryId: identifier }).readonly(),
25673
+ external_exports.strictObject({ ...identity, action: external_exports.literal("history"), entryId: identifier }).readonly(),
25700
25674
  external_exports.strictObject({ ...identity, action: external_exports.literal("find"), nativeSessionId: identifier }).readonly(),
25701
25675
  external_exports.strictObject({
25702
25676
  ...identity,
@@ -25723,6 +25697,7 @@ var nativeSessionCommandSchema = external_exports.discriminatedUnion("action", [
25723
25697
  ]);
25724
25698
  var nativeSessionEntrySchema = external_exports.strictObject({
25725
25699
  entryId: identifier,
25700
+ nativeSessionId: identifier,
25726
25701
  title: external_exports.string().max(500),
25727
25702
  directoryId,
25728
25703
  directoryLabel: external_exports.string().min(1).max(2048),
@@ -25734,6 +25709,18 @@ var resultEnvelope = {
25734
25709
  kind: external_exports.literal(NATIVE_SESSION_RESULT_KIND)
25735
25710
  };
25736
25711
  var nativeSessionResultSchema = external_exports.discriminatedUnion("action", [
25712
+ external_exports.strictObject({ ...resultEnvelope, action: external_exports.literal("create"), nativeSessionId: identifier }).readonly(),
25713
+ external_exports.strictObject({
25714
+ ...resultEnvelope,
25715
+ action: external_exports.literal("linked-history"),
25716
+ targetSessionId: identifier,
25717
+ history: sessionHistorySchema
25718
+ }).readonly(),
25719
+ external_exports.strictObject({
25720
+ ...resultEnvelope,
25721
+ action: external_exports.literal("unlinked-history"),
25722
+ targetSessionId: identifier
25723
+ }).readonly(),
25737
25724
  external_exports.strictObject({
25738
25725
  ...resultEnvelope,
25739
25726
  action: external_exports.literal("find"),
@@ -25763,6 +25750,13 @@ var nativeSessionResultSchema = external_exports.discriminatedUnion("action", [
25763
25750
  history: sessionHistorySchema,
25764
25751
  title: external_exports.string().max(500)
25765
25752
  }).readonly(),
25753
+ external_exports.strictObject({
25754
+ ...resultEnvelope,
25755
+ action: external_exports.literal("history"),
25756
+ entryId: identifier,
25757
+ history: sessionHistorySchema,
25758
+ title: external_exports.string().max(500)
25759
+ }).readonly(),
25766
25760
  external_exports.strictObject({
25767
25761
  ...resultEnvelope,
25768
25762
  action: external_exports.literal("delete"),
@@ -26274,7 +26268,6 @@ function createDaemonConfig(connection, agents = [], installableAgents = [], loc
26274
26268
  return {
26275
26269
  agents: daemonAgents,
26276
26270
  defaultWorkspace: connection.defaultWorkspace,
26277
- auditDatabasePath: connection.auditDatabasePath,
26278
26271
  bindingId: "workspace",
26279
26272
  catalog: new LocalAgentCatalog(daemonAgents, installableAgents),
26280
26273
  channelId: connection.channelId,
@@ -26286,7 +26279,7 @@ function createDaemonConfig(connection, agents = [], installableAgents = [], loc
26286
26279
  }
26287
26280
 
26288
26281
  // src/run-daemon.ts
26289
- import { createHash as createHash3, randomUUID as randomUUID3 } from "node:crypto";
26282
+ import { createHash as createHash4, randomUUID as randomUUID3 } from "node:crypto";
26290
26283
  import { basename as basename6 } from "node:path";
26291
26284
  import { styleText } from "node:util";
26292
26285
  import { fetch as fetch4, WebSocket as WebSocket2 } from "undici";
@@ -34794,9 +34787,6 @@ var AcpHistoryReplay = class {
34794
34787
  };
34795
34788
 
34796
34789
  // src/acp/session-store.ts
34797
- import { mkdirSync as mkdirSync2 } from "node:fs";
34798
- import { dirname as dirname4 } from "node:path";
34799
- import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
34800
34790
  var AcpStoredSession = class {
34801
34791
  additionalDirectories;
34802
34792
  agentId;
@@ -34829,44 +34819,6 @@ var FoundAcpStoredSession = class extends AcpStoredSessionLookup {
34829
34819
  var DeletedAcpStoredSession = class extends AcpStoredSessionLookup {
34830
34820
  found = false;
34831
34821
  };
34832
- function readString3(value, field) {
34833
- if (typeof value !== "string" || value.length === 0) {
34834
- throw new Error(`Stored ACP session has an invalid ${field}`);
34835
- }
34836
- return value;
34837
- }
34838
- function readAdditionalDirectories(value) {
34839
- if (typeof value !== "string") {
34840
- throw new Error("Stored ACP session has invalid additional directories");
34841
- }
34842
- const decoded = JSON.parse(value);
34843
- if (!Array.isArray(decoded) || decoded.some((directory) => typeof directory !== "string")) {
34844
- throw new Error("Stored ACP session has invalid additional directories");
34845
- }
34846
- return decoded;
34847
- }
34848
- function readPrompted(value) {
34849
- if (value === 0) {
34850
- return false;
34851
- }
34852
- if (value === 1) {
34853
- return true;
34854
- }
34855
- throw new Error("Stored ACP session has an invalid prompted state");
34856
- }
34857
- function decodeSessionRow(row) {
34858
- if (typeof row !== "object" || row === null || Array.isArray(row)) {
34859
- throw new Error("Stored ACP session is not an object");
34860
- }
34861
- return new AcpStoredSession(
34862
- readString3(Reflect.get(row, "session_id"), "session ID"),
34863
- readString3(Reflect.get(row, "agent_id"), "agent ID"),
34864
- readString3(Reflect.get(row, "native_session_id"), "native session ID"),
34865
- readString3(Reflect.get(row, "cwd"), "working directory"),
34866
- readAdditionalDirectories(Reflect.get(row, "additional_directories_json")),
34867
- readPrompted(Reflect.get(row, "prompted"))
34868
- );
34869
- }
34870
34822
  var MemoryAcpSessionStore = class {
34871
34823
  #sessions = /* @__PURE__ */ new Map();
34872
34824
  #deleted = /* @__PURE__ */ new Set();
@@ -34895,106 +34847,6 @@ var MemoryAcpSessionStore = class {
34895
34847
  this.#sessions.set(session.sessionId, session);
34896
34848
  };
34897
34849
  };
34898
- var SqliteAcpSessionStore = class {
34899
- #database;
34900
- constructor(path2) {
34901
- mkdirSync2(dirname4(path2), { recursive: true });
34902
- this.#database = new DatabaseSync2(path2);
34903
- this.#database.exec(`
34904
- CREATE TABLE IF NOT EXISTS acp_deleted_sessions (session_id TEXT PRIMARY KEY) STRICT;
34905
- CREATE TABLE IF NOT EXISTS acp_sessions (
34906
- session_id TEXT PRIMARY KEY,
34907
- agent_id TEXT NOT NULL,
34908
- native_session_id TEXT NOT NULL,
34909
- cwd TEXT NOT NULL,
34910
- additional_directories_json TEXT NOT NULL,
34911
- prompted INTEGER NOT NULL DEFAULT 0 CHECK (prompted IN (0, 1)),
34912
- updated_at TEXT NOT NULL
34913
- ) STRICT
34914
- `);
34915
- const columns = this.#database.prepare("PRAGMA table_info(acp_sessions)").all();
34916
- const hasPromptedColumn = columns.some(
34917
- (column) => typeof column === "object" && column !== null && Reflect.get(column, "name") === "prompted"
34918
- );
34919
- if (!hasPromptedColumn) {
34920
- this.#database.exec(`
34921
- ALTER TABLE acp_sessions
34922
- ADD COLUMN prompted INTEGER NOT NULL DEFAULT 1 CHECK (prompted IN (0, 1))
34923
- `);
34924
- }
34925
- }
34926
- read = (sessionId) => {
34927
- if (this.#database.prepare("SELECT session_id FROM acp_deleted_sessions WHERE session_id = ?").get(sessionId) !== void 0) {
34928
- return new DeletedAcpStoredSession();
34929
- }
34930
- const row = this.#database.prepare(
34931
- `
34932
- SELECT
34933
- session_id,
34934
- agent_id,
34935
- native_session_id,
34936
- cwd,
34937
- additional_directories_json,
34938
- prompted
34939
- FROM acp_sessions
34940
- WHERE session_id = ?
34941
- `
34942
- ).get(sessionId);
34943
- return row === void 0 ? new MissingAcpStoredSession() : new FoundAcpStoredSession(decodeSessionRow(row));
34944
- };
34945
- remove = (sessionId) => {
34946
- this.#database.prepare("DELETE FROM acp_sessions WHERE session_id = ?").run(sessionId);
34947
- };
34948
- findNative = (agentId, nativeSessionId) => this.#database.prepare("SELECT * FROM acp_sessions WHERE agent_id = ? AND native_session_id = ?").all(agentId, nativeSessionId).map(decodeSessionRow);
34949
- markDeleted = (agentId, nativeSessionId) => {
34950
- const ids = this.findNative(agentId, nativeSessionId).map((session) => session.sessionId);
34951
- this.#database.exec("BEGIN");
34952
- try {
34953
- for (const id of ids) {
34954
- this.#database.prepare("INSERT OR IGNORE INTO acp_deleted_sessions (session_id) VALUES (?)").run(id);
34955
- this.remove(id);
34956
- }
34957
- this.#database.exec("COMMIT");
34958
- return ids;
34959
- } catch (error62) {
34960
- this.#database.exec("ROLLBACK");
34961
- throw error62;
34962
- }
34963
- };
34964
- write = (session) => {
34965
- this.#database.prepare(
34966
- `
34967
- INSERT INTO acp_sessions (
34968
- session_id,
34969
- agent_id,
34970
- native_session_id,
34971
- cwd,
34972
- additional_directories_json,
34973
- prompted,
34974
- updated_at
34975
- ) VALUES (?, ?, ?, ?, ?, ?, ?)
34976
- ON CONFLICT(session_id) DO UPDATE SET
34977
- agent_id = excluded.agent_id,
34978
- native_session_id = excluded.native_session_id,
34979
- cwd = excluded.cwd,
34980
- additional_directories_json = excluded.additional_directories_json,
34981
- prompted = excluded.prompted,
34982
- updated_at = excluded.updated_at
34983
- `
34984
- ).run(
34985
- session.sessionId,
34986
- session.agentId,
34987
- session.nativeSessionId,
34988
- session.cwd,
34989
- JSON.stringify(session.additionalDirectories),
34990
- session.prompted ? 1 : 0,
34991
- (/* @__PURE__ */ new Date()).toISOString()
34992
- );
34993
- };
34994
- close = () => {
34995
- this.#database.close();
34996
- };
34997
- };
34998
34850
 
34999
34851
  // src/acp/session-manager.ts
35000
34852
  var PROCESS_STOP_TIMEOUT_MILLISECONDS = 1e3;
@@ -35221,7 +35073,7 @@ function truncate4(value, maximumLength) {
35221
35073
  function isRecord7(value) {
35222
35074
  return typeof value === "object" && value !== null && !Array.isArray(value);
35223
35075
  }
35224
- function readString4(value, fallback = "") {
35076
+ function readString3(value, fallback = "") {
35225
35077
  return typeof value === "string" ? value : fallback;
35226
35078
  }
35227
35079
  function arraysEqual(left, right) {
@@ -35254,8 +35106,8 @@ function normalizeElicitationOptions(schema) {
35254
35106
  for (const option of oneOf) {
35255
35107
  if (isRecord7(option) && typeof option["const"] === "string") {
35256
35108
  normalized.push({
35257
- description: truncate4(readString4(option["description"]), 500),
35258
- label: truncate4(readString4(option["title"], option["const"]), 255),
35109
+ description: truncate4(readString3(option["description"]), 500),
35110
+ label: truncate4(readString3(option["title"], option["const"]), 255),
35259
35111
  value: truncate4(option["const"], 500)
35260
35112
  });
35261
35113
  }
@@ -35306,8 +35158,8 @@ function normalizeElicitationFields(requestedSchema) {
35306
35158
  defaultBooleanValue: typeof defaultValue === "boolean" ? defaultValue : false,
35307
35159
  defaultNumberValue: typeof defaultValue === "number" && Number.isFinite(defaultValue) ? defaultValue : 0,
35308
35160
  defaultStringValue: typeof defaultValue === "string" ? truncate4(defaultValue, 1e4) : Array.isArray(defaultValue) ? truncate4(JSON.stringify(defaultValue), 1e4) : "",
35309
- description: truncate4(readString4(property["description"]), 500),
35310
- format: truncate4(readString4(property["format"]), 64),
35161
+ description: truncate4(readString3(property["description"]), 500),
35162
+ format: truncate4(readString3(property["format"]), 64),
35311
35163
  hasDefaultValue: defaultValue !== void 0 && defaultValue !== null,
35312
35164
  maximum: numericString(property["maximum"]),
35313
35165
  maximumLength: numericString(property["maxLength"] ?? property["maxItems"]),
@@ -35315,9 +35167,9 @@ function normalizeElicitationFields(requestedSchema) {
35315
35167
  minimumLength: numericString(property["minLength"] ?? property["minItems"]),
35316
35168
  name: truncate4(name, 128),
35317
35169
  options,
35318
- pattern: truncate4(readString4(property["pattern"]), 500),
35170
+ pattern: truncate4(readString3(property["pattern"]), 500),
35319
35171
  required: required2.has(name),
35320
- title: truncate4(readString4(property["title"], name), 255),
35172
+ title: truncate4(readString3(property["title"], name), 255),
35321
35173
  type: normalizedType
35322
35174
  });
35323
35175
  }
@@ -36156,6 +36008,17 @@ var AcpProcessSession = class _AcpProcessSession {
36156
36008
  );
36157
36009
  };
36158
36010
  nativeSessionId = () => this.#nativeSessionId;
36011
+ adoptNativeSessionId = (sessionId) => {
36012
+ if (this.#prompted || this.#nativeSessionId !== sessionId) {
36013
+ throw new AcpExecutionError("The new Codex Session cannot be adopted", {}, "session_identity_mismatch");
36014
+ }
36015
+ const previousSessionId = this.#mobiusSessionId;
36016
+ this.#store.write(
36017
+ new AcpStoredSession(sessionId, this.#agentId, sessionId, this.#cwd, this.#additionalDirectories, false)
36018
+ );
36019
+ this.#store.remove(previousSessionId);
36020
+ this.#mobiusSessionId = sessionId;
36021
+ };
36159
36022
  configure = async (options) => {
36160
36023
  const existing = this.#configOptions.find((option) => option.id === options.configId);
36161
36024
  if (existing === void 0 || existing.type !== options.valueType) {
@@ -36549,7 +36412,7 @@ var AcpProcessSession = class _AcpProcessSession {
36549
36412
  message: truncate4(request.message, 2e3),
36550
36413
  mode: request.mode,
36551
36414
  sessionId: this.#mobiusSessionId,
36552
- url: request.mode === "url" && typeof Reflect.get(request, "url") === "string" ? truncate4(readString4(Reflect.get(request, "url")), 4096) : ""
36415
+ url: request.mode === "url" && typeof Reflect.get(request, "url") === "string" ? truncate4(readString3(Reflect.get(request, "url")), 4096) : ""
36553
36416
  });
36554
36417
  return await pending.completion.promise;
36555
36418
  } finally {
@@ -36909,11 +36772,13 @@ var AcpSessionManager = class {
36909
36772
  #transientProcessCount = 0;
36910
36773
  #store;
36911
36774
  #nativeHistoryReader;
36775
+ #sessionIdentity;
36912
36776
  #observer;
36913
- constructor(observer = new NullAcpSessionObserver(), store = new MemoryAcpSessionStore(), nativeHistoryReader = null) {
36777
+ constructor(observer = new NullAcpSessionObserver(), store = new MemoryAcpSessionStore(), nativeHistoryReader = null, sessionIdentity = "assigned") {
36914
36778
  this.#observer = observer;
36915
36779
  this.#store = store;
36916
36780
  this.#nativeHistoryReader = nativeHistoryReader;
36781
+ this.#sessionIdentity = sessionIdentity;
36917
36782
  }
36918
36783
  setObserver = (observer) => {
36919
36784
  this.#observer = observer;
@@ -37025,7 +36890,13 @@ var AcpSessionManager = class {
37025
36890
  if (retained) {
37026
36891
  this.#sessions.delete(sessionId);
37027
36892
  }
37028
- await this.#retireProcess(runtime, retained, close);
36893
+ try {
36894
+ await this.#retireProcess(runtime, retained, close);
36895
+ } finally {
36896
+ if (retained && this.#sessionIdentity === "native") {
36897
+ this.#store.remove(sessionId);
36898
+ }
36899
+ }
37029
36900
  }
37030
36901
  async #retireNativeBrowserProcess(sessionId, runtime, close) {
37031
36902
  const retained = this.#nativeBrowserSessions.get(sessionId) === runtime;
@@ -37172,7 +37043,14 @@ var AcpSessionManager = class {
37172
37043
  try {
37173
37044
  return await this.#startRetainedSessionProcess(
37174
37045
  options,
37175
- async () => await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics)
37046
+ async () => await AcpProcessSession.start(
37047
+ 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(
37048
+ options.sessionId
37049
+ ) && this.#store.read(options.sessionId) instanceof MissingAcpStoredSession ? { ...options, origin: { kind: "import", nativeSessionId: options.sessionId } } : options,
37050
+ () => this.#observer,
37051
+ this.#store,
37052
+ metrics
37053
+ )
37176
37054
  );
37177
37055
  } finally {
37178
37056
  this.#preparing.delete(options.sessionId);
@@ -37595,6 +37473,45 @@ var AcpSessionManager = class {
37595
37473
  ]);
37596
37474
  };
37597
37475
  hasPreparedSession = (sessionId, agentId, cwd, additionalDirectories) => this.#sessions.get(sessionId)?.belongsTo(agentId, cwd, additionalDirectories) === true;
37476
+ createNativeSession = async (options) => {
37477
+ const temporarySessionId = `new-${crypto.randomUUID()}`;
37478
+ const temporaryOptions = { ...options, sessionId: temporarySessionId };
37479
+ this.#beginSessionUse(temporarySessionId);
37480
+ try {
37481
+ const runtime = await this.#startPreparation(temporaryOptions);
37482
+ let adopted = false;
37483
+ try {
37484
+ const nativeSessionId = runtime.nativeSessionId();
37485
+ 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)) {
37486
+ throw new AcpExecutionError(
37487
+ "Codex returned an invalid new Session ID",
37488
+ {},
37489
+ "invalid_native_session_response"
37490
+ );
37491
+ }
37492
+ runtime.adoptNativeSessionId(nativeSessionId);
37493
+ this.#sessions.delete(temporarySessionId);
37494
+ this.#sessions.set(nativeSessionId, runtime);
37495
+ this.#retainedProcesses.set(
37496
+ runtime,
37497
+ new FoundAcpSessionProcessEvictionCandidate(nativeSessionId, runtime)
37498
+ );
37499
+ adopted = true;
37500
+ return nativeSessionId;
37501
+ } finally {
37502
+ if (!adopted) {
37503
+ await this.#retireSessionProcess(
37504
+ temporarySessionId,
37505
+ runtime,
37506
+ async () => await runtime.closeProcess()
37507
+ );
37508
+ }
37509
+ }
37510
+ } finally {
37511
+ this.#store.remove(temporarySessionId);
37512
+ this.#endSessionUse(temporarySessionId);
37513
+ }
37514
+ };
37598
37515
  ensureSession = async (options) => {
37599
37516
  const existing = this.#sessions.get(options.sessionId);
37600
37517
  if (existing !== void 0) {
@@ -37688,6 +37605,25 @@ var AcpSessionManager = class {
37688
37605
  this.#endSessionUse(options.sessionId);
37689
37606
  }
37690
37607
  };
37608
+ loadLinkedSessionHistory = async (options) => {
37609
+ options.signal.throwIfAborted();
37610
+ const stored = this.#store.read(options.sessionId);
37611
+ if (!(stored instanceof FoundAcpStoredSession) || !stored.session.prompted) {
37612
+ return null;
37613
+ }
37614
+ const linked = stored.session;
37615
+ 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])) {
37616
+ throw new AcpExecutionError(
37617
+ "The session belongs to another Agent or workspace",
37618
+ {},
37619
+ "session_identity_mismatch"
37620
+ );
37621
+ }
37622
+ if (this.#nativeHistoryReader === null) {
37623
+ return await this.loadSessionHistory(options);
37624
+ }
37625
+ return await this.#nativeHistoryReader.read(options, linked.nativeSessionId);
37626
+ };
37691
37627
  openNativeSession = async (options, origin, loadHistory) => {
37692
37628
  const key = `${options.agent.id}:${origin.nativeSessionId}`;
37693
37629
  if (this.#nativeOperations.has(key)) {
@@ -38751,7 +38687,7 @@ var LocalAuthorizationError = class extends Error {
38751
38687
  // src/authorization/workspace-directory.ts
38752
38688
  import { readdir as readdir2, realpath as realpath8, stat as stat7 } from "node:fs/promises";
38753
38689
  import { homedir as homedir2 } from "node:os";
38754
- import { basename as basename4, dirname as dirname5, isAbsolute as isAbsolute10, join as join15, normalize as normalize4, relative as relative4 } from "node:path";
38690
+ import { basename as basename4, dirname as dirname3, isAbsolute as isAbsolute10, join as join15, normalize as normalize4, relative as relative4 } from "node:path";
38755
38691
  var WorkspaceDirectoryListing = class {
38756
38692
  directoryId;
38757
38693
  directoryLabel;
@@ -38875,7 +38811,7 @@ var WorkspaceDirectoryService = class {
38875
38811
  }
38876
38812
  }
38877
38813
  entries.sort((a, b) => a.name.localeCompare(b.name));
38878
- const parent = dirname5(target);
38814
+ const parent = dirname3(target);
38879
38815
  return new WorkspaceDirectoryListing(
38880
38816
  id,
38881
38817
  this.label(target),
@@ -38900,7 +38836,7 @@ var WorkspaceDirectoryService = class {
38900
38836
  };
38901
38837
 
38902
38838
  // src/daemon-diagnostic-log.ts
38903
- import { appendFileSync, mkdirSync as mkdirSync3, readFileSync as readFileSync2, renameSync, statSync as statSync3, writeFileSync } from "node:fs";
38839
+ import { appendFileSync, mkdirSync, readFileSync as readFileSync2, renameSync, statSync as statSync3, writeFileSync } from "node:fs";
38904
38840
  import { join as join16 } from "node:path";
38905
38841
  var MAXIMUM_DAEMON_LOG_BYTES = 1 * 1024 * 1024;
38906
38842
  var DaemonDiagnosticLog = class {
@@ -38916,7 +38852,7 @@ var DaemonDiagnosticLog = class {
38916
38852
  const encoded = `${diagnostic.replace(/[\r\n]+/gu, " ").trim()}
38917
38853
  `;
38918
38854
  const encodedBytes = Buffer.byteLength(encoded);
38919
- mkdirSync3(this.#directory, { mode: 448, recursive: true });
38855
+ mkdirSync(this.#directory, { mode: 448, recursive: true });
38920
38856
  let existingBytes = 0;
38921
38857
  try {
38922
38858
  existingBytes = statSync3(this.#path).size;
@@ -38969,7 +38905,7 @@ var turnsSchema = external_exports.object({
38969
38905
  error: external_exports.unknown().nullish(),
38970
38906
  items: external_exports.array(external_exports.unknown()).max(1e5)
38971
38907
  })
38972
- ).max(SESSION_HISTORY_PREVIEW_MESSAGE_LIMIT),
38908
+ ).max(SESSION_HISTORY_MESSAGE_LIMIT),
38973
38909
  nextCursor: external_exports.string().nullish()
38974
38910
  });
38975
38911
  var itemTypeSchema = external_exports.object({ type: external_exports.string().min(1).max(80) });
@@ -39156,7 +39092,7 @@ function decodeHistory(thread, value, options) {
39156
39092
  messages.push(message);
39157
39093
  characters += messageSize(message);
39158
39094
  }
39159
- while (messages.length > SESSION_HISTORY_PREVIEW_MESSAGE_LIMIT || characters > SESSION_HISTORY_CHARACTER_LIMIT) {
39095
+ while (messages.length > (options.detail === "rich" ? SESSION_HISTORY_MESSAGE_LIMIT : SESSION_HISTORY_PREVIEW_MESSAGE_LIMIT) || characters > SESSION_HISTORY_CHARACTER_LIMIT) {
39160
39096
  const removed = messages.shift();
39161
39097
  if (removed !== void 0) {
39162
39098
  characters -= messageSize(removed);
@@ -39196,6 +39132,7 @@ async function readCodexHistoryWithOptions(agent, cwd, nativeSessionId, signal,
39196
39132
  });
39197
39133
  const response = Promise.withResolvers();
39198
39134
  let state = { kind: "initializing", requestId: 1 };
39135
+ const seenCursors = /* @__PURE__ */ new Set();
39199
39136
  let pending = "";
39200
39137
  let receivedBytes = 0;
39201
39138
  const fail = (cause) => response.reject(
@@ -39262,7 +39199,7 @@ async function readCodexHistoryWithOptions(agent, cwd, nativeSessionId, signal,
39262
39199
  break;
39263
39200
  case "metadata": {
39264
39201
  const { thread } = threadSchema.parse(message.result);
39265
- state = { kind: "turns", requestId: 3, thread };
39202
+ state = { kind: "turns", requestId: 3, thread, pages: [] };
39266
39203
  send2({
39267
39204
  id: state.requestId,
39268
39205
  method: "thread/turns/list",
@@ -39275,9 +39212,45 @@ async function readCodexHistoryWithOptions(agent, cwd, nativeSessionId, signal,
39275
39212
  });
39276
39213
  break;
39277
39214
  }
39278
- case "turns":
39279
- response.resolve(decodeHistory(state.thread, message.result, options));
39280
- return;
39215
+ case "turns": {
39216
+ const page = turnsSchema.parse(message.result);
39217
+ const pages = [...state.pages, ...page.data];
39218
+ const maxTurns = options.detail === "rich" ? SESSION_HISTORY_MESSAGE_LIMIT : SESSION_HISTORY_PREVIEW_MESSAGE_LIMIT;
39219
+ if (page.nextCursor == null || pages.length >= maxTurns) {
39220
+ response.resolve(
39221
+ decodeHistory(
39222
+ state.thread,
39223
+ {
39224
+ data: pages.slice(0, maxTurns),
39225
+ nextCursor: page.nextCursor
39226
+ },
39227
+ options
39228
+ )
39229
+ );
39230
+ return;
39231
+ }
39232
+ if (page.data.length === 0 || seenCursors.has(page.nextCursor)) {
39233
+ throw new AcpExecutionError(
39234
+ "Codex repeated a history page cursor.",
39235
+ {},
39236
+ "invalid_native_session_response"
39237
+ );
39238
+ }
39239
+ seenCursors.add(page.nextCursor);
39240
+ state = { kind: "turns", requestId: state.requestId + 1, thread: state.thread, pages };
39241
+ send2({
39242
+ id: state.requestId,
39243
+ method: "thread/turns/list",
39244
+ params: {
39245
+ threadId: nativeSessionId,
39246
+ cursor: page.nextCursor,
39247
+ limit: Math.min(SESSION_HISTORY_PREVIEW_MESSAGE_LIMIT, maxTurns - pages.length),
39248
+ sortDirection: "desc",
39249
+ itemsView: options.detail === "rich" ? "full" : "summary"
39250
+ }
39251
+ });
39252
+ break;
39253
+ }
39281
39254
  default: {
39282
39255
  const unhandled = state;
39283
39256
  throw new Error(`Unknown history read state: ${String(unhandled)}`);
@@ -39298,7 +39271,7 @@ async function readCodexHistoryWithOptions(agent, cwd, nativeSessionId, signal,
39298
39271
  );
39299
39272
  const timeout = setTimeout(
39300
39273
  () => fail(new AcpExecutionError("Reading saved Codex history timed out.", {}, "native_history_timeout")),
39301
- 15e3
39274
+ options.detail === "rich" ? 6e4 : 15e3
39302
39275
  );
39303
39276
  child.stdout.setEncoding("utf8");
39304
39277
  child.stdout.on("data", onData);
@@ -39368,6 +39341,84 @@ var NativeSessionService = class {
39368
39341
  sessionId: command.sessionId,
39369
39342
  signal
39370
39343
  };
39344
+ if (command.action === "linked-history") {
39345
+ if (options.agent.id !== "codex") {
39346
+ const history = await this.#sessions.loadLinkedSessionHistory({
39347
+ ...options,
39348
+ sessionId: command.targetSessionId
39349
+ });
39350
+ this.record(command, "native_session_history_read");
39351
+ return history === null ? {
39352
+ action: "unlinked-history",
39353
+ kind: "native.session.result",
39354
+ requestId: command.requestId,
39355
+ sessionId: command.sessionId,
39356
+ targetSessionId: command.targetSessionId
39357
+ } : {
39358
+ action: "linked-history",
39359
+ history,
39360
+ kind: "native.session.result",
39361
+ requestId: command.requestId,
39362
+ sessionId: command.sessionId,
39363
+ targetSessionId: command.targetSessionId
39364
+ };
39365
+ }
39366
+ const nativeSessionId = nativeSessionIdSchema.parse(command.targetSessionId);
39367
+ if (this.#sessions.hasPreparedSession(nativeSessionId, options.agent.id, cwd, additionalDirectories) && await this.#sessions.loadLinkedSessionHistory({ ...options, sessionId: nativeSessionId }) === null) {
39368
+ this.record(command, "native_session_history_read");
39369
+ return {
39370
+ action: "linked-history",
39371
+ history: {
39372
+ status: "available",
39373
+ messages: [],
39374
+ truncated: false,
39375
+ coveredCommandIds: [],
39376
+ coveredMessageIds: []
39377
+ },
39378
+ kind: "native.session.result",
39379
+ requestId: command.requestId,
39380
+ sessionId: command.sessionId,
39381
+ targetSessionId: command.targetSessionId
39382
+ };
39383
+ }
39384
+ const snapshot = await readCodexFullHistory(options.agent, cwd, nativeSessionId, signal);
39385
+ const resolved = await this.#directories.identify(command.bindingId, snapshot.cwd, signal);
39386
+ if (snapshot.nativeSessionId !== nativeSessionId || resolved.path !== cwd) {
39387
+ throw new AcpExecutionError(
39388
+ "Codex returned history for a different session or workspace.",
39389
+ {},
39390
+ "invalid_native_session_response"
39391
+ );
39392
+ }
39393
+ this.record(command, "native_session_history_read");
39394
+ return {
39395
+ action: "linked-history",
39396
+ history: snapshot.history,
39397
+ kind: "native.session.result",
39398
+ requestId: command.requestId,
39399
+ sessionId: command.sessionId,
39400
+ targetSessionId: command.targetSessionId
39401
+ };
39402
+ }
39403
+ if (command.action === "create") {
39404
+ if (options.agent.id !== "codex") {
39405
+ throw new AcpExecutionError(
39406
+ "Native session creation is unavailable for this Agent",
39407
+ {},
39408
+ "native_session_unsupported"
39409
+ );
39410
+ }
39411
+ const nativeSessionId = await this.#sessions.createNativeSession(options);
39412
+ signal.throwIfAborted();
39413
+ this.record(command, "native_session_created");
39414
+ return {
39415
+ action: "create",
39416
+ kind: "native.session.result",
39417
+ nativeSessionId,
39418
+ requestId: command.requestId,
39419
+ sessionId: command.sessionId
39420
+ };
39421
+ }
39371
39422
  const prepared = await this.#sessions.prepareNativeSessionBrowser(options);
39372
39423
  if (!prepared.capabilities.listSessions) {
39373
39424
  throw new AcpExecutionError(
@@ -39395,6 +39446,7 @@ var NativeSessionService = class {
39395
39446
  });
39396
39447
  return {
39397
39448
  entryId,
39449
+ nativeSessionId: info.sessionId,
39398
39450
  title: info.title ?? "Untitled session",
39399
39451
  directoryId: authorized.directoryId,
39400
39452
  directoryLabel: authorized.directoryLabel,
@@ -39500,6 +39552,18 @@ var NativeSessionService = class {
39500
39552
  );
39501
39553
  }
39502
39554
  const target = await this.resolveTarget(command, options, selected);
39555
+ if (command.action === "history") {
39556
+ const history = await this.readHistory(command, options, target, signal);
39557
+ signal.throwIfAborted();
39558
+ this.record(command, "native_session_history_read");
39559
+ return {
39560
+ ...envelope2,
39561
+ action: "history",
39562
+ entryId: command.entryId,
39563
+ history,
39564
+ title: target.info.title ?? "Untitled session"
39565
+ };
39566
+ }
39503
39567
  if (command.action === "preview") {
39504
39568
  const history = await this.previewHistory(command, options, target, signal);
39505
39569
  signal.throwIfAborted();
@@ -39673,6 +39737,25 @@ var NativeSessionService = class {
39673
39737
  }
39674
39738
  return snapshot.history;
39675
39739
  };
39740
+ readHistory = async (command, options, target, signal) => {
39741
+ if (options.agent.id !== "codex") {
39742
+ throw new AcpExecutionError(
39743
+ "Native history is unavailable for this Agent",
39744
+ {},
39745
+ "native_session_unsupported"
39746
+ );
39747
+ }
39748
+ const snapshot = await readCodexFullHistory(options.agent, target.cwd, target.info.sessionId, signal);
39749
+ const resolved = await this.#directories.identify(command.bindingId, snapshot.cwd, signal);
39750
+ if (snapshot.nativeSessionId !== target.info.sessionId || resolved.path !== target.cwd) {
39751
+ throw new AcpExecutionError(
39752
+ "Codex returned history for a different session or workspace.",
39753
+ {},
39754
+ "invalid_native_session_response"
39755
+ );
39756
+ }
39757
+ return snapshot.history;
39758
+ };
39676
39759
  authorizeEntry = async (command, options, info) => {
39677
39760
  try {
39678
39761
  const primary = await this.#directories.identify(command.bindingId, info.cwd, options.signal);
@@ -40468,26 +40551,26 @@ var RelayConnectionLiveness = class {
40468
40551
  };
40469
40552
 
40470
40553
  // src/relay-connection/session-event-outbox.ts
40471
- import { mkdirSync as mkdirSync4 } from "node:fs";
40472
- import { dirname as dirname6 } from "node:path";
40473
- import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
40554
+ import { createHash as createHash3 } from "node:crypto";
40555
+ import { DatabaseSync } from "node:sqlite";
40474
40556
  var DEFAULT_OUTBOX_LIMITS = {
40475
40557
  criticalEventBytes: 136 * 1024 * 1024,
40476
40558
  runtimeDeliveryBytes: 64 * 1024 * 1024,
40477
40559
  runtimeDeliveryCount: 64,
40478
40560
  standardEventBytes: 128 * 1024 * 1024
40479
40561
  };
40562
+ var MAX_TERMINAL_RECEIPTS = 1024;
40480
40563
  var SessionEventOutboxCapacityError = class extends Error {
40481
40564
  code = "session_event_outbox_full";
40482
40565
  constructor() {
40483
- super("The durable Session event outbox is full");
40566
+ super("The in-memory Session event outbox is full");
40484
40567
  this.name = "SessionEventOutboxCapacityError";
40485
40568
  }
40486
40569
  };
40487
40570
  var RuntimeDeliveryInboxCapacityError = class extends Error {
40488
40571
  code = "runtime_delivery_inbox_full";
40489
40572
  constructor() {
40490
- super("The durable Runtime delivery inbox is full");
40573
+ super("The in-memory Runtime delivery inbox is full");
40491
40574
  this.name = "RuntimeDeliveryInboxCapacityError";
40492
40575
  }
40493
40576
  };
@@ -40532,11 +40615,10 @@ function rowString(row, field) {
40532
40615
  var SessionEventOutbox = class {
40533
40616
  #database;
40534
40617
  #limits;
40535
- constructor(path2, limits = DEFAULT_OUTBOX_LIMITS) {
40618
+ constructor(limits = DEFAULT_OUTBOX_LIMITS) {
40536
40619
  validateLimits(limits);
40537
40620
  this.#limits = limits;
40538
- mkdirSync4(dirname6(path2), { recursive: true });
40539
- this.#database = new DatabaseSync3(path2);
40621
+ this.#database = new DatabaseSync(":memory:");
40540
40622
  this.#database.exec(`
40541
40623
  CREATE TABLE IF NOT EXISTS relay_session_event_outbox (
40542
40624
  ordinal INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -40564,7 +40646,7 @@ var SessionEventOutbox = class {
40564
40646
  CREATE TABLE IF NOT EXISTS relay_turn_receipts (
40565
40647
  command_id TEXT PRIMARY KEY,
40566
40648
  session_id TEXT NOT NULL,
40567
- command_json TEXT NOT NULL,
40649
+ command_hash TEXT NOT NULL,
40568
40650
  attempt_id TEXT NOT NULL,
40569
40651
  state TEXT NOT NULL CHECK (
40570
40652
  state IN ('dispatching', 'running', 'succeeded', 'failed', 'cancelled')
@@ -40595,19 +40677,20 @@ var SessionEventOutbox = class {
40595
40677
  `);
40596
40678
  }
40597
40679
  claimExecution = (commandId, sessionId, commandJson) => {
40680
+ const commandHash = createHash3("sha256").update(commandJson).digest("hex");
40598
40681
  this.#database.exec("BEGIN IMMEDIATE");
40599
40682
  try {
40600
40683
  const existing = this.#database.prepare(
40601
- `SELECT session_id, command_json, attempt_id, state
40684
+ `SELECT session_id, command_hash, attempt_id, state
40602
40685
  FROM relay_turn_receipts WHERE command_id = ?`
40603
40686
  ).get(commandId);
40604
40687
  if (typeof existing === "object" && existing !== null) {
40605
40688
  const storedSessionId = Reflect.get(existing, "session_id");
40606
- const storedCommand = Reflect.get(existing, "command_json");
40689
+ const storedCommandHash = Reflect.get(existing, "command_hash");
40607
40690
  const attemptId2 = Reflect.get(existing, "attempt_id");
40608
40691
  const state = Reflect.get(existing, "state");
40609
- if (storedSessionId !== sessionId || storedCommand !== commandJson || typeof attemptId2 !== "string" || !isDaemonExecutionState(state)) {
40610
- throw new Error("The daemon command identity conflicts with its durable receipt");
40692
+ if (storedSessionId !== sessionId || storedCommandHash !== commandHash || typeof attemptId2 !== "string" || !isDaemonExecutionState(state)) {
40693
+ throw new Error("The daemon command identity conflicts with its in-memory receipt");
40611
40694
  }
40612
40695
  this.#database.exec("COMMIT");
40613
40696
  return { attemptId: attemptId2, commandId, kind: "duplicate", state };
@@ -40615,9 +40698,9 @@ var SessionEventOutbox = class {
40615
40698
  const attemptId = crypto.randomUUID();
40616
40699
  this.#database.prepare(
40617
40700
  `INSERT INTO relay_turn_receipts (
40618
- command_id, session_id, command_json, attempt_id, state
40701
+ command_id, session_id, command_hash, attempt_id, state
40619
40702
  ) VALUES (?, ?, ?, ?, 'dispatching')`
40620
- ).run(commandId, sessionId, commandJson, attemptId);
40703
+ ).run(commandId, sessionId, commandHash, attemptId);
40621
40704
  this.#database.exec("COMMIT");
40622
40705
  return {
40623
40706
  attemptId,
@@ -40644,11 +40727,21 @@ var SessionEventOutbox = class {
40644
40727
  throw new Error("The daemon execution transition is invalid");
40645
40728
  }
40646
40729
  this.#database.prepare(`UPDATE relay_turn_receipts SET state = ? WHERE command_id = ?`).run(state, commandId);
40730
+ if (state === "succeeded" || state === "failed" || state === "cancelled") {
40731
+ this.#database.prepare(
40732
+ `DELETE FROM relay_turn_receipts
40733
+ WHERE state IN ('succeeded', 'failed', 'cancelled')
40734
+ AND rowid NOT IN (
40735
+ SELECT rowid FROM relay_turn_receipts
40736
+ WHERE state IN ('succeeded', 'failed', 'cancelled')
40737
+ ORDER BY rowid DESC LIMIT ?
40738
+ )`
40739
+ ).run(MAX_TERMINAL_RECEIPTS);
40740
+ }
40647
40741
  };
40648
40742
  /**
40649
- * The Attempt this Runtime durably claimed for a command, when that Attempt never reached a
40650
- * terminal state. A restarted Runtime has no in-memory Turn for a command it was executing before
40651
- * the restart, so this is the only record of the Attempt identity the Relay is still waiting on.
40743
+ * The Attempt this live Runtime claimed for a command that has not reached a terminal state.
40744
+ * Receipts disappear when the daemon process exits.
40652
40745
  */
40653
40746
  findUnsettledAttemptId = (commandId, sessionId) => {
40654
40747
  const row = this.#database.prepare(`SELECT attempt_id, state FROM relay_turn_receipts WHERE command_id = ? AND session_id = ?`).get(commandId, sessionId);
@@ -40697,7 +40790,7 @@ var SessionEventOutbox = class {
40697
40790
  WHERE event_id = ? AND session_id = ?`
40698
40791
  ).run(rejection.eventId, rejection.sessionId);
40699
40792
  if (deletion.changes !== 1) {
40700
- throw new Error("The rejected session event could not be removed from the durable outbox");
40793
+ throw new Error("The rejected session event could not be removed from the in-memory outbox");
40701
40794
  }
40702
40795
  this.#decrementEventState(byteLength);
40703
40796
  this.#database.exec("COMMIT");
@@ -40716,7 +40809,7 @@ var SessionEventOutbox = class {
40716
40809
  enqueueCritical = (sessionId, payload, attemptId = "") => this.#enqueueBounded(sessionId, payload, attemptId, this.#limits.criticalEventBytes);
40717
40810
  /**
40718
40811
  * Bytes still available to standard Session events. The daemon uses this to shed
40719
- * superseded streaming events instead of filling the durable outbox, so a long Turn
40812
+ * superseded streaming events instead of filling the in-memory outbox, so a long Turn
40720
40813
  * behind a slow Relay cannot make the next enqueue throw.
40721
40814
  */
40722
40815
  standardCapacityRemaining = () => {
@@ -40741,7 +40834,7 @@ var SessionEventOutbox = class {
40741
40834
  const payload = rowString(existing, "payload_json");
40742
40835
  const state = runtimeDeliveryState(existing);
40743
40836
  if (sessionId !== delivery.sessionId || payload !== delivery.payload) {
40744
- throw new Error("The Runtime delivery identity conflicts with its durable receipt");
40837
+ throw new Error("The Runtime delivery identity conflicts with its in-memory receipt");
40745
40838
  }
40746
40839
  this.#database.exec("COMMIT");
40747
40840
  return new StoredRuntimeDelivery(delivery.deliveryId, sessionId, payload, state, true);
@@ -40909,7 +41002,7 @@ var SessionEventOutbox = class {
40909
41002
  WHERE event_id = ? AND session_id = ?`
40910
41003
  ).run(eventId, sessionId);
40911
41004
  if (deletion.changes !== 1) {
40912
- throw new Error("The acknowledged session event could not be removed from the durable outbox");
41005
+ throw new Error("The acknowledged session event could not be removed from the in-memory outbox");
40913
41006
  }
40914
41007
  this.#decrementEventState(byteLength);
40915
41008
  this.#database.exec("COMMIT");
@@ -41391,7 +41484,7 @@ var DaemonSessionEventPublisher = class {
41391
41484
  };
41392
41485
  /**
41393
41486
  * Enqueue a standard event, shedding it instead of ending the daemon when the
41394
- * durable outbox is full.
41487
+ * in-memory outbox is full.
41395
41488
  *
41396
41489
  * A capacity error used to escape the coalescing timer that publishes activities,
41397
41490
  * so the process exited and every restart died on the same retained backlog. A full
@@ -41434,7 +41527,7 @@ var DaemonSessionEventPublisher = class {
41434
41527
  return;
41435
41528
  }
41436
41529
  this.#shedEventKinds.add(kind);
41437
- console.warn(`Mobius daemon is dropping durable "${kind}" events because the Session event outbox is full`);
41530
+ console.warn(`Mobius daemon is dropping queued "${kind}" events because the Session event outbox is full`);
41438
41531
  };
41439
41532
  acknowledge = (acknowledgement) => {
41440
41533
  if (!this.#outbox.acknowledge(acknowledgement)) {
@@ -41948,7 +42041,7 @@ function settingsRevision(agent, reportedAgentVersion, settings, modelEffort) {
41948
42041
  unsupportedModelIds: modelEffort.unsupportedModelIds,
41949
42042
  valuesByModel: {}
41950
42043
  };
41951
- return createHash3("sha256").update(
42044
+ return createHash4("sha256").update(
41952
42045
  JSON.stringify({
41953
42046
  adapterVersion: agent.kind === "acp-adapter-process" ? agent.adapterVersion : agent.agentVersion,
41954
42047
  agentId: agent.id,
@@ -42943,7 +43036,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
42943
43036
  if (connectionController.signal.aborted) {
42944
43037
  return;
42945
43038
  }
42946
- console.error("Mobius daemon could not process a durable Runtime delivery", error62);
43039
+ console.error("Mobius daemon could not process a in-memory Runtime delivery", error62);
42947
43040
  failAndClose(
42948
43041
  new Error("Runtime delivery processing failed", { cause: error62 }),
42949
43042
  4008,
@@ -43746,8 +43839,8 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
43746
43839
  publishCatalog: async (installationSignal) => await publishAgentCatalog(config2, installationSignal),
43747
43840
  stateDirectory
43748
43841
  });
43749
- const sessionStore = new SqliteAcpSessionStore(config2.auditDatabasePath);
43750
- const outbox = new SessionEventOutbox(config2.auditDatabasePath);
43842
+ const sessionStore = new MemoryAcpSessionStore();
43843
+ const outbox = new SessionEventOutbox();
43751
43844
  const publisher = new DaemonSessionEventPublisher(outbox, timer);
43752
43845
  const activeTurns = /* @__PURE__ */ new Map();
43753
43846
  const activeAttemptIds = /* @__PURE__ */ new Map();
@@ -43759,9 +43852,14 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
43759
43852
  }
43760
43853
  publisher.recordAttempt(sessionId, event, attemptId);
43761
43854
  };
43762
- const sessions = new AcpSessionManager(new DaemonAcpObserver(recordSessionEvent), sessionStore, {
43763
- read: async (options2, nativeSessionId) => options2.agent.id === "codex" ? (await readCodexFullHistory(options2.agent, options2.cwd, nativeSessionId, options2.signal)).history : null
43764
- });
43855
+ const sessions = new AcpSessionManager(
43856
+ new DaemonAcpObserver(recordSessionEvent),
43857
+ sessionStore,
43858
+ {
43859
+ read: async (options2, nativeSessionId) => options2.agent.id === "codex" ? (await readCodexFullHistory(options2.agent, options2.cwd, nativeSessionId, options2.signal)).history : null
43860
+ },
43861
+ "native"
43862
+ );
43765
43863
  const directories = new WorkspaceDirectoryService(config2.bindingId, config2.defaultWorkspace);
43766
43864
  const installationObserver = new DaemonInstallationObserver();
43767
43865
  const diagnostics = new RelayConnectionDiagnostics(
@@ -43897,13 +43995,9 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
43897
43995
  await sessions.close();
43898
43996
  } finally {
43899
43997
  try {
43900
- sessionStore.close();
43998
+ publisher.close();
43901
43999
  } finally {
43902
- try {
43903
- publisher.close();
43904
- } finally {
43905
- outbox.close();
43906
- }
44000
+ outbox.close();
43907
44001
  }
43908
44002
  }
43909
44003
  }
@@ -43919,9 +44013,9 @@ import { basename as basename7, resolve as resolve6 } from "node:path";
43919
44013
  import { fetch as fetch5 } from "undici";
43920
44014
 
43921
44015
  // src/storage/runtime-installation-store.ts
43922
- import { createHash as createHash4, randomUUID as randomUUID4 } from "node:crypto";
44016
+ import { createHash as createHash5, randomUUID as randomUUID4 } from "node:crypto";
43923
44017
  import { mkdir as mkdir4, open as open5, readdir as readdir3, rename as rename3, unlink, writeFile as writeFile3 } from "node:fs/promises";
43924
- import { dirname as dirname7, join as join17, resolve as resolve5 } from "node:path";
44018
+ import { dirname as dirname4, join as join17, resolve as resolve5 } from "node:path";
43925
44019
  var APPLICATION_ID_PATTERN = /^[a-z][a-z0-9]*(?:[.-][a-z0-9]+){1,31}$/;
43926
44020
  var CONNECTION_ID_PATTERN = /^mcn_[a-f0-9]{32}$/;
43927
44021
  var INSTALLATION_ID_PATTERN = /^min_[a-f0-9]{32}$/;
@@ -44114,7 +44208,7 @@ function installationId() {
44114
44208
  return `min_${randomUUID4().replaceAll("-", "")}`;
44115
44209
  }
44116
44210
  function channelIndexFileName(channelId) {
44117
- return `mci_${createHash4("sha256").update(channelId).digest("hex")}.json`;
44211
+ return `mci_${createHash5("sha256").update(channelId).digest("hex")}.json`;
44118
44212
  }
44119
44213
  function decodeInstallationPointer(value) {
44120
44214
  if (!isRecord9(value) || !hasExactKeys(value, INSTALLATION_POINTER_KEYS) || value["version"] !== 1) {
@@ -44262,7 +44356,7 @@ async function readJsonFile(path2, signal, missingCode) {
44262
44356
  }
44263
44357
  async function writeJsonAtomically(path2, value, signal) {
44264
44358
  signal.throwIfAborted();
44265
- const directory = dirname7(path2);
44359
+ const directory = dirname4(path2);
44266
44360
  const temporaryPath = join17(directory, `.${randomUUID4()}.tmp`);
44267
44361
  try {
44268
44362
  await mkdir4(directory, { mode: 448, recursive: true });
@@ -44325,7 +44419,6 @@ var RuntimeInstallationStore = class _RuntimeInstallationStore {
44325
44419
  return new _RuntimeInstallationStore(applicationId, storedInstallationId, stateDirectory);
44326
44420
  };
44327
44421
  connectionPath = (connectionId2) => join17(this.#connectionDirectory, `${validateConnectionId(connectionId2)}.json`);
44328
- auditDatabasePath = (connectionId2) => join17(this.stateDirectory, "audit", `${validateConnectionId(connectionId2)}.sqlite`);
44329
44422
  channelIndexPath = (channelId) => join17(this.#channelDirectory, channelIndexFileName(validateIdentifier(channelId, "invalid_channel_id")));
44330
44423
  readConnection = async (connectionId2, signal) => {
44331
44424
  const stored = decodeConnection(
@@ -44718,7 +44811,6 @@ function buildPairedDaemon(installation, connection, defaultWorkspace, inventory
44718
44811
  config: createDaemonConfig(
44719
44812
  {
44720
44813
  defaultWorkspace,
44721
- auditDatabasePath: installation.auditDatabasePath(connection.connectionId),
44722
44814
  channelId: connection.channelId,
44723
44815
  relayUrl
44724
44816
  },
@@ -44840,7 +44932,6 @@ function loadMobiusRuntimeConnection(environment = process.env) {
44840
44932
  throw new MobiusRuntimeConfigurationError("MOBIUS_CHANNEL_ID is invalid");
44841
44933
  }
44842
44934
  return Object.freeze({
44843
- auditDatabasePath: environment["MOBIUS_AUDIT_DATABASE"]?.trim() || join18(readStateDirectory(environment), "audit", `${channelId}.sqlite`),
44844
44935
  channelId,
44845
44936
  defaultWorkspace: loadDefaultWorkspace(environment),
44846
44937
  relayUrl: requiredEnvironmentValue(environment, "MOBIUS_RELAY_URL"),
@@ -44869,8 +44960,6 @@ async function createMobiusRuntimeEngine(connection, signal, environment = proce
44869
44960
  const localContext = new DaemonLocalContext(readStateDirectory(environment), environment);
44870
44961
  const relayUrl = relayUrlFromConnection(connection);
44871
44962
  const defaultWorkspace = await resolveWorkspace(connection.defaultWorkspace);
44872
- const auditDatabasePath = resolve7(connection.auditDatabasePath);
44873
- await mkdir6(dirname8(auditDatabasePath), { recursive: true, mode: 448 });
44874
44963
  const inventory = await discoverLocalAgentInventory({
44875
44964
  defaultWorkspace,
44876
44965
  environment: localContext.environment,
@@ -44882,7 +44971,6 @@ async function createMobiusRuntimeEngine(connection, signal, environment = proce
44882
44971
  return new MobiusRuntimeEngine(
44883
44972
  createDaemonConfig(
44884
44973
  {
44885
- auditDatabasePath,
44886
44974
  channelId: connection.channelId,
44887
44975
  defaultWorkspace,
44888
44976
  relayUrl
@@ -44908,7 +44996,7 @@ var MobiusRuntimeEngine = class {
44908
44996
  }
44909
44997
  signal.throwIfAborted();
44910
44998
  this.#state = new RunningMobiusRuntimeState();
44911
- const audit = new AuditStore(this.#config.auditDatabasePath);
44999
+ const audit = new AuditStore();
44912
45000
  try {
44913
45001
  await runDaemon(this.#config, audit, signal, void 0, {
44914
45002
  ...this.#options.onConnectionStatus === void 0 ? {} : { onConnectionStatus: this.#options.onConnectionStatus },