@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/cli.js CHANGED
@@ -7,7 +7,7 @@ var __export = (target, all2) => {
7
7
 
8
8
  // src/cli.ts
9
9
  import { constants as constants2 } from "node:fs";
10
- import { mkdir as mkdir6, open as open7 } from "node:fs/promises";
10
+ import { mkdir as mkdir6, open as open6 } from "node:fs/promises";
11
11
  import { resolve as resolve7 } from "node:path";
12
12
 
13
13
  // ../../node_modules/.pnpm/commander@15.0.0/node_modules/commander/lib/error.js
@@ -3381,7 +3381,7 @@ var program = new Command();
3381
3381
  // package.json
3382
3382
  var package_default = {
3383
3383
  name: "@moxt-ai/mobius",
3384
- version: "0.0.93",
3384
+ version: "0.0.96",
3385
3385
  description: "Mobius CLI for pairing and running local AI agent services.",
3386
3386
  type: "module",
3387
3387
  bin: {
@@ -25186,18 +25186,17 @@ function effortValues(model) {
25186
25186
  }
25187
25187
  function modelSetting(models, currentValue) {
25188
25188
  const values = modelValues(models);
25189
- const current = currentValue.length > 0 ? currentValue : models.find((model) => model.isDefault === true)?.id ?? values[0]?.value ?? "";
25189
+ const current = values.some((value) => value.value === currentValue) ? currentValue : models.find((model) => model.isDefault === true)?.id ?? values[0]?.value ?? "";
25190
25190
  if (current.length === 0) {
25191
25191
  return null;
25192
25192
  }
25193
- const options = values.some((value) => value.value === current) ? values : [{ description: "", name: current, value: current }, ...values];
25194
25193
  return {
25195
25194
  category: "model",
25196
25195
  currentValue: current,
25197
25196
  description: "Model Codex uses for the session",
25198
25197
  id: MODEL_SETTING_ID,
25199
25198
  name: "Model",
25200
- options,
25199
+ options: values,
25201
25200
  type: "select"
25202
25201
  };
25203
25202
  }
@@ -27154,41 +27153,41 @@ var DiscoveryAcpHandler = class {
27154
27153
  };
27155
27154
  function readableAcpStream(input2) {
27156
27155
  let byteLength = 0;
27157
- let open8 = true;
27156
+ let open7 = true;
27158
27157
  return new ReadableStream({
27159
27158
  start(controller) {
27160
27159
  input2.on("data", (chunk) => {
27161
- if (!open8) {
27160
+ if (!open7) {
27162
27161
  return;
27163
27162
  }
27164
27163
  if (!(chunk instanceof Uint8Array)) {
27165
- open8 = false;
27164
+ open7 = false;
27166
27165
  controller.error(new Error("ACP adapter produced invalid output"));
27167
27166
  return;
27168
27167
  }
27169
27168
  byteLength += chunk.byteLength;
27170
27169
  if (byteLength > ACP_OUTPUT_LIMIT_BYTES) {
27171
- open8 = false;
27170
+ open7 = false;
27172
27171
  controller.error(new Error("ACP adapter output limit exceeded"));
27173
27172
  return;
27174
27173
  }
27175
27174
  controller.enqueue(new Uint8Array(chunk));
27176
27175
  });
27177
27176
  input2.once("end", () => {
27178
- if (open8) {
27179
- open8 = false;
27177
+ if (open7) {
27178
+ open7 = false;
27180
27179
  controller.close();
27181
27180
  }
27182
27181
  });
27183
27182
  input2.once("error", (error62) => {
27184
- if (open8) {
27185
- open8 = false;
27183
+ if (open7) {
27184
+ open7 = false;
27186
27185
  controller.error(error62);
27187
27186
  }
27188
27187
  });
27189
27188
  },
27190
27189
  cancel() {
27191
- open8 = false;
27190
+ open7 = false;
27192
27191
  }
27193
27192
  });
27194
27193
  }
@@ -28521,6 +28520,7 @@ var encodeAgentInstallCancelledEvent = (message) => encode3(message, agentInstal
28521
28520
 
28522
28521
  // ../protocol/src/messages.ts
28523
28522
  var SESSION_PROMPT_KIND = "session.prompt";
28523
+ var RUNTIME_WORKSPACE_BINDING_ID = "workspace";
28524
28524
  var SESSION_CANCEL_KIND = "session.cancel";
28525
28525
  var RUNTIME_LIVENESS_READY_KIND = "runtime.liveness.ready";
28526
28526
  var RUNTIME_HEARTBEAT_KIND = "runtime.heartbeat";
@@ -29127,6 +29127,8 @@ var nativeSessionTurnForkCommandSchema = external_exports.strictObject({
29127
29127
  title: external_exports.string().max(500)
29128
29128
  }).readonly();
29129
29129
  var nativeSessionRequestSchema = external_exports.discriminatedUnion("action", [
29130
+ external_exports.strictObject({ ...identity, action: external_exports.literal("create") }).readonly(),
29131
+ external_exports.strictObject({ ...identity, action: external_exports.literal("linked-history"), targetSessionId: identifier }).readonly(),
29130
29132
  external_exports.strictObject({ ...identity, action: external_exports.literal("preview"), entryId: identifier }).readonly(),
29131
29133
  external_exports.strictObject({ ...identity, action: external_exports.literal("history"), entryId: identifier }).readonly(),
29132
29134
  external_exports.strictObject({ ...identity, action: external_exports.literal("find"), nativeSessionId: identifier }).readonly(),
@@ -29148,6 +29150,8 @@ var nativeSessionRequestSchema = external_exports.discriminatedUnion("action", [
29148
29150
  }).readonly()
29149
29151
  ]);
29150
29152
  var nativeSessionCommandSchema = external_exports.discriminatedUnion("action", [
29153
+ external_exports.strictObject({ ...identity, action: external_exports.literal("create") }).readonly(),
29154
+ external_exports.strictObject({ ...identity, action: external_exports.literal("linked-history"), targetSessionId: identifier }).readonly(),
29151
29155
  external_exports.strictObject({ ...identity, action: external_exports.literal("preview"), entryId: identifier }).readonly(),
29152
29156
  external_exports.strictObject({ ...identity, action: external_exports.literal("history"), entryId: identifier }).readonly(),
29153
29157
  external_exports.strictObject({ ...identity, action: external_exports.literal("find"), nativeSessionId: identifier }).readonly(),
@@ -29176,7 +29180,7 @@ var nativeSessionCommandSchema = external_exports.discriminatedUnion("action", [
29176
29180
  ]);
29177
29181
  var nativeSessionEntrySchema = external_exports.strictObject({
29178
29182
  entryId: identifier,
29179
- mobiusSessionIds: external_exports.array(identifier).max(500).readonly(),
29183
+ nativeSessionId: identifier,
29180
29184
  title: external_exports.string().max(500),
29181
29185
  directoryId,
29182
29186
  directoryLabel: external_exports.string().min(1).max(2048),
@@ -29188,6 +29192,18 @@ var resultEnvelope = {
29188
29192
  kind: external_exports.literal(NATIVE_SESSION_RESULT_KIND)
29189
29193
  };
29190
29194
  var nativeSessionResultSchema = external_exports.discriminatedUnion("action", [
29195
+ external_exports.strictObject({ ...resultEnvelope, action: external_exports.literal("create"), nativeSessionId: identifier }).readonly(),
29196
+ external_exports.strictObject({
29197
+ ...resultEnvelope,
29198
+ action: external_exports.literal("linked-history"),
29199
+ targetSessionId: identifier,
29200
+ history: sessionHistorySchema
29201
+ }).readonly(),
29202
+ external_exports.strictObject({
29203
+ ...resultEnvelope,
29204
+ action: external_exports.literal("unlinked-history"),
29205
+ targetSessionId: identifier
29206
+ }).readonly(),
29191
29207
  external_exports.strictObject({
29192
29208
  ...resultEnvelope,
29193
29209
  action: external_exports.literal("find"),
@@ -29735,8 +29751,7 @@ function createDaemonConfig(connection, agents = [], installableAgents = [], loc
29735
29751
  return {
29736
29752
  agents: daemonAgents,
29737
29753
  defaultWorkspace: connection.defaultWorkspace,
29738
- auditDatabasePath: connection.auditDatabasePath,
29739
- bindingId: "workspace",
29754
+ bindingId: RUNTIME_WORKSPACE_BINDING_ID,
29740
29755
  catalog: new LocalAgentCatalog(daemonAgents, installableAgents),
29741
29756
  channelId: connection.channelId,
29742
29757
  installableAgents,
@@ -29748,8 +29763,8 @@ function createDaemonConfig(connection, agents = [], installableAgents = [], loc
29748
29763
 
29749
29764
  // src/daemon-manager.ts
29750
29765
  import { spawn as spawn6 } from "node:child_process";
29751
- import { createHash as createHash5, randomBytes } from "node:crypto";
29752
- import { open as open6, readFile as readFile3, unlink as unlink2, writeFile as writeFile4 } from "node:fs/promises";
29766
+ import { createHash as createHash6, randomBytes } from "node:crypto";
29767
+ import { readFile as readFile3, unlink as unlink2, writeFile as writeFile4 } from "node:fs/promises";
29753
29768
  import { createConnection, createServer } from "node:net";
29754
29769
  import { tmpdir } from "node:os";
29755
29770
  import { join as join18 } from "node:path";
@@ -30167,7 +30182,6 @@ var RuntimeInstallationStore = class _RuntimeInstallationStore {
30167
30182
  return new _RuntimeInstallationStore(applicationId, storedInstallationId, stateDirectory);
30168
30183
  };
30169
30184
  connectionPath = (connectionId2) => join15(this.#connectionDirectory, `${validateConnectionId(connectionId2)}.json`);
30170
- auditDatabasePath = (connectionId2) => join15(this.stateDirectory, "audit", `${validateConnectionId(connectionId2)}.sqlite`);
30171
30185
  channelIndexPath = (channelId) => join15(this.#channelDirectory, channelIndexFileName(validateIdentifier(channelId, "invalid_channel_id")));
30172
30186
  readConnection = async (connectionId2, signal) => {
30173
30187
  const stored = decodeConnection(
@@ -30606,7 +30620,6 @@ function buildPairedDaemon(installation, connection, defaultWorkspace, inventory
30606
30620
  config: createDaemonConfig(
30607
30621
  {
30608
30622
  defaultWorkspace,
30609
- auditDatabasePath: installation.auditDatabasePath(connection.connectionId),
30610
30623
  channelId: connection.channelId,
30611
30624
  relayUrl
30612
30625
  },
@@ -30695,255 +30708,245 @@ async function resumeLocalMachine(arguments_, signal = new AbortController().sig
30695
30708
  }
30696
30709
 
30697
30710
  // src/audit/audit-store.ts
30698
- import { mkdirSync } from "node:fs";
30699
- import { dirname as dirname4 } from "node:path";
30700
- import { DatabaseSync } from "node:sqlite";
30711
+ var MAX_AUDIT_RECORDS = 1024;
30701
30712
  var AuditStore = class {
30702
- database;
30703
- constructor(path3) {
30704
- mkdirSync(dirname4(path3), { recursive: true });
30705
- this.database = new DatabaseSync(path3);
30706
- this.database.exec(`
30707
- CREATE TABLE IF NOT EXISTS audit_events (
30708
- id INTEGER PRIMARY KEY AUTOINCREMENT,
30709
- recorded_at TEXT NOT NULL,
30710
- event TEXT NOT NULL,
30711
- command_id TEXT NOT NULL,
30712
- session_id TEXT NOT NULL,
30713
- details_json TEXT NOT NULL DEFAULT '{}'
30714
- ) STRICT
30715
- `);
30716
- const columns = this.database.prepare("PRAGMA table_info(audit_events)").all();
30717
- if (!columns.some((column) => Reflect.get(column, "name") === "details_json")) {
30718
- this.database.exec("ALTER TABLE audit_events ADD COLUMN details_json TEXT NOT NULL DEFAULT '{}'");
30719
- }
30720
- }
30721
- record(record2) {
30722
- this.database.prepare(
30723
- `
30724
- INSERT INTO audit_events (
30725
- recorded_at,
30726
- event,
30727
- command_id,
30728
- session_id,
30729
- details_json
30730
- ) VALUES (?, ?, ?, ?, ?)
30731
- `
30732
- ).run(
30733
- (/* @__PURE__ */ new Date()).toISOString(),
30734
- record2.event,
30735
- record2.commandId,
30736
- record2.sessionId,
30737
- JSON.stringify(record2.details ?? {})
30713
+ #records = [];
30714
+ record = (record2) => {
30715
+ if (this.#records.length === MAX_AUDIT_RECORDS) {
30716
+ this.#records.shift();
30717
+ }
30718
+ this.#records.push(
30719
+ record2.details === void 0 ? { ...record2 } : { ...record2, details: { ...record2.details } }
30738
30720
  );
30739
- }
30740
- close() {
30741
- this.database.close();
30742
- }
30721
+ };
30722
+ close = () => {
30723
+ this.#records.length = 0;
30724
+ };
30743
30725
  };
30744
30726
 
30745
30727
  // src/run-daemon.ts
30746
- import { createHash as createHash4, randomUUID as randomUUID4 } from "node:crypto";
30728
+ import { randomUUID as randomUUID5 } from "node:crypto";
30747
30729
  import { basename as basename7 } from "node:path";
30748
30730
  import { styleText } from "node:util";
30749
30731
  import { fetch as fetch5, WebSocket as WebSocket2 } from "undici";
30750
30732
 
30751
- // src/acp/session-manager.ts
30752
- import { spawn as spawn4 } from "node:child_process";
30753
- import {
30754
- methods as methods8,
30755
- ndJsonStream as ndJsonStream2,
30756
- PROTOCOL_VERSION as PROTOCOL_VERSION3,
30757
- RequestError as RequestError3
30758
- } from "@agentclientprotocol/sdk";
30733
+ // src/acp/session-config/apply-session-configuration.ts
30734
+ import { randomUUID as randomUUID2 } from "node:crypto";
30759
30735
 
30760
- // src/authorization/local-raster.ts
30761
- import { open as open5, readFile as readFile2, realpath as realpath7, stat as stat6 } from "node:fs/promises";
30762
- import { basename as basename2, isAbsolute as isAbsolute8, normalize as normalize2 } from "node:path";
30763
- import { fileURLToPath } from "node:url";
30764
- var MAX_LOCAL_RASTER_BYTES = 128 * 1024 * 1024;
30765
- var MAX_INLINE_RASTER_BYTES = 3e6;
30766
- var PNG_SIGNATURE = Uint8Array.of(137, 80, 78, 71);
30767
- var JPEG_SIGNATURE = Uint8Array.of(255, 216, 255);
30768
- var GIF87_SIGNATURE = new TextEncoder().encode("GIF87a");
30769
- var GIF89_SIGNATURE = new TextEncoder().encode("GIF89a");
30770
- var RIFF_SIGNATURE = new TextEncoder().encode("RIFF");
30771
- var WEBP_SIGNATURE = new TextEncoder().encode("WEBP");
30772
- var LocalRasterImage = class {
30773
- bytes;
30774
- mimeType;
30775
- name;
30776
- sourceUri;
30777
- constructor(name, mimeType, bytes, sourceUri = "") {
30778
- this.bytes = bytes;
30779
- this.mimeType = mimeType;
30780
- this.name = name;
30781
- this.sourceUri = sourceUri;
30736
+ // src/agent-catalog/agent-settings-base.ts
30737
+ var AgentSettingsConfigurationError = class extends Error {
30738
+ code = "invalid_session_configuration";
30739
+ constructor(message, options = {}) {
30740
+ super(message, options);
30741
+ this.name = "AgentSettingsConfigurationError";
30782
30742
  }
30783
- base64 = async () => {
30784
- const bytes = this.bytes ?? new Uint8Array(await readFile2(this.sourceUri));
30785
- return Buffer.from(bytes).toString("base64");
30786
- };
30787
30743
  };
30788
- function startsWith(bytes, signature, offset = 0) {
30789
- if (bytes.byteLength < offset + signature.byteLength) {
30790
- return false;
30791
- }
30792
- return signature.every((value, index2) => bytes[offset + index2] === value);
30793
- }
30794
- function sniffRasterMime(bytes) {
30795
- if (startsWith(bytes, PNG_SIGNATURE)) {
30796
- return "image/png";
30797
- }
30798
- if (startsWith(bytes, JPEG_SIGNATURE)) {
30799
- return "image/jpeg";
30800
- }
30801
- if (startsWith(bytes, GIF87_SIGNATURE) || startsWith(bytes, GIF89_SIGNATURE)) {
30802
- return "image/gif";
30744
+ var AgentSettingsLaunchSelectionResult = class {
30745
+ agent;
30746
+ handled;
30747
+ constructor(agent, handled) {
30748
+ this.agent = agent;
30749
+ this.handled = handled;
30803
30750
  }
30804
- if (startsWith(bytes, RIFF_SIGNATURE) && startsWith(bytes, WEBP_SIGNATURE, 8)) {
30805
- return "image/webp";
30751
+ };
30752
+ var AppliedAgentLaunchSettings = class {
30753
+ agent;
30754
+ sessionConfigurations;
30755
+ constructor(agent, sessionConfigurations) {
30756
+ this.agent = agent;
30757
+ this.sessionConfigurations = Object.freeze([...sessionConfigurations]);
30806
30758
  }
30807
- return null;
30759
+ };
30760
+ var AgentSettingsAdapter = class {
30761
+ modelEffortResolution = AGENT_MODEL_EFFORT_RESOLUTION_ON_MODEL_SELECTION;
30762
+ applyLaunchSelection = (agent, _selection) => new AgentSettingsLaunchSelectionResult(agent, false);
30763
+ settings = (_agent) => [];
30764
+ };
30765
+ function selectValue(name, value, description) {
30766
+ return {
30767
+ description,
30768
+ groupId: "",
30769
+ groupName: "",
30770
+ name,
30771
+ value
30772
+ };
30808
30773
  }
30809
- function readInlineRaster(data, name = "Image") {
30810
- if (data.length === 0 || data.length > Math.ceil(MAX_INLINE_RASTER_BYTES / 3) * 4 || data.length % 4 !== 0) {
30811
- return null;
30812
- }
30813
- if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(data)) {
30814
- return null;
30815
- }
30816
- const bytes = new Uint8Array(Buffer.from(data, "base64"));
30817
- if (bytes.byteLength < 1 || bytes.byteLength > MAX_INLINE_RASTER_BYTES) {
30818
- return null;
30774
+ function selectSetting(id, name, description, currentValue, values) {
30775
+ return {
30776
+ booleanValue: false,
30777
+ category: "execution",
30778
+ currentValue,
30779
+ description,
30780
+ id,
30781
+ name,
30782
+ type: "select",
30783
+ values
30784
+ };
30785
+ }
30786
+ function selectedValue(selection, configId) {
30787
+ if (selection.configId !== configId || selection.valueType !== "select" || selection.booleanValue || selection.value.length === 0) {
30788
+ throw new AgentSettingsConfigurationError("The requested Agent setting is invalid");
30819
30789
  }
30820
- const mimeType = sniffRasterMime(bytes);
30821
- if (mimeType === null) {
30822
- return null;
30790
+ return selection.value;
30791
+ }
30792
+ function validValue(values, value) {
30793
+ if (!values.some((candidate) => candidate.value === value)) {
30794
+ throw new AgentSettingsConfigurationError("The requested Agent setting is unavailable");
30823
30795
  }
30824
- return new LocalRasterImage(basename2(name) || "Image", mimeType, bytes);
30796
+ return value;
30825
30797
  }
30826
- async function resolveCanonicalPath(requested, signal) {
30827
- signal.throwIfAborted();
30828
- if (!isAbsolute8(requested) || requested.includes("\0") || normalize2(requested) !== requested) {
30829
- return null;
30798
+
30799
+ // src/agent-catalog/agents/codex-settings-adapter.ts
30800
+ var CodexSettingsAdapter = class extends AgentSettingsAdapter {
30801
+ modelEffortResolution = AGENT_MODEL_EFFORT_RESOLUTION_COMPLETE;
30802
+ };
30803
+
30804
+ // src/agent-catalog/agents/deepseek-settings-adapter.ts
30805
+ var READ_ONLY_VALUE = "read-only";
30806
+ var WORKSPACE_WRITE_VALUE = "workspace-write";
30807
+ var DANGER_FULL_ACCESS_VALUE = "danger-full-access";
30808
+ var DEEPSEEK_HARNESS_ACCESS_MODE_SETTING_ID = "dsh_access_mode";
30809
+ var dshAccessModes = Object.freeze([
30810
+ selectValue("Read only", READ_ONLY_VALUE, "Allow inspection without local writes."),
30811
+ selectValue("Workspace write", WORKSPACE_WRITE_VALUE, "Allow changes in the selected workspace."),
30812
+ selectValue("Full access", DANGER_FULL_ACCESS_VALUE, "Allow unrestricted local execution.")
30813
+ ]);
30814
+ var DeepSeekHarnessSettingsAdapter = class extends AgentSettingsAdapter {
30815
+ settings = (agent) => {
30816
+ const configured = agent.environment["DSH_PERMISSION_MODE"] ?? WORKSPACE_WRITE_VALUE;
30817
+ return [
30818
+ selectSetting(
30819
+ DEEPSEEK_HARNESS_ACCESS_MODE_SETTING_ID,
30820
+ "Access mode",
30821
+ "Controls the local side effects allowed for this DeepSeek Harness session.",
30822
+ validValue(dshAccessModes, configured),
30823
+ dshAccessModes
30824
+ )
30825
+ ];
30826
+ };
30827
+ applyLaunchSelection = (agent, selection) => {
30828
+ if (selection.configId !== DEEPSEEK_HARNESS_ACCESS_MODE_SETTING_ID) {
30829
+ return new AgentSettingsLaunchSelectionResult(agent, false);
30830
+ }
30831
+ const value = validValue(dshAccessModes, selectedValue(selection, DEEPSEEK_HARNESS_ACCESS_MODE_SETTING_ID));
30832
+ return new AgentSettingsLaunchSelectionResult(
30833
+ agent.withEnvironment({ ...agent.environment, DSH_PERMISSION_MODE: value }),
30834
+ true
30835
+ );
30836
+ };
30837
+ };
30838
+
30839
+ // src/agent-catalog/agents/opencode-settings-adapter.ts
30840
+ var AGENT_DEFAULT_VALUE = "agent_default";
30841
+ var READ_ONLY_VALUE2 = "read-only";
30842
+ var WORKSPACE_WRITE_VALUE2 = "workspace-write";
30843
+ var DANGER_FULL_ACCESS_VALUE2 = "danger-full-access";
30844
+ var OPENCODE_PERMISSION_SETTING_ID = "opencode_permission";
30845
+ var openCodePermissionModes = Object.freeze([
30846
+ selectValue("Agent default", AGENT_DEFAULT_VALUE, "Keep OpenCode's existing permission policy."),
30847
+ selectValue("Read only", READ_ONLY_VALUE2, "Allow inspection without local writes."),
30848
+ selectValue("Workspace write", WORKSPACE_WRITE_VALUE2, "Allow changes in the selected workspace."),
30849
+ selectValue("Full access", DANGER_FULL_ACCESS_VALUE2, "Allow unrestricted local execution.")
30850
+ ]);
30851
+ function openCodeConfiguration(environment) {
30852
+ const encoded = environment["OPENCODE_CONFIG_CONTENT"];
30853
+ if (encoded === void 0 || encoded.length === 0) {
30854
+ return {};
30830
30855
  }
30856
+ let parsed;
30831
30857
  try {
30832
- const target = await realpath7(requested);
30833
- signal.throwIfAborted();
30834
- if (!isAbsolute8(target) || normalize2(target) !== target) {
30835
- return null;
30836
- }
30837
- return target;
30858
+ parsed = JSON.parse(encoded);
30838
30859
  } catch (cause) {
30839
- signal.throwIfAborted();
30840
- if (cause instanceof Error && cause.name === "AbortError") {
30841
- throw cause;
30842
- }
30843
- return null;
30844
- }
30845
- }
30846
- function parseLocalImageUri(uri) {
30847
- const trimmed = uri.trim();
30848
- if (trimmed.length === 0 || trimmed.length > 2048 || trimmed.includes("\0")) {
30849
- return null;
30850
- }
30851
- if (trimmed.startsWith("data:")) {
30852
- return null;
30853
- }
30854
- if (trimmed.startsWith("file:")) {
30855
- try {
30856
- const url2 = new URL(trimmed);
30857
- if (url2.protocol !== "file:" || url2.host.length > 0) {
30858
- return null;
30859
- }
30860
- return fileURLToPath(url2);
30861
- } catch {
30862
- return null;
30863
- }
30860
+ throw new AgentSettingsConfigurationError("The OpenCode configuration is invalid", { cause });
30864
30861
  }
30865
- if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(trimmed)) {
30866
- return null;
30862
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
30863
+ throw new AgentSettingsConfigurationError("The OpenCode configuration is invalid");
30867
30864
  }
30868
- return trimmed;
30865
+ return Object.freeze({ ...parsed });
30869
30866
  }
30870
- async function readLocalRaster(uri, signal) {
30871
- signal.throwIfAborted();
30872
- const requested = parseLocalImageUri(uri);
30873
- if (requested === null) {
30874
- return null;
30875
- }
30876
- const target = await resolveCanonicalPath(requested, signal);
30877
- if (target === null) {
30878
- return null;
30879
- }
30880
- const targetMetadata = await stat6(target);
30881
- signal.throwIfAborted();
30882
- if (!targetMetadata.isFile() || targetMetadata.size < 1 || targetMetadata.size > MAX_LOCAL_RASTER_BYTES) {
30883
- return null;
30884
- }
30885
- const handle = await open5(target, "r");
30886
- const header = new Uint8Array(12);
30887
- try {
30888
- await handle.read(header, 0, header.byteLength, 0);
30889
- } finally {
30890
- await handle.close();
30867
+ function openCodePermission(value) {
30868
+ if (value === READ_ONLY_VALUE2) {
30869
+ return {
30870
+ "*": "deny",
30871
+ glob: "allow",
30872
+ grep: "allow",
30873
+ lsp: "allow",
30874
+ read: "allow",
30875
+ skill: "allow"
30876
+ };
30891
30877
  }
30892
- signal.throwIfAborted();
30893
- const mimeType = sniffRasterMime(header);
30894
- if (mimeType === null) {
30895
- return null;
30878
+ if (value === WORKSPACE_WRITE_VALUE2) {
30879
+ return {
30880
+ "*": "allow",
30881
+ external_directory: "ask"
30882
+ };
30896
30883
  }
30897
- return new LocalRasterImage(basename2(target) || "Image", mimeType, null, target);
30884
+ return "allow";
30898
30885
  }
30899
-
30900
- // src/authorization/local-video.ts
30901
- import { basename as basename3 } from "node:path";
30902
- var MAX_INLINE_VIDEO_BYTES = 3e6;
30903
- var MP4_FILE_TYPE = new TextEncoder().encode("ftyp");
30904
- var WEBM_SIGNATURE = Uint8Array.of(26, 69, 223, 163);
30905
- var LocalVideo = class {
30906
- bytes;
30907
- mimeType;
30908
- name;
30909
- constructor(name, mimeType, bytes) {
30910
- this.bytes = bytes;
30911
- this.mimeType = mimeType;
30912
- this.name = name;
30913
- }
30914
- base64 = () => Buffer.from(this.bytes).toString("base64");
30886
+ var OpenCodeSettingsAdapter = class extends AgentSettingsAdapter {
30887
+ settings = (agent) => {
30888
+ const currentValue = agent.environment["MOBIUS_OPENCODE_PERMISSION"] ?? AGENT_DEFAULT_VALUE;
30889
+ return [
30890
+ selectSetting(
30891
+ OPENCODE_PERMISSION_SETTING_ID,
30892
+ "Permissions",
30893
+ "Controls OpenCode's local permission policy.",
30894
+ validValue(openCodePermissionModes, currentValue),
30895
+ openCodePermissionModes
30896
+ )
30897
+ ];
30898
+ };
30899
+ applyLaunchSelection = (agent, selection) => {
30900
+ if (selection.configId !== OPENCODE_PERMISSION_SETTING_ID) {
30901
+ return new AgentSettingsLaunchSelectionResult(agent, false);
30902
+ }
30903
+ const value = validValue(openCodePermissionModes, selectedValue(selection, OPENCODE_PERMISSION_SETTING_ID));
30904
+ if (value === AGENT_DEFAULT_VALUE) {
30905
+ return new AgentSettingsLaunchSelectionResult(agent, true);
30906
+ }
30907
+ return new AgentSettingsLaunchSelectionResult(
30908
+ agent.withEnvironment({
30909
+ ...agent.environment,
30910
+ MOBIUS_OPENCODE_PERMISSION: value,
30911
+ OPENCODE_CONFIG_CONTENT: JSON.stringify({
30912
+ ...openCodeConfiguration(agent.environment),
30913
+ permission: openCodePermission(value)
30914
+ })
30915
+ }),
30916
+ true
30917
+ );
30918
+ };
30915
30919
  };
30916
- function startsWith2(bytes, signature, offset = 0) {
30917
- if (bytes.byteLength < offset + signature.byteLength) {
30918
- return false;
30920
+
30921
+ // src/agent-catalog/agent-settings-adapter.ts
30922
+ var genericAdapter = new AgentSettingsAdapter();
30923
+ var codexAdapter = new CodexSettingsAdapter();
30924
+ var deepSeekHarnessAdapter = new DeepSeekHarnessSettingsAdapter();
30925
+ var openCodeAdapter = new OpenCodeSettingsAdapter();
30926
+ function agentSettingsAdapterForAgent(agentId) {
30927
+ if (agentId === "codex") {
30928
+ return codexAdapter;
30919
30929
  }
30920
- return signature.every((value, index2) => bytes[offset + index2] === value);
30921
- }
30922
- function sniffVideoMime(bytes) {
30923
- if (startsWith2(bytes, MP4_FILE_TYPE, 4)) {
30924
- return "video/mp4";
30930
+ if (agentId === "deepseek-harness") {
30931
+ return deepSeekHarnessAdapter;
30925
30932
  }
30926
- if (startsWith2(bytes, WEBM_SIGNATURE)) {
30927
- return "video/webm";
30933
+ if (agentId === "opencode") {
30934
+ return openCodeAdapter;
30928
30935
  }
30929
- return null;
30936
+ return genericAdapter;
30930
30937
  }
30931
- function readInlineVideo(data, declaredMimeType, name = "Video") {
30932
- if (data.length === 0 || data.length > Math.ceil(MAX_INLINE_VIDEO_BYTES / 3) * 4 || data.length % 4 !== 0) {
30933
- return null;
30934
- }
30935
- if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(data)) {
30936
- return null;
30937
- }
30938
- const bytes = new Uint8Array(Buffer.from(data, "base64"));
30939
- if (bytes.byteLength < 1 || bytes.byteLength > MAX_INLINE_VIDEO_BYTES) {
30940
- return null;
30941
- }
30942
- const mimeType = sniffVideoMime(bytes);
30943
- if (mimeType === null || mimeType !== declaredMimeType) {
30944
- return null;
30938
+ function applyAgentLaunchSettings(agent, selections) {
30939
+ const adapter = agentSettingsAdapterForAgent(agent.id);
30940
+ let selectedAgent = agent;
30941
+ const sessionConfigurations = [];
30942
+ for (const selection of selections) {
30943
+ const applied = adapter.applyLaunchSelection(selectedAgent, selection);
30944
+ selectedAgent = applied.agent;
30945
+ if (!applied.handled) {
30946
+ sessionConfigurations.push(selection);
30947
+ }
30945
30948
  }
30946
- return new LocalVideo(basename3(name) || "Video", mimeType, bytes);
30949
+ return new AppliedAgentLaunchSettings(selectedAgent, sessionConfigurations);
30947
30950
  }
30948
30951
 
30949
30952
  // src/infra/operation-metrics.ts
@@ -30981,6 +30984,358 @@ var unmeasuredOperationMetrics = Object.freeze({
30981
30984
  snapshot: () => Object.freeze([])
30982
30985
  });
30983
30986
 
30987
+ // src/native-sessions/chat-agent.ts
30988
+ function supportsNativeChat(agentId) {
30989
+ return agentId === "codex" || agentId === "claude";
30990
+ }
30991
+
30992
+ // src/acp/process-capacity.ts
30993
+ var AcpProcessCapacityLease = class {
30994
+ #releaseCapacity;
30995
+ #released = false;
30996
+ constructor(releaseCapacity) {
30997
+ this.#releaseCapacity = releaseCapacity;
30998
+ }
30999
+ release = () => {
31000
+ if (this.#released) {
31001
+ return;
31002
+ }
31003
+ this.#released = true;
31004
+ this.#releaseCapacity();
31005
+ };
31006
+ };
31007
+ var AcpProcessCapacityWaiter = class {
31008
+ completion = Promise.withResolvers();
31009
+ signal;
31010
+ constructor(signal) {
31011
+ this.signal = signal;
31012
+ }
31013
+ cancel = () => {
31014
+ try {
31015
+ this.signal.throwIfAborted();
31016
+ } catch (error62) {
31017
+ this.completion.reject(error62);
31018
+ }
31019
+ };
31020
+ };
31021
+ var AcpProcessCapacityLock = class {
31022
+ #locked = false;
31023
+ #waiters = [];
31024
+ acquire = async (signal) => {
31025
+ signal.throwIfAborted();
31026
+ if (!this.#locked) {
31027
+ this.#locked = true;
31028
+ return new AcpProcessCapacityLease(this.#release);
31029
+ }
31030
+ const waiter = new AcpProcessCapacityWaiter(signal);
31031
+ this.#waiters.push(waiter);
31032
+ signal.addEventListener("abort", waiter.cancel, { once: true });
31033
+ if (signal.aborted) {
31034
+ waiter.cancel();
31035
+ }
31036
+ try {
31037
+ return await waiter.completion.promise;
31038
+ } finally {
31039
+ signal.removeEventListener("abort", waiter.cancel);
31040
+ const index2 = this.#waiters.indexOf(waiter);
31041
+ if (index2 >= 0) {
31042
+ this.#waiters.splice(index2, 1);
31043
+ }
31044
+ }
31045
+ };
31046
+ #release = () => {
31047
+ while (this.#waiters.length > 0) {
31048
+ const waiter = this.#waiters.shift();
31049
+ if (waiter === void 0 || waiter.signal.aborted) {
31050
+ continue;
31051
+ }
31052
+ waiter.completion.resolve(new AcpProcessCapacityLease(this.#release));
31053
+ return;
31054
+ }
31055
+ this.#locked = false;
31056
+ };
31057
+ };
31058
+ async function waitForAcpProcessCapacity(completion, signal) {
31059
+ signal.throwIfAborted();
31060
+ const cancelled = Promise.withResolvers();
31061
+ const cancel = () => {
31062
+ try {
31063
+ signal.throwIfAborted();
31064
+ } catch (error62) {
31065
+ cancelled.reject(error62);
31066
+ }
31067
+ };
31068
+ signal.addEventListener("abort", cancel, { once: true });
31069
+ if (signal.aborted) {
31070
+ cancel();
31071
+ }
31072
+ try {
31073
+ await Promise.race([completion, cancelled.promise]);
31074
+ } finally {
31075
+ signal.removeEventListener("abort", cancel);
31076
+ }
31077
+ }
31078
+
31079
+ // src/acp/session-store.ts
31080
+ var AcpStoredSession = class {
31081
+ additionalDirectories;
31082
+ agentId;
31083
+ cwd;
31084
+ nativeSessionId;
31085
+ prompted;
31086
+ sessionId;
31087
+ constructor(sessionId, agentId, nativeSessionId, cwd, additionalDirectories, prompted) {
31088
+ this.additionalDirectories = [...additionalDirectories];
31089
+ this.agentId = agentId;
31090
+ this.cwd = cwd;
31091
+ this.nativeSessionId = nativeSessionId;
31092
+ this.prompted = prompted;
31093
+ this.sessionId = sessionId;
31094
+ }
31095
+ };
31096
+ var AcpStoredSessionLookup = class {
31097
+ };
31098
+ var MissingAcpStoredSession = class extends AcpStoredSessionLookup {
31099
+ found = false;
31100
+ };
31101
+ var FoundAcpStoredSession = class extends AcpStoredSessionLookup {
31102
+ found = true;
31103
+ session;
31104
+ constructor(session) {
31105
+ super();
31106
+ this.session = session;
31107
+ }
31108
+ };
31109
+ var DeletedAcpStoredSession = class extends AcpStoredSessionLookup {
31110
+ found = false;
31111
+ };
31112
+ var MemoryAcpSessionStore = class {
31113
+ #sessions = /* @__PURE__ */ new Map();
31114
+ #deleted = /* @__PURE__ */ new Set();
31115
+ findNative = (agentId, nativeSessionId) => [...this.#sessions.values()].filter(
31116
+ (session) => session.agentId === agentId && session.nativeSessionId === nativeSessionId
31117
+ );
31118
+ markDeleted = (agentId, nativeSessionId) => {
31119
+ const ids = this.findNative(agentId, nativeSessionId).map((session) => session.sessionId);
31120
+ for (const id of ids) {
31121
+ this.#sessions.delete(id);
31122
+ this.#deleted.add(id);
31123
+ }
31124
+ return ids;
31125
+ };
31126
+ read = (sessionId) => {
31127
+ if (this.#deleted.has(sessionId)) {
31128
+ return new DeletedAcpStoredSession();
31129
+ }
31130
+ const session = this.#sessions.get(sessionId);
31131
+ return session === void 0 ? new MissingAcpStoredSession() : new FoundAcpStoredSession(session);
31132
+ };
31133
+ remove = (sessionId) => {
31134
+ this.#sessions.delete(sessionId);
31135
+ };
31136
+ write = (session) => {
31137
+ this.#sessions.set(session.sessionId, session);
31138
+ };
31139
+ };
31140
+
31141
+ // src/acp/process-session.ts
31142
+ import { spawn as spawn4 } from "node:child_process";
31143
+ import {
31144
+ methods as methods8,
31145
+ ndJsonStream as ndJsonStream2,
31146
+ PROTOCOL_VERSION as PROTOCOL_VERSION3,
31147
+ RequestError as RequestError3
31148
+ } from "@agentclientprotocol/sdk";
31149
+
31150
+ // src/authorization/local-raster.ts
31151
+ import { open as open5, readFile as readFile2, realpath as realpath7, stat as stat6 } from "node:fs/promises";
31152
+ import { basename as basename2, isAbsolute as isAbsolute8, normalize as normalize2 } from "node:path";
31153
+ import { fileURLToPath } from "node:url";
31154
+ var MAX_LOCAL_RASTER_BYTES = 128 * 1024 * 1024;
31155
+ var MAX_INLINE_RASTER_BYTES = 3e6;
31156
+ var PNG_SIGNATURE = Uint8Array.of(137, 80, 78, 71);
31157
+ var JPEG_SIGNATURE = Uint8Array.of(255, 216, 255);
31158
+ var GIF87_SIGNATURE = new TextEncoder().encode("GIF87a");
31159
+ var GIF89_SIGNATURE = new TextEncoder().encode("GIF89a");
31160
+ var RIFF_SIGNATURE = new TextEncoder().encode("RIFF");
31161
+ var WEBP_SIGNATURE = new TextEncoder().encode("WEBP");
31162
+ var LocalRasterImage = class {
31163
+ bytes;
31164
+ mimeType;
31165
+ name;
31166
+ sourceUri;
31167
+ constructor(name, mimeType, bytes, sourceUri = "") {
31168
+ this.bytes = bytes;
31169
+ this.mimeType = mimeType;
31170
+ this.name = name;
31171
+ this.sourceUri = sourceUri;
31172
+ }
31173
+ base64 = async () => {
31174
+ const bytes = this.bytes ?? new Uint8Array(await readFile2(this.sourceUri));
31175
+ return Buffer.from(bytes).toString("base64");
31176
+ };
31177
+ };
31178
+ function startsWith(bytes, signature, offset = 0) {
31179
+ if (bytes.byteLength < offset + signature.byteLength) {
31180
+ return false;
31181
+ }
31182
+ return signature.every((value, index2) => bytes[offset + index2] === value);
31183
+ }
31184
+ function sniffRasterMime(bytes) {
31185
+ if (startsWith(bytes, PNG_SIGNATURE)) {
31186
+ return "image/png";
31187
+ }
31188
+ if (startsWith(bytes, JPEG_SIGNATURE)) {
31189
+ return "image/jpeg";
31190
+ }
31191
+ if (startsWith(bytes, GIF87_SIGNATURE) || startsWith(bytes, GIF89_SIGNATURE)) {
31192
+ return "image/gif";
31193
+ }
31194
+ if (startsWith(bytes, RIFF_SIGNATURE) && startsWith(bytes, WEBP_SIGNATURE, 8)) {
31195
+ return "image/webp";
31196
+ }
31197
+ return null;
31198
+ }
31199
+ function readInlineRaster(data, name = "Image") {
31200
+ if (data.length === 0 || data.length > Math.ceil(MAX_INLINE_RASTER_BYTES / 3) * 4 || data.length % 4 !== 0) {
31201
+ return null;
31202
+ }
31203
+ if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(data)) {
31204
+ return null;
31205
+ }
31206
+ const bytes = new Uint8Array(Buffer.from(data, "base64"));
31207
+ if (bytes.byteLength < 1 || bytes.byteLength > MAX_INLINE_RASTER_BYTES) {
31208
+ return null;
31209
+ }
31210
+ const mimeType = sniffRasterMime(bytes);
31211
+ if (mimeType === null) {
31212
+ return null;
31213
+ }
31214
+ return new LocalRasterImage(basename2(name) || "Image", mimeType, bytes);
31215
+ }
31216
+ async function resolveCanonicalPath(requested, signal) {
31217
+ signal.throwIfAborted();
31218
+ if (!isAbsolute8(requested) || requested.includes("\0") || normalize2(requested) !== requested) {
31219
+ return null;
31220
+ }
31221
+ try {
31222
+ const target = await realpath7(requested);
31223
+ signal.throwIfAborted();
31224
+ if (!isAbsolute8(target) || normalize2(target) !== target) {
31225
+ return null;
31226
+ }
31227
+ return target;
31228
+ } catch (cause) {
31229
+ signal.throwIfAborted();
31230
+ if (cause instanceof Error && cause.name === "AbortError") {
31231
+ throw cause;
31232
+ }
31233
+ return null;
31234
+ }
31235
+ }
31236
+ function parseLocalImageUri(uri) {
31237
+ const trimmed = uri.trim();
31238
+ if (trimmed.length === 0 || trimmed.length > 2048 || trimmed.includes("\0")) {
31239
+ return null;
31240
+ }
31241
+ if (trimmed.startsWith("data:")) {
31242
+ return null;
31243
+ }
31244
+ if (trimmed.startsWith("file:")) {
31245
+ try {
31246
+ const url2 = new URL(trimmed);
31247
+ if (url2.protocol !== "file:" || url2.host.length > 0) {
31248
+ return null;
31249
+ }
31250
+ return fileURLToPath(url2);
31251
+ } catch {
31252
+ return null;
31253
+ }
31254
+ }
31255
+ if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(trimmed)) {
31256
+ return null;
31257
+ }
31258
+ return trimmed;
31259
+ }
31260
+ async function readLocalRaster(uri, signal) {
31261
+ signal.throwIfAborted();
31262
+ const requested = parseLocalImageUri(uri);
31263
+ if (requested === null) {
31264
+ return null;
31265
+ }
31266
+ const target = await resolveCanonicalPath(requested, signal);
31267
+ if (target === null) {
31268
+ return null;
31269
+ }
31270
+ const targetMetadata = await stat6(target);
31271
+ signal.throwIfAborted();
31272
+ if (!targetMetadata.isFile() || targetMetadata.size < 1 || targetMetadata.size > MAX_LOCAL_RASTER_BYTES) {
31273
+ return null;
31274
+ }
31275
+ const handle = await open5(target, "r");
31276
+ const header = new Uint8Array(12);
31277
+ try {
31278
+ await handle.read(header, 0, header.byteLength, 0);
31279
+ } finally {
31280
+ await handle.close();
31281
+ }
31282
+ signal.throwIfAborted();
31283
+ const mimeType = sniffRasterMime(header);
31284
+ if (mimeType === null) {
31285
+ return null;
31286
+ }
31287
+ return new LocalRasterImage(basename2(target) || "Image", mimeType, null, target);
31288
+ }
31289
+
31290
+ // src/authorization/local-video.ts
31291
+ import { basename as basename3 } from "node:path";
31292
+ var MAX_INLINE_VIDEO_BYTES = 3e6;
31293
+ var MP4_FILE_TYPE = new TextEncoder().encode("ftyp");
31294
+ var WEBM_SIGNATURE = Uint8Array.of(26, 69, 223, 163);
31295
+ var LocalVideo = class {
31296
+ bytes;
31297
+ mimeType;
31298
+ name;
31299
+ constructor(name, mimeType, bytes) {
31300
+ this.bytes = bytes;
31301
+ this.mimeType = mimeType;
31302
+ this.name = name;
31303
+ }
31304
+ base64 = () => Buffer.from(this.bytes).toString("base64");
31305
+ };
31306
+ function startsWith2(bytes, signature, offset = 0) {
31307
+ if (bytes.byteLength < offset + signature.byteLength) {
31308
+ return false;
31309
+ }
31310
+ return signature.every((value, index2) => bytes[offset + index2] === value);
31311
+ }
31312
+ function sniffVideoMime(bytes) {
31313
+ if (startsWith2(bytes, MP4_FILE_TYPE, 4)) {
31314
+ return "video/mp4";
31315
+ }
31316
+ if (startsWith2(bytes, WEBM_SIGNATURE)) {
31317
+ return "video/webm";
31318
+ }
31319
+ return null;
31320
+ }
31321
+ function readInlineVideo(data, declaredMimeType, name = "Video") {
31322
+ if (data.length === 0 || data.length > Math.ceil(MAX_INLINE_VIDEO_BYTES / 3) * 4 || data.length % 4 !== 0) {
31323
+ return null;
31324
+ }
31325
+ if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(data)) {
31326
+ return null;
31327
+ }
31328
+ const bytes = new Uint8Array(Buffer.from(data, "base64"));
31329
+ if (bytes.byteLength < 1 || bytes.byteLength > MAX_INLINE_VIDEO_BYTES) {
31330
+ return null;
31331
+ }
31332
+ const mimeType = sniffVideoMime(bytes);
31333
+ if (mimeType === null || mimeType !== declaredMimeType) {
31334
+ return null;
31335
+ }
31336
+ return new LocalVideo(basename3(name) || "Video", mimeType, bytes);
31337
+ }
31338
+
30984
31339
  // src/native-sessions/history-images.ts
30985
31340
  var IMAGE_MARKER = /\[@image\]\(([^)\r\n]*)(?:\)|$)/g;
30986
31341
  async function embedLocalHistoryImages(history, signal) {
@@ -31640,6 +31995,244 @@ var AcpActivityTracker = class {
31640
31995
  };
31641
31996
  };
31642
31997
 
31998
+ // src/acp/value-utils.ts
31999
+ function truncate3(value, maximumLength) {
32000
+ return value.length <= maximumLength ? value : `${value.slice(0, Math.max(0, maximumLength - 1))}\u2026`;
32001
+ }
32002
+ function isRecord8(value) {
32003
+ return typeof value === "object" && value !== null && !Array.isArray(value);
32004
+ }
32005
+ function readString2(value, fallback = "") {
32006
+ return typeof value === "string" ? value : fallback;
32007
+ }
32008
+
32009
+ // src/acp/elicitation.ts
32010
+ function elicitationFieldType(value) {
32011
+ if (value === "boolean") {
32012
+ return "boolean";
32013
+ }
32014
+ if (value === "integer") {
32015
+ return "integer";
32016
+ }
32017
+ if (value === "number") {
32018
+ return "number";
32019
+ }
32020
+ if (value === "array") {
32021
+ return "multiselect";
32022
+ }
32023
+ return "string";
32024
+ }
32025
+ function normalizeElicitationOptions(schema) {
32026
+ const normalized = [];
32027
+ const oneOf = schema["oneOf"];
32028
+ if (Array.isArray(oneOf)) {
32029
+ for (const option of oneOf) {
32030
+ if (isRecord8(option) && typeof option["const"] === "string") {
32031
+ normalized.push({
32032
+ description: truncate3(readString2(option["description"]), 500),
32033
+ label: truncate3(readString2(option["title"], option["const"]), 255),
32034
+ value: truncate3(option["const"], 500)
32035
+ });
32036
+ }
32037
+ }
32038
+ return normalized.slice(0, 200);
32039
+ }
32040
+ const enumValues = schema["enum"];
32041
+ if (Array.isArray(enumValues)) {
32042
+ for (const entry of enumValues) {
32043
+ if (typeof entry === "string") {
32044
+ normalized.push({ description: "", label: entry, value: entry });
32045
+ }
32046
+ }
32047
+ return normalized.slice(0, 200);
32048
+ }
32049
+ const items = schema["items"];
32050
+ if (!isRecord8(items)) {
32051
+ return normalized;
32052
+ }
32053
+ const anyOf = items["anyOf"];
32054
+ if (Array.isArray(anyOf)) {
32055
+ return normalizeElicitationOptions({ oneOf: anyOf });
32056
+ }
32057
+ return normalizeElicitationOptions({ enum: items["enum"] });
32058
+ }
32059
+ function numericString(value) {
32060
+ return typeof value === "number" && Number.isFinite(value) ? value.toString() : "";
32061
+ }
32062
+ function normalizeElicitationFields(requestedSchema) {
32063
+ if (!isRecord8(requestedSchema) || !isRecord8(requestedSchema["properties"])) {
32064
+ return [];
32065
+ }
32066
+ const properties = requestedSchema["properties"];
32067
+ const requiredValues = requestedSchema["required"];
32068
+ const required2 = new Set(
32069
+ Array.isArray(requiredValues) ? requiredValues.filter((entry) => typeof entry === "string") : []
32070
+ );
32071
+ const normalized = [];
32072
+ for (const [name, property] of Object.entries(properties)) {
32073
+ if (!isRecord8(property)) {
32074
+ continue;
32075
+ }
32076
+ const type = elicitationFieldType(property["type"]);
32077
+ const options = normalizeElicitationOptions(property);
32078
+ const normalizedType = type === "string" && options.length > 0 ? "select" : type;
32079
+ const defaultValue = property["default"];
32080
+ normalized.push({
32081
+ defaultBooleanValue: typeof defaultValue === "boolean" ? defaultValue : false,
32082
+ defaultNumberValue: typeof defaultValue === "number" && Number.isFinite(defaultValue) ? defaultValue : 0,
32083
+ defaultStringValue: typeof defaultValue === "string" ? truncate3(defaultValue, 1e4) : Array.isArray(defaultValue) ? truncate3(JSON.stringify(defaultValue), 1e4) : "",
32084
+ description: truncate3(readString2(property["description"]), 500),
32085
+ format: truncate3(readString2(property["format"]), 64),
32086
+ hasDefaultValue: defaultValue !== void 0 && defaultValue !== null,
32087
+ maximum: numericString(property["maximum"]),
32088
+ maximumLength: numericString(property["maxLength"] ?? property["maxItems"]),
32089
+ minimum: numericString(property["minimum"]),
32090
+ minimumLength: numericString(property["minLength"] ?? property["minItems"]),
32091
+ name: truncate3(name, 128),
32092
+ options,
32093
+ pattern: truncate3(readString2(property["pattern"]), 500),
32094
+ required: required2.has(name),
32095
+ title: truncate3(readString2(property["title"], name), 255),
32096
+ type: normalizedType
32097
+ });
32098
+ }
32099
+ return normalized.slice(0, 100);
32100
+ }
32101
+ function validateStringValue(name, value, schema) {
32102
+ const minimum = schema["minLength"];
32103
+ const maximum = schema["maxLength"];
32104
+ if (typeof minimum === "number" && value.length < minimum) {
32105
+ throw new AcpExecutionError(
32106
+ `Elicitation field ${name} is shorter than allowed`,
32107
+ {},
32108
+ "invalid_elicitation_response"
32109
+ );
32110
+ }
32111
+ if (typeof maximum === "number" && value.length > maximum) {
32112
+ throw new AcpExecutionError(
32113
+ `Elicitation field ${name} is longer than allowed`,
32114
+ {},
32115
+ "invalid_elicitation_response"
32116
+ );
32117
+ }
32118
+ const pattern = schema["pattern"];
32119
+ if (typeof pattern === "string" && !new RegExp(pattern, "u").test(value)) {
32120
+ throw new AcpExecutionError(
32121
+ `Elicitation field ${name} does not match the required format`,
32122
+ {},
32123
+ "invalid_elicitation_response"
32124
+ );
32125
+ }
32126
+ const allowed = normalizeElicitationOptions(schema);
32127
+ if (allowed.length > 0 && !allowed.some((entry) => entry.value === value)) {
32128
+ throw new AcpExecutionError(
32129
+ `Elicitation field ${name} is not an allowed value`,
32130
+ {},
32131
+ "invalid_elicitation_response"
32132
+ );
32133
+ }
32134
+ }
32135
+ function validateNumericValue(name, value, schema, integer2) {
32136
+ if (!Number.isFinite(value) || integer2 && !Number.isInteger(value)) {
32137
+ throw new AcpExecutionError(
32138
+ `Elicitation field ${name} is not a valid number`,
32139
+ {},
32140
+ "invalid_elicitation_response"
32141
+ );
32142
+ }
32143
+ const minimum = schema["minimum"];
32144
+ const maximum = schema["maximum"];
32145
+ if (typeof minimum === "number" && value < minimum || typeof maximum === "number" && value > maximum) {
32146
+ throw new AcpExecutionError(
32147
+ `Elicitation field ${name} is outside the allowed range`,
32148
+ {},
32149
+ "invalid_elicitation_response"
32150
+ );
32151
+ }
32152
+ }
32153
+ function validateElicitationContent(encoded, requestedSchema) {
32154
+ let decoded;
32155
+ try {
32156
+ decoded = JSON.parse(encoded);
32157
+ } catch (error62) {
32158
+ throw new AcpExecutionError(
32159
+ "Elicitation response is not valid JSON",
32160
+ { cause: error62 },
32161
+ "invalid_elicitation_response"
32162
+ );
32163
+ }
32164
+ if (!isRecord8(decoded) || !isRecord8(requestedSchema) || !isRecord8(requestedSchema["properties"])) {
32165
+ throw new AcpExecutionError(
32166
+ "Elicitation response does not match the requested form",
32167
+ {},
32168
+ "invalid_elicitation_response"
32169
+ );
32170
+ }
32171
+ const properties = requestedSchema["properties"];
32172
+ const requiredValue = requestedSchema["required"];
32173
+ const required2 = new Set(
32174
+ Array.isArray(requiredValue) ? requiredValue.filter((entry) => typeof entry === "string") : []
32175
+ );
32176
+ for (const name of required2) {
32177
+ if (!(name in decoded)) {
32178
+ throw new AcpExecutionError(`Elicitation field ${name} is required`, {}, "invalid_elicitation_response");
32179
+ }
32180
+ }
32181
+ const validated = {};
32182
+ for (const [name, value] of Object.entries(decoded)) {
32183
+ const property = properties[name];
32184
+ if (!isRecord8(property)) {
32185
+ throw new AcpExecutionError(
32186
+ `Elicitation field ${name} was not requested`,
32187
+ {},
32188
+ "invalid_elicitation_response"
32189
+ );
32190
+ }
32191
+ if (property["type"] === "string" && typeof value === "string") {
32192
+ validateStringValue(name, value, property);
32193
+ validated[name] = value;
32194
+ continue;
32195
+ }
32196
+ if (property["type"] === "number" && typeof value === "number") {
32197
+ validateNumericValue(name, value, property, false);
32198
+ validated[name] = value;
32199
+ continue;
32200
+ }
32201
+ if (property["type"] === "integer" && typeof value === "number") {
32202
+ validateNumericValue(name, value, property, true);
32203
+ validated[name] = value;
32204
+ continue;
32205
+ }
32206
+ if (property["type"] === "boolean" && typeof value === "boolean") {
32207
+ validated[name] = value;
32208
+ continue;
32209
+ }
32210
+ if (property["type"] === "array" && Array.isArray(value) && value.every((entry) => typeof entry === "string")) {
32211
+ const minimum = property["minItems"];
32212
+ const maximum = property["maxItems"];
32213
+ if (typeof minimum === "number" && value.length < minimum || typeof maximum === "number" && value.length > maximum) {
32214
+ throw new AcpExecutionError(
32215
+ `Elicitation field ${name} has an invalid selection count`,
32216
+ {},
32217
+ "invalid_elicitation_response"
32218
+ );
32219
+ }
32220
+ const allowed = normalizeElicitationOptions(property);
32221
+ if (allowed.length > 0 && value.some((entry) => !allowed.some((option) => option.value === entry))) {
32222
+ throw new AcpExecutionError(
32223
+ `Elicitation field ${name} contains an invalid selection`,
32224
+ {},
32225
+ "invalid_elicitation_response"
32226
+ );
32227
+ }
32228
+ validated[name] = value;
32229
+ continue;
32230
+ }
32231
+ throw new AcpExecutionError(`Elicitation field ${name} has the wrong type`, {}, "invalid_elicitation_response");
32232
+ }
32233
+ return validated;
32234
+ }
32235
+
31643
32236
  // ../../node_modules/.pnpm/mdast-util-to-string@4.0.0/node_modules/mdast-util-to-string/lib/index.js
31644
32237
  var emptyOptions = {};
31645
32238
  function toString(value, options) {
@@ -34227,7 +34820,7 @@ var attention = {
34227
34820
  };
34228
34821
  function resolveAllAttention(events, context) {
34229
34822
  let index2 = -1;
34230
- let open8;
34823
+ let open7;
34231
34824
  let group;
34232
34825
  let text3;
34233
34826
  let openingSequence;
@@ -34237,16 +34830,16 @@ function resolveAllAttention(events, context) {
34237
34830
  let offset;
34238
34831
  while (++index2 < events.length) {
34239
34832
  if (events[index2][0] === "enter" && events[index2][1].type === "attentionSequence" && events[index2][1]._close) {
34240
- open8 = index2;
34241
- while (open8--) {
34242
- if (events[open8][0] === "exit" && events[open8][1].type === "attentionSequence" && events[open8][1]._open && // If the markers are the same:
34243
- context.sliceSerialize(events[open8][1]).charCodeAt(0) === context.sliceSerialize(events[index2][1]).charCodeAt(0)) {
34244
- if ((events[open8][1]._close || events[index2][1]._open) && (events[index2][1].end.offset - events[index2][1].start.offset) % 3 && !((events[open8][1].end.offset - events[open8][1].start.offset + events[index2][1].end.offset - events[index2][1].start.offset) % 3)) {
34833
+ open7 = index2;
34834
+ while (open7--) {
34835
+ if (events[open7][0] === "exit" && events[open7][1].type === "attentionSequence" && events[open7][1]._open && // If the markers are the same:
34836
+ context.sliceSerialize(events[open7][1]).charCodeAt(0) === context.sliceSerialize(events[index2][1]).charCodeAt(0)) {
34837
+ if ((events[open7][1]._close || events[index2][1]._open) && (events[index2][1].end.offset - events[index2][1].start.offset) % 3 && !((events[open7][1].end.offset - events[open7][1].start.offset + events[index2][1].end.offset - events[index2][1].start.offset) % 3)) {
34245
34838
  continue;
34246
34839
  }
34247
- use = events[open8][1].end.offset - events[open8][1].start.offset > 1 && events[index2][1].end.offset - events[index2][1].start.offset > 1 ? 2 : 1;
34840
+ use = events[open7][1].end.offset - events[open7][1].start.offset > 1 && events[index2][1].end.offset - events[index2][1].start.offset > 1 ? 2 : 1;
34248
34841
  const start = {
34249
- ...events[open8][1].end
34842
+ ...events[open7][1].end
34250
34843
  };
34251
34844
  const end = {
34252
34845
  ...events[index2][1].start
@@ -34257,7 +34850,7 @@ function resolveAllAttention(events, context) {
34257
34850
  type: use > 1 ? "strongSequence" : "emphasisSequence",
34258
34851
  start,
34259
34852
  end: {
34260
- ...events[open8][1].end
34853
+ ...events[open7][1].end
34261
34854
  }
34262
34855
  };
34263
34856
  closingSequence = {
@@ -34270,7 +34863,7 @@ function resolveAllAttention(events, context) {
34270
34863
  text3 = {
34271
34864
  type: use > 1 ? "strongText" : "emphasisText",
34272
34865
  start: {
34273
- ...events[open8][1].end
34866
+ ...events[open7][1].end
34274
34867
  },
34275
34868
  end: {
34276
34869
  ...events[index2][1].start
@@ -34285,18 +34878,18 @@ function resolveAllAttention(events, context) {
34285
34878
  ...closingSequence.end
34286
34879
  }
34287
34880
  };
34288
- events[open8][1].end = {
34881
+ events[open7][1].end = {
34289
34882
  ...openingSequence.start
34290
34883
  };
34291
34884
  events[index2][1].start = {
34292
34885
  ...closingSequence.end
34293
34886
  };
34294
34887
  nextEvents = [];
34295
- if (events[open8][1].end.offset - events[open8][1].start.offset) {
34296
- nextEvents = push(nextEvents, [["enter", events[open8][1], context], ["exit", events[open8][1], context]]);
34888
+ if (events[open7][1].end.offset - events[open7][1].start.offset) {
34889
+ nextEvents = push(nextEvents, [["enter", events[open7][1], context], ["exit", events[open7][1], context]]);
34297
34890
  }
34298
34891
  nextEvents = push(nextEvents, [["enter", group, context], ["enter", openingSequence, context], ["exit", openingSequence, context], ["enter", text3, context]]);
34299
- nextEvents = push(nextEvents, resolveAll(context.parser.constructs.insideSpan.null, events.slice(open8 + 1, index2), context));
34892
+ nextEvents = push(nextEvents, resolveAll(context.parser.constructs.insideSpan.null, events.slice(open7 + 1, index2), context));
34300
34893
  nextEvents = push(nextEvents, [["exit", text3, context], ["enter", closingSequence, context], ["exit", closingSequence, context], ["exit", group, context]]);
34301
34894
  if (events[index2][1].end.offset - events[index2][1].start.offset) {
34302
34895
  offset = 2;
@@ -34304,8 +34897,8 @@ function resolveAllAttention(events, context) {
34304
34897
  } else {
34305
34898
  offset = 0;
34306
34899
  }
34307
- splice(events, open8 - 1, index2 - open8 + 3, nextEvents);
34308
- index2 = open8 + nextEvents.length - offset - 2;
34900
+ splice(events, open7 - 1, index2 - open7 + 3, nextEvents);
34901
+ index2 = open7 + nextEvents.length - offset - 2;
34309
34902
  break;
34310
34903
  }
34311
34904
  }
@@ -34337,10 +34930,10 @@ function tokenizeAttention(effects, ok2) {
34337
34930
  }
34338
34931
  const token = effects.exit("attentionSequence");
34339
34932
  const after = classifyCharacter(code);
34340
- const open8 = !after || after === 2 && before || attentionMarkers2.includes(code);
34933
+ const open7 = !after || after === 2 && before || attentionMarkers2.includes(code);
34341
34934
  const close = !before || before === 2 && after || attentionMarkers2.includes(previous2);
34342
- token._open = Boolean(marker === 42 ? open8 : open8 && (before || !close));
34343
- token._close = Boolean(marker === 42 ? close : close && (after || !open8));
34935
+ token._open = Boolean(marker === 42 ? open7 : open7 && (before || !close));
34936
+ token._close = Boolean(marker === 42 ? close : close && (after || !open7));
34344
34937
  return ok2(code);
34345
34938
  }
34346
34939
  }
@@ -34364,9 +34957,9 @@ function tokenizeAutolink(effects, ok2, nok) {
34364
34957
  effects.consume(code);
34365
34958
  effects.exit("autolinkMarker");
34366
34959
  effects.enter("autolinkProtocol");
34367
- return open8;
34960
+ return open7;
34368
34961
  }
34369
- function open8(code) {
34962
+ function open7(code) {
34370
34963
  if (asciiAlpha(code)) {
34371
34964
  effects.consume(code);
34372
34965
  return schemeOrEmailAtext;
@@ -34566,9 +35159,9 @@ function tokenizeCharacterReference(effects, ok2, nok) {
34566
35159
  effects.enter("characterReferenceMarker");
34567
35160
  effects.consume(code);
34568
35161
  effects.exit("characterReferenceMarker");
34569
- return open8;
35162
+ return open7;
34570
35163
  }
34571
- function open8(code) {
35164
+ function open7(code) {
34572
35165
  if (code === 35) {
34573
35166
  effects.enter("characterReferenceMarkerNumeric");
34574
35167
  effects.consume(code);
@@ -35937,9 +36530,9 @@ function tokenizeHtmlFlow(effects, ok2, nok) {
35937
36530
  effects.enter("htmlFlow");
35938
36531
  effects.enter("htmlFlowData");
35939
36532
  effects.consume(code);
35940
- return open8;
36533
+ return open7;
35941
36534
  }
35942
- function open8(code) {
36535
+ function open7(code) {
35943
36536
  if (code === 33) {
35944
36537
  effects.consume(code);
35945
36538
  return declarationOpen;
@@ -36287,9 +36880,9 @@ function tokenizeHtmlText(effects, ok2, nok) {
36287
36880
  effects.enter("htmlText");
36288
36881
  effects.enter("htmlTextData");
36289
36882
  effects.consume(code);
36290
- return open8;
36883
+ return open7;
36291
36884
  }
36292
- function open8(code) {
36885
+ function open7(code) {
36293
36886
  if (code === 33) {
36294
36887
  effects.consume(code);
36295
36888
  return declarationOpen;
@@ -36615,12 +37208,12 @@ function resolveToLabelEnd(events, context) {
36615
37208
  let index2 = events.length;
36616
37209
  let offset = 0;
36617
37210
  let token;
36618
- let open8;
37211
+ let open7;
36619
37212
  let close;
36620
37213
  let media;
36621
37214
  while (index2--) {
36622
37215
  token = events[index2][1];
36623
- if (open8) {
37216
+ if (open7) {
36624
37217
  if (token.type === "link" || token.type === "labelLink" && token._inactive) {
36625
37218
  break;
36626
37219
  }
@@ -36629,7 +37222,7 @@ function resolveToLabelEnd(events, context) {
36629
37222
  }
36630
37223
  } else if (close) {
36631
37224
  if (events[index2][0] === "enter" && (token.type === "labelImage" || token.type === "labelLink") && !token._balanced) {
36632
- open8 = index2;
37225
+ open7 = index2;
36633
37226
  if (token.type !== "labelLink") {
36634
37227
  offset = 2;
36635
37228
  break;
@@ -36640,9 +37233,9 @@ function resolveToLabelEnd(events, context) {
36640
37233
  }
36641
37234
  }
36642
37235
  const group = {
36643
- type: events[open8][1].type === "labelLink" ? "link" : "image",
37236
+ type: events[open7][1].type === "labelLink" ? "link" : "image",
36644
37237
  start: {
36645
- ...events[open8][1].start
37238
+ ...events[open7][1].start
36646
37239
  },
36647
37240
  end: {
36648
37241
  ...events[events.length - 1][1].end
@@ -36651,7 +37244,7 @@ function resolveToLabelEnd(events, context) {
36651
37244
  const label = {
36652
37245
  type: "label",
36653
37246
  start: {
36654
- ...events[open8][1].start
37247
+ ...events[open7][1].start
36655
37248
  },
36656
37249
  end: {
36657
37250
  ...events[close][1].end
@@ -36660,20 +37253,20 @@ function resolveToLabelEnd(events, context) {
36660
37253
  const text3 = {
36661
37254
  type: "labelText",
36662
37255
  start: {
36663
- ...events[open8 + offset + 2][1].end
37256
+ ...events[open7 + offset + 2][1].end
36664
37257
  },
36665
37258
  end: {
36666
37259
  ...events[close - 2][1].start
36667
37260
  }
36668
37261
  };
36669
37262
  media = [["enter", group, context], ["enter", label, context]];
36670
- media = push(media, events.slice(open8 + 1, open8 + offset + 3));
37263
+ media = push(media, events.slice(open7 + 1, open7 + offset + 3));
36671
37264
  media = push(media, [["enter", text3, context]]);
36672
- media = push(media, resolveAll(context.parser.constructs.insideSpan.null, events.slice(open8 + offset + 4, close - 3), context));
37265
+ media = push(media, resolveAll(context.parser.constructs.insideSpan.null, events.slice(open7 + offset + 4, close - 3), context));
36673
37266
  media = push(media, [["exit", text3, context], events[close - 2], events[close - 1], ["exit", label, context]]);
36674
37267
  media = push(media, events.slice(close + 1));
36675
37268
  media = push(media, [["exit", group, context]]);
36676
- splice(events, open8, events.length, media);
37269
+ splice(events, open7, events.length, media);
36677
37270
  return events;
36678
37271
  }
36679
37272
  function tokenizeLabelEnd(effects, ok2, nok) {
@@ -36818,9 +37411,9 @@ function tokenizeLabelStartImage(effects, ok2, nok) {
36818
37411
  effects.enter("labelImageMarker");
36819
37412
  effects.consume(code);
36820
37413
  effects.exit("labelImageMarker");
36821
- return open8;
37414
+ return open7;
36822
37415
  }
36823
- function open8(code) {
37416
+ function open7(code) {
36824
37417
  if (code === 91) {
36825
37418
  effects.enter("labelMarker");
36826
37419
  effects.consume(code);
@@ -38124,8 +38717,8 @@ function compiler(options) {
38124
38717
  return length;
38125
38718
  }
38126
38719
  function opener(create, and) {
38127
- return open8;
38128
- function open8(token) {
38720
+ return open7;
38721
+ function open7(token) {
38129
38722
  enter.call(this, create(token), token);
38130
38723
  if (and) and.call(this, token);
38131
38724
  }
@@ -38157,18 +38750,18 @@ function compiler(options) {
38157
38750
  }
38158
38751
  function exit2(token, onExitError) {
38159
38752
  const node3 = this.stack.pop();
38160
- const open8 = this.tokenStack.pop();
38161
- if (!open8) {
38753
+ const open7 = this.tokenStack.pop();
38754
+ if (!open7) {
38162
38755
  throw new Error("Cannot close `" + token.type + "` (" + stringifyPosition({
38163
38756
  start: token.start,
38164
38757
  end: token.end
38165
38758
  }) + "): it\u2019s not open");
38166
- } else if (open8[0].type !== token.type) {
38759
+ } else if (open7[0].type !== token.type) {
38167
38760
  if (onExitError) {
38168
- onExitError.call(this, token, open8[0]);
38761
+ onExitError.call(this, token, open7[0]);
38169
38762
  } else {
38170
- const handler = open8[1] || defaultOnError;
38171
- handler.call(this, token, open8[0]);
38763
+ const handler = open7[1] || defaultOnError;
38764
+ handler.call(this, token, open7[0]);
38172
38765
  }
38173
38766
  }
38174
38767
  node3.position.end = point2(token.end);
@@ -38851,13 +39444,13 @@ var SessionConfigProtocolError = class extends Error {
38851
39444
  this.name = "SessionConfigProtocolError";
38852
39445
  }
38853
39446
  };
38854
- function isRecord8(value) {
39447
+ function isRecord9(value) {
38855
39448
  return typeof value === "object" && value !== null && !Array.isArray(value);
38856
39449
  }
38857
- function readString2(value, fallback = "") {
39450
+ function readString3(value, fallback = "") {
38858
39451
  return typeof value === "string" ? value : fallback;
38859
39452
  }
38860
- function truncate3(value, maximum) {
39453
+ function truncate4(value, maximum) {
38861
39454
  return value.length <= maximum ? value : value.slice(0, maximum);
38862
39455
  }
38863
39456
  function readBoolean(value, fallback = false) {
@@ -38869,11 +39462,11 @@ function normalizeConfigValue(option, groupId = "", groupName = "") {
38869
39462
  return void 0;
38870
39463
  }
38871
39464
  return {
38872
- description: truncate3(readString2(option["description"]), 500),
38873
- groupId: truncate3(groupId, 128),
38874
- groupName: truncate3(groupName, 255),
38875
- name: truncate3(readString2(option["name"], value), 255),
38876
- value: truncate3(value, 500)
39465
+ description: truncate4(readString3(option["description"]), 500),
39466
+ groupId: truncate4(groupId, 128),
39467
+ groupName: truncate4(groupName, 255),
39468
+ name: truncate4(readString3(option["name"], value), 255),
39469
+ value: truncate4(value, 500)
38877
39470
  };
38878
39471
  }
38879
39472
  function normalizeConfigValues(value) {
@@ -38882,15 +39475,15 @@ function normalizeConfigValues(value) {
38882
39475
  }
38883
39476
  const normalized = [];
38884
39477
  for (const entry of value) {
38885
- if (!isRecord8(entry)) {
39478
+ if (!isRecord9(entry)) {
38886
39479
  continue;
38887
39480
  }
38888
39481
  const groupedOptions = entry["options"];
38889
39482
  if (Array.isArray(groupedOptions)) {
38890
- const groupId = readString2(entry["group"]);
38891
- const groupName = readString2(entry["name"]);
39483
+ const groupId = readString3(entry["group"]);
39484
+ const groupName = readString3(entry["name"]);
38892
39485
  for (const groupedOption of groupedOptions) {
38893
- if (isRecord8(groupedOption)) {
39486
+ if (isRecord9(groupedOption)) {
38894
39487
  const normalizedValue = normalizeConfigValue(groupedOption, groupId, groupName);
38895
39488
  if (normalizedValue !== void 0) {
38896
39489
  normalized.push(normalizedValue);
@@ -38910,12 +39503,12 @@ function normalizeConfigOptions(value, modes) {
38910
39503
  const normalized = [];
38911
39504
  if (Array.isArray(value)) {
38912
39505
  for (const option of value) {
38913
- if (!isRecord8(option)) {
39506
+ if (!isRecord9(option)) {
38914
39507
  continue;
38915
39508
  }
38916
- const id = truncate3(readString2(option["id"]), 128);
38917
- const name = truncate3(readString2(option["name"], id), 255);
38918
- const category = truncate3(readString2(option["category"]), 128);
39509
+ const id = truncate4(readString3(option["id"]), 128);
39510
+ const name = truncate4(readString3(option["name"], id), 255);
39511
+ const category = truncate4(readString3(option["category"]), 128);
38919
39512
  if (id.length === 0 || name.length === 0 || category === "_mobius_permission") {
38920
39513
  continue;
38921
39514
  }
@@ -38924,7 +39517,7 @@ function normalizeConfigOptions(value, modes) {
38924
39517
  booleanValue: readBoolean(option["currentValue"]),
38925
39518
  category,
38926
39519
  currentValue: "",
38927
- description: truncate3(readString2(option["description"]), 500),
39520
+ description: truncate4(readString3(option["description"]), 500),
38928
39521
  id,
38929
39522
  name,
38930
39523
  type: "boolean",
@@ -38934,13 +39527,13 @@ function normalizeConfigOptions(value, modes) {
38934
39527
  }
38935
39528
  if (option["type"] === "select") {
38936
39529
  const values = normalizeConfigValues(option["options"]);
38937
- const currentValue = truncate3(readString2(option["currentValue"]), 500);
39530
+ const currentValue = truncate4(readString3(option["currentValue"]), 500);
38938
39531
  if (values.some((entry) => entry.value === currentValue)) {
38939
39532
  normalized.push({
38940
39533
  booleanValue: false,
38941
39534
  category,
38942
39535
  currentValue,
38943
- description: truncate3(readString2(option["description"]), 500),
39536
+ description: truncate4(readString3(option["description"]), 500),
38944
39537
  id,
38945
39538
  name,
38946
39539
  type: "select",
@@ -38950,28 +39543,28 @@ function normalizeConfigOptions(value, modes) {
38950
39543
  }
38951
39544
  }
38952
39545
  }
38953
- if (isRecord8(modes)) {
39546
+ if (isRecord9(modes)) {
38954
39547
  const values = [];
38955
39548
  const availableModes = modes["availableModes"];
38956
39549
  if (Array.isArray(availableModes)) {
38957
39550
  for (const mode of availableModes) {
38958
- if (!isRecord8(mode)) {
39551
+ if (!isRecord9(mode)) {
38959
39552
  continue;
38960
39553
  }
38961
- const id = truncate3(readString2(mode["id"]), 500);
39554
+ const id = truncate4(readString3(mode["id"]), 500);
38962
39555
  if (id.length === 0) {
38963
39556
  continue;
38964
39557
  }
38965
39558
  values.push({
38966
- description: truncate3(readString2(mode["description"]), 500),
39559
+ description: truncate4(readString3(mode["description"]), 500),
38967
39560
  groupId: "",
38968
39561
  groupName: "",
38969
- name: truncate3(readString2(mode["name"], id), 255),
39562
+ name: truncate4(readString3(mode["name"], id), 255),
38970
39563
  value: id
38971
39564
  });
38972
39565
  }
38973
39566
  }
38974
- const currentValue = truncate3(readString2(modes["currentModeId"]), 500);
39567
+ const currentValue = truncate4(readString3(modes["currentModeId"]), 500);
38975
39568
  if (currentValue.length > 0 && values.some((entry) => entry.value === currentValue) && !normalized.some((entry) => entry.category === "mode")) {
38976
39569
  normalized.unshift({
38977
39570
  booleanValue: false,
@@ -38988,7 +39581,7 @@ function normalizeConfigOptions(value, modes) {
38988
39581
  return normalized.slice(0, MAXIMUM_CONFIG_OPTIONS);
38989
39582
  }
38990
39583
  function normalizeStandardLifecycle(response) {
38991
- const lifecycle = isRecord8(response) ? response : {};
39584
+ const lifecycle = isRecord9(response) ? response : {};
38992
39585
  return normalizeConfigOptions(lifecycle["configOptions"], lifecycle["modes"]);
38993
39586
  }
38994
39587
  function replaceStandardConfigOptions(current, value) {
@@ -39030,7 +39623,7 @@ var StandardSessionConfigProtocol = class {
39030
39623
  "ACP agent exited while changing session configuration",
39031
39624
  change.signal
39032
39625
  );
39033
- if (!isRecord8(response) || !Array.isArray(response["configOptions"])) {
39626
+ if (!isRecord9(response) || !Array.isArray(response["configOptions"])) {
39034
39627
  throw new SessionConfigProtocolError("The Agent returned an invalid session configuration response");
39035
39628
  }
39036
39629
  return replaceStandardConfigOptions(current, response["configOptions"]);
@@ -39250,216 +39843,11 @@ var AcpHistoryReplay = class {
39250
39843
  };
39251
39844
  };
39252
39845
 
39253
- // src/acp/session-store.ts
39254
- import { mkdirSync as mkdirSync2 } from "node:fs";
39255
- import { dirname as dirname5 } from "node:path";
39256
- import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
39257
- var AcpStoredSession = class {
39258
- additionalDirectories;
39259
- agentId;
39260
- cwd;
39261
- nativeSessionId;
39262
- prompted;
39263
- sessionId;
39264
- constructor(sessionId, agentId, nativeSessionId, cwd, additionalDirectories, prompted) {
39265
- this.additionalDirectories = [...additionalDirectories];
39266
- this.agentId = agentId;
39267
- this.cwd = cwd;
39268
- this.nativeSessionId = nativeSessionId;
39269
- this.prompted = prompted;
39270
- this.sessionId = sessionId;
39271
- }
39272
- };
39273
- var AcpStoredSessionLookup = class {
39274
- };
39275
- var MissingAcpStoredSession = class extends AcpStoredSessionLookup {
39276
- found = false;
39277
- };
39278
- var FoundAcpStoredSession = class extends AcpStoredSessionLookup {
39279
- found = true;
39280
- session;
39281
- constructor(session) {
39282
- super();
39283
- this.session = session;
39284
- }
39285
- };
39286
- var DeletedAcpStoredSession = class extends AcpStoredSessionLookup {
39287
- found = false;
39288
- };
39289
- function readString3(value, field) {
39290
- if (typeof value !== "string" || value.length === 0) {
39291
- throw new Error(`Stored ACP session has an invalid ${field}`);
39292
- }
39293
- return value;
39294
- }
39295
- function readAdditionalDirectories(value) {
39296
- if (typeof value !== "string") {
39297
- throw new Error("Stored ACP session has invalid additional directories");
39298
- }
39299
- const decoded = JSON.parse(value);
39300
- if (!Array.isArray(decoded) || decoded.some((directory) => typeof directory !== "string")) {
39301
- throw new Error("Stored ACP session has invalid additional directories");
39302
- }
39303
- return decoded;
39304
- }
39305
- function readPrompted(value) {
39306
- if (value === 0) {
39307
- return false;
39308
- }
39309
- if (value === 1) {
39310
- return true;
39311
- }
39312
- throw new Error("Stored ACP session has an invalid prompted state");
39313
- }
39314
- function decodeSessionRow(row) {
39315
- if (typeof row !== "object" || row === null || Array.isArray(row)) {
39316
- throw new Error("Stored ACP session is not an object");
39317
- }
39318
- return new AcpStoredSession(
39319
- readString3(Reflect.get(row, "session_id"), "session ID"),
39320
- readString3(Reflect.get(row, "agent_id"), "agent ID"),
39321
- readString3(Reflect.get(row, "native_session_id"), "native session ID"),
39322
- readString3(Reflect.get(row, "cwd"), "working directory"),
39323
- readAdditionalDirectories(Reflect.get(row, "additional_directories_json")),
39324
- readPrompted(Reflect.get(row, "prompted"))
39325
- );
39326
- }
39327
- var MemoryAcpSessionStore = class {
39328
- #sessions = /* @__PURE__ */ new Map();
39329
- #deleted = /* @__PURE__ */ new Set();
39330
- findNative = (agentId, nativeSessionId) => [...this.#sessions.values()].filter(
39331
- (session) => session.agentId === agentId && session.nativeSessionId === nativeSessionId
39332
- );
39333
- markDeleted = (agentId, nativeSessionId) => {
39334
- const ids = this.findNative(agentId, nativeSessionId).map((session) => session.sessionId);
39335
- for (const id of ids) {
39336
- this.#sessions.delete(id);
39337
- this.#deleted.add(id);
39338
- }
39339
- return ids;
39340
- };
39341
- read = (sessionId) => {
39342
- if (this.#deleted.has(sessionId)) {
39343
- return new DeletedAcpStoredSession();
39344
- }
39345
- const session = this.#sessions.get(sessionId);
39346
- return session === void 0 ? new MissingAcpStoredSession() : new FoundAcpStoredSession(session);
39347
- };
39348
- remove = (sessionId) => {
39349
- this.#sessions.delete(sessionId);
39350
- };
39351
- write = (session) => {
39352
- this.#sessions.set(session.sessionId, session);
39353
- };
39354
- };
39355
- var SqliteAcpSessionStore = class {
39356
- #database;
39357
- constructor(path3) {
39358
- mkdirSync2(dirname5(path3), { recursive: true });
39359
- this.#database = new DatabaseSync2(path3);
39360
- this.#database.exec(`
39361
- CREATE TABLE IF NOT EXISTS acp_deleted_sessions (session_id TEXT PRIMARY KEY) STRICT;
39362
- CREATE TABLE IF NOT EXISTS acp_sessions (
39363
- session_id TEXT PRIMARY KEY,
39364
- agent_id TEXT NOT NULL,
39365
- native_session_id TEXT NOT NULL,
39366
- cwd TEXT NOT NULL,
39367
- additional_directories_json TEXT NOT NULL,
39368
- prompted INTEGER NOT NULL DEFAULT 0 CHECK (prompted IN (0, 1)),
39369
- updated_at TEXT NOT NULL
39370
- ) STRICT
39371
- `);
39372
- const columns = this.#database.prepare("PRAGMA table_info(acp_sessions)").all();
39373
- const hasPromptedColumn = columns.some(
39374
- (column) => typeof column === "object" && column !== null && Reflect.get(column, "name") === "prompted"
39375
- );
39376
- if (!hasPromptedColumn) {
39377
- this.#database.exec(`
39378
- ALTER TABLE acp_sessions
39379
- ADD COLUMN prompted INTEGER NOT NULL DEFAULT 1 CHECK (prompted IN (0, 1))
39380
- `);
39381
- }
39382
- }
39383
- read = (sessionId) => {
39384
- if (this.#database.prepare("SELECT session_id FROM acp_deleted_sessions WHERE session_id = ?").get(sessionId) !== void 0) {
39385
- return new DeletedAcpStoredSession();
39386
- }
39387
- const row = this.#database.prepare(
39388
- `
39389
- SELECT
39390
- session_id,
39391
- agent_id,
39392
- native_session_id,
39393
- cwd,
39394
- additional_directories_json,
39395
- prompted
39396
- FROM acp_sessions
39397
- WHERE session_id = ?
39398
- `
39399
- ).get(sessionId);
39400
- return row === void 0 ? new MissingAcpStoredSession() : new FoundAcpStoredSession(decodeSessionRow(row));
39401
- };
39402
- remove = (sessionId) => {
39403
- this.#database.prepare("DELETE FROM acp_sessions WHERE session_id = ?").run(sessionId);
39404
- };
39405
- findNative = (agentId, nativeSessionId) => this.#database.prepare("SELECT * FROM acp_sessions WHERE agent_id = ? AND native_session_id = ?").all(agentId, nativeSessionId).map(decodeSessionRow);
39406
- markDeleted = (agentId, nativeSessionId) => {
39407
- const ids = this.findNative(agentId, nativeSessionId).map((session) => session.sessionId);
39408
- this.#database.exec("BEGIN");
39409
- try {
39410
- for (const id of ids) {
39411
- this.#database.prepare("INSERT OR IGNORE INTO acp_deleted_sessions (session_id) VALUES (?)").run(id);
39412
- this.remove(id);
39413
- }
39414
- this.#database.exec("COMMIT");
39415
- return ids;
39416
- } catch (error62) {
39417
- this.#database.exec("ROLLBACK");
39418
- throw error62;
39419
- }
39420
- };
39421
- write = (session) => {
39422
- this.#database.prepare(
39423
- `
39424
- INSERT INTO acp_sessions (
39425
- session_id,
39426
- agent_id,
39427
- native_session_id,
39428
- cwd,
39429
- additional_directories_json,
39430
- prompted,
39431
- updated_at
39432
- ) VALUES (?, ?, ?, ?, ?, ?, ?)
39433
- ON CONFLICT(session_id) DO UPDATE SET
39434
- agent_id = excluded.agent_id,
39435
- native_session_id = excluded.native_session_id,
39436
- cwd = excluded.cwd,
39437
- additional_directories_json = excluded.additional_directories_json,
39438
- prompted = excluded.prompted,
39439
- updated_at = excluded.updated_at
39440
- `
39441
- ).run(
39442
- session.sessionId,
39443
- session.agentId,
39444
- session.nativeSessionId,
39445
- session.cwd,
39446
- JSON.stringify(session.additionalDirectories),
39447
- session.prompted ? 1 : 0,
39448
- (/* @__PURE__ */ new Date()).toISOString()
39449
- );
39450
- };
39451
- close = () => {
39452
- this.#database.close();
39453
- };
39454
- };
39455
-
39456
- // src/acp/session-manager.ts
39846
+ // src/acp/process-session.ts
39457
39847
  var PROCESS_STOP_TIMEOUT_MILLISECONDS = 1e3;
39458
- var MAX_ACP_PROCESSES = 10;
39459
39848
  var MAX_PRE_SESSION_UPDATES = 100;
39460
39849
  var MAX_PRE_SESSION_UPDATE_BYTES = 1024 * 1024;
39461
39850
  var SESSION_CONTROL_COMMAND_ID = "session-control";
39462
- var SESSION_CONTROL_TIMEOUT_MILLISECONDS = 3e4;
39463
39851
  function nativeHistoryNotRetained() {
39464
39852
  return {
39465
39853
  cause: {
@@ -39512,91 +39900,6 @@ var RetryableAcpInitializationError = class extends AcpExecutionError {
39512
39900
  this.name = "RetryableAcpInitializationError";
39513
39901
  }
39514
39902
  };
39515
- var AcpProcessCapacityLease = class {
39516
- #releaseCapacity;
39517
- #released = false;
39518
- constructor(releaseCapacity) {
39519
- this.#releaseCapacity = releaseCapacity;
39520
- }
39521
- release = () => {
39522
- if (this.#released) {
39523
- return;
39524
- }
39525
- this.#released = true;
39526
- this.#releaseCapacity();
39527
- };
39528
- };
39529
- var AcpProcessCapacityWaiter = class {
39530
- completion = Promise.withResolvers();
39531
- signal;
39532
- constructor(signal) {
39533
- this.signal = signal;
39534
- }
39535
- cancel = () => {
39536
- try {
39537
- this.signal.throwIfAborted();
39538
- } catch (error62) {
39539
- this.completion.reject(error62);
39540
- }
39541
- };
39542
- };
39543
- var AcpProcessCapacityLock = class {
39544
- #locked = false;
39545
- #waiters = [];
39546
- acquire = async (signal) => {
39547
- signal.throwIfAborted();
39548
- if (!this.#locked) {
39549
- this.#locked = true;
39550
- return new AcpProcessCapacityLease(this.#release);
39551
- }
39552
- const waiter = new AcpProcessCapacityWaiter(signal);
39553
- this.#waiters.push(waiter);
39554
- signal.addEventListener("abort", waiter.cancel, { once: true });
39555
- if (signal.aborted) {
39556
- waiter.cancel();
39557
- }
39558
- try {
39559
- return await waiter.completion.promise;
39560
- } finally {
39561
- signal.removeEventListener("abort", waiter.cancel);
39562
- const index2 = this.#waiters.indexOf(waiter);
39563
- if (index2 >= 0) {
39564
- this.#waiters.splice(index2, 1);
39565
- }
39566
- }
39567
- };
39568
- #release = () => {
39569
- while (this.#waiters.length > 0) {
39570
- const waiter = this.#waiters.shift();
39571
- if (waiter === void 0 || waiter.signal.aborted) {
39572
- continue;
39573
- }
39574
- waiter.completion.resolve(new AcpProcessCapacityLease(this.#release));
39575
- return;
39576
- }
39577
- this.#locked = false;
39578
- };
39579
- };
39580
- async function waitForAcpProcessCapacity(completion, signal) {
39581
- signal.throwIfAborted();
39582
- const cancelled = Promise.withResolvers();
39583
- const cancel = () => {
39584
- try {
39585
- signal.throwIfAborted();
39586
- } catch (error62) {
39587
- cancelled.reject(error62);
39588
- }
39589
- };
39590
- signal.addEventListener("abort", cancel, { once: true });
39591
- if (signal.aborted) {
39592
- cancel();
39593
- }
39594
- try {
39595
- await Promise.race([completion, cancelled.promise]);
39596
- } finally {
39597
- signal.removeEventListener("abort", cancel);
39598
- }
39599
- }
39600
39903
  function readableWebStream(input2) {
39601
39904
  let streamOpen = true;
39602
39905
  return new ReadableStream({
@@ -39672,15 +39975,6 @@ function createWritableAcpStream(output2) {
39672
39975
  }
39673
39976
  });
39674
39977
  }
39675
- function truncate4(value, maximumLength) {
39676
- return value.length <= maximumLength ? value : `${value.slice(0, Math.max(0, maximumLength - 1))}\u2026`;
39677
- }
39678
- function isRecord9(value) {
39679
- return typeof value === "object" && value !== null && !Array.isArray(value);
39680
- }
39681
- function readString4(value, fallback = "") {
39682
- return typeof value === "string" ? value : fallback;
39683
- }
39684
39978
  function arraysEqual(left, right) {
39685
39979
  return left.length === right.length && left.every((value, index2) => value === right[index2]);
39686
39980
  }
@@ -39689,231 +39983,6 @@ function recordsEqual(left, right) {
39689
39983
  const rightEntries = Object.entries(right);
39690
39984
  return leftEntries.length === rightEntries.length && leftEntries.every(([name, value]) => right[name] === value);
39691
39985
  }
39692
- function elicitationFieldType(value) {
39693
- if (value === "boolean") {
39694
- return "boolean";
39695
- }
39696
- if (value === "integer") {
39697
- return "integer";
39698
- }
39699
- if (value === "number") {
39700
- return "number";
39701
- }
39702
- if (value === "array") {
39703
- return "multiselect";
39704
- }
39705
- return "string";
39706
- }
39707
- function normalizeElicitationOptions(schema) {
39708
- const normalized = [];
39709
- const oneOf = schema["oneOf"];
39710
- if (Array.isArray(oneOf)) {
39711
- for (const option of oneOf) {
39712
- if (isRecord9(option) && typeof option["const"] === "string") {
39713
- normalized.push({
39714
- description: truncate4(readString4(option["description"]), 500),
39715
- label: truncate4(readString4(option["title"], option["const"]), 255),
39716
- value: truncate4(option["const"], 500)
39717
- });
39718
- }
39719
- }
39720
- return normalized.slice(0, 200);
39721
- }
39722
- const enumValues = schema["enum"];
39723
- if (Array.isArray(enumValues)) {
39724
- for (const entry of enumValues) {
39725
- if (typeof entry === "string") {
39726
- normalized.push({ description: "", label: entry, value: entry });
39727
- }
39728
- }
39729
- return normalized.slice(0, 200);
39730
- }
39731
- const items = schema["items"];
39732
- if (!isRecord9(items)) {
39733
- return normalized;
39734
- }
39735
- const anyOf = items["anyOf"];
39736
- if (Array.isArray(anyOf)) {
39737
- return normalizeElicitationOptions({ oneOf: anyOf });
39738
- }
39739
- return normalizeElicitationOptions({ enum: items["enum"] });
39740
- }
39741
- function numericString(value) {
39742
- return typeof value === "number" && Number.isFinite(value) ? value.toString() : "";
39743
- }
39744
- function normalizeElicitationFields(requestedSchema) {
39745
- if (!isRecord9(requestedSchema) || !isRecord9(requestedSchema["properties"])) {
39746
- return [];
39747
- }
39748
- const properties = requestedSchema["properties"];
39749
- const requiredValues = requestedSchema["required"];
39750
- const required2 = new Set(
39751
- Array.isArray(requiredValues) ? requiredValues.filter((entry) => typeof entry === "string") : []
39752
- );
39753
- const normalized = [];
39754
- for (const [name, property] of Object.entries(properties)) {
39755
- if (!isRecord9(property)) {
39756
- continue;
39757
- }
39758
- const type = elicitationFieldType(property["type"]);
39759
- const options = normalizeElicitationOptions(property);
39760
- const normalizedType = type === "string" && options.length > 0 ? "select" : type;
39761
- const defaultValue = property["default"];
39762
- normalized.push({
39763
- defaultBooleanValue: typeof defaultValue === "boolean" ? defaultValue : false,
39764
- defaultNumberValue: typeof defaultValue === "number" && Number.isFinite(defaultValue) ? defaultValue : 0,
39765
- defaultStringValue: typeof defaultValue === "string" ? truncate4(defaultValue, 1e4) : Array.isArray(defaultValue) ? truncate4(JSON.stringify(defaultValue), 1e4) : "",
39766
- description: truncate4(readString4(property["description"]), 500),
39767
- format: truncate4(readString4(property["format"]), 64),
39768
- hasDefaultValue: defaultValue !== void 0 && defaultValue !== null,
39769
- maximum: numericString(property["maximum"]),
39770
- maximumLength: numericString(property["maxLength"] ?? property["maxItems"]),
39771
- minimum: numericString(property["minimum"]),
39772
- minimumLength: numericString(property["minLength"] ?? property["minItems"]),
39773
- name: truncate4(name, 128),
39774
- options,
39775
- pattern: truncate4(readString4(property["pattern"]), 500),
39776
- required: required2.has(name),
39777
- title: truncate4(readString4(property["title"], name), 255),
39778
- type: normalizedType
39779
- });
39780
- }
39781
- return normalized.slice(0, 100);
39782
- }
39783
- function validateStringValue(name, value, schema) {
39784
- const minimum = schema["minLength"];
39785
- const maximum = schema["maxLength"];
39786
- if (typeof minimum === "number" && value.length < minimum) {
39787
- throw new AcpExecutionError(
39788
- `Elicitation field ${name} is shorter than allowed`,
39789
- {},
39790
- "invalid_elicitation_response"
39791
- );
39792
- }
39793
- if (typeof maximum === "number" && value.length > maximum) {
39794
- throw new AcpExecutionError(
39795
- `Elicitation field ${name} is longer than allowed`,
39796
- {},
39797
- "invalid_elicitation_response"
39798
- );
39799
- }
39800
- const pattern = schema["pattern"];
39801
- if (typeof pattern === "string" && !new RegExp(pattern, "u").test(value)) {
39802
- throw new AcpExecutionError(
39803
- `Elicitation field ${name} does not match the required format`,
39804
- {},
39805
- "invalid_elicitation_response"
39806
- );
39807
- }
39808
- const allowed = normalizeElicitationOptions(schema);
39809
- if (allowed.length > 0 && !allowed.some((entry) => entry.value === value)) {
39810
- throw new AcpExecutionError(
39811
- `Elicitation field ${name} is not an allowed value`,
39812
- {},
39813
- "invalid_elicitation_response"
39814
- );
39815
- }
39816
- }
39817
- function validateNumericValue(name, value, schema, integer2) {
39818
- if (!Number.isFinite(value) || integer2 && !Number.isInteger(value)) {
39819
- throw new AcpExecutionError(
39820
- `Elicitation field ${name} is not a valid number`,
39821
- {},
39822
- "invalid_elicitation_response"
39823
- );
39824
- }
39825
- const minimum = schema["minimum"];
39826
- const maximum = schema["maximum"];
39827
- if (typeof minimum === "number" && value < minimum || typeof maximum === "number" && value > maximum) {
39828
- throw new AcpExecutionError(
39829
- `Elicitation field ${name} is outside the allowed range`,
39830
- {},
39831
- "invalid_elicitation_response"
39832
- );
39833
- }
39834
- }
39835
- function validateElicitationContent(encoded, requestedSchema) {
39836
- let decoded;
39837
- try {
39838
- decoded = JSON.parse(encoded);
39839
- } catch (error62) {
39840
- throw new AcpExecutionError(
39841
- "Elicitation response is not valid JSON",
39842
- { cause: error62 },
39843
- "invalid_elicitation_response"
39844
- );
39845
- }
39846
- if (!isRecord9(decoded) || !isRecord9(requestedSchema) || !isRecord9(requestedSchema["properties"])) {
39847
- throw new AcpExecutionError(
39848
- "Elicitation response does not match the requested form",
39849
- {},
39850
- "invalid_elicitation_response"
39851
- );
39852
- }
39853
- const properties = requestedSchema["properties"];
39854
- const requiredValue = requestedSchema["required"];
39855
- const required2 = new Set(
39856
- Array.isArray(requiredValue) ? requiredValue.filter((entry) => typeof entry === "string") : []
39857
- );
39858
- for (const name of required2) {
39859
- if (!(name in decoded)) {
39860
- throw new AcpExecutionError(`Elicitation field ${name} is required`, {}, "invalid_elicitation_response");
39861
- }
39862
- }
39863
- const validated = {};
39864
- for (const [name, value] of Object.entries(decoded)) {
39865
- const property = properties[name];
39866
- if (!isRecord9(property)) {
39867
- throw new AcpExecutionError(
39868
- `Elicitation field ${name} was not requested`,
39869
- {},
39870
- "invalid_elicitation_response"
39871
- );
39872
- }
39873
- if (property["type"] === "string" && typeof value === "string") {
39874
- validateStringValue(name, value, property);
39875
- validated[name] = value;
39876
- continue;
39877
- }
39878
- if (property["type"] === "number" && typeof value === "number") {
39879
- validateNumericValue(name, value, property, false);
39880
- validated[name] = value;
39881
- continue;
39882
- }
39883
- if (property["type"] === "integer" && typeof value === "number") {
39884
- validateNumericValue(name, value, property, true);
39885
- validated[name] = value;
39886
- continue;
39887
- }
39888
- if (property["type"] === "boolean" && typeof value === "boolean") {
39889
- validated[name] = value;
39890
- continue;
39891
- }
39892
- if (property["type"] === "array" && Array.isArray(value) && value.every((entry) => typeof entry === "string")) {
39893
- const minimum = property["minItems"];
39894
- const maximum = property["maxItems"];
39895
- if (typeof minimum === "number" && value.length < minimum || typeof maximum === "number" && value.length > maximum) {
39896
- throw new AcpExecutionError(
39897
- `Elicitation field ${name} has an invalid selection count`,
39898
- {},
39899
- "invalid_elicitation_response"
39900
- );
39901
- }
39902
- const allowed = normalizeElicitationOptions(property);
39903
- if (allowed.length > 0 && value.some((entry) => !allowed.some((option) => option.value === entry))) {
39904
- throw new AcpExecutionError(
39905
- `Elicitation field ${name} contains an invalid selection`,
39906
- {},
39907
- "invalid_elicitation_response"
39908
- );
39909
- }
39910
- validated[name] = value;
39911
- continue;
39912
- }
39913
- throw new AcpExecutionError(`Elicitation field ${name} has the wrong type`, {}, "invalid_elicitation_response");
39914
- }
39915
- return validated;
39916
- }
39917
39986
  var AcpTurnState = class {
39918
39987
  };
39919
39988
  var IdleAcpTurn = class extends AcpTurnState {
@@ -40380,8 +40449,8 @@ var AcpProcessSession = class _AcpProcessSession {
40380
40449
  );
40381
40450
  }
40382
40451
  this.#capabilities = normalizeAcpCapabilities(initialized);
40383
- this.#agentName = truncate4(initialized.agentInfo?.title ?? initialized.agentInfo?.name ?? this.#agentId, 255);
40384
- this.#agentVersion = truncate4(
40452
+ this.#agentName = truncate3(initialized.agentInfo?.title ?? initialized.agentInfo?.name ?? this.#agentId, 255);
40453
+ this.#agentVersion = truncate3(
40385
40454
  this.#verifiedAgentVersion.length > 0 ? this.#verifiedAgentVersion : initialized.agentInfo?.version ?? "",
40386
40455
  128
40387
40456
  );
@@ -40613,6 +40682,17 @@ var AcpProcessSession = class _AcpProcessSession {
40613
40682
  );
40614
40683
  };
40615
40684
  nativeSessionId = () => this.#nativeSessionId;
40685
+ adoptNativeSessionId = (sessionId) => {
40686
+ if (this.#prompted || this.#nativeSessionId !== sessionId) {
40687
+ throw new AcpExecutionError("The new native Session cannot be adopted", {}, "session_identity_mismatch");
40688
+ }
40689
+ const previousSessionId = this.#mobiusSessionId;
40690
+ this.#store.write(
40691
+ new AcpStoredSession(sessionId, this.#agentId, sessionId, this.#cwd, this.#additionalDirectories, false)
40692
+ );
40693
+ this.#store.remove(previousSessionId);
40694
+ this.#mobiusSessionId = sessionId;
40695
+ };
40616
40696
  configure = async (options) => {
40617
40697
  const existing = this.#configOptions.find((option) => option.id === options.configId);
40618
40698
  if (existing === void 0 || existing.type !== options.valueType) {
@@ -40817,7 +40897,7 @@ var AcpProcessSession = class _AcpProcessSession {
40817
40897
  "ACP agent exited during steering",
40818
40898
  options.signal
40819
40899
  );
40820
- if (!isRecord9(response)) {
40900
+ if (!isRecord8(response)) {
40821
40901
  throw new AcpExecutionError(
40822
40902
  "ACP agent returned an invalid steering response",
40823
40903
  {},
@@ -40934,8 +41014,8 @@ var AcpProcessSession = class _AcpProcessSession {
40934
41014
  const interactionId = `permission-${crypto.randomUUID()}`;
40935
41015
  const options = request.options.slice(0, 20).map((option) => ({
40936
41016
  kind: option.kind,
40937
- name: truncate4(option.name, 255),
40938
- optionId: truncate4(option.optionId, 255)
41017
+ name: truncate3(option.name, 255),
41018
+ optionId: truncate3(option.optionId, 255)
40939
41019
  }));
40940
41020
  if (options.length === 0) {
40941
41021
  throw new AcpExecutionError(
@@ -40957,9 +41037,9 @@ var AcpProcessSession = class _AcpProcessSession {
40957
41037
  kind: SESSION_PERMISSION_REQUESTED_KIND,
40958
41038
  options,
40959
41039
  sessionId: this.#mobiusSessionId,
40960
- title: truncate4(request.toolCall.title ?? "Permission required", 500),
40961
- toolCallId: truncate4(request.toolCall.toolCallId, 255),
40962
- toolKind: truncate4(request.toolCall.kind ?? "other", 64)
41040
+ title: truncate3(request.toolCall.title ?? "Permission required", 500),
41041
+ toolCallId: truncate3(request.toolCall.toolCallId, 255),
41042
+ toolKind: truncate3(request.toolCall.kind ?? "other", 64)
40963
41043
  });
40964
41044
  return await pending.completion.promise;
40965
41045
  } finally {
@@ -40988,7 +41068,7 @@ var AcpProcessSession = class _AcpProcessSession {
40988
41068
  const schemaValue = Reflect.get(request, "requestedSchema");
40989
41069
  const requestedSchema = request.mode === "form" ? schemaValue : {};
40990
41070
  const elicitationIdValue = Reflect.get(request, "elicitationId");
40991
- const elicitationId = request.mode === "url" && typeof elicitationIdValue === "string" ? truncate4(elicitationIdValue, 255) : "";
41071
+ const elicitationId = request.mode === "url" && typeof elicitationIdValue === "string" ? truncate3(elicitationIdValue, 255) : "";
40992
41072
  const pending = new PendingElicitation(interactionId, elicitationId, requestedSchema);
40993
41073
  this.#pendingElicitations.set(interactionId, pending);
40994
41074
  const abort = () => {
@@ -41003,10 +41083,10 @@ var AcpProcessSession = class _AcpProcessSession {
41003
41083
  fields: normalizeElicitationFields(requestedSchema),
41004
41084
  interactionId,
41005
41085
  kind: SESSION_ELICITATION_REQUESTED_KIND,
41006
- message: truncate4(request.message, 2e3),
41086
+ message: truncate3(request.message, 2e3),
41007
41087
  mode: request.mode,
41008
41088
  sessionId: this.#mobiusSessionId,
41009
- url: request.mode === "url" && typeof Reflect.get(request, "url") === "string" ? truncate4(readString4(Reflect.get(request, "url")), 4096) : ""
41089
+ url: request.mode === "url" && typeof Reflect.get(request, "url") === "string" ? truncate3(readString2(Reflect.get(request, "url")), 4096) : ""
41010
41090
  });
41011
41091
  return await pending.completion.promise;
41012
41092
  } finally {
@@ -41084,14 +41164,14 @@ var AcpProcessSession = class _AcpProcessSession {
41084
41164
  );
41085
41165
  } else {
41086
41166
  await this.#turn.activities.finishNarrative();
41087
- await this.bufferAgentText(update.content.text, truncate4(update.messageId ?? "", 255));
41167
+ await this.bufferAgentText(update.content.text, truncate3(update.messageId ?? "", 255));
41088
41168
  }
41089
41169
  } else {
41090
41170
  await this.#turn.activities.finishNarrative();
41091
41171
  await this.flushAgentText();
41092
41172
  await this.emitAgentContent(
41093
41173
  normalizeContentBlock(update.content),
41094
- truncate4(update.messageId ?? "", 255)
41174
+ truncate3(update.messageId ?? "", 255)
41095
41175
  );
41096
41176
  }
41097
41177
  return;
@@ -41130,9 +41210,9 @@ var AcpProcessSession = class _AcpProcessSession {
41130
41210
  }
41131
41211
  if (update.sessionUpdate === "available_commands_update") {
41132
41212
  const commands = update.availableCommands.slice(0, 500).map((command) => ({
41133
- description: truncate4(command.description, 500),
41134
- inputHint: truncate4(command.input?.hint ?? "", 255),
41135
- name: truncate4(command.name, 128)
41213
+ description: truncate3(command.description, 500),
41214
+ inputHint: truncate3(command.input?.hint ?? "", 255),
41215
+ name: truncate3(command.name, 128)
41136
41216
  })).filter((command) => command.name.length > 0);
41137
41217
  this.#commands = commands;
41138
41218
  await this.#getObserver().onCommands({
@@ -41161,10 +41241,10 @@ var AcpProcessSession = class _AcpProcessSession {
41161
41241
  }
41162
41242
  if (update.sessionUpdate === "session_info_update") {
41163
41243
  if (Object.hasOwn(update, "title")) {
41164
- this.#sessionTitle = truncate4(update.title ?? "", 500);
41244
+ this.#sessionTitle = truncate3(update.title ?? "", 500);
41165
41245
  }
41166
41246
  if (Object.hasOwn(update, "updatedAt")) {
41167
- this.#sessionUpdatedAt = truncate4(update.updatedAt ?? "", 128);
41247
+ this.#sessionUpdatedAt = truncate3(update.updatedAt ?? "", 128);
41168
41248
  }
41169
41249
  await this.#getObserver().onInfo({
41170
41250
  kind: SESSION_INFO_UPDATED_KIND,
@@ -41177,7 +41257,7 @@ var AcpProcessSession = class _AcpProcessSession {
41177
41257
  if (update.sessionUpdate === "usage_update") {
41178
41258
  await this.#getObserver().onUsage({
41179
41259
  costAmount: update.cost?.amount ?? 0,
41180
- costCurrency: truncate4(update.cost?.currency ?? "", 16),
41260
+ costCurrency: truncate3(update.cost?.currency ?? "", 16),
41181
41261
  hasCost: update.cost !== void 0 && update.cost !== null,
41182
41262
  kind: SESSION_USAGE_UPDATED_KIND,
41183
41263
  sessionId: this.#mobiusSessionId,
@@ -41250,7 +41330,7 @@ var AcpProcessSession = class _AcpProcessSession {
41250
41330
  );
41251
41331
  }
41252
41332
  if (error62 instanceof RequestError3) {
41253
- throw new AcpExecutionError(truncate4(error62.message, 500), { cause: error62 }, "acp_agent_error");
41333
+ throw new AcpExecutionError(truncate3(error62.message, 500), { cause: error62 }, "acp_agent_error");
41254
41334
  }
41255
41335
  throw error62;
41256
41336
  }
@@ -41319,6 +41399,10 @@ var AcpProcessSession = class _AcpProcessSession {
41319
41399
  }
41320
41400
  };
41321
41401
  };
41402
+
41403
+ // src/acp/session-manager.ts
41404
+ var MAX_ACP_PROCESSES = 10;
41405
+ var SESSION_CONTROL_TIMEOUT_MILLISECONDS = 3e4;
41322
41406
  var AcpProcessEvictionCandidate = class {
41323
41407
  };
41324
41408
  var MissingAcpProcessEvictionCandidate = class extends AcpProcessEvictionCandidate {
@@ -41366,16 +41450,17 @@ var AcpSessionManager = class {
41366
41450
  #transientProcessCount = 0;
41367
41451
  #store;
41368
41452
  #nativeHistoryReader;
41453
+ #sessionIdentity;
41369
41454
  #observer;
41370
- constructor(observer = new NullAcpSessionObserver(), store = new MemoryAcpSessionStore(), nativeHistoryReader = null) {
41455
+ constructor(observer = new NullAcpSessionObserver(), store = new MemoryAcpSessionStore(), nativeHistoryReader = null, sessionIdentity = "assigned") {
41371
41456
  this.#observer = observer;
41372
41457
  this.#store = store;
41373
41458
  this.#nativeHistoryReader = nativeHistoryReader;
41459
+ this.#sessionIdentity = sessionIdentity;
41374
41460
  }
41375
41461
  setObserver = (observer) => {
41376
41462
  this.#observer = observer;
41377
41463
  };
41378
- findLinkedSessions = (agentId, nativeSessionId) => this.#store.findNative(agentId, nativeSessionId);
41379
41464
  #notifyProcessCapacityChanged() {
41380
41465
  const changed = this.#processCapacityChanged;
41381
41466
  this.#processCapacityChanged = Promise.withResolvers();
@@ -41483,7 +41568,13 @@ var AcpSessionManager = class {
41483
41568
  if (retained) {
41484
41569
  this.#sessions.delete(sessionId);
41485
41570
  }
41486
- await this.#retireProcess(runtime, retained, close);
41571
+ try {
41572
+ await this.#retireProcess(runtime, retained, close);
41573
+ } finally {
41574
+ if (retained && this.#sessionIdentity === "native") {
41575
+ this.#store.remove(sessionId);
41576
+ }
41577
+ }
41487
41578
  }
41488
41579
  async #retireNativeBrowserProcess(sessionId, runtime, close) {
41489
41580
  const retained = this.#nativeBrowserSessions.get(sessionId) === runtime;
@@ -41630,7 +41721,14 @@ var AcpSessionManager = class {
41630
41721
  try {
41631
41722
  return await this.#startRetainedSessionProcess(
41632
41723
  options,
41633
- async () => await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics)
41724
+ async () => await AcpProcessSession.start(
41725
+ 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(
41726
+ options.sessionId
41727
+ ) && this.#store.read(options.sessionId) instanceof MissingAcpStoredSession ? { ...options, origin: { kind: "import", nativeSessionId: options.sessionId } } : options,
41728
+ () => this.#observer,
41729
+ this.#store,
41730
+ metrics
41731
+ )
41634
41732
  );
41635
41733
  } finally {
41636
41734
  this.#preparing.delete(options.sessionId);
@@ -42053,6 +42151,45 @@ var AcpSessionManager = class {
42053
42151
  ]);
42054
42152
  };
42055
42153
  hasPreparedSession = (sessionId, agentId, cwd, additionalDirectories) => this.#sessions.get(sessionId)?.belongsTo(agentId, cwd, additionalDirectories) === true;
42154
+ createNativeSession = async (options) => {
42155
+ const temporarySessionId = `new-${crypto.randomUUID()}`;
42156
+ const temporaryOptions = { ...options, sessionId: temporarySessionId };
42157
+ this.#beginSessionUse(temporarySessionId);
42158
+ try {
42159
+ const runtime = await this.#startPreparation(temporaryOptions);
42160
+ let adopted = false;
42161
+ try {
42162
+ const nativeSessionId = runtime.nativeSessionId();
42163
+ 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)) {
42164
+ throw new AcpExecutionError(
42165
+ "The Agent returned an invalid new Session ID",
42166
+ {},
42167
+ "invalid_native_session_response"
42168
+ );
42169
+ }
42170
+ runtime.adoptNativeSessionId(nativeSessionId);
42171
+ this.#sessions.delete(temporarySessionId);
42172
+ this.#sessions.set(nativeSessionId, runtime);
42173
+ this.#retainedProcesses.set(
42174
+ runtime,
42175
+ new FoundAcpSessionProcessEvictionCandidate(nativeSessionId, runtime)
42176
+ );
42177
+ adopted = true;
42178
+ return nativeSessionId;
42179
+ } finally {
42180
+ if (!adopted) {
42181
+ await this.#retireSessionProcess(
42182
+ temporarySessionId,
42183
+ runtime,
42184
+ async () => await runtime.closeProcess()
42185
+ );
42186
+ }
42187
+ }
42188
+ } finally {
42189
+ this.#store.remove(temporarySessionId);
42190
+ this.#endSessionUse(temporarySessionId);
42191
+ }
42192
+ };
42056
42193
  ensureSession = async (options) => {
42057
42194
  const existing = this.#sessions.get(options.sessionId);
42058
42195
  if (existing !== void 0) {
@@ -42146,6 +42283,25 @@ var AcpSessionManager = class {
42146
42283
  this.#endSessionUse(options.sessionId);
42147
42284
  }
42148
42285
  };
42286
+ loadLinkedSessionHistory = async (options) => {
42287
+ options.signal.throwIfAborted();
42288
+ const stored = this.#store.read(options.sessionId);
42289
+ if (!(stored instanceof FoundAcpStoredSession) || !stored.session.prompted) {
42290
+ return null;
42291
+ }
42292
+ const linked = stored.session;
42293
+ 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])) {
42294
+ throw new AcpExecutionError(
42295
+ "The session belongs to another Agent or workspace",
42296
+ {},
42297
+ "session_identity_mismatch"
42298
+ );
42299
+ }
42300
+ if (this.#nativeHistoryReader === null) {
42301
+ return await this.loadSessionHistory(options);
42302
+ }
42303
+ return await this.#nativeHistoryReader.read(options, linked.nativeSessionId);
42304
+ };
42149
42305
  openNativeSession = async (options, origin, loadHistory) => {
42150
42306
  const key = `${options.agent.id}:${origin.nativeSessionId}`;
42151
42307
  if (this.#nativeOperations.has(key)) {
@@ -42297,253 +42453,490 @@ var AcpSessionManager = class {
42297
42453
  this.#endSessionUse(options.sessionId);
42298
42454
  }
42299
42455
  };
42300
- deleteNativeSession = async (options, nativeSessionId) => {
42301
- this.#beginNativeBrowserUse(options.sessionId);
42302
- try {
42303
- const runtime = await this.#ensureNativeSessionBrowser(options);
42304
- const key = `${options.agent.id}:${nativeSessionId}`;
42305
- const linked = this.#store.findNative(options.agent.id, nativeSessionId);
42306
- if (this.#nativeOperations.has(key) || linked.some(
42307
- (entry) => this.#activeSessionIds.has(entry.sessionId) || this.#preparing.has(entry.sessionId)
42308
- )) {
42309
- throw new AcpExecutionError(
42310
- "Wait for the native session's running operation to finish",
42311
- {},
42312
- "session_busy"
42313
- );
42314
- }
42315
- this.#nativeOperations.add(key);
42456
+ deleteNativeSession = async (options, nativeSessionId) => {
42457
+ this.#beginNativeBrowserUse(options.sessionId);
42458
+ try {
42459
+ const runtime = await this.#ensureNativeSessionBrowser(options);
42460
+ const key = `${options.agent.id}:${nativeSessionId}`;
42461
+ const linked = this.#store.findNative(options.agent.id, nativeSessionId);
42462
+ if (this.#nativeOperations.has(key) || linked.some(
42463
+ (entry) => this.#activeSessionIds.has(entry.sessionId) || this.#preparing.has(entry.sessionId)
42464
+ )) {
42465
+ throw new AcpExecutionError(
42466
+ "Wait for the native session's running operation to finish",
42467
+ {},
42468
+ "session_busy"
42469
+ );
42470
+ }
42471
+ this.#nativeOperations.add(key);
42472
+ try {
42473
+ for (const entry of linked) {
42474
+ const active = this.#sessions.get(entry.sessionId);
42475
+ if (active !== void 0 && active !== runtime) {
42476
+ await this.#retireSessionProcess(entry.sessionId, active, async () => await active.close());
42477
+ }
42478
+ }
42479
+ options.signal.throwIfAborted();
42480
+ await runtime.deleteNativeSession(nativeSessionId, options.signal);
42481
+ const deleted = this.#store.markDeleted(options.agent.id, nativeSessionId);
42482
+ if (runtime.nativeSessionId() === nativeSessionId) {
42483
+ await this.#retireNativeBrowserProcess(
42484
+ options.sessionId,
42485
+ runtime,
42486
+ async () => await runtime.close()
42487
+ );
42488
+ }
42489
+ return deleted;
42490
+ } finally {
42491
+ this.#nativeOperations.delete(key);
42492
+ this.#notifyProcessCapacityChanged();
42493
+ }
42494
+ } finally {
42495
+ this.#endNativeBrowserUse(options.sessionId);
42496
+ }
42497
+ };
42498
+ };
42499
+
42500
+ // src/acp/session-config/apply-session-configuration.ts
42501
+ function invalidSessionConfiguration(message) {
42502
+ return new AcpExecutionError(message, {}, "invalid_session_configuration");
42503
+ }
42504
+ function agentForSessionConfiguration(agent, selections) {
42505
+ try {
42506
+ return applyAgentLaunchSettings(agent, selections);
42507
+ } catch (error62) {
42508
+ if (error62 instanceof Error) {
42509
+ throw invalidSessionConfiguration(error62.message);
42510
+ }
42511
+ throw error62;
42512
+ }
42513
+ }
42514
+ function validateSessionConfigurationSelection(option, selection) {
42515
+ if (option.type !== selection.valueType) {
42516
+ throw invalidSessionConfiguration(`The Agent setting ${selection.configId} changed type`);
42517
+ }
42518
+ if (option.type === "boolean") {
42519
+ if (selection.value.length > 0) {
42520
+ throw invalidSessionConfiguration(`The Agent setting ${selection.configId} has an invalid value`);
42521
+ }
42522
+ return;
42523
+ }
42524
+ if (selection.booleanValue) {
42525
+ throw invalidSessionConfiguration(`The Agent setting ${selection.configId} has an invalid value`);
42526
+ }
42527
+ if (!option.values.some((value) => value.value === selection.value)) {
42528
+ throw invalidSessionConfiguration(`The Agent setting ${selection.configId} has an unavailable value`);
42529
+ }
42530
+ }
42531
+ function sessionConfigurationSelectionIsAvailable(option, selection) {
42532
+ if (option.type !== selection.valueType) {
42533
+ return false;
42534
+ }
42535
+ if (option.type === "boolean") {
42536
+ return selection.value.length === 0;
42537
+ }
42538
+ return !selection.booleanValue && option.values.some((value) => value.value === selection.value);
42539
+ }
42540
+ function sessionConfigurationMatches(option, selection) {
42541
+ validateSessionConfigurationSelection(option, selection);
42542
+ return option.type === "boolean" ? option.booleanValue === selection.booleanValue : option.currentValue === selection.value;
42543
+ }
42544
+ function sessionConfigurationPriority(selection, options) {
42545
+ const option = options.find((candidate) => candidate.id === selection.configId);
42546
+ if (selection.configId === "model" || option?.category === "model") {
42547
+ return 0;
42548
+ }
42549
+ if (selection.configId === "reasoning_effort" || option?.category === "thought_level") {
42550
+ return 1;
42551
+ }
42552
+ if (option?.category === "model_config") {
42553
+ return 2;
42554
+ }
42555
+ return 3;
42556
+ }
42557
+ function assertAppliedSessionConfiguration(options, selections) {
42558
+ const selectionsById = new Map(selections.map((selection) => [selection.configId, selection]));
42559
+ for (const option of options) {
42560
+ const selection = selectionsById.get(option.id);
42561
+ if (selection === void 0 || !sessionConfigurationSelectionIsAvailable(option, selection)) {
42562
+ continue;
42563
+ }
42564
+ if (!sessionConfigurationMatches(option, selection)) {
42565
+ throw invalidSessionConfiguration(`The Turn configuration does not match Agent setting ${option.id}`);
42566
+ }
42567
+ }
42568
+ }
42569
+ function unavailableSessionConfigurationCategory(selection) {
42570
+ if (selection.configId === "model") {
42571
+ return "model";
42572
+ }
42573
+ if (selection.configId === "reasoning_effort") {
42574
+ return "thought_level";
42575
+ }
42576
+ return "unknown";
42577
+ }
42578
+ async function applySessionConfigurationSelection(sessions, audit, options, selection, agent, cwd, additionalDirectories, commandId, sessionId, signal) {
42579
+ const option = options.find((candidate) => candidate.id === selection.configId);
42580
+ if (option === void 0) {
42581
+ warnIgnoredSetting(
42582
+ audit,
42583
+ "session_configuration_setting_ignored",
42584
+ commandId,
42585
+ sessionId,
42586
+ agent.id,
42587
+ selection,
42588
+ unavailableSessionConfigurationCategory(selection),
42589
+ "setting_unavailable"
42590
+ );
42591
+ return options;
42592
+ }
42593
+ if (option.type !== selection.valueType) {
42594
+ warnIgnoredSetting(
42595
+ audit,
42596
+ "session_configuration_setting_ignored",
42597
+ commandId,
42598
+ sessionId,
42599
+ agent.id,
42600
+ selection,
42601
+ option.category,
42602
+ "setting_schema_mismatch"
42603
+ );
42604
+ return options;
42605
+ }
42606
+ if (option.type === "boolean" && selection.value.length > 0 || option.type === "select" && selection.booleanValue) {
42607
+ warnIgnoredSetting(
42608
+ audit,
42609
+ "session_configuration_setting_ignored",
42610
+ commandId,
42611
+ sessionId,
42612
+ agent.id,
42613
+ selection,
42614
+ option.category,
42615
+ "selection_schema_mismatch"
42616
+ );
42617
+ return options;
42618
+ }
42619
+ if (option.type === "select" && !option.values.some((value) => value.value === selection.value)) {
42620
+ warnIgnoredSetting(
42621
+ audit,
42622
+ "session_configuration_setting_ignored",
42623
+ commandId,
42624
+ sessionId,
42625
+ agent.id,
42626
+ selection,
42627
+ option.category,
42628
+ "value_unavailable"
42629
+ );
42630
+ return options;
42631
+ }
42632
+ if (sessionConfigurationMatches(option, selection)) {
42633
+ return options;
42634
+ }
42635
+ return await sessions.configureSession({
42636
+ additionalDirectories,
42637
+ agent,
42638
+ booleanValue: selection.booleanValue,
42639
+ configId: selection.configId,
42640
+ cwd,
42641
+ requestId: `cfg_${randomUUID2()}`,
42642
+ sessionId,
42643
+ signal,
42644
+ value: selection.value,
42645
+ valueType: selection.valueType
42646
+ });
42647
+ }
42648
+ async function applyCompleteSessionConfiguration(sessions, audit, initialOptions, selections, agent, cwd, additionalDirectories, commandId, sessionId, signal) {
42649
+ let options = initialOptions;
42650
+ const orderedSelections = selections.toSorted((left, right) => {
42651
+ const priority = sessionConfigurationPriority(left, initialOptions) - sessionConfigurationPriority(right, initialOptions);
42652
+ return priority === 0 ? left.configId.localeCompare(right.configId) : priority;
42653
+ });
42654
+ for (const selection of orderedSelections) {
42655
+ options = await applySessionConfigurationSelection(
42656
+ sessions,
42657
+ audit,
42658
+ options,
42659
+ selection,
42660
+ agent,
42661
+ cwd,
42662
+ additionalDirectories,
42663
+ commandId,
42664
+ sessionId,
42665
+ signal
42666
+ );
42667
+ }
42668
+ assertAppliedSessionConfiguration(options, selections);
42669
+ }
42670
+ function warnIgnoredSetting(audit, event, commandId, sessionId, agentId, selection, category, reason) {
42671
+ const details = {
42672
+ agentId,
42673
+ category,
42674
+ configId: selection.configId,
42675
+ reason,
42676
+ requestedValue: selection.value
42677
+ };
42678
+ audit.record({ commandId, details, event, sessionId });
42679
+ process.stderr.write(`Mobius daemon warning ${JSON.stringify({ commandId, event, sessionId, ...details })}
42680
+ `);
42681
+ }
42682
+
42683
+ // src/agent-catalog/discover-agent-settings.ts
42684
+ import { createHash as createHash3 } from "node:crypto";
42685
+ function isUnavailableModel(cause, modelSettingId, requestedModel) {
42686
+ return cause instanceof AcpConfigurationValueUnavailableError && cause.configId === modelSettingId && cause.requestedValue === requestedModel;
42687
+ }
42688
+ function unsupportedModelIds(unsupportedModels) {
42689
+ return [...new Set(unsupportedModels.map((item) => item.requestedValue))];
42690
+ }
42691
+ async function discoverAgentSettings(command, config2, directories, sessions, signal) {
42692
+ const agent = config2.catalog.find(command.agentId);
42693
+ const cwd = await directories.resolve(config2.bindingId, "default", signal);
42694
+ const inspectedBaseSnapshot = await sessions.inspectAgentSettings({
42695
+ additionalDirectories: [],
42696
+ agent,
42697
+ cwd,
42698
+ signal
42699
+ });
42700
+ const baseSnapshot = {
42701
+ agentName: inspectedBaseSnapshot.agentName,
42702
+ agentVersion: inspectedBaseSnapshot.agentVersion,
42703
+ configOptions: await discoverOpenCodeModelOptions(agent, cwd, inspectedBaseSnapshot.configOptions, signal)
42704
+ };
42705
+ const baseModel = modelOption(baseSnapshot.configOptions);
42706
+ const unsupportedModels = [];
42707
+ let selectedSnapshot = baseSnapshot;
42708
+ if (command.model !== void 0) {
42709
+ if (baseModel === void 0 || baseModel.type !== "select" || !baseModel.values.some((value) => value.value === command.model)) {
42710
+ unsupportedModels.push(
42711
+ new AcpConfigurationValueUnavailableError(
42712
+ baseModel?.id ?? "model",
42713
+ command.model,
42714
+ baseModel?.values.map((value) => value.value) ?? []
42715
+ )
42716
+ );
42717
+ } else {
42316
42718
  try {
42317
- for (const entry of linked) {
42318
- const active = this.#sessions.get(entry.sessionId);
42319
- if (active !== void 0 && active !== runtime) {
42320
- await this.#retireSessionProcess(entry.sessionId, active, async () => await active.close());
42321
- }
42322
- }
42323
- options.signal.throwIfAborted();
42324
- await runtime.deleteNativeSession(nativeSessionId, options.signal);
42325
- const deleted = this.#store.markDeleted(options.agent.id, nativeSessionId);
42326
- if (runtime.nativeSessionId() === nativeSessionId) {
42327
- await this.#retireNativeBrowserProcess(
42328
- options.sessionId,
42329
- runtime,
42330
- async () => await runtime.close()
42331
- );
42719
+ selectedSnapshot = await sessions.inspectAgentSettings({
42720
+ additionalDirectories: [],
42721
+ agent,
42722
+ cwd,
42723
+ model: command.model,
42724
+ signal
42725
+ });
42726
+ } catch (cause) {
42727
+ signal.throwIfAborted();
42728
+ if (!isUnavailableModel(cause, baseModel.id, command.model)) {
42729
+ throw cause;
42332
42730
  }
42333
- return deleted;
42334
- } finally {
42335
- this.#nativeOperations.delete(key);
42336
- this.#notifyProcessCapacityChanged();
42731
+ unsupportedModels.push(cause);
42337
42732
  }
42338
- } finally {
42339
- this.#endNativeBrowserUse(options.sessionId);
42340
42733
  }
42341
- };
42342
- };
42343
-
42344
- // src/agent-catalog/agent-settings-adapter.ts
42345
- var AGENT_DEFAULT_VALUE = "agent_default";
42346
- var READ_ONLY_VALUE = "read-only";
42347
- var WORKSPACE_WRITE_VALUE = "workspace-write";
42348
- var DANGER_FULL_ACCESS_VALUE = "danger-full-access";
42349
- var DEEPSEEK_HARNESS_ACCESS_MODE_SETTING_ID = "dsh_access_mode";
42350
- var OPENCODE_PERMISSION_SETTING_ID = "opencode_permission";
42351
- var AgentSettingsConfigurationError = class extends Error {
42352
- code = "invalid_session_configuration";
42353
- constructor(message, options = {}) {
42354
- super(message, options);
42355
- this.name = "AgentSettingsConfigurationError";
42356
- }
42357
- };
42358
- var AgentSettingsLaunchSelectionResult = class {
42359
- agent;
42360
- handled;
42361
- constructor(agent, handled) {
42362
- this.agent = agent;
42363
- this.handled = handled;
42364
- }
42365
- };
42366
- var AppliedAgentLaunchSettings = class {
42367
- agent;
42368
- sessionConfigurations;
42369
- constructor(agent, sessionConfigurations) {
42370
- this.agent = agent;
42371
- this.sessionConfigurations = Object.freeze([...sessionConfigurations]);
42372
42734
  }
42373
- };
42374
- var AgentSettingsAdapter = class {
42375
- modelEffortResolution = AGENT_MODEL_EFFORT_RESOLUTION_ON_MODEL_SELECTION;
42376
- applyLaunchSelection = (agent, _selection) => new AgentSettingsLaunchSelectionResult(agent, false);
42377
- settings = (_agent) => [];
42378
- };
42379
- function selectValue(name, value, description) {
42735
+ const adapter = agentSettingsAdapterForAgent(agent.id);
42736
+ const modelEffort = await discoverModelEffort(
42737
+ command,
42738
+ agent,
42739
+ adapter.modelEffortResolution,
42740
+ baseSnapshot.configOptions,
42741
+ selectedSnapshot.configOptions,
42742
+ unsupportedModels,
42743
+ cwd,
42744
+ sessions,
42745
+ signal
42746
+ );
42747
+ const baseSettings = withoutUnsupportedModels(
42748
+ settingsFromSnapshot(agent, baseSnapshot.configOptions),
42749
+ baseModel?.id ?? "",
42750
+ modelEffort.unsupportedModelIds
42751
+ );
42752
+ const settings = withoutUnsupportedModels(
42753
+ settingsFromSnapshot(agent, selectedSnapshot.configOptions),
42754
+ baseModel?.id ?? "",
42755
+ modelEffort.unsupportedModelIds
42756
+ );
42380
42757
  return {
42381
- description,
42382
- groupId: "",
42383
- groupName: "",
42384
- name,
42385
- value
42758
+ event: {
42759
+ agentId: command.agentId,
42760
+ agentName: selectedSnapshot.agentName,
42761
+ agentVersion: selectedSnapshot.agentVersion,
42762
+ kind: AGENT_SETTINGS_DISCOVERED_KIND,
42763
+ modelEffort,
42764
+ requestId: command.requestId,
42765
+ settings,
42766
+ settingsRevision: settingsRevision(agent, baseSnapshot.agentVersion, baseSettings, modelEffort)
42767
+ },
42768
+ unsupportedModels
42386
42769
  };
42387
42770
  }
42388
- function selectSetting(id, name, description, currentValue, values) {
42771
+ function settingFromOption(option) {
42389
42772
  return {
42390
- booleanValue: false,
42391
- category: "execution",
42392
- currentValue,
42393
- description,
42394
- id,
42395
- name,
42396
- type: "select",
42397
- values
42773
+ booleanValue: option.booleanValue,
42774
+ category: option.category,
42775
+ defaultValue: option.type === "boolean" ? "" : option.currentValue,
42776
+ description: option.description,
42777
+ id: option.id,
42778
+ name: option.name,
42779
+ type: option.type,
42780
+ values: option.values
42398
42781
  };
42399
42782
  }
42400
- function selectedValue(selection, configId) {
42401
- if (selection.configId !== configId || selection.valueType !== "select" || selection.booleanValue || selection.value.length === 0) {
42402
- throw new AgentSettingsConfigurationError("The requested Agent setting is invalid");
42783
+ function settingsFromSnapshot(agent, configOptions) {
42784
+ const settings = [
42785
+ ...agentSettingsAdapterForAgent(agent.id).settings(agent).map(settingFromOption),
42786
+ ...configOptions.map(settingFromOption)
42787
+ ];
42788
+ const identifiers = /* @__PURE__ */ new Set();
42789
+ for (const setting of settings) {
42790
+ if (identifiers.has(setting.id)) {
42791
+ throw new AcpExecutionError(
42792
+ "The Agent returned duplicate setting identifiers",
42793
+ {},
42794
+ "invalid_session_configuration"
42795
+ );
42796
+ }
42797
+ identifiers.add(setting.id);
42403
42798
  }
42404
- return selection.value;
42405
- }
42406
- function validValue(values, value) {
42407
- if (!values.some((candidate) => candidate.value === value)) {
42408
- throw new AgentSettingsConfigurationError("The requested Agent setting is unavailable");
42799
+ if (settings.length > 128) {
42800
+ throw new AcpExecutionError("The Agent returned too many settings", {}, "invalid_session_configuration");
42409
42801
  }
42410
- return value;
42802
+ return settings;
42411
42803
  }
42412
- var dshAccessModes = Object.freeze([
42413
- selectValue("Read only", READ_ONLY_VALUE, "Allow inspection without local writes."),
42414
- selectValue("Workspace write", WORKSPACE_WRITE_VALUE, "Allow changes in the selected workspace."),
42415
- selectValue("Full access", DANGER_FULL_ACCESS_VALUE, "Allow unrestricted local execution.")
42416
- ]);
42417
- var DeepSeekHarnessSettingsAdapter = class extends AgentSettingsAdapter {
42418
- settings = (agent) => {
42419
- const configured = agent.environment["DSH_PERMISSION_MODE"] ?? WORKSPACE_WRITE_VALUE;
42420
- return [
42421
- selectSetting(
42422
- DEEPSEEK_HARNESS_ACCESS_MODE_SETTING_ID,
42423
- "Access mode",
42424
- "Controls the local side effects allowed for this DeepSeek Harness session.",
42425
- validValue(dshAccessModes, configured),
42426
- dshAccessModes
42427
- )
42428
- ];
42429
- };
42430
- applyLaunchSelection = (agent, selection) => {
42431
- if (selection.configId !== DEEPSEEK_HARNESS_ACCESS_MODE_SETTING_ID) {
42432
- return new AgentSettingsLaunchSelectionResult(agent, false);
42804
+ function withoutUnsupportedModels(settings, modelSettingId, unsupportedModelIds2) {
42805
+ if (modelSettingId.length === 0 || unsupportedModelIds2.length === 0) {
42806
+ return settings;
42807
+ }
42808
+ const unsupported = new Set(unsupportedModelIds2);
42809
+ return settings.map((setting) => {
42810
+ if (setting.id !== modelSettingId || setting.type !== "select") {
42811
+ return setting;
42433
42812
  }
42434
- const value = validValue(dshAccessModes, selectedValue(selection, DEEPSEEK_HARNESS_ACCESS_MODE_SETTING_ID));
42435
- return new AgentSettingsLaunchSelectionResult(
42436
- agent.withEnvironment({ ...agent.environment, DSH_PERMISSION_MODE: value }),
42437
- true
42438
- );
42813
+ return {
42814
+ ...setting,
42815
+ defaultValue: unsupported.has(setting.defaultValue) ? "" : setting.defaultValue,
42816
+ values: setting.values.filter((value) => !unsupported.has(value.value))
42817
+ };
42818
+ });
42819
+ }
42820
+ function modelOption(options) {
42821
+ return options.find((option) => option.id === "model" || option.category === "model");
42822
+ }
42823
+ function effortOption(options) {
42824
+ return options.find((option) => option.id === "reasoning_effort" || option.category === "thought_level");
42825
+ }
42826
+ function unavailableModelEffort() {
42827
+ return {
42828
+ effortSettingId: "",
42829
+ modelSettingId: "",
42830
+ resolution: AGENT_MODEL_EFFORT_RESOLUTION_UNAVAILABLE,
42831
+ unsupportedModelIds: [],
42832
+ valuesByModel: {}
42439
42833
  };
42440
- };
42441
- var openCodePermissionModes = Object.freeze([
42442
- selectValue("Agent default", AGENT_DEFAULT_VALUE, "Keep OpenCode's existing permission policy."),
42443
- selectValue("Read only", READ_ONLY_VALUE, "Allow inspection without local writes."),
42444
- selectValue("Workspace write", WORKSPACE_WRITE_VALUE, "Allow changes in the selected workspace."),
42445
- selectValue("Full access", DANGER_FULL_ACCESS_VALUE, "Allow unrestricted local execution.")
42446
- ]);
42447
- function openCodeConfiguration(environment) {
42448
- const encoded = environment["OPENCODE_CONFIG_CONTENT"];
42449
- if (encoded === void 0 || encoded.length === 0) {
42450
- return {};
42451
- }
42452
- let parsed;
42453
- try {
42454
- parsed = JSON.parse(encoded);
42455
- } catch (cause) {
42456
- throw new AgentSettingsConfigurationError("The OpenCode configuration is invalid", { cause });
42834
+ }
42835
+ async function discoverModelEffort(command, agent, resolution, initialOptions, selectedOptions, initiallyUnsupportedModels, cwd, sessions, signal) {
42836
+ const model = modelOption(initialOptions);
42837
+ const unsupportedModels = initiallyUnsupportedModels;
42838
+ if (resolution !== AGENT_MODEL_EFFORT_RESOLUTION_COMPLETE && resolution !== AGENT_MODEL_EFFORT_RESOLUTION_ON_MODEL_SELECTION) {
42839
+ return { ...unavailableModelEffort(), unsupportedModelIds: unsupportedModelIds(unsupportedModels) };
42457
42840
  }
42458
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
42459
- throw new AgentSettingsConfigurationError("The OpenCode configuration is invalid");
42841
+ if (model === void 0 || model.type !== "select" || model.values.length === 0) {
42842
+ return { ...unavailableModelEffort(), unsupportedModelIds: unsupportedModelIds(unsupportedModels) };
42460
42843
  }
42461
- return Object.freeze({ ...parsed });
42462
- }
42463
- function openCodePermission(value) {
42464
- if (value === READ_ONLY_VALUE) {
42844
+ const inspectModel = async (modelValue) => (await sessions.inspectAgentSettings({
42845
+ additionalDirectories: [],
42846
+ agent,
42847
+ cwd,
42848
+ model: modelValue,
42849
+ signal
42850
+ })).configOptions;
42851
+ const valuesByModel = {};
42852
+ if (resolution === "complete") {
42853
+ const effort = effortOption(initialOptions);
42854
+ if (effort === void 0 || effort.type !== "select" || effort.values.length < 2) {
42855
+ return {
42856
+ ...unavailableModelEffort(),
42857
+ unsupportedModelIds: unsupportedModelIds(unsupportedModels)
42858
+ };
42859
+ }
42860
+ for (const value of model.values) {
42861
+ if (unsupportedModels.some((diagnostic) => diagnostic.requestedValue === value.value)) {
42862
+ continue;
42863
+ }
42864
+ try {
42865
+ const selectedEffort2 = effortOption(await inspectModel(value.value));
42866
+ valuesByModel[value.value] = selectedEffort2?.type === "select" ? selectedEffort2.values : [];
42867
+ } catch (cause) {
42868
+ signal.throwIfAborted();
42869
+ if (!isUnavailableModel(cause, model.id, value.value)) {
42870
+ throw cause;
42871
+ }
42872
+ unsupportedModels.push(cause);
42873
+ }
42874
+ }
42465
42875
  return {
42466
- "*": "deny",
42467
- glob: "allow",
42468
- grep: "allow",
42469
- lsp: "allow",
42470
- read: "allow",
42471
- skill: "allow"
42876
+ effortSettingId: effort.id,
42877
+ modelSettingId: model.id,
42878
+ resolution: "complete",
42879
+ unsupportedModelIds: unsupportedModelIds(unsupportedModels),
42880
+ valuesByModel
42472
42881
  };
42473
42882
  }
42474
- if (value === WORKSPACE_WRITE_VALUE) {
42883
+ if (command.model !== void 0) {
42884
+ const modelUnsupported = unsupportedModels.some((diagnostic) => diagnostic.requestedValue === command.model);
42885
+ const selectedEffort2 = effortOption(selectedOptions);
42886
+ if (!modelUnsupported) {
42887
+ valuesByModel[command.model] = selectedEffort2?.type === "select" ? selectedEffort2.values : [];
42888
+ }
42475
42889
  return {
42476
- "*": "allow",
42477
- external_directory: "ask"
42890
+ effortSettingId: selectedEffort2?.id ?? "",
42891
+ modelSettingId: model.id,
42892
+ resolution: "on_model_selection",
42893
+ unsupportedModelIds: unsupportedModelIds(unsupportedModels),
42894
+ valuesByModel
42478
42895
  };
42479
42896
  }
42480
- return "allow";
42481
- }
42482
- var OpenCodeSettingsAdapter = class extends AgentSettingsAdapter {
42483
- settings = (agent) => {
42484
- const currentValue = agent.environment["MOBIUS_OPENCODE_PERMISSION"] ?? AGENT_DEFAULT_VALUE;
42485
- return [
42486
- selectSetting(
42487
- OPENCODE_PERMISSION_SETTING_ID,
42488
- "Permissions",
42489
- "Controls OpenCode's local permission policy.",
42490
- validValue(openCodePermissionModes, currentValue),
42491
- openCodePermissionModes
42492
- )
42493
- ];
42494
- };
42495
- applyLaunchSelection = (agent, selection) => {
42496
- if (selection.configId !== OPENCODE_PERMISSION_SETTING_ID) {
42497
- return new AgentSettingsLaunchSelectionResult(agent, false);
42498
- }
42499
- const value = validValue(openCodePermissionModes, selectedValue(selection, OPENCODE_PERMISSION_SETTING_ID));
42500
- if (value === AGENT_DEFAULT_VALUE) {
42501
- return new AgentSettingsLaunchSelectionResult(agent, true);
42897
+ const defaultModel = model.type === "select" ? model.currentValue : "";
42898
+ const reportedEffort = effortOption(selectedOptions);
42899
+ let selectedEffort = reportedEffort;
42900
+ if (defaultModel.length > 0 && reportedEffort === void 0) {
42901
+ try {
42902
+ selectedEffort = effortOption(await inspectModel(defaultModel));
42903
+ } catch (cause) {
42904
+ signal.throwIfAborted();
42905
+ if (!isUnavailableModel(cause, model.id, defaultModel)) {
42906
+ throw cause;
42907
+ }
42908
+ unsupportedModels.push(cause);
42502
42909
  }
42503
- return new AgentSettingsLaunchSelectionResult(
42504
- agent.withEnvironment({
42505
- ...agent.environment,
42506
- MOBIUS_OPENCODE_PERMISSION: value,
42507
- OPENCODE_CONFIG_CONTENT: JSON.stringify({
42508
- ...openCodeConfiguration(agent.environment),
42509
- permission: openCodePermission(value)
42510
- })
42511
- }),
42512
- true
42513
- );
42514
- };
42515
- };
42516
- var CodexSettingsAdapter = class extends AgentSettingsAdapter {
42517
- modelEffortResolution = AGENT_MODEL_EFFORT_RESOLUTION_COMPLETE;
42518
- };
42519
- var genericAdapter = new AgentSettingsAdapter();
42520
- var codexAdapter = new CodexSettingsAdapter();
42521
- var deepSeekHarnessAdapter = new DeepSeekHarnessSettingsAdapter();
42522
- var openCodeAdapter = new OpenCodeSettingsAdapter();
42523
- function agentSettingsAdapterForAgent(agentId) {
42524
- if (agentId === "codex") {
42525
- return codexAdapter;
42526
- }
42527
- if (agentId === "deepseek-harness") {
42528
- return deepSeekHarnessAdapter;
42529
42910
  }
42530
- if (agentId === "opencode") {
42531
- return openCodeAdapter;
42911
+ if (defaultModel.length > 0 && !unsupportedModels.some((diagnostic) => diagnostic.requestedValue === defaultModel)) {
42912
+ valuesByModel[defaultModel] = selectedEffort?.type === "select" ? selectedEffort.values : [];
42532
42913
  }
42533
- return genericAdapter;
42914
+ return {
42915
+ effortSettingId: selectedEffort?.id ?? "",
42916
+ modelSettingId: model.id,
42917
+ resolution: "on_model_selection",
42918
+ unsupportedModelIds: unsupportedModelIds(unsupportedModels),
42919
+ valuesByModel
42920
+ };
42534
42921
  }
42535
- function applyAgentLaunchSettings(agent, selections) {
42536
- const adapter = agentSettingsAdapterForAgent(agent.id);
42537
- let selectedAgent = agent;
42538
- const sessionConfigurations = [];
42539
- for (const selection of selections) {
42540
- const applied = adapter.applyLaunchSelection(selectedAgent, selection);
42541
- selectedAgent = applied.agent;
42542
- if (!applied.handled) {
42543
- sessionConfigurations.push(selection);
42544
- }
42545
- }
42546
- return new AppliedAgentLaunchSettings(selectedAgent, sessionConfigurations);
42922
+ function settingsRevision(agent, reportedAgentVersion, settings, modelEffort) {
42923
+ const revisionModelEffort = modelEffort.resolution === AGENT_MODEL_EFFORT_RESOLUTION_COMPLETE ? modelEffort : {
42924
+ effortSettingId: "",
42925
+ modelSettingId: modelEffort.modelSettingId,
42926
+ resolution: modelEffort.resolution,
42927
+ unsupportedModelIds: modelEffort.unsupportedModelIds,
42928
+ valuesByModel: {}
42929
+ };
42930
+ return createHash3("sha256").update(
42931
+ JSON.stringify({
42932
+ adapterVersion: agent.kind === "acp-adapter-process" ? agent.adapterVersion : agent.agentVersion,
42933
+ agentId: agent.id,
42934
+ agentVersion: agent.agentVersion,
42935
+ modelEffort: revisionModelEffort,
42936
+ reportedAgentVersion,
42937
+ settings
42938
+ })
42939
+ ).digest("hex");
42547
42940
  }
42548
42941
 
42549
42942
  // src/agent-catalog/publish-agent-catalog.ts
@@ -43209,7 +43602,7 @@ var LocalAuthorizationError = class extends Error {
43209
43602
  // src/authorization/workspace-directory.ts
43210
43603
  import { readdir as readdir3, realpath as realpath9, stat as stat8 } from "node:fs/promises";
43211
43604
  import { homedir as homedir2 } from "node:os";
43212
- import { basename as basename5, dirname as dirname6, isAbsolute as isAbsolute10, join as join16, normalize as normalize4, relative as relative4 } from "node:path";
43605
+ import { basename as basename5, dirname as dirname4, isAbsolute as isAbsolute10, join as join16, normalize as normalize4, relative as relative4 } from "node:path";
43213
43606
  var WorkspaceDirectoryListing = class {
43214
43607
  directoryId;
43215
43608
  directoryLabel;
@@ -43333,7 +43726,7 @@ var WorkspaceDirectoryService = class {
43333
43726
  }
43334
43727
  }
43335
43728
  entries.sort((a, b) => a.name.localeCompare(b.name));
43336
- const parent = dirname6(target);
43729
+ const parent = dirname4(target);
43337
43730
  return new WorkspaceDirectoryListing(
43338
43731
  id,
43339
43732
  this.label(target),
@@ -43358,7 +43751,7 @@ var WorkspaceDirectoryService = class {
43358
43751
  };
43359
43752
 
43360
43753
  // src/daemon-diagnostic-log.ts
43361
- import { appendFileSync, mkdirSync as mkdirSync3, readFileSync as readFileSync2, renameSync, statSync as statSync3, writeFileSync } from "node:fs";
43754
+ import { appendFileSync, mkdirSync, readFileSync as readFileSync2, renameSync, statSync as statSync3, writeFileSync } from "node:fs";
43362
43755
  import { join as join17 } from "node:path";
43363
43756
  var MAXIMUM_DAEMON_LOG_BYTES = 1 * 1024 * 1024;
43364
43757
  var DaemonDiagnosticLog = class {
@@ -43374,7 +43767,7 @@ var DaemonDiagnosticLog = class {
43374
43767
  const encoded = `${diagnostic.replace(/[\r\n]+/gu, " ").trim()}
43375
43768
  `;
43376
43769
  const encodedBytes = Buffer.byteLength(encoded);
43377
- mkdirSync3(this.#directory, { mode: 448, recursive: true });
43770
+ mkdirSync(this.#directory, { mode: 448, recursive: true });
43378
43771
  let existingBytes = 0;
43379
43772
  try {
43380
43773
  existingBytes = statSync3(this.#path).size;
@@ -43832,8 +44225,91 @@ var readCodexHistory = async (agent, cwd, nativeSessionId, signal) => await read
43832
44225
  var readCodexFullHistory = async (agent, cwd, nativeSessionId, signal) => await readCodexHistoryWithOptions(agent, cwd, nativeSessionId, signal, { detail: "rich" });
43833
44226
 
43834
44227
  // src/native-sessions/service.ts
43835
- import { randomUUID as randomUUID2 } from "node:crypto";
44228
+ import { randomUUID as randomUUID3 } from "node:crypto";
43836
44229
  import { basename as basename6 } from "node:path";
44230
+
44231
+ // src/native-sessions/claude-history.ts
44232
+ async function readClaudeHistory(sessions, directories, bindingId, options, nativeSessionId) {
44233
+ let cursor = null;
44234
+ let inspected = 0;
44235
+ for (let pageNumber = 0; pageNumber < 500 && inspected < 500; pageNumber += 1) {
44236
+ const page = await sessions.listNativeSessions(options, cursor);
44237
+ inspected += page.sessions.length;
44238
+ const found = page.sessions.find((entry) => entry.sessionId === nativeSessionId);
44239
+ if (found !== void 0) {
44240
+ const primary = await directories.identify(bindingId, found.cwd, options.signal);
44241
+ const additional = await Promise.all(
44242
+ found.additionalDirectories.map(
44243
+ async (directory) => await directories.identify(bindingId, directory, options.signal)
44244
+ )
44245
+ );
44246
+ if (primary.path !== options.cwd || additional.length !== options.additionalDirectories.length || additional.some((directory, index2) => directory.path !== options.additionalDirectories[index2])) {
44247
+ throw new AcpExecutionError(
44248
+ "The native Session belongs to another workspace.",
44249
+ {},
44250
+ "session_identity_mismatch"
44251
+ );
44252
+ }
44253
+ return await sessions.previewNativeSession(options, nativeSessionId);
44254
+ }
44255
+ if (page.nextCursor === null || page.nextCursor === cursor) {
44256
+ break;
44257
+ }
44258
+ cursor = page.nextCursor ?? null;
44259
+ }
44260
+ throw new AcpExecutionError("The native Session was not found.", {}, "native_session_not_found");
44261
+ }
44262
+
44263
+ // src/native-sessions/claude-adapter.ts
44264
+ var claudeSessionAdapter = {
44265
+ linkedHistory: async ({ sessions, directories, bindingId, options, nativeSessionId }) => await readClaudeHistory(sessions, directories, bindingId, options, nativeSessionId),
44266
+ history: async ({ sessions, directories, bindingId, options, nativeSessionId }) => await readClaudeHistory(sessions, directories, bindingId, options, nativeSessionId),
44267
+ preview: async ({ sessions, options, nativeSessionId }) => await sessions.previewNativeSession(options, nativeSessionId)
44268
+ };
44269
+
44270
+ // src/native-sessions/codex-adapter.ts
44271
+ async function verifiedHistory(context, full) {
44272
+ const { options, nativeSessionId, directories, bindingId } = context;
44273
+ const snapshot = full ? await readCodexFullHistory(options.agent, options.cwd, nativeSessionId, options.signal) : await readCodexHistory(options.agent, options.cwd, nativeSessionId, options.signal);
44274
+ const resolved = await directories.identify(bindingId, snapshot.cwd, options.signal);
44275
+ if (snapshot.nativeSessionId !== nativeSessionId || resolved.path !== options.cwd) {
44276
+ throw new AcpExecutionError(
44277
+ "Codex returned history for a different session or workspace.",
44278
+ {},
44279
+ "invalid_native_session_response"
44280
+ );
44281
+ }
44282
+ return snapshot.history;
44283
+ }
44284
+ var codexSessionAdapter = {
44285
+ linkedHistory: async (context) => await verifiedHistory(context, true),
44286
+ history: async (context) => await verifiedHistory(context, true),
44287
+ // Codex enforces an exclusive writer per thread. Its read-only app-server
44288
+ // history path keeps externally owned conversations previewable.
44289
+ preview: async (context) => await verifiedHistory(context, false)
44290
+ };
44291
+
44292
+ // src/native-sessions/agent-adapter.ts
44293
+ var genericSessionAdapter = {
44294
+ linkedHistory: async () => {
44295
+ throw new AcpExecutionError("This Agent does not support Chat history", {}, "native_session_unsupported");
44296
+ },
44297
+ history: async () => {
44298
+ throw new AcpExecutionError("Native history is unavailable for this Agent", {}, "native_session_unsupported");
44299
+ },
44300
+ preview: async ({ sessions, options, nativeSessionId }) => await sessions.previewNativeSession(options, nativeSessionId)
44301
+ };
44302
+ function nativeSessionAdapter(agentId) {
44303
+ if (agentId === "codex") {
44304
+ return codexSessionAdapter;
44305
+ }
44306
+ if (agentId === "claude") {
44307
+ return claudeSessionAdapter;
44308
+ }
44309
+ return genericSessionAdapter;
44310
+ }
44311
+
44312
+ // src/native-sessions/service.ts
43837
44313
  var NativeSessionService = class {
43838
44314
  #entries = /* @__PURE__ */ new Map();
43839
44315
  #cursors = /* @__PURE__ */ new Map();
@@ -43863,6 +44339,61 @@ var NativeSessionService = class {
43863
44339
  sessionId: command.sessionId,
43864
44340
  signal
43865
44341
  };
44342
+ if (command.action === "linked-history") {
44343
+ const nativeSessionId = nativeSessionIdSchema.parse(command.targetSessionId);
44344
+ if (this.#sessions.hasPreparedSession(nativeSessionId, options.agent.id, cwd, additionalDirectories) && await this.#sessions.loadLinkedSessionHistory({ ...options, sessionId: nativeSessionId }) === null) {
44345
+ this.record(command, "native_session_history_read");
44346
+ return {
44347
+ action: "linked-history",
44348
+ history: {
44349
+ status: "available",
44350
+ messages: [],
44351
+ truncated: false,
44352
+ coveredCommandIds: [],
44353
+ coveredMessageIds: []
44354
+ },
44355
+ kind: "native.session.result",
44356
+ requestId: command.requestId,
44357
+ sessionId: command.sessionId,
44358
+ targetSessionId: command.targetSessionId
44359
+ };
44360
+ }
44361
+ const history = await nativeSessionAdapter(options.agent.id).linkedHistory({
44362
+ sessions: this.#sessions,
44363
+ directories: this.#directories,
44364
+ bindingId: command.bindingId,
44365
+ options,
44366
+ nativeSessionId
44367
+ });
44368
+ this.record(command, "native_session_history_read");
44369
+ return {
44370
+ action: "linked-history",
44371
+ history,
44372
+ kind: "native.session.result",
44373
+ requestId: command.requestId,
44374
+ sessionId: command.sessionId,
44375
+ targetSessionId: command.targetSessionId
44376
+ };
44377
+ }
44378
+ if (command.action === "create") {
44379
+ if (!supportsNativeChat(options.agent.id)) {
44380
+ throw new AcpExecutionError(
44381
+ "Native session creation is unavailable for this Agent",
44382
+ {},
44383
+ "native_session_unsupported"
44384
+ );
44385
+ }
44386
+ const nativeSessionId = await this.#sessions.createNativeSession(options);
44387
+ signal.throwIfAborted();
44388
+ this.record(command, "native_session_created");
44389
+ return {
44390
+ action: "create",
44391
+ kind: "native.session.result",
44392
+ nativeSessionId,
44393
+ requestId: command.requestId,
44394
+ sessionId: command.sessionId
44395
+ };
44396
+ }
43866
44397
  const prepared = await this.#sessions.prepareNativeSessionBrowser(options);
43867
44398
  if (!prepared.capabilities.listSessions) {
43868
44399
  throw new AcpExecutionError(
@@ -43878,7 +44409,7 @@ var NativeSessionService = class {
43878
44409
  if (authorized === null) {
43879
44410
  return null;
43880
44411
  }
43881
- const entryId = randomUUID2();
44412
+ const entryId = randomUUID3();
43882
44413
  if (this.#entries.size >= 5e3) {
43883
44414
  this.#entries.clear();
43884
44415
  }
@@ -43890,7 +44421,7 @@ var NativeSessionService = class {
43890
44421
  });
43891
44422
  return {
43892
44423
  entryId,
43893
- mobiusSessionIds: this.#sessions.findLinkedSessions(command.agentId, info.sessionId).filter((session) => session.prompted && session.cwd === authorized.cwd).map((session) => session.sessionId),
44424
+ nativeSessionId: info.sessionId,
43894
44425
  title: info.title ?? "Untitled session",
43895
44426
  directoryId: authorized.directoryId,
43896
44427
  directoryLabel: authorized.directoryLabel,
@@ -43933,7 +44464,7 @@ var NativeSessionService = class {
43933
44464
  "invalid_native_session_response"
43934
44465
  );
43935
44466
  }
43936
- nextCursor = randomUUID2();
44467
+ nextCursor = randomUUID3();
43937
44468
  if (this.#cursors.size >= 500) {
43938
44469
  this.#cursors.clear();
43939
44470
  }
@@ -43997,7 +44528,13 @@ var NativeSessionService = class {
43997
44528
  }
43998
44529
  const target = await this.resolveTarget(command, options, selected);
43999
44530
  if (command.action === "history") {
44000
- const history = await this.readHistory(command, options, target, signal);
44531
+ const history = await nativeSessionAdapter(options.agent.id).history({
44532
+ sessions: this.#sessions,
44533
+ directories: this.#directories,
44534
+ bindingId: command.bindingId,
44535
+ options: { ...options, cwd: target.cwd, additionalDirectories: target.additionalDirectories },
44536
+ nativeSessionId: target.info.sessionId
44537
+ });
44001
44538
  signal.throwIfAborted();
44002
44539
  this.record(command, "native_session_history_read");
44003
44540
  return {
@@ -44009,7 +44546,13 @@ var NativeSessionService = class {
44009
44546
  };
44010
44547
  }
44011
44548
  if (command.action === "preview") {
44012
- const history = await this.previewHistory(command, options, target, signal);
44549
+ const history = await nativeSessionAdapter(options.agent.id).preview({
44550
+ sessions: this.#sessions,
44551
+ directories: this.#directories,
44552
+ bindingId: command.bindingId,
44553
+ options: { ...options, cwd: target.cwd, additionalDirectories: target.additionalDirectories },
44554
+ nativeSessionId: target.info.sessionId
44555
+ });
44013
44556
  signal.throwIfAborted();
44014
44557
  this.record(command, "native_session_previewed");
44015
44558
  return {
@@ -44163,43 +44706,6 @@ var NativeSessionService = class {
44163
44706
  title: command.title
44164
44707
  };
44165
44708
  };
44166
- previewHistory = async (command, options, target, signal) => {
44167
- if (options.agent.id !== "codex") {
44168
- return await this.#sessions.previewNativeSession(
44169
- { ...options, cwd: target.cwd, additionalDirectories: target.additionalDirectories },
44170
- target.info.sessionId
44171
- );
44172
- }
44173
- const snapshot = await readCodexHistory(options.agent, target.cwd, target.info.sessionId, signal);
44174
- const resolved = await this.#directories.identify(command.bindingId, snapshot.cwd, signal);
44175
- if (snapshot.nativeSessionId !== target.info.sessionId || resolved.path !== target.cwd) {
44176
- throw new AcpExecutionError(
44177
- "Codex returned history for a different session or workspace.",
44178
- {},
44179
- "invalid_native_session_response"
44180
- );
44181
- }
44182
- return snapshot.history;
44183
- };
44184
- readHistory = async (command, options, target, signal) => {
44185
- if (options.agent.id !== "codex") {
44186
- throw new AcpExecutionError(
44187
- "Native history is unavailable for this Agent",
44188
- {},
44189
- "native_session_unsupported"
44190
- );
44191
- }
44192
- const snapshot = await readCodexFullHistory(options.agent, target.cwd, target.info.sessionId, signal);
44193
- const resolved = await this.#directories.identify(command.bindingId, snapshot.cwd, signal);
44194
- if (snapshot.nativeSessionId !== target.info.sessionId || resolved.path !== target.cwd) {
44195
- throw new AcpExecutionError(
44196
- "Codex returned history for a different session or workspace.",
44197
- {},
44198
- "invalid_native_session_response"
44199
- );
44200
- }
44201
- return snapshot.history;
44202
- };
44203
44709
  authorizeEntry = async (command, options, info) => {
44204
44710
  try {
44205
44711
  const primary = await this.#directories.identify(command.bindingId, info.cwd, options.signal);
@@ -44284,7 +44790,7 @@ var NativeSessionService = class {
44284
44790
  };
44285
44791
 
44286
44792
  // src/prompt-artifact-resolver.ts
44287
- import { createHash as createHash3 } from "node:crypto";
44793
+ import { createHash as createHash4 } from "node:crypto";
44288
44794
  import { fetch as fetch4 } from "undici";
44289
44795
  var ARTIFACT_SCHEME = "mobius-artifact:";
44290
44796
  var ARTIFACT_DOWNLOAD_TIMEOUT_MILLISECONDS = 2e4;
@@ -44423,7 +44929,7 @@ async function download(config2, command, reference, signal) {
44423
44929
  );
44424
44930
  }
44425
44931
  const bytes = await responseBytes(response, reference.byteLength, requestSignal);
44426
- if (createHash3("sha256").update(bytes).digest("hex") !== reference.sha256) {
44932
+ if (createHash4("sha256").update(bytes).digest("hex") !== reference.sha256) {
44427
44933
  throw new PromptArtifactError(
44428
44934
  "artifact_integrity_failed",
44429
44935
  "The prompt artifact failed integrity validation"
@@ -44889,7 +45395,7 @@ var RelayConnectionDiagnostics = class {
44889
45395
  };
44890
45396
 
44891
45397
  // src/relay-connection/liveness.ts
44892
- import { randomUUID as randomUUID3 } from "node:crypto";
45398
+ import { randomUUID as randomUUID4 } from "node:crypto";
44893
45399
  var HEARTBEAT_ACK_TIMEOUT_MILLISECONDS = 1e4;
44894
45400
  var HEARTBEAT_INTERVAL_MILLISECONDS = 2e4;
44895
45401
  var RelayLivenessState = class {
@@ -44978,7 +45484,7 @@ var RelayConnectionLiveness = class {
44978
45484
  }
44979
45485
  throw new Error("Heartbeat was scheduled in an invalid state");
44980
45486
  }
44981
- const heartbeatId = randomUUID3();
45487
+ const heartbeatId = randomUUID4();
44982
45488
  this.#state = new AwaitingHeartbeatAckState(
44983
45489
  heartbeatId,
44984
45490
  this.#timer.schedule(this.#handleTimeout, HEARTBEAT_ACK_TIMEOUT_MILLISECONDS)
@@ -44995,26 +45501,26 @@ var RelayConnectionLiveness = class {
44995
45501
  };
44996
45502
 
44997
45503
  // src/relay-connection/session-event-outbox.ts
44998
- import { mkdirSync as mkdirSync4 } from "node:fs";
44999
- import { dirname as dirname7 } from "node:path";
45000
- import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
45504
+ import { createHash as createHash5 } from "node:crypto";
45505
+ import { DatabaseSync } from "node:sqlite";
45001
45506
  var DEFAULT_OUTBOX_LIMITS = {
45002
45507
  criticalEventBytes: 136 * 1024 * 1024,
45003
45508
  runtimeDeliveryBytes: 64 * 1024 * 1024,
45004
45509
  runtimeDeliveryCount: 64,
45005
45510
  standardEventBytes: 128 * 1024 * 1024
45006
45511
  };
45512
+ var MAX_TERMINAL_RECEIPTS = 1024;
45007
45513
  var SessionEventOutboxCapacityError = class extends Error {
45008
45514
  code = "session_event_outbox_full";
45009
45515
  constructor() {
45010
- super("The durable Session event outbox is full");
45516
+ super("The in-memory Session event outbox is full");
45011
45517
  this.name = "SessionEventOutboxCapacityError";
45012
45518
  }
45013
45519
  };
45014
45520
  var RuntimeDeliveryInboxCapacityError = class extends Error {
45015
45521
  code = "runtime_delivery_inbox_full";
45016
45522
  constructor() {
45017
- super("The durable Runtime delivery inbox is full");
45523
+ super("The in-memory Runtime delivery inbox is full");
45018
45524
  this.name = "RuntimeDeliveryInboxCapacityError";
45019
45525
  }
45020
45526
  };
@@ -45059,11 +45565,10 @@ function rowString(row, field) {
45059
45565
  var SessionEventOutbox = class {
45060
45566
  #database;
45061
45567
  #limits;
45062
- constructor(path3, limits = DEFAULT_OUTBOX_LIMITS) {
45568
+ constructor(limits = DEFAULT_OUTBOX_LIMITS) {
45063
45569
  validateLimits(limits);
45064
45570
  this.#limits = limits;
45065
- mkdirSync4(dirname7(path3), { recursive: true });
45066
- this.#database = new DatabaseSync3(path3);
45571
+ this.#database = new DatabaseSync(":memory:");
45067
45572
  this.#database.exec(`
45068
45573
  CREATE TABLE IF NOT EXISTS relay_session_event_outbox (
45069
45574
  ordinal INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -45091,7 +45596,7 @@ var SessionEventOutbox = class {
45091
45596
  CREATE TABLE IF NOT EXISTS relay_turn_receipts (
45092
45597
  command_id TEXT PRIMARY KEY,
45093
45598
  session_id TEXT NOT NULL,
45094
- command_json TEXT NOT NULL,
45599
+ command_hash TEXT NOT NULL,
45095
45600
  attempt_id TEXT NOT NULL,
45096
45601
  state TEXT NOT NULL CHECK (
45097
45602
  state IN ('dispatching', 'running', 'succeeded', 'failed', 'cancelled')
@@ -45122,19 +45627,20 @@ var SessionEventOutbox = class {
45122
45627
  `);
45123
45628
  }
45124
45629
  claimExecution = (commandId, sessionId, commandJson) => {
45630
+ const commandHash = createHash5("sha256").update(commandJson).digest("hex");
45125
45631
  this.#database.exec("BEGIN IMMEDIATE");
45126
45632
  try {
45127
45633
  const existing = this.#database.prepare(
45128
- `SELECT session_id, command_json, attempt_id, state
45634
+ `SELECT session_id, command_hash, attempt_id, state
45129
45635
  FROM relay_turn_receipts WHERE command_id = ?`
45130
45636
  ).get(commandId);
45131
45637
  if (typeof existing === "object" && existing !== null) {
45132
45638
  const storedSessionId = Reflect.get(existing, "session_id");
45133
- const storedCommand = Reflect.get(existing, "command_json");
45639
+ const storedCommandHash = Reflect.get(existing, "command_hash");
45134
45640
  const attemptId2 = Reflect.get(existing, "attempt_id");
45135
45641
  const state = Reflect.get(existing, "state");
45136
- if (storedSessionId !== sessionId || storedCommand !== commandJson || typeof attemptId2 !== "string" || !isDaemonExecutionState(state)) {
45137
- throw new Error("The daemon command identity conflicts with its durable receipt");
45642
+ if (storedSessionId !== sessionId || storedCommandHash !== commandHash || typeof attemptId2 !== "string" || !isDaemonExecutionState(state)) {
45643
+ throw new Error("The daemon command identity conflicts with its in-memory receipt");
45138
45644
  }
45139
45645
  this.#database.exec("COMMIT");
45140
45646
  return { attemptId: attemptId2, commandId, kind: "duplicate", state };
@@ -45142,9 +45648,9 @@ var SessionEventOutbox = class {
45142
45648
  const attemptId = crypto.randomUUID();
45143
45649
  this.#database.prepare(
45144
45650
  `INSERT INTO relay_turn_receipts (
45145
- command_id, session_id, command_json, attempt_id, state
45651
+ command_id, session_id, command_hash, attempt_id, state
45146
45652
  ) VALUES (?, ?, ?, ?, 'dispatching')`
45147
- ).run(commandId, sessionId, commandJson, attemptId);
45653
+ ).run(commandId, sessionId, commandHash, attemptId);
45148
45654
  this.#database.exec("COMMIT");
45149
45655
  return {
45150
45656
  attemptId,
@@ -45171,11 +45677,21 @@ var SessionEventOutbox = class {
45171
45677
  throw new Error("The daemon execution transition is invalid");
45172
45678
  }
45173
45679
  this.#database.prepare(`UPDATE relay_turn_receipts SET state = ? WHERE command_id = ?`).run(state, commandId);
45680
+ if (state === "succeeded" || state === "failed" || state === "cancelled") {
45681
+ this.#database.prepare(
45682
+ `DELETE FROM relay_turn_receipts
45683
+ WHERE state IN ('succeeded', 'failed', 'cancelled')
45684
+ AND rowid NOT IN (
45685
+ SELECT rowid FROM relay_turn_receipts
45686
+ WHERE state IN ('succeeded', 'failed', 'cancelled')
45687
+ ORDER BY rowid DESC LIMIT ?
45688
+ )`
45689
+ ).run(MAX_TERMINAL_RECEIPTS);
45690
+ }
45174
45691
  };
45175
45692
  /**
45176
- * The Attempt this Runtime durably claimed for a command, when that Attempt never reached a
45177
- * terminal state. A restarted Runtime has no in-memory Turn for a command it was executing before
45178
- * the restart, so this is the only record of the Attempt identity the Relay is still waiting on.
45693
+ * The Attempt this live Runtime claimed for a command that has not reached a terminal state.
45694
+ * Receipts disappear when the daemon process exits.
45179
45695
  */
45180
45696
  findUnsettledAttemptId = (commandId, sessionId) => {
45181
45697
  const row = this.#database.prepare(`SELECT attempt_id, state FROM relay_turn_receipts WHERE command_id = ? AND session_id = ?`).get(commandId, sessionId);
@@ -45224,7 +45740,7 @@ var SessionEventOutbox = class {
45224
45740
  WHERE event_id = ? AND session_id = ?`
45225
45741
  ).run(rejection.eventId, rejection.sessionId);
45226
45742
  if (deletion.changes !== 1) {
45227
- throw new Error("The rejected session event could not be removed from the durable outbox");
45743
+ throw new Error("The rejected session event could not be removed from the in-memory outbox");
45228
45744
  }
45229
45745
  this.#decrementEventState(byteLength);
45230
45746
  this.#database.exec("COMMIT");
@@ -45243,7 +45759,7 @@ var SessionEventOutbox = class {
45243
45759
  enqueueCritical = (sessionId, payload, attemptId = "") => this.#enqueueBounded(sessionId, payload, attemptId, this.#limits.criticalEventBytes);
45244
45760
  /**
45245
45761
  * Bytes still available to standard Session events. The daemon uses this to shed
45246
- * superseded streaming events instead of filling the durable outbox, so a long Turn
45762
+ * superseded streaming events instead of filling the in-memory outbox, so a long Turn
45247
45763
  * behind a slow Relay cannot make the next enqueue throw.
45248
45764
  */
45249
45765
  standardCapacityRemaining = () => {
@@ -45268,7 +45784,7 @@ var SessionEventOutbox = class {
45268
45784
  const payload = rowString(existing, "payload_json");
45269
45785
  const state = runtimeDeliveryState(existing);
45270
45786
  if (sessionId !== delivery.sessionId || payload !== delivery.payload) {
45271
- throw new Error("The Runtime delivery identity conflicts with its durable receipt");
45787
+ throw new Error("The Runtime delivery identity conflicts with its in-memory receipt");
45272
45788
  }
45273
45789
  this.#database.exec("COMMIT");
45274
45790
  return new StoredRuntimeDelivery(delivery.deliveryId, sessionId, payload, state, true);
@@ -45436,7 +45952,7 @@ var SessionEventOutbox = class {
45436
45952
  WHERE event_id = ? AND session_id = ?`
45437
45953
  ).run(eventId, sessionId);
45438
45954
  if (deletion.changes !== 1) {
45439
- throw new Error("The acknowledged session event could not be removed from the durable outbox");
45955
+ throw new Error("The acknowledged session event could not be removed from the in-memory outbox");
45440
45956
  }
45441
45957
  this.#decrementEventState(byteLength);
45442
45958
  this.#database.exec("COMMIT");
@@ -45918,7 +46434,7 @@ var DaemonSessionEventPublisher = class {
45918
46434
  };
45919
46435
  /**
45920
46436
  * Enqueue a standard event, shedding it instead of ending the daemon when the
45921
- * durable outbox is full.
46437
+ * in-memory outbox is full.
45922
46438
  *
45923
46439
  * A capacity error used to escape the coalescing timer that publishes activities,
45924
46440
  * so the process exited and every restart died on the same retained backlog. A full
@@ -45961,7 +46477,7 @@ var DaemonSessionEventPublisher = class {
45961
46477
  return;
45962
46478
  }
45963
46479
  this.#shedEventKinds.add(kind);
45964
- console.warn(`Mobius daemon is dropping durable "${kind}" events because the Session event outbox is full`);
46480
+ console.warn(`Mobius daemon is dropping queued "${kind}" events because the Session event outbox is full`);
45965
46481
  };
45966
46482
  acknowledge = (acknowledgement) => {
45967
46483
  if (!this.#outbox.acknowledge(acknowledgement)) {
@@ -46230,262 +46746,6 @@ async function resolveSessionDirectories(directories, bindingId, directoryId2, a
46230
46746
  }
46231
46747
  return new ResolvedSessionDirectories(cwd, additionalDirectories, additionalDirectoryEntries);
46232
46748
  }
46233
- function isUnavailableModel(cause, modelSettingId, requestedModel) {
46234
- return cause instanceof AcpConfigurationValueUnavailableError && cause.configId === modelSettingId && cause.requestedValue === requestedModel;
46235
- }
46236
- function unsupportedModelIds(unsupportedModels) {
46237
- return [...new Set(unsupportedModels.map((item) => item.requestedValue))];
46238
- }
46239
- async function discoverAgentSettings(command, config2, directories, sessions, signal) {
46240
- const agent = config2.catalog.find(command.agentId);
46241
- const cwd = await directories.resolve(config2.bindingId, "default", signal);
46242
- const inspectedBaseSnapshot = await sessions.inspectAgentSettings({
46243
- additionalDirectories: [],
46244
- agent,
46245
- cwd,
46246
- signal
46247
- });
46248
- const baseSnapshot = {
46249
- agentName: inspectedBaseSnapshot.agentName,
46250
- agentVersion: inspectedBaseSnapshot.agentVersion,
46251
- configOptions: await discoverOpenCodeModelOptions(agent, cwd, inspectedBaseSnapshot.configOptions, signal)
46252
- };
46253
- const baseModel = modelOption(baseSnapshot.configOptions);
46254
- const unsupportedModels = [];
46255
- let selectedSnapshot = baseSnapshot;
46256
- if (command.model !== void 0) {
46257
- if (baseModel === void 0 || baseModel.type !== "select" || !baseModel.values.some((value) => value.value === command.model)) {
46258
- unsupportedModels.push(
46259
- new AcpConfigurationValueUnavailableError(
46260
- baseModel?.id ?? "model",
46261
- command.model,
46262
- baseModel?.values.map((value) => value.value) ?? []
46263
- )
46264
- );
46265
- } else {
46266
- try {
46267
- selectedSnapshot = await sessions.inspectAgentSettings({
46268
- additionalDirectories: [],
46269
- agent,
46270
- cwd,
46271
- model: command.model,
46272
- signal
46273
- });
46274
- } catch (cause) {
46275
- signal.throwIfAborted();
46276
- if (!isUnavailableModel(cause, baseModel.id, command.model)) {
46277
- throw cause;
46278
- }
46279
- unsupportedModels.push(cause);
46280
- }
46281
- }
46282
- }
46283
- const adapter = agentSettingsAdapterForAgent(agent.id);
46284
- const modelEffort = await discoverModelEffort(
46285
- command,
46286
- agent,
46287
- adapter.modelEffortResolution,
46288
- baseSnapshot.configOptions,
46289
- selectedSnapshot.configOptions,
46290
- unsupportedModels,
46291
- cwd,
46292
- sessions,
46293
- signal
46294
- );
46295
- const baseSettings = withoutUnsupportedModels(
46296
- settingsFromSnapshot(agent, baseSnapshot.configOptions),
46297
- baseModel?.id ?? "",
46298
- modelEffort.unsupportedModelIds
46299
- );
46300
- const settings = withoutUnsupportedModels(
46301
- settingsFromSnapshot(agent, selectedSnapshot.configOptions),
46302
- baseModel?.id ?? "",
46303
- modelEffort.unsupportedModelIds
46304
- );
46305
- return {
46306
- event: {
46307
- agentId: command.agentId,
46308
- agentName: selectedSnapshot.agentName,
46309
- agentVersion: selectedSnapshot.agentVersion,
46310
- kind: AGENT_SETTINGS_DISCOVERED_KIND,
46311
- modelEffort,
46312
- requestId: command.requestId,
46313
- settings,
46314
- settingsRevision: settingsRevision(agent, baseSnapshot.agentVersion, baseSettings, modelEffort)
46315
- },
46316
- unsupportedModels
46317
- };
46318
- }
46319
- function settingFromOption(option) {
46320
- return {
46321
- booleanValue: option.booleanValue,
46322
- category: option.category,
46323
- defaultValue: option.type === "boolean" ? "" : option.currentValue,
46324
- description: option.description,
46325
- id: option.id,
46326
- name: option.name,
46327
- type: option.type,
46328
- values: option.values
46329
- };
46330
- }
46331
- function settingsFromSnapshot(agent, configOptions) {
46332
- const settings = [
46333
- ...agentSettingsAdapterForAgent(agent.id).settings(agent).map(settingFromOption),
46334
- ...configOptions.map(settingFromOption)
46335
- ];
46336
- const identifiers = /* @__PURE__ */ new Set();
46337
- for (const setting of settings) {
46338
- if (identifiers.has(setting.id)) {
46339
- throw new AcpExecutionError(
46340
- "The Agent returned duplicate setting identifiers",
46341
- {},
46342
- "invalid_session_configuration"
46343
- );
46344
- }
46345
- identifiers.add(setting.id);
46346
- }
46347
- if (settings.length > 128) {
46348
- throw new AcpExecutionError("The Agent returned too many settings", {}, "invalid_session_configuration");
46349
- }
46350
- return settings;
46351
- }
46352
- function withoutUnsupportedModels(settings, modelSettingId, unsupportedModelIds2) {
46353
- if (modelSettingId.length === 0 || unsupportedModelIds2.length === 0) {
46354
- return settings;
46355
- }
46356
- const unsupported = new Set(unsupportedModelIds2);
46357
- return settings.map((setting) => {
46358
- if (setting.id !== modelSettingId || setting.type !== "select") {
46359
- return setting;
46360
- }
46361
- return {
46362
- ...setting,
46363
- defaultValue: unsupported.has(setting.defaultValue) ? "" : setting.defaultValue,
46364
- values: setting.values.filter((value) => !unsupported.has(value.value))
46365
- };
46366
- });
46367
- }
46368
- function modelOption(options) {
46369
- return options.find((option) => option.id === "model" || option.category === "model");
46370
- }
46371
- function effortOption(options) {
46372
- return options.find((option) => option.id === "reasoning_effort" || option.category === "thought_level");
46373
- }
46374
- function unavailableModelEffort() {
46375
- return {
46376
- effortSettingId: "",
46377
- modelSettingId: "",
46378
- resolution: AGENT_MODEL_EFFORT_RESOLUTION_UNAVAILABLE,
46379
- unsupportedModelIds: [],
46380
- valuesByModel: {}
46381
- };
46382
- }
46383
- async function discoverModelEffort(command, agent, resolution, initialOptions, selectedOptions, initiallyUnsupportedModels, cwd, sessions, signal) {
46384
- const model = modelOption(initialOptions);
46385
- const unsupportedModels = initiallyUnsupportedModels;
46386
- if (resolution !== AGENT_MODEL_EFFORT_RESOLUTION_COMPLETE && resolution !== AGENT_MODEL_EFFORT_RESOLUTION_ON_MODEL_SELECTION) {
46387
- return { ...unavailableModelEffort(), unsupportedModelIds: unsupportedModelIds(unsupportedModels) };
46388
- }
46389
- if (model === void 0 || model.type !== "select" || model.values.length === 0) {
46390
- return { ...unavailableModelEffort(), unsupportedModelIds: unsupportedModelIds(unsupportedModels) };
46391
- }
46392
- const inspectModel = async (modelValue) => (await sessions.inspectAgentSettings({
46393
- additionalDirectories: [],
46394
- agent,
46395
- cwd,
46396
- model: modelValue,
46397
- signal
46398
- })).configOptions;
46399
- const valuesByModel = {};
46400
- if (resolution === "complete") {
46401
- const effort = effortOption(initialOptions);
46402
- if (effort === void 0 || effort.type !== "select" || effort.values.length < 2) {
46403
- return {
46404
- ...unavailableModelEffort(),
46405
- unsupportedModelIds: unsupportedModelIds(unsupportedModels)
46406
- };
46407
- }
46408
- for (const value of model.values) {
46409
- if (unsupportedModels.some((diagnostic) => diagnostic.requestedValue === value.value)) {
46410
- continue;
46411
- }
46412
- try {
46413
- const selectedEffort2 = effortOption(await inspectModel(value.value));
46414
- valuesByModel[value.value] = selectedEffort2?.type === "select" ? selectedEffort2.values : [];
46415
- } catch (cause) {
46416
- signal.throwIfAborted();
46417
- if (!isUnavailableModel(cause, model.id, value.value)) {
46418
- throw cause;
46419
- }
46420
- unsupportedModels.push(cause);
46421
- }
46422
- }
46423
- return {
46424
- effortSettingId: effort.id,
46425
- modelSettingId: model.id,
46426
- resolution: "complete",
46427
- unsupportedModelIds: unsupportedModelIds(unsupportedModels),
46428
- valuesByModel
46429
- };
46430
- }
46431
- if (command.model !== void 0) {
46432
- const modelUnsupported = unsupportedModels.some((diagnostic) => diagnostic.requestedValue === command.model);
46433
- const selectedEffort2 = effortOption(selectedOptions);
46434
- if (!modelUnsupported) {
46435
- valuesByModel[command.model] = selectedEffort2?.type === "select" ? selectedEffort2.values : [];
46436
- }
46437
- return {
46438
- effortSettingId: selectedEffort2?.id ?? "",
46439
- modelSettingId: model.id,
46440
- resolution: "on_model_selection",
46441
- unsupportedModelIds: unsupportedModelIds(unsupportedModels),
46442
- valuesByModel
46443
- };
46444
- }
46445
- const defaultModel = model.type === "select" ? model.currentValue : "";
46446
- const reportedEffort = effortOption(selectedOptions);
46447
- let selectedEffort = reportedEffort;
46448
- if (defaultModel.length > 0 && reportedEffort === void 0) {
46449
- try {
46450
- selectedEffort = effortOption(await inspectModel(defaultModel));
46451
- } catch (cause) {
46452
- signal.throwIfAborted();
46453
- if (!isUnavailableModel(cause, model.id, defaultModel)) {
46454
- throw cause;
46455
- }
46456
- unsupportedModels.push(cause);
46457
- }
46458
- }
46459
- if (defaultModel.length > 0 && !unsupportedModels.some((diagnostic) => diagnostic.requestedValue === defaultModel)) {
46460
- valuesByModel[defaultModel] = selectedEffort?.type === "select" ? selectedEffort.values : [];
46461
- }
46462
- return {
46463
- effortSettingId: selectedEffort?.id ?? "",
46464
- modelSettingId: model.id,
46465
- resolution: "on_model_selection",
46466
- unsupportedModelIds: unsupportedModelIds(unsupportedModels),
46467
- valuesByModel
46468
- };
46469
- }
46470
- function settingsRevision(agent, reportedAgentVersion, settings, modelEffort) {
46471
- const revisionModelEffort = modelEffort.resolution === AGENT_MODEL_EFFORT_RESOLUTION_COMPLETE ? modelEffort : {
46472
- effortSettingId: "",
46473
- modelSettingId: modelEffort.modelSettingId,
46474
- resolution: modelEffort.resolution,
46475
- unsupportedModelIds: modelEffort.unsupportedModelIds,
46476
- valuesByModel: {}
46477
- };
46478
- return createHash4("sha256").update(
46479
- JSON.stringify({
46480
- adapterVersion: agent.kind === "acp-adapter-process" ? agent.adapterVersion : agent.agentVersion,
46481
- agentId: agent.id,
46482
- agentVersion: agent.agentVersion,
46483
- modelEffort: revisionModelEffort,
46484
- reportedAgentVersion,
46485
- settings
46486
- })
46487
- ).digest("hex");
46488
- }
46489
46749
  async function executeWorkspaceList(socket, command, directories, audit, signal) {
46490
46750
  try {
46491
46751
  const listing = await directories.list(command.bindingId, command.directoryId, signal);
@@ -46991,187 +47251,6 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
46991
47251
  console.error("Mobius daemon command failed", error62);
46992
47252
  }
46993
47253
  }
46994
- function invalidSessionConfiguration(message) {
46995
- return new AcpExecutionError(message, {}, "invalid_session_configuration");
46996
- }
46997
- function agentForSessionConfiguration(agent, selections) {
46998
- try {
46999
- return applyAgentLaunchSettings(agent, selections);
47000
- } catch (error62) {
47001
- if (error62 instanceof Error) {
47002
- throw invalidSessionConfiguration(error62.message);
47003
- }
47004
- throw error62;
47005
- }
47006
- }
47007
- function validateSessionConfigurationSelection(option, selection) {
47008
- if (option.type !== selection.valueType) {
47009
- throw invalidSessionConfiguration(`The Agent setting ${selection.configId} changed type`);
47010
- }
47011
- if (option.type === "boolean") {
47012
- if (selection.value.length > 0) {
47013
- throw invalidSessionConfiguration(`The Agent setting ${selection.configId} has an invalid value`);
47014
- }
47015
- return;
47016
- }
47017
- if (selection.booleanValue) {
47018
- throw invalidSessionConfiguration(`The Agent setting ${selection.configId} has an invalid value`);
47019
- }
47020
- if (!option.values.some((value) => value.value === selection.value)) {
47021
- throw invalidSessionConfiguration(`The Agent setting ${selection.configId} has an unavailable value`);
47022
- }
47023
- }
47024
- function sessionConfigurationSelectionIsAvailable(option, selection) {
47025
- if (option.type !== selection.valueType) {
47026
- return false;
47027
- }
47028
- if (option.type === "boolean") {
47029
- return selection.value.length === 0;
47030
- }
47031
- return !selection.booleanValue && option.values.some((value) => value.value === selection.value);
47032
- }
47033
- function sessionConfigurationMatches(option, selection) {
47034
- validateSessionConfigurationSelection(option, selection);
47035
- return option.type === "boolean" ? option.booleanValue === selection.booleanValue : option.currentValue === selection.value;
47036
- }
47037
- function sessionConfigurationPriority(selection, options) {
47038
- const option = options.find((candidate) => candidate.id === selection.configId);
47039
- if (selection.configId === "model" || option?.category === "model") {
47040
- return 0;
47041
- }
47042
- if (selection.configId === "reasoning_effort" || option?.category === "thought_level") {
47043
- return 1;
47044
- }
47045
- if (option?.category === "model_config") {
47046
- return 2;
47047
- }
47048
- return 3;
47049
- }
47050
- function assertAppliedSessionConfiguration(options, selections) {
47051
- const selectionsById = new Map(selections.map((selection) => [selection.configId, selection]));
47052
- for (const option of options) {
47053
- const selection = selectionsById.get(option.id);
47054
- if (selection === void 0 || !sessionConfigurationSelectionIsAvailable(option, selection)) {
47055
- continue;
47056
- }
47057
- if (!sessionConfigurationMatches(option, selection)) {
47058
- throw invalidSessionConfiguration(`The Turn configuration does not match Agent setting ${option.id}`);
47059
- }
47060
- }
47061
- }
47062
- function unavailableSessionConfigurationCategory(selection) {
47063
- if (selection.configId === "model") {
47064
- return "model";
47065
- }
47066
- if (selection.configId === "reasoning_effort") {
47067
- return "thought_level";
47068
- }
47069
- return "unknown";
47070
- }
47071
- async function applySessionConfigurationSelection(sessions, audit, options, selection, agent, cwd, additionalDirectories, commandId, sessionId, signal) {
47072
- const option = options.find((candidate) => candidate.id === selection.configId);
47073
- if (option === void 0) {
47074
- warnIgnoredSetting(
47075
- audit,
47076
- "session_configuration_setting_ignored",
47077
- commandId,
47078
- sessionId,
47079
- agent.id,
47080
- selection,
47081
- unavailableSessionConfigurationCategory(selection),
47082
- "setting_unavailable"
47083
- );
47084
- return options;
47085
- }
47086
- if (option.type !== selection.valueType) {
47087
- warnIgnoredSetting(
47088
- audit,
47089
- "session_configuration_setting_ignored",
47090
- commandId,
47091
- sessionId,
47092
- agent.id,
47093
- selection,
47094
- option.category,
47095
- "setting_schema_mismatch"
47096
- );
47097
- return options;
47098
- }
47099
- if (option.type === "boolean" && selection.value.length > 0 || option.type === "select" && selection.booleanValue) {
47100
- warnIgnoredSetting(
47101
- audit,
47102
- "session_configuration_setting_ignored",
47103
- commandId,
47104
- sessionId,
47105
- agent.id,
47106
- selection,
47107
- option.category,
47108
- "selection_schema_mismatch"
47109
- );
47110
- return options;
47111
- }
47112
- if (option.type === "select" && !option.values.some((value) => value.value === selection.value)) {
47113
- warnIgnoredSetting(
47114
- audit,
47115
- "session_configuration_setting_ignored",
47116
- commandId,
47117
- sessionId,
47118
- agent.id,
47119
- selection,
47120
- option.category,
47121
- "value_unavailable"
47122
- );
47123
- return options;
47124
- }
47125
- if (sessionConfigurationMatches(option, selection)) {
47126
- return options;
47127
- }
47128
- return await sessions.configureSession({
47129
- additionalDirectories,
47130
- agent,
47131
- booleanValue: selection.booleanValue,
47132
- configId: selection.configId,
47133
- cwd,
47134
- requestId: `cfg_${randomUUID4()}`,
47135
- sessionId,
47136
- signal,
47137
- value: selection.value,
47138
- valueType: selection.valueType
47139
- });
47140
- }
47141
- async function applyCompleteSessionConfiguration(sessions, audit, initialOptions, selections, agent, cwd, additionalDirectories, commandId, sessionId, signal) {
47142
- let options = initialOptions;
47143
- const orderedSelections = selections.toSorted((left, right) => {
47144
- const priority = sessionConfigurationPriority(left, initialOptions) - sessionConfigurationPriority(right, initialOptions);
47145
- return priority === 0 ? left.configId.localeCompare(right.configId) : priority;
47146
- });
47147
- for (const selection of orderedSelections) {
47148
- options = await applySessionConfigurationSelection(
47149
- sessions,
47150
- audit,
47151
- options,
47152
- selection,
47153
- agent,
47154
- cwd,
47155
- additionalDirectories,
47156
- commandId,
47157
- sessionId,
47158
- signal
47159
- );
47160
- }
47161
- assertAppliedSessionConfiguration(options, selections);
47162
- }
47163
- function warnIgnoredSetting(audit, event, commandId, sessionId, agentId, selection, category, reason) {
47164
- const details = {
47165
- agentId,
47166
- category,
47167
- configId: selection.configId,
47168
- reason,
47169
- requestedValue: selection.value
47170
- };
47171
- audit.record({ commandId, details, event, sessionId });
47172
- process.stderr.write(`Mobius daemon warning ${JSON.stringify({ commandId, event, sessionId, ...details })}
47173
- `);
47174
- }
47175
47254
  function waitForRelayRetry(signal, timer) {
47176
47255
  if (signal.aborted) {
47177
47256
  return Promise.resolve();
@@ -47218,7 +47297,7 @@ async function installDetectedAgentIntegrations(config2, installations, signal)
47218
47297
  {
47219
47298
  agentId: agent.id,
47220
47299
  kind: AGENT_INSTALL_REQUEST_KIND,
47221
- requestId: `automatic-integration-${randomUUID4()}`
47300
+ requestId: `automatic-integration-${randomUUID5()}`
47222
47301
  },
47223
47302
  signal
47224
47303
  );
@@ -47470,7 +47549,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
47470
47549
  if (connectionController.signal.aborted) {
47471
47550
  return;
47472
47551
  }
47473
- console.error("Mobius daemon could not process a durable Runtime delivery", error62);
47552
+ console.error("Mobius daemon could not process a in-memory Runtime delivery", error62);
47474
47553
  failAndClose(
47475
47554
  new Error("Runtime delivery processing failed", { cause: error62 }),
47476
47555
  4008,
@@ -48273,8 +48352,8 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
48273
48352
  publishCatalog: async (installationSignal) => await publishAgentCatalog(config2, installationSignal),
48274
48353
  stateDirectory
48275
48354
  });
48276
- const sessionStore = new SqliteAcpSessionStore(config2.auditDatabasePath);
48277
- const outbox = new SessionEventOutbox(config2.auditDatabasePath);
48355
+ const sessionStore = new MemoryAcpSessionStore();
48356
+ const outbox = new SessionEventOutbox();
48278
48357
  const publisher = new DaemonSessionEventPublisher(outbox, timer);
48279
48358
  const activeTurns = /* @__PURE__ */ new Map();
48280
48359
  const activeAttemptIds = /* @__PURE__ */ new Map();
@@ -48286,9 +48365,14 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
48286
48365
  }
48287
48366
  publisher.recordAttempt(sessionId, event, attemptId);
48288
48367
  };
48289
- const sessions = new AcpSessionManager(new DaemonAcpObserver(recordSessionEvent), sessionStore, {
48290
- read: async (options2, nativeSessionId) => options2.agent.id === "codex" ? (await readCodexFullHistory(options2.agent, options2.cwd, nativeSessionId, options2.signal)).history : null
48291
- });
48368
+ const sessions = new AcpSessionManager(
48369
+ new DaemonAcpObserver(recordSessionEvent),
48370
+ sessionStore,
48371
+ {
48372
+ read: async (options2, nativeSessionId) => options2.agent.id === "codex" ? (await readCodexFullHistory(options2.agent, options2.cwd, nativeSessionId, options2.signal)).history : null
48373
+ },
48374
+ "native"
48375
+ );
48292
48376
  const directories = new WorkspaceDirectoryService(config2.bindingId, config2.defaultWorkspace);
48293
48377
  const installationObserver = new DaemonInstallationObserver();
48294
48378
  const diagnostics = new RelayConnectionDiagnostics(
@@ -48424,13 +48508,9 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
48424
48508
  await sessions.close();
48425
48509
  } finally {
48426
48510
  try {
48427
- sessionStore.close();
48511
+ publisher.close();
48428
48512
  } finally {
48429
- try {
48430
- publisher.close();
48431
- } finally {
48432
- outbox.close();
48433
- }
48513
+ outbox.close();
48434
48514
  }
48435
48515
  }
48436
48516
  }
@@ -48486,7 +48566,7 @@ var MobiusRuntimeEngine = class {
48486
48566
  }
48487
48567
  signal.throwIfAborted();
48488
48568
  this.#state = new RunningMobiusRuntimeState();
48489
- const audit = new AuditStore(this.#config.auditDatabasePath);
48569
+ const audit = new AuditStore();
48490
48570
  try {
48491
48571
  await runDaemon(this.#config, audit, signal, void 0, {
48492
48572
  ...this.#options.onConnectionStatus === void 0 ? {} : { onConnectionStatus: this.#options.onConnectionStatus },
@@ -48536,7 +48616,7 @@ function isRecord11(value) {
48536
48616
  return typeof value === "object" && value !== null && !Array.isArray(value);
48537
48617
  }
48538
48618
  function controlSocketPath(stateDirectory) {
48539
- const installationHash = createHash5("sha256").update(stateDirectory).digest("hex").slice(0, 32);
48619
+ const installationHash = createHash6("sha256").update(stateDirectory).digest("hex").slice(0, 32);
48540
48620
  return process.platform === "win32" ? `\\\\.\\pipe\\mobius-${installationHash}` : join18(tmpdir(), `mobius-${installationHash}.sock`);
48541
48621
  }
48542
48622
  function controlTokenPath(stateDirectory) {
@@ -48857,24 +48937,19 @@ async function sendControlRequest(stateDirectory, command, signal) {
48857
48937
  socket.destroy();
48858
48938
  }
48859
48939
  }
48860
- async function spawnManager(stateDirectory) {
48861
- const log = await open6(join18(stateDirectory, "manager.log"), "a", 384);
48862
- try {
48863
- const child = spawn6(process.execPath, [process.argv[1] ?? "", "__manager"], {
48864
- detached: true,
48865
- env: process.env,
48866
- stdio: ["ignore", log.fd, log.fd]
48867
- });
48868
- child.unref();
48869
- return child;
48870
- } finally {
48871
- await log.close();
48872
- }
48940
+ async function spawnManager() {
48941
+ const child = spawn6(process.execPath, [process.argv[1] ?? "", "__manager"], {
48942
+ detached: true,
48943
+ env: process.env,
48944
+ stdio: "ignore"
48945
+ });
48946
+ child.unref();
48947
+ return child;
48873
48948
  }
48874
- async function launchManager(stateDirectory, managerVersion) {
48949
+ async function launchManager(managerVersion) {
48875
48950
  process.stdout.write(`Starting mobius daemon ${managerVersion}
48876
48951
  `);
48877
- await spawnManager(stateDirectory);
48952
+ await spawnManager();
48878
48953
  }
48879
48954
  async function waitForManagerExit(stateDirectory, signal) {
48880
48955
  const deadline = AbortSignal.any([signal, AbortSignal.timeout(1e4)]);
@@ -48937,14 +49012,14 @@ async function ensureMatchingManager(stateDirectory, managerVersion, signal) {
48937
49012
  throw new Error("The Mobius manager returned an unexpected response");
48938
49013
  }
48939
49014
  await stopManager(stateDirectory, signal);
48940
- await launchManager(stateDirectory, managerVersion);
49015
+ await launchManager(managerVersion);
48941
49016
  managerStarted = true;
48942
49017
  } catch (cause) {
48943
49018
  if (!isNodeError2(cause, "ENOENT") && !isNodeError2(cause, "ECONNREFUSED")) {
48944
49019
  throw cause;
48945
49020
  }
48946
49021
  if (!managerStarted) {
48947
- await launchManager(stateDirectory, managerVersion);
49022
+ await launchManager(managerVersion);
48948
49023
  managerStarted = true;
48949
49024
  }
48950
49025
  await new Promise((resolve8, reject) => {
@@ -49121,7 +49196,7 @@ async function writePairList(path3, pairs) {
49121
49196
  shutdown.signal.throwIfAborted();
49122
49197
  let file2;
49123
49198
  try {
49124
- file2 = await open7(path3, constants2.O_WRONLY | constants2.O_NOFOLLOW);
49199
+ file2 = await open6(path3, constants2.O_WRONLY | constants2.O_NOFOLLOW);
49125
49200
  } catch (cause) {
49126
49201
  if (typeof cause === "object" && cause !== null && "code" in cause && cause.code === "ENOENT") {
49127
49202
  throw new Error("The JSON output file does not exist", { cause });