@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/index.js CHANGED
@@ -33,7 +33,6 @@ var createAcpClient = (handler) => client({ name: "mobius" }).onRequest(
33
33
 
34
34
  // src/config.ts
35
35
  import { join as join3, resolve as resolve3 } from "node:path";
36
- import { fileURLToPath } from "node:url";
37
36
 
38
37
  // ../../node_modules/.pnpm/zod@4.6.5/node_modules/zod/v4/classic/external.js
39
38
  var external_exports = {};
@@ -20399,6 +20398,7 @@ var encodeAgentInstallCancelledEvent = (message) => encode3(message, agentInstal
20399
20398
 
20400
20399
  // ../protocol/src/messages.ts
20401
20400
  var SESSION_PROMPT_KIND = "session.prompt";
20401
+ var RUNTIME_WORKSPACE_BINDING_ID = "workspace";
20402
20402
  var SESSION_CANCEL_KIND = "session.cancel";
20403
20403
  var RUNTIME_LIVENESS_READY_KIND = "runtime.liveness.ready";
20404
20404
  var RUNTIME_HEARTBEAT_KIND = "runtime.heartbeat";
@@ -21005,6 +21005,8 @@ var nativeSessionTurnForkCommandSchema = external_exports.strictObject({
21005
21005
  title: external_exports.string().max(500)
21006
21006
  }).readonly();
21007
21007
  var nativeSessionRequestSchema = external_exports.discriminatedUnion("action", [
21008
+ external_exports.strictObject({ ...identity, action: external_exports.literal("create") }).readonly(),
21009
+ external_exports.strictObject({ ...identity, action: external_exports.literal("linked-history"), targetSessionId: identifier }).readonly(),
21008
21010
  external_exports.strictObject({ ...identity, action: external_exports.literal("preview"), entryId: identifier }).readonly(),
21009
21011
  external_exports.strictObject({ ...identity, action: external_exports.literal("history"), entryId: identifier }).readonly(),
21010
21012
  external_exports.strictObject({ ...identity, action: external_exports.literal("find"), nativeSessionId: identifier }).readonly(),
@@ -21026,6 +21028,8 @@ var nativeSessionRequestSchema = external_exports.discriminatedUnion("action", [
21026
21028
  }).readonly()
21027
21029
  ]);
21028
21030
  var nativeSessionCommandSchema = external_exports.discriminatedUnion("action", [
21031
+ external_exports.strictObject({ ...identity, action: external_exports.literal("create") }).readonly(),
21032
+ external_exports.strictObject({ ...identity, action: external_exports.literal("linked-history"), targetSessionId: identifier }).readonly(),
21029
21033
  external_exports.strictObject({ ...identity, action: external_exports.literal("preview"), entryId: identifier }).readonly(),
21030
21034
  external_exports.strictObject({ ...identity, action: external_exports.literal("history"), entryId: identifier }).readonly(),
21031
21035
  external_exports.strictObject({ ...identity, action: external_exports.literal("find"), nativeSessionId: identifier }).readonly(),
@@ -21054,7 +21058,7 @@ var nativeSessionCommandSchema = external_exports.discriminatedUnion("action", [
21054
21058
  ]);
21055
21059
  var nativeSessionEntrySchema = external_exports.strictObject({
21056
21060
  entryId: identifier,
21057
- mobiusSessionIds: external_exports.array(identifier).max(500).readonly(),
21061
+ nativeSessionId: identifier,
21058
21062
  title: external_exports.string().max(500),
21059
21063
  directoryId,
21060
21064
  directoryLabel: external_exports.string().min(1).max(2048),
@@ -21066,6 +21070,18 @@ var resultEnvelope = {
21066
21070
  kind: external_exports.literal(NATIVE_SESSION_RESULT_KIND)
21067
21071
  };
21068
21072
  var nativeSessionResultSchema = external_exports.discriminatedUnion("action", [
21073
+ external_exports.strictObject({ ...resultEnvelope, action: external_exports.literal("create"), nativeSessionId: identifier }).readonly(),
21074
+ external_exports.strictObject({
21075
+ ...resultEnvelope,
21076
+ action: external_exports.literal("linked-history"),
21077
+ targetSessionId: identifier,
21078
+ history: sessionHistorySchema
21079
+ }).readonly(),
21080
+ external_exports.strictObject({
21081
+ ...resultEnvelope,
21082
+ action: external_exports.literal("unlinked-history"),
21083
+ targetSessionId: identifier
21084
+ }).readonly(),
21069
21085
  external_exports.strictObject({
21070
21086
  ...resultEnvelope,
21071
21087
  action: external_exports.literal("find"),
@@ -22359,8 +22375,7 @@ function createDaemonConfig(connection, agents = [], installableAgents = [], loc
22359
22375
  return {
22360
22376
  agents: daemonAgents,
22361
22377
  defaultWorkspace: connection.defaultWorkspace,
22362
- auditDatabasePath: connection.auditDatabasePath,
22363
- bindingId: "workspace",
22378
+ bindingId: RUNTIME_WORKSPACE_BINDING_ID,
22364
22379
  catalog: new LocalAgentCatalog(daemonAgents, installableAgents),
22365
22380
  channelId: connection.channelId,
22366
22381
  installableAgents,
@@ -22380,7 +22395,6 @@ function loadDaemonConfig() {
22380
22395
  return createDaemonConfig(
22381
22396
  {
22382
22397
  defaultWorkspace: loadDefaultWorkspace(),
22383
- auditDatabasePath: process.env["MOBIUS_AUDIT_DATABASE"] ?? fileURLToPath(new URL("../../../.mobius/daemon.sqlite", import.meta.url)),
22384
22398
  channelId: process.env["MOBIUS_CHANNEL_ID"] ?? "local",
22385
22399
  relayUrl
22386
22400
  },
@@ -22389,204 +22403,6 @@ function loadDaemonConfig() {
22389
22403
  );
22390
22404
  }
22391
22405
 
22392
- // src/acp/session-manager.ts
22393
- import { spawn as spawn2 } from "node:child_process";
22394
- import {
22395
- methods as methods3,
22396
- ndJsonStream,
22397
- PROTOCOL_VERSION,
22398
- RequestError
22399
- } from "@agentclientprotocol/sdk";
22400
-
22401
- // src/authorization/local-raster.ts
22402
- import { open as open2, readFile as readFile2, realpath as realpath2, stat as stat2 } from "node:fs/promises";
22403
- import { basename, isAbsolute, normalize } from "node:path";
22404
- import { fileURLToPath as fileURLToPath2 } from "node:url";
22405
- var MAX_LOCAL_RASTER_BYTES = 128 * 1024 * 1024;
22406
- var MAX_INLINE_RASTER_BYTES = 3e6;
22407
- var PNG_SIGNATURE = Uint8Array.of(137, 80, 78, 71);
22408
- var JPEG_SIGNATURE = Uint8Array.of(255, 216, 255);
22409
- var GIF87_SIGNATURE = new TextEncoder().encode("GIF87a");
22410
- var GIF89_SIGNATURE = new TextEncoder().encode("GIF89a");
22411
- var RIFF_SIGNATURE = new TextEncoder().encode("RIFF");
22412
- var WEBP_SIGNATURE = new TextEncoder().encode("WEBP");
22413
- var LocalRasterImage = class {
22414
- bytes;
22415
- mimeType;
22416
- name;
22417
- sourceUri;
22418
- constructor(name, mimeType, bytes, sourceUri = "") {
22419
- this.bytes = bytes;
22420
- this.mimeType = mimeType;
22421
- this.name = name;
22422
- this.sourceUri = sourceUri;
22423
- }
22424
- base64 = async () => {
22425
- const bytes = this.bytes ?? new Uint8Array(await readFile2(this.sourceUri));
22426
- return Buffer.from(bytes).toString("base64");
22427
- };
22428
- };
22429
- function startsWith(bytes, signature, offset = 0) {
22430
- if (bytes.byteLength < offset + signature.byteLength) {
22431
- return false;
22432
- }
22433
- return signature.every((value, index2) => bytes[offset + index2] === value);
22434
- }
22435
- function sniffRasterMime(bytes) {
22436
- if (startsWith(bytes, PNG_SIGNATURE)) {
22437
- return "image/png";
22438
- }
22439
- if (startsWith(bytes, JPEG_SIGNATURE)) {
22440
- return "image/jpeg";
22441
- }
22442
- if (startsWith(bytes, GIF87_SIGNATURE) || startsWith(bytes, GIF89_SIGNATURE)) {
22443
- return "image/gif";
22444
- }
22445
- if (startsWith(bytes, RIFF_SIGNATURE) && startsWith(bytes, WEBP_SIGNATURE, 8)) {
22446
- return "image/webp";
22447
- }
22448
- return null;
22449
- }
22450
- function readInlineRaster(data, name = "Image") {
22451
- if (data.length === 0 || data.length > Math.ceil(MAX_INLINE_RASTER_BYTES / 3) * 4 || data.length % 4 !== 0) {
22452
- return null;
22453
- }
22454
- if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(data)) {
22455
- return null;
22456
- }
22457
- const bytes = new Uint8Array(Buffer.from(data, "base64"));
22458
- if (bytes.byteLength < 1 || bytes.byteLength > MAX_INLINE_RASTER_BYTES) {
22459
- return null;
22460
- }
22461
- const mimeType = sniffRasterMime(bytes);
22462
- if (mimeType === null) {
22463
- return null;
22464
- }
22465
- return new LocalRasterImage(basename(name) || "Image", mimeType, bytes);
22466
- }
22467
- async function resolveCanonicalPath(requested, signal) {
22468
- signal.throwIfAborted();
22469
- if (!isAbsolute(requested) || requested.includes("\0") || normalize(requested) !== requested) {
22470
- return null;
22471
- }
22472
- try {
22473
- const target = await realpath2(requested);
22474
- signal.throwIfAborted();
22475
- if (!isAbsolute(target) || normalize(target) !== target) {
22476
- return null;
22477
- }
22478
- return target;
22479
- } catch (cause) {
22480
- signal.throwIfAborted();
22481
- if (cause instanceof Error && cause.name === "AbortError") {
22482
- throw cause;
22483
- }
22484
- return null;
22485
- }
22486
- }
22487
- function parseLocalImageUri(uri) {
22488
- const trimmed = uri.trim();
22489
- if (trimmed.length === 0 || trimmed.length > 2048 || trimmed.includes("\0")) {
22490
- return null;
22491
- }
22492
- if (trimmed.startsWith("data:")) {
22493
- return null;
22494
- }
22495
- if (trimmed.startsWith("file:")) {
22496
- try {
22497
- const url2 = new URL(trimmed);
22498
- if (url2.protocol !== "file:" || url2.host.length > 0) {
22499
- return null;
22500
- }
22501
- return fileURLToPath2(url2);
22502
- } catch {
22503
- return null;
22504
- }
22505
- }
22506
- if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(trimmed)) {
22507
- return null;
22508
- }
22509
- return trimmed;
22510
- }
22511
- async function readLocalRaster(uri, signal) {
22512
- signal.throwIfAborted();
22513
- const requested = parseLocalImageUri(uri);
22514
- if (requested === null) {
22515
- return null;
22516
- }
22517
- const target = await resolveCanonicalPath(requested, signal);
22518
- if (target === null) {
22519
- return null;
22520
- }
22521
- const targetMetadata = await stat2(target);
22522
- signal.throwIfAborted();
22523
- if (!targetMetadata.isFile() || targetMetadata.size < 1 || targetMetadata.size > MAX_LOCAL_RASTER_BYTES) {
22524
- return null;
22525
- }
22526
- const handle = await open2(target, "r");
22527
- const header = new Uint8Array(12);
22528
- try {
22529
- await handle.read(header, 0, header.byteLength, 0);
22530
- } finally {
22531
- await handle.close();
22532
- }
22533
- signal.throwIfAborted();
22534
- const mimeType = sniffRasterMime(header);
22535
- if (mimeType === null) {
22536
- return null;
22537
- }
22538
- return new LocalRasterImage(basename(target) || "Image", mimeType, null, target);
22539
- }
22540
-
22541
- // src/authorization/local-video.ts
22542
- import { basename as basename2 } from "node:path";
22543
- var MAX_INLINE_VIDEO_BYTES = 3e6;
22544
- var MP4_FILE_TYPE = new TextEncoder().encode("ftyp");
22545
- var WEBM_SIGNATURE = Uint8Array.of(26, 69, 223, 163);
22546
- var LocalVideo = class {
22547
- bytes;
22548
- mimeType;
22549
- name;
22550
- constructor(name, mimeType, bytes) {
22551
- this.bytes = bytes;
22552
- this.mimeType = mimeType;
22553
- this.name = name;
22554
- }
22555
- base64 = () => Buffer.from(this.bytes).toString("base64");
22556
- };
22557
- function startsWith2(bytes, signature, offset = 0) {
22558
- if (bytes.byteLength < offset + signature.byteLength) {
22559
- return false;
22560
- }
22561
- return signature.every((value, index2) => bytes[offset + index2] === value);
22562
- }
22563
- function sniffVideoMime(bytes) {
22564
- if (startsWith2(bytes, MP4_FILE_TYPE, 4)) {
22565
- return "video/mp4";
22566
- }
22567
- if (startsWith2(bytes, WEBM_SIGNATURE)) {
22568
- return "video/webm";
22569
- }
22570
- return null;
22571
- }
22572
- function readInlineVideo(data, declaredMimeType, name = "Video") {
22573
- if (data.length === 0 || data.length > Math.ceil(MAX_INLINE_VIDEO_BYTES / 3) * 4 || data.length % 4 !== 0) {
22574
- return null;
22575
- }
22576
- if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(data)) {
22577
- return null;
22578
- }
22579
- const bytes = new Uint8Array(Buffer.from(data, "base64"));
22580
- if (bytes.byteLength < 1 || bytes.byteLength > MAX_INLINE_VIDEO_BYTES) {
22581
- return null;
22582
- }
22583
- const mimeType = sniffVideoMime(bytes);
22584
- if (mimeType === null || mimeType !== declaredMimeType) {
22585
- return null;
22586
- }
22587
- return new LocalVideo(basename2(name) || "Video", mimeType, bytes);
22588
- }
22589
-
22590
22406
  // src/infra/operation-metrics.ts
22591
22407
  var AccumulatingOperationMetrics = class {
22592
22408
  #durations = /* @__PURE__ */ new Map();
@@ -22622,77 +22438,9 @@ var unmeasuredOperationMetrics = Object.freeze({
22622
22438
  snapshot: () => Object.freeze([])
22623
22439
  });
22624
22440
 
22625
- // src/native-sessions/history-images.ts
22626
- var IMAGE_MARKER = /\[@image\]\(([^)\r\n]*)(?:\)|$)/g;
22627
- async function embedLocalHistoryImages(history, signal) {
22628
- if (history.status !== "available") {
22629
- return history;
22630
- }
22631
- const messages = [];
22632
- let imageCharacters = 0;
22633
- for (const message of history.messages) {
22634
- signal.throwIfAborted();
22635
- const resolved = await resolveMessageImages(message, imageCharacters, signal);
22636
- imageCharacters += (resolved.images ?? []).reduce((size, image) => size + image.data.length, 0);
22637
- messages.push(resolved);
22638
- }
22639
- return {
22640
- ...history,
22641
- messages
22642
- };
22643
- }
22644
- async function resolveMessageImages(message, usedCharacters, signal) {
22645
- const images = [...message.images ?? []];
22646
- let imageCharacters = images.reduce((size, image) => size + image.data.length, 0);
22647
- const text3 = await replaceImageMarkers(message.text, async (uri) => {
22648
- if (images.length >= 8 || usedCharacters + imageCharacters >= SESSION_HISTORY_IMAGE_CHARACTER_LIMIT) {
22649
- return "[Image unavailable]";
22650
- }
22651
- const embedded = parseNativeHistoryText(`[@image](${uri})`).images[0];
22652
- if (embedded !== void 0) {
22653
- if (usedCharacters + imageCharacters + embedded.data.length > SESSION_HISTORY_IMAGE_CHARACTER_LIMIT) {
22654
- return "[Image unavailable]";
22655
- }
22656
- images.push(embedded);
22657
- imageCharacters += embedded.data.length;
22658
- return "";
22659
- }
22660
- const local = await readLocalRaster(uri, signal);
22661
- if (local === null) {
22662
- return "[Image unavailable]";
22663
- }
22664
- const data = await local.base64();
22665
- if (usedCharacters + imageCharacters + data.length > SESSION_HISTORY_IMAGE_CHARACTER_LIMIT) {
22666
- return "[Image unavailable]";
22667
- }
22668
- images.push({
22669
- data,
22670
- mimeType: local.mimeType,
22671
- name: local.name
22672
- });
22673
- imageCharacters += data.length;
22674
- return "";
22675
- });
22676
- return {
22677
- ...message,
22678
- text: text3,
22679
- ...images.length > 0 ? { images } : {}
22680
- };
22681
- }
22682
- async function replaceImageMarkers(text3, replace) {
22683
- const matches = [...text3.matchAll(IMAGE_MARKER)];
22684
- if (matches.length === 0) {
22685
- return text3;
22686
- }
22687
- let cursor = 0;
22688
- let rewritten = "";
22689
- for (const match of matches) {
22690
- const index2 = match.index ?? 0;
22691
- rewritten += text3.slice(cursor, index2);
22692
- rewritten += await replace(match[1] ?? "");
22693
- cursor = index2 + match[0].length;
22694
- }
22695
- return `${rewritten}${text3.slice(cursor)}`;
22441
+ // src/native-sessions/chat-agent.ts
22442
+ function supportsNativeChat(agentId) {
22443
+ return agentId === "codex" || agentId === "claude";
22696
22444
  }
22697
22445
 
22698
22446
  // src/acp/acp-error.ts
@@ -22719,6 +22467,426 @@ var AcpConfigurationValueUnavailableError = class extends AcpExecutionError {
22719
22467
  }
22720
22468
  };
22721
22469
 
22470
+ // src/acp/process-capacity.ts
22471
+ var AcpProcessCapacityLease = class {
22472
+ #releaseCapacity;
22473
+ #released = false;
22474
+ constructor(releaseCapacity) {
22475
+ this.#releaseCapacity = releaseCapacity;
22476
+ }
22477
+ release = () => {
22478
+ if (this.#released) {
22479
+ return;
22480
+ }
22481
+ this.#released = true;
22482
+ this.#releaseCapacity();
22483
+ };
22484
+ };
22485
+ var AcpProcessCapacityWaiter = class {
22486
+ completion = Promise.withResolvers();
22487
+ signal;
22488
+ constructor(signal) {
22489
+ this.signal = signal;
22490
+ }
22491
+ cancel = () => {
22492
+ try {
22493
+ this.signal.throwIfAborted();
22494
+ } catch (error62) {
22495
+ this.completion.reject(error62);
22496
+ }
22497
+ };
22498
+ };
22499
+ var AcpProcessCapacityLock = class {
22500
+ #locked = false;
22501
+ #waiters = [];
22502
+ acquire = async (signal) => {
22503
+ signal.throwIfAborted();
22504
+ if (!this.#locked) {
22505
+ this.#locked = true;
22506
+ return new AcpProcessCapacityLease(this.#release);
22507
+ }
22508
+ const waiter = new AcpProcessCapacityWaiter(signal);
22509
+ this.#waiters.push(waiter);
22510
+ signal.addEventListener("abort", waiter.cancel, { once: true });
22511
+ if (signal.aborted) {
22512
+ waiter.cancel();
22513
+ }
22514
+ try {
22515
+ return await waiter.completion.promise;
22516
+ } finally {
22517
+ signal.removeEventListener("abort", waiter.cancel);
22518
+ const index2 = this.#waiters.indexOf(waiter);
22519
+ if (index2 >= 0) {
22520
+ this.#waiters.splice(index2, 1);
22521
+ }
22522
+ }
22523
+ };
22524
+ #release = () => {
22525
+ while (this.#waiters.length > 0) {
22526
+ const waiter = this.#waiters.shift();
22527
+ if (waiter === void 0 || waiter.signal.aborted) {
22528
+ continue;
22529
+ }
22530
+ waiter.completion.resolve(new AcpProcessCapacityLease(this.#release));
22531
+ return;
22532
+ }
22533
+ this.#locked = false;
22534
+ };
22535
+ };
22536
+ async function waitForAcpProcessCapacity(completion, signal) {
22537
+ signal.throwIfAborted();
22538
+ const cancelled = Promise.withResolvers();
22539
+ const cancel = () => {
22540
+ try {
22541
+ signal.throwIfAborted();
22542
+ } catch (error62) {
22543
+ cancelled.reject(error62);
22544
+ }
22545
+ };
22546
+ signal.addEventListener("abort", cancel, { once: true });
22547
+ if (signal.aborted) {
22548
+ cancel();
22549
+ }
22550
+ try {
22551
+ await Promise.race([completion, cancelled.promise]);
22552
+ } finally {
22553
+ signal.removeEventListener("abort", cancel);
22554
+ }
22555
+ }
22556
+
22557
+ // src/acp/session-store.ts
22558
+ var AcpStoredSession = class {
22559
+ additionalDirectories;
22560
+ agentId;
22561
+ cwd;
22562
+ nativeSessionId;
22563
+ prompted;
22564
+ sessionId;
22565
+ constructor(sessionId, agentId, nativeSessionId, cwd, additionalDirectories, prompted) {
22566
+ this.additionalDirectories = [...additionalDirectories];
22567
+ this.agentId = agentId;
22568
+ this.cwd = cwd;
22569
+ this.nativeSessionId = nativeSessionId;
22570
+ this.prompted = prompted;
22571
+ this.sessionId = sessionId;
22572
+ }
22573
+ };
22574
+ var AcpStoredSessionLookup = class {
22575
+ };
22576
+ var MissingAcpStoredSession = class extends AcpStoredSessionLookup {
22577
+ found = false;
22578
+ };
22579
+ var FoundAcpStoredSession = class extends AcpStoredSessionLookup {
22580
+ found = true;
22581
+ session;
22582
+ constructor(session) {
22583
+ super();
22584
+ this.session = session;
22585
+ }
22586
+ };
22587
+ var DeletedAcpStoredSession = class extends AcpStoredSessionLookup {
22588
+ found = false;
22589
+ };
22590
+ var MemoryAcpSessionStore = class {
22591
+ #sessions = /* @__PURE__ */ new Map();
22592
+ #deleted = /* @__PURE__ */ new Set();
22593
+ findNative = (agentId, nativeSessionId) => [...this.#sessions.values()].filter(
22594
+ (session) => session.agentId === agentId && session.nativeSessionId === nativeSessionId
22595
+ );
22596
+ markDeleted = (agentId, nativeSessionId) => {
22597
+ const ids = this.findNative(agentId, nativeSessionId).map((session) => session.sessionId);
22598
+ for (const id of ids) {
22599
+ this.#sessions.delete(id);
22600
+ this.#deleted.add(id);
22601
+ }
22602
+ return ids;
22603
+ };
22604
+ read = (sessionId) => {
22605
+ if (this.#deleted.has(sessionId)) {
22606
+ return new DeletedAcpStoredSession();
22607
+ }
22608
+ const session = this.#sessions.get(sessionId);
22609
+ return session === void 0 ? new MissingAcpStoredSession() : new FoundAcpStoredSession(session);
22610
+ };
22611
+ remove = (sessionId) => {
22612
+ this.#sessions.delete(sessionId);
22613
+ };
22614
+ write = (session) => {
22615
+ this.#sessions.set(session.sessionId, session);
22616
+ };
22617
+ };
22618
+
22619
+ // src/acp/process-session.ts
22620
+ import { spawn as spawn2 } from "node:child_process";
22621
+ import {
22622
+ methods as methods3,
22623
+ ndJsonStream,
22624
+ PROTOCOL_VERSION,
22625
+ RequestError
22626
+ } from "@agentclientprotocol/sdk";
22627
+
22628
+ // src/authorization/local-raster.ts
22629
+ import { open as open2, readFile as readFile2, realpath as realpath2, stat as stat2 } from "node:fs/promises";
22630
+ import { basename, isAbsolute, normalize } from "node:path";
22631
+ import { fileURLToPath } from "node:url";
22632
+ var MAX_LOCAL_RASTER_BYTES = 128 * 1024 * 1024;
22633
+ var MAX_INLINE_RASTER_BYTES = 3e6;
22634
+ var PNG_SIGNATURE = Uint8Array.of(137, 80, 78, 71);
22635
+ var JPEG_SIGNATURE = Uint8Array.of(255, 216, 255);
22636
+ var GIF87_SIGNATURE = new TextEncoder().encode("GIF87a");
22637
+ var GIF89_SIGNATURE = new TextEncoder().encode("GIF89a");
22638
+ var RIFF_SIGNATURE = new TextEncoder().encode("RIFF");
22639
+ var WEBP_SIGNATURE = new TextEncoder().encode("WEBP");
22640
+ var LocalRasterImage = class {
22641
+ bytes;
22642
+ mimeType;
22643
+ name;
22644
+ sourceUri;
22645
+ constructor(name, mimeType, bytes, sourceUri = "") {
22646
+ this.bytes = bytes;
22647
+ this.mimeType = mimeType;
22648
+ this.name = name;
22649
+ this.sourceUri = sourceUri;
22650
+ }
22651
+ base64 = async () => {
22652
+ const bytes = this.bytes ?? new Uint8Array(await readFile2(this.sourceUri));
22653
+ return Buffer.from(bytes).toString("base64");
22654
+ };
22655
+ };
22656
+ function startsWith(bytes, signature, offset = 0) {
22657
+ if (bytes.byteLength < offset + signature.byteLength) {
22658
+ return false;
22659
+ }
22660
+ return signature.every((value, index2) => bytes[offset + index2] === value);
22661
+ }
22662
+ function sniffRasterMime(bytes) {
22663
+ if (startsWith(bytes, PNG_SIGNATURE)) {
22664
+ return "image/png";
22665
+ }
22666
+ if (startsWith(bytes, JPEG_SIGNATURE)) {
22667
+ return "image/jpeg";
22668
+ }
22669
+ if (startsWith(bytes, GIF87_SIGNATURE) || startsWith(bytes, GIF89_SIGNATURE)) {
22670
+ return "image/gif";
22671
+ }
22672
+ if (startsWith(bytes, RIFF_SIGNATURE) && startsWith(bytes, WEBP_SIGNATURE, 8)) {
22673
+ return "image/webp";
22674
+ }
22675
+ return null;
22676
+ }
22677
+ function readInlineRaster(data, name = "Image") {
22678
+ if (data.length === 0 || data.length > Math.ceil(MAX_INLINE_RASTER_BYTES / 3) * 4 || data.length % 4 !== 0) {
22679
+ return null;
22680
+ }
22681
+ if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(data)) {
22682
+ return null;
22683
+ }
22684
+ const bytes = new Uint8Array(Buffer.from(data, "base64"));
22685
+ if (bytes.byteLength < 1 || bytes.byteLength > MAX_INLINE_RASTER_BYTES) {
22686
+ return null;
22687
+ }
22688
+ const mimeType = sniffRasterMime(bytes);
22689
+ if (mimeType === null) {
22690
+ return null;
22691
+ }
22692
+ return new LocalRasterImage(basename(name) || "Image", mimeType, bytes);
22693
+ }
22694
+ async function resolveCanonicalPath(requested, signal) {
22695
+ signal.throwIfAborted();
22696
+ if (!isAbsolute(requested) || requested.includes("\0") || normalize(requested) !== requested) {
22697
+ return null;
22698
+ }
22699
+ try {
22700
+ const target = await realpath2(requested);
22701
+ signal.throwIfAborted();
22702
+ if (!isAbsolute(target) || normalize(target) !== target) {
22703
+ return null;
22704
+ }
22705
+ return target;
22706
+ } catch (cause) {
22707
+ signal.throwIfAborted();
22708
+ if (cause instanceof Error && cause.name === "AbortError") {
22709
+ throw cause;
22710
+ }
22711
+ return null;
22712
+ }
22713
+ }
22714
+ function parseLocalImageUri(uri) {
22715
+ const trimmed = uri.trim();
22716
+ if (trimmed.length === 0 || trimmed.length > 2048 || trimmed.includes("\0")) {
22717
+ return null;
22718
+ }
22719
+ if (trimmed.startsWith("data:")) {
22720
+ return null;
22721
+ }
22722
+ if (trimmed.startsWith("file:")) {
22723
+ try {
22724
+ const url2 = new URL(trimmed);
22725
+ if (url2.protocol !== "file:" || url2.host.length > 0) {
22726
+ return null;
22727
+ }
22728
+ return fileURLToPath(url2);
22729
+ } catch {
22730
+ return null;
22731
+ }
22732
+ }
22733
+ if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(trimmed)) {
22734
+ return null;
22735
+ }
22736
+ return trimmed;
22737
+ }
22738
+ async function readLocalRaster(uri, signal) {
22739
+ signal.throwIfAborted();
22740
+ const requested = parseLocalImageUri(uri);
22741
+ if (requested === null) {
22742
+ return null;
22743
+ }
22744
+ const target = await resolveCanonicalPath(requested, signal);
22745
+ if (target === null) {
22746
+ return null;
22747
+ }
22748
+ const targetMetadata = await stat2(target);
22749
+ signal.throwIfAborted();
22750
+ if (!targetMetadata.isFile() || targetMetadata.size < 1 || targetMetadata.size > MAX_LOCAL_RASTER_BYTES) {
22751
+ return null;
22752
+ }
22753
+ const handle = await open2(target, "r");
22754
+ const header = new Uint8Array(12);
22755
+ try {
22756
+ await handle.read(header, 0, header.byteLength, 0);
22757
+ } finally {
22758
+ await handle.close();
22759
+ }
22760
+ signal.throwIfAborted();
22761
+ const mimeType = sniffRasterMime(header);
22762
+ if (mimeType === null) {
22763
+ return null;
22764
+ }
22765
+ return new LocalRasterImage(basename(target) || "Image", mimeType, null, target);
22766
+ }
22767
+
22768
+ // src/authorization/local-video.ts
22769
+ import { basename as basename2 } from "node:path";
22770
+ var MAX_INLINE_VIDEO_BYTES = 3e6;
22771
+ var MP4_FILE_TYPE = new TextEncoder().encode("ftyp");
22772
+ var WEBM_SIGNATURE = Uint8Array.of(26, 69, 223, 163);
22773
+ var LocalVideo = class {
22774
+ bytes;
22775
+ mimeType;
22776
+ name;
22777
+ constructor(name, mimeType, bytes) {
22778
+ this.bytes = bytes;
22779
+ this.mimeType = mimeType;
22780
+ this.name = name;
22781
+ }
22782
+ base64 = () => Buffer.from(this.bytes).toString("base64");
22783
+ };
22784
+ function startsWith2(bytes, signature, offset = 0) {
22785
+ if (bytes.byteLength < offset + signature.byteLength) {
22786
+ return false;
22787
+ }
22788
+ return signature.every((value, index2) => bytes[offset + index2] === value);
22789
+ }
22790
+ function sniffVideoMime(bytes) {
22791
+ if (startsWith2(bytes, MP4_FILE_TYPE, 4)) {
22792
+ return "video/mp4";
22793
+ }
22794
+ if (startsWith2(bytes, WEBM_SIGNATURE)) {
22795
+ return "video/webm";
22796
+ }
22797
+ return null;
22798
+ }
22799
+ function readInlineVideo(data, declaredMimeType, name = "Video") {
22800
+ if (data.length === 0 || data.length > Math.ceil(MAX_INLINE_VIDEO_BYTES / 3) * 4 || data.length % 4 !== 0) {
22801
+ return null;
22802
+ }
22803
+ if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(data)) {
22804
+ return null;
22805
+ }
22806
+ const bytes = new Uint8Array(Buffer.from(data, "base64"));
22807
+ if (bytes.byteLength < 1 || bytes.byteLength > MAX_INLINE_VIDEO_BYTES) {
22808
+ return null;
22809
+ }
22810
+ const mimeType = sniffVideoMime(bytes);
22811
+ if (mimeType === null || mimeType !== declaredMimeType) {
22812
+ return null;
22813
+ }
22814
+ return new LocalVideo(basename2(name) || "Video", mimeType, bytes);
22815
+ }
22816
+
22817
+ // src/native-sessions/history-images.ts
22818
+ var IMAGE_MARKER = /\[@image\]\(([^)\r\n]*)(?:\)|$)/g;
22819
+ async function embedLocalHistoryImages(history, signal) {
22820
+ if (history.status !== "available") {
22821
+ return history;
22822
+ }
22823
+ const messages = [];
22824
+ let imageCharacters = 0;
22825
+ for (const message of history.messages) {
22826
+ signal.throwIfAborted();
22827
+ const resolved = await resolveMessageImages(message, imageCharacters, signal);
22828
+ imageCharacters += (resolved.images ?? []).reduce((size, image) => size + image.data.length, 0);
22829
+ messages.push(resolved);
22830
+ }
22831
+ return {
22832
+ ...history,
22833
+ messages
22834
+ };
22835
+ }
22836
+ async function resolveMessageImages(message, usedCharacters, signal) {
22837
+ const images = [...message.images ?? []];
22838
+ let imageCharacters = images.reduce((size, image) => size + image.data.length, 0);
22839
+ const text3 = await replaceImageMarkers(message.text, async (uri) => {
22840
+ if (images.length >= 8 || usedCharacters + imageCharacters >= SESSION_HISTORY_IMAGE_CHARACTER_LIMIT) {
22841
+ return "[Image unavailable]";
22842
+ }
22843
+ const embedded = parseNativeHistoryText(`[@image](${uri})`).images[0];
22844
+ if (embedded !== void 0) {
22845
+ if (usedCharacters + imageCharacters + embedded.data.length > SESSION_HISTORY_IMAGE_CHARACTER_LIMIT) {
22846
+ return "[Image unavailable]";
22847
+ }
22848
+ images.push(embedded);
22849
+ imageCharacters += embedded.data.length;
22850
+ return "";
22851
+ }
22852
+ const local = await readLocalRaster(uri, signal);
22853
+ if (local === null) {
22854
+ return "[Image unavailable]";
22855
+ }
22856
+ const data = await local.base64();
22857
+ if (usedCharacters + imageCharacters + data.length > SESSION_HISTORY_IMAGE_CHARACTER_LIMIT) {
22858
+ return "[Image unavailable]";
22859
+ }
22860
+ images.push({
22861
+ data,
22862
+ mimeType: local.mimeType,
22863
+ name: local.name
22864
+ });
22865
+ imageCharacters += data.length;
22866
+ return "";
22867
+ });
22868
+ return {
22869
+ ...message,
22870
+ text: text3,
22871
+ ...images.length > 0 ? { images } : {}
22872
+ };
22873
+ }
22874
+ async function replaceImageMarkers(text3, replace) {
22875
+ const matches = [...text3.matchAll(IMAGE_MARKER)];
22876
+ if (matches.length === 0) {
22877
+ return text3;
22878
+ }
22879
+ let cursor = 0;
22880
+ let rewritten = "";
22881
+ for (const match of matches) {
22882
+ const index2 = match.index ?? 0;
22883
+ rewritten += text3.slice(cursor, index2);
22884
+ rewritten += await replace(match[1] ?? "");
22885
+ cursor = index2 + match[0].length;
22886
+ }
22887
+ return `${rewritten}${text3.slice(cursor)}`;
22888
+ }
22889
+
22722
22890
  // src/acp/activity.ts
22723
22891
  var TRUNCATION_MARKER = "\n\u2026 output truncated by Mobius";
22724
22892
  var AcpActivityNarration = class {
@@ -23305,6 +23473,244 @@ var AcpActivityTracker = class {
23305
23473
  };
23306
23474
  };
23307
23475
 
23476
+ // src/acp/value-utils.ts
23477
+ function truncate2(value, maximumLength) {
23478
+ return value.length <= maximumLength ? value : `${value.slice(0, Math.max(0, maximumLength - 1))}\u2026`;
23479
+ }
23480
+ function isRecord4(value) {
23481
+ return typeof value === "object" && value !== null && !Array.isArray(value);
23482
+ }
23483
+ function readString2(value, fallback = "") {
23484
+ return typeof value === "string" ? value : fallback;
23485
+ }
23486
+
23487
+ // src/acp/elicitation.ts
23488
+ function elicitationFieldType(value) {
23489
+ if (value === "boolean") {
23490
+ return "boolean";
23491
+ }
23492
+ if (value === "integer") {
23493
+ return "integer";
23494
+ }
23495
+ if (value === "number") {
23496
+ return "number";
23497
+ }
23498
+ if (value === "array") {
23499
+ return "multiselect";
23500
+ }
23501
+ return "string";
23502
+ }
23503
+ function normalizeElicitationOptions(schema) {
23504
+ const normalized = [];
23505
+ const oneOf = schema["oneOf"];
23506
+ if (Array.isArray(oneOf)) {
23507
+ for (const option of oneOf) {
23508
+ if (isRecord4(option) && typeof option["const"] === "string") {
23509
+ normalized.push({
23510
+ description: truncate2(readString2(option["description"]), 500),
23511
+ label: truncate2(readString2(option["title"], option["const"]), 255),
23512
+ value: truncate2(option["const"], 500)
23513
+ });
23514
+ }
23515
+ }
23516
+ return normalized.slice(0, 200);
23517
+ }
23518
+ const enumValues = schema["enum"];
23519
+ if (Array.isArray(enumValues)) {
23520
+ for (const entry of enumValues) {
23521
+ if (typeof entry === "string") {
23522
+ normalized.push({ description: "", label: entry, value: entry });
23523
+ }
23524
+ }
23525
+ return normalized.slice(0, 200);
23526
+ }
23527
+ const items = schema["items"];
23528
+ if (!isRecord4(items)) {
23529
+ return normalized;
23530
+ }
23531
+ const anyOf = items["anyOf"];
23532
+ if (Array.isArray(anyOf)) {
23533
+ return normalizeElicitationOptions({ oneOf: anyOf });
23534
+ }
23535
+ return normalizeElicitationOptions({ enum: items["enum"] });
23536
+ }
23537
+ function numericString(value) {
23538
+ return typeof value === "number" && Number.isFinite(value) ? value.toString() : "";
23539
+ }
23540
+ function normalizeElicitationFields(requestedSchema) {
23541
+ if (!isRecord4(requestedSchema) || !isRecord4(requestedSchema["properties"])) {
23542
+ return [];
23543
+ }
23544
+ const properties = requestedSchema["properties"];
23545
+ const requiredValues = requestedSchema["required"];
23546
+ const required2 = new Set(
23547
+ Array.isArray(requiredValues) ? requiredValues.filter((entry) => typeof entry === "string") : []
23548
+ );
23549
+ const normalized = [];
23550
+ for (const [name, property] of Object.entries(properties)) {
23551
+ if (!isRecord4(property)) {
23552
+ continue;
23553
+ }
23554
+ const type = elicitationFieldType(property["type"]);
23555
+ const options = normalizeElicitationOptions(property);
23556
+ const normalizedType = type === "string" && options.length > 0 ? "select" : type;
23557
+ const defaultValue = property["default"];
23558
+ normalized.push({
23559
+ defaultBooleanValue: typeof defaultValue === "boolean" ? defaultValue : false,
23560
+ defaultNumberValue: typeof defaultValue === "number" && Number.isFinite(defaultValue) ? defaultValue : 0,
23561
+ defaultStringValue: typeof defaultValue === "string" ? truncate2(defaultValue, 1e4) : Array.isArray(defaultValue) ? truncate2(JSON.stringify(defaultValue), 1e4) : "",
23562
+ description: truncate2(readString2(property["description"]), 500),
23563
+ format: truncate2(readString2(property["format"]), 64),
23564
+ hasDefaultValue: defaultValue !== void 0 && defaultValue !== null,
23565
+ maximum: numericString(property["maximum"]),
23566
+ maximumLength: numericString(property["maxLength"] ?? property["maxItems"]),
23567
+ minimum: numericString(property["minimum"]),
23568
+ minimumLength: numericString(property["minLength"] ?? property["minItems"]),
23569
+ name: truncate2(name, 128),
23570
+ options,
23571
+ pattern: truncate2(readString2(property["pattern"]), 500),
23572
+ required: required2.has(name),
23573
+ title: truncate2(readString2(property["title"], name), 255),
23574
+ type: normalizedType
23575
+ });
23576
+ }
23577
+ return normalized.slice(0, 100);
23578
+ }
23579
+ function validateStringValue(name, value, schema) {
23580
+ const minimum = schema["minLength"];
23581
+ const maximum = schema["maxLength"];
23582
+ if (typeof minimum === "number" && value.length < minimum) {
23583
+ throw new AcpExecutionError(
23584
+ `Elicitation field ${name} is shorter than allowed`,
23585
+ {},
23586
+ "invalid_elicitation_response"
23587
+ );
23588
+ }
23589
+ if (typeof maximum === "number" && value.length > maximum) {
23590
+ throw new AcpExecutionError(
23591
+ `Elicitation field ${name} is longer than allowed`,
23592
+ {},
23593
+ "invalid_elicitation_response"
23594
+ );
23595
+ }
23596
+ const pattern = schema["pattern"];
23597
+ if (typeof pattern === "string" && !new RegExp(pattern, "u").test(value)) {
23598
+ throw new AcpExecutionError(
23599
+ `Elicitation field ${name} does not match the required format`,
23600
+ {},
23601
+ "invalid_elicitation_response"
23602
+ );
23603
+ }
23604
+ const allowed = normalizeElicitationOptions(schema);
23605
+ if (allowed.length > 0 && !allowed.some((entry) => entry.value === value)) {
23606
+ throw new AcpExecutionError(
23607
+ `Elicitation field ${name} is not an allowed value`,
23608
+ {},
23609
+ "invalid_elicitation_response"
23610
+ );
23611
+ }
23612
+ }
23613
+ function validateNumericValue(name, value, schema, integer2) {
23614
+ if (!Number.isFinite(value) || integer2 && !Number.isInteger(value)) {
23615
+ throw new AcpExecutionError(
23616
+ `Elicitation field ${name} is not a valid number`,
23617
+ {},
23618
+ "invalid_elicitation_response"
23619
+ );
23620
+ }
23621
+ const minimum = schema["minimum"];
23622
+ const maximum = schema["maximum"];
23623
+ if (typeof minimum === "number" && value < minimum || typeof maximum === "number" && value > maximum) {
23624
+ throw new AcpExecutionError(
23625
+ `Elicitation field ${name} is outside the allowed range`,
23626
+ {},
23627
+ "invalid_elicitation_response"
23628
+ );
23629
+ }
23630
+ }
23631
+ function validateElicitationContent(encoded, requestedSchema) {
23632
+ let decoded;
23633
+ try {
23634
+ decoded = JSON.parse(encoded);
23635
+ } catch (error62) {
23636
+ throw new AcpExecutionError(
23637
+ "Elicitation response is not valid JSON",
23638
+ { cause: error62 },
23639
+ "invalid_elicitation_response"
23640
+ );
23641
+ }
23642
+ if (!isRecord4(decoded) || !isRecord4(requestedSchema) || !isRecord4(requestedSchema["properties"])) {
23643
+ throw new AcpExecutionError(
23644
+ "Elicitation response does not match the requested form",
23645
+ {},
23646
+ "invalid_elicitation_response"
23647
+ );
23648
+ }
23649
+ const properties = requestedSchema["properties"];
23650
+ const requiredValue = requestedSchema["required"];
23651
+ const required2 = new Set(
23652
+ Array.isArray(requiredValue) ? requiredValue.filter((entry) => typeof entry === "string") : []
23653
+ );
23654
+ for (const name of required2) {
23655
+ if (!(name in decoded)) {
23656
+ throw new AcpExecutionError(`Elicitation field ${name} is required`, {}, "invalid_elicitation_response");
23657
+ }
23658
+ }
23659
+ const validated = {};
23660
+ for (const [name, value] of Object.entries(decoded)) {
23661
+ const property = properties[name];
23662
+ if (!isRecord4(property)) {
23663
+ throw new AcpExecutionError(
23664
+ `Elicitation field ${name} was not requested`,
23665
+ {},
23666
+ "invalid_elicitation_response"
23667
+ );
23668
+ }
23669
+ if (property["type"] === "string" && typeof value === "string") {
23670
+ validateStringValue(name, value, property);
23671
+ validated[name] = value;
23672
+ continue;
23673
+ }
23674
+ if (property["type"] === "number" && typeof value === "number") {
23675
+ validateNumericValue(name, value, property, false);
23676
+ validated[name] = value;
23677
+ continue;
23678
+ }
23679
+ if (property["type"] === "integer" && typeof value === "number") {
23680
+ validateNumericValue(name, value, property, true);
23681
+ validated[name] = value;
23682
+ continue;
23683
+ }
23684
+ if (property["type"] === "boolean" && typeof value === "boolean") {
23685
+ validated[name] = value;
23686
+ continue;
23687
+ }
23688
+ if (property["type"] === "array" && Array.isArray(value) && value.every((entry) => typeof entry === "string")) {
23689
+ const minimum = property["minItems"];
23690
+ const maximum = property["maxItems"];
23691
+ if (typeof minimum === "number" && value.length < minimum || typeof maximum === "number" && value.length > maximum) {
23692
+ throw new AcpExecutionError(
23693
+ `Elicitation field ${name} has an invalid selection count`,
23694
+ {},
23695
+ "invalid_elicitation_response"
23696
+ );
23697
+ }
23698
+ const allowed = normalizeElicitationOptions(property);
23699
+ if (allowed.length > 0 && value.some((entry) => !allowed.some((option) => option.value === entry))) {
23700
+ throw new AcpExecutionError(
23701
+ `Elicitation field ${name} contains an invalid selection`,
23702
+ {},
23703
+ "invalid_elicitation_response"
23704
+ );
23705
+ }
23706
+ validated[name] = value;
23707
+ continue;
23708
+ }
23709
+ throw new AcpExecutionError(`Elicitation field ${name} has the wrong type`, {}, "invalid_elicitation_response");
23710
+ }
23711
+ return validated;
23712
+ }
23713
+
23308
23714
  // src/acp/in-process/acp-endpoint.ts
23309
23715
  function acpEndpointTerminationError(termination) {
23310
23716
  switch (termination.kind) {
@@ -30530,13 +30936,13 @@ var SessionConfigProtocolError = class extends Error {
30530
30936
  this.name = "SessionConfigProtocolError";
30531
30937
  }
30532
30938
  };
30533
- function isRecord4(value) {
30939
+ function isRecord5(value) {
30534
30940
  return typeof value === "object" && value !== null && !Array.isArray(value);
30535
30941
  }
30536
- function readString2(value, fallback = "") {
30942
+ function readString3(value, fallback = "") {
30537
30943
  return typeof value === "string" ? value : fallback;
30538
30944
  }
30539
- function truncate2(value, maximum) {
30945
+ function truncate3(value, maximum) {
30540
30946
  return value.length <= maximum ? value : value.slice(0, maximum);
30541
30947
  }
30542
30948
  function readBoolean(value, fallback = false) {
@@ -30548,11 +30954,11 @@ function normalizeConfigValue(option, groupId = "", groupName = "") {
30548
30954
  return void 0;
30549
30955
  }
30550
30956
  return {
30551
- description: truncate2(readString2(option["description"]), 500),
30552
- groupId: truncate2(groupId, 128),
30553
- groupName: truncate2(groupName, 255),
30554
- name: truncate2(readString2(option["name"], value), 255),
30555
- value: truncate2(value, 500)
30957
+ description: truncate3(readString3(option["description"]), 500),
30958
+ groupId: truncate3(groupId, 128),
30959
+ groupName: truncate3(groupName, 255),
30960
+ name: truncate3(readString3(option["name"], value), 255),
30961
+ value: truncate3(value, 500)
30556
30962
  };
30557
30963
  }
30558
30964
  function normalizeConfigValues(value) {
@@ -30561,15 +30967,15 @@ function normalizeConfigValues(value) {
30561
30967
  }
30562
30968
  const normalized = [];
30563
30969
  for (const entry of value) {
30564
- if (!isRecord4(entry)) {
30970
+ if (!isRecord5(entry)) {
30565
30971
  continue;
30566
30972
  }
30567
30973
  const groupedOptions = entry["options"];
30568
30974
  if (Array.isArray(groupedOptions)) {
30569
- const groupId = readString2(entry["group"]);
30570
- const groupName = readString2(entry["name"]);
30975
+ const groupId = readString3(entry["group"]);
30976
+ const groupName = readString3(entry["name"]);
30571
30977
  for (const groupedOption of groupedOptions) {
30572
- if (isRecord4(groupedOption)) {
30978
+ if (isRecord5(groupedOption)) {
30573
30979
  const normalizedValue = normalizeConfigValue(groupedOption, groupId, groupName);
30574
30980
  if (normalizedValue !== void 0) {
30575
30981
  normalized.push(normalizedValue);
@@ -30589,12 +30995,12 @@ function normalizeConfigOptions(value, modes) {
30589
30995
  const normalized = [];
30590
30996
  if (Array.isArray(value)) {
30591
30997
  for (const option of value) {
30592
- if (!isRecord4(option)) {
30998
+ if (!isRecord5(option)) {
30593
30999
  continue;
30594
31000
  }
30595
- const id = truncate2(readString2(option["id"]), 128);
30596
- const name = truncate2(readString2(option["name"], id), 255);
30597
- const category = truncate2(readString2(option["category"]), 128);
31001
+ const id = truncate3(readString3(option["id"]), 128);
31002
+ const name = truncate3(readString3(option["name"], id), 255);
31003
+ const category = truncate3(readString3(option["category"]), 128);
30598
31004
  if (id.length === 0 || name.length === 0 || category === "_mobius_permission") {
30599
31005
  continue;
30600
31006
  }
@@ -30603,7 +31009,7 @@ function normalizeConfigOptions(value, modes) {
30603
31009
  booleanValue: readBoolean(option["currentValue"]),
30604
31010
  category,
30605
31011
  currentValue: "",
30606
- description: truncate2(readString2(option["description"]), 500),
31012
+ description: truncate3(readString3(option["description"]), 500),
30607
31013
  id,
30608
31014
  name,
30609
31015
  type: "boolean",
@@ -30613,13 +31019,13 @@ function normalizeConfigOptions(value, modes) {
30613
31019
  }
30614
31020
  if (option["type"] === "select") {
30615
31021
  const values = normalizeConfigValues(option["options"]);
30616
- const currentValue = truncate2(readString2(option["currentValue"]), 500);
31022
+ const currentValue = truncate3(readString3(option["currentValue"]), 500);
30617
31023
  if (values.some((entry) => entry.value === currentValue)) {
30618
31024
  normalized.push({
30619
31025
  booleanValue: false,
30620
31026
  category,
30621
31027
  currentValue,
30622
- description: truncate2(readString2(option["description"]), 500),
31028
+ description: truncate3(readString3(option["description"]), 500),
30623
31029
  id,
30624
31030
  name,
30625
31031
  type: "select",
@@ -30629,28 +31035,28 @@ function normalizeConfigOptions(value, modes) {
30629
31035
  }
30630
31036
  }
30631
31037
  }
30632
- if (isRecord4(modes)) {
31038
+ if (isRecord5(modes)) {
30633
31039
  const values = [];
30634
31040
  const availableModes = modes["availableModes"];
30635
31041
  if (Array.isArray(availableModes)) {
30636
31042
  for (const mode of availableModes) {
30637
- if (!isRecord4(mode)) {
31043
+ if (!isRecord5(mode)) {
30638
31044
  continue;
30639
31045
  }
30640
- const id = truncate2(readString2(mode["id"]), 500);
31046
+ const id = truncate3(readString3(mode["id"]), 500);
30641
31047
  if (id.length === 0) {
30642
31048
  continue;
30643
31049
  }
30644
31050
  values.push({
30645
- description: truncate2(readString2(mode["description"]), 500),
31051
+ description: truncate3(readString3(mode["description"]), 500),
30646
31052
  groupId: "",
30647
31053
  groupName: "",
30648
- name: truncate2(readString2(mode["name"], id), 255),
31054
+ name: truncate3(readString3(mode["name"], id), 255),
30649
31055
  value: id
30650
31056
  });
30651
31057
  }
30652
31058
  }
30653
- const currentValue = truncate2(readString2(modes["currentModeId"]), 500);
31059
+ const currentValue = truncate3(readString3(modes["currentModeId"]), 500);
30654
31060
  if (currentValue.length > 0 && values.some((entry) => entry.value === currentValue) && !normalized.some((entry) => entry.category === "mode")) {
30655
31061
  normalized.unshift({
30656
31062
  booleanValue: false,
@@ -30667,7 +31073,7 @@ function normalizeConfigOptions(value, modes) {
30667
31073
  return normalized.slice(0, MAXIMUM_CONFIG_OPTIONS);
30668
31074
  }
30669
31075
  function normalizeStandardLifecycle(response) {
30670
- const lifecycle = isRecord4(response) ? response : {};
31076
+ const lifecycle = isRecord5(response) ? response : {};
30671
31077
  return normalizeConfigOptions(lifecycle["configOptions"], lifecycle["modes"]);
30672
31078
  }
30673
31079
  function replaceStandardConfigOptions(current, value) {
@@ -30709,7 +31115,7 @@ var StandardSessionConfigProtocol = class {
30709
31115
  "ACP agent exited while changing session configuration",
30710
31116
  change.signal
30711
31117
  );
30712
- if (!isRecord4(response) || !Array.isArray(response["configOptions"])) {
31118
+ if (!isRecord5(response) || !Array.isArray(response["configOptions"])) {
30713
31119
  throw new SessionConfigProtocolError("The Agent returned an invalid session configuration response");
30714
31120
  }
30715
31121
  return replaceStandardConfigOptions(current, response["configOptions"]);
@@ -30929,216 +31335,11 @@ var AcpHistoryReplay = class {
30929
31335
  };
30930
31336
  };
30931
31337
 
30932
- // src/acp/session-store.ts
30933
- import { mkdirSync } from "node:fs";
30934
- import { dirname } from "node:path";
30935
- import { DatabaseSync } from "node:sqlite";
30936
- var AcpStoredSession = class {
30937
- additionalDirectories;
30938
- agentId;
30939
- cwd;
30940
- nativeSessionId;
30941
- prompted;
30942
- sessionId;
30943
- constructor(sessionId, agentId, nativeSessionId, cwd, additionalDirectories, prompted) {
30944
- this.additionalDirectories = [...additionalDirectories];
30945
- this.agentId = agentId;
30946
- this.cwd = cwd;
30947
- this.nativeSessionId = nativeSessionId;
30948
- this.prompted = prompted;
30949
- this.sessionId = sessionId;
30950
- }
30951
- };
30952
- var AcpStoredSessionLookup = class {
30953
- };
30954
- var MissingAcpStoredSession = class extends AcpStoredSessionLookup {
30955
- found = false;
30956
- };
30957
- var FoundAcpStoredSession = class extends AcpStoredSessionLookup {
30958
- found = true;
30959
- session;
30960
- constructor(session) {
30961
- super();
30962
- this.session = session;
30963
- }
30964
- };
30965
- var DeletedAcpStoredSession = class extends AcpStoredSessionLookup {
30966
- found = false;
30967
- };
30968
- function readString3(value, field) {
30969
- if (typeof value !== "string" || value.length === 0) {
30970
- throw new Error(`Stored ACP session has an invalid ${field}`);
30971
- }
30972
- return value;
30973
- }
30974
- function readAdditionalDirectories(value) {
30975
- if (typeof value !== "string") {
30976
- throw new Error("Stored ACP session has invalid additional directories");
30977
- }
30978
- const decoded = JSON.parse(value);
30979
- if (!Array.isArray(decoded) || decoded.some((directory) => typeof directory !== "string")) {
30980
- throw new Error("Stored ACP session has invalid additional directories");
30981
- }
30982
- return decoded;
30983
- }
30984
- function readPrompted(value) {
30985
- if (value === 0) {
30986
- return false;
30987
- }
30988
- if (value === 1) {
30989
- return true;
30990
- }
30991
- throw new Error("Stored ACP session has an invalid prompted state");
30992
- }
30993
- function decodeSessionRow(row) {
30994
- if (typeof row !== "object" || row === null || Array.isArray(row)) {
30995
- throw new Error("Stored ACP session is not an object");
30996
- }
30997
- return new AcpStoredSession(
30998
- readString3(Reflect.get(row, "session_id"), "session ID"),
30999
- readString3(Reflect.get(row, "agent_id"), "agent ID"),
31000
- readString3(Reflect.get(row, "native_session_id"), "native session ID"),
31001
- readString3(Reflect.get(row, "cwd"), "working directory"),
31002
- readAdditionalDirectories(Reflect.get(row, "additional_directories_json")),
31003
- readPrompted(Reflect.get(row, "prompted"))
31004
- );
31005
- }
31006
- var MemoryAcpSessionStore = class {
31007
- #sessions = /* @__PURE__ */ new Map();
31008
- #deleted = /* @__PURE__ */ new Set();
31009
- findNative = (agentId, nativeSessionId) => [...this.#sessions.values()].filter(
31010
- (session) => session.agentId === agentId && session.nativeSessionId === nativeSessionId
31011
- );
31012
- markDeleted = (agentId, nativeSessionId) => {
31013
- const ids = this.findNative(agentId, nativeSessionId).map((session) => session.sessionId);
31014
- for (const id of ids) {
31015
- this.#sessions.delete(id);
31016
- this.#deleted.add(id);
31017
- }
31018
- return ids;
31019
- };
31020
- read = (sessionId) => {
31021
- if (this.#deleted.has(sessionId)) {
31022
- return new DeletedAcpStoredSession();
31023
- }
31024
- const session = this.#sessions.get(sessionId);
31025
- return session === void 0 ? new MissingAcpStoredSession() : new FoundAcpStoredSession(session);
31026
- };
31027
- remove = (sessionId) => {
31028
- this.#sessions.delete(sessionId);
31029
- };
31030
- write = (session) => {
31031
- this.#sessions.set(session.sessionId, session);
31032
- };
31033
- };
31034
- var SqliteAcpSessionStore = class {
31035
- #database;
31036
- constructor(path2) {
31037
- mkdirSync(dirname(path2), { recursive: true });
31038
- this.#database = new DatabaseSync(path2);
31039
- this.#database.exec(`
31040
- CREATE TABLE IF NOT EXISTS acp_deleted_sessions (session_id TEXT PRIMARY KEY) STRICT;
31041
- CREATE TABLE IF NOT EXISTS acp_sessions (
31042
- session_id TEXT PRIMARY KEY,
31043
- agent_id TEXT NOT NULL,
31044
- native_session_id TEXT NOT NULL,
31045
- cwd TEXT NOT NULL,
31046
- additional_directories_json TEXT NOT NULL,
31047
- prompted INTEGER NOT NULL DEFAULT 0 CHECK (prompted IN (0, 1)),
31048
- updated_at TEXT NOT NULL
31049
- ) STRICT
31050
- `);
31051
- const columns = this.#database.prepare("PRAGMA table_info(acp_sessions)").all();
31052
- const hasPromptedColumn = columns.some(
31053
- (column) => typeof column === "object" && column !== null && Reflect.get(column, "name") === "prompted"
31054
- );
31055
- if (!hasPromptedColumn) {
31056
- this.#database.exec(`
31057
- ALTER TABLE acp_sessions
31058
- ADD COLUMN prompted INTEGER NOT NULL DEFAULT 1 CHECK (prompted IN (0, 1))
31059
- `);
31060
- }
31061
- }
31062
- read = (sessionId) => {
31063
- if (this.#database.prepare("SELECT session_id FROM acp_deleted_sessions WHERE session_id = ?").get(sessionId) !== void 0) {
31064
- return new DeletedAcpStoredSession();
31065
- }
31066
- const row = this.#database.prepare(
31067
- `
31068
- SELECT
31069
- session_id,
31070
- agent_id,
31071
- native_session_id,
31072
- cwd,
31073
- additional_directories_json,
31074
- prompted
31075
- FROM acp_sessions
31076
- WHERE session_id = ?
31077
- `
31078
- ).get(sessionId);
31079
- return row === void 0 ? new MissingAcpStoredSession() : new FoundAcpStoredSession(decodeSessionRow(row));
31080
- };
31081
- remove = (sessionId) => {
31082
- this.#database.prepare("DELETE FROM acp_sessions WHERE session_id = ?").run(sessionId);
31083
- };
31084
- findNative = (agentId, nativeSessionId) => this.#database.prepare("SELECT * FROM acp_sessions WHERE agent_id = ? AND native_session_id = ?").all(agentId, nativeSessionId).map(decodeSessionRow);
31085
- markDeleted = (agentId, nativeSessionId) => {
31086
- const ids = this.findNative(agentId, nativeSessionId).map((session) => session.sessionId);
31087
- this.#database.exec("BEGIN");
31088
- try {
31089
- for (const id of ids) {
31090
- this.#database.prepare("INSERT OR IGNORE INTO acp_deleted_sessions (session_id) VALUES (?)").run(id);
31091
- this.remove(id);
31092
- }
31093
- this.#database.exec("COMMIT");
31094
- return ids;
31095
- } catch (error62) {
31096
- this.#database.exec("ROLLBACK");
31097
- throw error62;
31098
- }
31099
- };
31100
- write = (session) => {
31101
- this.#database.prepare(
31102
- `
31103
- INSERT INTO acp_sessions (
31104
- session_id,
31105
- agent_id,
31106
- native_session_id,
31107
- cwd,
31108
- additional_directories_json,
31109
- prompted,
31110
- updated_at
31111
- ) VALUES (?, ?, ?, ?, ?, ?, ?)
31112
- ON CONFLICT(session_id) DO UPDATE SET
31113
- agent_id = excluded.agent_id,
31114
- native_session_id = excluded.native_session_id,
31115
- cwd = excluded.cwd,
31116
- additional_directories_json = excluded.additional_directories_json,
31117
- prompted = excluded.prompted,
31118
- updated_at = excluded.updated_at
31119
- `
31120
- ).run(
31121
- session.sessionId,
31122
- session.agentId,
31123
- session.nativeSessionId,
31124
- session.cwd,
31125
- JSON.stringify(session.additionalDirectories),
31126
- session.prompted ? 1 : 0,
31127
- (/* @__PURE__ */ new Date()).toISOString()
31128
- );
31129
- };
31130
- close = () => {
31131
- this.#database.close();
31132
- };
31133
- };
31134
-
31135
- // src/acp/session-manager.ts
31338
+ // src/acp/process-session.ts
31136
31339
  var PROCESS_STOP_TIMEOUT_MILLISECONDS = 1e3;
31137
- var MAX_ACP_PROCESSES = 10;
31138
31340
  var MAX_PRE_SESSION_UPDATES = 100;
31139
31341
  var MAX_PRE_SESSION_UPDATE_BYTES = 1024 * 1024;
31140
31342
  var SESSION_CONTROL_COMMAND_ID = "session-control";
31141
- var SESSION_CONTROL_TIMEOUT_MILLISECONDS = 3e4;
31142
31343
  function nativeHistoryNotRetained() {
31143
31344
  return {
31144
31345
  cause: {
@@ -31191,91 +31392,6 @@ var RetryableAcpInitializationError = class extends AcpExecutionError {
31191
31392
  this.name = "RetryableAcpInitializationError";
31192
31393
  }
31193
31394
  };
31194
- var AcpProcessCapacityLease = class {
31195
- #releaseCapacity;
31196
- #released = false;
31197
- constructor(releaseCapacity) {
31198
- this.#releaseCapacity = releaseCapacity;
31199
- }
31200
- release = () => {
31201
- if (this.#released) {
31202
- return;
31203
- }
31204
- this.#released = true;
31205
- this.#releaseCapacity();
31206
- };
31207
- };
31208
- var AcpProcessCapacityWaiter = class {
31209
- completion = Promise.withResolvers();
31210
- signal;
31211
- constructor(signal) {
31212
- this.signal = signal;
31213
- }
31214
- cancel = () => {
31215
- try {
31216
- this.signal.throwIfAborted();
31217
- } catch (error62) {
31218
- this.completion.reject(error62);
31219
- }
31220
- };
31221
- };
31222
- var AcpProcessCapacityLock = class {
31223
- #locked = false;
31224
- #waiters = [];
31225
- acquire = async (signal) => {
31226
- signal.throwIfAborted();
31227
- if (!this.#locked) {
31228
- this.#locked = true;
31229
- return new AcpProcessCapacityLease(this.#release);
31230
- }
31231
- const waiter = new AcpProcessCapacityWaiter(signal);
31232
- this.#waiters.push(waiter);
31233
- signal.addEventListener("abort", waiter.cancel, { once: true });
31234
- if (signal.aborted) {
31235
- waiter.cancel();
31236
- }
31237
- try {
31238
- return await waiter.completion.promise;
31239
- } finally {
31240
- signal.removeEventListener("abort", waiter.cancel);
31241
- const index2 = this.#waiters.indexOf(waiter);
31242
- if (index2 >= 0) {
31243
- this.#waiters.splice(index2, 1);
31244
- }
31245
- }
31246
- };
31247
- #release = () => {
31248
- while (this.#waiters.length > 0) {
31249
- const waiter = this.#waiters.shift();
31250
- if (waiter === void 0 || waiter.signal.aborted) {
31251
- continue;
31252
- }
31253
- waiter.completion.resolve(new AcpProcessCapacityLease(this.#release));
31254
- return;
31255
- }
31256
- this.#locked = false;
31257
- };
31258
- };
31259
- async function waitForAcpProcessCapacity(completion, signal) {
31260
- signal.throwIfAborted();
31261
- const cancelled = Promise.withResolvers();
31262
- const cancel = () => {
31263
- try {
31264
- signal.throwIfAborted();
31265
- } catch (error62) {
31266
- cancelled.reject(error62);
31267
- }
31268
- };
31269
- signal.addEventListener("abort", cancel, { once: true });
31270
- if (signal.aborted) {
31271
- cancel();
31272
- }
31273
- try {
31274
- await Promise.race([completion, cancelled.promise]);
31275
- } finally {
31276
- signal.removeEventListener("abort", cancel);
31277
- }
31278
- }
31279
31395
  function readableWebStream(input2) {
31280
31396
  let streamOpen = true;
31281
31397
  return new ReadableStream({
@@ -31351,15 +31467,6 @@ function createWritableAcpStream(output2) {
31351
31467
  }
31352
31468
  });
31353
31469
  }
31354
- function truncate3(value, maximumLength) {
31355
- return value.length <= maximumLength ? value : `${value.slice(0, Math.max(0, maximumLength - 1))}\u2026`;
31356
- }
31357
- function isRecord5(value) {
31358
- return typeof value === "object" && value !== null && !Array.isArray(value);
31359
- }
31360
- function readString4(value, fallback = "") {
31361
- return typeof value === "string" ? value : fallback;
31362
- }
31363
31470
  function arraysEqual(left, right) {
31364
31471
  return left.length === right.length && left.every((value, index2) => value === right[index2]);
31365
31472
  }
@@ -31368,231 +31475,6 @@ function recordsEqual(left, right) {
31368
31475
  const rightEntries = Object.entries(right);
31369
31476
  return leftEntries.length === rightEntries.length && leftEntries.every(([name, value]) => right[name] === value);
31370
31477
  }
31371
- function elicitationFieldType(value) {
31372
- if (value === "boolean") {
31373
- return "boolean";
31374
- }
31375
- if (value === "integer") {
31376
- return "integer";
31377
- }
31378
- if (value === "number") {
31379
- return "number";
31380
- }
31381
- if (value === "array") {
31382
- return "multiselect";
31383
- }
31384
- return "string";
31385
- }
31386
- function normalizeElicitationOptions(schema) {
31387
- const normalized = [];
31388
- const oneOf = schema["oneOf"];
31389
- if (Array.isArray(oneOf)) {
31390
- for (const option of oneOf) {
31391
- if (isRecord5(option) && typeof option["const"] === "string") {
31392
- normalized.push({
31393
- description: truncate3(readString4(option["description"]), 500),
31394
- label: truncate3(readString4(option["title"], option["const"]), 255),
31395
- value: truncate3(option["const"], 500)
31396
- });
31397
- }
31398
- }
31399
- return normalized.slice(0, 200);
31400
- }
31401
- const enumValues = schema["enum"];
31402
- if (Array.isArray(enumValues)) {
31403
- for (const entry of enumValues) {
31404
- if (typeof entry === "string") {
31405
- normalized.push({ description: "", label: entry, value: entry });
31406
- }
31407
- }
31408
- return normalized.slice(0, 200);
31409
- }
31410
- const items = schema["items"];
31411
- if (!isRecord5(items)) {
31412
- return normalized;
31413
- }
31414
- const anyOf = items["anyOf"];
31415
- if (Array.isArray(anyOf)) {
31416
- return normalizeElicitationOptions({ oneOf: anyOf });
31417
- }
31418
- return normalizeElicitationOptions({ enum: items["enum"] });
31419
- }
31420
- function numericString(value) {
31421
- return typeof value === "number" && Number.isFinite(value) ? value.toString() : "";
31422
- }
31423
- function normalizeElicitationFields(requestedSchema) {
31424
- if (!isRecord5(requestedSchema) || !isRecord5(requestedSchema["properties"])) {
31425
- return [];
31426
- }
31427
- const properties = requestedSchema["properties"];
31428
- const requiredValues = requestedSchema["required"];
31429
- const required2 = new Set(
31430
- Array.isArray(requiredValues) ? requiredValues.filter((entry) => typeof entry === "string") : []
31431
- );
31432
- const normalized = [];
31433
- for (const [name, property] of Object.entries(properties)) {
31434
- if (!isRecord5(property)) {
31435
- continue;
31436
- }
31437
- const type = elicitationFieldType(property["type"]);
31438
- const options = normalizeElicitationOptions(property);
31439
- const normalizedType = type === "string" && options.length > 0 ? "select" : type;
31440
- const defaultValue = property["default"];
31441
- normalized.push({
31442
- defaultBooleanValue: typeof defaultValue === "boolean" ? defaultValue : false,
31443
- defaultNumberValue: typeof defaultValue === "number" && Number.isFinite(defaultValue) ? defaultValue : 0,
31444
- defaultStringValue: typeof defaultValue === "string" ? truncate3(defaultValue, 1e4) : Array.isArray(defaultValue) ? truncate3(JSON.stringify(defaultValue), 1e4) : "",
31445
- description: truncate3(readString4(property["description"]), 500),
31446
- format: truncate3(readString4(property["format"]), 64),
31447
- hasDefaultValue: defaultValue !== void 0 && defaultValue !== null,
31448
- maximum: numericString(property["maximum"]),
31449
- maximumLength: numericString(property["maxLength"] ?? property["maxItems"]),
31450
- minimum: numericString(property["minimum"]),
31451
- minimumLength: numericString(property["minLength"] ?? property["minItems"]),
31452
- name: truncate3(name, 128),
31453
- options,
31454
- pattern: truncate3(readString4(property["pattern"]), 500),
31455
- required: required2.has(name),
31456
- title: truncate3(readString4(property["title"], name), 255),
31457
- type: normalizedType
31458
- });
31459
- }
31460
- return normalized.slice(0, 100);
31461
- }
31462
- function validateStringValue(name, value, schema) {
31463
- const minimum = schema["minLength"];
31464
- const maximum = schema["maxLength"];
31465
- if (typeof minimum === "number" && value.length < minimum) {
31466
- throw new AcpExecutionError(
31467
- `Elicitation field ${name} is shorter than allowed`,
31468
- {},
31469
- "invalid_elicitation_response"
31470
- );
31471
- }
31472
- if (typeof maximum === "number" && value.length > maximum) {
31473
- throw new AcpExecutionError(
31474
- `Elicitation field ${name} is longer than allowed`,
31475
- {},
31476
- "invalid_elicitation_response"
31477
- );
31478
- }
31479
- const pattern = schema["pattern"];
31480
- if (typeof pattern === "string" && !new RegExp(pattern, "u").test(value)) {
31481
- throw new AcpExecutionError(
31482
- `Elicitation field ${name} does not match the required format`,
31483
- {},
31484
- "invalid_elicitation_response"
31485
- );
31486
- }
31487
- const allowed = normalizeElicitationOptions(schema);
31488
- if (allowed.length > 0 && !allowed.some((entry) => entry.value === value)) {
31489
- throw new AcpExecutionError(
31490
- `Elicitation field ${name} is not an allowed value`,
31491
- {},
31492
- "invalid_elicitation_response"
31493
- );
31494
- }
31495
- }
31496
- function validateNumericValue(name, value, schema, integer2) {
31497
- if (!Number.isFinite(value) || integer2 && !Number.isInteger(value)) {
31498
- throw new AcpExecutionError(
31499
- `Elicitation field ${name} is not a valid number`,
31500
- {},
31501
- "invalid_elicitation_response"
31502
- );
31503
- }
31504
- const minimum = schema["minimum"];
31505
- const maximum = schema["maximum"];
31506
- if (typeof minimum === "number" && value < minimum || typeof maximum === "number" && value > maximum) {
31507
- throw new AcpExecutionError(
31508
- `Elicitation field ${name} is outside the allowed range`,
31509
- {},
31510
- "invalid_elicitation_response"
31511
- );
31512
- }
31513
- }
31514
- function validateElicitationContent(encoded, requestedSchema) {
31515
- let decoded;
31516
- try {
31517
- decoded = JSON.parse(encoded);
31518
- } catch (error62) {
31519
- throw new AcpExecutionError(
31520
- "Elicitation response is not valid JSON",
31521
- { cause: error62 },
31522
- "invalid_elicitation_response"
31523
- );
31524
- }
31525
- if (!isRecord5(decoded) || !isRecord5(requestedSchema) || !isRecord5(requestedSchema["properties"])) {
31526
- throw new AcpExecutionError(
31527
- "Elicitation response does not match the requested form",
31528
- {},
31529
- "invalid_elicitation_response"
31530
- );
31531
- }
31532
- const properties = requestedSchema["properties"];
31533
- const requiredValue = requestedSchema["required"];
31534
- const required2 = new Set(
31535
- Array.isArray(requiredValue) ? requiredValue.filter((entry) => typeof entry === "string") : []
31536
- );
31537
- for (const name of required2) {
31538
- if (!(name in decoded)) {
31539
- throw new AcpExecutionError(`Elicitation field ${name} is required`, {}, "invalid_elicitation_response");
31540
- }
31541
- }
31542
- const validated = {};
31543
- for (const [name, value] of Object.entries(decoded)) {
31544
- const property = properties[name];
31545
- if (!isRecord5(property)) {
31546
- throw new AcpExecutionError(
31547
- `Elicitation field ${name} was not requested`,
31548
- {},
31549
- "invalid_elicitation_response"
31550
- );
31551
- }
31552
- if (property["type"] === "string" && typeof value === "string") {
31553
- validateStringValue(name, value, property);
31554
- validated[name] = value;
31555
- continue;
31556
- }
31557
- if (property["type"] === "number" && typeof value === "number") {
31558
- validateNumericValue(name, value, property, false);
31559
- validated[name] = value;
31560
- continue;
31561
- }
31562
- if (property["type"] === "integer" && typeof value === "number") {
31563
- validateNumericValue(name, value, property, true);
31564
- validated[name] = value;
31565
- continue;
31566
- }
31567
- if (property["type"] === "boolean" && typeof value === "boolean") {
31568
- validated[name] = value;
31569
- continue;
31570
- }
31571
- if (property["type"] === "array" && Array.isArray(value) && value.every((entry) => typeof entry === "string")) {
31572
- const minimum = property["minItems"];
31573
- const maximum = property["maxItems"];
31574
- if (typeof minimum === "number" && value.length < minimum || typeof maximum === "number" && value.length > maximum) {
31575
- throw new AcpExecutionError(
31576
- `Elicitation field ${name} has an invalid selection count`,
31577
- {},
31578
- "invalid_elicitation_response"
31579
- );
31580
- }
31581
- const allowed = normalizeElicitationOptions(property);
31582
- if (allowed.length > 0 && value.some((entry) => !allowed.some((option) => option.value === entry))) {
31583
- throw new AcpExecutionError(
31584
- `Elicitation field ${name} contains an invalid selection`,
31585
- {},
31586
- "invalid_elicitation_response"
31587
- );
31588
- }
31589
- validated[name] = value;
31590
- continue;
31591
- }
31592
- throw new AcpExecutionError(`Elicitation field ${name} has the wrong type`, {}, "invalid_elicitation_response");
31593
- }
31594
- return validated;
31595
- }
31596
31478
  var AcpTurnState = class {
31597
31479
  };
31598
31480
  var IdleAcpTurn = class extends AcpTurnState {
@@ -32059,8 +31941,8 @@ var AcpProcessSession = class _AcpProcessSession {
32059
31941
  );
32060
31942
  }
32061
31943
  this.#capabilities = normalizeAcpCapabilities(initialized);
32062
- this.#agentName = truncate3(initialized.agentInfo?.title ?? initialized.agentInfo?.name ?? this.#agentId, 255);
32063
- this.#agentVersion = truncate3(
31944
+ this.#agentName = truncate2(initialized.agentInfo?.title ?? initialized.agentInfo?.name ?? this.#agentId, 255);
31945
+ this.#agentVersion = truncate2(
32064
31946
  this.#verifiedAgentVersion.length > 0 ? this.#verifiedAgentVersion : initialized.agentInfo?.version ?? "",
32065
31947
  128
32066
31948
  );
@@ -32292,6 +32174,17 @@ var AcpProcessSession = class _AcpProcessSession {
32292
32174
  );
32293
32175
  };
32294
32176
  nativeSessionId = () => this.#nativeSessionId;
32177
+ adoptNativeSessionId = (sessionId) => {
32178
+ if (this.#prompted || this.#nativeSessionId !== sessionId) {
32179
+ throw new AcpExecutionError("The new native Session cannot be adopted", {}, "session_identity_mismatch");
32180
+ }
32181
+ const previousSessionId = this.#mobiusSessionId;
32182
+ this.#store.write(
32183
+ new AcpStoredSession(sessionId, this.#agentId, sessionId, this.#cwd, this.#additionalDirectories, false)
32184
+ );
32185
+ this.#store.remove(previousSessionId);
32186
+ this.#mobiusSessionId = sessionId;
32187
+ };
32295
32188
  configure = async (options) => {
32296
32189
  const existing = this.#configOptions.find((option) => option.id === options.configId);
32297
32190
  if (existing === void 0 || existing.type !== options.valueType) {
@@ -32496,7 +32389,7 @@ var AcpProcessSession = class _AcpProcessSession {
32496
32389
  "ACP agent exited during steering",
32497
32390
  options.signal
32498
32391
  );
32499
- if (!isRecord5(response)) {
32392
+ if (!isRecord4(response)) {
32500
32393
  throw new AcpExecutionError(
32501
32394
  "ACP agent returned an invalid steering response",
32502
32395
  {},
@@ -32613,8 +32506,8 @@ var AcpProcessSession = class _AcpProcessSession {
32613
32506
  const interactionId = `permission-${crypto.randomUUID()}`;
32614
32507
  const options = request.options.slice(0, 20).map((option) => ({
32615
32508
  kind: option.kind,
32616
- name: truncate3(option.name, 255),
32617
- optionId: truncate3(option.optionId, 255)
32509
+ name: truncate2(option.name, 255),
32510
+ optionId: truncate2(option.optionId, 255)
32618
32511
  }));
32619
32512
  if (options.length === 0) {
32620
32513
  throw new AcpExecutionError(
@@ -32636,9 +32529,9 @@ var AcpProcessSession = class _AcpProcessSession {
32636
32529
  kind: SESSION_PERMISSION_REQUESTED_KIND,
32637
32530
  options,
32638
32531
  sessionId: this.#mobiusSessionId,
32639
- title: truncate3(request.toolCall.title ?? "Permission required", 500),
32640
- toolCallId: truncate3(request.toolCall.toolCallId, 255),
32641
- toolKind: truncate3(request.toolCall.kind ?? "other", 64)
32532
+ title: truncate2(request.toolCall.title ?? "Permission required", 500),
32533
+ toolCallId: truncate2(request.toolCall.toolCallId, 255),
32534
+ toolKind: truncate2(request.toolCall.kind ?? "other", 64)
32642
32535
  });
32643
32536
  return await pending.completion.promise;
32644
32537
  } finally {
@@ -32667,7 +32560,7 @@ var AcpProcessSession = class _AcpProcessSession {
32667
32560
  const schemaValue = Reflect.get(request, "requestedSchema");
32668
32561
  const requestedSchema = request.mode === "form" ? schemaValue : {};
32669
32562
  const elicitationIdValue = Reflect.get(request, "elicitationId");
32670
- const elicitationId = request.mode === "url" && typeof elicitationIdValue === "string" ? truncate3(elicitationIdValue, 255) : "";
32563
+ const elicitationId = request.mode === "url" && typeof elicitationIdValue === "string" ? truncate2(elicitationIdValue, 255) : "";
32671
32564
  const pending = new PendingElicitation(interactionId, elicitationId, requestedSchema);
32672
32565
  this.#pendingElicitations.set(interactionId, pending);
32673
32566
  const abort = () => {
@@ -32682,10 +32575,10 @@ var AcpProcessSession = class _AcpProcessSession {
32682
32575
  fields: normalizeElicitationFields(requestedSchema),
32683
32576
  interactionId,
32684
32577
  kind: SESSION_ELICITATION_REQUESTED_KIND,
32685
- message: truncate3(request.message, 2e3),
32578
+ message: truncate2(request.message, 2e3),
32686
32579
  mode: request.mode,
32687
32580
  sessionId: this.#mobiusSessionId,
32688
- url: request.mode === "url" && typeof Reflect.get(request, "url") === "string" ? truncate3(readString4(Reflect.get(request, "url")), 4096) : ""
32581
+ url: request.mode === "url" && typeof Reflect.get(request, "url") === "string" ? truncate2(readString2(Reflect.get(request, "url")), 4096) : ""
32689
32582
  });
32690
32583
  return await pending.completion.promise;
32691
32584
  } finally {
@@ -32763,14 +32656,14 @@ var AcpProcessSession = class _AcpProcessSession {
32763
32656
  );
32764
32657
  } else {
32765
32658
  await this.#turn.activities.finishNarrative();
32766
- await this.bufferAgentText(update.content.text, truncate3(update.messageId ?? "", 255));
32659
+ await this.bufferAgentText(update.content.text, truncate2(update.messageId ?? "", 255));
32767
32660
  }
32768
32661
  } else {
32769
32662
  await this.#turn.activities.finishNarrative();
32770
32663
  await this.flushAgentText();
32771
32664
  await this.emitAgentContent(
32772
32665
  normalizeContentBlock(update.content),
32773
- truncate3(update.messageId ?? "", 255)
32666
+ truncate2(update.messageId ?? "", 255)
32774
32667
  );
32775
32668
  }
32776
32669
  return;
@@ -32809,9 +32702,9 @@ var AcpProcessSession = class _AcpProcessSession {
32809
32702
  }
32810
32703
  if (update.sessionUpdate === "available_commands_update") {
32811
32704
  const commands = update.availableCommands.slice(0, 500).map((command) => ({
32812
- description: truncate3(command.description, 500),
32813
- inputHint: truncate3(command.input?.hint ?? "", 255),
32814
- name: truncate3(command.name, 128)
32705
+ description: truncate2(command.description, 500),
32706
+ inputHint: truncate2(command.input?.hint ?? "", 255),
32707
+ name: truncate2(command.name, 128)
32815
32708
  })).filter((command) => command.name.length > 0);
32816
32709
  this.#commands = commands;
32817
32710
  await this.#getObserver().onCommands({
@@ -32840,10 +32733,10 @@ var AcpProcessSession = class _AcpProcessSession {
32840
32733
  }
32841
32734
  if (update.sessionUpdate === "session_info_update") {
32842
32735
  if (Object.hasOwn(update, "title")) {
32843
- this.#sessionTitle = truncate3(update.title ?? "", 500);
32736
+ this.#sessionTitle = truncate2(update.title ?? "", 500);
32844
32737
  }
32845
32738
  if (Object.hasOwn(update, "updatedAt")) {
32846
- this.#sessionUpdatedAt = truncate3(update.updatedAt ?? "", 128);
32739
+ this.#sessionUpdatedAt = truncate2(update.updatedAt ?? "", 128);
32847
32740
  }
32848
32741
  await this.#getObserver().onInfo({
32849
32742
  kind: SESSION_INFO_UPDATED_KIND,
@@ -32856,7 +32749,7 @@ var AcpProcessSession = class _AcpProcessSession {
32856
32749
  if (update.sessionUpdate === "usage_update") {
32857
32750
  await this.#getObserver().onUsage({
32858
32751
  costAmount: update.cost?.amount ?? 0,
32859
- costCurrency: truncate3(update.cost?.currency ?? "", 16),
32752
+ costCurrency: truncate2(update.cost?.currency ?? "", 16),
32860
32753
  hasCost: update.cost !== void 0 && update.cost !== null,
32861
32754
  kind: SESSION_USAGE_UPDATED_KIND,
32862
32755
  sessionId: this.#mobiusSessionId,
@@ -32929,7 +32822,7 @@ var AcpProcessSession = class _AcpProcessSession {
32929
32822
  );
32930
32823
  }
32931
32824
  if (error62 instanceof RequestError) {
32932
- throw new AcpExecutionError(truncate3(error62.message, 500), { cause: error62 }, "acp_agent_error");
32825
+ throw new AcpExecutionError(truncate2(error62.message, 500), { cause: error62 }, "acp_agent_error");
32933
32826
  }
32934
32827
  throw error62;
32935
32828
  }
@@ -32998,6 +32891,10 @@ var AcpProcessSession = class _AcpProcessSession {
32998
32891
  }
32999
32892
  };
33000
32893
  };
32894
+
32895
+ // src/acp/session-manager.ts
32896
+ var MAX_ACP_PROCESSES = 10;
32897
+ var SESSION_CONTROL_TIMEOUT_MILLISECONDS = 3e4;
33001
32898
  var AcpProcessEvictionCandidate = class {
33002
32899
  };
33003
32900
  var MissingAcpProcessEvictionCandidate = class extends AcpProcessEvictionCandidate {
@@ -33045,16 +32942,17 @@ var AcpSessionManager = class {
33045
32942
  #transientProcessCount = 0;
33046
32943
  #store;
33047
32944
  #nativeHistoryReader;
32945
+ #sessionIdentity;
33048
32946
  #observer;
33049
- constructor(observer = new NullAcpSessionObserver(), store = new MemoryAcpSessionStore(), nativeHistoryReader = null) {
32947
+ constructor(observer = new NullAcpSessionObserver(), store = new MemoryAcpSessionStore(), nativeHistoryReader = null, sessionIdentity = "assigned") {
33050
32948
  this.#observer = observer;
33051
32949
  this.#store = store;
33052
32950
  this.#nativeHistoryReader = nativeHistoryReader;
32951
+ this.#sessionIdentity = sessionIdentity;
33053
32952
  }
33054
32953
  setObserver = (observer) => {
33055
32954
  this.#observer = observer;
33056
32955
  };
33057
- findLinkedSessions = (agentId, nativeSessionId) => this.#store.findNative(agentId, nativeSessionId);
33058
32956
  #notifyProcessCapacityChanged() {
33059
32957
  const changed = this.#processCapacityChanged;
33060
32958
  this.#processCapacityChanged = Promise.withResolvers();
@@ -33162,7 +33060,13 @@ var AcpSessionManager = class {
33162
33060
  if (retained) {
33163
33061
  this.#sessions.delete(sessionId);
33164
33062
  }
33165
- await this.#retireProcess(runtime, retained, close);
33063
+ try {
33064
+ await this.#retireProcess(runtime, retained, close);
33065
+ } finally {
33066
+ if (retained && this.#sessionIdentity === "native") {
33067
+ this.#store.remove(sessionId);
33068
+ }
33069
+ }
33166
33070
  }
33167
33071
  async #retireNativeBrowserProcess(sessionId, runtime, close) {
33168
33072
  const retained = this.#nativeBrowserSessions.get(sessionId) === runtime;
@@ -33309,7 +33213,14 @@ var AcpSessionManager = class {
33309
33213
  try {
33310
33214
  return await this.#startRetainedSessionProcess(
33311
33215
  options,
33312
- async () => await AcpProcessSession.start(options, () => this.#observer, this.#store, metrics)
33216
+ async () => await AcpProcessSession.start(
33217
+ 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(
33218
+ options.sessionId
33219
+ ) && this.#store.read(options.sessionId) instanceof MissingAcpStoredSession ? { ...options, origin: { kind: "import", nativeSessionId: options.sessionId } } : options,
33220
+ () => this.#observer,
33221
+ this.#store,
33222
+ metrics
33223
+ )
33313
33224
  );
33314
33225
  } finally {
33315
33226
  this.#preparing.delete(options.sessionId);
@@ -33732,6 +33643,45 @@ var AcpSessionManager = class {
33732
33643
  ]);
33733
33644
  };
33734
33645
  hasPreparedSession = (sessionId, agentId, cwd, additionalDirectories) => this.#sessions.get(sessionId)?.belongsTo(agentId, cwd, additionalDirectories) === true;
33646
+ createNativeSession = async (options) => {
33647
+ const temporarySessionId = `new-${crypto.randomUUID()}`;
33648
+ const temporaryOptions = { ...options, sessionId: temporarySessionId };
33649
+ this.#beginSessionUse(temporarySessionId);
33650
+ try {
33651
+ const runtime = await this.#startPreparation(temporaryOptions);
33652
+ let adopted = false;
33653
+ try {
33654
+ const nativeSessionId = runtime.nativeSessionId();
33655
+ 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)) {
33656
+ throw new AcpExecutionError(
33657
+ "The Agent returned an invalid new Session ID",
33658
+ {},
33659
+ "invalid_native_session_response"
33660
+ );
33661
+ }
33662
+ runtime.adoptNativeSessionId(nativeSessionId);
33663
+ this.#sessions.delete(temporarySessionId);
33664
+ this.#sessions.set(nativeSessionId, runtime);
33665
+ this.#retainedProcesses.set(
33666
+ runtime,
33667
+ new FoundAcpSessionProcessEvictionCandidate(nativeSessionId, runtime)
33668
+ );
33669
+ adopted = true;
33670
+ return nativeSessionId;
33671
+ } finally {
33672
+ if (!adopted) {
33673
+ await this.#retireSessionProcess(
33674
+ temporarySessionId,
33675
+ runtime,
33676
+ async () => await runtime.closeProcess()
33677
+ );
33678
+ }
33679
+ }
33680
+ } finally {
33681
+ this.#store.remove(temporarySessionId);
33682
+ this.#endSessionUse(temporarySessionId);
33683
+ }
33684
+ };
33735
33685
  ensureSession = async (options) => {
33736
33686
  const existing = this.#sessions.get(options.sessionId);
33737
33687
  if (existing !== void 0) {
@@ -33825,6 +33775,25 @@ var AcpSessionManager = class {
33825
33775
  this.#endSessionUse(options.sessionId);
33826
33776
  }
33827
33777
  };
33778
+ loadLinkedSessionHistory = async (options) => {
33779
+ options.signal.throwIfAborted();
33780
+ const stored = this.#store.read(options.sessionId);
33781
+ if (!(stored instanceof FoundAcpStoredSession) || !stored.session.prompted) {
33782
+ return null;
33783
+ }
33784
+ const linked = stored.session;
33785
+ 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])) {
33786
+ throw new AcpExecutionError(
33787
+ "The session belongs to another Agent or workspace",
33788
+ {},
33789
+ "session_identity_mismatch"
33790
+ );
33791
+ }
33792
+ if (this.#nativeHistoryReader === null) {
33793
+ return await this.loadSessionHistory(options);
33794
+ }
33795
+ return await this.#nativeHistoryReader.read(options, linked.nativeSessionId);
33796
+ };
33828
33797
  openNativeSession = async (options, origin, loadHistory) => {
33829
33798
  const key = `${options.agent.id}:${origin.nativeSessionId}`;
33830
33799
  if (this.#nativeOperations.has(key)) {
@@ -34044,51 +34013,20 @@ async function runAcpPrompt(options) {
34044
34013
  }
34045
34014
 
34046
34015
  // src/audit/audit-store.ts
34047
- import { mkdirSync as mkdirSync2 } from "node:fs";
34048
- import { dirname as dirname2 } from "node:path";
34049
- import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
34016
+ var MAX_AUDIT_RECORDS = 1024;
34050
34017
  var AuditStore = class {
34051
- database;
34052
- constructor(path2) {
34053
- mkdirSync2(dirname2(path2), { recursive: true });
34054
- this.database = new DatabaseSync2(path2);
34055
- this.database.exec(`
34056
- CREATE TABLE IF NOT EXISTS audit_events (
34057
- id INTEGER PRIMARY KEY AUTOINCREMENT,
34058
- recorded_at TEXT NOT NULL,
34059
- event TEXT NOT NULL,
34060
- command_id TEXT NOT NULL,
34061
- session_id TEXT NOT NULL,
34062
- details_json TEXT NOT NULL DEFAULT '{}'
34063
- ) STRICT
34064
- `);
34065
- const columns = this.database.prepare("PRAGMA table_info(audit_events)").all();
34066
- if (!columns.some((column) => Reflect.get(column, "name") === "details_json")) {
34067
- this.database.exec("ALTER TABLE audit_events ADD COLUMN details_json TEXT NOT NULL DEFAULT '{}'");
34068
- }
34069
- }
34070
- record(record2) {
34071
- this.database.prepare(
34072
- `
34073
- INSERT INTO audit_events (
34074
- recorded_at,
34075
- event,
34076
- command_id,
34077
- session_id,
34078
- details_json
34079
- ) VALUES (?, ?, ?, ?, ?)
34080
- `
34081
- ).run(
34082
- (/* @__PURE__ */ new Date()).toISOString(),
34083
- record2.event,
34084
- record2.commandId,
34085
- record2.sessionId,
34086
- JSON.stringify(record2.details ?? {})
34018
+ #records = [];
34019
+ record = (record2) => {
34020
+ if (this.#records.length === MAX_AUDIT_RECORDS) {
34021
+ this.#records.shift();
34022
+ }
34023
+ this.#records.push(
34024
+ record2.details === void 0 ? { ...record2 } : { ...record2, details: { ...record2.details } }
34087
34025
  );
34088
- }
34089
- close() {
34090
- this.database.close();
34091
- }
34026
+ };
34027
+ close = () => {
34028
+ this.#records.length = 0;
34029
+ };
34092
34030
  };
34093
34031
 
34094
34032
  // src/authorization/local-authorization-error.ts
@@ -34214,7 +34152,7 @@ var LocalAgentInventory = class {
34214
34152
 
34215
34153
  // src/agent-installation/managed-npm-package.ts
34216
34154
  import { mkdir, mkdtemp, open as open3, realpath as realpath3, rename, rm, stat as stat3 } from "node:fs/promises";
34217
- import { delimiter, dirname as dirname3, isAbsolute as isAbsolute2, join as join4, relative, sep } from "node:path";
34155
+ import { delimiter, dirname, isAbsolute as isAbsolute2, join as join4, relative, sep } from "node:path";
34218
34156
  var INSTALL_TIMEOUT_MILLISECONDS = 5 * 60 * 1e3;
34219
34157
  var PACKAGE_METADATA_LIMIT_BYTES = 64 * 1024;
34220
34158
  var PACKAGE_LOCK_LIMIT_BYTES = 8 * 1024 * 1024;
@@ -34444,7 +34382,7 @@ var ManagedNpmPackageInstaller = class {
34444
34382
  throw error62;
34445
34383
  }
34446
34384
  }
34447
- const parent = dirname3(root);
34385
+ const parent = dirname(root);
34448
34386
  await mkdir(parent, { mode: 448, recursive: true });
34449
34387
  const staging = await mkdtemp(join4(parent, `.${definition2.version}.staging-`));
34450
34388
  try {
@@ -34479,7 +34417,7 @@ var ManagedNpmPackageInstaller = class {
34479
34417
  NPM_CONFIG_IGNORE_SCRIPTS: "true",
34480
34418
  NPM_CONFIG_PACKAGE_LOCK: "true",
34481
34419
  NPM_CONFIG_REGISTRY: "https://registry.npmjs.org/",
34482
- PATH: `${dirname3(process.execPath)}${delimiter}/usr/bin${delimiter}/bin`
34420
+ PATH: `${dirname(process.execPath)}${delimiter}/usr/bin${delimiter}/bin`
34483
34421
  };
34484
34422
  if (definition2.includeOptionalDependencies) {
34485
34423
  installEnvironment["NPM_CONFIG_INCLUDE"] = "optional";
@@ -35344,18 +35282,17 @@ function effortValues(model) {
35344
35282
  }
35345
35283
  function modelSetting(models, currentValue) {
35346
35284
  const values = modelValues(models);
35347
- const current = currentValue.length > 0 ? currentValue : models.find((model) => model.isDefault === true)?.id ?? values[0]?.value ?? "";
35285
+ const current = values.some((value) => value.value === currentValue) ? currentValue : models.find((model) => model.isDefault === true)?.id ?? values[0]?.value ?? "";
35348
35286
  if (current.length === 0) {
35349
35287
  return null;
35350
35288
  }
35351
- const options = values.some((value) => value.value === current) ? values : [{ description: "", name: current, value: current }, ...values];
35352
35289
  return {
35353
35290
  category: "model",
35354
35291
  currentValue: current,
35355
35292
  description: "Model Codex uses for the session",
35356
35293
  id: MODEL_SETTING_ID,
35357
35294
  name: "Model",
35358
- options,
35295
+ options: values,
35359
35296
  type: "select"
35360
35297
  };
35361
35298
  }
@@ -36643,7 +36580,7 @@ import { join as join10 } from "node:path";
36643
36580
  import { createHash } from "node:crypto";
36644
36581
  import { createReadStream } from "node:fs";
36645
36582
  import { chmod, copyFile, mkdir as mkdir3, mkdtemp as mkdtemp2, open as open4, realpath as realpath6, rename as rename2, rm as rm2, stat as stat5, writeFile as writeFile2 } from "node:fs/promises";
36646
- import { delimiter as delimiter2, dirname as dirname4, isAbsolute as isAbsolute6, join as join9, relative as relative3, sep as sep3 } from "node:path";
36583
+ import { delimiter as delimiter2, dirname as dirname2, isAbsolute as isAbsolute6, join as join9, relative as relative3, sep as sep3 } from "node:path";
36647
36584
 
36648
36585
  // src/agent-installation/verified-download.ts
36649
36586
  import { fetch } from "undici";
@@ -37943,7 +37880,7 @@ async function discoverLocalAgentInventory(options) {
37943
37880
  // src/storage/runtime-installation-store.ts
37944
37881
  import { createHash as createHash2, randomUUID } from "node:crypto";
37945
37882
  import { mkdir as mkdir4, open as open5, readdir as readdir2, rename as rename3, unlink, writeFile as writeFile3 } from "node:fs/promises";
37946
- import { dirname as dirname5, join as join15, resolve as resolve4 } from "node:path";
37883
+ import { dirname as dirname3, join as join15, resolve as resolve4 } from "node:path";
37947
37884
  var APPLICATION_ID_PATTERN = /^[a-z][a-z0-9]*(?:[.-][a-z0-9]+){1,31}$/;
37948
37885
  var CONNECTION_ID_PATTERN = /^mcn_[a-f0-9]{32}$/;
37949
37886
  var INSTALLATION_ID_PATTERN = /^min_[a-f0-9]{32}$/;
@@ -38284,7 +38221,7 @@ async function readJsonFile(path2, signal, missingCode) {
38284
38221
  }
38285
38222
  async function writeJsonAtomically(path2, value, signal) {
38286
38223
  signal.throwIfAborted();
38287
- const directory = dirname5(path2);
38224
+ const directory = dirname3(path2);
38288
38225
  const temporaryPath = join15(directory, `.${randomUUID()}.tmp`);
38289
38226
  try {
38290
38227
  await mkdir4(directory, { mode: 448, recursive: true });
@@ -38347,7 +38284,6 @@ var RuntimeInstallationStore = class _RuntimeInstallationStore {
38347
38284
  return new _RuntimeInstallationStore(applicationId, storedInstallationId, stateDirectory);
38348
38285
  };
38349
38286
  connectionPath = (connectionId2) => join15(this.#connectionDirectory, `${validateConnectionId(connectionId2)}.json`);
38350
- auditDatabasePath = (connectionId2) => join15(this.stateDirectory, "audit", `${validateConnectionId(connectionId2)}.sqlite`);
38351
38287
  channelIndexPath = (channelId) => join15(this.#channelDirectory, channelIndexFileName(validateIdentifier(channelId, "invalid_channel_id")));
38352
38288
  readConnection = async (connectionId2, signal) => {
38353
38289
  const stored = decodeConnection(
@@ -38786,7 +38722,6 @@ function buildPairedDaemon(installation, connection, defaultWorkspace, inventory
38786
38722
  config: createDaemonConfig(
38787
38723
  {
38788
38724
  defaultWorkspace,
38789
- auditDatabasePath: installation.auditDatabasePath(connection.connectionId),
38790
38725
  channelId: connection.channelId,
38791
38726
  relayUrl
38792
38727
  },
@@ -38905,215 +38840,671 @@ function isRuntimeRelayRevocation(closeCode, closeReason) {
38905
38840
  return closeCode === runtimeRevocationCloseCode && closeReason === runtimeRevocationCloseReason;
38906
38841
  }
38907
38842
 
38908
- // src/run-daemon.ts
38909
- import { createHash as createHash4, randomUUID as randomUUID4 } from "node:crypto";
38910
- import { basename as basename7 } from "node:path";
38911
- import { styleText } from "node:util";
38912
- import { fetch as fetch5, WebSocket as WebSocket2 } from "undici";
38913
-
38914
- // src/agent-catalog/agent-settings-adapter.ts
38915
- var AGENT_DEFAULT_VALUE = "agent_default";
38916
- var READ_ONLY_VALUE = "read-only";
38917
- var WORKSPACE_WRITE_VALUE = "workspace-write";
38918
- var DANGER_FULL_ACCESS_VALUE = "danger-full-access";
38919
- var DEEPSEEK_HARNESS_ACCESS_MODE_SETTING_ID = "dsh_access_mode";
38920
- var OPENCODE_PERMISSION_SETTING_ID = "opencode_permission";
38921
- var AgentSettingsConfigurationError = class extends Error {
38922
- code = "invalid_session_configuration";
38923
- constructor(message, options = {}) {
38924
- super(message, options);
38925
- this.name = "AgentSettingsConfigurationError";
38926
- }
38927
- };
38928
- var AgentSettingsLaunchSelectionResult = class {
38929
- agent;
38930
- handled;
38931
- constructor(agent, handled) {
38932
- this.agent = agent;
38933
- this.handled = handled;
38934
- }
38935
- };
38936
- var AppliedAgentLaunchSettings = class {
38937
- agent;
38938
- sessionConfigurations;
38939
- constructor(agent, sessionConfigurations) {
38940
- this.agent = agent;
38941
- this.sessionConfigurations = Object.freeze([...sessionConfigurations]);
38843
+ // src/run-daemon.ts
38844
+ import { randomUUID as randomUUID5 } from "node:crypto";
38845
+ import { basename as basename7 } from "node:path";
38846
+ import { styleText } from "node:util";
38847
+ import { fetch as fetch5, WebSocket as WebSocket2 } from "undici";
38848
+
38849
+ // src/acp/session-config/apply-session-configuration.ts
38850
+ import { randomUUID as randomUUID2 } from "node:crypto";
38851
+
38852
+ // src/agent-catalog/agent-settings-base.ts
38853
+ var AgentSettingsConfigurationError = class extends Error {
38854
+ code = "invalid_session_configuration";
38855
+ constructor(message, options = {}) {
38856
+ super(message, options);
38857
+ this.name = "AgentSettingsConfigurationError";
38858
+ }
38859
+ };
38860
+ var AgentSettingsLaunchSelectionResult = class {
38861
+ agent;
38862
+ handled;
38863
+ constructor(agent, handled) {
38864
+ this.agent = agent;
38865
+ this.handled = handled;
38866
+ }
38867
+ };
38868
+ var AppliedAgentLaunchSettings = class {
38869
+ agent;
38870
+ sessionConfigurations;
38871
+ constructor(agent, sessionConfigurations) {
38872
+ this.agent = agent;
38873
+ this.sessionConfigurations = Object.freeze([...sessionConfigurations]);
38874
+ }
38875
+ };
38876
+ var AgentSettingsAdapter = class {
38877
+ modelEffortResolution = AGENT_MODEL_EFFORT_RESOLUTION_ON_MODEL_SELECTION;
38878
+ applyLaunchSelection = (agent, _selection) => new AgentSettingsLaunchSelectionResult(agent, false);
38879
+ settings = (_agent) => [];
38880
+ };
38881
+ function selectValue(name, value, description) {
38882
+ return {
38883
+ description,
38884
+ groupId: "",
38885
+ groupName: "",
38886
+ name,
38887
+ value
38888
+ };
38889
+ }
38890
+ function selectSetting(id, name, description, currentValue, values) {
38891
+ return {
38892
+ booleanValue: false,
38893
+ category: "execution",
38894
+ currentValue,
38895
+ description,
38896
+ id,
38897
+ name,
38898
+ type: "select",
38899
+ values
38900
+ };
38901
+ }
38902
+ function selectedValue(selection, configId) {
38903
+ if (selection.configId !== configId || selection.valueType !== "select" || selection.booleanValue || selection.value.length === 0) {
38904
+ throw new AgentSettingsConfigurationError("The requested Agent setting is invalid");
38905
+ }
38906
+ return selection.value;
38907
+ }
38908
+ function validValue(values, value) {
38909
+ if (!values.some((candidate) => candidate.value === value)) {
38910
+ throw new AgentSettingsConfigurationError("The requested Agent setting is unavailable");
38911
+ }
38912
+ return value;
38913
+ }
38914
+
38915
+ // src/agent-catalog/agents/codex-settings-adapter.ts
38916
+ var CodexSettingsAdapter = class extends AgentSettingsAdapter {
38917
+ modelEffortResolution = AGENT_MODEL_EFFORT_RESOLUTION_COMPLETE;
38918
+ };
38919
+
38920
+ // src/agent-catalog/agents/deepseek-settings-adapter.ts
38921
+ var READ_ONLY_VALUE = "read-only";
38922
+ var WORKSPACE_WRITE_VALUE = "workspace-write";
38923
+ var DANGER_FULL_ACCESS_VALUE = "danger-full-access";
38924
+ var DEEPSEEK_HARNESS_ACCESS_MODE_SETTING_ID = "dsh_access_mode";
38925
+ var dshAccessModes = Object.freeze([
38926
+ selectValue("Read only", READ_ONLY_VALUE, "Allow inspection without local writes."),
38927
+ selectValue("Workspace write", WORKSPACE_WRITE_VALUE, "Allow changes in the selected workspace."),
38928
+ selectValue("Full access", DANGER_FULL_ACCESS_VALUE, "Allow unrestricted local execution.")
38929
+ ]);
38930
+ var DeepSeekHarnessSettingsAdapter = class extends AgentSettingsAdapter {
38931
+ settings = (agent) => {
38932
+ const configured = agent.environment["DSH_PERMISSION_MODE"] ?? WORKSPACE_WRITE_VALUE;
38933
+ return [
38934
+ selectSetting(
38935
+ DEEPSEEK_HARNESS_ACCESS_MODE_SETTING_ID,
38936
+ "Access mode",
38937
+ "Controls the local side effects allowed for this DeepSeek Harness session.",
38938
+ validValue(dshAccessModes, configured),
38939
+ dshAccessModes
38940
+ )
38941
+ ];
38942
+ };
38943
+ applyLaunchSelection = (agent, selection) => {
38944
+ if (selection.configId !== DEEPSEEK_HARNESS_ACCESS_MODE_SETTING_ID) {
38945
+ return new AgentSettingsLaunchSelectionResult(agent, false);
38946
+ }
38947
+ const value = validValue(dshAccessModes, selectedValue(selection, DEEPSEEK_HARNESS_ACCESS_MODE_SETTING_ID));
38948
+ return new AgentSettingsLaunchSelectionResult(
38949
+ agent.withEnvironment({ ...agent.environment, DSH_PERMISSION_MODE: value }),
38950
+ true
38951
+ );
38952
+ };
38953
+ };
38954
+
38955
+ // src/agent-catalog/agents/opencode-settings-adapter.ts
38956
+ var AGENT_DEFAULT_VALUE = "agent_default";
38957
+ var READ_ONLY_VALUE2 = "read-only";
38958
+ var WORKSPACE_WRITE_VALUE2 = "workspace-write";
38959
+ var DANGER_FULL_ACCESS_VALUE2 = "danger-full-access";
38960
+ var OPENCODE_PERMISSION_SETTING_ID = "opencode_permission";
38961
+ var openCodePermissionModes = Object.freeze([
38962
+ selectValue("Agent default", AGENT_DEFAULT_VALUE, "Keep OpenCode's existing permission policy."),
38963
+ selectValue("Read only", READ_ONLY_VALUE2, "Allow inspection without local writes."),
38964
+ selectValue("Workspace write", WORKSPACE_WRITE_VALUE2, "Allow changes in the selected workspace."),
38965
+ selectValue("Full access", DANGER_FULL_ACCESS_VALUE2, "Allow unrestricted local execution.")
38966
+ ]);
38967
+ function openCodeConfiguration(environment) {
38968
+ const encoded = environment["OPENCODE_CONFIG_CONTENT"];
38969
+ if (encoded === void 0 || encoded.length === 0) {
38970
+ return {};
38971
+ }
38972
+ let parsed;
38973
+ try {
38974
+ parsed = JSON.parse(encoded);
38975
+ } catch (cause) {
38976
+ throw new AgentSettingsConfigurationError("The OpenCode configuration is invalid", { cause });
38977
+ }
38978
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
38979
+ throw new AgentSettingsConfigurationError("The OpenCode configuration is invalid");
38980
+ }
38981
+ return Object.freeze({ ...parsed });
38982
+ }
38983
+ function openCodePermission(value) {
38984
+ if (value === READ_ONLY_VALUE2) {
38985
+ return {
38986
+ "*": "deny",
38987
+ glob: "allow",
38988
+ grep: "allow",
38989
+ lsp: "allow",
38990
+ read: "allow",
38991
+ skill: "allow"
38992
+ };
38993
+ }
38994
+ if (value === WORKSPACE_WRITE_VALUE2) {
38995
+ return {
38996
+ "*": "allow",
38997
+ external_directory: "ask"
38998
+ };
38999
+ }
39000
+ return "allow";
39001
+ }
39002
+ var OpenCodeSettingsAdapter = class extends AgentSettingsAdapter {
39003
+ settings = (agent) => {
39004
+ const currentValue = agent.environment["MOBIUS_OPENCODE_PERMISSION"] ?? AGENT_DEFAULT_VALUE;
39005
+ return [
39006
+ selectSetting(
39007
+ OPENCODE_PERMISSION_SETTING_ID,
39008
+ "Permissions",
39009
+ "Controls OpenCode's local permission policy.",
39010
+ validValue(openCodePermissionModes, currentValue),
39011
+ openCodePermissionModes
39012
+ )
39013
+ ];
39014
+ };
39015
+ applyLaunchSelection = (agent, selection) => {
39016
+ if (selection.configId !== OPENCODE_PERMISSION_SETTING_ID) {
39017
+ return new AgentSettingsLaunchSelectionResult(agent, false);
39018
+ }
39019
+ const value = validValue(openCodePermissionModes, selectedValue(selection, OPENCODE_PERMISSION_SETTING_ID));
39020
+ if (value === AGENT_DEFAULT_VALUE) {
39021
+ return new AgentSettingsLaunchSelectionResult(agent, true);
39022
+ }
39023
+ return new AgentSettingsLaunchSelectionResult(
39024
+ agent.withEnvironment({
39025
+ ...agent.environment,
39026
+ MOBIUS_OPENCODE_PERMISSION: value,
39027
+ OPENCODE_CONFIG_CONTENT: JSON.stringify({
39028
+ ...openCodeConfiguration(agent.environment),
39029
+ permission: openCodePermission(value)
39030
+ })
39031
+ }),
39032
+ true
39033
+ );
39034
+ };
39035
+ };
39036
+
39037
+ // src/agent-catalog/agent-settings-adapter.ts
39038
+ var genericAdapter = new AgentSettingsAdapter();
39039
+ var codexAdapter = new CodexSettingsAdapter();
39040
+ var deepSeekHarnessAdapter = new DeepSeekHarnessSettingsAdapter();
39041
+ var openCodeAdapter = new OpenCodeSettingsAdapter();
39042
+ function agentSettingsAdapterForAgent(agentId) {
39043
+ if (agentId === "codex") {
39044
+ return codexAdapter;
39045
+ }
39046
+ if (agentId === "deepseek-harness") {
39047
+ return deepSeekHarnessAdapter;
39048
+ }
39049
+ if (agentId === "opencode") {
39050
+ return openCodeAdapter;
39051
+ }
39052
+ return genericAdapter;
39053
+ }
39054
+ function applyAgentLaunchSettings(agent, selections) {
39055
+ const adapter = agentSettingsAdapterForAgent(agent.id);
39056
+ let selectedAgent = agent;
39057
+ const sessionConfigurations = [];
39058
+ for (const selection of selections) {
39059
+ const applied = adapter.applyLaunchSelection(selectedAgent, selection);
39060
+ selectedAgent = applied.agent;
39061
+ if (!applied.handled) {
39062
+ sessionConfigurations.push(selection);
39063
+ }
39064
+ }
39065
+ return new AppliedAgentLaunchSettings(selectedAgent, sessionConfigurations);
39066
+ }
39067
+
39068
+ // src/acp/session-config/apply-session-configuration.ts
39069
+ function invalidSessionConfiguration(message) {
39070
+ return new AcpExecutionError(message, {}, "invalid_session_configuration");
39071
+ }
39072
+ function agentForSessionConfiguration(agent, selections) {
39073
+ try {
39074
+ return applyAgentLaunchSettings(agent, selections);
39075
+ } catch (error62) {
39076
+ if (error62 instanceof Error) {
39077
+ throw invalidSessionConfiguration(error62.message);
39078
+ }
39079
+ throw error62;
39080
+ }
39081
+ }
39082
+ function validateSessionConfigurationSelection(option, selection) {
39083
+ if (option.type !== selection.valueType) {
39084
+ throw invalidSessionConfiguration(`The Agent setting ${selection.configId} changed type`);
39085
+ }
39086
+ if (option.type === "boolean") {
39087
+ if (selection.value.length > 0) {
39088
+ throw invalidSessionConfiguration(`The Agent setting ${selection.configId} has an invalid value`);
39089
+ }
39090
+ return;
39091
+ }
39092
+ if (selection.booleanValue) {
39093
+ throw invalidSessionConfiguration(`The Agent setting ${selection.configId} has an invalid value`);
39094
+ }
39095
+ if (!option.values.some((value) => value.value === selection.value)) {
39096
+ throw invalidSessionConfiguration(`The Agent setting ${selection.configId} has an unavailable value`);
39097
+ }
39098
+ }
39099
+ function sessionConfigurationSelectionIsAvailable(option, selection) {
39100
+ if (option.type !== selection.valueType) {
39101
+ return false;
39102
+ }
39103
+ if (option.type === "boolean") {
39104
+ return selection.value.length === 0;
39105
+ }
39106
+ return !selection.booleanValue && option.values.some((value) => value.value === selection.value);
39107
+ }
39108
+ function sessionConfigurationMatches(option, selection) {
39109
+ validateSessionConfigurationSelection(option, selection);
39110
+ return option.type === "boolean" ? option.booleanValue === selection.booleanValue : option.currentValue === selection.value;
39111
+ }
39112
+ function sessionConfigurationPriority(selection, options) {
39113
+ const option = options.find((candidate) => candidate.id === selection.configId);
39114
+ if (selection.configId === "model" || option?.category === "model") {
39115
+ return 0;
39116
+ }
39117
+ if (selection.configId === "reasoning_effort" || option?.category === "thought_level") {
39118
+ return 1;
39119
+ }
39120
+ if (option?.category === "model_config") {
39121
+ return 2;
39122
+ }
39123
+ return 3;
39124
+ }
39125
+ function assertAppliedSessionConfiguration(options, selections) {
39126
+ const selectionsById = new Map(selections.map((selection) => [selection.configId, selection]));
39127
+ for (const option of options) {
39128
+ const selection = selectionsById.get(option.id);
39129
+ if (selection === void 0 || !sessionConfigurationSelectionIsAvailable(option, selection)) {
39130
+ continue;
39131
+ }
39132
+ if (!sessionConfigurationMatches(option, selection)) {
39133
+ throw invalidSessionConfiguration(`The Turn configuration does not match Agent setting ${option.id}`);
39134
+ }
39135
+ }
39136
+ }
39137
+ function unavailableSessionConfigurationCategory(selection) {
39138
+ if (selection.configId === "model") {
39139
+ return "model";
39140
+ }
39141
+ if (selection.configId === "reasoning_effort") {
39142
+ return "thought_level";
39143
+ }
39144
+ return "unknown";
39145
+ }
39146
+ async function applySessionConfigurationSelection(sessions, audit, options, selection, agent, cwd, additionalDirectories, commandId, sessionId, signal) {
39147
+ const option = options.find((candidate) => candidate.id === selection.configId);
39148
+ if (option === void 0) {
39149
+ warnIgnoredSetting(
39150
+ audit,
39151
+ "session_configuration_setting_ignored",
39152
+ commandId,
39153
+ sessionId,
39154
+ agent.id,
39155
+ selection,
39156
+ unavailableSessionConfigurationCategory(selection),
39157
+ "setting_unavailable"
39158
+ );
39159
+ return options;
39160
+ }
39161
+ if (option.type !== selection.valueType) {
39162
+ warnIgnoredSetting(
39163
+ audit,
39164
+ "session_configuration_setting_ignored",
39165
+ commandId,
39166
+ sessionId,
39167
+ agent.id,
39168
+ selection,
39169
+ option.category,
39170
+ "setting_schema_mismatch"
39171
+ );
39172
+ return options;
39173
+ }
39174
+ if (option.type === "boolean" && selection.value.length > 0 || option.type === "select" && selection.booleanValue) {
39175
+ warnIgnoredSetting(
39176
+ audit,
39177
+ "session_configuration_setting_ignored",
39178
+ commandId,
39179
+ sessionId,
39180
+ agent.id,
39181
+ selection,
39182
+ option.category,
39183
+ "selection_schema_mismatch"
39184
+ );
39185
+ return options;
39186
+ }
39187
+ if (option.type === "select" && !option.values.some((value) => value.value === selection.value)) {
39188
+ warnIgnoredSetting(
39189
+ audit,
39190
+ "session_configuration_setting_ignored",
39191
+ commandId,
39192
+ sessionId,
39193
+ agent.id,
39194
+ selection,
39195
+ option.category,
39196
+ "value_unavailable"
39197
+ );
39198
+ return options;
39199
+ }
39200
+ if (sessionConfigurationMatches(option, selection)) {
39201
+ return options;
39202
+ }
39203
+ return await sessions.configureSession({
39204
+ additionalDirectories,
39205
+ agent,
39206
+ booleanValue: selection.booleanValue,
39207
+ configId: selection.configId,
39208
+ cwd,
39209
+ requestId: `cfg_${randomUUID2()}`,
39210
+ sessionId,
39211
+ signal,
39212
+ value: selection.value,
39213
+ valueType: selection.valueType
39214
+ });
39215
+ }
39216
+ async function applyCompleteSessionConfiguration(sessions, audit, initialOptions, selections, agent, cwd, additionalDirectories, commandId, sessionId, signal) {
39217
+ let options = initialOptions;
39218
+ const orderedSelections = selections.toSorted((left, right) => {
39219
+ const priority = sessionConfigurationPriority(left, initialOptions) - sessionConfigurationPriority(right, initialOptions);
39220
+ return priority === 0 ? left.configId.localeCompare(right.configId) : priority;
39221
+ });
39222
+ for (const selection of orderedSelections) {
39223
+ options = await applySessionConfigurationSelection(
39224
+ sessions,
39225
+ audit,
39226
+ options,
39227
+ selection,
39228
+ agent,
39229
+ cwd,
39230
+ additionalDirectories,
39231
+ commandId,
39232
+ sessionId,
39233
+ signal
39234
+ );
39235
+ }
39236
+ assertAppliedSessionConfiguration(options, selections);
39237
+ }
39238
+ function warnIgnoredSetting(audit, event, commandId, sessionId, agentId, selection, category, reason) {
39239
+ const details = {
39240
+ agentId,
39241
+ category,
39242
+ configId: selection.configId,
39243
+ reason,
39244
+ requestedValue: selection.value
39245
+ };
39246
+ audit.record({ commandId, details, event, sessionId });
39247
+ process.stderr.write(`Mobius daemon warning ${JSON.stringify({ commandId, event, sessionId, ...details })}
39248
+ `);
39249
+ }
39250
+
39251
+ // src/agent-catalog/discover-agent-settings.ts
39252
+ import { createHash as createHash3 } from "node:crypto";
39253
+ function isUnavailableModel(cause, modelSettingId, requestedModel) {
39254
+ return cause instanceof AcpConfigurationValueUnavailableError && cause.configId === modelSettingId && cause.requestedValue === requestedModel;
39255
+ }
39256
+ function unsupportedModelIds(unsupportedModels) {
39257
+ return [...new Set(unsupportedModels.map((item) => item.requestedValue))];
39258
+ }
39259
+ async function discoverAgentSettings(command, config2, directories, sessions, signal) {
39260
+ const agent = config2.catalog.find(command.agentId);
39261
+ const cwd = await directories.resolve(config2.bindingId, "default", signal);
39262
+ const inspectedBaseSnapshot = await sessions.inspectAgentSettings({
39263
+ additionalDirectories: [],
39264
+ agent,
39265
+ cwd,
39266
+ signal
39267
+ });
39268
+ const baseSnapshot = {
39269
+ agentName: inspectedBaseSnapshot.agentName,
39270
+ agentVersion: inspectedBaseSnapshot.agentVersion,
39271
+ configOptions: await discoverOpenCodeModelOptions(agent, cwd, inspectedBaseSnapshot.configOptions, signal)
39272
+ };
39273
+ const baseModel = modelOption(baseSnapshot.configOptions);
39274
+ const unsupportedModels = [];
39275
+ let selectedSnapshot = baseSnapshot;
39276
+ if (command.model !== void 0) {
39277
+ if (baseModel === void 0 || baseModel.type !== "select" || !baseModel.values.some((value) => value.value === command.model)) {
39278
+ unsupportedModels.push(
39279
+ new AcpConfigurationValueUnavailableError(
39280
+ baseModel?.id ?? "model",
39281
+ command.model,
39282
+ baseModel?.values.map((value) => value.value) ?? []
39283
+ )
39284
+ );
39285
+ } else {
39286
+ try {
39287
+ selectedSnapshot = await sessions.inspectAgentSettings({
39288
+ additionalDirectories: [],
39289
+ agent,
39290
+ cwd,
39291
+ model: command.model,
39292
+ signal
39293
+ });
39294
+ } catch (cause) {
39295
+ signal.throwIfAborted();
39296
+ if (!isUnavailableModel(cause, baseModel.id, command.model)) {
39297
+ throw cause;
39298
+ }
39299
+ unsupportedModels.push(cause);
39300
+ }
39301
+ }
38942
39302
  }
38943
- };
38944
- var AgentSettingsAdapter = class {
38945
- modelEffortResolution = AGENT_MODEL_EFFORT_RESOLUTION_ON_MODEL_SELECTION;
38946
- applyLaunchSelection = (agent, _selection) => new AgentSettingsLaunchSelectionResult(agent, false);
38947
- settings = (_agent) => [];
38948
- };
38949
- function selectValue(name, value, description) {
39303
+ const adapter = agentSettingsAdapterForAgent(agent.id);
39304
+ const modelEffort = await discoverModelEffort(
39305
+ command,
39306
+ agent,
39307
+ adapter.modelEffortResolution,
39308
+ baseSnapshot.configOptions,
39309
+ selectedSnapshot.configOptions,
39310
+ unsupportedModels,
39311
+ cwd,
39312
+ sessions,
39313
+ signal
39314
+ );
39315
+ const baseSettings = withoutUnsupportedModels(
39316
+ settingsFromSnapshot(agent, baseSnapshot.configOptions),
39317
+ baseModel?.id ?? "",
39318
+ modelEffort.unsupportedModelIds
39319
+ );
39320
+ const settings = withoutUnsupportedModels(
39321
+ settingsFromSnapshot(agent, selectedSnapshot.configOptions),
39322
+ baseModel?.id ?? "",
39323
+ modelEffort.unsupportedModelIds
39324
+ );
38950
39325
  return {
38951
- description,
38952
- groupId: "",
38953
- groupName: "",
38954
- name,
38955
- value
39326
+ event: {
39327
+ agentId: command.agentId,
39328
+ agentName: selectedSnapshot.agentName,
39329
+ agentVersion: selectedSnapshot.agentVersion,
39330
+ kind: AGENT_SETTINGS_DISCOVERED_KIND,
39331
+ modelEffort,
39332
+ requestId: command.requestId,
39333
+ settings,
39334
+ settingsRevision: settingsRevision(agent, baseSnapshot.agentVersion, baseSettings, modelEffort)
39335
+ },
39336
+ unsupportedModels
38956
39337
  };
38957
39338
  }
38958
- function selectSetting(id, name, description, currentValue, values) {
39339
+ function settingFromOption(option) {
38959
39340
  return {
38960
- booleanValue: false,
38961
- category: "execution",
38962
- currentValue,
38963
- description,
38964
- id,
38965
- name,
38966
- type: "select",
38967
- values
39341
+ booleanValue: option.booleanValue,
39342
+ category: option.category,
39343
+ defaultValue: option.type === "boolean" ? "" : option.currentValue,
39344
+ description: option.description,
39345
+ id: option.id,
39346
+ name: option.name,
39347
+ type: option.type,
39348
+ values: option.values
38968
39349
  };
38969
39350
  }
38970
- function selectedValue(selection, configId) {
38971
- if (selection.configId !== configId || selection.valueType !== "select" || selection.booleanValue || selection.value.length === 0) {
38972
- throw new AgentSettingsConfigurationError("The requested Agent setting is invalid");
39351
+ function settingsFromSnapshot(agent, configOptions) {
39352
+ const settings = [
39353
+ ...agentSettingsAdapterForAgent(agent.id).settings(agent).map(settingFromOption),
39354
+ ...configOptions.map(settingFromOption)
39355
+ ];
39356
+ const identifiers = /* @__PURE__ */ new Set();
39357
+ for (const setting of settings) {
39358
+ if (identifiers.has(setting.id)) {
39359
+ throw new AcpExecutionError(
39360
+ "The Agent returned duplicate setting identifiers",
39361
+ {},
39362
+ "invalid_session_configuration"
39363
+ );
39364
+ }
39365
+ identifiers.add(setting.id);
38973
39366
  }
38974
- return selection.value;
38975
- }
38976
- function validValue(values, value) {
38977
- if (!values.some((candidate) => candidate.value === value)) {
38978
- throw new AgentSettingsConfigurationError("The requested Agent setting is unavailable");
39367
+ if (settings.length > 128) {
39368
+ throw new AcpExecutionError("The Agent returned too many settings", {}, "invalid_session_configuration");
38979
39369
  }
38980
- return value;
39370
+ return settings;
38981
39371
  }
38982
- var dshAccessModes = Object.freeze([
38983
- selectValue("Read only", READ_ONLY_VALUE, "Allow inspection without local writes."),
38984
- selectValue("Workspace write", WORKSPACE_WRITE_VALUE, "Allow changes in the selected workspace."),
38985
- selectValue("Full access", DANGER_FULL_ACCESS_VALUE, "Allow unrestricted local execution.")
38986
- ]);
38987
- var DeepSeekHarnessSettingsAdapter = class extends AgentSettingsAdapter {
38988
- settings = (agent) => {
38989
- const configured = agent.environment["DSH_PERMISSION_MODE"] ?? WORKSPACE_WRITE_VALUE;
38990
- return [
38991
- selectSetting(
38992
- DEEPSEEK_HARNESS_ACCESS_MODE_SETTING_ID,
38993
- "Access mode",
38994
- "Controls the local side effects allowed for this DeepSeek Harness session.",
38995
- validValue(dshAccessModes, configured),
38996
- dshAccessModes
38997
- )
38998
- ];
38999
- };
39000
- applyLaunchSelection = (agent, selection) => {
39001
- if (selection.configId !== DEEPSEEK_HARNESS_ACCESS_MODE_SETTING_ID) {
39002
- return new AgentSettingsLaunchSelectionResult(agent, false);
39372
+ function withoutUnsupportedModels(settings, modelSettingId, unsupportedModelIds2) {
39373
+ if (modelSettingId.length === 0 || unsupportedModelIds2.length === 0) {
39374
+ return settings;
39375
+ }
39376
+ const unsupported = new Set(unsupportedModelIds2);
39377
+ return settings.map((setting) => {
39378
+ if (setting.id !== modelSettingId || setting.type !== "select") {
39379
+ return setting;
39003
39380
  }
39004
- const value = validValue(dshAccessModes, selectedValue(selection, DEEPSEEK_HARNESS_ACCESS_MODE_SETTING_ID));
39005
- return new AgentSettingsLaunchSelectionResult(
39006
- agent.withEnvironment({ ...agent.environment, DSH_PERMISSION_MODE: value }),
39007
- true
39008
- );
39381
+ return {
39382
+ ...setting,
39383
+ defaultValue: unsupported.has(setting.defaultValue) ? "" : setting.defaultValue,
39384
+ values: setting.values.filter((value) => !unsupported.has(value.value))
39385
+ };
39386
+ });
39387
+ }
39388
+ function modelOption(options) {
39389
+ return options.find((option) => option.id === "model" || option.category === "model");
39390
+ }
39391
+ function effortOption(options) {
39392
+ return options.find((option) => option.id === "reasoning_effort" || option.category === "thought_level");
39393
+ }
39394
+ function unavailableModelEffort() {
39395
+ return {
39396
+ effortSettingId: "",
39397
+ modelSettingId: "",
39398
+ resolution: AGENT_MODEL_EFFORT_RESOLUTION_UNAVAILABLE,
39399
+ unsupportedModelIds: [],
39400
+ valuesByModel: {}
39009
39401
  };
39010
- };
39011
- var openCodePermissionModes = Object.freeze([
39012
- selectValue("Agent default", AGENT_DEFAULT_VALUE, "Keep OpenCode's existing permission policy."),
39013
- selectValue("Read only", READ_ONLY_VALUE, "Allow inspection without local writes."),
39014
- selectValue("Workspace write", WORKSPACE_WRITE_VALUE, "Allow changes in the selected workspace."),
39015
- selectValue("Full access", DANGER_FULL_ACCESS_VALUE, "Allow unrestricted local execution.")
39016
- ]);
39017
- function openCodeConfiguration(environment) {
39018
- const encoded = environment["OPENCODE_CONFIG_CONTENT"];
39019
- if (encoded === void 0 || encoded.length === 0) {
39020
- return {};
39021
- }
39022
- let parsed;
39023
- try {
39024
- parsed = JSON.parse(encoded);
39025
- } catch (cause) {
39026
- throw new AgentSettingsConfigurationError("The OpenCode configuration is invalid", { cause });
39402
+ }
39403
+ async function discoverModelEffort(command, agent, resolution, initialOptions, selectedOptions, initiallyUnsupportedModels, cwd, sessions, signal) {
39404
+ const model = modelOption(initialOptions);
39405
+ const unsupportedModels = initiallyUnsupportedModels;
39406
+ if (resolution !== AGENT_MODEL_EFFORT_RESOLUTION_COMPLETE && resolution !== AGENT_MODEL_EFFORT_RESOLUTION_ON_MODEL_SELECTION) {
39407
+ return { ...unavailableModelEffort(), unsupportedModelIds: unsupportedModelIds(unsupportedModels) };
39027
39408
  }
39028
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
39029
- throw new AgentSettingsConfigurationError("The OpenCode configuration is invalid");
39409
+ if (model === void 0 || model.type !== "select" || model.values.length === 0) {
39410
+ return { ...unavailableModelEffort(), unsupportedModelIds: unsupportedModelIds(unsupportedModels) };
39030
39411
  }
39031
- return Object.freeze({ ...parsed });
39032
- }
39033
- function openCodePermission(value) {
39034
- if (value === READ_ONLY_VALUE) {
39412
+ const inspectModel = async (modelValue) => (await sessions.inspectAgentSettings({
39413
+ additionalDirectories: [],
39414
+ agent,
39415
+ cwd,
39416
+ model: modelValue,
39417
+ signal
39418
+ })).configOptions;
39419
+ const valuesByModel = {};
39420
+ if (resolution === "complete") {
39421
+ const effort = effortOption(initialOptions);
39422
+ if (effort === void 0 || effort.type !== "select" || effort.values.length < 2) {
39423
+ return {
39424
+ ...unavailableModelEffort(),
39425
+ unsupportedModelIds: unsupportedModelIds(unsupportedModels)
39426
+ };
39427
+ }
39428
+ for (const value of model.values) {
39429
+ if (unsupportedModels.some((diagnostic) => diagnostic.requestedValue === value.value)) {
39430
+ continue;
39431
+ }
39432
+ try {
39433
+ const selectedEffort2 = effortOption(await inspectModel(value.value));
39434
+ valuesByModel[value.value] = selectedEffort2?.type === "select" ? selectedEffort2.values : [];
39435
+ } catch (cause) {
39436
+ signal.throwIfAborted();
39437
+ if (!isUnavailableModel(cause, model.id, value.value)) {
39438
+ throw cause;
39439
+ }
39440
+ unsupportedModels.push(cause);
39441
+ }
39442
+ }
39035
39443
  return {
39036
- "*": "deny",
39037
- glob: "allow",
39038
- grep: "allow",
39039
- lsp: "allow",
39040
- read: "allow",
39041
- skill: "allow"
39444
+ effortSettingId: effort.id,
39445
+ modelSettingId: model.id,
39446
+ resolution: "complete",
39447
+ unsupportedModelIds: unsupportedModelIds(unsupportedModels),
39448
+ valuesByModel
39042
39449
  };
39043
39450
  }
39044
- if (value === WORKSPACE_WRITE_VALUE) {
39451
+ if (command.model !== void 0) {
39452
+ const modelUnsupported = unsupportedModels.some((diagnostic) => diagnostic.requestedValue === command.model);
39453
+ const selectedEffort2 = effortOption(selectedOptions);
39454
+ if (!modelUnsupported) {
39455
+ valuesByModel[command.model] = selectedEffort2?.type === "select" ? selectedEffort2.values : [];
39456
+ }
39045
39457
  return {
39046
- "*": "allow",
39047
- external_directory: "ask"
39458
+ effortSettingId: selectedEffort2?.id ?? "",
39459
+ modelSettingId: model.id,
39460
+ resolution: "on_model_selection",
39461
+ unsupportedModelIds: unsupportedModelIds(unsupportedModels),
39462
+ valuesByModel
39048
39463
  };
39049
39464
  }
39050
- return "allow";
39051
- }
39052
- var OpenCodeSettingsAdapter = class extends AgentSettingsAdapter {
39053
- settings = (agent) => {
39054
- const currentValue = agent.environment["MOBIUS_OPENCODE_PERMISSION"] ?? AGENT_DEFAULT_VALUE;
39055
- return [
39056
- selectSetting(
39057
- OPENCODE_PERMISSION_SETTING_ID,
39058
- "Permissions",
39059
- "Controls OpenCode's local permission policy.",
39060
- validValue(openCodePermissionModes, currentValue),
39061
- openCodePermissionModes
39062
- )
39063
- ];
39064
- };
39065
- applyLaunchSelection = (agent, selection) => {
39066
- if (selection.configId !== OPENCODE_PERMISSION_SETTING_ID) {
39067
- return new AgentSettingsLaunchSelectionResult(agent, false);
39068
- }
39069
- const value = validValue(openCodePermissionModes, selectedValue(selection, OPENCODE_PERMISSION_SETTING_ID));
39070
- if (value === AGENT_DEFAULT_VALUE) {
39071
- return new AgentSettingsLaunchSelectionResult(agent, true);
39465
+ const defaultModel = model.type === "select" ? model.currentValue : "";
39466
+ const reportedEffort = effortOption(selectedOptions);
39467
+ let selectedEffort = reportedEffort;
39468
+ if (defaultModel.length > 0 && reportedEffort === void 0) {
39469
+ try {
39470
+ selectedEffort = effortOption(await inspectModel(defaultModel));
39471
+ } catch (cause) {
39472
+ signal.throwIfAborted();
39473
+ if (!isUnavailableModel(cause, model.id, defaultModel)) {
39474
+ throw cause;
39475
+ }
39476
+ unsupportedModels.push(cause);
39072
39477
  }
39073
- return new AgentSettingsLaunchSelectionResult(
39074
- agent.withEnvironment({
39075
- ...agent.environment,
39076
- MOBIUS_OPENCODE_PERMISSION: value,
39077
- OPENCODE_CONFIG_CONTENT: JSON.stringify({
39078
- ...openCodeConfiguration(agent.environment),
39079
- permission: openCodePermission(value)
39080
- })
39081
- }),
39082
- true
39083
- );
39084
- };
39085
- };
39086
- var CodexSettingsAdapter = class extends AgentSettingsAdapter {
39087
- modelEffortResolution = AGENT_MODEL_EFFORT_RESOLUTION_COMPLETE;
39088
- };
39089
- var genericAdapter = new AgentSettingsAdapter();
39090
- var codexAdapter = new CodexSettingsAdapter();
39091
- var deepSeekHarnessAdapter = new DeepSeekHarnessSettingsAdapter();
39092
- var openCodeAdapter = new OpenCodeSettingsAdapter();
39093
- function agentSettingsAdapterForAgent(agentId) {
39094
- if (agentId === "codex") {
39095
- return codexAdapter;
39096
39478
  }
39097
- if (agentId === "deepseek-harness") {
39098
- return deepSeekHarnessAdapter;
39099
- }
39100
- if (agentId === "opencode") {
39101
- return openCodeAdapter;
39479
+ if (defaultModel.length > 0 && !unsupportedModels.some((diagnostic) => diagnostic.requestedValue === defaultModel)) {
39480
+ valuesByModel[defaultModel] = selectedEffort?.type === "select" ? selectedEffort.values : [];
39102
39481
  }
39103
- return genericAdapter;
39482
+ return {
39483
+ effortSettingId: selectedEffort?.id ?? "",
39484
+ modelSettingId: model.id,
39485
+ resolution: "on_model_selection",
39486
+ unsupportedModelIds: unsupportedModelIds(unsupportedModels),
39487
+ valuesByModel
39488
+ };
39104
39489
  }
39105
- function applyAgentLaunchSettings(agent, selections) {
39106
- const adapter = agentSettingsAdapterForAgent(agent.id);
39107
- let selectedAgent = agent;
39108
- const sessionConfigurations = [];
39109
- for (const selection of selections) {
39110
- const applied = adapter.applyLaunchSelection(selectedAgent, selection);
39111
- selectedAgent = applied.agent;
39112
- if (!applied.handled) {
39113
- sessionConfigurations.push(selection);
39114
- }
39115
- }
39116
- return new AppliedAgentLaunchSettings(selectedAgent, sessionConfigurations);
39490
+ function settingsRevision(agent, reportedAgentVersion, settings, modelEffort) {
39491
+ const revisionModelEffort = modelEffort.resolution === AGENT_MODEL_EFFORT_RESOLUTION_COMPLETE ? modelEffort : {
39492
+ effortSettingId: "",
39493
+ modelSettingId: modelEffort.modelSettingId,
39494
+ resolution: modelEffort.resolution,
39495
+ unsupportedModelIds: modelEffort.unsupportedModelIds,
39496
+ valuesByModel: {}
39497
+ };
39498
+ return createHash3("sha256").update(
39499
+ JSON.stringify({
39500
+ adapterVersion: agent.kind === "acp-adapter-process" ? agent.adapterVersion : agent.agentVersion,
39501
+ agentId: agent.id,
39502
+ agentVersion: agent.agentVersion,
39503
+ modelEffort: revisionModelEffort,
39504
+ reportedAgentVersion,
39505
+ settings
39506
+ })
39507
+ ).digest("hex");
39117
39508
  }
39118
39509
 
39119
39510
  // src/agent-catalog/publish-agent-catalog.ts
@@ -39692,7 +40083,7 @@ var FixedInstallationExecutor = class {
39692
40083
  import { createReadStream as createReadStream2 } from "node:fs";
39693
40084
  import { realpath as realpath8, stat as stat7 } from "node:fs/promises";
39694
40085
  import { basename as basename4, isAbsolute as isAbsolute9, normalize as normalize3 } from "node:path";
39695
- import { fileURLToPath as fileURLToPath3 } from "node:url";
40086
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
39696
40087
  var CHUNK_BYTES = 192 * 1024;
39697
40088
  function requestedPath(value) {
39698
40089
  if (value.includes("\0")) {
@@ -39701,7 +40092,7 @@ function requestedPath(value) {
39701
40092
  if (value.startsWith("file:")) {
39702
40093
  try {
39703
40094
  const url2 = new URL(value);
39704
- return url2.protocol === "file:" && url2.host.length === 0 ? fileURLToPath3(url2) : null;
40095
+ return url2.protocol === "file:" && url2.host.length === 0 ? fileURLToPath2(url2) : null;
39705
40096
  } catch {
39706
40097
  return null;
39707
40098
  }
@@ -39770,7 +40161,7 @@ async function streamLocalFile(command, send2, signal) {
39770
40161
  // src/authorization/workspace-directory.ts
39771
40162
  import { readdir as readdir3, realpath as realpath9, stat as stat8 } from "node:fs/promises";
39772
40163
  import { homedir as homedir2 } from "node:os";
39773
- import { basename as basename5, dirname as dirname6, isAbsolute as isAbsolute10, join as join16, normalize as normalize4, relative as relative4 } from "node:path";
40164
+ import { basename as basename5, dirname as dirname4, isAbsolute as isAbsolute10, join as join16, normalize as normalize4, relative as relative4 } from "node:path";
39774
40165
  var WorkspaceDirectoryListing = class {
39775
40166
  directoryId;
39776
40167
  directoryLabel;
@@ -39894,7 +40285,7 @@ var WorkspaceDirectoryService = class {
39894
40285
  }
39895
40286
  }
39896
40287
  entries.sort((a, b) => a.name.localeCompare(b.name));
39897
- const parent = dirname6(target);
40288
+ const parent = dirname4(target);
39898
40289
  return new WorkspaceDirectoryListing(
39899
40290
  id,
39900
40291
  this.label(target),
@@ -39919,7 +40310,7 @@ var WorkspaceDirectoryService = class {
39919
40310
  };
39920
40311
 
39921
40312
  // src/daemon-diagnostic-log.ts
39922
- import { appendFileSync, mkdirSync as mkdirSync3, readFileSync as readFileSync2, renameSync, statSync as statSync3, writeFileSync } from "node:fs";
40313
+ import { appendFileSync, mkdirSync, readFileSync as readFileSync2, renameSync, statSync as statSync3, writeFileSync } from "node:fs";
39923
40314
  import { join as join17 } from "node:path";
39924
40315
  var MAXIMUM_DAEMON_LOG_BYTES = 1 * 1024 * 1024;
39925
40316
  var DaemonDiagnosticLog = class {
@@ -39935,7 +40326,7 @@ var DaemonDiagnosticLog = class {
39935
40326
  const encoded = `${diagnostic.replace(/[\r\n]+/gu, " ").trim()}
39936
40327
  `;
39937
40328
  const encodedBytes = Buffer.byteLength(encoded);
39938
- mkdirSync3(this.#directory, { mode: 448, recursive: true });
40329
+ mkdirSync(this.#directory, { mode: 448, recursive: true });
39939
40330
  let existingBytes = 0;
39940
40331
  try {
39941
40332
  existingBytes = statSync3(this.#path).size;
@@ -40393,8 +40784,91 @@ var readCodexHistory = async (agent, cwd, nativeSessionId, signal) => await read
40393
40784
  var readCodexFullHistory = async (agent, cwd, nativeSessionId, signal) => await readCodexHistoryWithOptions(agent, cwd, nativeSessionId, signal, { detail: "rich" });
40394
40785
 
40395
40786
  // src/native-sessions/service.ts
40396
- import { randomUUID as randomUUID2 } from "node:crypto";
40787
+ import { randomUUID as randomUUID3 } from "node:crypto";
40397
40788
  import { basename as basename6 } from "node:path";
40789
+
40790
+ // src/native-sessions/claude-history.ts
40791
+ async function readClaudeHistory(sessions, directories, bindingId, options, nativeSessionId) {
40792
+ let cursor = null;
40793
+ let inspected = 0;
40794
+ for (let pageNumber = 0; pageNumber < 500 && inspected < 500; pageNumber += 1) {
40795
+ const page = await sessions.listNativeSessions(options, cursor);
40796
+ inspected += page.sessions.length;
40797
+ const found = page.sessions.find((entry) => entry.sessionId === nativeSessionId);
40798
+ if (found !== void 0) {
40799
+ const primary = await directories.identify(bindingId, found.cwd, options.signal);
40800
+ const additional = await Promise.all(
40801
+ found.additionalDirectories.map(
40802
+ async (directory) => await directories.identify(bindingId, directory, options.signal)
40803
+ )
40804
+ );
40805
+ if (primary.path !== options.cwd || additional.length !== options.additionalDirectories.length || additional.some((directory, index2) => directory.path !== options.additionalDirectories[index2])) {
40806
+ throw new AcpExecutionError(
40807
+ "The native Session belongs to another workspace.",
40808
+ {},
40809
+ "session_identity_mismatch"
40810
+ );
40811
+ }
40812
+ return await sessions.previewNativeSession(options, nativeSessionId);
40813
+ }
40814
+ if (page.nextCursor === null || page.nextCursor === cursor) {
40815
+ break;
40816
+ }
40817
+ cursor = page.nextCursor ?? null;
40818
+ }
40819
+ throw new AcpExecutionError("The native Session was not found.", {}, "native_session_not_found");
40820
+ }
40821
+
40822
+ // src/native-sessions/claude-adapter.ts
40823
+ var claudeSessionAdapter = {
40824
+ linkedHistory: async ({ sessions, directories, bindingId, options, nativeSessionId }) => await readClaudeHistory(sessions, directories, bindingId, options, nativeSessionId),
40825
+ history: async ({ sessions, directories, bindingId, options, nativeSessionId }) => await readClaudeHistory(sessions, directories, bindingId, options, nativeSessionId),
40826
+ preview: async ({ sessions, options, nativeSessionId }) => await sessions.previewNativeSession(options, nativeSessionId)
40827
+ };
40828
+
40829
+ // src/native-sessions/codex-adapter.ts
40830
+ async function verifiedHistory(context, full) {
40831
+ const { options, nativeSessionId, directories, bindingId } = context;
40832
+ const snapshot = full ? await readCodexFullHistory(options.agent, options.cwd, nativeSessionId, options.signal) : await readCodexHistory(options.agent, options.cwd, nativeSessionId, options.signal);
40833
+ const resolved = await directories.identify(bindingId, snapshot.cwd, options.signal);
40834
+ if (snapshot.nativeSessionId !== nativeSessionId || resolved.path !== options.cwd) {
40835
+ throw new AcpExecutionError(
40836
+ "Codex returned history for a different session or workspace.",
40837
+ {},
40838
+ "invalid_native_session_response"
40839
+ );
40840
+ }
40841
+ return snapshot.history;
40842
+ }
40843
+ var codexSessionAdapter = {
40844
+ linkedHistory: async (context) => await verifiedHistory(context, true),
40845
+ history: async (context) => await verifiedHistory(context, true),
40846
+ // Codex enforces an exclusive writer per thread. Its read-only app-server
40847
+ // history path keeps externally owned conversations previewable.
40848
+ preview: async (context) => await verifiedHistory(context, false)
40849
+ };
40850
+
40851
+ // src/native-sessions/agent-adapter.ts
40852
+ var genericSessionAdapter = {
40853
+ linkedHistory: async () => {
40854
+ throw new AcpExecutionError("This Agent does not support Chat history", {}, "native_session_unsupported");
40855
+ },
40856
+ history: async () => {
40857
+ throw new AcpExecutionError("Native history is unavailable for this Agent", {}, "native_session_unsupported");
40858
+ },
40859
+ preview: async ({ sessions, options, nativeSessionId }) => await sessions.previewNativeSession(options, nativeSessionId)
40860
+ };
40861
+ function nativeSessionAdapter(agentId) {
40862
+ if (agentId === "codex") {
40863
+ return codexSessionAdapter;
40864
+ }
40865
+ if (agentId === "claude") {
40866
+ return claudeSessionAdapter;
40867
+ }
40868
+ return genericSessionAdapter;
40869
+ }
40870
+
40871
+ // src/native-sessions/service.ts
40398
40872
  var NativeSessionService = class {
40399
40873
  #entries = /* @__PURE__ */ new Map();
40400
40874
  #cursors = /* @__PURE__ */ new Map();
@@ -40424,6 +40898,61 @@ var NativeSessionService = class {
40424
40898
  sessionId: command.sessionId,
40425
40899
  signal
40426
40900
  };
40901
+ if (command.action === "linked-history") {
40902
+ const nativeSessionId = nativeSessionIdSchema.parse(command.targetSessionId);
40903
+ if (this.#sessions.hasPreparedSession(nativeSessionId, options.agent.id, cwd, additionalDirectories) && await this.#sessions.loadLinkedSessionHistory({ ...options, sessionId: nativeSessionId }) === null) {
40904
+ this.record(command, "native_session_history_read");
40905
+ return {
40906
+ action: "linked-history",
40907
+ history: {
40908
+ status: "available",
40909
+ messages: [],
40910
+ truncated: false,
40911
+ coveredCommandIds: [],
40912
+ coveredMessageIds: []
40913
+ },
40914
+ kind: "native.session.result",
40915
+ requestId: command.requestId,
40916
+ sessionId: command.sessionId,
40917
+ targetSessionId: command.targetSessionId
40918
+ };
40919
+ }
40920
+ const history = await nativeSessionAdapter(options.agent.id).linkedHistory({
40921
+ sessions: this.#sessions,
40922
+ directories: this.#directories,
40923
+ bindingId: command.bindingId,
40924
+ options,
40925
+ nativeSessionId
40926
+ });
40927
+ this.record(command, "native_session_history_read");
40928
+ return {
40929
+ action: "linked-history",
40930
+ history,
40931
+ kind: "native.session.result",
40932
+ requestId: command.requestId,
40933
+ sessionId: command.sessionId,
40934
+ targetSessionId: command.targetSessionId
40935
+ };
40936
+ }
40937
+ if (command.action === "create") {
40938
+ if (!supportsNativeChat(options.agent.id)) {
40939
+ throw new AcpExecutionError(
40940
+ "Native session creation is unavailable for this Agent",
40941
+ {},
40942
+ "native_session_unsupported"
40943
+ );
40944
+ }
40945
+ const nativeSessionId = await this.#sessions.createNativeSession(options);
40946
+ signal.throwIfAborted();
40947
+ this.record(command, "native_session_created");
40948
+ return {
40949
+ action: "create",
40950
+ kind: "native.session.result",
40951
+ nativeSessionId,
40952
+ requestId: command.requestId,
40953
+ sessionId: command.sessionId
40954
+ };
40955
+ }
40427
40956
  const prepared = await this.#sessions.prepareNativeSessionBrowser(options);
40428
40957
  if (!prepared.capabilities.listSessions) {
40429
40958
  throw new AcpExecutionError(
@@ -40439,7 +40968,7 @@ var NativeSessionService = class {
40439
40968
  if (authorized === null) {
40440
40969
  return null;
40441
40970
  }
40442
- const entryId = randomUUID2();
40971
+ const entryId = randomUUID3();
40443
40972
  if (this.#entries.size >= 5e3) {
40444
40973
  this.#entries.clear();
40445
40974
  }
@@ -40451,7 +40980,7 @@ var NativeSessionService = class {
40451
40980
  });
40452
40981
  return {
40453
40982
  entryId,
40454
- mobiusSessionIds: this.#sessions.findLinkedSessions(command.agentId, info.sessionId).filter((session) => session.prompted && session.cwd === authorized.cwd).map((session) => session.sessionId),
40983
+ nativeSessionId: info.sessionId,
40455
40984
  title: info.title ?? "Untitled session",
40456
40985
  directoryId: authorized.directoryId,
40457
40986
  directoryLabel: authorized.directoryLabel,
@@ -40494,7 +41023,7 @@ var NativeSessionService = class {
40494
41023
  "invalid_native_session_response"
40495
41024
  );
40496
41025
  }
40497
- nextCursor = randomUUID2();
41026
+ nextCursor = randomUUID3();
40498
41027
  if (this.#cursors.size >= 500) {
40499
41028
  this.#cursors.clear();
40500
41029
  }
@@ -40558,7 +41087,13 @@ var NativeSessionService = class {
40558
41087
  }
40559
41088
  const target = await this.resolveTarget(command, options, selected);
40560
41089
  if (command.action === "history") {
40561
- const history = await this.readHistory(command, options, target, signal);
41090
+ const history = await nativeSessionAdapter(options.agent.id).history({
41091
+ sessions: this.#sessions,
41092
+ directories: this.#directories,
41093
+ bindingId: command.bindingId,
41094
+ options: { ...options, cwd: target.cwd, additionalDirectories: target.additionalDirectories },
41095
+ nativeSessionId: target.info.sessionId
41096
+ });
40562
41097
  signal.throwIfAborted();
40563
41098
  this.record(command, "native_session_history_read");
40564
41099
  return {
@@ -40570,7 +41105,13 @@ var NativeSessionService = class {
40570
41105
  };
40571
41106
  }
40572
41107
  if (command.action === "preview") {
40573
- const history = await this.previewHistory(command, options, target, signal);
41108
+ const history = await nativeSessionAdapter(options.agent.id).preview({
41109
+ sessions: this.#sessions,
41110
+ directories: this.#directories,
41111
+ bindingId: command.bindingId,
41112
+ options: { ...options, cwd: target.cwd, additionalDirectories: target.additionalDirectories },
41113
+ nativeSessionId: target.info.sessionId
41114
+ });
40574
41115
  signal.throwIfAborted();
40575
41116
  this.record(command, "native_session_previewed");
40576
41117
  return {
@@ -40724,43 +41265,6 @@ var NativeSessionService = class {
40724
41265
  title: command.title
40725
41266
  };
40726
41267
  };
40727
- previewHistory = async (command, options, target, signal) => {
40728
- if (options.agent.id !== "codex") {
40729
- return await this.#sessions.previewNativeSession(
40730
- { ...options, cwd: target.cwd, additionalDirectories: target.additionalDirectories },
40731
- target.info.sessionId
40732
- );
40733
- }
40734
- const snapshot = await readCodexHistory(options.agent, target.cwd, target.info.sessionId, signal);
40735
- const resolved = await this.#directories.identify(command.bindingId, snapshot.cwd, signal);
40736
- if (snapshot.nativeSessionId !== target.info.sessionId || resolved.path !== target.cwd) {
40737
- throw new AcpExecutionError(
40738
- "Codex returned history for a different session or workspace.",
40739
- {},
40740
- "invalid_native_session_response"
40741
- );
40742
- }
40743
- return snapshot.history;
40744
- };
40745
- readHistory = async (command, options, target, signal) => {
40746
- if (options.agent.id !== "codex") {
40747
- throw new AcpExecutionError(
40748
- "Native history is unavailable for this Agent",
40749
- {},
40750
- "native_session_unsupported"
40751
- );
40752
- }
40753
- const snapshot = await readCodexFullHistory(options.agent, target.cwd, target.info.sessionId, signal);
40754
- const resolved = await this.#directories.identify(command.bindingId, snapshot.cwd, signal);
40755
- if (snapshot.nativeSessionId !== target.info.sessionId || resolved.path !== target.cwd) {
40756
- throw new AcpExecutionError(
40757
- "Codex returned history for a different session or workspace.",
40758
- {},
40759
- "invalid_native_session_response"
40760
- );
40761
- }
40762
- return snapshot.history;
40763
- };
40764
41268
  authorizeEntry = async (command, options, info) => {
40765
41269
  try {
40766
41270
  const primary = await this.#directories.identify(command.bindingId, info.cwd, options.signal);
@@ -40845,7 +41349,7 @@ var NativeSessionService = class {
40845
41349
  };
40846
41350
 
40847
41351
  // src/prompt-artifact-resolver.ts
40848
- import { createHash as createHash3 } from "node:crypto";
41352
+ import { createHash as createHash4 } from "node:crypto";
40849
41353
  import { fetch as fetch4 } from "undici";
40850
41354
  var ARTIFACT_SCHEME = "mobius-artifact:";
40851
41355
  var ARTIFACT_DOWNLOAD_TIMEOUT_MILLISECONDS = 2e4;
@@ -40984,7 +41488,7 @@ async function download(config2, command, reference, signal) {
40984
41488
  );
40985
41489
  }
40986
41490
  const bytes = await responseBytes(response, reference.byteLength, requestSignal);
40987
- if (createHash3("sha256").update(bytes).digest("hex") !== reference.sha256) {
41491
+ if (createHash4("sha256").update(bytes).digest("hex") !== reference.sha256) {
40988
41492
  throw new PromptArtifactError(
40989
41493
  "artifact_integrity_failed",
40990
41494
  "The prompt artifact failed integrity validation"
@@ -41430,7 +41934,7 @@ var RelayConnectionDiagnostics = class {
41430
41934
  };
41431
41935
 
41432
41936
  // src/relay-connection/liveness.ts
41433
- import { randomUUID as randomUUID3 } from "node:crypto";
41937
+ import { randomUUID as randomUUID4 } from "node:crypto";
41434
41938
  var HEARTBEAT_ACK_TIMEOUT_MILLISECONDS = 1e4;
41435
41939
  var HEARTBEAT_INTERVAL_MILLISECONDS = 2e4;
41436
41940
  var RelayLivenessState = class {
@@ -41519,7 +42023,7 @@ var RelayConnectionLiveness = class {
41519
42023
  }
41520
42024
  throw new Error("Heartbeat was scheduled in an invalid state");
41521
42025
  }
41522
- const heartbeatId = randomUUID3();
42026
+ const heartbeatId = randomUUID4();
41523
42027
  this.#state = new AwaitingHeartbeatAckState(
41524
42028
  heartbeatId,
41525
42029
  this.#timer.schedule(this.#handleTimeout, HEARTBEAT_ACK_TIMEOUT_MILLISECONDS)
@@ -41536,26 +42040,26 @@ var RelayConnectionLiveness = class {
41536
42040
  };
41537
42041
 
41538
42042
  // src/relay-connection/session-event-outbox.ts
41539
- import { mkdirSync as mkdirSync4 } from "node:fs";
41540
- import { dirname as dirname7 } from "node:path";
41541
- import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
42043
+ import { createHash as createHash5 } from "node:crypto";
42044
+ import { DatabaseSync } from "node:sqlite";
41542
42045
  var DEFAULT_OUTBOX_LIMITS = {
41543
42046
  criticalEventBytes: 136 * 1024 * 1024,
41544
42047
  runtimeDeliveryBytes: 64 * 1024 * 1024,
41545
42048
  runtimeDeliveryCount: 64,
41546
42049
  standardEventBytes: 128 * 1024 * 1024
41547
42050
  };
42051
+ var MAX_TERMINAL_RECEIPTS = 1024;
41548
42052
  var SessionEventOutboxCapacityError = class extends Error {
41549
42053
  code = "session_event_outbox_full";
41550
42054
  constructor() {
41551
- super("The durable Session event outbox is full");
42055
+ super("The in-memory Session event outbox is full");
41552
42056
  this.name = "SessionEventOutboxCapacityError";
41553
42057
  }
41554
42058
  };
41555
42059
  var RuntimeDeliveryInboxCapacityError = class extends Error {
41556
42060
  code = "runtime_delivery_inbox_full";
41557
42061
  constructor() {
41558
- super("The durable Runtime delivery inbox is full");
42062
+ super("The in-memory Runtime delivery inbox is full");
41559
42063
  this.name = "RuntimeDeliveryInboxCapacityError";
41560
42064
  }
41561
42065
  };
@@ -41600,11 +42104,10 @@ function rowString(row, field) {
41600
42104
  var SessionEventOutbox = class {
41601
42105
  #database;
41602
42106
  #limits;
41603
- constructor(path2, limits = DEFAULT_OUTBOX_LIMITS) {
42107
+ constructor(limits = DEFAULT_OUTBOX_LIMITS) {
41604
42108
  validateLimits(limits);
41605
42109
  this.#limits = limits;
41606
- mkdirSync4(dirname7(path2), { recursive: true });
41607
- this.#database = new DatabaseSync3(path2);
42110
+ this.#database = new DatabaseSync(":memory:");
41608
42111
  this.#database.exec(`
41609
42112
  CREATE TABLE IF NOT EXISTS relay_session_event_outbox (
41610
42113
  ordinal INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -41632,7 +42135,7 @@ var SessionEventOutbox = class {
41632
42135
  CREATE TABLE IF NOT EXISTS relay_turn_receipts (
41633
42136
  command_id TEXT PRIMARY KEY,
41634
42137
  session_id TEXT NOT NULL,
41635
- command_json TEXT NOT NULL,
42138
+ command_hash TEXT NOT NULL,
41636
42139
  attempt_id TEXT NOT NULL,
41637
42140
  state TEXT NOT NULL CHECK (
41638
42141
  state IN ('dispatching', 'running', 'succeeded', 'failed', 'cancelled')
@@ -41663,19 +42166,20 @@ var SessionEventOutbox = class {
41663
42166
  `);
41664
42167
  }
41665
42168
  claimExecution = (commandId, sessionId, commandJson) => {
42169
+ const commandHash = createHash5("sha256").update(commandJson).digest("hex");
41666
42170
  this.#database.exec("BEGIN IMMEDIATE");
41667
42171
  try {
41668
42172
  const existing = this.#database.prepare(
41669
- `SELECT session_id, command_json, attempt_id, state
42173
+ `SELECT session_id, command_hash, attempt_id, state
41670
42174
  FROM relay_turn_receipts WHERE command_id = ?`
41671
42175
  ).get(commandId);
41672
42176
  if (typeof existing === "object" && existing !== null) {
41673
42177
  const storedSessionId = Reflect.get(existing, "session_id");
41674
- const storedCommand = Reflect.get(existing, "command_json");
42178
+ const storedCommandHash = Reflect.get(existing, "command_hash");
41675
42179
  const attemptId2 = Reflect.get(existing, "attempt_id");
41676
42180
  const state = Reflect.get(existing, "state");
41677
- if (storedSessionId !== sessionId || storedCommand !== commandJson || typeof attemptId2 !== "string" || !isDaemonExecutionState(state)) {
41678
- throw new Error("The daemon command identity conflicts with its durable receipt");
42181
+ if (storedSessionId !== sessionId || storedCommandHash !== commandHash || typeof attemptId2 !== "string" || !isDaemonExecutionState(state)) {
42182
+ throw new Error("The daemon command identity conflicts with its in-memory receipt");
41679
42183
  }
41680
42184
  this.#database.exec("COMMIT");
41681
42185
  return { attemptId: attemptId2, commandId, kind: "duplicate", state };
@@ -41683,9 +42187,9 @@ var SessionEventOutbox = class {
41683
42187
  const attemptId = crypto.randomUUID();
41684
42188
  this.#database.prepare(
41685
42189
  `INSERT INTO relay_turn_receipts (
41686
- command_id, session_id, command_json, attempt_id, state
42190
+ command_id, session_id, command_hash, attempt_id, state
41687
42191
  ) VALUES (?, ?, ?, ?, 'dispatching')`
41688
- ).run(commandId, sessionId, commandJson, attemptId);
42192
+ ).run(commandId, sessionId, commandHash, attemptId);
41689
42193
  this.#database.exec("COMMIT");
41690
42194
  return {
41691
42195
  attemptId,
@@ -41712,11 +42216,21 @@ var SessionEventOutbox = class {
41712
42216
  throw new Error("The daemon execution transition is invalid");
41713
42217
  }
41714
42218
  this.#database.prepare(`UPDATE relay_turn_receipts SET state = ? WHERE command_id = ?`).run(state, commandId);
42219
+ if (state === "succeeded" || state === "failed" || state === "cancelled") {
42220
+ this.#database.prepare(
42221
+ `DELETE FROM relay_turn_receipts
42222
+ WHERE state IN ('succeeded', 'failed', 'cancelled')
42223
+ AND rowid NOT IN (
42224
+ SELECT rowid FROM relay_turn_receipts
42225
+ WHERE state IN ('succeeded', 'failed', 'cancelled')
42226
+ ORDER BY rowid DESC LIMIT ?
42227
+ )`
42228
+ ).run(MAX_TERMINAL_RECEIPTS);
42229
+ }
41715
42230
  };
41716
42231
  /**
41717
- * The Attempt this Runtime durably claimed for a command, when that Attempt never reached a
41718
- * terminal state. A restarted Runtime has no in-memory Turn for a command it was executing before
41719
- * the restart, so this is the only record of the Attempt identity the Relay is still waiting on.
42232
+ * The Attempt this live Runtime claimed for a command that has not reached a terminal state.
42233
+ * Receipts disappear when the daemon process exits.
41720
42234
  */
41721
42235
  findUnsettledAttemptId = (commandId, sessionId) => {
41722
42236
  const row = this.#database.prepare(`SELECT attempt_id, state FROM relay_turn_receipts WHERE command_id = ? AND session_id = ?`).get(commandId, sessionId);
@@ -41765,7 +42279,7 @@ var SessionEventOutbox = class {
41765
42279
  WHERE event_id = ? AND session_id = ?`
41766
42280
  ).run(rejection.eventId, rejection.sessionId);
41767
42281
  if (deletion.changes !== 1) {
41768
- throw new Error("The rejected session event could not be removed from the durable outbox");
42282
+ throw new Error("The rejected session event could not be removed from the in-memory outbox");
41769
42283
  }
41770
42284
  this.#decrementEventState(byteLength);
41771
42285
  this.#database.exec("COMMIT");
@@ -41784,7 +42298,7 @@ var SessionEventOutbox = class {
41784
42298
  enqueueCritical = (sessionId, payload, attemptId = "") => this.#enqueueBounded(sessionId, payload, attemptId, this.#limits.criticalEventBytes);
41785
42299
  /**
41786
42300
  * Bytes still available to standard Session events. The daemon uses this to shed
41787
- * superseded streaming events instead of filling the durable outbox, so a long Turn
42301
+ * superseded streaming events instead of filling the in-memory outbox, so a long Turn
41788
42302
  * behind a slow Relay cannot make the next enqueue throw.
41789
42303
  */
41790
42304
  standardCapacityRemaining = () => {
@@ -41809,7 +42323,7 @@ var SessionEventOutbox = class {
41809
42323
  const payload = rowString(existing, "payload_json");
41810
42324
  const state = runtimeDeliveryState(existing);
41811
42325
  if (sessionId !== delivery.sessionId || payload !== delivery.payload) {
41812
- throw new Error("The Runtime delivery identity conflicts with its durable receipt");
42326
+ throw new Error("The Runtime delivery identity conflicts with its in-memory receipt");
41813
42327
  }
41814
42328
  this.#database.exec("COMMIT");
41815
42329
  return new StoredRuntimeDelivery(delivery.deliveryId, sessionId, payload, state, true);
@@ -41977,7 +42491,7 @@ var SessionEventOutbox = class {
41977
42491
  WHERE event_id = ? AND session_id = ?`
41978
42492
  ).run(eventId, sessionId);
41979
42493
  if (deletion.changes !== 1) {
41980
- throw new Error("The acknowledged session event could not be removed from the durable outbox");
42494
+ throw new Error("The acknowledged session event could not be removed from the in-memory outbox");
41981
42495
  }
41982
42496
  this.#decrementEventState(byteLength);
41983
42497
  this.#database.exec("COMMIT");
@@ -42459,7 +42973,7 @@ var DaemonSessionEventPublisher = class {
42459
42973
  };
42460
42974
  /**
42461
42975
  * Enqueue a standard event, shedding it instead of ending the daemon when the
42462
- * durable outbox is full.
42976
+ * in-memory outbox is full.
42463
42977
  *
42464
42978
  * A capacity error used to escape the coalescing timer that publishes activities,
42465
42979
  * so the process exited and every restart died on the same retained backlog. A full
@@ -42502,7 +43016,7 @@ var DaemonSessionEventPublisher = class {
42502
43016
  return;
42503
43017
  }
42504
43018
  this.#shedEventKinds.add(kind);
42505
- console.warn(`Mobius daemon is dropping durable "${kind}" events because the Session event outbox is full`);
43019
+ console.warn(`Mobius daemon is dropping queued "${kind}" events because the Session event outbox is full`);
42506
43020
  };
42507
43021
  acknowledge = (acknowledgement) => {
42508
43022
  if (!this.#outbox.acknowledge(acknowledgement)) {
@@ -42771,262 +43285,6 @@ async function resolveSessionDirectories(directories, bindingId, directoryId2, a
42771
43285
  }
42772
43286
  return new ResolvedSessionDirectories(cwd, additionalDirectories, additionalDirectoryEntries);
42773
43287
  }
42774
- function isUnavailableModel(cause, modelSettingId, requestedModel) {
42775
- return cause instanceof AcpConfigurationValueUnavailableError && cause.configId === modelSettingId && cause.requestedValue === requestedModel;
42776
- }
42777
- function unsupportedModelIds(unsupportedModels) {
42778
- return [...new Set(unsupportedModels.map((item) => item.requestedValue))];
42779
- }
42780
- async function discoverAgentSettings(command, config2, directories, sessions, signal) {
42781
- const agent = config2.catalog.find(command.agentId);
42782
- const cwd = await directories.resolve(config2.bindingId, "default", signal);
42783
- const inspectedBaseSnapshot = await sessions.inspectAgentSettings({
42784
- additionalDirectories: [],
42785
- agent,
42786
- cwd,
42787
- signal
42788
- });
42789
- const baseSnapshot = {
42790
- agentName: inspectedBaseSnapshot.agentName,
42791
- agentVersion: inspectedBaseSnapshot.agentVersion,
42792
- configOptions: await discoverOpenCodeModelOptions(agent, cwd, inspectedBaseSnapshot.configOptions, signal)
42793
- };
42794
- const baseModel = modelOption(baseSnapshot.configOptions);
42795
- const unsupportedModels = [];
42796
- let selectedSnapshot = baseSnapshot;
42797
- if (command.model !== void 0) {
42798
- if (baseModel === void 0 || baseModel.type !== "select" || !baseModel.values.some((value) => value.value === command.model)) {
42799
- unsupportedModels.push(
42800
- new AcpConfigurationValueUnavailableError(
42801
- baseModel?.id ?? "model",
42802
- command.model,
42803
- baseModel?.values.map((value) => value.value) ?? []
42804
- )
42805
- );
42806
- } else {
42807
- try {
42808
- selectedSnapshot = await sessions.inspectAgentSettings({
42809
- additionalDirectories: [],
42810
- agent,
42811
- cwd,
42812
- model: command.model,
42813
- signal
42814
- });
42815
- } catch (cause) {
42816
- signal.throwIfAborted();
42817
- if (!isUnavailableModel(cause, baseModel.id, command.model)) {
42818
- throw cause;
42819
- }
42820
- unsupportedModels.push(cause);
42821
- }
42822
- }
42823
- }
42824
- const adapter = agentSettingsAdapterForAgent(agent.id);
42825
- const modelEffort = await discoverModelEffort(
42826
- command,
42827
- agent,
42828
- adapter.modelEffortResolution,
42829
- baseSnapshot.configOptions,
42830
- selectedSnapshot.configOptions,
42831
- unsupportedModels,
42832
- cwd,
42833
- sessions,
42834
- signal
42835
- );
42836
- const baseSettings = withoutUnsupportedModels(
42837
- settingsFromSnapshot(agent, baseSnapshot.configOptions),
42838
- baseModel?.id ?? "",
42839
- modelEffort.unsupportedModelIds
42840
- );
42841
- const settings = withoutUnsupportedModels(
42842
- settingsFromSnapshot(agent, selectedSnapshot.configOptions),
42843
- baseModel?.id ?? "",
42844
- modelEffort.unsupportedModelIds
42845
- );
42846
- return {
42847
- event: {
42848
- agentId: command.agentId,
42849
- agentName: selectedSnapshot.agentName,
42850
- agentVersion: selectedSnapshot.agentVersion,
42851
- kind: AGENT_SETTINGS_DISCOVERED_KIND,
42852
- modelEffort,
42853
- requestId: command.requestId,
42854
- settings,
42855
- settingsRevision: settingsRevision(agent, baseSnapshot.agentVersion, baseSettings, modelEffort)
42856
- },
42857
- unsupportedModels
42858
- };
42859
- }
42860
- function settingFromOption(option) {
42861
- return {
42862
- booleanValue: option.booleanValue,
42863
- category: option.category,
42864
- defaultValue: option.type === "boolean" ? "" : option.currentValue,
42865
- description: option.description,
42866
- id: option.id,
42867
- name: option.name,
42868
- type: option.type,
42869
- values: option.values
42870
- };
42871
- }
42872
- function settingsFromSnapshot(agent, configOptions) {
42873
- const settings = [
42874
- ...agentSettingsAdapterForAgent(agent.id).settings(agent).map(settingFromOption),
42875
- ...configOptions.map(settingFromOption)
42876
- ];
42877
- const identifiers = /* @__PURE__ */ new Set();
42878
- for (const setting of settings) {
42879
- if (identifiers.has(setting.id)) {
42880
- throw new AcpExecutionError(
42881
- "The Agent returned duplicate setting identifiers",
42882
- {},
42883
- "invalid_session_configuration"
42884
- );
42885
- }
42886
- identifiers.add(setting.id);
42887
- }
42888
- if (settings.length > 128) {
42889
- throw new AcpExecutionError("The Agent returned too many settings", {}, "invalid_session_configuration");
42890
- }
42891
- return settings;
42892
- }
42893
- function withoutUnsupportedModels(settings, modelSettingId, unsupportedModelIds2) {
42894
- if (modelSettingId.length === 0 || unsupportedModelIds2.length === 0) {
42895
- return settings;
42896
- }
42897
- const unsupported = new Set(unsupportedModelIds2);
42898
- return settings.map((setting) => {
42899
- if (setting.id !== modelSettingId || setting.type !== "select") {
42900
- return setting;
42901
- }
42902
- return {
42903
- ...setting,
42904
- defaultValue: unsupported.has(setting.defaultValue) ? "" : setting.defaultValue,
42905
- values: setting.values.filter((value) => !unsupported.has(value.value))
42906
- };
42907
- });
42908
- }
42909
- function modelOption(options) {
42910
- return options.find((option) => option.id === "model" || option.category === "model");
42911
- }
42912
- function effortOption(options) {
42913
- return options.find((option) => option.id === "reasoning_effort" || option.category === "thought_level");
42914
- }
42915
- function unavailableModelEffort() {
42916
- return {
42917
- effortSettingId: "",
42918
- modelSettingId: "",
42919
- resolution: AGENT_MODEL_EFFORT_RESOLUTION_UNAVAILABLE,
42920
- unsupportedModelIds: [],
42921
- valuesByModel: {}
42922
- };
42923
- }
42924
- async function discoverModelEffort(command, agent, resolution, initialOptions, selectedOptions, initiallyUnsupportedModels, cwd, sessions, signal) {
42925
- const model = modelOption(initialOptions);
42926
- const unsupportedModels = initiallyUnsupportedModels;
42927
- if (resolution !== AGENT_MODEL_EFFORT_RESOLUTION_COMPLETE && resolution !== AGENT_MODEL_EFFORT_RESOLUTION_ON_MODEL_SELECTION) {
42928
- return { ...unavailableModelEffort(), unsupportedModelIds: unsupportedModelIds(unsupportedModels) };
42929
- }
42930
- if (model === void 0 || model.type !== "select" || model.values.length === 0) {
42931
- return { ...unavailableModelEffort(), unsupportedModelIds: unsupportedModelIds(unsupportedModels) };
42932
- }
42933
- const inspectModel = async (modelValue) => (await sessions.inspectAgentSettings({
42934
- additionalDirectories: [],
42935
- agent,
42936
- cwd,
42937
- model: modelValue,
42938
- signal
42939
- })).configOptions;
42940
- const valuesByModel = {};
42941
- if (resolution === "complete") {
42942
- const effort = effortOption(initialOptions);
42943
- if (effort === void 0 || effort.type !== "select" || effort.values.length < 2) {
42944
- return {
42945
- ...unavailableModelEffort(),
42946
- unsupportedModelIds: unsupportedModelIds(unsupportedModels)
42947
- };
42948
- }
42949
- for (const value of model.values) {
42950
- if (unsupportedModels.some((diagnostic) => diagnostic.requestedValue === value.value)) {
42951
- continue;
42952
- }
42953
- try {
42954
- const selectedEffort2 = effortOption(await inspectModel(value.value));
42955
- valuesByModel[value.value] = selectedEffort2?.type === "select" ? selectedEffort2.values : [];
42956
- } catch (cause) {
42957
- signal.throwIfAborted();
42958
- if (!isUnavailableModel(cause, model.id, value.value)) {
42959
- throw cause;
42960
- }
42961
- unsupportedModels.push(cause);
42962
- }
42963
- }
42964
- return {
42965
- effortSettingId: effort.id,
42966
- modelSettingId: model.id,
42967
- resolution: "complete",
42968
- unsupportedModelIds: unsupportedModelIds(unsupportedModels),
42969
- valuesByModel
42970
- };
42971
- }
42972
- if (command.model !== void 0) {
42973
- const modelUnsupported = unsupportedModels.some((diagnostic) => diagnostic.requestedValue === command.model);
42974
- const selectedEffort2 = effortOption(selectedOptions);
42975
- if (!modelUnsupported) {
42976
- valuesByModel[command.model] = selectedEffort2?.type === "select" ? selectedEffort2.values : [];
42977
- }
42978
- return {
42979
- effortSettingId: selectedEffort2?.id ?? "",
42980
- modelSettingId: model.id,
42981
- resolution: "on_model_selection",
42982
- unsupportedModelIds: unsupportedModelIds(unsupportedModels),
42983
- valuesByModel
42984
- };
42985
- }
42986
- const defaultModel = model.type === "select" ? model.currentValue : "";
42987
- const reportedEffort = effortOption(selectedOptions);
42988
- let selectedEffort = reportedEffort;
42989
- if (defaultModel.length > 0 && reportedEffort === void 0) {
42990
- try {
42991
- selectedEffort = effortOption(await inspectModel(defaultModel));
42992
- } catch (cause) {
42993
- signal.throwIfAborted();
42994
- if (!isUnavailableModel(cause, model.id, defaultModel)) {
42995
- throw cause;
42996
- }
42997
- unsupportedModels.push(cause);
42998
- }
42999
- }
43000
- if (defaultModel.length > 0 && !unsupportedModels.some((diagnostic) => diagnostic.requestedValue === defaultModel)) {
43001
- valuesByModel[defaultModel] = selectedEffort?.type === "select" ? selectedEffort.values : [];
43002
- }
43003
- return {
43004
- effortSettingId: selectedEffort?.id ?? "",
43005
- modelSettingId: model.id,
43006
- resolution: "on_model_selection",
43007
- unsupportedModelIds: unsupportedModelIds(unsupportedModels),
43008
- valuesByModel
43009
- };
43010
- }
43011
- function settingsRevision(agent, reportedAgentVersion, settings, modelEffort) {
43012
- const revisionModelEffort = modelEffort.resolution === AGENT_MODEL_EFFORT_RESOLUTION_COMPLETE ? modelEffort : {
43013
- effortSettingId: "",
43014
- modelSettingId: modelEffort.modelSettingId,
43015
- resolution: modelEffort.resolution,
43016
- unsupportedModelIds: modelEffort.unsupportedModelIds,
43017
- valuesByModel: {}
43018
- };
43019
- return createHash4("sha256").update(
43020
- JSON.stringify({
43021
- adapterVersion: agent.kind === "acp-adapter-process" ? agent.adapterVersion : agent.agentVersion,
43022
- agentId: agent.id,
43023
- agentVersion: agent.agentVersion,
43024
- modelEffort: revisionModelEffort,
43025
- reportedAgentVersion,
43026
- settings
43027
- })
43028
- ).digest("hex");
43029
- }
43030
43288
  async function executeWorkspaceList(socket, command, directories, audit, signal) {
43031
43289
  try {
43032
43290
  const listing = await directories.list(command.bindingId, command.directoryId, signal);
@@ -43532,187 +43790,6 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
43532
43790
  console.error("Mobius daemon command failed", error62);
43533
43791
  }
43534
43792
  }
43535
- function invalidSessionConfiguration(message) {
43536
- return new AcpExecutionError(message, {}, "invalid_session_configuration");
43537
- }
43538
- function agentForSessionConfiguration(agent, selections) {
43539
- try {
43540
- return applyAgentLaunchSettings(agent, selections);
43541
- } catch (error62) {
43542
- if (error62 instanceof Error) {
43543
- throw invalidSessionConfiguration(error62.message);
43544
- }
43545
- throw error62;
43546
- }
43547
- }
43548
- function validateSessionConfigurationSelection(option, selection) {
43549
- if (option.type !== selection.valueType) {
43550
- throw invalidSessionConfiguration(`The Agent setting ${selection.configId} changed type`);
43551
- }
43552
- if (option.type === "boolean") {
43553
- if (selection.value.length > 0) {
43554
- throw invalidSessionConfiguration(`The Agent setting ${selection.configId} has an invalid value`);
43555
- }
43556
- return;
43557
- }
43558
- if (selection.booleanValue) {
43559
- throw invalidSessionConfiguration(`The Agent setting ${selection.configId} has an invalid value`);
43560
- }
43561
- if (!option.values.some((value) => value.value === selection.value)) {
43562
- throw invalidSessionConfiguration(`The Agent setting ${selection.configId} has an unavailable value`);
43563
- }
43564
- }
43565
- function sessionConfigurationSelectionIsAvailable(option, selection) {
43566
- if (option.type !== selection.valueType) {
43567
- return false;
43568
- }
43569
- if (option.type === "boolean") {
43570
- return selection.value.length === 0;
43571
- }
43572
- return !selection.booleanValue && option.values.some((value) => value.value === selection.value);
43573
- }
43574
- function sessionConfigurationMatches(option, selection) {
43575
- validateSessionConfigurationSelection(option, selection);
43576
- return option.type === "boolean" ? option.booleanValue === selection.booleanValue : option.currentValue === selection.value;
43577
- }
43578
- function sessionConfigurationPriority(selection, options) {
43579
- const option = options.find((candidate) => candidate.id === selection.configId);
43580
- if (selection.configId === "model" || option?.category === "model") {
43581
- return 0;
43582
- }
43583
- if (selection.configId === "reasoning_effort" || option?.category === "thought_level") {
43584
- return 1;
43585
- }
43586
- if (option?.category === "model_config") {
43587
- return 2;
43588
- }
43589
- return 3;
43590
- }
43591
- function assertAppliedSessionConfiguration(options, selections) {
43592
- const selectionsById = new Map(selections.map((selection) => [selection.configId, selection]));
43593
- for (const option of options) {
43594
- const selection = selectionsById.get(option.id);
43595
- if (selection === void 0 || !sessionConfigurationSelectionIsAvailable(option, selection)) {
43596
- continue;
43597
- }
43598
- if (!sessionConfigurationMatches(option, selection)) {
43599
- throw invalidSessionConfiguration(`The Turn configuration does not match Agent setting ${option.id}`);
43600
- }
43601
- }
43602
- }
43603
- function unavailableSessionConfigurationCategory(selection) {
43604
- if (selection.configId === "model") {
43605
- return "model";
43606
- }
43607
- if (selection.configId === "reasoning_effort") {
43608
- return "thought_level";
43609
- }
43610
- return "unknown";
43611
- }
43612
- async function applySessionConfigurationSelection(sessions, audit, options, selection, agent, cwd, additionalDirectories, commandId, sessionId, signal) {
43613
- const option = options.find((candidate) => candidate.id === selection.configId);
43614
- if (option === void 0) {
43615
- warnIgnoredSetting(
43616
- audit,
43617
- "session_configuration_setting_ignored",
43618
- commandId,
43619
- sessionId,
43620
- agent.id,
43621
- selection,
43622
- unavailableSessionConfigurationCategory(selection),
43623
- "setting_unavailable"
43624
- );
43625
- return options;
43626
- }
43627
- if (option.type !== selection.valueType) {
43628
- warnIgnoredSetting(
43629
- audit,
43630
- "session_configuration_setting_ignored",
43631
- commandId,
43632
- sessionId,
43633
- agent.id,
43634
- selection,
43635
- option.category,
43636
- "setting_schema_mismatch"
43637
- );
43638
- return options;
43639
- }
43640
- if (option.type === "boolean" && selection.value.length > 0 || option.type === "select" && selection.booleanValue) {
43641
- warnIgnoredSetting(
43642
- audit,
43643
- "session_configuration_setting_ignored",
43644
- commandId,
43645
- sessionId,
43646
- agent.id,
43647
- selection,
43648
- option.category,
43649
- "selection_schema_mismatch"
43650
- );
43651
- return options;
43652
- }
43653
- if (option.type === "select" && !option.values.some((value) => value.value === selection.value)) {
43654
- warnIgnoredSetting(
43655
- audit,
43656
- "session_configuration_setting_ignored",
43657
- commandId,
43658
- sessionId,
43659
- agent.id,
43660
- selection,
43661
- option.category,
43662
- "value_unavailable"
43663
- );
43664
- return options;
43665
- }
43666
- if (sessionConfigurationMatches(option, selection)) {
43667
- return options;
43668
- }
43669
- return await sessions.configureSession({
43670
- additionalDirectories,
43671
- agent,
43672
- booleanValue: selection.booleanValue,
43673
- configId: selection.configId,
43674
- cwd,
43675
- requestId: `cfg_${randomUUID4()}`,
43676
- sessionId,
43677
- signal,
43678
- value: selection.value,
43679
- valueType: selection.valueType
43680
- });
43681
- }
43682
- async function applyCompleteSessionConfiguration(sessions, audit, initialOptions, selections, agent, cwd, additionalDirectories, commandId, sessionId, signal) {
43683
- let options = initialOptions;
43684
- const orderedSelections = selections.toSorted((left, right) => {
43685
- const priority = sessionConfigurationPriority(left, initialOptions) - sessionConfigurationPriority(right, initialOptions);
43686
- return priority === 0 ? left.configId.localeCompare(right.configId) : priority;
43687
- });
43688
- for (const selection of orderedSelections) {
43689
- options = await applySessionConfigurationSelection(
43690
- sessions,
43691
- audit,
43692
- options,
43693
- selection,
43694
- agent,
43695
- cwd,
43696
- additionalDirectories,
43697
- commandId,
43698
- sessionId,
43699
- signal
43700
- );
43701
- }
43702
- assertAppliedSessionConfiguration(options, selections);
43703
- }
43704
- function warnIgnoredSetting(audit, event, commandId, sessionId, agentId, selection, category, reason) {
43705
- const details = {
43706
- agentId,
43707
- category,
43708
- configId: selection.configId,
43709
- reason,
43710
- requestedValue: selection.value
43711
- };
43712
- audit.record({ commandId, details, event, sessionId });
43713
- process.stderr.write(`Mobius daemon warning ${JSON.stringify({ commandId, event, sessionId, ...details })}
43714
- `);
43715
- }
43716
43793
  function waitForRelayRetry(signal, timer) {
43717
43794
  if (signal.aborted) {
43718
43795
  return Promise.resolve();
@@ -43759,7 +43836,7 @@ async function installDetectedAgentIntegrations(config2, installations, signal)
43759
43836
  {
43760
43837
  agentId: agent.id,
43761
43838
  kind: AGENT_INSTALL_REQUEST_KIND,
43762
- requestId: `automatic-integration-${randomUUID4()}`
43839
+ requestId: `automatic-integration-${randomUUID5()}`
43763
43840
  },
43764
43841
  signal
43765
43842
  );
@@ -44011,7 +44088,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
44011
44088
  if (connectionController.signal.aborted) {
44012
44089
  return;
44013
44090
  }
44014
- console.error("Mobius daemon could not process a durable Runtime delivery", error62);
44091
+ console.error("Mobius daemon could not process a in-memory Runtime delivery", error62);
44015
44092
  failAndClose(
44016
44093
  new Error("Runtime delivery processing failed", { cause: error62 }),
44017
44094
  4008,
@@ -44814,8 +44891,8 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
44814
44891
  publishCatalog: async (installationSignal) => await publishAgentCatalog(config2, installationSignal),
44815
44892
  stateDirectory
44816
44893
  });
44817
- const sessionStore = new SqliteAcpSessionStore(config2.auditDatabasePath);
44818
- const outbox = new SessionEventOutbox(config2.auditDatabasePath);
44894
+ const sessionStore = new MemoryAcpSessionStore();
44895
+ const outbox = new SessionEventOutbox();
44819
44896
  const publisher = new DaemonSessionEventPublisher(outbox, timer);
44820
44897
  const activeTurns = /* @__PURE__ */ new Map();
44821
44898
  const activeAttemptIds = /* @__PURE__ */ new Map();
@@ -44827,9 +44904,14 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
44827
44904
  }
44828
44905
  publisher.recordAttempt(sessionId, event, attemptId);
44829
44906
  };
44830
- const sessions = new AcpSessionManager(new DaemonAcpObserver(recordSessionEvent), sessionStore, {
44831
- read: async (options2, nativeSessionId) => options2.agent.id === "codex" ? (await readCodexFullHistory(options2.agent, options2.cwd, nativeSessionId, options2.signal)).history : null
44832
- });
44907
+ const sessions = new AcpSessionManager(
44908
+ new DaemonAcpObserver(recordSessionEvent),
44909
+ sessionStore,
44910
+ {
44911
+ read: async (options2, nativeSessionId) => options2.agent.id === "codex" ? (await readCodexFullHistory(options2.agent, options2.cwd, nativeSessionId, options2.signal)).history : null
44912
+ },
44913
+ "native"
44914
+ );
44833
44915
  const directories = new WorkspaceDirectoryService(config2.bindingId, config2.defaultWorkspace);
44834
44916
  const installationObserver = new DaemonInstallationObserver();
44835
44917
  const diagnostics = new RelayConnectionDiagnostics(
@@ -44965,13 +45047,9 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
44965
45047
  await sessions.close();
44966
45048
  } finally {
44967
45049
  try {
44968
- sessionStore.close();
45050
+ publisher.close();
44969
45051
  } finally {
44970
- try {
44971
- publisher.close();
44972
- } finally {
44973
- outbox.close();
44974
- }
45052
+ outbox.close();
44975
45053
  }
44976
45054
  }
44977
45055
  }
@@ -44982,7 +45060,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
44982
45060
 
44983
45061
  // src/runtime.ts
44984
45062
  import { mkdir as mkdir6, realpath as realpath10, stat as stat9 } from "node:fs/promises";
44985
- import { dirname as dirname8, join as join18, resolve as resolve7 } from "node:path";
45063
+ import { resolve as resolve7 } from "node:path";
44986
45064
  var IDENTIFIER_PATTERN7 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
44987
45065
  var RUNTIME_CREDENTIAL_PATTERN2 = /^[a-zA-Z0-9_-]{32,256}$/;
44988
45066
  var MobiusRuntimeConfigurationError = class extends Error {
@@ -45039,7 +45117,6 @@ function loadMobiusRuntimeConnection(environment = process.env) {
45039
45117
  throw new MobiusRuntimeConfigurationError("MOBIUS_CHANNEL_ID is invalid");
45040
45118
  }
45041
45119
  return Object.freeze({
45042
- auditDatabasePath: environment["MOBIUS_AUDIT_DATABASE"]?.trim() || join18(readStateDirectory(environment), "audit", `${channelId}.sqlite`),
45043
45120
  channelId,
45044
45121
  defaultWorkspace: loadDefaultWorkspace(environment),
45045
45122
  relayUrl: requiredEnvironmentValue(environment, "MOBIUS_RELAY_URL"),
@@ -45068,8 +45145,6 @@ async function createMobiusRuntimeEngine(connection, signal, environment = proce
45068
45145
  const localContext = new DaemonLocalContext(readStateDirectory(environment), environment);
45069
45146
  const relayUrl = relayUrlFromConnection(connection);
45070
45147
  const defaultWorkspace = await resolveWorkspace(connection.defaultWorkspace);
45071
- const auditDatabasePath = resolve7(connection.auditDatabasePath);
45072
- await mkdir6(dirname8(auditDatabasePath), { recursive: true, mode: 448 });
45073
45148
  const inventory = await discoverLocalAgentInventory({
45074
45149
  defaultWorkspace,
45075
45150
  environment: localContext.environment,
@@ -45081,7 +45156,6 @@ async function createMobiusRuntimeEngine(connection, signal, environment = proce
45081
45156
  return new MobiusRuntimeEngine(
45082
45157
  createDaemonConfig(
45083
45158
  {
45084
- auditDatabasePath,
45085
45159
  channelId: connection.channelId,
45086
45160
  defaultWorkspace,
45087
45161
  relayUrl
@@ -45107,7 +45181,7 @@ var MobiusRuntimeEngine = class {
45107
45181
  }
45108
45182
  signal.throwIfAborted();
45109
45183
  this.#state = new RunningMobiusRuntimeState();
45110
- const audit = new AuditStore(this.#config.auditDatabasePath);
45184
+ const audit = new AuditStore();
45111
45185
  try {
45112
45186
  await runDaemon(this.#config, audit, signal, void 0, {
45113
45187
  ...this.#options.onConnectionStatus === void 0 ? {} : { onConnectionStatus: this.#options.onConnectionStatus },