@moxt-ai/mobius 0.0.93 → 0.0.96

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 (119) 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/elicitation.d.ts +5 -0
  7. package/dist/acp/elicitation.d.ts.map +1 -0
  8. package/dist/acp/elicitation.js +186 -0
  9. package/dist/acp/elicitation.js.map +1 -0
  10. package/dist/acp/process-capacity.d.ts +12 -0
  11. package/dist/acp/process-capacity.d.ts.map +1 -0
  12. package/dist/acp/process-capacity.js +90 -0
  13. package/dist/acp/process-capacity.js.map +1 -0
  14. package/dist/acp/process-session.d.ts +166 -0
  15. package/dist/acp/process-session.d.ts.map +1 -0
  16. package/dist/acp/process-session.js +1300 -0
  17. package/dist/acp/process-session.js.map +1 -0
  18. package/dist/acp/session-config/apply-session-configuration.d.ts +9 -0
  19. package/dist/acp/session-config/apply-session-configuration.d.ts.map +1 -0
  20. package/dist/acp/session-config/apply-session-configuration.js +141 -0
  21. package/dist/acp/session-config/apply-session-configuration.js.map +1 -0
  22. package/dist/acp/session-manager.d.ts +8 -161
  23. package/dist/acp/session-manager.d.ts.map +1 -1
  24. package/dist/acp/session-manager.js +73 -1571
  25. package/dist/acp/session-manager.js.map +1 -1
  26. package/dist/acp/session-store.d.ts +3 -10
  27. package/dist/acp/session-store.d.ts.map +1 -1
  28. package/dist/acp/session-store.js +1 -131
  29. package/dist/acp/session-store.js.map +1 -1
  30. package/dist/acp/value-utils.d.ts +4 -0
  31. package/dist/acp/value-utils.d.ts.map +1 -0
  32. package/dist/acp/value-utils.js +10 -0
  33. package/dist/acp/value-utils.js.map +1 -0
  34. package/dist/agent-catalog/agent-settings-adapter.d.ts +5 -18
  35. package/dist/agent-catalog/agent-settings-adapter.d.ts.map +1 -1
  36. package/dist/agent-catalog/agent-settings-adapter.js +7 -161
  37. package/dist/agent-catalog/agent-settings-adapter.js.map +1 -1
  38. package/dist/agent-catalog/agent-settings-base.d.ts +26 -0
  39. package/dist/agent-catalog/agent-settings-base.d.ts.map +1 -0
  40. package/dist/agent-catalog/agent-settings-base.js +66 -0
  41. package/dist/agent-catalog/agent-settings-base.js.map +1 -0
  42. package/dist/agent-catalog/agents/codex-settings-adapter.d.ts +5 -0
  43. package/dist/agent-catalog/agents/codex-settings-adapter.d.ts.map +1 -0
  44. package/dist/agent-catalog/agents/codex-settings-adapter.js +6 -0
  45. package/dist/agent-catalog/agents/codex-settings-adapter.js.map +1 -0
  46. package/dist/agent-catalog/agents/deepseek-settings-adapter.d.ts +9 -0
  47. package/dist/agent-catalog/agents/deepseek-settings-adapter.d.ts.map +1 -0
  48. package/dist/agent-catalog/agents/deepseek-settings-adapter.js +26 -0
  49. package/dist/agent-catalog/agents/deepseek-settings-adapter.js.map +1 -0
  50. package/dist/agent-catalog/agents/opencode-settings-adapter.d.ts +9 -0
  51. package/dist/agent-catalog/agents/opencode-settings-adapter.d.ts.map +1 -0
  52. package/dist/agent-catalog/agents/opencode-settings-adapter.js +74 -0
  53. package/dist/agent-catalog/agents/opencode-settings-adapter.js.map +1 -0
  54. package/dist/agent-catalog/discover-agent-settings.d.ts +10 -0
  55. package/dist/agent-catalog/discover-agent-settings.d.ts.map +1 -0
  56. package/dist/agent-catalog/discover-agent-settings.js +252 -0
  57. package/dist/agent-catalog/discover-agent-settings.js.map +1 -0
  58. package/dist/audit/audit-store.d.ts +3 -4
  59. package/dist/audit/audit-store.d.ts.map +1 -1
  60. package/dist/audit/audit-store.js +10 -37
  61. package/dist/audit/audit-store.js.map +1 -1
  62. package/dist/cli.js +1699 -1624
  63. package/dist/cli.js.map +4 -4
  64. package/dist/config.d.ts +0 -2
  65. package/dist/config.d.ts.map +1 -1
  66. package/dist/config.js +2 -6
  67. package/dist/config.js.map +1 -1
  68. package/dist/daemon-manager.d.ts.map +1 -1
  69. package/dist/daemon-manager.js +13 -19
  70. package/dist/daemon-manager.js.map +1 -1
  71. package/dist/index.js +1696 -1622
  72. package/dist/index.js.map +4 -4
  73. package/dist/native-sessions/agent-adapter.d.ts +17 -0
  74. package/dist/native-sessions/agent-adapter.d.ts.map +1 -0
  75. package/dist/native-sessions/agent-adapter.js +22 -0
  76. package/dist/native-sessions/agent-adapter.js.map +1 -0
  77. package/dist/native-sessions/chat-agent.d.ts +3 -0
  78. package/dist/native-sessions/chat-agent.d.ts.map +1 -0
  79. package/dist/native-sessions/chat-agent.js +5 -0
  80. package/dist/native-sessions/chat-agent.js.map +1 -0
  81. package/dist/native-sessions/claude-adapter.d.ts +3 -0
  82. package/dist/native-sessions/claude-adapter.d.ts.map +1 -0
  83. package/dist/native-sessions/claude-adapter.js +7 -0
  84. package/dist/native-sessions/claude-adapter.js.map +1 -0
  85. package/dist/native-sessions/claude-history.d.ts +6 -0
  86. package/dist/native-sessions/claude-history.d.ts.map +1 -0
  87. package/dist/native-sessions/claude-history.js +27 -0
  88. package/dist/native-sessions/claude-history.js.map +1 -0
  89. package/dist/native-sessions/codex-adapter.d.ts +3 -0
  90. package/dist/native-sessions/codex-adapter.d.ts.map +1 -0
  91. package/dist/native-sessions/codex-adapter.js +21 -0
  92. package/dist/native-sessions/codex-adapter.js.map +1 -0
  93. package/dist/native-sessions/service.d.ts +0 -2
  94. package/dist/native-sessions/service.d.ts.map +1 -1
  95. package/dist/native-sessions/service.js +70 -32
  96. package/dist/native-sessions/service.js.map +1 -1
  97. package/dist/pairing/pair-local-machine.d.ts.map +1 -1
  98. package/dist/pairing/pair-local-machine.js +0 -1
  99. package/dist/pairing/pair-local-machine.js.map +1 -1
  100. package/dist/relay-connection/coalescing-narration-publisher.d.ts +1 -1
  101. package/dist/relay-connection/coalescing-narration-publisher.js +1 -1
  102. package/dist/relay-connection/coalescing-text-publisher.d.ts +1 -1
  103. package/dist/relay-connection/coalescing-text-publisher.js +1 -1
  104. package/dist/relay-connection/session-event-outbox.d.ts +4 -5
  105. package/dist/relay-connection/session-event-outbox.d.ts.map +1 -1
  106. package/dist/relay-connection/session-event-outbox.js +31 -21
  107. package/dist/relay-connection/session-event-outbox.js.map +1 -1
  108. package/dist/run-daemon.d.ts.map +1 -1
  109. package/dist/run-daemon.js +17 -406
  110. package/dist/run-daemon.js.map +1 -1
  111. package/dist/runtime.d.ts +0 -1
  112. package/dist/runtime.d.ts.map +1 -1
  113. package/dist/runtime.js +1633 -1557
  114. package/dist/runtime.js.map +4 -4
  115. package/dist/storage/runtime-installation-store.d.ts +0 -1
  116. package/dist/storage/runtime-installation-store.d.ts.map +1 -1
  117. package/dist/storage/runtime-installation-store.js +0 -1
  118. package/dist/storage/runtime-installation-store.js.map +1 -1
  119. 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
@@ -25070,6 +25038,7 @@ var encodeAgentInstallCancelledEvent = (message) => encode3(message, agentInstal
25070
25038
 
25071
25039
  // ../protocol/src/messages.ts
25072
25040
  var SESSION_PROMPT_KIND = "session.prompt";
25041
+ var RUNTIME_WORKSPACE_BINDING_ID = "workspace";
25073
25042
  var SESSION_CANCEL_KIND = "session.cancel";
25074
25043
  var RUNTIME_LIVENESS_READY_KIND = "runtime.liveness.ready";
25075
25044
  var RUNTIME_HEARTBEAT_KIND = "runtime.heartbeat";
@@ -25676,6 +25645,8 @@ var nativeSessionTurnForkCommandSchema = external_exports.strictObject({
25676
25645
  title: external_exports.string().max(500)
25677
25646
  }).readonly();
25678
25647
  var nativeSessionRequestSchema = external_exports.discriminatedUnion("action", [
25648
+ external_exports.strictObject({ ...identity, action: external_exports.literal("create") }).readonly(),
25649
+ external_exports.strictObject({ ...identity, action: external_exports.literal("linked-history"), targetSessionId: identifier }).readonly(),
25679
25650
  external_exports.strictObject({ ...identity, action: external_exports.literal("preview"), entryId: identifier }).readonly(),
25680
25651
  external_exports.strictObject({ ...identity, action: external_exports.literal("history"), entryId: identifier }).readonly(),
25681
25652
  external_exports.strictObject({ ...identity, action: external_exports.literal("find"), nativeSessionId: identifier }).readonly(),
@@ -25697,6 +25668,8 @@ var nativeSessionRequestSchema = external_exports.discriminatedUnion("action", [
25697
25668
  }).readonly()
25698
25669
  ]);
25699
25670
  var nativeSessionCommandSchema = external_exports.discriminatedUnion("action", [
25671
+ external_exports.strictObject({ ...identity, action: external_exports.literal("create") }).readonly(),
25672
+ external_exports.strictObject({ ...identity, action: external_exports.literal("linked-history"), targetSessionId: identifier }).readonly(),
25700
25673
  external_exports.strictObject({ ...identity, action: external_exports.literal("preview"), entryId: identifier }).readonly(),
25701
25674
  external_exports.strictObject({ ...identity, action: external_exports.literal("history"), entryId: identifier }).readonly(),
25702
25675
  external_exports.strictObject({ ...identity, action: external_exports.literal("find"), nativeSessionId: identifier }).readonly(),
@@ -25725,7 +25698,7 @@ var nativeSessionCommandSchema = external_exports.discriminatedUnion("action", [
25725
25698
  ]);
25726
25699
  var nativeSessionEntrySchema = external_exports.strictObject({
25727
25700
  entryId: identifier,
25728
- mobiusSessionIds: external_exports.array(identifier).max(500).readonly(),
25701
+ nativeSessionId: identifier,
25729
25702
  title: external_exports.string().max(500),
25730
25703
  directoryId,
25731
25704
  directoryLabel: external_exports.string().min(1).max(2048),
@@ -25737,6 +25710,18 @@ var resultEnvelope = {
25737
25710
  kind: external_exports.literal(NATIVE_SESSION_RESULT_KIND)
25738
25711
  };
25739
25712
  var nativeSessionResultSchema = external_exports.discriminatedUnion("action", [
25713
+ external_exports.strictObject({ ...resultEnvelope, action: external_exports.literal("create"), nativeSessionId: identifier }).readonly(),
25714
+ external_exports.strictObject({
25715
+ ...resultEnvelope,
25716
+ action: external_exports.literal("linked-history"),
25717
+ targetSessionId: identifier,
25718
+ history: sessionHistorySchema
25719
+ }).readonly(),
25720
+ external_exports.strictObject({
25721
+ ...resultEnvelope,
25722
+ action: external_exports.literal("unlinked-history"),
25723
+ targetSessionId: identifier
25724
+ }).readonly(),
25740
25725
  external_exports.strictObject({
25741
25726
  ...resultEnvelope,
25742
25727
  action: external_exports.literal("find"),
@@ -26284,8 +26269,7 @@ function createDaemonConfig(connection, agents = [], installableAgents = [], loc
26284
26269
  return {
26285
26270
  agents: daemonAgents,
26286
26271
  defaultWorkspace: connection.defaultWorkspace,
26287
- auditDatabasePath: connection.auditDatabasePath,
26288
- bindingId: "workspace",
26272
+ bindingId: RUNTIME_WORKSPACE_BINDING_ID,
26289
26273
  catalog: new LocalAgentCatalog(daemonAgents, installableAgents),
26290
26274
  channelId: connection.channelId,
26291
26275
  installableAgents,
@@ -26296,207 +26280,228 @@ function createDaemonConfig(connection, agents = [], installableAgents = [], loc
26296
26280
  }
26297
26281
 
26298
26282
  // src/run-daemon.ts
26299
- import { createHash as createHash3, randomUUID as randomUUID3 } from "node:crypto";
26283
+ import { randomUUID as randomUUID4 } from "node:crypto";
26300
26284
  import { basename as basename6 } from "node:path";
26301
26285
  import { styleText } from "node:util";
26302
26286
  import { fetch as fetch4, WebSocket as WebSocket2 } from "undici";
26303
26287
 
26304
- // src/acp/session-manager.ts
26305
- import { spawn as spawn4 } from "node:child_process";
26306
- import {
26307
- methods as methods8,
26308
- ndJsonStream as ndJsonStream2,
26309
- PROTOCOL_VERSION as PROTOCOL_VERSION3,
26310
- RequestError as RequestError3
26311
- } from "@agentclientprotocol/sdk";
26288
+ // src/acp/session-config/apply-session-configuration.ts
26289
+ import { randomUUID } from "node:crypto";
26312
26290
 
26313
- // src/authorization/local-raster.ts
26314
- import { open as open4, readFile as readFile2, realpath as realpath6, stat as stat5 } from "node:fs/promises";
26315
- import { basename, isAbsolute as isAbsolute8, normalize as normalize2 } from "node:path";
26316
- import { fileURLToPath } from "node:url";
26317
- var MAX_LOCAL_RASTER_BYTES = 128 * 1024 * 1024;
26318
- var MAX_INLINE_RASTER_BYTES = 3e6;
26319
- var PNG_SIGNATURE = Uint8Array.of(137, 80, 78, 71);
26320
- var JPEG_SIGNATURE = Uint8Array.of(255, 216, 255);
26321
- var GIF87_SIGNATURE = new TextEncoder().encode("GIF87a");
26322
- var GIF89_SIGNATURE = new TextEncoder().encode("GIF89a");
26323
- var RIFF_SIGNATURE = new TextEncoder().encode("RIFF");
26324
- var WEBP_SIGNATURE = new TextEncoder().encode("WEBP");
26325
- var LocalRasterImage = class {
26326
- bytes;
26327
- mimeType;
26328
- name;
26329
- sourceUri;
26330
- constructor(name, mimeType, bytes, sourceUri = "") {
26331
- this.bytes = bytes;
26332
- this.mimeType = mimeType;
26333
- this.name = name;
26334
- this.sourceUri = sourceUri;
26291
+ // src/agent-catalog/agent-settings-base.ts
26292
+ var AgentSettingsConfigurationError = class extends Error {
26293
+ code = "invalid_session_configuration";
26294
+ constructor(message, options = {}) {
26295
+ super(message, options);
26296
+ this.name = "AgentSettingsConfigurationError";
26335
26297
  }
26336
- base64 = async () => {
26337
- const bytes = this.bytes ?? new Uint8Array(await readFile2(this.sourceUri));
26338
- return Buffer.from(bytes).toString("base64");
26339
- };
26340
26298
  };
26341
- function startsWith(bytes, signature, offset = 0) {
26342
- if (bytes.byteLength < offset + signature.byteLength) {
26343
- return false;
26344
- }
26345
- return signature.every((value, index2) => bytes[offset + index2] === value);
26346
- }
26347
- function sniffRasterMime(bytes) {
26348
- if (startsWith(bytes, PNG_SIGNATURE)) {
26349
- return "image/png";
26350
- }
26351
- if (startsWith(bytes, JPEG_SIGNATURE)) {
26352
- return "image/jpeg";
26353
- }
26354
- if (startsWith(bytes, GIF87_SIGNATURE) || startsWith(bytes, GIF89_SIGNATURE)) {
26355
- return "image/gif";
26299
+ var AgentSettingsLaunchSelectionResult = class {
26300
+ agent;
26301
+ handled;
26302
+ constructor(agent, handled) {
26303
+ this.agent = agent;
26304
+ this.handled = handled;
26356
26305
  }
26357
- if (startsWith(bytes, RIFF_SIGNATURE) && startsWith(bytes, WEBP_SIGNATURE, 8)) {
26358
- return "image/webp";
26306
+ };
26307
+ var AppliedAgentLaunchSettings = class {
26308
+ agent;
26309
+ sessionConfigurations;
26310
+ constructor(agent, sessionConfigurations) {
26311
+ this.agent = agent;
26312
+ this.sessionConfigurations = Object.freeze([...sessionConfigurations]);
26359
26313
  }
26360
- return null;
26314
+ };
26315
+ var AgentSettingsAdapter = class {
26316
+ modelEffortResolution = AGENT_MODEL_EFFORT_RESOLUTION_ON_MODEL_SELECTION;
26317
+ applyLaunchSelection = (agent, _selection) => new AgentSettingsLaunchSelectionResult(agent, false);
26318
+ settings = (_agent) => [];
26319
+ };
26320
+ function selectValue(name, value, description) {
26321
+ return {
26322
+ description,
26323
+ groupId: "",
26324
+ groupName: "",
26325
+ name,
26326
+ value
26327
+ };
26361
26328
  }
26362
- function readInlineRaster(data, name = "Image") {
26363
- if (data.length === 0 || data.length > Math.ceil(MAX_INLINE_RASTER_BYTES / 3) * 4 || data.length % 4 !== 0) {
26364
- return null;
26365
- }
26366
- if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(data)) {
26367
- return null;
26368
- }
26369
- const bytes = new Uint8Array(Buffer.from(data, "base64"));
26370
- if (bytes.byteLength < 1 || bytes.byteLength > MAX_INLINE_RASTER_BYTES) {
26371
- return null;
26329
+ function selectSetting(id, name, description, currentValue, values) {
26330
+ return {
26331
+ booleanValue: false,
26332
+ category: "execution",
26333
+ currentValue,
26334
+ description,
26335
+ id,
26336
+ name,
26337
+ type: "select",
26338
+ values
26339
+ };
26340
+ }
26341
+ function selectedValue(selection, configId) {
26342
+ if (selection.configId !== configId || selection.valueType !== "select" || selection.booleanValue || selection.value.length === 0) {
26343
+ throw new AgentSettingsConfigurationError("The requested Agent setting is invalid");
26372
26344
  }
26373
- const mimeType = sniffRasterMime(bytes);
26374
- if (mimeType === null) {
26375
- return null;
26345
+ return selection.value;
26346
+ }
26347
+ function validValue(values, value) {
26348
+ if (!values.some((candidate) => candidate.value === value)) {
26349
+ throw new AgentSettingsConfigurationError("The requested Agent setting is unavailable");
26376
26350
  }
26377
- return new LocalRasterImage(basename(name) || "Image", mimeType, bytes);
26351
+ return value;
26378
26352
  }
26379
- async function resolveCanonicalPath(requested, signal) {
26380
- signal.throwIfAborted();
26381
- if (!isAbsolute8(requested) || requested.includes("\0") || normalize2(requested) !== requested) {
26382
- return null;
26353
+
26354
+ // src/agent-catalog/agents/codex-settings-adapter.ts
26355
+ var CodexSettingsAdapter = class extends AgentSettingsAdapter {
26356
+ modelEffortResolution = AGENT_MODEL_EFFORT_RESOLUTION_COMPLETE;
26357
+ };
26358
+
26359
+ // src/agent-catalog/agents/deepseek-settings-adapter.ts
26360
+ var READ_ONLY_VALUE = "read-only";
26361
+ var WORKSPACE_WRITE_VALUE = "workspace-write";
26362
+ var DANGER_FULL_ACCESS_VALUE = "danger-full-access";
26363
+ var DEEPSEEK_HARNESS_ACCESS_MODE_SETTING_ID = "dsh_access_mode";
26364
+ var dshAccessModes = Object.freeze([
26365
+ selectValue("Read only", READ_ONLY_VALUE, "Allow inspection without local writes."),
26366
+ selectValue("Workspace write", WORKSPACE_WRITE_VALUE, "Allow changes in the selected workspace."),
26367
+ selectValue("Full access", DANGER_FULL_ACCESS_VALUE, "Allow unrestricted local execution.")
26368
+ ]);
26369
+ var DeepSeekHarnessSettingsAdapter = class extends AgentSettingsAdapter {
26370
+ settings = (agent) => {
26371
+ const configured = agent.environment["DSH_PERMISSION_MODE"] ?? WORKSPACE_WRITE_VALUE;
26372
+ return [
26373
+ selectSetting(
26374
+ DEEPSEEK_HARNESS_ACCESS_MODE_SETTING_ID,
26375
+ "Access mode",
26376
+ "Controls the local side effects allowed for this DeepSeek Harness session.",
26377
+ validValue(dshAccessModes, configured),
26378
+ dshAccessModes
26379
+ )
26380
+ ];
26381
+ };
26382
+ applyLaunchSelection = (agent, selection) => {
26383
+ if (selection.configId !== DEEPSEEK_HARNESS_ACCESS_MODE_SETTING_ID) {
26384
+ return new AgentSettingsLaunchSelectionResult(agent, false);
26385
+ }
26386
+ const value = validValue(dshAccessModes, selectedValue(selection, DEEPSEEK_HARNESS_ACCESS_MODE_SETTING_ID));
26387
+ return new AgentSettingsLaunchSelectionResult(
26388
+ agent.withEnvironment({ ...agent.environment, DSH_PERMISSION_MODE: value }),
26389
+ true
26390
+ );
26391
+ };
26392
+ };
26393
+
26394
+ // src/agent-catalog/agents/opencode-settings-adapter.ts
26395
+ var AGENT_DEFAULT_VALUE = "agent_default";
26396
+ var READ_ONLY_VALUE2 = "read-only";
26397
+ var WORKSPACE_WRITE_VALUE2 = "workspace-write";
26398
+ var DANGER_FULL_ACCESS_VALUE2 = "danger-full-access";
26399
+ var OPENCODE_PERMISSION_SETTING_ID = "opencode_permission";
26400
+ var openCodePermissionModes = Object.freeze([
26401
+ selectValue("Agent default", AGENT_DEFAULT_VALUE, "Keep OpenCode's existing permission policy."),
26402
+ selectValue("Read only", READ_ONLY_VALUE2, "Allow inspection without local writes."),
26403
+ selectValue("Workspace write", WORKSPACE_WRITE_VALUE2, "Allow changes in the selected workspace."),
26404
+ selectValue("Full access", DANGER_FULL_ACCESS_VALUE2, "Allow unrestricted local execution.")
26405
+ ]);
26406
+ function openCodeConfiguration(environment) {
26407
+ const encoded = environment["OPENCODE_CONFIG_CONTENT"];
26408
+ if (encoded === void 0 || encoded.length === 0) {
26409
+ return {};
26383
26410
  }
26411
+ let parsed;
26384
26412
  try {
26385
- const target = await realpath6(requested);
26386
- signal.throwIfAborted();
26387
- if (!isAbsolute8(target) || normalize2(target) !== target) {
26388
- return null;
26389
- }
26390
- return target;
26413
+ parsed = JSON.parse(encoded);
26391
26414
  } catch (cause) {
26392
- signal.throwIfAborted();
26393
- if (cause instanceof Error && cause.name === "AbortError") {
26394
- throw cause;
26395
- }
26396
- return null;
26397
- }
26398
- }
26399
- function parseLocalImageUri(uri) {
26400
- const trimmed = uri.trim();
26401
- if (trimmed.length === 0 || trimmed.length > 2048 || trimmed.includes("\0")) {
26402
- return null;
26403
- }
26404
- if (trimmed.startsWith("data:")) {
26405
- return null;
26406
- }
26407
- if (trimmed.startsWith("file:")) {
26408
- try {
26409
- const url2 = new URL(trimmed);
26410
- if (url2.protocol !== "file:" || url2.host.length > 0) {
26411
- return null;
26412
- }
26413
- return fileURLToPath(url2);
26414
- } catch {
26415
- return null;
26416
- }
26415
+ throw new AgentSettingsConfigurationError("The OpenCode configuration is invalid", { cause });
26417
26416
  }
26418
- if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(trimmed)) {
26419
- return null;
26417
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
26418
+ throw new AgentSettingsConfigurationError("The OpenCode configuration is invalid");
26420
26419
  }
26421
- return trimmed;
26420
+ return Object.freeze({ ...parsed });
26422
26421
  }
26423
- async function readLocalRaster(uri, signal) {
26424
- signal.throwIfAborted();
26425
- const requested = parseLocalImageUri(uri);
26426
- if (requested === null) {
26427
- return null;
26428
- }
26429
- const target = await resolveCanonicalPath(requested, signal);
26430
- if (target === null) {
26431
- return null;
26432
- }
26433
- const targetMetadata = await stat5(target);
26434
- signal.throwIfAborted();
26435
- if (!targetMetadata.isFile() || targetMetadata.size < 1 || targetMetadata.size > MAX_LOCAL_RASTER_BYTES) {
26436
- return null;
26437
- }
26438
- const handle = await open4(target, "r");
26439
- const header = new Uint8Array(12);
26440
- try {
26441
- await handle.read(header, 0, header.byteLength, 0);
26442
- } finally {
26443
- await handle.close();
26422
+ function openCodePermission(value) {
26423
+ if (value === READ_ONLY_VALUE2) {
26424
+ return {
26425
+ "*": "deny",
26426
+ glob: "allow",
26427
+ grep: "allow",
26428
+ lsp: "allow",
26429
+ read: "allow",
26430
+ skill: "allow"
26431
+ };
26444
26432
  }
26445
- signal.throwIfAborted();
26446
- const mimeType = sniffRasterMime(header);
26447
- if (mimeType === null) {
26448
- return null;
26433
+ if (value === WORKSPACE_WRITE_VALUE2) {
26434
+ return {
26435
+ "*": "allow",
26436
+ external_directory: "ask"
26437
+ };
26449
26438
  }
26450
- return new LocalRasterImage(basename(target) || "Image", mimeType, null, target);
26439
+ return "allow";
26451
26440
  }
26452
-
26453
- // src/authorization/local-video.ts
26454
- import { basename as basename2 } from "node:path";
26455
- var MAX_INLINE_VIDEO_BYTES = 3e6;
26456
- var MP4_FILE_TYPE = new TextEncoder().encode("ftyp");
26457
- var WEBM_SIGNATURE = Uint8Array.of(26, 69, 223, 163);
26458
- var LocalVideo = class {
26459
- bytes;
26460
- mimeType;
26461
- name;
26462
- constructor(name, mimeType, bytes) {
26463
- this.bytes = bytes;
26464
- this.mimeType = mimeType;
26465
- this.name = name;
26466
- }
26467
- base64 = () => Buffer.from(this.bytes).toString("base64");
26441
+ var OpenCodeSettingsAdapter = class extends AgentSettingsAdapter {
26442
+ settings = (agent) => {
26443
+ const currentValue = agent.environment["MOBIUS_OPENCODE_PERMISSION"] ?? AGENT_DEFAULT_VALUE;
26444
+ return [
26445
+ selectSetting(
26446
+ OPENCODE_PERMISSION_SETTING_ID,
26447
+ "Permissions",
26448
+ "Controls OpenCode's local permission policy.",
26449
+ validValue(openCodePermissionModes, currentValue),
26450
+ openCodePermissionModes
26451
+ )
26452
+ ];
26453
+ };
26454
+ applyLaunchSelection = (agent, selection) => {
26455
+ if (selection.configId !== OPENCODE_PERMISSION_SETTING_ID) {
26456
+ return new AgentSettingsLaunchSelectionResult(agent, false);
26457
+ }
26458
+ const value = validValue(openCodePermissionModes, selectedValue(selection, OPENCODE_PERMISSION_SETTING_ID));
26459
+ if (value === AGENT_DEFAULT_VALUE) {
26460
+ return new AgentSettingsLaunchSelectionResult(agent, true);
26461
+ }
26462
+ return new AgentSettingsLaunchSelectionResult(
26463
+ agent.withEnvironment({
26464
+ ...agent.environment,
26465
+ MOBIUS_OPENCODE_PERMISSION: value,
26466
+ OPENCODE_CONFIG_CONTENT: JSON.stringify({
26467
+ ...openCodeConfiguration(agent.environment),
26468
+ permission: openCodePermission(value)
26469
+ })
26470
+ }),
26471
+ true
26472
+ );
26473
+ };
26468
26474
  };
26469
- function startsWith2(bytes, signature, offset = 0) {
26470
- if (bytes.byteLength < offset + signature.byteLength) {
26471
- return false;
26475
+
26476
+ // src/agent-catalog/agent-settings-adapter.ts
26477
+ var genericAdapter = new AgentSettingsAdapter();
26478
+ var codexAdapter = new CodexSettingsAdapter();
26479
+ var deepSeekHarnessAdapter = new DeepSeekHarnessSettingsAdapter();
26480
+ var openCodeAdapter = new OpenCodeSettingsAdapter();
26481
+ function agentSettingsAdapterForAgent(agentId) {
26482
+ if (agentId === "codex") {
26483
+ return codexAdapter;
26472
26484
  }
26473
- return signature.every((value, index2) => bytes[offset + index2] === value);
26474
- }
26475
- function sniffVideoMime(bytes) {
26476
- if (startsWith2(bytes, MP4_FILE_TYPE, 4)) {
26477
- return "video/mp4";
26485
+ if (agentId === "deepseek-harness") {
26486
+ return deepSeekHarnessAdapter;
26478
26487
  }
26479
- if (startsWith2(bytes, WEBM_SIGNATURE)) {
26480
- return "video/webm";
26488
+ if (agentId === "opencode") {
26489
+ return openCodeAdapter;
26481
26490
  }
26482
- return null;
26491
+ return genericAdapter;
26483
26492
  }
26484
- function readInlineVideo(data, declaredMimeType, name = "Video") {
26485
- if (data.length === 0 || data.length > Math.ceil(MAX_INLINE_VIDEO_BYTES / 3) * 4 || data.length % 4 !== 0) {
26486
- return null;
26487
- }
26488
- if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(data)) {
26489
- return null;
26490
- }
26491
- const bytes = new Uint8Array(Buffer.from(data, "base64"));
26492
- if (bytes.byteLength < 1 || bytes.byteLength > MAX_INLINE_VIDEO_BYTES) {
26493
- return null;
26494
- }
26495
- const mimeType = sniffVideoMime(bytes);
26496
- if (mimeType === null || mimeType !== declaredMimeType) {
26497
- return null;
26493
+ function applyAgentLaunchSettings(agent, selections) {
26494
+ const adapter = agentSettingsAdapterForAgent(agent.id);
26495
+ let selectedAgent = agent;
26496
+ const sessionConfigurations = [];
26497
+ for (const selection of selections) {
26498
+ const applied = adapter.applyLaunchSelection(selectedAgent, selection);
26499
+ selectedAgent = applied.agent;
26500
+ if (!applied.handled) {
26501
+ sessionConfigurations.push(selection);
26502
+ }
26498
26503
  }
26499
- return new LocalVideo(basename2(name) || "Video", mimeType, bytes);
26504
+ return new AppliedAgentLaunchSettings(selectedAgent, sessionConfigurations);
26500
26505
  }
26501
26506
 
26502
26507
  // src/infra/operation-metrics.ts
@@ -26534,6 +26539,358 @@ var unmeasuredOperationMetrics = Object.freeze({
26534
26539
  snapshot: () => Object.freeze([])
26535
26540
  });
26536
26541
 
26542
+ // src/native-sessions/chat-agent.ts
26543
+ function supportsNativeChat(agentId) {
26544
+ return agentId === "codex" || agentId === "claude";
26545
+ }
26546
+
26547
+ // src/acp/process-capacity.ts
26548
+ var AcpProcessCapacityLease = class {
26549
+ #releaseCapacity;
26550
+ #released = false;
26551
+ constructor(releaseCapacity) {
26552
+ this.#releaseCapacity = releaseCapacity;
26553
+ }
26554
+ release = () => {
26555
+ if (this.#released) {
26556
+ return;
26557
+ }
26558
+ this.#released = true;
26559
+ this.#releaseCapacity();
26560
+ };
26561
+ };
26562
+ var AcpProcessCapacityWaiter = class {
26563
+ completion = Promise.withResolvers();
26564
+ signal;
26565
+ constructor(signal) {
26566
+ this.signal = signal;
26567
+ }
26568
+ cancel = () => {
26569
+ try {
26570
+ this.signal.throwIfAborted();
26571
+ } catch (error62) {
26572
+ this.completion.reject(error62);
26573
+ }
26574
+ };
26575
+ };
26576
+ var AcpProcessCapacityLock = class {
26577
+ #locked = false;
26578
+ #waiters = [];
26579
+ acquire = async (signal) => {
26580
+ signal.throwIfAborted();
26581
+ if (!this.#locked) {
26582
+ this.#locked = true;
26583
+ return new AcpProcessCapacityLease(this.#release);
26584
+ }
26585
+ const waiter = new AcpProcessCapacityWaiter(signal);
26586
+ this.#waiters.push(waiter);
26587
+ signal.addEventListener("abort", waiter.cancel, { once: true });
26588
+ if (signal.aborted) {
26589
+ waiter.cancel();
26590
+ }
26591
+ try {
26592
+ return await waiter.completion.promise;
26593
+ } finally {
26594
+ signal.removeEventListener("abort", waiter.cancel);
26595
+ const index2 = this.#waiters.indexOf(waiter);
26596
+ if (index2 >= 0) {
26597
+ this.#waiters.splice(index2, 1);
26598
+ }
26599
+ }
26600
+ };
26601
+ #release = () => {
26602
+ while (this.#waiters.length > 0) {
26603
+ const waiter = this.#waiters.shift();
26604
+ if (waiter === void 0 || waiter.signal.aborted) {
26605
+ continue;
26606
+ }
26607
+ waiter.completion.resolve(new AcpProcessCapacityLease(this.#release));
26608
+ return;
26609
+ }
26610
+ this.#locked = false;
26611
+ };
26612
+ };
26613
+ async function waitForAcpProcessCapacity(completion, signal) {
26614
+ signal.throwIfAborted();
26615
+ const cancelled = Promise.withResolvers();
26616
+ const cancel = () => {
26617
+ try {
26618
+ signal.throwIfAborted();
26619
+ } catch (error62) {
26620
+ cancelled.reject(error62);
26621
+ }
26622
+ };
26623
+ signal.addEventListener("abort", cancel, { once: true });
26624
+ if (signal.aborted) {
26625
+ cancel();
26626
+ }
26627
+ try {
26628
+ await Promise.race([completion, cancelled.promise]);
26629
+ } finally {
26630
+ signal.removeEventListener("abort", cancel);
26631
+ }
26632
+ }
26633
+
26634
+ // src/acp/session-store.ts
26635
+ var AcpStoredSession = class {
26636
+ additionalDirectories;
26637
+ agentId;
26638
+ cwd;
26639
+ nativeSessionId;
26640
+ prompted;
26641
+ sessionId;
26642
+ constructor(sessionId, agentId, nativeSessionId, cwd, additionalDirectories, prompted) {
26643
+ this.additionalDirectories = [...additionalDirectories];
26644
+ this.agentId = agentId;
26645
+ this.cwd = cwd;
26646
+ this.nativeSessionId = nativeSessionId;
26647
+ this.prompted = prompted;
26648
+ this.sessionId = sessionId;
26649
+ }
26650
+ };
26651
+ var AcpStoredSessionLookup = class {
26652
+ };
26653
+ var MissingAcpStoredSession = class extends AcpStoredSessionLookup {
26654
+ found = false;
26655
+ };
26656
+ var FoundAcpStoredSession = class extends AcpStoredSessionLookup {
26657
+ found = true;
26658
+ session;
26659
+ constructor(session) {
26660
+ super();
26661
+ this.session = session;
26662
+ }
26663
+ };
26664
+ var DeletedAcpStoredSession = class extends AcpStoredSessionLookup {
26665
+ found = false;
26666
+ };
26667
+ var MemoryAcpSessionStore = class {
26668
+ #sessions = /* @__PURE__ */ new Map();
26669
+ #deleted = /* @__PURE__ */ new Set();
26670
+ findNative = (agentId, nativeSessionId) => [...this.#sessions.values()].filter(
26671
+ (session) => session.agentId === agentId && session.nativeSessionId === nativeSessionId
26672
+ );
26673
+ markDeleted = (agentId, nativeSessionId) => {
26674
+ const ids = this.findNative(agentId, nativeSessionId).map((session) => session.sessionId);
26675
+ for (const id of ids) {
26676
+ this.#sessions.delete(id);
26677
+ this.#deleted.add(id);
26678
+ }
26679
+ return ids;
26680
+ };
26681
+ read = (sessionId) => {
26682
+ if (this.#deleted.has(sessionId)) {
26683
+ return new DeletedAcpStoredSession();
26684
+ }
26685
+ const session = this.#sessions.get(sessionId);
26686
+ return session === void 0 ? new MissingAcpStoredSession() : new FoundAcpStoredSession(session);
26687
+ };
26688
+ remove = (sessionId) => {
26689
+ this.#sessions.delete(sessionId);
26690
+ };
26691
+ write = (session) => {
26692
+ this.#sessions.set(session.sessionId, session);
26693
+ };
26694
+ };
26695
+
26696
+ // src/acp/process-session.ts
26697
+ import { spawn as spawn4 } from "node:child_process";
26698
+ import {
26699
+ methods as methods8,
26700
+ ndJsonStream as ndJsonStream2,
26701
+ PROTOCOL_VERSION as PROTOCOL_VERSION3,
26702
+ RequestError as RequestError3
26703
+ } from "@agentclientprotocol/sdk";
26704
+
26705
+ // src/authorization/local-raster.ts
26706
+ import { open as open4, readFile as readFile2, realpath as realpath6, stat as stat5 } from "node:fs/promises";
26707
+ import { basename, isAbsolute as isAbsolute8, normalize as normalize2 } from "node:path";
26708
+ import { fileURLToPath } from "node:url";
26709
+ var MAX_LOCAL_RASTER_BYTES = 128 * 1024 * 1024;
26710
+ var MAX_INLINE_RASTER_BYTES = 3e6;
26711
+ var PNG_SIGNATURE = Uint8Array.of(137, 80, 78, 71);
26712
+ var JPEG_SIGNATURE = Uint8Array.of(255, 216, 255);
26713
+ var GIF87_SIGNATURE = new TextEncoder().encode("GIF87a");
26714
+ var GIF89_SIGNATURE = new TextEncoder().encode("GIF89a");
26715
+ var RIFF_SIGNATURE = new TextEncoder().encode("RIFF");
26716
+ var WEBP_SIGNATURE = new TextEncoder().encode("WEBP");
26717
+ var LocalRasterImage = class {
26718
+ bytes;
26719
+ mimeType;
26720
+ name;
26721
+ sourceUri;
26722
+ constructor(name, mimeType, bytes, sourceUri = "") {
26723
+ this.bytes = bytes;
26724
+ this.mimeType = mimeType;
26725
+ this.name = name;
26726
+ this.sourceUri = sourceUri;
26727
+ }
26728
+ base64 = async () => {
26729
+ const bytes = this.bytes ?? new Uint8Array(await readFile2(this.sourceUri));
26730
+ return Buffer.from(bytes).toString("base64");
26731
+ };
26732
+ };
26733
+ function startsWith(bytes, signature, offset = 0) {
26734
+ if (bytes.byteLength < offset + signature.byteLength) {
26735
+ return false;
26736
+ }
26737
+ return signature.every((value, index2) => bytes[offset + index2] === value);
26738
+ }
26739
+ function sniffRasterMime(bytes) {
26740
+ if (startsWith(bytes, PNG_SIGNATURE)) {
26741
+ return "image/png";
26742
+ }
26743
+ if (startsWith(bytes, JPEG_SIGNATURE)) {
26744
+ return "image/jpeg";
26745
+ }
26746
+ if (startsWith(bytes, GIF87_SIGNATURE) || startsWith(bytes, GIF89_SIGNATURE)) {
26747
+ return "image/gif";
26748
+ }
26749
+ if (startsWith(bytes, RIFF_SIGNATURE) && startsWith(bytes, WEBP_SIGNATURE, 8)) {
26750
+ return "image/webp";
26751
+ }
26752
+ return null;
26753
+ }
26754
+ function readInlineRaster(data, name = "Image") {
26755
+ if (data.length === 0 || data.length > Math.ceil(MAX_INLINE_RASTER_BYTES / 3) * 4 || data.length % 4 !== 0) {
26756
+ return null;
26757
+ }
26758
+ if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(data)) {
26759
+ return null;
26760
+ }
26761
+ const bytes = new Uint8Array(Buffer.from(data, "base64"));
26762
+ if (bytes.byteLength < 1 || bytes.byteLength > MAX_INLINE_RASTER_BYTES) {
26763
+ return null;
26764
+ }
26765
+ const mimeType = sniffRasterMime(bytes);
26766
+ if (mimeType === null) {
26767
+ return null;
26768
+ }
26769
+ return new LocalRasterImage(basename(name) || "Image", mimeType, bytes);
26770
+ }
26771
+ async function resolveCanonicalPath(requested, signal) {
26772
+ signal.throwIfAborted();
26773
+ if (!isAbsolute8(requested) || requested.includes("\0") || normalize2(requested) !== requested) {
26774
+ return null;
26775
+ }
26776
+ try {
26777
+ const target = await realpath6(requested);
26778
+ signal.throwIfAborted();
26779
+ if (!isAbsolute8(target) || normalize2(target) !== target) {
26780
+ return null;
26781
+ }
26782
+ return target;
26783
+ } catch (cause) {
26784
+ signal.throwIfAborted();
26785
+ if (cause instanceof Error && cause.name === "AbortError") {
26786
+ throw cause;
26787
+ }
26788
+ return null;
26789
+ }
26790
+ }
26791
+ function parseLocalImageUri(uri) {
26792
+ const trimmed = uri.trim();
26793
+ if (trimmed.length === 0 || trimmed.length > 2048 || trimmed.includes("\0")) {
26794
+ return null;
26795
+ }
26796
+ if (trimmed.startsWith("data:")) {
26797
+ return null;
26798
+ }
26799
+ if (trimmed.startsWith("file:")) {
26800
+ try {
26801
+ const url2 = new URL(trimmed);
26802
+ if (url2.protocol !== "file:" || url2.host.length > 0) {
26803
+ return null;
26804
+ }
26805
+ return fileURLToPath(url2);
26806
+ } catch {
26807
+ return null;
26808
+ }
26809
+ }
26810
+ if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(trimmed)) {
26811
+ return null;
26812
+ }
26813
+ return trimmed;
26814
+ }
26815
+ async function readLocalRaster(uri, signal) {
26816
+ signal.throwIfAborted();
26817
+ const requested = parseLocalImageUri(uri);
26818
+ if (requested === null) {
26819
+ return null;
26820
+ }
26821
+ const target = await resolveCanonicalPath(requested, signal);
26822
+ if (target === null) {
26823
+ return null;
26824
+ }
26825
+ const targetMetadata = await stat5(target);
26826
+ signal.throwIfAborted();
26827
+ if (!targetMetadata.isFile() || targetMetadata.size < 1 || targetMetadata.size > MAX_LOCAL_RASTER_BYTES) {
26828
+ return null;
26829
+ }
26830
+ const handle = await open4(target, "r");
26831
+ const header = new Uint8Array(12);
26832
+ try {
26833
+ await handle.read(header, 0, header.byteLength, 0);
26834
+ } finally {
26835
+ await handle.close();
26836
+ }
26837
+ signal.throwIfAborted();
26838
+ const mimeType = sniffRasterMime(header);
26839
+ if (mimeType === null) {
26840
+ return null;
26841
+ }
26842
+ return new LocalRasterImage(basename(target) || "Image", mimeType, null, target);
26843
+ }
26844
+
26845
+ // src/authorization/local-video.ts
26846
+ import { basename as basename2 } from "node:path";
26847
+ var MAX_INLINE_VIDEO_BYTES = 3e6;
26848
+ var MP4_FILE_TYPE = new TextEncoder().encode("ftyp");
26849
+ var WEBM_SIGNATURE = Uint8Array.of(26, 69, 223, 163);
26850
+ var LocalVideo = class {
26851
+ bytes;
26852
+ mimeType;
26853
+ name;
26854
+ constructor(name, mimeType, bytes) {
26855
+ this.bytes = bytes;
26856
+ this.mimeType = mimeType;
26857
+ this.name = name;
26858
+ }
26859
+ base64 = () => Buffer.from(this.bytes).toString("base64");
26860
+ };
26861
+ function startsWith2(bytes, signature, offset = 0) {
26862
+ if (bytes.byteLength < offset + signature.byteLength) {
26863
+ return false;
26864
+ }
26865
+ return signature.every((value, index2) => bytes[offset + index2] === value);
26866
+ }
26867
+ function sniffVideoMime(bytes) {
26868
+ if (startsWith2(bytes, MP4_FILE_TYPE, 4)) {
26869
+ return "video/mp4";
26870
+ }
26871
+ if (startsWith2(bytes, WEBM_SIGNATURE)) {
26872
+ return "video/webm";
26873
+ }
26874
+ return null;
26875
+ }
26876
+ function readInlineVideo(data, declaredMimeType, name = "Video") {
26877
+ if (data.length === 0 || data.length > Math.ceil(MAX_INLINE_VIDEO_BYTES / 3) * 4 || data.length % 4 !== 0) {
26878
+ return null;
26879
+ }
26880
+ if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(data)) {
26881
+ return null;
26882
+ }
26883
+ const bytes = new Uint8Array(Buffer.from(data, "base64"));
26884
+ if (bytes.byteLength < 1 || bytes.byteLength > MAX_INLINE_VIDEO_BYTES) {
26885
+ return null;
26886
+ }
26887
+ const mimeType = sniffVideoMime(bytes);
26888
+ if (mimeType === null || mimeType !== declaredMimeType) {
26889
+ return null;
26890
+ }
26891
+ return new LocalVideo(basename2(name) || "Video", mimeType, bytes);
26892
+ }
26893
+
26537
26894
  // src/native-sessions/history-images.ts
26538
26895
  var IMAGE_MARKER = /\[@image\]\(([^)\r\n]*)(?:\)|$)/g;
26539
26896
  async function embedLocalHistoryImages(history, signal) {
@@ -27193,6 +27550,244 @@ var AcpActivityTracker = class {
27193
27550
  };
27194
27551
  };
27195
27552
 
27553
+ // src/acp/value-utils.ts
27554
+ function truncate3(value, maximumLength) {
27555
+ return value.length <= maximumLength ? value : `${value.slice(0, Math.max(0, maximumLength - 1))}\u2026`;
27556
+ }
27557
+ function isRecord6(value) {
27558
+ return typeof value === "object" && value !== null && !Array.isArray(value);
27559
+ }
27560
+ function readString2(value, fallback = "") {
27561
+ return typeof value === "string" ? value : fallback;
27562
+ }
27563
+
27564
+ // src/acp/elicitation.ts
27565
+ function elicitationFieldType(value) {
27566
+ if (value === "boolean") {
27567
+ return "boolean";
27568
+ }
27569
+ if (value === "integer") {
27570
+ return "integer";
27571
+ }
27572
+ if (value === "number") {
27573
+ return "number";
27574
+ }
27575
+ if (value === "array") {
27576
+ return "multiselect";
27577
+ }
27578
+ return "string";
27579
+ }
27580
+ function normalizeElicitationOptions(schema) {
27581
+ const normalized = [];
27582
+ const oneOf = schema["oneOf"];
27583
+ if (Array.isArray(oneOf)) {
27584
+ for (const option of oneOf) {
27585
+ if (isRecord6(option) && typeof option["const"] === "string") {
27586
+ normalized.push({
27587
+ description: truncate3(readString2(option["description"]), 500),
27588
+ label: truncate3(readString2(option["title"], option["const"]), 255),
27589
+ value: truncate3(option["const"], 500)
27590
+ });
27591
+ }
27592
+ }
27593
+ return normalized.slice(0, 200);
27594
+ }
27595
+ const enumValues = schema["enum"];
27596
+ if (Array.isArray(enumValues)) {
27597
+ for (const entry of enumValues) {
27598
+ if (typeof entry === "string") {
27599
+ normalized.push({ description: "", label: entry, value: entry });
27600
+ }
27601
+ }
27602
+ return normalized.slice(0, 200);
27603
+ }
27604
+ const items = schema["items"];
27605
+ if (!isRecord6(items)) {
27606
+ return normalized;
27607
+ }
27608
+ const anyOf = items["anyOf"];
27609
+ if (Array.isArray(anyOf)) {
27610
+ return normalizeElicitationOptions({ oneOf: anyOf });
27611
+ }
27612
+ return normalizeElicitationOptions({ enum: items["enum"] });
27613
+ }
27614
+ function numericString(value) {
27615
+ return typeof value === "number" && Number.isFinite(value) ? value.toString() : "";
27616
+ }
27617
+ function normalizeElicitationFields(requestedSchema) {
27618
+ if (!isRecord6(requestedSchema) || !isRecord6(requestedSchema["properties"])) {
27619
+ return [];
27620
+ }
27621
+ const properties = requestedSchema["properties"];
27622
+ const requiredValues = requestedSchema["required"];
27623
+ const required2 = new Set(
27624
+ Array.isArray(requiredValues) ? requiredValues.filter((entry) => typeof entry === "string") : []
27625
+ );
27626
+ const normalized = [];
27627
+ for (const [name, property] of Object.entries(properties)) {
27628
+ if (!isRecord6(property)) {
27629
+ continue;
27630
+ }
27631
+ const type = elicitationFieldType(property["type"]);
27632
+ const options = normalizeElicitationOptions(property);
27633
+ const normalizedType = type === "string" && options.length > 0 ? "select" : type;
27634
+ const defaultValue = property["default"];
27635
+ normalized.push({
27636
+ defaultBooleanValue: typeof defaultValue === "boolean" ? defaultValue : false,
27637
+ defaultNumberValue: typeof defaultValue === "number" && Number.isFinite(defaultValue) ? defaultValue : 0,
27638
+ defaultStringValue: typeof defaultValue === "string" ? truncate3(defaultValue, 1e4) : Array.isArray(defaultValue) ? truncate3(JSON.stringify(defaultValue), 1e4) : "",
27639
+ description: truncate3(readString2(property["description"]), 500),
27640
+ format: truncate3(readString2(property["format"]), 64),
27641
+ hasDefaultValue: defaultValue !== void 0 && defaultValue !== null,
27642
+ maximum: numericString(property["maximum"]),
27643
+ maximumLength: numericString(property["maxLength"] ?? property["maxItems"]),
27644
+ minimum: numericString(property["minimum"]),
27645
+ minimumLength: numericString(property["minLength"] ?? property["minItems"]),
27646
+ name: truncate3(name, 128),
27647
+ options,
27648
+ pattern: truncate3(readString2(property["pattern"]), 500),
27649
+ required: required2.has(name),
27650
+ title: truncate3(readString2(property["title"], name), 255),
27651
+ type: normalizedType
27652
+ });
27653
+ }
27654
+ return normalized.slice(0, 100);
27655
+ }
27656
+ function validateStringValue(name, value, schema) {
27657
+ const minimum = schema["minLength"];
27658
+ const maximum = schema["maxLength"];
27659
+ if (typeof minimum === "number" && value.length < minimum) {
27660
+ throw new AcpExecutionError(
27661
+ `Elicitation field ${name} is shorter than allowed`,
27662
+ {},
27663
+ "invalid_elicitation_response"
27664
+ );
27665
+ }
27666
+ if (typeof maximum === "number" && value.length > maximum) {
27667
+ throw new AcpExecutionError(
27668
+ `Elicitation field ${name} is longer than allowed`,
27669
+ {},
27670
+ "invalid_elicitation_response"
27671
+ );
27672
+ }
27673
+ const pattern = schema["pattern"];
27674
+ if (typeof pattern === "string" && !new RegExp(pattern, "u").test(value)) {
27675
+ throw new AcpExecutionError(
27676
+ `Elicitation field ${name} does not match the required format`,
27677
+ {},
27678
+ "invalid_elicitation_response"
27679
+ );
27680
+ }
27681
+ const allowed = normalizeElicitationOptions(schema);
27682
+ if (allowed.length > 0 && !allowed.some((entry) => entry.value === value)) {
27683
+ throw new AcpExecutionError(
27684
+ `Elicitation field ${name} is not an allowed value`,
27685
+ {},
27686
+ "invalid_elicitation_response"
27687
+ );
27688
+ }
27689
+ }
27690
+ function validateNumericValue(name, value, schema, integer2) {
27691
+ if (!Number.isFinite(value) || integer2 && !Number.isInteger(value)) {
27692
+ throw new AcpExecutionError(
27693
+ `Elicitation field ${name} is not a valid number`,
27694
+ {},
27695
+ "invalid_elicitation_response"
27696
+ );
27697
+ }
27698
+ const minimum = schema["minimum"];
27699
+ const maximum = schema["maximum"];
27700
+ if (typeof minimum === "number" && value < minimum || typeof maximum === "number" && value > maximum) {
27701
+ throw new AcpExecutionError(
27702
+ `Elicitation field ${name} is outside the allowed range`,
27703
+ {},
27704
+ "invalid_elicitation_response"
27705
+ );
27706
+ }
27707
+ }
27708
+ function validateElicitationContent(encoded, requestedSchema) {
27709
+ let decoded;
27710
+ try {
27711
+ decoded = JSON.parse(encoded);
27712
+ } catch (error62) {
27713
+ throw new AcpExecutionError(
27714
+ "Elicitation response is not valid JSON",
27715
+ { cause: error62 },
27716
+ "invalid_elicitation_response"
27717
+ );
27718
+ }
27719
+ if (!isRecord6(decoded) || !isRecord6(requestedSchema) || !isRecord6(requestedSchema["properties"])) {
27720
+ throw new AcpExecutionError(
27721
+ "Elicitation response does not match the requested form",
27722
+ {},
27723
+ "invalid_elicitation_response"
27724
+ );
27725
+ }
27726
+ const properties = requestedSchema["properties"];
27727
+ const requiredValue = requestedSchema["required"];
27728
+ const required2 = new Set(
27729
+ Array.isArray(requiredValue) ? requiredValue.filter((entry) => typeof entry === "string") : []
27730
+ );
27731
+ for (const name of required2) {
27732
+ if (!(name in decoded)) {
27733
+ throw new AcpExecutionError(`Elicitation field ${name} is required`, {}, "invalid_elicitation_response");
27734
+ }
27735
+ }
27736
+ const validated = {};
27737
+ for (const [name, value] of Object.entries(decoded)) {
27738
+ const property = properties[name];
27739
+ if (!isRecord6(property)) {
27740
+ throw new AcpExecutionError(
27741
+ `Elicitation field ${name} was not requested`,
27742
+ {},
27743
+ "invalid_elicitation_response"
27744
+ );
27745
+ }
27746
+ if (property["type"] === "string" && typeof value === "string") {
27747
+ validateStringValue(name, value, property);
27748
+ validated[name] = value;
27749
+ continue;
27750
+ }
27751
+ if (property["type"] === "number" && typeof value === "number") {
27752
+ validateNumericValue(name, value, property, false);
27753
+ validated[name] = value;
27754
+ continue;
27755
+ }
27756
+ if (property["type"] === "integer" && typeof value === "number") {
27757
+ validateNumericValue(name, value, property, true);
27758
+ validated[name] = value;
27759
+ continue;
27760
+ }
27761
+ if (property["type"] === "boolean" && typeof value === "boolean") {
27762
+ validated[name] = value;
27763
+ continue;
27764
+ }
27765
+ if (property["type"] === "array" && Array.isArray(value) && value.every((entry) => typeof entry === "string")) {
27766
+ const minimum = property["minItems"];
27767
+ const maximum = property["maxItems"];
27768
+ if (typeof minimum === "number" && value.length < minimum || typeof maximum === "number" && value.length > maximum) {
27769
+ throw new AcpExecutionError(
27770
+ `Elicitation field ${name} has an invalid selection count`,
27771
+ {},
27772
+ "invalid_elicitation_response"
27773
+ );
27774
+ }
27775
+ const allowed = normalizeElicitationOptions(property);
27776
+ if (allowed.length > 0 && value.some((entry) => !allowed.some((option) => option.value === entry))) {
27777
+ throw new AcpExecutionError(
27778
+ `Elicitation field ${name} contains an invalid selection`,
27779
+ {},
27780
+ "invalid_elicitation_response"
27781
+ );
27782
+ }
27783
+ validated[name] = value;
27784
+ continue;
27785
+ }
27786
+ throw new AcpExecutionError(`Elicitation field ${name} has the wrong type`, {}, "invalid_elicitation_response");
27787
+ }
27788
+ return validated;
27789
+ }
27790
+
27196
27791
  // ../../node_modules/.pnpm/mdast-util-to-string@4.0.0/node_modules/mdast-util-to-string/lib/index.js
27197
27792
  var emptyOptions = {};
27198
27793
  function toString(value, options) {
@@ -34404,13 +34999,13 @@ var SessionConfigProtocolError = class extends Error {
34404
34999
  this.name = "SessionConfigProtocolError";
34405
35000
  }
34406
35001
  };
34407
- function isRecord6(value) {
35002
+ function isRecord7(value) {
34408
35003
  return typeof value === "object" && value !== null && !Array.isArray(value);
34409
35004
  }
34410
- function readString2(value, fallback = "") {
35005
+ function readString3(value, fallback = "") {
34411
35006
  return typeof value === "string" ? value : fallback;
34412
35007
  }
34413
- function truncate3(value, maximum) {
35008
+ function truncate4(value, maximum) {
34414
35009
  return value.length <= maximum ? value : value.slice(0, maximum);
34415
35010
  }
34416
35011
  function readBoolean(value, fallback = false) {
@@ -34422,11 +35017,11 @@ function normalizeConfigValue(option, groupId = "", groupName = "") {
34422
35017
  return void 0;
34423
35018
  }
34424
35019
  return {
34425
- description: truncate3(readString2(option["description"]), 500),
34426
- groupId: truncate3(groupId, 128),
34427
- groupName: truncate3(groupName, 255),
34428
- name: truncate3(readString2(option["name"], value), 255),
34429
- value: truncate3(value, 500)
35020
+ description: truncate4(readString3(option["description"]), 500),
35021
+ groupId: truncate4(groupId, 128),
35022
+ groupName: truncate4(groupName, 255),
35023
+ name: truncate4(readString3(option["name"], value), 255),
35024
+ value: truncate4(value, 500)
34430
35025
  };
34431
35026
  }
34432
35027
  function normalizeConfigValues(value) {
@@ -34435,15 +35030,15 @@ function normalizeConfigValues(value) {
34435
35030
  }
34436
35031
  const normalized = [];
34437
35032
  for (const entry of value) {
34438
- if (!isRecord6(entry)) {
35033
+ if (!isRecord7(entry)) {
34439
35034
  continue;
34440
35035
  }
34441
35036
  const groupedOptions = entry["options"];
34442
35037
  if (Array.isArray(groupedOptions)) {
34443
- const groupId = readString2(entry["group"]);
34444
- const groupName = readString2(entry["name"]);
35038
+ const groupId = readString3(entry["group"]);
35039
+ const groupName = readString3(entry["name"]);
34445
35040
  for (const groupedOption of groupedOptions) {
34446
- if (isRecord6(groupedOption)) {
35041
+ if (isRecord7(groupedOption)) {
34447
35042
  const normalizedValue = normalizeConfigValue(groupedOption, groupId, groupName);
34448
35043
  if (normalizedValue !== void 0) {
34449
35044
  normalized.push(normalizedValue);
@@ -34463,12 +35058,12 @@ function normalizeConfigOptions(value, modes) {
34463
35058
  const normalized = [];
34464
35059
  if (Array.isArray(value)) {
34465
35060
  for (const option of value) {
34466
- if (!isRecord6(option)) {
35061
+ if (!isRecord7(option)) {
34467
35062
  continue;
34468
35063
  }
34469
- const id = truncate3(readString2(option["id"]), 128);
34470
- const name = truncate3(readString2(option["name"], id), 255);
34471
- const category = truncate3(readString2(option["category"]), 128);
35064
+ const id = truncate4(readString3(option["id"]), 128);
35065
+ const name = truncate4(readString3(option["name"], id), 255);
35066
+ const category = truncate4(readString3(option["category"]), 128);
34472
35067
  if (id.length === 0 || name.length === 0 || category === "_mobius_permission") {
34473
35068
  continue;
34474
35069
  }
@@ -34477,7 +35072,7 @@ function normalizeConfigOptions(value, modes) {
34477
35072
  booleanValue: readBoolean(option["currentValue"]),
34478
35073
  category,
34479
35074
  currentValue: "",
34480
- description: truncate3(readString2(option["description"]), 500),
35075
+ description: truncate4(readString3(option["description"]), 500),
34481
35076
  id,
34482
35077
  name,
34483
35078
  type: "boolean",
@@ -34487,13 +35082,13 @@ function normalizeConfigOptions(value, modes) {
34487
35082
  }
34488
35083
  if (option["type"] === "select") {
34489
35084
  const values = normalizeConfigValues(option["options"]);
34490
- const currentValue = truncate3(readString2(option["currentValue"]), 500);
35085
+ const currentValue = truncate4(readString3(option["currentValue"]), 500);
34491
35086
  if (values.some((entry) => entry.value === currentValue)) {
34492
35087
  normalized.push({
34493
35088
  booleanValue: false,
34494
35089
  category,
34495
35090
  currentValue,
34496
- description: truncate3(readString2(option["description"]), 500),
35091
+ description: truncate4(readString3(option["description"]), 500),
34497
35092
  id,
34498
35093
  name,
34499
35094
  type: "select",
@@ -34503,28 +35098,28 @@ function normalizeConfigOptions(value, modes) {
34503
35098
  }
34504
35099
  }
34505
35100
  }
34506
- if (isRecord6(modes)) {
35101
+ if (isRecord7(modes)) {
34507
35102
  const values = [];
34508
35103
  const availableModes = modes["availableModes"];
34509
35104
  if (Array.isArray(availableModes)) {
34510
35105
  for (const mode of availableModes) {
34511
- if (!isRecord6(mode)) {
35106
+ if (!isRecord7(mode)) {
34512
35107
  continue;
34513
35108
  }
34514
- const id = truncate3(readString2(mode["id"]), 500);
35109
+ const id = truncate4(readString3(mode["id"]), 500);
34515
35110
  if (id.length === 0) {
34516
35111
  continue;
34517
35112
  }
34518
35113
  values.push({
34519
- description: truncate3(readString2(mode["description"]), 500),
35114
+ description: truncate4(readString3(mode["description"]), 500),
34520
35115
  groupId: "",
34521
35116
  groupName: "",
34522
- name: truncate3(readString2(mode["name"], id), 255),
35117
+ name: truncate4(readString3(mode["name"], id), 255),
34523
35118
  value: id
34524
35119
  });
34525
35120
  }
34526
35121
  }
34527
- const currentValue = truncate3(readString2(modes["currentModeId"]), 500);
35122
+ const currentValue = truncate4(readString3(modes["currentModeId"]), 500);
34528
35123
  if (currentValue.length > 0 && values.some((entry) => entry.value === currentValue) && !normalized.some((entry) => entry.category === "mode")) {
34529
35124
  normalized.unshift({
34530
35125
  booleanValue: false,
@@ -34541,7 +35136,7 @@ function normalizeConfigOptions(value, modes) {
34541
35136
  return normalized.slice(0, MAXIMUM_CONFIG_OPTIONS);
34542
35137
  }
34543
35138
  function normalizeStandardLifecycle(response) {
34544
- const lifecycle = isRecord6(response) ? response : {};
35139
+ const lifecycle = isRecord7(response) ? response : {};
34545
35140
  return normalizeConfigOptions(lifecycle["configOptions"], lifecycle["modes"]);
34546
35141
  }
34547
35142
  function replaceStandardConfigOptions(current, value) {
@@ -34583,7 +35178,7 @@ var StandardSessionConfigProtocol = class {
34583
35178
  "ACP agent exited while changing session configuration",
34584
35179
  change.signal
34585
35180
  );
34586
- if (!isRecord6(response) || !Array.isArray(response["configOptions"])) {
35181
+ if (!isRecord7(response) || !Array.isArray(response["configOptions"])) {
34587
35182
  throw new SessionConfigProtocolError("The Agent returned an invalid session configuration response");
34588
35183
  }
34589
35184
  return replaceStandardConfigOptions(current, response["configOptions"]);
@@ -34803,216 +35398,11 @@ var AcpHistoryReplay = class {
34803
35398
  };
34804
35399
  };
34805
35400
 
34806
- // src/acp/session-store.ts
34807
- import { mkdirSync as mkdirSync2 } from "node:fs";
34808
- import { dirname as dirname4 } from "node:path";
34809
- import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
34810
- var AcpStoredSession = class {
34811
- additionalDirectories;
34812
- agentId;
34813
- cwd;
34814
- nativeSessionId;
34815
- prompted;
34816
- sessionId;
34817
- constructor(sessionId, agentId, nativeSessionId, cwd, additionalDirectories, prompted) {
34818
- this.additionalDirectories = [...additionalDirectories];
34819
- this.agentId = agentId;
34820
- this.cwd = cwd;
34821
- this.nativeSessionId = nativeSessionId;
34822
- this.prompted = prompted;
34823
- this.sessionId = sessionId;
34824
- }
34825
- };
34826
- var AcpStoredSessionLookup = class {
34827
- };
34828
- var MissingAcpStoredSession = class extends AcpStoredSessionLookup {
34829
- found = false;
34830
- };
34831
- var FoundAcpStoredSession = class extends AcpStoredSessionLookup {
34832
- found = true;
34833
- session;
34834
- constructor(session) {
34835
- super();
34836
- this.session = session;
34837
- }
34838
- };
34839
- var DeletedAcpStoredSession = class extends AcpStoredSessionLookup {
34840
- found = false;
34841
- };
34842
- function readString3(value, field) {
34843
- if (typeof value !== "string" || value.length === 0) {
34844
- throw new Error(`Stored ACP session has an invalid ${field}`);
34845
- }
34846
- return value;
34847
- }
34848
- function readAdditionalDirectories(value) {
34849
- if (typeof value !== "string") {
34850
- throw new Error("Stored ACP session has invalid additional directories");
34851
- }
34852
- const decoded = JSON.parse(value);
34853
- if (!Array.isArray(decoded) || decoded.some((directory) => typeof directory !== "string")) {
34854
- throw new Error("Stored ACP session has invalid additional directories");
34855
- }
34856
- return decoded;
34857
- }
34858
- function readPrompted(value) {
34859
- if (value === 0) {
34860
- return false;
34861
- }
34862
- if (value === 1) {
34863
- return true;
34864
- }
34865
- throw new Error("Stored ACP session has an invalid prompted state");
34866
- }
34867
- function decodeSessionRow(row) {
34868
- if (typeof row !== "object" || row === null || Array.isArray(row)) {
34869
- throw new Error("Stored ACP session is not an object");
34870
- }
34871
- return new AcpStoredSession(
34872
- readString3(Reflect.get(row, "session_id"), "session ID"),
34873
- readString3(Reflect.get(row, "agent_id"), "agent ID"),
34874
- readString3(Reflect.get(row, "native_session_id"), "native session ID"),
34875
- readString3(Reflect.get(row, "cwd"), "working directory"),
34876
- readAdditionalDirectories(Reflect.get(row, "additional_directories_json")),
34877
- readPrompted(Reflect.get(row, "prompted"))
34878
- );
34879
- }
34880
- var MemoryAcpSessionStore = class {
34881
- #sessions = /* @__PURE__ */ new Map();
34882
- #deleted = /* @__PURE__ */ new Set();
34883
- findNative = (agentId, nativeSessionId) => [...this.#sessions.values()].filter(
34884
- (session) => session.agentId === agentId && session.nativeSessionId === nativeSessionId
34885
- );
34886
- markDeleted = (agentId, nativeSessionId) => {
34887
- const ids = this.findNative(agentId, nativeSessionId).map((session) => session.sessionId);
34888
- for (const id of ids) {
34889
- this.#sessions.delete(id);
34890
- this.#deleted.add(id);
34891
- }
34892
- return ids;
34893
- };
34894
- read = (sessionId) => {
34895
- if (this.#deleted.has(sessionId)) {
34896
- return new DeletedAcpStoredSession();
34897
- }
34898
- const session = this.#sessions.get(sessionId);
34899
- return session === void 0 ? new MissingAcpStoredSession() : new FoundAcpStoredSession(session);
34900
- };
34901
- remove = (sessionId) => {
34902
- this.#sessions.delete(sessionId);
34903
- };
34904
- write = (session) => {
34905
- this.#sessions.set(session.sessionId, session);
34906
- };
34907
- };
34908
- var SqliteAcpSessionStore = class {
34909
- #database;
34910
- constructor(path2) {
34911
- mkdirSync2(dirname4(path2), { recursive: true });
34912
- this.#database = new DatabaseSync2(path2);
34913
- this.#database.exec(`
34914
- CREATE TABLE IF NOT EXISTS acp_deleted_sessions (session_id TEXT PRIMARY KEY) STRICT;
34915
- CREATE TABLE IF NOT EXISTS acp_sessions (
34916
- session_id TEXT PRIMARY KEY,
34917
- agent_id TEXT NOT NULL,
34918
- native_session_id TEXT NOT NULL,
34919
- cwd TEXT NOT NULL,
34920
- additional_directories_json TEXT NOT NULL,
34921
- prompted INTEGER NOT NULL DEFAULT 0 CHECK (prompted IN (0, 1)),
34922
- updated_at TEXT NOT NULL
34923
- ) STRICT
34924
- `);
34925
- const columns = this.#database.prepare("PRAGMA table_info(acp_sessions)").all();
34926
- const hasPromptedColumn = columns.some(
34927
- (column) => typeof column === "object" && column !== null && Reflect.get(column, "name") === "prompted"
34928
- );
34929
- if (!hasPromptedColumn) {
34930
- this.#database.exec(`
34931
- ALTER TABLE acp_sessions
34932
- ADD COLUMN prompted INTEGER NOT NULL DEFAULT 1 CHECK (prompted IN (0, 1))
34933
- `);
34934
- }
34935
- }
34936
- read = (sessionId) => {
34937
- if (this.#database.prepare("SELECT session_id FROM acp_deleted_sessions WHERE session_id = ?").get(sessionId) !== void 0) {
34938
- return new DeletedAcpStoredSession();
34939
- }
34940
- const row = this.#database.prepare(
34941
- `
34942
- SELECT
34943
- session_id,
34944
- agent_id,
34945
- native_session_id,
34946
- cwd,
34947
- additional_directories_json,
34948
- prompted
34949
- FROM acp_sessions
34950
- WHERE session_id = ?
34951
- `
34952
- ).get(sessionId);
34953
- return row === void 0 ? new MissingAcpStoredSession() : new FoundAcpStoredSession(decodeSessionRow(row));
34954
- };
34955
- remove = (sessionId) => {
34956
- this.#database.prepare("DELETE FROM acp_sessions WHERE session_id = ?").run(sessionId);
34957
- };
34958
- findNative = (agentId, nativeSessionId) => this.#database.prepare("SELECT * FROM acp_sessions WHERE agent_id = ? AND native_session_id = ?").all(agentId, nativeSessionId).map(decodeSessionRow);
34959
- markDeleted = (agentId, nativeSessionId) => {
34960
- const ids = this.findNative(agentId, nativeSessionId).map((session) => session.sessionId);
34961
- this.#database.exec("BEGIN");
34962
- try {
34963
- for (const id of ids) {
34964
- this.#database.prepare("INSERT OR IGNORE INTO acp_deleted_sessions (session_id) VALUES (?)").run(id);
34965
- this.remove(id);
34966
- }
34967
- this.#database.exec("COMMIT");
34968
- return ids;
34969
- } catch (error62) {
34970
- this.#database.exec("ROLLBACK");
34971
- throw error62;
34972
- }
34973
- };
34974
- write = (session) => {
34975
- this.#database.prepare(
34976
- `
34977
- INSERT INTO acp_sessions (
34978
- session_id,
34979
- agent_id,
34980
- native_session_id,
34981
- cwd,
34982
- additional_directories_json,
34983
- prompted,
34984
- updated_at
34985
- ) VALUES (?, ?, ?, ?, ?, ?, ?)
34986
- ON CONFLICT(session_id) DO UPDATE SET
34987
- agent_id = excluded.agent_id,
34988
- native_session_id = excluded.native_session_id,
34989
- cwd = excluded.cwd,
34990
- additional_directories_json = excluded.additional_directories_json,
34991
- prompted = excluded.prompted,
34992
- updated_at = excluded.updated_at
34993
- `
34994
- ).run(
34995
- session.sessionId,
34996
- session.agentId,
34997
- session.nativeSessionId,
34998
- session.cwd,
34999
- JSON.stringify(session.additionalDirectories),
35000
- session.prompted ? 1 : 0,
35001
- (/* @__PURE__ */ new Date()).toISOString()
35002
- );
35003
- };
35004
- close = () => {
35005
- this.#database.close();
35006
- };
35007
- };
35008
-
35009
- // src/acp/session-manager.ts
35401
+ // src/acp/process-session.ts
35010
35402
  var PROCESS_STOP_TIMEOUT_MILLISECONDS = 1e3;
35011
- var MAX_ACP_PROCESSES = 10;
35012
35403
  var MAX_PRE_SESSION_UPDATES = 100;
35013
35404
  var MAX_PRE_SESSION_UPDATE_BYTES = 1024 * 1024;
35014
35405
  var SESSION_CONTROL_COMMAND_ID = "session-control";
35015
- var SESSION_CONTROL_TIMEOUT_MILLISECONDS = 3e4;
35016
35406
  function nativeHistoryNotRetained() {
35017
35407
  return {
35018
35408
  cause: {
@@ -35065,91 +35455,6 @@ var RetryableAcpInitializationError = class extends AcpExecutionError {
35065
35455
  this.name = "RetryableAcpInitializationError";
35066
35456
  }
35067
35457
  };
35068
- var AcpProcessCapacityLease = class {
35069
- #releaseCapacity;
35070
- #released = false;
35071
- constructor(releaseCapacity) {
35072
- this.#releaseCapacity = releaseCapacity;
35073
- }
35074
- release = () => {
35075
- if (this.#released) {
35076
- return;
35077
- }
35078
- this.#released = true;
35079
- this.#releaseCapacity();
35080
- };
35081
- };
35082
- var AcpProcessCapacityWaiter = class {
35083
- completion = Promise.withResolvers();
35084
- signal;
35085
- constructor(signal) {
35086
- this.signal = signal;
35087
- }
35088
- cancel = () => {
35089
- try {
35090
- this.signal.throwIfAborted();
35091
- } catch (error62) {
35092
- this.completion.reject(error62);
35093
- }
35094
- };
35095
- };
35096
- var AcpProcessCapacityLock = class {
35097
- #locked = false;
35098
- #waiters = [];
35099
- acquire = async (signal) => {
35100
- signal.throwIfAborted();
35101
- if (!this.#locked) {
35102
- this.#locked = true;
35103
- return new AcpProcessCapacityLease(this.#release);
35104
- }
35105
- const waiter = new AcpProcessCapacityWaiter(signal);
35106
- this.#waiters.push(waiter);
35107
- signal.addEventListener("abort", waiter.cancel, { once: true });
35108
- if (signal.aborted) {
35109
- waiter.cancel();
35110
- }
35111
- try {
35112
- return await waiter.completion.promise;
35113
- } finally {
35114
- signal.removeEventListener("abort", waiter.cancel);
35115
- const index2 = this.#waiters.indexOf(waiter);
35116
- if (index2 >= 0) {
35117
- this.#waiters.splice(index2, 1);
35118
- }
35119
- }
35120
- };
35121
- #release = () => {
35122
- while (this.#waiters.length > 0) {
35123
- const waiter = this.#waiters.shift();
35124
- if (waiter === void 0 || waiter.signal.aborted) {
35125
- continue;
35126
- }
35127
- waiter.completion.resolve(new AcpProcessCapacityLease(this.#release));
35128
- return;
35129
- }
35130
- this.#locked = false;
35131
- };
35132
- };
35133
- async function waitForAcpProcessCapacity(completion, signal) {
35134
- signal.throwIfAborted();
35135
- const cancelled = Promise.withResolvers();
35136
- const cancel = () => {
35137
- try {
35138
- signal.throwIfAborted();
35139
- } catch (error62) {
35140
- cancelled.reject(error62);
35141
- }
35142
- };
35143
- signal.addEventListener("abort", cancel, { once: true });
35144
- if (signal.aborted) {
35145
- cancel();
35146
- }
35147
- try {
35148
- await Promise.race([completion, cancelled.promise]);
35149
- } finally {
35150
- signal.removeEventListener("abort", cancel);
35151
- }
35152
- }
35153
35458
  function readableWebStream(input2) {
35154
35459
  let streamOpen = true;
35155
35460
  return new ReadableStream({
@@ -35225,15 +35530,6 @@ function createWritableAcpStream(output2) {
35225
35530
  }
35226
35531
  });
35227
35532
  }
35228
- function truncate4(value, maximumLength) {
35229
- return value.length <= maximumLength ? value : `${value.slice(0, Math.max(0, maximumLength - 1))}\u2026`;
35230
- }
35231
- function isRecord7(value) {
35232
- return typeof value === "object" && value !== null && !Array.isArray(value);
35233
- }
35234
- function readString4(value, fallback = "") {
35235
- return typeof value === "string" ? value : fallback;
35236
- }
35237
35533
  function arraysEqual(left, right) {
35238
35534
  return left.length === right.length && left.every((value, index2) => value === right[index2]);
35239
35535
  }
@@ -35242,231 +35538,6 @@ function recordsEqual(left, right) {
35242
35538
  const rightEntries = Object.entries(right);
35243
35539
  return leftEntries.length === rightEntries.length && leftEntries.every(([name, value]) => right[name] === value);
35244
35540
  }
35245
- function elicitationFieldType(value) {
35246
- if (value === "boolean") {
35247
- return "boolean";
35248
- }
35249
- if (value === "integer") {
35250
- return "integer";
35251
- }
35252
- if (value === "number") {
35253
- return "number";
35254
- }
35255
- if (value === "array") {
35256
- return "multiselect";
35257
- }
35258
- return "string";
35259
- }
35260
- function normalizeElicitationOptions(schema) {
35261
- const normalized = [];
35262
- const oneOf = schema["oneOf"];
35263
- if (Array.isArray(oneOf)) {
35264
- for (const option of oneOf) {
35265
- if (isRecord7(option) && typeof option["const"] === "string") {
35266
- normalized.push({
35267
- description: truncate4(readString4(option["description"]), 500),
35268
- label: truncate4(readString4(option["title"], option["const"]), 255),
35269
- value: truncate4(option["const"], 500)
35270
- });
35271
- }
35272
- }
35273
- return normalized.slice(0, 200);
35274
- }
35275
- const enumValues = schema["enum"];
35276
- if (Array.isArray(enumValues)) {
35277
- for (const entry of enumValues) {
35278
- if (typeof entry === "string") {
35279
- normalized.push({ description: "", label: entry, value: entry });
35280
- }
35281
- }
35282
- return normalized.slice(0, 200);
35283
- }
35284
- const items = schema["items"];
35285
- if (!isRecord7(items)) {
35286
- return normalized;
35287
- }
35288
- const anyOf = items["anyOf"];
35289
- if (Array.isArray(anyOf)) {
35290
- return normalizeElicitationOptions({ oneOf: anyOf });
35291
- }
35292
- return normalizeElicitationOptions({ enum: items["enum"] });
35293
- }
35294
- function numericString(value) {
35295
- return typeof value === "number" && Number.isFinite(value) ? value.toString() : "";
35296
- }
35297
- function normalizeElicitationFields(requestedSchema) {
35298
- if (!isRecord7(requestedSchema) || !isRecord7(requestedSchema["properties"])) {
35299
- return [];
35300
- }
35301
- const properties = requestedSchema["properties"];
35302
- const requiredValues = requestedSchema["required"];
35303
- const required2 = new Set(
35304
- Array.isArray(requiredValues) ? requiredValues.filter((entry) => typeof entry === "string") : []
35305
- );
35306
- const normalized = [];
35307
- for (const [name, property] of Object.entries(properties)) {
35308
- if (!isRecord7(property)) {
35309
- continue;
35310
- }
35311
- const type = elicitationFieldType(property["type"]);
35312
- const options = normalizeElicitationOptions(property);
35313
- const normalizedType = type === "string" && options.length > 0 ? "select" : type;
35314
- const defaultValue = property["default"];
35315
- normalized.push({
35316
- defaultBooleanValue: typeof defaultValue === "boolean" ? defaultValue : false,
35317
- defaultNumberValue: typeof defaultValue === "number" && Number.isFinite(defaultValue) ? defaultValue : 0,
35318
- defaultStringValue: typeof defaultValue === "string" ? truncate4(defaultValue, 1e4) : Array.isArray(defaultValue) ? truncate4(JSON.stringify(defaultValue), 1e4) : "",
35319
- description: truncate4(readString4(property["description"]), 500),
35320
- format: truncate4(readString4(property["format"]), 64),
35321
- hasDefaultValue: defaultValue !== void 0 && defaultValue !== null,
35322
- maximum: numericString(property["maximum"]),
35323
- maximumLength: numericString(property["maxLength"] ?? property["maxItems"]),
35324
- minimum: numericString(property["minimum"]),
35325
- minimumLength: numericString(property["minLength"] ?? property["minItems"]),
35326
- name: truncate4(name, 128),
35327
- options,
35328
- pattern: truncate4(readString4(property["pattern"]), 500),
35329
- required: required2.has(name),
35330
- title: truncate4(readString4(property["title"], name), 255),
35331
- type: normalizedType
35332
- });
35333
- }
35334
- return normalized.slice(0, 100);
35335
- }
35336
- function validateStringValue(name, value, schema) {
35337
- const minimum = schema["minLength"];
35338
- const maximum = schema["maxLength"];
35339
- if (typeof minimum === "number" && value.length < minimum) {
35340
- throw new AcpExecutionError(
35341
- `Elicitation field ${name} is shorter than allowed`,
35342
- {},
35343
- "invalid_elicitation_response"
35344
- );
35345
- }
35346
- if (typeof maximum === "number" && value.length > maximum) {
35347
- throw new AcpExecutionError(
35348
- `Elicitation field ${name} is longer than allowed`,
35349
- {},
35350
- "invalid_elicitation_response"
35351
- );
35352
- }
35353
- const pattern = schema["pattern"];
35354
- if (typeof pattern === "string" && !new RegExp(pattern, "u").test(value)) {
35355
- throw new AcpExecutionError(
35356
- `Elicitation field ${name} does not match the required format`,
35357
- {},
35358
- "invalid_elicitation_response"
35359
- );
35360
- }
35361
- const allowed = normalizeElicitationOptions(schema);
35362
- if (allowed.length > 0 && !allowed.some((entry) => entry.value === value)) {
35363
- throw new AcpExecutionError(
35364
- `Elicitation field ${name} is not an allowed value`,
35365
- {},
35366
- "invalid_elicitation_response"
35367
- );
35368
- }
35369
- }
35370
- function validateNumericValue(name, value, schema, integer2) {
35371
- if (!Number.isFinite(value) || integer2 && !Number.isInteger(value)) {
35372
- throw new AcpExecutionError(
35373
- `Elicitation field ${name} is not a valid number`,
35374
- {},
35375
- "invalid_elicitation_response"
35376
- );
35377
- }
35378
- const minimum = schema["minimum"];
35379
- const maximum = schema["maximum"];
35380
- if (typeof minimum === "number" && value < minimum || typeof maximum === "number" && value > maximum) {
35381
- throw new AcpExecutionError(
35382
- `Elicitation field ${name} is outside the allowed range`,
35383
- {},
35384
- "invalid_elicitation_response"
35385
- );
35386
- }
35387
- }
35388
- function validateElicitationContent(encoded, requestedSchema) {
35389
- let decoded;
35390
- try {
35391
- decoded = JSON.parse(encoded);
35392
- } catch (error62) {
35393
- throw new AcpExecutionError(
35394
- "Elicitation response is not valid JSON",
35395
- { cause: error62 },
35396
- "invalid_elicitation_response"
35397
- );
35398
- }
35399
- if (!isRecord7(decoded) || !isRecord7(requestedSchema) || !isRecord7(requestedSchema["properties"])) {
35400
- throw new AcpExecutionError(
35401
- "Elicitation response does not match the requested form",
35402
- {},
35403
- "invalid_elicitation_response"
35404
- );
35405
- }
35406
- const properties = requestedSchema["properties"];
35407
- const requiredValue = requestedSchema["required"];
35408
- const required2 = new Set(
35409
- Array.isArray(requiredValue) ? requiredValue.filter((entry) => typeof entry === "string") : []
35410
- );
35411
- for (const name of required2) {
35412
- if (!(name in decoded)) {
35413
- throw new AcpExecutionError(`Elicitation field ${name} is required`, {}, "invalid_elicitation_response");
35414
- }
35415
- }
35416
- const validated = {};
35417
- for (const [name, value] of Object.entries(decoded)) {
35418
- const property = properties[name];
35419
- if (!isRecord7(property)) {
35420
- throw new AcpExecutionError(
35421
- `Elicitation field ${name} was not requested`,
35422
- {},
35423
- "invalid_elicitation_response"
35424
- );
35425
- }
35426
- if (property["type"] === "string" && typeof value === "string") {
35427
- validateStringValue(name, value, property);
35428
- validated[name] = value;
35429
- continue;
35430
- }
35431
- if (property["type"] === "number" && typeof value === "number") {
35432
- validateNumericValue(name, value, property, false);
35433
- validated[name] = value;
35434
- continue;
35435
- }
35436
- if (property["type"] === "integer" && typeof value === "number") {
35437
- validateNumericValue(name, value, property, true);
35438
- validated[name] = value;
35439
- continue;
35440
- }
35441
- if (property["type"] === "boolean" && typeof value === "boolean") {
35442
- validated[name] = value;
35443
- continue;
35444
- }
35445
- if (property["type"] === "array" && Array.isArray(value) && value.every((entry) => typeof entry === "string")) {
35446
- const minimum = property["minItems"];
35447
- const maximum = property["maxItems"];
35448
- if (typeof minimum === "number" && value.length < minimum || typeof maximum === "number" && value.length > maximum) {
35449
- throw new AcpExecutionError(
35450
- `Elicitation field ${name} has an invalid selection count`,
35451
- {},
35452
- "invalid_elicitation_response"
35453
- );
35454
- }
35455
- const allowed = normalizeElicitationOptions(property);
35456
- if (allowed.length > 0 && value.some((entry) => !allowed.some((option) => option.value === entry))) {
35457
- throw new AcpExecutionError(
35458
- `Elicitation field ${name} contains an invalid selection`,
35459
- {},
35460
- "invalid_elicitation_response"
35461
- );
35462
- }
35463
- validated[name] = value;
35464
- continue;
35465
- }
35466
- throw new AcpExecutionError(`Elicitation field ${name} has the wrong type`, {}, "invalid_elicitation_response");
35467
- }
35468
- return validated;
35469
- }
35470
35541
  var AcpTurnState = class {
35471
35542
  };
35472
35543
  var IdleAcpTurn = class extends AcpTurnState {
@@ -35933,8 +36004,8 @@ var AcpProcessSession = class _AcpProcessSession {
35933
36004
  );
35934
36005
  }
35935
36006
  this.#capabilities = normalizeAcpCapabilities(initialized);
35936
- this.#agentName = truncate4(initialized.agentInfo?.title ?? initialized.agentInfo?.name ?? this.#agentId, 255);
35937
- this.#agentVersion = truncate4(
36007
+ this.#agentName = truncate3(initialized.agentInfo?.title ?? initialized.agentInfo?.name ?? this.#agentId, 255);
36008
+ this.#agentVersion = truncate3(
35938
36009
  this.#verifiedAgentVersion.length > 0 ? this.#verifiedAgentVersion : initialized.agentInfo?.version ?? "",
35939
36010
  128
35940
36011
  );
@@ -36166,6 +36237,17 @@ var AcpProcessSession = class _AcpProcessSession {
36166
36237
  );
36167
36238
  };
36168
36239
  nativeSessionId = () => this.#nativeSessionId;
36240
+ adoptNativeSessionId = (sessionId) => {
36241
+ if (this.#prompted || this.#nativeSessionId !== sessionId) {
36242
+ throw new AcpExecutionError("The new native Session cannot be adopted", {}, "session_identity_mismatch");
36243
+ }
36244
+ const previousSessionId = this.#mobiusSessionId;
36245
+ this.#store.write(
36246
+ new AcpStoredSession(sessionId, this.#agentId, sessionId, this.#cwd, this.#additionalDirectories, false)
36247
+ );
36248
+ this.#store.remove(previousSessionId);
36249
+ this.#mobiusSessionId = sessionId;
36250
+ };
36169
36251
  configure = async (options) => {
36170
36252
  const existing = this.#configOptions.find((option) => option.id === options.configId);
36171
36253
  if (existing === void 0 || existing.type !== options.valueType) {
@@ -36370,7 +36452,7 @@ var AcpProcessSession = class _AcpProcessSession {
36370
36452
  "ACP agent exited during steering",
36371
36453
  options.signal
36372
36454
  );
36373
- if (!isRecord7(response)) {
36455
+ if (!isRecord6(response)) {
36374
36456
  throw new AcpExecutionError(
36375
36457
  "ACP agent returned an invalid steering response",
36376
36458
  {},
@@ -36487,8 +36569,8 @@ var AcpProcessSession = class _AcpProcessSession {
36487
36569
  const interactionId = `permission-${crypto.randomUUID()}`;
36488
36570
  const options = request.options.slice(0, 20).map((option) => ({
36489
36571
  kind: option.kind,
36490
- name: truncate4(option.name, 255),
36491
- optionId: truncate4(option.optionId, 255)
36572
+ name: truncate3(option.name, 255),
36573
+ optionId: truncate3(option.optionId, 255)
36492
36574
  }));
36493
36575
  if (options.length === 0) {
36494
36576
  throw new AcpExecutionError(
@@ -36510,9 +36592,9 @@ var AcpProcessSession = class _AcpProcessSession {
36510
36592
  kind: SESSION_PERMISSION_REQUESTED_KIND,
36511
36593
  options,
36512
36594
  sessionId: this.#mobiusSessionId,
36513
- title: truncate4(request.toolCall.title ?? "Permission required", 500),
36514
- toolCallId: truncate4(request.toolCall.toolCallId, 255),
36515
- toolKind: truncate4(request.toolCall.kind ?? "other", 64)
36595
+ title: truncate3(request.toolCall.title ?? "Permission required", 500),
36596
+ toolCallId: truncate3(request.toolCall.toolCallId, 255),
36597
+ toolKind: truncate3(request.toolCall.kind ?? "other", 64)
36516
36598
  });
36517
36599
  return await pending.completion.promise;
36518
36600
  } finally {
@@ -36541,7 +36623,7 @@ var AcpProcessSession = class _AcpProcessSession {
36541
36623
  const schemaValue = Reflect.get(request, "requestedSchema");
36542
36624
  const requestedSchema = request.mode === "form" ? schemaValue : {};
36543
36625
  const elicitationIdValue = Reflect.get(request, "elicitationId");
36544
- const elicitationId = request.mode === "url" && typeof elicitationIdValue === "string" ? truncate4(elicitationIdValue, 255) : "";
36626
+ const elicitationId = request.mode === "url" && typeof elicitationIdValue === "string" ? truncate3(elicitationIdValue, 255) : "";
36545
36627
  const pending = new PendingElicitation(interactionId, elicitationId, requestedSchema);
36546
36628
  this.#pendingElicitations.set(interactionId, pending);
36547
36629
  const abort = () => {
@@ -36556,10 +36638,10 @@ var AcpProcessSession = class _AcpProcessSession {
36556
36638
  fields: normalizeElicitationFields(requestedSchema),
36557
36639
  interactionId,
36558
36640
  kind: SESSION_ELICITATION_REQUESTED_KIND,
36559
- message: truncate4(request.message, 2e3),
36641
+ message: truncate3(request.message, 2e3),
36560
36642
  mode: request.mode,
36561
36643
  sessionId: this.#mobiusSessionId,
36562
- url: request.mode === "url" && typeof Reflect.get(request, "url") === "string" ? truncate4(readString4(Reflect.get(request, "url")), 4096) : ""
36644
+ url: request.mode === "url" && typeof Reflect.get(request, "url") === "string" ? truncate3(readString2(Reflect.get(request, "url")), 4096) : ""
36563
36645
  });
36564
36646
  return await pending.completion.promise;
36565
36647
  } finally {
@@ -36637,14 +36719,14 @@ var AcpProcessSession = class _AcpProcessSession {
36637
36719
  );
36638
36720
  } else {
36639
36721
  await this.#turn.activities.finishNarrative();
36640
- await this.bufferAgentText(update.content.text, truncate4(update.messageId ?? "", 255));
36722
+ await this.bufferAgentText(update.content.text, truncate3(update.messageId ?? "", 255));
36641
36723
  }
36642
36724
  } else {
36643
36725
  await this.#turn.activities.finishNarrative();
36644
36726
  await this.flushAgentText();
36645
36727
  await this.emitAgentContent(
36646
36728
  normalizeContentBlock(update.content),
36647
- truncate4(update.messageId ?? "", 255)
36729
+ truncate3(update.messageId ?? "", 255)
36648
36730
  );
36649
36731
  }
36650
36732
  return;
@@ -36683,9 +36765,9 @@ var AcpProcessSession = class _AcpProcessSession {
36683
36765
  }
36684
36766
  if (update.sessionUpdate === "available_commands_update") {
36685
36767
  const commands = update.availableCommands.slice(0, 500).map((command) => ({
36686
- description: truncate4(command.description, 500),
36687
- inputHint: truncate4(command.input?.hint ?? "", 255),
36688
- name: truncate4(command.name, 128)
36768
+ description: truncate3(command.description, 500),
36769
+ inputHint: truncate3(command.input?.hint ?? "", 255),
36770
+ name: truncate3(command.name, 128)
36689
36771
  })).filter((command) => command.name.length > 0);
36690
36772
  this.#commands = commands;
36691
36773
  await this.#getObserver().onCommands({
@@ -36714,10 +36796,10 @@ var AcpProcessSession = class _AcpProcessSession {
36714
36796
  }
36715
36797
  if (update.sessionUpdate === "session_info_update") {
36716
36798
  if (Object.hasOwn(update, "title")) {
36717
- this.#sessionTitle = truncate4(update.title ?? "", 500);
36799
+ this.#sessionTitle = truncate3(update.title ?? "", 500);
36718
36800
  }
36719
36801
  if (Object.hasOwn(update, "updatedAt")) {
36720
- this.#sessionUpdatedAt = truncate4(update.updatedAt ?? "", 128);
36802
+ this.#sessionUpdatedAt = truncate3(update.updatedAt ?? "", 128);
36721
36803
  }
36722
36804
  await this.#getObserver().onInfo({
36723
36805
  kind: SESSION_INFO_UPDATED_KIND,
@@ -36730,7 +36812,7 @@ var AcpProcessSession = class _AcpProcessSession {
36730
36812
  if (update.sessionUpdate === "usage_update") {
36731
36813
  await this.#getObserver().onUsage({
36732
36814
  costAmount: update.cost?.amount ?? 0,
36733
- costCurrency: truncate4(update.cost?.currency ?? "", 16),
36815
+ costCurrency: truncate3(update.cost?.currency ?? "", 16),
36734
36816
  hasCost: update.cost !== void 0 && update.cost !== null,
36735
36817
  kind: SESSION_USAGE_UPDATED_KIND,
36736
36818
  sessionId: this.#mobiusSessionId,
@@ -36803,7 +36885,7 @@ var AcpProcessSession = class _AcpProcessSession {
36803
36885
  );
36804
36886
  }
36805
36887
  if (error62 instanceof RequestError3) {
36806
- throw new AcpExecutionError(truncate4(error62.message, 500), { cause: error62 }, "acp_agent_error");
36888
+ throw new AcpExecutionError(truncate3(error62.message, 500), { cause: error62 }, "acp_agent_error");
36807
36889
  }
36808
36890
  throw error62;
36809
36891
  }
@@ -36872,6 +36954,10 @@ var AcpProcessSession = class _AcpProcessSession {
36872
36954
  }
36873
36955
  };
36874
36956
  };
36957
+
36958
+ // src/acp/session-manager.ts
36959
+ var MAX_ACP_PROCESSES = 10;
36960
+ var SESSION_CONTROL_TIMEOUT_MILLISECONDS = 3e4;
36875
36961
  var AcpProcessEvictionCandidate = class {
36876
36962
  };
36877
36963
  var MissingAcpProcessEvictionCandidate = class extends AcpProcessEvictionCandidate {
@@ -36919,16 +37005,17 @@ var AcpSessionManager = class {
36919
37005
  #transientProcessCount = 0;
36920
37006
  #store;
36921
37007
  #nativeHistoryReader;
37008
+ #sessionIdentity;
36922
37009
  #observer;
36923
- constructor(observer = new NullAcpSessionObserver(), store = new MemoryAcpSessionStore(), nativeHistoryReader = null) {
37010
+ constructor(observer = new NullAcpSessionObserver(), store = new MemoryAcpSessionStore(), nativeHistoryReader = null, sessionIdentity = "assigned") {
36924
37011
  this.#observer = observer;
36925
37012
  this.#store = store;
36926
37013
  this.#nativeHistoryReader = nativeHistoryReader;
37014
+ this.#sessionIdentity = sessionIdentity;
36927
37015
  }
36928
37016
  setObserver = (observer) => {
36929
37017
  this.#observer = observer;
36930
37018
  };
36931
- findLinkedSessions = (agentId, nativeSessionId) => this.#store.findNative(agentId, nativeSessionId);
36932
37019
  #notifyProcessCapacityChanged() {
36933
37020
  const changed = this.#processCapacityChanged;
36934
37021
  this.#processCapacityChanged = Promise.withResolvers();
@@ -37036,7 +37123,13 @@ var AcpSessionManager = class {
37036
37123
  if (retained) {
37037
37124
  this.#sessions.delete(sessionId);
37038
37125
  }
37039
- await this.#retireProcess(runtime, retained, close);
37126
+ try {
37127
+ await this.#retireProcess(runtime, retained, close);
37128
+ } finally {
37129
+ if (retained && this.#sessionIdentity === "native") {
37130
+ this.#store.remove(sessionId);
37131
+ }
37132
+ }
37040
37133
  }
37041
37134
  async #retireNativeBrowserProcess(sessionId, runtime, close) {
37042
37135
  const retained = this.#nativeBrowserSessions.get(sessionId) === runtime;
@@ -37183,7 +37276,14 @@ var AcpSessionManager = class {
37183
37276
  try {
37184
37277
  return await this.#startRetainedSessionProcess(
37185
37278
  options,
37186
- async () => await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics)
37279
+ async () => await AcpProcessSession.start(
37280
+ this.#sessionIdentity === "native" && supportsNativeChat(options.agent.id) && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu.test(
37281
+ options.sessionId
37282
+ ) && this.#store.read(options.sessionId) instanceof MissingAcpStoredSession ? { ...options, origin: { kind: "import", nativeSessionId: options.sessionId } } : options,
37283
+ () => this.#observer,
37284
+ this.#store,
37285
+ metrics
37286
+ )
37187
37287
  );
37188
37288
  } finally {
37189
37289
  this.#preparing.delete(options.sessionId);
@@ -37606,6 +37706,45 @@ var AcpSessionManager = class {
37606
37706
  ]);
37607
37707
  };
37608
37708
  hasPreparedSession = (sessionId, agentId, cwd, additionalDirectories) => this.#sessions.get(sessionId)?.belongsTo(agentId, cwd, additionalDirectories) === true;
37709
+ createNativeSession = async (options) => {
37710
+ const temporarySessionId = `new-${crypto.randomUUID()}`;
37711
+ const temporaryOptions = { ...options, sessionId: temporarySessionId };
37712
+ this.#beginSessionUse(temporarySessionId);
37713
+ try {
37714
+ const runtime = await this.#startPreparation(temporaryOptions);
37715
+ let adopted = false;
37716
+ try {
37717
+ const nativeSessionId = runtime.nativeSessionId();
37718
+ 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)) {
37719
+ throw new AcpExecutionError(
37720
+ "The Agent returned an invalid new Session ID",
37721
+ {},
37722
+ "invalid_native_session_response"
37723
+ );
37724
+ }
37725
+ runtime.adoptNativeSessionId(nativeSessionId);
37726
+ this.#sessions.delete(temporarySessionId);
37727
+ this.#sessions.set(nativeSessionId, runtime);
37728
+ this.#retainedProcesses.set(
37729
+ runtime,
37730
+ new FoundAcpSessionProcessEvictionCandidate(nativeSessionId, runtime)
37731
+ );
37732
+ adopted = true;
37733
+ return nativeSessionId;
37734
+ } finally {
37735
+ if (!adopted) {
37736
+ await this.#retireSessionProcess(
37737
+ temporarySessionId,
37738
+ runtime,
37739
+ async () => await runtime.closeProcess()
37740
+ );
37741
+ }
37742
+ }
37743
+ } finally {
37744
+ this.#store.remove(temporarySessionId);
37745
+ this.#endSessionUse(temporarySessionId);
37746
+ }
37747
+ };
37609
37748
  ensureSession = async (options) => {
37610
37749
  const existing = this.#sessions.get(options.sessionId);
37611
37750
  if (existing !== void 0) {
@@ -37699,6 +37838,25 @@ var AcpSessionManager = class {
37699
37838
  this.#endSessionUse(options.sessionId);
37700
37839
  }
37701
37840
  };
37841
+ loadLinkedSessionHistory = async (options) => {
37842
+ options.signal.throwIfAborted();
37843
+ const stored = this.#store.read(options.sessionId);
37844
+ if (!(stored instanceof FoundAcpStoredSession) || !stored.session.prompted) {
37845
+ return null;
37846
+ }
37847
+ const linked = stored.session;
37848
+ 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])) {
37849
+ throw new AcpExecutionError(
37850
+ "The session belongs to another Agent or workspace",
37851
+ {},
37852
+ "session_identity_mismatch"
37853
+ );
37854
+ }
37855
+ if (this.#nativeHistoryReader === null) {
37856
+ return await this.loadSessionHistory(options);
37857
+ }
37858
+ return await this.#nativeHistoryReader.read(options, linked.nativeSessionId);
37859
+ };
37702
37860
  openNativeSession = async (options, origin, loadHistory) => {
37703
37861
  const key = `${options.agent.id}:${origin.nativeSessionId}`;
37704
37862
  if (this.#nativeOperations.has(key)) {
@@ -37850,253 +38008,490 @@ var AcpSessionManager = class {
37850
38008
  this.#endSessionUse(options.sessionId);
37851
38009
  }
37852
38010
  };
37853
- deleteNativeSession = async (options, nativeSessionId) => {
37854
- this.#beginNativeBrowserUse(options.sessionId);
37855
- try {
37856
- const runtime = await this.#ensureNativeSessionBrowser(options);
37857
- const key = `${options.agent.id}:${nativeSessionId}`;
37858
- const linked = this.#store.findNative(options.agent.id, nativeSessionId);
37859
- if (this.#nativeOperations.has(key) || linked.some(
37860
- (entry) => this.#activeSessionIds.has(entry.sessionId) || this.#preparing.has(entry.sessionId)
37861
- )) {
37862
- throw new AcpExecutionError(
37863
- "Wait for the native session's running operation to finish",
37864
- {},
37865
- "session_busy"
37866
- );
37867
- }
37868
- this.#nativeOperations.add(key);
38011
+ deleteNativeSession = async (options, nativeSessionId) => {
38012
+ this.#beginNativeBrowserUse(options.sessionId);
38013
+ try {
38014
+ const runtime = await this.#ensureNativeSessionBrowser(options);
38015
+ const key = `${options.agent.id}:${nativeSessionId}`;
38016
+ const linked = this.#store.findNative(options.agent.id, nativeSessionId);
38017
+ if (this.#nativeOperations.has(key) || linked.some(
38018
+ (entry) => this.#activeSessionIds.has(entry.sessionId) || this.#preparing.has(entry.sessionId)
38019
+ )) {
38020
+ throw new AcpExecutionError(
38021
+ "Wait for the native session's running operation to finish",
38022
+ {},
38023
+ "session_busy"
38024
+ );
38025
+ }
38026
+ this.#nativeOperations.add(key);
38027
+ try {
38028
+ for (const entry of linked) {
38029
+ const active = this.#sessions.get(entry.sessionId);
38030
+ if (active !== void 0 && active !== runtime) {
38031
+ await this.#retireSessionProcess(entry.sessionId, active, async () => await active.close());
38032
+ }
38033
+ }
38034
+ options.signal.throwIfAborted();
38035
+ await runtime.deleteNativeSession(nativeSessionId, options.signal);
38036
+ const deleted = this.#store.markDeleted(options.agent.id, nativeSessionId);
38037
+ if (runtime.nativeSessionId() === nativeSessionId) {
38038
+ await this.#retireNativeBrowserProcess(
38039
+ options.sessionId,
38040
+ runtime,
38041
+ async () => await runtime.close()
38042
+ );
38043
+ }
38044
+ return deleted;
38045
+ } finally {
38046
+ this.#nativeOperations.delete(key);
38047
+ this.#notifyProcessCapacityChanged();
38048
+ }
38049
+ } finally {
38050
+ this.#endNativeBrowserUse(options.sessionId);
38051
+ }
38052
+ };
38053
+ };
38054
+
38055
+ // src/acp/session-config/apply-session-configuration.ts
38056
+ function invalidSessionConfiguration(message) {
38057
+ return new AcpExecutionError(message, {}, "invalid_session_configuration");
38058
+ }
38059
+ function agentForSessionConfiguration(agent, selections) {
38060
+ try {
38061
+ return applyAgentLaunchSettings(agent, selections);
38062
+ } catch (error62) {
38063
+ if (error62 instanceof Error) {
38064
+ throw invalidSessionConfiguration(error62.message);
38065
+ }
38066
+ throw error62;
38067
+ }
38068
+ }
38069
+ function validateSessionConfigurationSelection(option, selection) {
38070
+ if (option.type !== selection.valueType) {
38071
+ throw invalidSessionConfiguration(`The Agent setting ${selection.configId} changed type`);
38072
+ }
38073
+ if (option.type === "boolean") {
38074
+ if (selection.value.length > 0) {
38075
+ throw invalidSessionConfiguration(`The Agent setting ${selection.configId} has an invalid value`);
38076
+ }
38077
+ return;
38078
+ }
38079
+ if (selection.booleanValue) {
38080
+ throw invalidSessionConfiguration(`The Agent setting ${selection.configId} has an invalid value`);
38081
+ }
38082
+ if (!option.values.some((value) => value.value === selection.value)) {
38083
+ throw invalidSessionConfiguration(`The Agent setting ${selection.configId} has an unavailable value`);
38084
+ }
38085
+ }
38086
+ function sessionConfigurationSelectionIsAvailable(option, selection) {
38087
+ if (option.type !== selection.valueType) {
38088
+ return false;
38089
+ }
38090
+ if (option.type === "boolean") {
38091
+ return selection.value.length === 0;
38092
+ }
38093
+ return !selection.booleanValue && option.values.some((value) => value.value === selection.value);
38094
+ }
38095
+ function sessionConfigurationMatches(option, selection) {
38096
+ validateSessionConfigurationSelection(option, selection);
38097
+ return option.type === "boolean" ? option.booleanValue === selection.booleanValue : option.currentValue === selection.value;
38098
+ }
38099
+ function sessionConfigurationPriority(selection, options) {
38100
+ const option = options.find((candidate) => candidate.id === selection.configId);
38101
+ if (selection.configId === "model" || option?.category === "model") {
38102
+ return 0;
38103
+ }
38104
+ if (selection.configId === "reasoning_effort" || option?.category === "thought_level") {
38105
+ return 1;
38106
+ }
38107
+ if (option?.category === "model_config") {
38108
+ return 2;
38109
+ }
38110
+ return 3;
38111
+ }
38112
+ function assertAppliedSessionConfiguration(options, selections) {
38113
+ const selectionsById = new Map(selections.map((selection) => [selection.configId, selection]));
38114
+ for (const option of options) {
38115
+ const selection = selectionsById.get(option.id);
38116
+ if (selection === void 0 || !sessionConfigurationSelectionIsAvailable(option, selection)) {
38117
+ continue;
38118
+ }
38119
+ if (!sessionConfigurationMatches(option, selection)) {
38120
+ throw invalidSessionConfiguration(`The Turn configuration does not match Agent setting ${option.id}`);
38121
+ }
38122
+ }
38123
+ }
38124
+ function unavailableSessionConfigurationCategory(selection) {
38125
+ if (selection.configId === "model") {
38126
+ return "model";
38127
+ }
38128
+ if (selection.configId === "reasoning_effort") {
38129
+ return "thought_level";
38130
+ }
38131
+ return "unknown";
38132
+ }
38133
+ async function applySessionConfigurationSelection(sessions, audit, options, selection, agent, cwd, additionalDirectories, commandId, sessionId, signal) {
38134
+ const option = options.find((candidate) => candidate.id === selection.configId);
38135
+ if (option === void 0) {
38136
+ warnIgnoredSetting(
38137
+ audit,
38138
+ "session_configuration_setting_ignored",
38139
+ commandId,
38140
+ sessionId,
38141
+ agent.id,
38142
+ selection,
38143
+ unavailableSessionConfigurationCategory(selection),
38144
+ "setting_unavailable"
38145
+ );
38146
+ return options;
38147
+ }
38148
+ if (option.type !== selection.valueType) {
38149
+ warnIgnoredSetting(
38150
+ audit,
38151
+ "session_configuration_setting_ignored",
38152
+ commandId,
38153
+ sessionId,
38154
+ agent.id,
38155
+ selection,
38156
+ option.category,
38157
+ "setting_schema_mismatch"
38158
+ );
38159
+ return options;
38160
+ }
38161
+ if (option.type === "boolean" && selection.value.length > 0 || option.type === "select" && selection.booleanValue) {
38162
+ warnIgnoredSetting(
38163
+ audit,
38164
+ "session_configuration_setting_ignored",
38165
+ commandId,
38166
+ sessionId,
38167
+ agent.id,
38168
+ selection,
38169
+ option.category,
38170
+ "selection_schema_mismatch"
38171
+ );
38172
+ return options;
38173
+ }
38174
+ if (option.type === "select" && !option.values.some((value) => value.value === selection.value)) {
38175
+ warnIgnoredSetting(
38176
+ audit,
38177
+ "session_configuration_setting_ignored",
38178
+ commandId,
38179
+ sessionId,
38180
+ agent.id,
38181
+ selection,
38182
+ option.category,
38183
+ "value_unavailable"
38184
+ );
38185
+ return options;
38186
+ }
38187
+ if (sessionConfigurationMatches(option, selection)) {
38188
+ return options;
38189
+ }
38190
+ return await sessions.configureSession({
38191
+ additionalDirectories,
38192
+ agent,
38193
+ booleanValue: selection.booleanValue,
38194
+ configId: selection.configId,
38195
+ cwd,
38196
+ requestId: `cfg_${randomUUID()}`,
38197
+ sessionId,
38198
+ signal,
38199
+ value: selection.value,
38200
+ valueType: selection.valueType
38201
+ });
38202
+ }
38203
+ async function applyCompleteSessionConfiguration(sessions, audit, initialOptions, selections, agent, cwd, additionalDirectories, commandId, sessionId, signal) {
38204
+ let options = initialOptions;
38205
+ const orderedSelections = selections.toSorted((left, right) => {
38206
+ const priority = sessionConfigurationPriority(left, initialOptions) - sessionConfigurationPriority(right, initialOptions);
38207
+ return priority === 0 ? left.configId.localeCompare(right.configId) : priority;
38208
+ });
38209
+ for (const selection of orderedSelections) {
38210
+ options = await applySessionConfigurationSelection(
38211
+ sessions,
38212
+ audit,
38213
+ options,
38214
+ selection,
38215
+ agent,
38216
+ cwd,
38217
+ additionalDirectories,
38218
+ commandId,
38219
+ sessionId,
38220
+ signal
38221
+ );
38222
+ }
38223
+ assertAppliedSessionConfiguration(options, selections);
38224
+ }
38225
+ function warnIgnoredSetting(audit, event, commandId, sessionId, agentId, selection, category, reason) {
38226
+ const details = {
38227
+ agentId,
38228
+ category,
38229
+ configId: selection.configId,
38230
+ reason,
38231
+ requestedValue: selection.value
38232
+ };
38233
+ audit.record({ commandId, details, event, sessionId });
38234
+ process.stderr.write(`Mobius daemon warning ${JSON.stringify({ commandId, event, sessionId, ...details })}
38235
+ `);
38236
+ }
38237
+
38238
+ // src/agent-catalog/discover-agent-settings.ts
38239
+ import { createHash as createHash2 } from "node:crypto";
38240
+ function isUnavailableModel(cause, modelSettingId, requestedModel) {
38241
+ return cause instanceof AcpConfigurationValueUnavailableError && cause.configId === modelSettingId && cause.requestedValue === requestedModel;
38242
+ }
38243
+ function unsupportedModelIds(unsupportedModels) {
38244
+ return [...new Set(unsupportedModels.map((item) => item.requestedValue))];
38245
+ }
38246
+ async function discoverAgentSettings(command, config2, directories, sessions, signal) {
38247
+ const agent = config2.catalog.find(command.agentId);
38248
+ const cwd = await directories.resolve(config2.bindingId, "default", signal);
38249
+ const inspectedBaseSnapshot = await sessions.inspectAgentSettings({
38250
+ additionalDirectories: [],
38251
+ agent,
38252
+ cwd,
38253
+ signal
38254
+ });
38255
+ const baseSnapshot = {
38256
+ agentName: inspectedBaseSnapshot.agentName,
38257
+ agentVersion: inspectedBaseSnapshot.agentVersion,
38258
+ configOptions: await discoverOpenCodeModelOptions(agent, cwd, inspectedBaseSnapshot.configOptions, signal)
38259
+ };
38260
+ const baseModel = modelOption(baseSnapshot.configOptions);
38261
+ const unsupportedModels = [];
38262
+ let selectedSnapshot = baseSnapshot;
38263
+ if (command.model !== void 0) {
38264
+ if (baseModel === void 0 || baseModel.type !== "select" || !baseModel.values.some((value) => value.value === command.model)) {
38265
+ unsupportedModels.push(
38266
+ new AcpConfigurationValueUnavailableError(
38267
+ baseModel?.id ?? "model",
38268
+ command.model,
38269
+ baseModel?.values.map((value) => value.value) ?? []
38270
+ )
38271
+ );
38272
+ } else {
37869
38273
  try {
37870
- for (const entry of linked) {
37871
- const active = this.#sessions.get(entry.sessionId);
37872
- if (active !== void 0 && active !== runtime) {
37873
- await this.#retireSessionProcess(entry.sessionId, active, async () => await active.close());
37874
- }
37875
- }
37876
- options.signal.throwIfAborted();
37877
- await runtime.deleteNativeSession(nativeSessionId, options.signal);
37878
- const deleted = this.#store.markDeleted(options.agent.id, nativeSessionId);
37879
- if (runtime.nativeSessionId() === nativeSessionId) {
37880
- await this.#retireNativeBrowserProcess(
37881
- options.sessionId,
37882
- runtime,
37883
- async () => await runtime.close()
37884
- );
38274
+ selectedSnapshot = await sessions.inspectAgentSettings({
38275
+ additionalDirectories: [],
38276
+ agent,
38277
+ cwd,
38278
+ model: command.model,
38279
+ signal
38280
+ });
38281
+ } catch (cause) {
38282
+ signal.throwIfAborted();
38283
+ if (!isUnavailableModel(cause, baseModel.id, command.model)) {
38284
+ throw cause;
37885
38285
  }
37886
- return deleted;
37887
- } finally {
37888
- this.#nativeOperations.delete(key);
37889
- this.#notifyProcessCapacityChanged();
38286
+ unsupportedModels.push(cause);
37890
38287
  }
37891
- } finally {
37892
- this.#endNativeBrowserUse(options.sessionId);
37893
38288
  }
37894
- };
37895
- };
37896
-
37897
- // src/agent-catalog/agent-settings-adapter.ts
37898
- var AGENT_DEFAULT_VALUE = "agent_default";
37899
- var READ_ONLY_VALUE = "read-only";
37900
- var WORKSPACE_WRITE_VALUE = "workspace-write";
37901
- var DANGER_FULL_ACCESS_VALUE = "danger-full-access";
37902
- var DEEPSEEK_HARNESS_ACCESS_MODE_SETTING_ID = "dsh_access_mode";
37903
- var OPENCODE_PERMISSION_SETTING_ID = "opencode_permission";
37904
- var AgentSettingsConfigurationError = class extends Error {
37905
- code = "invalid_session_configuration";
37906
- constructor(message, options = {}) {
37907
- super(message, options);
37908
- this.name = "AgentSettingsConfigurationError";
37909
- }
37910
- };
37911
- var AgentSettingsLaunchSelectionResult = class {
37912
- agent;
37913
- handled;
37914
- constructor(agent, handled) {
37915
- this.agent = agent;
37916
- this.handled = handled;
37917
- }
37918
- };
37919
- var AppliedAgentLaunchSettings = class {
37920
- agent;
37921
- sessionConfigurations;
37922
- constructor(agent, sessionConfigurations) {
37923
- this.agent = agent;
37924
- this.sessionConfigurations = Object.freeze([...sessionConfigurations]);
37925
38289
  }
37926
- };
37927
- var AgentSettingsAdapter = class {
37928
- modelEffortResolution = AGENT_MODEL_EFFORT_RESOLUTION_ON_MODEL_SELECTION;
37929
- applyLaunchSelection = (agent, _selection) => new AgentSettingsLaunchSelectionResult(agent, false);
37930
- settings = (_agent) => [];
37931
- };
37932
- function selectValue(name, value, description) {
38290
+ const adapter = agentSettingsAdapterForAgent(agent.id);
38291
+ const modelEffort = await discoverModelEffort(
38292
+ command,
38293
+ agent,
38294
+ adapter.modelEffortResolution,
38295
+ baseSnapshot.configOptions,
38296
+ selectedSnapshot.configOptions,
38297
+ unsupportedModels,
38298
+ cwd,
38299
+ sessions,
38300
+ signal
38301
+ );
38302
+ const baseSettings = withoutUnsupportedModels(
38303
+ settingsFromSnapshot(agent, baseSnapshot.configOptions),
38304
+ baseModel?.id ?? "",
38305
+ modelEffort.unsupportedModelIds
38306
+ );
38307
+ const settings = withoutUnsupportedModels(
38308
+ settingsFromSnapshot(agent, selectedSnapshot.configOptions),
38309
+ baseModel?.id ?? "",
38310
+ modelEffort.unsupportedModelIds
38311
+ );
37933
38312
  return {
37934
- description,
37935
- groupId: "",
37936
- groupName: "",
37937
- name,
37938
- value
38313
+ event: {
38314
+ agentId: command.agentId,
38315
+ agentName: selectedSnapshot.agentName,
38316
+ agentVersion: selectedSnapshot.agentVersion,
38317
+ kind: AGENT_SETTINGS_DISCOVERED_KIND,
38318
+ modelEffort,
38319
+ requestId: command.requestId,
38320
+ settings,
38321
+ settingsRevision: settingsRevision(agent, baseSnapshot.agentVersion, baseSettings, modelEffort)
38322
+ },
38323
+ unsupportedModels
37939
38324
  };
37940
38325
  }
37941
- function selectSetting(id, name, description, currentValue, values) {
38326
+ function settingFromOption(option) {
37942
38327
  return {
37943
- booleanValue: false,
37944
- category: "execution",
37945
- currentValue,
37946
- description,
37947
- id,
37948
- name,
37949
- type: "select",
37950
- values
38328
+ booleanValue: option.booleanValue,
38329
+ category: option.category,
38330
+ defaultValue: option.type === "boolean" ? "" : option.currentValue,
38331
+ description: option.description,
38332
+ id: option.id,
38333
+ name: option.name,
38334
+ type: option.type,
38335
+ values: option.values
37951
38336
  };
37952
38337
  }
37953
- function selectedValue(selection, configId) {
37954
- if (selection.configId !== configId || selection.valueType !== "select" || selection.booleanValue || selection.value.length === 0) {
37955
- throw new AgentSettingsConfigurationError("The requested Agent setting is invalid");
38338
+ function settingsFromSnapshot(agent, configOptions) {
38339
+ const settings = [
38340
+ ...agentSettingsAdapterForAgent(agent.id).settings(agent).map(settingFromOption),
38341
+ ...configOptions.map(settingFromOption)
38342
+ ];
38343
+ const identifiers = /* @__PURE__ */ new Set();
38344
+ for (const setting of settings) {
38345
+ if (identifiers.has(setting.id)) {
38346
+ throw new AcpExecutionError(
38347
+ "The Agent returned duplicate setting identifiers",
38348
+ {},
38349
+ "invalid_session_configuration"
38350
+ );
38351
+ }
38352
+ identifiers.add(setting.id);
37956
38353
  }
37957
- return selection.value;
37958
- }
37959
- function validValue(values, value) {
37960
- if (!values.some((candidate) => candidate.value === value)) {
37961
- throw new AgentSettingsConfigurationError("The requested Agent setting is unavailable");
38354
+ if (settings.length > 128) {
38355
+ throw new AcpExecutionError("The Agent returned too many settings", {}, "invalid_session_configuration");
37962
38356
  }
37963
- return value;
38357
+ return settings;
37964
38358
  }
37965
- var dshAccessModes = Object.freeze([
37966
- selectValue("Read only", READ_ONLY_VALUE, "Allow inspection without local writes."),
37967
- selectValue("Workspace write", WORKSPACE_WRITE_VALUE, "Allow changes in the selected workspace."),
37968
- selectValue("Full access", DANGER_FULL_ACCESS_VALUE, "Allow unrestricted local execution.")
37969
- ]);
37970
- var DeepSeekHarnessSettingsAdapter = class extends AgentSettingsAdapter {
37971
- settings = (agent) => {
37972
- const configured = agent.environment["DSH_PERMISSION_MODE"] ?? WORKSPACE_WRITE_VALUE;
37973
- return [
37974
- selectSetting(
37975
- DEEPSEEK_HARNESS_ACCESS_MODE_SETTING_ID,
37976
- "Access mode",
37977
- "Controls the local side effects allowed for this DeepSeek Harness session.",
37978
- validValue(dshAccessModes, configured),
37979
- dshAccessModes
37980
- )
37981
- ];
37982
- };
37983
- applyLaunchSelection = (agent, selection) => {
37984
- if (selection.configId !== DEEPSEEK_HARNESS_ACCESS_MODE_SETTING_ID) {
37985
- return new AgentSettingsLaunchSelectionResult(agent, false);
38359
+ function withoutUnsupportedModels(settings, modelSettingId, unsupportedModelIds2) {
38360
+ if (modelSettingId.length === 0 || unsupportedModelIds2.length === 0) {
38361
+ return settings;
38362
+ }
38363
+ const unsupported = new Set(unsupportedModelIds2);
38364
+ return settings.map((setting) => {
38365
+ if (setting.id !== modelSettingId || setting.type !== "select") {
38366
+ return setting;
37986
38367
  }
37987
- const value = validValue(dshAccessModes, selectedValue(selection, DEEPSEEK_HARNESS_ACCESS_MODE_SETTING_ID));
37988
- return new AgentSettingsLaunchSelectionResult(
37989
- agent.withEnvironment({ ...agent.environment, DSH_PERMISSION_MODE: value }),
37990
- true
37991
- );
38368
+ return {
38369
+ ...setting,
38370
+ defaultValue: unsupported.has(setting.defaultValue) ? "" : setting.defaultValue,
38371
+ values: setting.values.filter((value) => !unsupported.has(value.value))
38372
+ };
38373
+ });
38374
+ }
38375
+ function modelOption(options) {
38376
+ return options.find((option) => option.id === "model" || option.category === "model");
38377
+ }
38378
+ function effortOption(options) {
38379
+ return options.find((option) => option.id === "reasoning_effort" || option.category === "thought_level");
38380
+ }
38381
+ function unavailableModelEffort() {
38382
+ return {
38383
+ effortSettingId: "",
38384
+ modelSettingId: "",
38385
+ resolution: AGENT_MODEL_EFFORT_RESOLUTION_UNAVAILABLE,
38386
+ unsupportedModelIds: [],
38387
+ valuesByModel: {}
37992
38388
  };
37993
- };
37994
- var openCodePermissionModes = Object.freeze([
37995
- selectValue("Agent default", AGENT_DEFAULT_VALUE, "Keep OpenCode's existing permission policy."),
37996
- selectValue("Read only", READ_ONLY_VALUE, "Allow inspection without local writes."),
37997
- selectValue("Workspace write", WORKSPACE_WRITE_VALUE, "Allow changes in the selected workspace."),
37998
- selectValue("Full access", DANGER_FULL_ACCESS_VALUE, "Allow unrestricted local execution.")
37999
- ]);
38000
- function openCodeConfiguration(environment) {
38001
- const encoded = environment["OPENCODE_CONFIG_CONTENT"];
38002
- if (encoded === void 0 || encoded.length === 0) {
38003
- return {};
38004
- }
38005
- let parsed;
38006
- try {
38007
- parsed = JSON.parse(encoded);
38008
- } catch (cause) {
38009
- throw new AgentSettingsConfigurationError("The OpenCode configuration is invalid", { cause });
38389
+ }
38390
+ async function discoverModelEffort(command, agent, resolution, initialOptions, selectedOptions, initiallyUnsupportedModels, cwd, sessions, signal) {
38391
+ const model = modelOption(initialOptions);
38392
+ const unsupportedModels = initiallyUnsupportedModels;
38393
+ if (resolution !== AGENT_MODEL_EFFORT_RESOLUTION_COMPLETE && resolution !== AGENT_MODEL_EFFORT_RESOLUTION_ON_MODEL_SELECTION) {
38394
+ return { ...unavailableModelEffort(), unsupportedModelIds: unsupportedModelIds(unsupportedModels) };
38010
38395
  }
38011
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
38012
- throw new AgentSettingsConfigurationError("The OpenCode configuration is invalid");
38396
+ if (model === void 0 || model.type !== "select" || model.values.length === 0) {
38397
+ return { ...unavailableModelEffort(), unsupportedModelIds: unsupportedModelIds(unsupportedModels) };
38013
38398
  }
38014
- return Object.freeze({ ...parsed });
38015
- }
38016
- function openCodePermission(value) {
38017
- if (value === READ_ONLY_VALUE) {
38399
+ const inspectModel = async (modelValue) => (await sessions.inspectAgentSettings({
38400
+ additionalDirectories: [],
38401
+ agent,
38402
+ cwd,
38403
+ model: modelValue,
38404
+ signal
38405
+ })).configOptions;
38406
+ const valuesByModel = {};
38407
+ if (resolution === "complete") {
38408
+ const effort = effortOption(initialOptions);
38409
+ if (effort === void 0 || effort.type !== "select" || effort.values.length < 2) {
38410
+ return {
38411
+ ...unavailableModelEffort(),
38412
+ unsupportedModelIds: unsupportedModelIds(unsupportedModels)
38413
+ };
38414
+ }
38415
+ for (const value of model.values) {
38416
+ if (unsupportedModels.some((diagnostic) => diagnostic.requestedValue === value.value)) {
38417
+ continue;
38418
+ }
38419
+ try {
38420
+ const selectedEffort2 = effortOption(await inspectModel(value.value));
38421
+ valuesByModel[value.value] = selectedEffort2?.type === "select" ? selectedEffort2.values : [];
38422
+ } catch (cause) {
38423
+ signal.throwIfAborted();
38424
+ if (!isUnavailableModel(cause, model.id, value.value)) {
38425
+ throw cause;
38426
+ }
38427
+ unsupportedModels.push(cause);
38428
+ }
38429
+ }
38018
38430
  return {
38019
- "*": "deny",
38020
- glob: "allow",
38021
- grep: "allow",
38022
- lsp: "allow",
38023
- read: "allow",
38024
- skill: "allow"
38431
+ effortSettingId: effort.id,
38432
+ modelSettingId: model.id,
38433
+ resolution: "complete",
38434
+ unsupportedModelIds: unsupportedModelIds(unsupportedModels),
38435
+ valuesByModel
38025
38436
  };
38026
38437
  }
38027
- if (value === WORKSPACE_WRITE_VALUE) {
38438
+ if (command.model !== void 0) {
38439
+ const modelUnsupported = unsupportedModels.some((diagnostic) => diagnostic.requestedValue === command.model);
38440
+ const selectedEffort2 = effortOption(selectedOptions);
38441
+ if (!modelUnsupported) {
38442
+ valuesByModel[command.model] = selectedEffort2?.type === "select" ? selectedEffort2.values : [];
38443
+ }
38028
38444
  return {
38029
- "*": "allow",
38030
- external_directory: "ask"
38445
+ effortSettingId: selectedEffort2?.id ?? "",
38446
+ modelSettingId: model.id,
38447
+ resolution: "on_model_selection",
38448
+ unsupportedModelIds: unsupportedModelIds(unsupportedModels),
38449
+ valuesByModel
38031
38450
  };
38032
38451
  }
38033
- return "allow";
38034
- }
38035
- var OpenCodeSettingsAdapter = class extends AgentSettingsAdapter {
38036
- settings = (agent) => {
38037
- const currentValue = agent.environment["MOBIUS_OPENCODE_PERMISSION"] ?? AGENT_DEFAULT_VALUE;
38038
- return [
38039
- selectSetting(
38040
- OPENCODE_PERMISSION_SETTING_ID,
38041
- "Permissions",
38042
- "Controls OpenCode's local permission policy.",
38043
- validValue(openCodePermissionModes, currentValue),
38044
- openCodePermissionModes
38045
- )
38046
- ];
38047
- };
38048
- applyLaunchSelection = (agent, selection) => {
38049
- if (selection.configId !== OPENCODE_PERMISSION_SETTING_ID) {
38050
- return new AgentSettingsLaunchSelectionResult(agent, false);
38051
- }
38052
- const value = validValue(openCodePermissionModes, selectedValue(selection, OPENCODE_PERMISSION_SETTING_ID));
38053
- if (value === AGENT_DEFAULT_VALUE) {
38054
- return new AgentSettingsLaunchSelectionResult(agent, true);
38452
+ const defaultModel = model.type === "select" ? model.currentValue : "";
38453
+ const reportedEffort = effortOption(selectedOptions);
38454
+ let selectedEffort = reportedEffort;
38455
+ if (defaultModel.length > 0 && reportedEffort === void 0) {
38456
+ try {
38457
+ selectedEffort = effortOption(await inspectModel(defaultModel));
38458
+ } catch (cause) {
38459
+ signal.throwIfAborted();
38460
+ if (!isUnavailableModel(cause, model.id, defaultModel)) {
38461
+ throw cause;
38462
+ }
38463
+ unsupportedModels.push(cause);
38055
38464
  }
38056
- return new AgentSettingsLaunchSelectionResult(
38057
- agent.withEnvironment({
38058
- ...agent.environment,
38059
- MOBIUS_OPENCODE_PERMISSION: value,
38060
- OPENCODE_CONFIG_CONTENT: JSON.stringify({
38061
- ...openCodeConfiguration(agent.environment),
38062
- permission: openCodePermission(value)
38063
- })
38064
- }),
38065
- true
38066
- );
38067
- };
38068
- };
38069
- var CodexSettingsAdapter = class extends AgentSettingsAdapter {
38070
- modelEffortResolution = AGENT_MODEL_EFFORT_RESOLUTION_COMPLETE;
38071
- };
38072
- var genericAdapter = new AgentSettingsAdapter();
38073
- var codexAdapter = new CodexSettingsAdapter();
38074
- var deepSeekHarnessAdapter = new DeepSeekHarnessSettingsAdapter();
38075
- var openCodeAdapter = new OpenCodeSettingsAdapter();
38076
- function agentSettingsAdapterForAgent(agentId) {
38077
- if (agentId === "codex") {
38078
- return codexAdapter;
38079
- }
38080
- if (agentId === "deepseek-harness") {
38081
- return deepSeekHarnessAdapter;
38082
38465
  }
38083
- if (agentId === "opencode") {
38084
- return openCodeAdapter;
38466
+ if (defaultModel.length > 0 && !unsupportedModels.some((diagnostic) => diagnostic.requestedValue === defaultModel)) {
38467
+ valuesByModel[defaultModel] = selectedEffort?.type === "select" ? selectedEffort.values : [];
38085
38468
  }
38086
- return genericAdapter;
38469
+ return {
38470
+ effortSettingId: selectedEffort?.id ?? "",
38471
+ modelSettingId: model.id,
38472
+ resolution: "on_model_selection",
38473
+ unsupportedModelIds: unsupportedModelIds(unsupportedModels),
38474
+ valuesByModel
38475
+ };
38087
38476
  }
38088
- function applyAgentLaunchSettings(agent, selections) {
38089
- const adapter = agentSettingsAdapterForAgent(agent.id);
38090
- let selectedAgent = agent;
38091
- const sessionConfigurations = [];
38092
- for (const selection of selections) {
38093
- const applied = adapter.applyLaunchSelection(selectedAgent, selection);
38094
- selectedAgent = applied.agent;
38095
- if (!applied.handled) {
38096
- sessionConfigurations.push(selection);
38097
- }
38098
- }
38099
- return new AppliedAgentLaunchSettings(selectedAgent, sessionConfigurations);
38477
+ function settingsRevision(agent, reportedAgentVersion, settings, modelEffort) {
38478
+ const revisionModelEffort = modelEffort.resolution === AGENT_MODEL_EFFORT_RESOLUTION_COMPLETE ? modelEffort : {
38479
+ effortSettingId: "",
38480
+ modelSettingId: modelEffort.modelSettingId,
38481
+ resolution: modelEffort.resolution,
38482
+ unsupportedModelIds: modelEffort.unsupportedModelIds,
38483
+ valuesByModel: {}
38484
+ };
38485
+ return createHash2("sha256").update(
38486
+ JSON.stringify({
38487
+ adapterVersion: agent.kind === "acp-adapter-process" ? agent.adapterVersion : agent.agentVersion,
38488
+ agentId: agent.id,
38489
+ agentVersion: agent.agentVersion,
38490
+ modelEffort: revisionModelEffort,
38491
+ reportedAgentVersion,
38492
+ settings
38493
+ })
38494
+ ).digest("hex");
38100
38495
  }
38101
38496
 
38102
38497
  // src/agent-catalog/publish-agent-catalog.ts
@@ -38762,7 +39157,7 @@ var LocalAuthorizationError = class extends Error {
38762
39157
  // src/authorization/workspace-directory.ts
38763
39158
  import { readdir as readdir2, realpath as realpath8, stat as stat7 } from "node:fs/promises";
38764
39159
  import { homedir as homedir2 } from "node:os";
38765
- import { basename as basename4, dirname as dirname5, isAbsolute as isAbsolute10, join as join15, normalize as normalize4, relative as relative4 } from "node:path";
39160
+ import { basename as basename4, dirname as dirname3, isAbsolute as isAbsolute10, join as join15, normalize as normalize4, relative as relative4 } from "node:path";
38766
39161
  var WorkspaceDirectoryListing = class {
38767
39162
  directoryId;
38768
39163
  directoryLabel;
@@ -38886,7 +39281,7 @@ var WorkspaceDirectoryService = class {
38886
39281
  }
38887
39282
  }
38888
39283
  entries.sort((a, b) => a.name.localeCompare(b.name));
38889
- const parent = dirname5(target);
39284
+ const parent = dirname3(target);
38890
39285
  return new WorkspaceDirectoryListing(
38891
39286
  id,
38892
39287
  this.label(target),
@@ -38911,7 +39306,7 @@ var WorkspaceDirectoryService = class {
38911
39306
  };
38912
39307
 
38913
39308
  // src/daemon-diagnostic-log.ts
38914
- import { appendFileSync, mkdirSync as mkdirSync3, readFileSync as readFileSync2, renameSync, statSync as statSync3, writeFileSync } from "node:fs";
39309
+ import { appendFileSync, mkdirSync, readFileSync as readFileSync2, renameSync, statSync as statSync3, writeFileSync } from "node:fs";
38915
39310
  import { join as join16 } from "node:path";
38916
39311
  var MAXIMUM_DAEMON_LOG_BYTES = 1 * 1024 * 1024;
38917
39312
  var DaemonDiagnosticLog = class {
@@ -38927,7 +39322,7 @@ var DaemonDiagnosticLog = class {
38927
39322
  const encoded = `${diagnostic.replace(/[\r\n]+/gu, " ").trim()}
38928
39323
  `;
38929
39324
  const encodedBytes = Buffer.byteLength(encoded);
38930
- mkdirSync3(this.#directory, { mode: 448, recursive: true });
39325
+ mkdirSync(this.#directory, { mode: 448, recursive: true });
38931
39326
  let existingBytes = 0;
38932
39327
  try {
38933
39328
  existingBytes = statSync3(this.#path).size;
@@ -39385,8 +39780,91 @@ var readCodexHistory = async (agent, cwd, nativeSessionId, signal) => await read
39385
39780
  var readCodexFullHistory = async (agent, cwd, nativeSessionId, signal) => await readCodexHistoryWithOptions(agent, cwd, nativeSessionId, signal, { detail: "rich" });
39386
39781
 
39387
39782
  // src/native-sessions/service.ts
39388
- import { randomUUID } from "node:crypto";
39783
+ import { randomUUID as randomUUID2 } from "node:crypto";
39389
39784
  import { basename as basename5 } from "node:path";
39785
+
39786
+ // src/native-sessions/claude-history.ts
39787
+ async function readClaudeHistory(sessions, directories, bindingId, options, nativeSessionId) {
39788
+ let cursor = null;
39789
+ let inspected = 0;
39790
+ for (let pageNumber = 0; pageNumber < 500 && inspected < 500; pageNumber += 1) {
39791
+ const page = await sessions.listNativeSessions(options, cursor);
39792
+ inspected += page.sessions.length;
39793
+ const found = page.sessions.find((entry) => entry.sessionId === nativeSessionId);
39794
+ if (found !== void 0) {
39795
+ const primary = await directories.identify(bindingId, found.cwd, options.signal);
39796
+ const additional = await Promise.all(
39797
+ found.additionalDirectories.map(
39798
+ async (directory) => await directories.identify(bindingId, directory, options.signal)
39799
+ )
39800
+ );
39801
+ if (primary.path !== options.cwd || additional.length !== options.additionalDirectories.length || additional.some((directory, index2) => directory.path !== options.additionalDirectories[index2])) {
39802
+ throw new AcpExecutionError(
39803
+ "The native Session belongs to another workspace.",
39804
+ {},
39805
+ "session_identity_mismatch"
39806
+ );
39807
+ }
39808
+ return await sessions.previewNativeSession(options, nativeSessionId);
39809
+ }
39810
+ if (page.nextCursor === null || page.nextCursor === cursor) {
39811
+ break;
39812
+ }
39813
+ cursor = page.nextCursor ?? null;
39814
+ }
39815
+ throw new AcpExecutionError("The native Session was not found.", {}, "native_session_not_found");
39816
+ }
39817
+
39818
+ // src/native-sessions/claude-adapter.ts
39819
+ var claudeSessionAdapter = {
39820
+ linkedHistory: async ({ sessions, directories, bindingId, options, nativeSessionId }) => await readClaudeHistory(sessions, directories, bindingId, options, nativeSessionId),
39821
+ history: async ({ sessions, directories, bindingId, options, nativeSessionId }) => await readClaudeHistory(sessions, directories, bindingId, options, nativeSessionId),
39822
+ preview: async ({ sessions, options, nativeSessionId }) => await sessions.previewNativeSession(options, nativeSessionId)
39823
+ };
39824
+
39825
+ // src/native-sessions/codex-adapter.ts
39826
+ async function verifiedHistory(context, full) {
39827
+ const { options, nativeSessionId, directories, bindingId } = context;
39828
+ const snapshot = full ? await readCodexFullHistory(options.agent, options.cwd, nativeSessionId, options.signal) : await readCodexHistory(options.agent, options.cwd, nativeSessionId, options.signal);
39829
+ const resolved = await directories.identify(bindingId, snapshot.cwd, options.signal);
39830
+ if (snapshot.nativeSessionId !== nativeSessionId || resolved.path !== options.cwd) {
39831
+ throw new AcpExecutionError(
39832
+ "Codex returned history for a different session or workspace.",
39833
+ {},
39834
+ "invalid_native_session_response"
39835
+ );
39836
+ }
39837
+ return snapshot.history;
39838
+ }
39839
+ var codexSessionAdapter = {
39840
+ linkedHistory: async (context) => await verifiedHistory(context, true),
39841
+ history: async (context) => await verifiedHistory(context, true),
39842
+ // Codex enforces an exclusive writer per thread. Its read-only app-server
39843
+ // history path keeps externally owned conversations previewable.
39844
+ preview: async (context) => await verifiedHistory(context, false)
39845
+ };
39846
+
39847
+ // src/native-sessions/agent-adapter.ts
39848
+ var genericSessionAdapter = {
39849
+ linkedHistory: async () => {
39850
+ throw new AcpExecutionError("This Agent does not support Chat history", {}, "native_session_unsupported");
39851
+ },
39852
+ history: async () => {
39853
+ throw new AcpExecutionError("Native history is unavailable for this Agent", {}, "native_session_unsupported");
39854
+ },
39855
+ preview: async ({ sessions, options, nativeSessionId }) => await sessions.previewNativeSession(options, nativeSessionId)
39856
+ };
39857
+ function nativeSessionAdapter(agentId) {
39858
+ if (agentId === "codex") {
39859
+ return codexSessionAdapter;
39860
+ }
39861
+ if (agentId === "claude") {
39862
+ return claudeSessionAdapter;
39863
+ }
39864
+ return genericSessionAdapter;
39865
+ }
39866
+
39867
+ // src/native-sessions/service.ts
39390
39868
  var NativeSessionService = class {
39391
39869
  #entries = /* @__PURE__ */ new Map();
39392
39870
  #cursors = /* @__PURE__ */ new Map();
@@ -39416,6 +39894,61 @@ var NativeSessionService = class {
39416
39894
  sessionId: command.sessionId,
39417
39895
  signal
39418
39896
  };
39897
+ if (command.action === "linked-history") {
39898
+ const nativeSessionId = nativeSessionIdSchema.parse(command.targetSessionId);
39899
+ if (this.#sessions.hasPreparedSession(nativeSessionId, options.agent.id, cwd, additionalDirectories) && await this.#sessions.loadLinkedSessionHistory({ ...options, sessionId: nativeSessionId }) === null) {
39900
+ this.record(command, "native_session_history_read");
39901
+ return {
39902
+ action: "linked-history",
39903
+ history: {
39904
+ status: "available",
39905
+ messages: [],
39906
+ truncated: false,
39907
+ coveredCommandIds: [],
39908
+ coveredMessageIds: []
39909
+ },
39910
+ kind: "native.session.result",
39911
+ requestId: command.requestId,
39912
+ sessionId: command.sessionId,
39913
+ targetSessionId: command.targetSessionId
39914
+ };
39915
+ }
39916
+ const history = await nativeSessionAdapter(options.agent.id).linkedHistory({
39917
+ sessions: this.#sessions,
39918
+ directories: this.#directories,
39919
+ bindingId: command.bindingId,
39920
+ options,
39921
+ nativeSessionId
39922
+ });
39923
+ this.record(command, "native_session_history_read");
39924
+ return {
39925
+ action: "linked-history",
39926
+ history,
39927
+ kind: "native.session.result",
39928
+ requestId: command.requestId,
39929
+ sessionId: command.sessionId,
39930
+ targetSessionId: command.targetSessionId
39931
+ };
39932
+ }
39933
+ if (command.action === "create") {
39934
+ if (!supportsNativeChat(options.agent.id)) {
39935
+ throw new AcpExecutionError(
39936
+ "Native session creation is unavailable for this Agent",
39937
+ {},
39938
+ "native_session_unsupported"
39939
+ );
39940
+ }
39941
+ const nativeSessionId = await this.#sessions.createNativeSession(options);
39942
+ signal.throwIfAborted();
39943
+ this.record(command, "native_session_created");
39944
+ return {
39945
+ action: "create",
39946
+ kind: "native.session.result",
39947
+ nativeSessionId,
39948
+ requestId: command.requestId,
39949
+ sessionId: command.sessionId
39950
+ };
39951
+ }
39419
39952
  const prepared = await this.#sessions.prepareNativeSessionBrowser(options);
39420
39953
  if (!prepared.capabilities.listSessions) {
39421
39954
  throw new AcpExecutionError(
@@ -39431,7 +39964,7 @@ var NativeSessionService = class {
39431
39964
  if (authorized === null) {
39432
39965
  return null;
39433
39966
  }
39434
- const entryId = randomUUID();
39967
+ const entryId = randomUUID2();
39435
39968
  if (this.#entries.size >= 5e3) {
39436
39969
  this.#entries.clear();
39437
39970
  }
@@ -39443,7 +39976,7 @@ var NativeSessionService = class {
39443
39976
  });
39444
39977
  return {
39445
39978
  entryId,
39446
- mobiusSessionIds: this.#sessions.findLinkedSessions(command.agentId, info.sessionId).filter((session) => session.prompted && session.cwd === authorized.cwd).map((session) => session.sessionId),
39979
+ nativeSessionId: info.sessionId,
39447
39980
  title: info.title ?? "Untitled session",
39448
39981
  directoryId: authorized.directoryId,
39449
39982
  directoryLabel: authorized.directoryLabel,
@@ -39486,7 +40019,7 @@ var NativeSessionService = class {
39486
40019
  "invalid_native_session_response"
39487
40020
  );
39488
40021
  }
39489
- nextCursor = randomUUID();
40022
+ nextCursor = randomUUID2();
39490
40023
  if (this.#cursors.size >= 500) {
39491
40024
  this.#cursors.clear();
39492
40025
  }
@@ -39550,7 +40083,13 @@ var NativeSessionService = class {
39550
40083
  }
39551
40084
  const target = await this.resolveTarget(command, options, selected);
39552
40085
  if (command.action === "history") {
39553
- const history = await this.readHistory(command, options, target, signal);
40086
+ const history = await nativeSessionAdapter(options.agent.id).history({
40087
+ sessions: this.#sessions,
40088
+ directories: this.#directories,
40089
+ bindingId: command.bindingId,
40090
+ options: { ...options, cwd: target.cwd, additionalDirectories: target.additionalDirectories },
40091
+ nativeSessionId: target.info.sessionId
40092
+ });
39554
40093
  signal.throwIfAborted();
39555
40094
  this.record(command, "native_session_history_read");
39556
40095
  return {
@@ -39562,7 +40101,13 @@ var NativeSessionService = class {
39562
40101
  };
39563
40102
  }
39564
40103
  if (command.action === "preview") {
39565
- const history = await this.previewHistory(command, options, target, signal);
40104
+ const history = await nativeSessionAdapter(options.agent.id).preview({
40105
+ sessions: this.#sessions,
40106
+ directories: this.#directories,
40107
+ bindingId: command.bindingId,
40108
+ options: { ...options, cwd: target.cwd, additionalDirectories: target.additionalDirectories },
40109
+ nativeSessionId: target.info.sessionId
40110
+ });
39566
40111
  signal.throwIfAborted();
39567
40112
  this.record(command, "native_session_previewed");
39568
40113
  return {
@@ -39716,43 +40261,6 @@ var NativeSessionService = class {
39716
40261
  title: command.title
39717
40262
  };
39718
40263
  };
39719
- previewHistory = async (command, options, target, signal) => {
39720
- if (options.agent.id !== "codex") {
39721
- return await this.#sessions.previewNativeSession(
39722
- { ...options, cwd: target.cwd, additionalDirectories: target.additionalDirectories },
39723
- target.info.sessionId
39724
- );
39725
- }
39726
- const snapshot = await readCodexHistory(options.agent, target.cwd, target.info.sessionId, signal);
39727
- const resolved = await this.#directories.identify(command.bindingId, snapshot.cwd, signal);
39728
- if (snapshot.nativeSessionId !== target.info.sessionId || resolved.path !== target.cwd) {
39729
- throw new AcpExecutionError(
39730
- "Codex returned history for a different session or workspace.",
39731
- {},
39732
- "invalid_native_session_response"
39733
- );
39734
- }
39735
- return snapshot.history;
39736
- };
39737
- readHistory = async (command, options, target, signal) => {
39738
- if (options.agent.id !== "codex") {
39739
- throw new AcpExecutionError(
39740
- "Native history is unavailable for this Agent",
39741
- {},
39742
- "native_session_unsupported"
39743
- );
39744
- }
39745
- const snapshot = await readCodexFullHistory(options.agent, target.cwd, target.info.sessionId, signal);
39746
- const resolved = await this.#directories.identify(command.bindingId, snapshot.cwd, signal);
39747
- if (snapshot.nativeSessionId !== target.info.sessionId || resolved.path !== target.cwd) {
39748
- throw new AcpExecutionError(
39749
- "Codex returned history for a different session or workspace.",
39750
- {},
39751
- "invalid_native_session_response"
39752
- );
39753
- }
39754
- return snapshot.history;
39755
- };
39756
40264
  authorizeEntry = async (command, options, info) => {
39757
40265
  try {
39758
40266
  const primary = await this.#directories.identify(command.bindingId, info.cwd, options.signal);
@@ -39837,7 +40345,7 @@ var NativeSessionService = class {
39837
40345
  };
39838
40346
 
39839
40347
  // src/prompt-artifact-resolver.ts
39840
- import { createHash as createHash2 } from "node:crypto";
40348
+ import { createHash as createHash3 } from "node:crypto";
39841
40349
  import { fetch as fetch3 } from "undici";
39842
40350
  var ARTIFACT_SCHEME = "mobius-artifact:";
39843
40351
  var ARTIFACT_DOWNLOAD_TIMEOUT_MILLISECONDS = 2e4;
@@ -39976,7 +40484,7 @@ async function download(config2, command, reference, signal) {
39976
40484
  );
39977
40485
  }
39978
40486
  const bytes = await responseBytes(response, reference.byteLength, requestSignal);
39979
- if (createHash2("sha256").update(bytes).digest("hex") !== reference.sha256) {
40487
+ if (createHash3("sha256").update(bytes).digest("hex") !== reference.sha256) {
39980
40488
  throw new PromptArtifactError(
39981
40489
  "artifact_integrity_failed",
39982
40490
  "The prompt artifact failed integrity validation"
@@ -40442,7 +40950,7 @@ var RelayConnectionDiagnostics = class {
40442
40950
  };
40443
40951
 
40444
40952
  // src/relay-connection/liveness.ts
40445
- import { randomUUID as randomUUID2 } from "node:crypto";
40953
+ import { randomUUID as randomUUID3 } from "node:crypto";
40446
40954
  var HEARTBEAT_ACK_TIMEOUT_MILLISECONDS = 1e4;
40447
40955
  var HEARTBEAT_INTERVAL_MILLISECONDS = 2e4;
40448
40956
  var RelayLivenessState = class {
@@ -40531,7 +41039,7 @@ var RelayConnectionLiveness = class {
40531
41039
  }
40532
41040
  throw new Error("Heartbeat was scheduled in an invalid state");
40533
41041
  }
40534
- const heartbeatId = randomUUID2();
41042
+ const heartbeatId = randomUUID3();
40535
41043
  this.#state = new AwaitingHeartbeatAckState(
40536
41044
  heartbeatId,
40537
41045
  this.#timer.schedule(this.#handleTimeout, HEARTBEAT_ACK_TIMEOUT_MILLISECONDS)
@@ -40548,26 +41056,26 @@ var RelayConnectionLiveness = class {
40548
41056
  };
40549
41057
 
40550
41058
  // src/relay-connection/session-event-outbox.ts
40551
- import { mkdirSync as mkdirSync4 } from "node:fs";
40552
- import { dirname as dirname6 } from "node:path";
40553
- import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
41059
+ import { createHash as createHash4 } from "node:crypto";
41060
+ import { DatabaseSync } from "node:sqlite";
40554
41061
  var DEFAULT_OUTBOX_LIMITS = {
40555
41062
  criticalEventBytes: 136 * 1024 * 1024,
40556
41063
  runtimeDeliveryBytes: 64 * 1024 * 1024,
40557
41064
  runtimeDeliveryCount: 64,
40558
41065
  standardEventBytes: 128 * 1024 * 1024
40559
41066
  };
41067
+ var MAX_TERMINAL_RECEIPTS = 1024;
40560
41068
  var SessionEventOutboxCapacityError = class extends Error {
40561
41069
  code = "session_event_outbox_full";
40562
41070
  constructor() {
40563
- super("The durable Session event outbox is full");
41071
+ super("The in-memory Session event outbox is full");
40564
41072
  this.name = "SessionEventOutboxCapacityError";
40565
41073
  }
40566
41074
  };
40567
41075
  var RuntimeDeliveryInboxCapacityError = class extends Error {
40568
41076
  code = "runtime_delivery_inbox_full";
40569
41077
  constructor() {
40570
- super("The durable Runtime delivery inbox is full");
41078
+ super("The in-memory Runtime delivery inbox is full");
40571
41079
  this.name = "RuntimeDeliveryInboxCapacityError";
40572
41080
  }
40573
41081
  };
@@ -40612,11 +41120,10 @@ function rowString(row, field) {
40612
41120
  var SessionEventOutbox = class {
40613
41121
  #database;
40614
41122
  #limits;
40615
- constructor(path2, limits = DEFAULT_OUTBOX_LIMITS) {
41123
+ constructor(limits = DEFAULT_OUTBOX_LIMITS) {
40616
41124
  validateLimits(limits);
40617
41125
  this.#limits = limits;
40618
- mkdirSync4(dirname6(path2), { recursive: true });
40619
- this.#database = new DatabaseSync3(path2);
41126
+ this.#database = new DatabaseSync(":memory:");
40620
41127
  this.#database.exec(`
40621
41128
  CREATE TABLE IF NOT EXISTS relay_session_event_outbox (
40622
41129
  ordinal INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -40644,7 +41151,7 @@ var SessionEventOutbox = class {
40644
41151
  CREATE TABLE IF NOT EXISTS relay_turn_receipts (
40645
41152
  command_id TEXT PRIMARY KEY,
40646
41153
  session_id TEXT NOT NULL,
40647
- command_json TEXT NOT NULL,
41154
+ command_hash TEXT NOT NULL,
40648
41155
  attempt_id TEXT NOT NULL,
40649
41156
  state TEXT NOT NULL CHECK (
40650
41157
  state IN ('dispatching', 'running', 'succeeded', 'failed', 'cancelled')
@@ -40675,19 +41182,20 @@ var SessionEventOutbox = class {
40675
41182
  `);
40676
41183
  }
40677
41184
  claimExecution = (commandId, sessionId, commandJson) => {
41185
+ const commandHash = createHash4("sha256").update(commandJson).digest("hex");
40678
41186
  this.#database.exec("BEGIN IMMEDIATE");
40679
41187
  try {
40680
41188
  const existing = this.#database.prepare(
40681
- `SELECT session_id, command_json, attempt_id, state
41189
+ `SELECT session_id, command_hash, attempt_id, state
40682
41190
  FROM relay_turn_receipts WHERE command_id = ?`
40683
41191
  ).get(commandId);
40684
41192
  if (typeof existing === "object" && existing !== null) {
40685
41193
  const storedSessionId = Reflect.get(existing, "session_id");
40686
- const storedCommand = Reflect.get(existing, "command_json");
41194
+ const storedCommandHash = Reflect.get(existing, "command_hash");
40687
41195
  const attemptId2 = Reflect.get(existing, "attempt_id");
40688
41196
  const state = Reflect.get(existing, "state");
40689
- if (storedSessionId !== sessionId || storedCommand !== commandJson || typeof attemptId2 !== "string" || !isDaemonExecutionState(state)) {
40690
- throw new Error("The daemon command identity conflicts with its durable receipt");
41197
+ if (storedSessionId !== sessionId || storedCommandHash !== commandHash || typeof attemptId2 !== "string" || !isDaemonExecutionState(state)) {
41198
+ throw new Error("The daemon command identity conflicts with its in-memory receipt");
40691
41199
  }
40692
41200
  this.#database.exec("COMMIT");
40693
41201
  return { attemptId: attemptId2, commandId, kind: "duplicate", state };
@@ -40695,9 +41203,9 @@ var SessionEventOutbox = class {
40695
41203
  const attemptId = crypto.randomUUID();
40696
41204
  this.#database.prepare(
40697
41205
  `INSERT INTO relay_turn_receipts (
40698
- command_id, session_id, command_json, attempt_id, state
41206
+ command_id, session_id, command_hash, attempt_id, state
40699
41207
  ) VALUES (?, ?, ?, ?, 'dispatching')`
40700
- ).run(commandId, sessionId, commandJson, attemptId);
41208
+ ).run(commandId, sessionId, commandHash, attemptId);
40701
41209
  this.#database.exec("COMMIT");
40702
41210
  return {
40703
41211
  attemptId,
@@ -40724,11 +41232,21 @@ var SessionEventOutbox = class {
40724
41232
  throw new Error("The daemon execution transition is invalid");
40725
41233
  }
40726
41234
  this.#database.prepare(`UPDATE relay_turn_receipts SET state = ? WHERE command_id = ?`).run(state, commandId);
41235
+ if (state === "succeeded" || state === "failed" || state === "cancelled") {
41236
+ this.#database.prepare(
41237
+ `DELETE FROM relay_turn_receipts
41238
+ WHERE state IN ('succeeded', 'failed', 'cancelled')
41239
+ AND rowid NOT IN (
41240
+ SELECT rowid FROM relay_turn_receipts
41241
+ WHERE state IN ('succeeded', 'failed', 'cancelled')
41242
+ ORDER BY rowid DESC LIMIT ?
41243
+ )`
41244
+ ).run(MAX_TERMINAL_RECEIPTS);
41245
+ }
40727
41246
  };
40728
41247
  /**
40729
- * The Attempt this Runtime durably claimed for a command, when that Attempt never reached a
40730
- * terminal state. A restarted Runtime has no in-memory Turn for a command it was executing before
40731
- * the restart, so this is the only record of the Attempt identity the Relay is still waiting on.
41248
+ * The Attempt this live Runtime claimed for a command that has not reached a terminal state.
41249
+ * Receipts disappear when the daemon process exits.
40732
41250
  */
40733
41251
  findUnsettledAttemptId = (commandId, sessionId) => {
40734
41252
  const row = this.#database.prepare(`SELECT attempt_id, state FROM relay_turn_receipts WHERE command_id = ? AND session_id = ?`).get(commandId, sessionId);
@@ -40777,7 +41295,7 @@ var SessionEventOutbox = class {
40777
41295
  WHERE event_id = ? AND session_id = ?`
40778
41296
  ).run(rejection.eventId, rejection.sessionId);
40779
41297
  if (deletion.changes !== 1) {
40780
- throw new Error("The rejected session event could not be removed from the durable outbox");
41298
+ throw new Error("The rejected session event could not be removed from the in-memory outbox");
40781
41299
  }
40782
41300
  this.#decrementEventState(byteLength);
40783
41301
  this.#database.exec("COMMIT");
@@ -40796,7 +41314,7 @@ var SessionEventOutbox = class {
40796
41314
  enqueueCritical = (sessionId, payload, attemptId = "") => this.#enqueueBounded(sessionId, payload, attemptId, this.#limits.criticalEventBytes);
40797
41315
  /**
40798
41316
  * Bytes still available to standard Session events. The daemon uses this to shed
40799
- * superseded streaming events instead of filling the durable outbox, so a long Turn
41317
+ * superseded streaming events instead of filling the in-memory outbox, so a long Turn
40800
41318
  * behind a slow Relay cannot make the next enqueue throw.
40801
41319
  */
40802
41320
  standardCapacityRemaining = () => {
@@ -40821,7 +41339,7 @@ var SessionEventOutbox = class {
40821
41339
  const payload = rowString(existing, "payload_json");
40822
41340
  const state = runtimeDeliveryState(existing);
40823
41341
  if (sessionId !== delivery.sessionId || payload !== delivery.payload) {
40824
- throw new Error("The Runtime delivery identity conflicts with its durable receipt");
41342
+ throw new Error("The Runtime delivery identity conflicts with its in-memory receipt");
40825
41343
  }
40826
41344
  this.#database.exec("COMMIT");
40827
41345
  return new StoredRuntimeDelivery(delivery.deliveryId, sessionId, payload, state, true);
@@ -40989,7 +41507,7 @@ var SessionEventOutbox = class {
40989
41507
  WHERE event_id = ? AND session_id = ?`
40990
41508
  ).run(eventId, sessionId);
40991
41509
  if (deletion.changes !== 1) {
40992
- throw new Error("The acknowledged session event could not be removed from the durable outbox");
41510
+ throw new Error("The acknowledged session event could not be removed from the in-memory outbox");
40993
41511
  }
40994
41512
  this.#decrementEventState(byteLength);
40995
41513
  this.#database.exec("COMMIT");
@@ -41471,7 +41989,7 @@ var DaemonSessionEventPublisher = class {
41471
41989
  };
41472
41990
  /**
41473
41991
  * Enqueue a standard event, shedding it instead of ending the daemon when the
41474
- * durable outbox is full.
41992
+ * in-memory outbox is full.
41475
41993
  *
41476
41994
  * A capacity error used to escape the coalescing timer that publishes activities,
41477
41995
  * so the process exited and every restart died on the same retained backlog. A full
@@ -41514,7 +42032,7 @@ var DaemonSessionEventPublisher = class {
41514
42032
  return;
41515
42033
  }
41516
42034
  this.#shedEventKinds.add(kind);
41517
- console.warn(`Mobius daemon is dropping durable "${kind}" events because the Session event outbox is full`);
42035
+ console.warn(`Mobius daemon is dropping queued "${kind}" events because the Session event outbox is full`);
41518
42036
  };
41519
42037
  acknowledge = (acknowledgement) => {
41520
42038
  if (!this.#outbox.acknowledge(acknowledgement)) {
@@ -41783,262 +42301,6 @@ async function resolveSessionDirectories(directories, bindingId, directoryId2, a
41783
42301
  }
41784
42302
  return new ResolvedSessionDirectories(cwd, additionalDirectories, additionalDirectoryEntries);
41785
42303
  }
41786
- function isUnavailableModel(cause, modelSettingId, requestedModel) {
41787
- return cause instanceof AcpConfigurationValueUnavailableError && cause.configId === modelSettingId && cause.requestedValue === requestedModel;
41788
- }
41789
- function unsupportedModelIds(unsupportedModels) {
41790
- return [...new Set(unsupportedModels.map((item) => item.requestedValue))];
41791
- }
41792
- async function discoverAgentSettings(command, config2, directories, sessions, signal) {
41793
- const agent = config2.catalog.find(command.agentId);
41794
- const cwd = await directories.resolve(config2.bindingId, "default", signal);
41795
- const inspectedBaseSnapshot = await sessions.inspectAgentSettings({
41796
- additionalDirectories: [],
41797
- agent,
41798
- cwd,
41799
- signal
41800
- });
41801
- const baseSnapshot = {
41802
- agentName: inspectedBaseSnapshot.agentName,
41803
- agentVersion: inspectedBaseSnapshot.agentVersion,
41804
- configOptions: await discoverOpenCodeModelOptions(agent, cwd, inspectedBaseSnapshot.configOptions, signal)
41805
- };
41806
- const baseModel = modelOption(baseSnapshot.configOptions);
41807
- const unsupportedModels = [];
41808
- let selectedSnapshot = baseSnapshot;
41809
- if (command.model !== void 0) {
41810
- if (baseModel === void 0 || baseModel.type !== "select" || !baseModel.values.some((value) => value.value === command.model)) {
41811
- unsupportedModels.push(
41812
- new AcpConfigurationValueUnavailableError(
41813
- baseModel?.id ?? "model",
41814
- command.model,
41815
- baseModel?.values.map((value) => value.value) ?? []
41816
- )
41817
- );
41818
- } else {
41819
- try {
41820
- selectedSnapshot = await sessions.inspectAgentSettings({
41821
- additionalDirectories: [],
41822
- agent,
41823
- cwd,
41824
- model: command.model,
41825
- signal
41826
- });
41827
- } catch (cause) {
41828
- signal.throwIfAborted();
41829
- if (!isUnavailableModel(cause, baseModel.id, command.model)) {
41830
- throw cause;
41831
- }
41832
- unsupportedModels.push(cause);
41833
- }
41834
- }
41835
- }
41836
- const adapter = agentSettingsAdapterForAgent(agent.id);
41837
- const modelEffort = await discoverModelEffort(
41838
- command,
41839
- agent,
41840
- adapter.modelEffortResolution,
41841
- baseSnapshot.configOptions,
41842
- selectedSnapshot.configOptions,
41843
- unsupportedModels,
41844
- cwd,
41845
- sessions,
41846
- signal
41847
- );
41848
- const baseSettings = withoutUnsupportedModels(
41849
- settingsFromSnapshot(agent, baseSnapshot.configOptions),
41850
- baseModel?.id ?? "",
41851
- modelEffort.unsupportedModelIds
41852
- );
41853
- const settings = withoutUnsupportedModels(
41854
- settingsFromSnapshot(agent, selectedSnapshot.configOptions),
41855
- baseModel?.id ?? "",
41856
- modelEffort.unsupportedModelIds
41857
- );
41858
- return {
41859
- event: {
41860
- agentId: command.agentId,
41861
- agentName: selectedSnapshot.agentName,
41862
- agentVersion: selectedSnapshot.agentVersion,
41863
- kind: AGENT_SETTINGS_DISCOVERED_KIND,
41864
- modelEffort,
41865
- requestId: command.requestId,
41866
- settings,
41867
- settingsRevision: settingsRevision(agent, baseSnapshot.agentVersion, baseSettings, modelEffort)
41868
- },
41869
- unsupportedModels
41870
- };
41871
- }
41872
- function settingFromOption(option) {
41873
- return {
41874
- booleanValue: option.booleanValue,
41875
- category: option.category,
41876
- defaultValue: option.type === "boolean" ? "" : option.currentValue,
41877
- description: option.description,
41878
- id: option.id,
41879
- name: option.name,
41880
- type: option.type,
41881
- values: option.values
41882
- };
41883
- }
41884
- function settingsFromSnapshot(agent, configOptions) {
41885
- const settings = [
41886
- ...agentSettingsAdapterForAgent(agent.id).settings(agent).map(settingFromOption),
41887
- ...configOptions.map(settingFromOption)
41888
- ];
41889
- const identifiers = /* @__PURE__ */ new Set();
41890
- for (const setting of settings) {
41891
- if (identifiers.has(setting.id)) {
41892
- throw new AcpExecutionError(
41893
- "The Agent returned duplicate setting identifiers",
41894
- {},
41895
- "invalid_session_configuration"
41896
- );
41897
- }
41898
- identifiers.add(setting.id);
41899
- }
41900
- if (settings.length > 128) {
41901
- throw new AcpExecutionError("The Agent returned too many settings", {}, "invalid_session_configuration");
41902
- }
41903
- return settings;
41904
- }
41905
- function withoutUnsupportedModels(settings, modelSettingId, unsupportedModelIds2) {
41906
- if (modelSettingId.length === 0 || unsupportedModelIds2.length === 0) {
41907
- return settings;
41908
- }
41909
- const unsupported = new Set(unsupportedModelIds2);
41910
- return settings.map((setting) => {
41911
- if (setting.id !== modelSettingId || setting.type !== "select") {
41912
- return setting;
41913
- }
41914
- return {
41915
- ...setting,
41916
- defaultValue: unsupported.has(setting.defaultValue) ? "" : setting.defaultValue,
41917
- values: setting.values.filter((value) => !unsupported.has(value.value))
41918
- };
41919
- });
41920
- }
41921
- function modelOption(options) {
41922
- return options.find((option) => option.id === "model" || option.category === "model");
41923
- }
41924
- function effortOption(options) {
41925
- return options.find((option) => option.id === "reasoning_effort" || option.category === "thought_level");
41926
- }
41927
- function unavailableModelEffort() {
41928
- return {
41929
- effortSettingId: "",
41930
- modelSettingId: "",
41931
- resolution: AGENT_MODEL_EFFORT_RESOLUTION_UNAVAILABLE,
41932
- unsupportedModelIds: [],
41933
- valuesByModel: {}
41934
- };
41935
- }
41936
- async function discoverModelEffort(command, agent, resolution, initialOptions, selectedOptions, initiallyUnsupportedModels, cwd, sessions, signal) {
41937
- const model = modelOption(initialOptions);
41938
- const unsupportedModels = initiallyUnsupportedModels;
41939
- if (resolution !== AGENT_MODEL_EFFORT_RESOLUTION_COMPLETE && resolution !== AGENT_MODEL_EFFORT_RESOLUTION_ON_MODEL_SELECTION) {
41940
- return { ...unavailableModelEffort(), unsupportedModelIds: unsupportedModelIds(unsupportedModels) };
41941
- }
41942
- if (model === void 0 || model.type !== "select" || model.values.length === 0) {
41943
- return { ...unavailableModelEffort(), unsupportedModelIds: unsupportedModelIds(unsupportedModels) };
41944
- }
41945
- const inspectModel = async (modelValue) => (await sessions.inspectAgentSettings({
41946
- additionalDirectories: [],
41947
- agent,
41948
- cwd,
41949
- model: modelValue,
41950
- signal
41951
- })).configOptions;
41952
- const valuesByModel = {};
41953
- if (resolution === "complete") {
41954
- const effort = effortOption(initialOptions);
41955
- if (effort === void 0 || effort.type !== "select" || effort.values.length < 2) {
41956
- return {
41957
- ...unavailableModelEffort(),
41958
- unsupportedModelIds: unsupportedModelIds(unsupportedModels)
41959
- };
41960
- }
41961
- for (const value of model.values) {
41962
- if (unsupportedModels.some((diagnostic) => diagnostic.requestedValue === value.value)) {
41963
- continue;
41964
- }
41965
- try {
41966
- const selectedEffort2 = effortOption(await inspectModel(value.value));
41967
- valuesByModel[value.value] = selectedEffort2?.type === "select" ? selectedEffort2.values : [];
41968
- } catch (cause) {
41969
- signal.throwIfAborted();
41970
- if (!isUnavailableModel(cause, model.id, value.value)) {
41971
- throw cause;
41972
- }
41973
- unsupportedModels.push(cause);
41974
- }
41975
- }
41976
- return {
41977
- effortSettingId: effort.id,
41978
- modelSettingId: model.id,
41979
- resolution: "complete",
41980
- unsupportedModelIds: unsupportedModelIds(unsupportedModels),
41981
- valuesByModel
41982
- };
41983
- }
41984
- if (command.model !== void 0) {
41985
- const modelUnsupported = unsupportedModels.some((diagnostic) => diagnostic.requestedValue === command.model);
41986
- const selectedEffort2 = effortOption(selectedOptions);
41987
- if (!modelUnsupported) {
41988
- valuesByModel[command.model] = selectedEffort2?.type === "select" ? selectedEffort2.values : [];
41989
- }
41990
- return {
41991
- effortSettingId: selectedEffort2?.id ?? "",
41992
- modelSettingId: model.id,
41993
- resolution: "on_model_selection",
41994
- unsupportedModelIds: unsupportedModelIds(unsupportedModels),
41995
- valuesByModel
41996
- };
41997
- }
41998
- const defaultModel = model.type === "select" ? model.currentValue : "";
41999
- const reportedEffort = effortOption(selectedOptions);
42000
- let selectedEffort = reportedEffort;
42001
- if (defaultModel.length > 0 && reportedEffort === void 0) {
42002
- try {
42003
- selectedEffort = effortOption(await inspectModel(defaultModel));
42004
- } catch (cause) {
42005
- signal.throwIfAborted();
42006
- if (!isUnavailableModel(cause, model.id, defaultModel)) {
42007
- throw cause;
42008
- }
42009
- unsupportedModels.push(cause);
42010
- }
42011
- }
42012
- if (defaultModel.length > 0 && !unsupportedModels.some((diagnostic) => diagnostic.requestedValue === defaultModel)) {
42013
- valuesByModel[defaultModel] = selectedEffort?.type === "select" ? selectedEffort.values : [];
42014
- }
42015
- return {
42016
- effortSettingId: selectedEffort?.id ?? "",
42017
- modelSettingId: model.id,
42018
- resolution: "on_model_selection",
42019
- unsupportedModelIds: unsupportedModelIds(unsupportedModels),
42020
- valuesByModel
42021
- };
42022
- }
42023
- function settingsRevision(agent, reportedAgentVersion, settings, modelEffort) {
42024
- const revisionModelEffort = modelEffort.resolution === AGENT_MODEL_EFFORT_RESOLUTION_COMPLETE ? modelEffort : {
42025
- effortSettingId: "",
42026
- modelSettingId: modelEffort.modelSettingId,
42027
- resolution: modelEffort.resolution,
42028
- unsupportedModelIds: modelEffort.unsupportedModelIds,
42029
- valuesByModel: {}
42030
- };
42031
- return createHash3("sha256").update(
42032
- JSON.stringify({
42033
- adapterVersion: agent.kind === "acp-adapter-process" ? agent.adapterVersion : agent.agentVersion,
42034
- agentId: agent.id,
42035
- agentVersion: agent.agentVersion,
42036
- modelEffort: revisionModelEffort,
42037
- reportedAgentVersion,
42038
- settings
42039
- })
42040
- ).digest("hex");
42041
- }
42042
42304
  async function executeWorkspaceList(socket, command, directories, audit, signal) {
42043
42305
  try {
42044
42306
  const listing = await directories.list(command.bindingId, command.directoryId, signal);
@@ -42544,187 +42806,6 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
42544
42806
  console.error("Mobius daemon command failed", error62);
42545
42807
  }
42546
42808
  }
42547
- function invalidSessionConfiguration(message) {
42548
- return new AcpExecutionError(message, {}, "invalid_session_configuration");
42549
- }
42550
- function agentForSessionConfiguration(agent, selections) {
42551
- try {
42552
- return applyAgentLaunchSettings(agent, selections);
42553
- } catch (error62) {
42554
- if (error62 instanceof Error) {
42555
- throw invalidSessionConfiguration(error62.message);
42556
- }
42557
- throw error62;
42558
- }
42559
- }
42560
- function validateSessionConfigurationSelection(option, selection) {
42561
- if (option.type !== selection.valueType) {
42562
- throw invalidSessionConfiguration(`The Agent setting ${selection.configId} changed type`);
42563
- }
42564
- if (option.type === "boolean") {
42565
- if (selection.value.length > 0) {
42566
- throw invalidSessionConfiguration(`The Agent setting ${selection.configId} has an invalid value`);
42567
- }
42568
- return;
42569
- }
42570
- if (selection.booleanValue) {
42571
- throw invalidSessionConfiguration(`The Agent setting ${selection.configId} has an invalid value`);
42572
- }
42573
- if (!option.values.some((value) => value.value === selection.value)) {
42574
- throw invalidSessionConfiguration(`The Agent setting ${selection.configId} has an unavailable value`);
42575
- }
42576
- }
42577
- function sessionConfigurationSelectionIsAvailable(option, selection) {
42578
- if (option.type !== selection.valueType) {
42579
- return false;
42580
- }
42581
- if (option.type === "boolean") {
42582
- return selection.value.length === 0;
42583
- }
42584
- return !selection.booleanValue && option.values.some((value) => value.value === selection.value);
42585
- }
42586
- function sessionConfigurationMatches(option, selection) {
42587
- validateSessionConfigurationSelection(option, selection);
42588
- return option.type === "boolean" ? option.booleanValue === selection.booleanValue : option.currentValue === selection.value;
42589
- }
42590
- function sessionConfigurationPriority(selection, options) {
42591
- const option = options.find((candidate) => candidate.id === selection.configId);
42592
- if (selection.configId === "model" || option?.category === "model") {
42593
- return 0;
42594
- }
42595
- if (selection.configId === "reasoning_effort" || option?.category === "thought_level") {
42596
- return 1;
42597
- }
42598
- if (option?.category === "model_config") {
42599
- return 2;
42600
- }
42601
- return 3;
42602
- }
42603
- function assertAppliedSessionConfiguration(options, selections) {
42604
- const selectionsById = new Map(selections.map((selection) => [selection.configId, selection]));
42605
- for (const option of options) {
42606
- const selection = selectionsById.get(option.id);
42607
- if (selection === void 0 || !sessionConfigurationSelectionIsAvailable(option, selection)) {
42608
- continue;
42609
- }
42610
- if (!sessionConfigurationMatches(option, selection)) {
42611
- throw invalidSessionConfiguration(`The Turn configuration does not match Agent setting ${option.id}`);
42612
- }
42613
- }
42614
- }
42615
- function unavailableSessionConfigurationCategory(selection) {
42616
- if (selection.configId === "model") {
42617
- return "model";
42618
- }
42619
- if (selection.configId === "reasoning_effort") {
42620
- return "thought_level";
42621
- }
42622
- return "unknown";
42623
- }
42624
- async function applySessionConfigurationSelection(sessions, audit, options, selection, agent, cwd, additionalDirectories, commandId, sessionId, signal) {
42625
- const option = options.find((candidate) => candidate.id === selection.configId);
42626
- if (option === void 0) {
42627
- warnIgnoredSetting(
42628
- audit,
42629
- "session_configuration_setting_ignored",
42630
- commandId,
42631
- sessionId,
42632
- agent.id,
42633
- selection,
42634
- unavailableSessionConfigurationCategory(selection),
42635
- "setting_unavailable"
42636
- );
42637
- return options;
42638
- }
42639
- if (option.type !== selection.valueType) {
42640
- warnIgnoredSetting(
42641
- audit,
42642
- "session_configuration_setting_ignored",
42643
- commandId,
42644
- sessionId,
42645
- agent.id,
42646
- selection,
42647
- option.category,
42648
- "setting_schema_mismatch"
42649
- );
42650
- return options;
42651
- }
42652
- if (option.type === "boolean" && selection.value.length > 0 || option.type === "select" && selection.booleanValue) {
42653
- warnIgnoredSetting(
42654
- audit,
42655
- "session_configuration_setting_ignored",
42656
- commandId,
42657
- sessionId,
42658
- agent.id,
42659
- selection,
42660
- option.category,
42661
- "selection_schema_mismatch"
42662
- );
42663
- return options;
42664
- }
42665
- if (option.type === "select" && !option.values.some((value) => value.value === selection.value)) {
42666
- warnIgnoredSetting(
42667
- audit,
42668
- "session_configuration_setting_ignored",
42669
- commandId,
42670
- sessionId,
42671
- agent.id,
42672
- selection,
42673
- option.category,
42674
- "value_unavailable"
42675
- );
42676
- return options;
42677
- }
42678
- if (sessionConfigurationMatches(option, selection)) {
42679
- return options;
42680
- }
42681
- return await sessions.configureSession({
42682
- additionalDirectories,
42683
- agent,
42684
- booleanValue: selection.booleanValue,
42685
- configId: selection.configId,
42686
- cwd,
42687
- requestId: `cfg_${randomUUID3()}`,
42688
- sessionId,
42689
- signal,
42690
- value: selection.value,
42691
- valueType: selection.valueType
42692
- });
42693
- }
42694
- async function applyCompleteSessionConfiguration(sessions, audit, initialOptions, selections, agent, cwd, additionalDirectories, commandId, sessionId, signal) {
42695
- let options = initialOptions;
42696
- const orderedSelections = selections.toSorted((left, right) => {
42697
- const priority = sessionConfigurationPriority(left, initialOptions) - sessionConfigurationPriority(right, initialOptions);
42698
- return priority === 0 ? left.configId.localeCompare(right.configId) : priority;
42699
- });
42700
- for (const selection of orderedSelections) {
42701
- options = await applySessionConfigurationSelection(
42702
- sessions,
42703
- audit,
42704
- options,
42705
- selection,
42706
- agent,
42707
- cwd,
42708
- additionalDirectories,
42709
- commandId,
42710
- sessionId,
42711
- signal
42712
- );
42713
- }
42714
- assertAppliedSessionConfiguration(options, selections);
42715
- }
42716
- function warnIgnoredSetting(audit, event, commandId, sessionId, agentId, selection, category, reason) {
42717
- const details = {
42718
- agentId,
42719
- category,
42720
- configId: selection.configId,
42721
- reason,
42722
- requestedValue: selection.value
42723
- };
42724
- audit.record({ commandId, details, event, sessionId });
42725
- process.stderr.write(`Mobius daemon warning ${JSON.stringify({ commandId, event, sessionId, ...details })}
42726
- `);
42727
- }
42728
42809
  function waitForRelayRetry(signal, timer) {
42729
42810
  if (signal.aborted) {
42730
42811
  return Promise.resolve();
@@ -42771,7 +42852,7 @@ async function installDetectedAgentIntegrations(config2, installations, signal)
42771
42852
  {
42772
42853
  agentId: agent.id,
42773
42854
  kind: AGENT_INSTALL_REQUEST_KIND,
42774
- requestId: `automatic-integration-${randomUUID3()}`
42855
+ requestId: `automatic-integration-${randomUUID4()}`
42775
42856
  },
42776
42857
  signal
42777
42858
  );
@@ -43023,7 +43104,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
43023
43104
  if (connectionController.signal.aborted) {
43024
43105
  return;
43025
43106
  }
43026
- console.error("Mobius daemon could not process a durable Runtime delivery", error62);
43107
+ console.error("Mobius daemon could not process a in-memory Runtime delivery", error62);
43027
43108
  failAndClose(
43028
43109
  new Error("Runtime delivery processing failed", { cause: error62 }),
43029
43110
  4008,
@@ -43826,8 +43907,8 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
43826
43907
  publishCatalog: async (installationSignal) => await publishAgentCatalog(config2, installationSignal),
43827
43908
  stateDirectory
43828
43909
  });
43829
- const sessionStore = new SqliteAcpSessionStore(config2.auditDatabasePath);
43830
- const outbox = new SessionEventOutbox(config2.auditDatabasePath);
43910
+ const sessionStore = new MemoryAcpSessionStore();
43911
+ const outbox = new SessionEventOutbox();
43831
43912
  const publisher = new DaemonSessionEventPublisher(outbox, timer);
43832
43913
  const activeTurns = /* @__PURE__ */ new Map();
43833
43914
  const activeAttemptIds = /* @__PURE__ */ new Map();
@@ -43839,9 +43920,14 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
43839
43920
  }
43840
43921
  publisher.recordAttempt(sessionId, event, attemptId);
43841
43922
  };
43842
- const sessions = new AcpSessionManager(new DaemonAcpObserver(recordSessionEvent), sessionStore, {
43843
- read: async (options2, nativeSessionId) => options2.agent.id === "codex" ? (await readCodexFullHistory(options2.agent, options2.cwd, nativeSessionId, options2.signal)).history : null
43844
- });
43923
+ const sessions = new AcpSessionManager(
43924
+ new DaemonAcpObserver(recordSessionEvent),
43925
+ sessionStore,
43926
+ {
43927
+ read: async (options2, nativeSessionId) => options2.agent.id === "codex" ? (await readCodexFullHistory(options2.agent, options2.cwd, nativeSessionId, options2.signal)).history : null
43928
+ },
43929
+ "native"
43930
+ );
43845
43931
  const directories = new WorkspaceDirectoryService(config2.bindingId, config2.defaultWorkspace);
43846
43932
  const installationObserver = new DaemonInstallationObserver();
43847
43933
  const diagnostics = new RelayConnectionDiagnostics(
@@ -43977,13 +44063,9 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
43977
44063
  await sessions.close();
43978
44064
  } finally {
43979
44065
  try {
43980
- sessionStore.close();
44066
+ publisher.close();
43981
44067
  } finally {
43982
- try {
43983
- publisher.close();
43984
- } finally {
43985
- outbox.close();
43986
- }
44068
+ outbox.close();
43987
44069
  }
43988
44070
  }
43989
44071
  }
@@ -43999,9 +44081,9 @@ import { basename as basename7, resolve as resolve6 } from "node:path";
43999
44081
  import { fetch as fetch5 } from "undici";
44000
44082
 
44001
44083
  // src/storage/runtime-installation-store.ts
44002
- import { createHash as createHash4, randomUUID as randomUUID4 } from "node:crypto";
44084
+ import { createHash as createHash5, randomUUID as randomUUID5 } from "node:crypto";
44003
44085
  import { mkdir as mkdir4, open as open5, readdir as readdir3, rename as rename3, unlink, writeFile as writeFile3 } from "node:fs/promises";
44004
- import { dirname as dirname7, join as join17, resolve as resolve5 } from "node:path";
44086
+ import { dirname as dirname4, join as join17, resolve as resolve5 } from "node:path";
44005
44087
  var APPLICATION_ID_PATTERN = /^[a-z][a-z0-9]*(?:[.-][a-z0-9]+){1,31}$/;
44006
44088
  var CONNECTION_ID_PATTERN = /^mcn_[a-f0-9]{32}$/;
44007
44089
  var INSTALLATION_ID_PATTERN = /^min_[a-f0-9]{32}$/;
@@ -44188,13 +44270,13 @@ function parseRelayOrigin(value) {
44188
44270
  return origin;
44189
44271
  }
44190
44272
  function connectionId() {
44191
- return `mcn_${randomUUID4().replaceAll("-", "")}`;
44273
+ return `mcn_${randomUUID5().replaceAll("-", "")}`;
44192
44274
  }
44193
44275
  function installationId() {
44194
- return `min_${randomUUID4().replaceAll("-", "")}`;
44276
+ return `min_${randomUUID5().replaceAll("-", "")}`;
44195
44277
  }
44196
44278
  function channelIndexFileName(channelId) {
44197
- return `mci_${createHash4("sha256").update(channelId).digest("hex")}.json`;
44279
+ return `mci_${createHash5("sha256").update(channelId).digest("hex")}.json`;
44198
44280
  }
44199
44281
  function decodeInstallationPointer(value) {
44200
44282
  if (!isRecord9(value) || !hasExactKeys(value, INSTALLATION_POINTER_KEYS) || value["version"] !== 1) {
@@ -44342,8 +44424,8 @@ async function readJsonFile(path2, signal, missingCode) {
44342
44424
  }
44343
44425
  async function writeJsonAtomically(path2, value, signal) {
44344
44426
  signal.throwIfAborted();
44345
- const directory = dirname7(path2);
44346
- const temporaryPath = join17(directory, `.${randomUUID4()}.tmp`);
44427
+ const directory = dirname4(path2);
44428
+ const temporaryPath = join17(directory, `.${randomUUID5()}.tmp`);
44347
44429
  try {
44348
44430
  await mkdir4(directory, { mode: 448, recursive: true });
44349
44431
  signal.throwIfAborted();
@@ -44405,7 +44487,6 @@ var RuntimeInstallationStore = class _RuntimeInstallationStore {
44405
44487
  return new _RuntimeInstallationStore(applicationId, storedInstallationId, stateDirectory);
44406
44488
  };
44407
44489
  connectionPath = (connectionId2) => join17(this.#connectionDirectory, `${validateConnectionId(connectionId2)}.json`);
44408
- auditDatabasePath = (connectionId2) => join17(this.stateDirectory, "audit", `${validateConnectionId(connectionId2)}.sqlite`);
44409
44490
  channelIndexPath = (channelId) => join17(this.#channelDirectory, channelIndexFileName(validateIdentifier(channelId, "invalid_channel_id")));
44410
44491
  readConnection = async (connectionId2, signal) => {
44411
44492
  const stored = decodeConnection(
@@ -44798,7 +44879,6 @@ function buildPairedDaemon(installation, connection, defaultWorkspace, inventory
44798
44879
  config: createDaemonConfig(
44799
44880
  {
44800
44881
  defaultWorkspace,
44801
- auditDatabasePath: installation.auditDatabasePath(connection.connectionId),
44802
44882
  channelId: connection.channelId,
44803
44883
  relayUrl
44804
44884
  },
@@ -44920,7 +45000,6 @@ function loadMobiusRuntimeConnection(environment = process.env) {
44920
45000
  throw new MobiusRuntimeConfigurationError("MOBIUS_CHANNEL_ID is invalid");
44921
45001
  }
44922
45002
  return Object.freeze({
44923
- auditDatabasePath: environment["MOBIUS_AUDIT_DATABASE"]?.trim() || join18(readStateDirectory(environment), "audit", `${channelId}.sqlite`),
44924
45003
  channelId,
44925
45004
  defaultWorkspace: loadDefaultWorkspace(environment),
44926
45005
  relayUrl: requiredEnvironmentValue(environment, "MOBIUS_RELAY_URL"),
@@ -44949,8 +45028,6 @@ async function createMobiusRuntimeEngine(connection, signal, environment = proce
44949
45028
  const localContext = new DaemonLocalContext(readStateDirectory(environment), environment);
44950
45029
  const relayUrl = relayUrlFromConnection(connection);
44951
45030
  const defaultWorkspace = await resolveWorkspace(connection.defaultWorkspace);
44952
- const auditDatabasePath = resolve7(connection.auditDatabasePath);
44953
- await mkdir6(dirname8(auditDatabasePath), { recursive: true, mode: 448 });
44954
45031
  const inventory = await discoverLocalAgentInventory({
44955
45032
  defaultWorkspace,
44956
45033
  environment: localContext.environment,
@@ -44962,7 +45039,6 @@ async function createMobiusRuntimeEngine(connection, signal, environment = proce
44962
45039
  return new MobiusRuntimeEngine(
44963
45040
  createDaemonConfig(
44964
45041
  {
44965
- auditDatabasePath,
44966
45042
  channelId: connection.channelId,
44967
45043
  defaultWorkspace,
44968
45044
  relayUrl
@@ -44988,7 +45064,7 @@ var MobiusRuntimeEngine = class {
44988
45064
  }
44989
45065
  signal.throwIfAborted();
44990
45066
  this.#state = new RunningMobiusRuntimeState();
44991
- const audit = new AuditStore(this.#config.auditDatabasePath);
45067
+ const audit = new AuditStore();
44992
45068
  try {
44993
45069
  await runDaemon(this.#config, audit, signal, void 0, {
44994
45070
  ...this.#options.onConnectionStatus === void 0 ? {} : { onConnectionStatus: this.#options.onConnectionStatus },