@moxt-ai/mobius 0.0.18 → 0.0.19

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 (166) hide show
  1. package/dist/acp/activity.d.ts.map +1 -1
  2. package/dist/acp/activity.js +4 -12
  3. package/dist/acp/activity.js.map +1 -1
  4. package/dist/acp/create-client.d.ts.map +1 -1
  5. package/dist/acp/create-client.js.map +1 -1
  6. package/dist/acp/native-session.d.ts.map +1 -1
  7. package/dist/acp/native-session.js +1 -3
  8. package/dist/acp/native-session.js.map +1 -1
  9. package/dist/acp/run-prompt.d.ts.map +1 -1
  10. package/dist/acp/run-prompt.js +1 -1
  11. package/dist/acp/run-prompt.js.map +1 -1
  12. package/dist/acp/session-capabilities.d.ts +5 -0
  13. package/dist/acp/session-capabilities.d.ts.map +1 -0
  14. package/dist/acp/session-capabilities.js +31 -0
  15. package/dist/acp/session-capabilities.js.map +1 -0
  16. package/dist/acp/session-config/grok-build-session-config.d.ts.map +1 -1
  17. package/dist/acp/session-config/grok-build-session-config.js +6 -11
  18. package/dist/acp/session-config/grok-build-session-config.js.map +1 -1
  19. package/dist/acp/session-config/session-config-protocol.d.ts.map +1 -1
  20. package/dist/acp/session-config/session-config-protocol.js +4 -12
  21. package/dist/acp/session-config/session-config-protocol.js.map +1 -1
  22. package/dist/acp/session-config/session-config-registry.d.ts.map +1 -1
  23. package/dist/acp/session-config/session-config-registry.js +2 -4
  24. package/dist/acp/session-config/session-config-registry.js.map +1 -1
  25. package/dist/acp/session-history.d.ts.map +1 -1
  26. package/dist/acp/session-history.js +7 -8
  27. package/dist/acp/session-history.js.map +1 -1
  28. package/dist/acp/session-manager.d.ts.map +1 -1
  29. package/dist/acp/session-manager.js +59 -96
  30. package/dist/acp/session-manager.js.map +1 -1
  31. package/dist/acp/session-store.d.ts.map +1 -1
  32. package/dist/acp/session-store.js +12 -24
  33. package/dist/acp/session-store.js.map +1 -1
  34. package/dist/agent-catalog/acp-readiness-probe.d.ts +7 -1
  35. package/dist/agent-catalog/acp-readiness-probe.d.ts.map +1 -1
  36. package/dist/agent-catalog/acp-readiness-probe.js +13 -3
  37. package/dist/agent-catalog/acp-readiness-probe.js.map +1 -1
  38. package/dist/agent-catalog/agent-diagnostics.d.ts.map +1 -1
  39. package/dist/agent-catalog/agent-diagnostics.js.map +1 -1
  40. package/dist/agent-catalog/agent-discovery-context.d.ts.map +1 -1
  41. package/dist/agent-catalog/agent-discovery.d.ts.map +1 -1
  42. package/dist/agent-catalog/agent-discovery.js.map +1 -1
  43. package/dist/agent-catalog/agent-probe-error.d.ts.map +1 -1
  44. package/dist/agent-catalog/agent-probe-error.js.map +1 -1
  45. package/dist/agent-catalog/agent-specification.d.ts.map +1 -1
  46. package/dist/agent-catalog/agent-specification.js +2 -4
  47. package/dist/agent-catalog/agent-specification.js.map +1 -1
  48. package/dist/agent-catalog/agents/claude-code-agent.d.ts.map +1 -1
  49. package/dist/agent-catalog/agents/claude-code-agent.js +1 -8
  50. package/dist/agent-catalog/agents/claude-code-agent.js.map +1 -1
  51. package/dist/agent-catalog/agents/codex-agent.d.ts.map +1 -1
  52. package/dist/agent-catalog/agents/codex-agent.js.map +1 -1
  53. package/dist/agent-catalog/agents/cursor-cli-agent.d.ts.map +1 -1
  54. package/dist/agent-catalog/agents/cursor-cli-agent.js.map +1 -1
  55. package/dist/agent-catalog/agents/deepseek-harness-agent.d.ts.map +1 -1
  56. package/dist/agent-catalog/agents/deepseek-harness-agent.js +4 -4
  57. package/dist/agent-catalog/agents/deepseek-harness-agent.js.map +1 -1
  58. package/dist/agent-catalog/agents/grok-build-agent.d.ts.map +1 -1
  59. package/dist/agent-catalog/agents/grok-build-agent.js +4 -14
  60. package/dist/agent-catalog/agents/grok-build-agent.js.map +1 -1
  61. package/dist/agent-catalog/agents/opencode-agent.d.ts.map +1 -1
  62. package/dist/agent-catalog/agents/opencode-agent.js +1 -1
  63. package/dist/agent-catalog/agents/opencode-agent.js.map +1 -1
  64. package/dist/agent-catalog/agents/pi-agent.d.ts.map +1 -1
  65. package/dist/agent-catalog/agents/pi-agent.js +1 -1
  66. package/dist/agent-catalog/agents/pi-agent.js.map +1 -1
  67. package/dist/agent-catalog/agents/supported-agent-specifications.js.map +1 -1
  68. package/dist/agent-catalog/agents/verify-session-creation.d.ts.map +1 -1
  69. package/dist/agent-catalog/agents/verify-session-creation.js +1 -1
  70. package/dist/agent-catalog/agents/verify-session-creation.js.map +1 -1
  71. package/dist/agent-catalog/agents/workbuddy-agent.d.ts.map +1 -1
  72. package/dist/agent-catalog/agents/workbuddy-agent.js +3 -6
  73. package/dist/agent-catalog/agents/workbuddy-agent.js.map +1 -1
  74. package/dist/agent-catalog/discover-agent.d.ts.map +1 -1
  75. package/dist/agent-catalog/discover-agent.js +9 -14
  76. package/dist/agent-catalog/discover-agent.js.map +1 -1
  77. package/dist/agent-catalog/discover-local-agents.d.ts.map +1 -1
  78. package/dist/agent-catalog/discover-local-agents.js.map +1 -1
  79. package/dist/agent-catalog/executable-discovery.d.ts.map +1 -1
  80. package/dist/agent-catalog/executable-discovery.js.map +1 -1
  81. package/dist/agent-catalog/local-agent.d.ts +3 -1
  82. package/dist/agent-catalog/local-agent.d.ts.map +1 -1
  83. package/dist/agent-catalog/local-agent.js +5 -3
  84. package/dist/agent-catalog/local-agent.js.map +1 -1
  85. package/dist/agent-catalog/publish-agent-catalog.d.ts.map +1 -1
  86. package/dist/agent-catalog/publish-agent-catalog.js +2 -3
  87. package/dist/agent-catalog/publish-agent-catalog.js.map +1 -1
  88. package/dist/agent-installation/agent-installation-manager.d.ts.map +1 -1
  89. package/dist/agent-installation/agent-installation-manager.js +3 -1
  90. package/dist/agent-installation/agent-installation-manager.js.map +1 -1
  91. package/dist/agent-installation/deepseek-managed-package.d.ts.map +1 -1
  92. package/dist/agent-installation/deepseek-managed-package.js +1 -3
  93. package/dist/agent-installation/deepseek-managed-package.js.map +1 -1
  94. package/dist/agent-installation/fixed-installation-executor.d.ts.map +1 -1
  95. package/dist/agent-installation/fixed-installation-executor.js +8 -11
  96. package/dist/agent-installation/fixed-installation-executor.js.map +1 -1
  97. package/dist/agent-installation/grok-managed-package.d.ts.map +1 -1
  98. package/dist/agent-installation/grok-managed-package.js +2 -4
  99. package/dist/agent-installation/grok-managed-package.js.map +1 -1
  100. package/dist/agent-installation/managed-adapter-installer.d.ts.map +1 -1
  101. package/dist/agent-installation/managed-adapter-installer.js +3 -1
  102. package/dist/agent-installation/managed-adapter-installer.js.map +1 -1
  103. package/dist/agent-installation/managed-agent-archive.d.ts.map +1 -1
  104. package/dist/agent-installation/managed-agent-archive.js +17 -19
  105. package/dist/agent-installation/managed-agent-archive.js.map +1 -1
  106. package/dist/agent-installation/managed-npm-package.d.ts.map +1 -1
  107. package/dist/agent-installation/managed-npm-package.js +8 -13
  108. package/dist/agent-installation/managed-npm-package.js.map +1 -1
  109. package/dist/agent-installation/opencode-managed-release.d.ts.map +1 -1
  110. package/dist/agent-installation/opencode-managed-release.js.map +1 -1
  111. package/dist/agent-installation/pi-managed-packages.js.map +1 -1
  112. package/dist/agent-installation/verified-download.d.ts.map +1 -1
  113. package/dist/agent-installation/verified-download.js +4 -4
  114. package/dist/agent-installation/verified-download.js.map +1 -1
  115. package/dist/agent-installation/workbuddy-managed-package.d.ts.map +1 -1
  116. package/dist/agent-installation/workbuddy-managed-package.js +1 -3
  117. package/dist/agent-installation/workbuddy-managed-package.js.map +1 -1
  118. package/dist/audit/audit-store.d.ts.map +1 -1
  119. package/dist/audit/audit-store.js +1 -3
  120. package/dist/audit/audit-store.js.map +1 -1
  121. package/dist/authorization/local-authorization-error.d.ts.map +1 -1
  122. package/dist/authorization/local-authorization-error.js.map +1 -1
  123. package/dist/authorization/workspace-directory.d.ts.map +1 -1
  124. package/dist/authorization/workspace-directory.js +30 -21
  125. package/dist/authorization/workspace-directory.js.map +1 -1
  126. package/dist/cli.js +858 -1999
  127. package/dist/cli.js.map +4 -4
  128. package/dist/config.d.ts.map +1 -1
  129. package/dist/config.js +1 -2
  130. package/dist/config.js.map +1 -1
  131. package/dist/index.d.ts.map +1 -1
  132. package/dist/index.js +828 -1950
  133. package/dist/index.js.map +4 -4
  134. package/dist/native-sessions/codex-history.d.ts.map +1 -1
  135. package/dist/native-sessions/codex-history.js +26 -17
  136. package/dist/native-sessions/codex-history.js.map +1 -1
  137. package/dist/native-sessions/service.d.ts.map +1 -1
  138. package/dist/native-sessions/service.js +46 -36
  139. package/dist/native-sessions/service.js.map +1 -1
  140. package/dist/pairing/pair-local-machine.d.ts.map +1 -1
  141. package/dist/pairing/pair-local-machine.js +12 -24
  142. package/dist/pairing/pair-local-machine.js.map +1 -1
  143. package/dist/process/executable.d.ts.map +1 -1
  144. package/dist/process/executable.js +16 -15
  145. package/dist/process/executable.js.map +1 -1
  146. package/dist/prompt-artifact-resolver.d.ts +13 -0
  147. package/dist/prompt-artifact-resolver.d.ts.map +1 -0
  148. package/dist/prompt-artifact-resolver.js +205 -0
  149. package/dist/prompt-artifact-resolver.js.map +1 -0
  150. package/dist/relay-connection/connect.d.ts.map +1 -1
  151. package/dist/relay-connection/connect.js +3 -1
  152. package/dist/relay-connection/connect.js.map +1 -1
  153. package/dist/relay-connection/liveness.d.ts.map +1 -1
  154. package/dist/relay-connection/liveness.js +1 -2
  155. package/dist/relay-connection/liveness.js.map +1 -1
  156. package/dist/relay-connection/session-event-outbox.d.ts.map +1 -1
  157. package/dist/relay-connection/session-event-outbox.js +7 -19
  158. package/dist/relay-connection/session-event-outbox.js.map +1 -1
  159. package/dist/relay-connection/timer.d.ts.map +1 -1
  160. package/dist/relay-connection/timer.js.map +1 -1
  161. package/dist/run-daemon.d.ts.map +1 -1
  162. package/dist/run-daemon.js +44 -34
  163. package/dist/run-daemon.js.map +1 -1
  164. package/dist/storage/state-directory.d.ts.map +1 -1
  165. package/dist/storage/state-directory.js.map +1 -1
  166. package/package.json +55 -55
package/dist/index.js CHANGED
@@ -29,19 +29,7 @@ var createAcpClient = (handler) => client({ name: "mobius" }).onRequest(
29
29
  }
30
30
  })).onRequest("cursor/create_plan", discardExtensionParams, async () => ({
31
31
  outcome: { outcome: "cancelled" }
32
- })).onNotification(
33
- "cursor/update_todos",
34
- discardExtensionParams,
35
- async () => Promise.resolve()
36
- ).onNotification(
37
- "cursor/task",
38
- discardExtensionParams,
39
- async () => Promise.resolve()
40
- ).onNotification(
41
- "cursor/generate_image",
42
- discardExtensionParams,
43
- async () => Promise.resolve()
44
- );
32
+ })).onNotification("cursor/update_todos", discardExtensionParams, async () => Promise.resolve()).onNotification("cursor/task", discardExtensionParams, async () => Promise.resolve()).onNotification("cursor/generate_image", discardExtensionParams, async () => Promise.resolve());
45
33
 
46
34
  // src/config.ts
47
35
  import { join as join3 } from "node:path";
@@ -18944,13 +18932,7 @@ var promptMetadataSchema = external_exports.object({
18944
18932
  }).readonly();
18945
18933
  var agentPromptResponseSchema = external_exports.object({
18946
18934
  _meta: promptMetadataSchema.nullish(),
18947
- stopReason: external_exports.enum([
18948
- "end_turn",
18949
- "max_tokens",
18950
- "max_turn_requests",
18951
- "refusal",
18952
- "cancelled"
18953
- ]),
18935
+ stopReason: external_exports.enum(["end_turn", "max_tokens", "max_turn_requests", "refusal", "cancelled"]),
18954
18936
  usage: promptUsageSchema.nullish()
18955
18937
  }).readonly();
18956
18938
  function decodeAgentPromptResponse(value) {
@@ -19033,12 +19015,7 @@ var sessionCommandSchema = external_exports.strictObject({
19033
19015
  name: external_exports.string().min(1).max(128)
19034
19016
  }).readonly();
19035
19017
  var permissionOptionSchema = external_exports.strictObject({
19036
- kind: external_exports.enum([
19037
- "allow_once",
19038
- "allow_always",
19039
- "reject_once",
19040
- "reject_always"
19041
- ]),
19018
+ kind: external_exports.enum(["allow_once", "allow_always", "reject_once", "reject_always"]),
19042
19019
  name: external_exports.string().min(1).max(255),
19043
19020
  optionId: external_exports.string().min(1).max(255)
19044
19021
  }).readonly();
@@ -19063,14 +19040,7 @@ var elicitationFieldSchema = external_exports.strictObject({
19063
19040
  pattern: external_exports.string().max(500),
19064
19041
  required: external_exports.boolean(),
19065
19042
  title: external_exports.string().min(1).max(255),
19066
- type: external_exports.enum([
19067
- "boolean",
19068
- "integer",
19069
- "multiselect",
19070
- "number",
19071
- "select",
19072
- "string"
19073
- ])
19043
+ type: external_exports.enum(["boolean", "integer", "multiselect", "number", "select", "string"])
19074
19044
  }).readonly();
19075
19045
  var displayContentSchema = external_exports.strictObject({
19076
19046
  data: external_exports.string().max(4e6),
@@ -19081,14 +19051,7 @@ var displayContentSchema = external_exports.strictObject({
19081
19051
  path: external_exports.string().max(2048),
19082
19052
  terminalId: external_exports.string().max(255),
19083
19053
  text: LONG_TEXT,
19084
- type: external_exports.enum([
19085
- "diff",
19086
- "image",
19087
- "resource",
19088
- "resource_link",
19089
- "terminal",
19090
- "text"
19091
- ]),
19054
+ type: external_exports.enum(["diff", "image", "resource", "resource_link", "terminal", "text"]),
19092
19055
  uri: external_exports.string().max(4096)
19093
19056
  }).readonly();
19094
19057
  var recordedDisplayContentSchema = external_exports.strictObject({
@@ -19100,14 +19063,7 @@ var recordedDisplayContentSchema = external_exports.strictObject({
19100
19063
  path: external_exports.string().max(2048),
19101
19064
  terminalId: external_exports.string().max(255),
19102
19065
  text: external_exports.string().max(4e6),
19103
- type: external_exports.enum([
19104
- "diff",
19105
- "image",
19106
- "resource",
19107
- "resource_link",
19108
- "terminal",
19109
- "text"
19110
- ]),
19066
+ type: external_exports.enum(["diff", "image", "resource", "resource_link", "terminal", "text"]),
19111
19067
  uri: external_exports.string().max(4096)
19112
19068
  }).readonly();
19113
19069
  var promptImageSchema = external_exports.strictObject({
@@ -19400,12 +19356,7 @@ var MAX_PROMPT_LENGTH = 1e4;
19400
19356
  var MAX_PROMPT_ATTACHMENT_LENGTH = 6e6;
19401
19357
  var MAX_EVENT_TEXT_LENGTH = 1e5;
19402
19358
  var ACTIVITY_TYPES = /* @__PURE__ */ new Set(["plan", "progress", "reasoning", "tool"]);
19403
- var ACTIVITY_STATUSES = /* @__PURE__ */ new Set([
19404
- "pending",
19405
- "running",
19406
- "completed",
19407
- "failed"
19408
- ]);
19359
+ var ACTIVITY_STATUSES = /* @__PURE__ */ new Set(["pending", "running", "completed", "failed"]);
19409
19360
  var TOOL_KINDS = /* @__PURE__ */ new Set([
19410
19361
  "",
19411
19362
  "delete",
@@ -19553,9 +19504,7 @@ function readActivityDetail(value) {
19553
19504
  throw new ProtocolMessageError("Invalid recorded activity content");
19554
19505
  }
19555
19506
  const detail = {
19556
- content: contentValue.map(
19557
- (entry) => decodeRecordedAgentContentValue(entry)
19558
- ),
19507
+ content: contentValue.map((entry) => decodeRecordedAgentContentValue(entry)),
19559
19508
  input: readText(field, "input", AGENT_ACTIVITY_RECORDED_FIELD_LIMIT),
19560
19509
  kind,
19561
19510
  output: readText(field, "output", AGENT_ACTIVITY_RECORDED_FIELD_LIMIT)
@@ -19577,9 +19526,7 @@ function readIdentifier(value, key) {
19577
19526
  function readDirectoryIdentifier(value, key) {
19578
19527
  const field = readString(value, key, 2048);
19579
19528
  if (!DIRECTORY_IDENTIFIER_PATTERN2.test(field)) {
19580
- throw new ProtocolMessageError(
19581
- `Invalid directory identifier field: ${key}`
19582
- );
19529
+ throw new ProtocolMessageError(`Invalid directory identifier field: ${key}`);
19583
19530
  }
19584
19531
  return field;
19585
19532
  }
@@ -19617,11 +19564,7 @@ function decodeSessionPromptCommand(encoded) {
19617
19564
  throw new ProtocolMessageError("Prompt must contain content");
19618
19565
  }
19619
19566
  return {
19620
- additionalDirectoryIds: readDirectoryIdentifiers(
19621
- value,
19622
- "additionalDirectoryIds",
19623
- 16
19624
- ),
19567
+ additionalDirectoryIds: readDirectoryIdentifiers(value, "additionalDirectoryIds", 16),
19625
19568
  agentId: readIdentifier(value, "agentId"),
19626
19569
  bindingId: readIdentifier(value, "bindingId"),
19627
19570
  commandId: readIdentifier(value, "commandId"),
@@ -19798,32 +19741,30 @@ var SESSION_HISTORY_MESSAGE_LIMIT = 1e3;
19798
19741
  var SESSION_HISTORY_PREVIEW_MESSAGE_LIMIT = 10;
19799
19742
  var SESSION_HISTORY_IMAGE_CHARACTER_LIMIT = 4e6;
19800
19743
  var historyImage = external_exports.strictObject({
19801
- data: external_exports.string().min(4).max(SESSION_HISTORY_IMAGE_CHARACTER_LIMIT).refine(
19802
- (data) => data.length % 4 === 0 && /^[A-Za-z0-9+/]*={0,2}$/.test(data)
19803
- ),
19744
+ data: external_exports.string().min(4).max(SESSION_HISTORY_IMAGE_CHARACTER_LIMIT).refine((data) => data.length % 4 === 0 && /^[A-Za-z0-9+/]*={0,2}$/.test(data)),
19804
19745
  mimeType: external_exports.enum(["image/png", "image/jpeg", "image/gif", "image/webp"]),
19805
19746
  name: external_exports.string().min(1).max(500)
19806
19747
  }).readonly();
19807
19748
  function parseNativeHistoryText(text) {
19808
19749
  const images = [];
19809
19750
  let imageCharacters = 0;
19810
- const plainText = text.replace(
19811
- /\[@image\]\(([^)\r\n]*)(?:\)|$)/g,
19812
- (_marker, uri) => {
19813
- const header = /^data:(image\/[a-z+]+);base64,/.exec(uri);
19814
- if (header === null) return "[Image unavailable]";
19815
- const parsed = historyImage.safeParse({
19816
- data: uri.slice(header[0].length),
19817
- mimeType: header[1],
19818
- name: `Image ${(images.length + 1).toString()}`
19819
- });
19820
- if (!parsed.success || images.length >= 8 || imageCharacters + parsed.data.data.length > SESSION_HISTORY_IMAGE_CHARACTER_LIMIT)
19821
- return "[Image unavailable]";
19822
- images.push(parsed.data);
19823
- imageCharacters += parsed.data.data.length;
19824
- return "";
19751
+ const plainText = text.replace(/\[@image\]\(([^)\r\n]*)(?:\)|$)/g, (_marker, uri) => {
19752
+ const header = /^data:(image\/[a-z+]+);base64,/.exec(uri);
19753
+ if (header === null) {
19754
+ return "[Image unavailable]";
19755
+ }
19756
+ const parsed = historyImage.safeParse({
19757
+ data: uri.slice(header[0].length),
19758
+ mimeType: header[1],
19759
+ name: `Image ${(images.length + 1).toString()}`
19760
+ });
19761
+ if (!parsed.success || images.length >= 8 || imageCharacters + parsed.data.data.length > SESSION_HISTORY_IMAGE_CHARACTER_LIMIT) {
19762
+ return "[Image unavailable]";
19825
19763
  }
19826
- );
19764
+ images.push(parsed.data);
19765
+ imageCharacters += parsed.data.data.length;
19766
+ return "";
19767
+ });
19827
19768
  return { text: plainText, images };
19828
19769
  }
19829
19770
  var historyMessage = external_exports.strictObject({
@@ -19837,20 +19778,12 @@ var sessionHistorySchema = external_exports.discriminatedUnion("status", [
19837
19778
  messages: external_exports.array(historyMessage).max(SESSION_HISTORY_MESSAGE_LIMIT).readonly(),
19838
19779
  truncated: external_exports.boolean(),
19839
19780
  coveredCommandIds: external_exports.array(external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/)).max(1e4).readonly(),
19840
- coveredMessageIds: external_exports.array(
19841
- external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}:(?:user|agent)$/)
19842
- ).max(2e4).readonly().default([])
19781
+ coveredMessageIds: external_exports.array(external_exports.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}:(?:user|agent)$/)).max(2e4).readonly().default([])
19843
19782
  }).readonly(),
19844
19783
  external_exports.strictObject({ status: external_exports.literal("unavailable") }).readonly()
19845
19784
  ]).refine(
19846
- (history) => history.status === "unavailable" || history.messages.reduce(
19847
- (total, message) => total + message.text.length,
19848
- 0
19849
- ) <= SESSION_HISTORY_CHARACTER_LIMIT && history.messages.reduce(
19850
- (total, message) => total + (message.images ?? []).reduce(
19851
- (size, image) => size + image.data.length,
19852
- 0
19853
- ),
19785
+ (history) => history.status === "unavailable" || history.messages.reduce((total, message) => total + message.text.length, 0) <= SESSION_HISTORY_CHARACTER_LIMIT && history.messages.reduce(
19786
+ (total, message) => total + (message.images ?? []).reduce((size, image) => size + image.data.length, 0),
19854
19787
  0
19855
19788
  ) <= SESSION_HISTORY_IMAGE_CHARACTER_LIMIT
19856
19789
  );
@@ -19897,9 +19830,7 @@ var nativeSessionEntrySchema = external_exports.strictObject({
19897
19830
  directoryId,
19898
19831
  directoryLabel: external_exports.string().min(1).max(2048),
19899
19832
  updatedAt: external_exports.iso.datetime({ offset: true }).nullable(),
19900
- additionalDirectories: external_exports.array(
19901
- external_exports.strictObject({ directoryId, name: external_exports.string().min(1).max(255) }).readonly()
19902
- ).max(16).readonly()
19833
+ additionalDirectories: external_exports.array(external_exports.strictObject({ directoryId, name: external_exports.string().min(1).max(255) }).readonly()).max(16).readonly()
19903
19834
  }).readonly();
19904
19835
  var resultEnvelope = {
19905
19836
  ...envelope,
@@ -19950,535 +19881,49 @@ var decodeNativeSessionCommand = (encoded) => decode4(nativeSessionCommandSchema
19950
19881
  var encodeNativeSessionResult = (value) => JSON.stringify(nativeSessionResultSchema.parse(value));
19951
19882
  var decodeNativeSessionCancel = (encoded) => decode4(nativeSessionCancelSchema, encoded);
19952
19883
 
19953
- // ../protocol/src/resource-model.ts
19954
- var IDENTIFIER_PATTERN3 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
19955
- var DECIMAL_SEQUENCE_PATTERN = /^(?:0|[1-9][0-9]*)$/;
19956
- var SHA256_PATTERN = /^[a-f0-9]{64}$/;
19957
- var identifierSchema = external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3);
19958
- var timestampSchema = external_exports.string().datetime({ offset: true });
19959
- var decimalSequenceSchema = external_exports.string().min(1).max(40).regex(DECIMAL_SEQUENCE_PATTERN);
19960
- var digestSchema = external_exports.string().length(64).regex(SHA256_PATTERN);
19961
- var recordingPolicySchema = external_exports.strictObject({
19962
- contentLimitBytes: external_exports.number().int().positive().safe(),
19963
- hotEventLimit: external_exports.number().int().positive().safe(),
19964
- idempotencyRetentionMilliseconds: external_exports.number().int().positive().safe(),
19965
- level: external_exports.enum(["full", "summary"]),
19966
- retentionMilliseconds: external_exports.number().int().positive().safe()
19967
- }).readonly();
19968
- var tenantLifecycleSchema = external_exports.discriminatedUnion("kind", [
19969
- external_exports.strictObject({ kind: external_exports.literal("active") }).readonly(),
19970
- external_exports.strictObject({
19971
- kind: external_exports.literal("suspended"),
19972
- suspendedAt: timestampSchema
19973
- }).readonly(),
19974
- external_exports.strictObject({ deletedAt: timestampSchema, kind: external_exports.literal("deleted") }).readonly()
19975
- ]);
19976
- var tenantSchema = external_exports.strictObject({
19977
- lifecycle: tenantLifecycleSchema,
19978
- quotaPolicyRevision: external_exports.number().int().nonnegative().safe(),
19979
- recordingPolicy: recordingPolicySchema,
19980
- tenantId: identifierSchema
19981
- }).readonly();
19982
- var projectLifecycleSchema = external_exports.discriminatedUnion("kind", [
19983
- external_exports.strictObject({ kind: external_exports.literal("active") }).readonly(),
19984
- external_exports.strictObject({ archivedAt: timestampSchema, kind: external_exports.literal("archived") }).readonly(),
19985
- external_exports.strictObject({ deletedAt: timestampSchema, kind: external_exports.literal("deleted") }).readonly()
19986
- ]);
19987
- var projectSchema = external_exports.strictObject({
19988
- displayName: external_exports.string().min(1).max(120),
19989
- lifecycle: projectLifecycleSchema,
19990
- projectId: identifierSchema,
19991
- tenantId: identifierSchema
19992
- }).readonly();
19993
- var runtimeLifecycleSchema = external_exports.discriminatedUnion("kind", [
19994
- external_exports.strictObject({ kind: external_exports.literal("registered") }).readonly(),
19995
- external_exports.strictObject({ disabledAt: timestampSchema, kind: external_exports.literal("disabled") }).readonly(),
19996
- external_exports.strictObject({ deletedAt: timestampSchema, kind: external_exports.literal("deleted") }).readonly()
19997
- ]);
19998
- var runtimeCapabilitySchema = external_exports.strictObject({
19999
- name: identifierSchema,
20000
- revision: external_exports.number().int().nonnegative().safe()
20001
- }).readonly();
20002
- var runtimeSchema = external_exports.strictObject({
20003
- capabilities: external_exports.array(runtimeCapabilitySchema).max(100).readonly(),
20004
- displayName: external_exports.string().min(1).max(120),
20005
- lifecycle: runtimeLifecycleSchema,
20006
- runtimeId: identifierSchema,
20007
- tenantId: identifierSchema
20008
- }).readonly();
20009
- var channelStateSchema = external_exports.discriminatedUnion("kind", [
20010
- external_exports.strictObject({
20011
- connectionEpoch: external_exports.number().int().nonnegative().safe(),
20012
- connectedAt: timestampSchema,
20013
- connectionId: identifierSchema,
20014
- kind: external_exports.literal("online")
20015
- }).readonly(),
20016
- external_exports.strictObject({
20017
- connectionEpoch: external_exports.number().int().nonnegative().safe(),
20018
- disconnectedAt: timestampSchema,
20019
- kind: external_exports.literal("offline")
20020
- }).readonly()
20021
- ]);
20022
- var channelSchema = external_exports.strictObject({
20023
- channelId: identifierSchema,
20024
- runtimeId: identifierSchema,
20025
- state: channelStateSchema
20026
- }).readonly();
20027
- var sessionLifecycleSchema = external_exports.discriminatedUnion("kind", [
20028
- external_exports.strictObject({ kind: external_exports.literal("ready") }).readonly(),
20029
- external_exports.strictObject({ kind: external_exports.literal("deleting"), requestedAt: timestampSchema }).readonly(),
20030
- external_exports.strictObject({ completedAt: timestampSchema, kind: external_exports.literal("deleted") }).readonly()
20031
- ]);
20032
- var sessionSchema = external_exports.strictObject({
20033
- createdAt: timestampSchema,
20034
- createdBy: identifierSchema,
20035
- defaultBindingId: identifierSchema,
20036
- lastCommittedSeq: decimalSequenceSchema,
20037
- lifecycle: sessionLifecycleSchema,
20038
- projectId: identifierSchema,
20039
- sessionId: identifierSchema,
20040
- tenantId: identifierSchema
20041
- }).readonly();
20042
- var sessionBindingSchema = external_exports.strictObject({
20043
- agentRef: identifierSchema,
20044
- bindingId: identifierSchema,
20045
- configRevision: external_exports.number().int().nonnegative().safe(),
20046
- createdAt: timestampSchema,
20047
- runtimeId: identifierSchema,
20048
- sessionId: identifierSchema,
20049
- workspaceRef: identifierSchema
20050
- }).readonly();
20051
- var domainErrorSchema = external_exports.strictObject({
20052
- code: identifierSchema,
20053
- message: external_exports.string().min(1).max(2e3),
20054
- retryable: external_exports.boolean()
20055
- }).readonly();
20056
- var executionResultSchema = external_exports.strictObject({
20057
- kind: external_exports.literal("agent_result"),
20058
- stopReason: external_exports.string().min(1).max(128)
20059
- }).readonly();
20060
- var reconciliationSchema = external_exports.strictObject({
20061
- detectedAt: timestampSchema,
20062
- reason: external_exports.enum([
20063
- "connection_lost",
20064
- "dispatch_indeterminate",
20065
- "runtime_restarted"
20066
- ])
20067
- }).readonly();
20068
- var turnStateSchema = external_exports.discriminatedUnion("kind", [
20069
- external_exports.strictObject({ kind: external_exports.literal("queued") }).readonly(),
20070
- external_exports.strictObject({ kind: external_exports.literal("running"), startedAt: timestampSchema }).readonly(),
20071
- external_exports.strictObject({
20072
- completedAt: timestampSchema,
20073
- kind: external_exports.literal("succeeded"),
20074
- result: executionResultSchema
20075
- }).readonly(),
20076
- external_exports.strictObject({
20077
- error: domainErrorSchema,
20078
- failedAt: timestampSchema,
20079
- kind: external_exports.literal("failed")
20080
- }).readonly(),
20081
- external_exports.strictObject({
20082
- cancelledAt: timestampSchema,
20083
- kind: external_exports.literal("cancelled")
20084
- }).readonly(),
20085
- external_exports.strictObject({
20086
- kind: external_exports.literal("indeterminate"),
20087
- reconciliation: reconciliationSchema
20088
- }).readonly()
20089
- ]);
20090
- var turnRequestSchema = external_exports.discriminatedUnion("kind", [
20091
- external_exports.strictObject({
20092
- content: external_exports.string().max(1e5),
20093
- kind: external_exports.literal("prompt")
20094
- }).readonly()
20095
- ]);
20096
- var turnSchema = external_exports.strictObject({
20097
- acceptedAt: timestampSchema,
20098
- bindingId: identifierSchema,
20099
- idempotencyKey: identifierSchema,
20100
- request: turnRequestSchema,
20101
- sessionId: identifierSchema,
20102
- state: turnStateSchema,
20103
- turnId: identifierSchema
20104
- }).readonly();
20105
- var attemptStateSchema = external_exports.discriminatedUnion("kind", [
20106
- external_exports.strictObject({
20107
- dispatchedAt: timestampSchema,
20108
- kind: external_exports.literal("dispatching")
20109
- }).readonly(),
20110
- external_exports.strictObject({ kind: external_exports.literal("running"), startedAt: timestampSchema }).readonly(),
20111
- external_exports.strictObject({
20112
- interactionIds: external_exports.array(identifierSchema).min(1).max(100).readonly(),
20113
- kind: external_exports.literal("waiting_input"),
20114
- startedAt: timestampSchema
20115
- }).readonly(),
20116
- external_exports.strictObject({
20117
- completedAt: timestampSchema,
20118
- kind: external_exports.literal("succeeded"),
20119
- result: executionResultSchema,
20120
- startedAt: timestampSchema
20121
- }).readonly(),
20122
- external_exports.strictObject({
20123
- error: domainErrorSchema,
20124
- failedAt: timestampSchema,
20125
- kind: external_exports.literal("failed"),
20126
- startedAt: timestampSchema
20127
- }).readonly(),
20128
- external_exports.strictObject({
20129
- cancelledAt: timestampSchema,
20130
- kind: external_exports.literal("cancelled"),
20131
- startedAt: timestampSchema
20132
- }).readonly(),
20133
- external_exports.strictObject({
20134
- kind: external_exports.literal("indeterminate"),
20135
- reconciliation: reconciliationSchema,
20136
- startedAt: timestampSchema
20137
- }).readonly()
20138
- ]);
20139
- var attemptSchema = external_exports.strictObject({
20140
- attemptId: identifierSchema,
20141
- bindingId: identifierSchema,
20142
- sessionId: identifierSchema,
20143
- state: attemptStateSchema,
20144
- turnId: identifierSchema
20145
- }).readonly();
20146
- var permissionRequestSchema = external_exports.strictObject({
20147
- kind: external_exports.literal("permission"),
20148
- options: external_exports.array(permissionOptionSchema).min(1).max(20).readonly(),
20149
- title: external_exports.string().min(1).max(500),
20150
- toolCallId: external_exports.string().min(1).max(255),
20151
- toolKind: external_exports.string().max(64)
20152
- }).readonly();
20153
- var elicitationRequestSchema = external_exports.strictObject({
20154
- elicitationId: external_exports.string().max(255),
20155
- fields: external_exports.array(elicitationFieldSchema).max(100).readonly(),
20156
- kind: external_exports.literal("elicitation"),
20157
- message: external_exports.string().min(1).max(2e3),
20158
- mode: external_exports.enum(["form", "url"]),
20159
- url: external_exports.string().max(4096)
20160
- }).readonly();
20161
- var interactionRequestSchema = external_exports.discriminatedUnion("kind", [
20162
- permissionRequestSchema,
20163
- elicitationRequestSchema
20164
- ]);
20165
- var interactionResponseSchema = external_exports.strictObject({
20166
- content: external_exports.string().max(1e5),
20167
- kind: external_exports.enum(["permission", "elicitation"])
20168
- }).readonly();
20169
- var interactionStateSchema = external_exports.discriminatedUnion("kind", [
20170
- external_exports.strictObject({ kind: external_exports.literal("pending") }).readonly(),
20171
- external_exports.strictObject({
20172
- kind: external_exports.literal("responded"),
20173
- respondedAt: timestampSchema,
20174
- responderId: identifierSchema,
20175
- response: interactionResponseSchema
20176
- }).readonly(),
20177
- external_exports.strictObject({
20178
- kind: external_exports.literal("resolved"),
20179
- resolution: external_exports.discriminatedUnion("kind", [
20180
- external_exports.strictObject({ kind: external_exports.literal("without_response") }).readonly(),
20181
- external_exports.strictObject({
20182
- kind: external_exports.literal("response_applied"),
20183
- respondedAt: timestampSchema,
20184
- responderId: identifierSchema,
20185
- response: interactionResponseSchema
20186
- }).readonly()
20187
- ]),
20188
- resolvedAt: timestampSchema
20189
- }).readonly(),
20190
- external_exports.strictObject({ expiredAt: timestampSchema, kind: external_exports.literal("expired") }).readonly(),
20191
- external_exports.strictObject({
20192
- cancelledAt: timestampSchema,
20193
- kind: external_exports.literal("cancelled")
20194
- }).readonly()
20195
- ]);
20196
- var interactionSchema = external_exports.strictObject({
20197
- attemptId: identifierSchema,
20198
- interactionId: identifierSchema,
20199
- request: interactionRequestSchema,
20200
- sessionId: identifierSchema,
20201
- state: interactionStateSchema,
20202
- turnId: identifierSchema
20203
- }).readonly();
20204
- var recordingCompletenessSchema = external_exports.discriminatedUnion("kind", [
20205
- external_exports.strictObject({ kind: external_exports.literal("complete") }).readonly(),
20206
- external_exports.strictObject({
20207
- capturedBytes: external_exports.number().int().nonnegative().safe(),
20208
- kind: external_exports.literal("truncated"),
20209
- originalBytes: external_exports.number().int().positive().safe()
20210
- }).readonly(),
20211
- external_exports.strictObject({ kind: external_exports.literal("redacted"), reason: identifierSchema }).readonly(),
20212
- external_exports.strictObject({ kind: external_exports.literal("uncaptured") }).readonly()
20213
- ]);
20214
- var messageViewStateSchema = external_exports.discriminatedUnion("kind", [
20215
- external_exports.strictObject({ kind: external_exports.literal("building") }).readonly(),
20216
- external_exports.strictObject({
20217
- completeness: recordingCompletenessSchema,
20218
- kind: external_exports.literal("available")
20219
- }).readonly(),
20220
- external_exports.strictObject({ deletedAt: timestampSchema, kind: external_exports.literal("deleted") }).readonly()
20221
- ]);
20222
- var messageViewCommon = {
20223
- contentArtifactIds: external_exports.array(identifierSchema).max(100).readonly(),
20224
- lastAppliedSeq: decimalSequenceSchema,
20225
- messageId: identifierSchema,
20226
- preview: external_exports.string().max(4e3),
20227
- sessionId: identifierSchema,
20228
- state: messageViewStateSchema
20229
- };
20230
- var messageViewSchema = external_exports.discriminatedUnion("role", [
20231
- external_exports.strictObject({
20232
- ...messageViewCommon,
20233
- role: external_exports.literal("user"),
20234
- source: external_exports.strictObject({ kind: external_exports.literal("turn"), turnId: identifierSchema }).readonly()
20235
- }).readonly(),
20236
- external_exports.strictObject({
20237
- ...messageViewCommon,
20238
- role: external_exports.literal("agent"),
20239
- source: external_exports.strictObject({
20240
- attemptId: identifierSchema,
20241
- kind: external_exports.literal("attempt"),
20242
- turnId: identifierSchema
20243
- }).readonly()
20244
- }).readonly(),
20245
- external_exports.strictObject({
20246
- ...messageViewCommon,
20247
- role: external_exports.literal("tool"),
20248
- source: external_exports.strictObject({
20249
- attemptId: identifierSchema,
20250
- kind: external_exports.literal("tool_call"),
20251
- toolCallId: identifierSchema,
20252
- turnId: identifierSchema
20253
- }).readonly()
20254
- }).readonly(),
20255
- external_exports.strictObject({
20256
- ...messageViewCommon,
20257
- role: external_exports.literal("system"),
20258
- source: external_exports.strictObject({ kind: external_exports.literal("system") }).readonly()
20259
- }).readonly()
20260
- ]);
20261
- var toolCallDetailSchema = external_exports.discriminatedUnion("kind", [
20262
- external_exports.strictObject({
20263
- artifactId: identifierSchema,
20264
- kind: external_exports.literal("available")
20265
- }).readonly(),
20266
- external_exports.strictObject({
20267
- capturedBytes: external_exports.number().int().nonnegative().safe(),
20268
- kind: external_exports.literal("truncated"),
20269
- originalBytes: external_exports.number().int().positive().safe()
20270
- }).readonly(),
20271
- external_exports.strictObject({ kind: external_exports.literal("uncaptured") }).readonly(),
20272
- external_exports.strictObject({ deletedAt: timestampSchema, kind: external_exports.literal("deleted") }).readonly()
20273
- ]);
20274
- var toolCallViewStateSchema = external_exports.discriminatedUnion("kind", [
20275
- external_exports.strictObject({ kind: external_exports.literal("pending") }).readonly(),
20276
- external_exports.strictObject({ kind: external_exports.literal("running"), startedAt: timestampSchema }).readonly(),
20277
- external_exports.strictObject({
20278
- completedAt: timestampSchema,
20279
- kind: external_exports.literal("succeeded")
20280
- }).readonly(),
20281
- external_exports.strictObject({
20282
- error: domainErrorSchema,
20283
- failedAt: timestampSchema,
20284
- kind: external_exports.literal("failed")
20285
- }).readonly(),
20286
- external_exports.strictObject({
20287
- cancelledAt: timestampSchema,
20288
- kind: external_exports.literal("cancelled")
20289
- }).readonly()
20290
- ]);
20291
- var toolCallViewSchema = external_exports.strictObject({
20292
- attemptId: identifierSchema,
20293
- detail: toolCallDetailSchema,
20294
- inputPreview: external_exports.string().max(4e3),
20295
- lastAppliedSeq: decimalSequenceSchema,
20296
- name: external_exports.string().max(128),
20297
- outputPreview: external_exports.string().max(4e3),
20298
- state: toolCallViewStateSchema,
20299
- title: external_exports.string().min(1).max(500),
20300
- toolCallId: identifierSchema,
20301
- toolKind: identifierSchema
20302
- }).readonly();
20303
- var sessionListEntrySchema = external_exports.strictObject({
20304
- lastAppliedSeq: decimalSequenceSchema,
20305
- preview: external_exports.string().max(4e3),
20306
- projectId: identifierSchema,
20307
- projectedAttemptState: external_exports.enum([
20308
- "idle",
20309
- "dispatching",
20310
- "running",
20311
- "waiting_input",
20312
- "indeterminate"
20313
- ]),
20314
- sessionId: identifierSchema,
20315
- tenantId: identifierSchema,
20316
- title: external_exports.string().max(500),
20317
- updatedAt: timestampSchema
20318
- }).readonly();
20319
- var artifactStateSchema = external_exports.discriminatedUnion("kind", [
20320
- external_exports.strictObject({
20321
- expectedBytes: external_exports.number().int().nonnegative().safe(),
20322
- expiresAt: timestampSchema,
20323
- kind: external_exports.literal("uploading"),
20324
- uploadId: identifierSchema
20325
- }).readonly(),
20326
- external_exports.strictObject({
20327
- availableAt: timestampSchema,
20328
- byteLength: external_exports.number().int().nonnegative().safe(),
20329
- kind: external_exports.literal("available"),
20330
- sha256: digestSchema
20331
- }).readonly(),
20332
- external_exports.strictObject({ kind: external_exports.literal("deleting"), requestedAt: timestampSchema }).readonly(),
20333
- external_exports.strictObject({ completedAt: timestampSchema, kind: external_exports.literal("deleted") }).readonly(),
20334
- external_exports.strictObject({
20335
- error: domainErrorSchema,
20336
- failedAt: timestampSchema,
20337
- kind: external_exports.literal("failed")
20338
- }).readonly(),
20339
- external_exports.strictObject({ expiredAt: timestampSchema, kind: external_exports.literal("expired") }).readonly()
20340
- ]);
20341
- var artifactSchema = external_exports.strictObject({
20342
- artifactId: identifierSchema,
20343
- completeness: recordingCompletenessSchema,
20344
- contentKind: identifierSchema,
20345
- mediaType: external_exports.string().min(1).max(128),
20346
- projectId: identifierSchema,
20347
- provenance: external_exports.discriminatedUnion("kind", [
20348
- external_exports.strictObject({ kind: external_exports.literal("user_upload") }).readonly(),
20349
- external_exports.strictObject({
20350
- attemptId: identifierSchema,
20351
- kind: external_exports.literal("tool_call"),
20352
- toolCallId: identifierSchema,
20353
- turnId: identifierSchema
20354
- }).readonly(),
20355
- external_exports.strictObject({
20356
- attemptId: identifierSchema,
20357
- kind: external_exports.literal("agent_generated"),
20358
- turnId: identifierSchema
20359
- }).readonly()
20360
- ]),
20361
- sessionId: identifierSchema,
20362
- state: artifactStateSchema,
20363
- tenantId: identifierSchema
20364
- }).readonly();
20365
- var archiveSegmentStateSchema = external_exports.discriminatedUnion("kind", [
20366
- external_exports.strictObject({ kind: external_exports.literal("pending"), queuedAt: timestampSchema }).readonly(),
20367
- external_exports.strictObject({
20368
- byteLength: external_exports.number().int().nonnegative().safe(),
20369
- kind: external_exports.literal("uploaded"),
20370
- sha256: digestSchema,
20371
- uploadedAt: timestampSchema
20372
- }).readonly(),
20373
- external_exports.strictObject({
20374
- byteLength: external_exports.number().int().nonnegative().safe(),
20375
- kind: external_exports.literal("published"),
20376
- publishedAt: timestampSchema,
20377
- sha256: digestSchema
20378
- }).readonly(),
20379
- external_exports.strictObject({ kind: external_exports.literal("deleting"), requestedAt: timestampSchema }).readonly(),
20380
- external_exports.strictObject({ completedAt: timestampSchema, kind: external_exports.literal("deleted") }).readonly()
20381
- ]);
20382
- var archiveSegmentSchema = external_exports.strictObject({
20383
- compression: external_exports.literal("gzip"),
20384
- eventCount: external_exports.number().int().positive().safe(),
20385
- firstSeq: decimalSequenceSchema,
20386
- lastSeq: decimalSequenceSchema,
20387
- segmentId: identifierSchema,
20388
- sessionId: identifierSchema,
20389
- state: archiveSegmentStateSchema
20390
- }).readonly();
20391
- var pendingWorkStateSchema = external_exports.discriminatedUnion("kind", [
20392
- external_exports.strictObject({ kind: external_exports.literal("pending"), queuedAt: timestampSchema }).readonly(),
20393
- external_exports.strictObject({
20394
- attempt: external_exports.number().int().positive().safe(),
20395
- kind: external_exports.literal("running"),
20396
- startedAt: timestampSchema
20397
- }).readonly(),
20398
- external_exports.strictObject({
20399
- completedAt: timestampSchema,
20400
- kind: external_exports.literal("completed")
20401
- }).readonly(),
20402
- external_exports.strictObject({
20403
- error: domainErrorSchema,
20404
- kind: external_exports.literal("retryable"),
20405
- nextAttemptAt: timestampSchema
20406
- }).readonly(),
20407
- external_exports.strictObject({
20408
- error: domainErrorSchema,
20409
- failedAt: timestampSchema,
20410
- kind: external_exports.literal("failed")
20411
- }).readonly()
20412
- ]);
20413
- var pendingWorkSchema = external_exports.strictObject({
20414
- kind: external_exports.enum([
20415
- "archive",
20416
- "delete",
20417
- "dispatch",
20418
- "interaction_response",
20419
- "projection"
20420
- ]),
20421
- projectId: identifierSchema,
20422
- sessionId: identifierSchema,
20423
- state: pendingWorkStateSchema,
20424
- tenantId: identifierSchema,
20425
- workId: identifierSchema
20426
- }).readonly();
20427
- var commandReceiptSchema = external_exports.strictObject({
20428
- acceptedAt: timestampSchema,
20429
- commandKind: identifierSchema,
20430
- expiresAt: timestampSchema,
20431
- idempotencyKey: identifierSchema,
20432
- projectId: identifierSchema,
20433
- requestHash: digestSchema,
20434
- resultId: identifierSchema,
20435
- sessionId: identifierSchema,
20436
- tenantId: identifierSchema
20437
- }).readonly();
20438
-
20439
19884
  // ../protocol/src/session-events.ts
20440
19885
  var SESSION_EVENT_KIND = "session.event";
20441
19886
  var SESSION_EVENT_ACK_KIND = "session.event.ack";
20442
19887
  var SESSION_EVENT_COMMITTED_KIND = "session.event.committed";
20443
- var IDENTIFIER_PATTERN4 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
19888
+ var IDENTIFIER_PATTERN3 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
20444
19889
  var CURSOR_PATTERN = /^[A-Za-z0-9_-]{1,512}$/;
20445
19890
  var MAX_RECORDED_EVENT_LENGTH = 8 * 1024 * 1024;
20446
- var DECIMAL_SEQUENCE_PATTERN2 = /^(?:0|[1-9][0-9]*)$/;
19891
+ var DECIMAL_SEQUENCE_PATTERN = /^(?:0|[1-9][0-9]*)$/;
20447
19892
  var eventSourceSchema = external_exports.discriminatedUnion("kind", [
20448
19893
  external_exports.strictObject({
20449
- attemptId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN4),
19894
+ attemptId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
20450
19895
  kind: external_exports.literal("attempt"),
20451
- sourceSeq: external_exports.string().min(1).max(40).regex(DECIMAL_SEQUENCE_PATTERN2)
19896
+ sourceSeq: external_exports.string().min(1).max(40).regex(DECIMAL_SEQUENCE_PATTERN)
20452
19897
  }).readonly(),
20453
19898
  external_exports.strictObject({
20454
19899
  kind: external_exports.literal("runtime"),
20455
- sourceSeq: external_exports.string().min(1).max(40).regex(DECIMAL_SEQUENCE_PATTERN2)
19900
+ sourceSeq: external_exports.string().min(1).max(40).regex(DECIMAL_SEQUENCE_PATTERN)
20456
19901
  }).readonly()
20457
19902
  ]);
20458
19903
  var eventEnvelopeSchema = external_exports.strictObject({
20459
- eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN4),
19904
+ eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
20460
19905
  kind: external_exports.literal(SESSION_EVENT_KIND),
20461
19906
  payload: external_exports.string().min(2).max(MAX_RECORDED_EVENT_LENGTH),
20462
- sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN4),
19907
+ sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
20463
19908
  source: eventSourceSchema
20464
19909
  }).readonly();
20465
19910
  var committedEventSchema = external_exports.strictObject({
20466
19911
  cursor: external_exports.string().min(1).max(512).regex(CURSOR_PATTERN),
20467
- eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN4),
19912
+ eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
20468
19913
  kind: external_exports.literal(SESSION_EVENT_COMMITTED_KIND),
20469
19914
  payload: external_exports.string().min(2).max(MAX_RECORDED_EVENT_LENGTH),
20470
19915
  recordedAt: external_exports.string().datetime({ offset: true }),
20471
- sequence: external_exports.string().min(1).max(40).regex(DECIMAL_SEQUENCE_PATTERN2),
20472
- sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN4),
19916
+ sequence: external_exports.string().min(1).max(40).regex(DECIMAL_SEQUENCE_PATTERN),
19917
+ sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
20473
19918
  source: eventSourceSchema
20474
19919
  }).readonly();
20475
19920
  var eventAcknowledgementSchema = external_exports.strictObject({
20476
19921
  cursor: external_exports.string().min(1).max(512).regex(CURSOR_PATTERN),
20477
19922
  duplicate: external_exports.boolean(),
20478
- eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN4),
19923
+ eventId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3),
20479
19924
  kind: external_exports.literal(SESSION_EVENT_ACK_KIND),
20480
- sequence: external_exports.string().min(1).max(40).regex(DECIMAL_SEQUENCE_PATTERN2),
20481
- sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN4)
19925
+ sequence: external_exports.string().min(1).max(40).regex(DECIMAL_SEQUENCE_PATTERN),
19926
+ sessionId: external_exports.string().min(1).max(128).regex(IDENTIFIER_PATTERN3)
20482
19927
  }).readonly();
20483
19928
  function decode5(encoded, schema) {
20484
19929
  let value;
@@ -20510,6 +19955,38 @@ var decodeSessionEventAcknowledgement = (encoded) => decode5(encoded, eventAckno
20510
19955
  // src/agent-catalog/local-agent.ts
20511
19956
  import { realpathSync, statSync } from "node:fs";
20512
19957
 
19958
+ // src/acp/session-capabilities.ts
19959
+ function unsupportedSessionCapabilities() {
19960
+ return Object.freeze({
19961
+ additionalDirectories: false,
19962
+ audioPrompt: false,
19963
+ closeSession: false,
19964
+ deleteSession: false,
19965
+ embeddedContextPrompt: false,
19966
+ imagePrompt: false,
19967
+ listSessions: false,
19968
+ loadSession: false,
19969
+ resumeSession: false,
19970
+ unstableForkSession: false
19971
+ });
19972
+ }
19973
+ function normalizeAcpCapabilities(capabilities) {
19974
+ const session = capabilities.sessionCapabilities;
19975
+ const prompt = capabilities.promptCapabilities;
19976
+ return Object.freeze({
19977
+ additionalDirectories: session?.additionalDirectories != null,
19978
+ audioPrompt: prompt?.audio === true,
19979
+ closeSession: session?.close != null,
19980
+ deleteSession: session?.delete != null,
19981
+ embeddedContextPrompt: prompt?.embeddedContext === true,
19982
+ imagePrompt: prompt?.image === true,
19983
+ listSessions: session?.list != null,
19984
+ loadSession: capabilities.loadSession === true,
19985
+ resumeSession: session?.resume != null,
19986
+ unstableForkSession: session?.fork != null
19987
+ });
19988
+ }
19989
+
20513
19990
  // src/process/executable.ts
20514
19991
  import { execFile, spawn } from "node:child_process";
20515
19992
  import { constants } from "node:fs";
@@ -20572,9 +20049,7 @@ function executableExtensions(executableName, environment, platform) {
20572
20049
  return [""];
20573
20050
  }
20574
20051
  const configured = environment["PATHEXT"] ?? ".COM;.EXE;.BAT;.CMD";
20575
- const extensions = configured.split(";").map((extension) => extension.trim()).filter((extension) => extension.length > 0).map(
20576
- (extension) => extension.startsWith(".") ? extension : `.${extension}`
20577
- );
20052
+ const extensions = configured.split(";").map((extension) => extension.trim()).filter((extension) => extension.length > 0).map((extension) => extension.startsWith(".") ? extension : `.${extension}`);
20578
20053
  return extensions.length > 0 ? extensions : [".EXE"];
20579
20054
  }
20580
20055
  async function resolveExecutablePath(requestedPath, platform = process.platform) {
@@ -20605,19 +20080,13 @@ async function resolveExecutablePath(requestedPath, platform = process.platform)
20605
20080
  async function findExecutableOnPath(executableName, environment, platform = process.platform) {
20606
20081
  const encodedPath = environment["PATH"] ?? "";
20607
20082
  const separator = platform === "win32" ? ";" : ":";
20608
- const extensions = executableExtensions(
20609
- executableName,
20610
- environment,
20611
- platform
20612
- );
20083
+ const extensions = executableExtensions(executableName, environment, platform);
20613
20084
  for (const entry of encodedPath.split(separator)) {
20614
20085
  if (entry.length === 0) {
20615
20086
  continue;
20616
20087
  }
20617
20088
  for (const extension of extensions) {
20618
- const requestedPath = resolve(
20619
- join(entry, `${executableName}${extension}`)
20620
- );
20089
+ const requestedPath = resolve(join(entry, `${executableName}${extension}`));
20621
20090
  const executable = await resolveExecutablePath(requestedPath, platform);
20622
20091
  if (executable !== null) {
20623
20092
  return executable;
@@ -20633,10 +20102,7 @@ async function revalidateExecutable(identity2, platform = process.platform) {
20633
20102
  function appendBounded(chunks, chunk, currentBytes, limitBytes) {
20634
20103
  const nextBytes = currentBytes + chunk.byteLength;
20635
20104
  if (nextBytes > limitBytes) {
20636
- throw new ProcessExecutionError(
20637
- "process_output_limit",
20638
- "The executable produced too much output"
20639
- );
20105
+ throw new ProcessExecutionError("process_output_limit", "The executable produced too much output");
20640
20106
  }
20641
20107
  chunks.push(chunk);
20642
20108
  return nextBytes;
@@ -20644,9 +20110,7 @@ function appendBounded(chunks, chunk, currentBytes, limitBytes) {
20644
20110
  function parseProcessTable(output2) {
20645
20111
  const entries = [];
20646
20112
  for (const line of output2.split("\n")) {
20647
- const groups = /^\s*(?<pid>\d+)\s+(?<ppid>\d+)\s+(?<pgid>\d+)\s*$/.exec(
20648
- line
20649
- )?.groups;
20113
+ const groups = /^\s*(?<pid>\d+)\s+(?<ppid>\d+)\s+(?<pgid>\d+)\s*$/.exec(line)?.groups;
20650
20114
  if (groups === void 0) {
20651
20115
  continue;
20652
20116
  }
@@ -20789,10 +20253,7 @@ async function stopProcessTree(child, capturedProcesses = []) {
20789
20253
  if (childExited && capturedProcesses.length === 0) {
20790
20254
  return;
20791
20255
  }
20792
- const processes = mergeProcessTrees(
20793
- capturedProcesses,
20794
- childExited ? [] : await captureProcessTree(child)
20795
- );
20256
+ const processes = mergeProcessTrees(capturedProcesses, childExited ? [] : await captureProcessTree(child));
20796
20257
  signalDetachedProcessGroups(processes, childProcessId, GRACEFUL_STOP_SIGNAL);
20797
20258
  terminateProcess(child);
20798
20259
  const [exitedAfterTermination, descendantsExitedAfterTermination] = await Promise.all([
@@ -20809,10 +20270,7 @@ async function stopProcessTree(child, capturedProcesses = []) {
20809
20270
  waitForCapturedProcessesExit(processes, childProcessId)
20810
20271
  ]);
20811
20272
  if (!exitedAfterForce || !descendantsExitedAfterForce) {
20812
- throw new ProcessExecutionError(
20813
- "process_termination_timeout",
20814
- "The executable process could not be stopped"
20815
- );
20273
+ throw new ProcessExecutionError("process_termination_timeout", "The executable process could not be stopped");
20816
20274
  }
20817
20275
  }
20818
20276
  function waitForProcessExit(child, timeoutMilliseconds) {
@@ -20884,11 +20342,9 @@ async function runBoundedProcess(options) {
20884
20342
  try {
20885
20343
  stdoutBytes = appendBounded(stdout, chunk, stdoutBytes, outputLimitBytes);
20886
20344
  } catch (error61) {
20887
- const failure = error61 instanceof ProcessExecutionError ? error61 : new ProcessExecutionError(
20888
- "process_output_limit",
20889
- "The executable produced too much output",
20890
- { cause: error61 }
20891
- );
20345
+ const failure = error61 instanceof ProcessExecutionError ? error61 : new ProcessExecutionError("process_output_limit", "The executable produced too much output", {
20346
+ cause: error61
20347
+ });
20892
20348
  interrupt(failure);
20893
20349
  }
20894
20350
  };
@@ -20899,30 +20355,21 @@ async function runBoundedProcess(options) {
20899
20355
  try {
20900
20356
  stderrBytes = appendBounded(stderr, chunk, stderrBytes, outputLimitBytes);
20901
20357
  } catch (error61) {
20902
- const failure = error61 instanceof ProcessExecutionError ? error61 : new ProcessExecutionError(
20903
- "process_output_limit",
20904
- "The executable produced too much output",
20905
- { cause: error61 }
20906
- );
20358
+ const failure = error61 instanceof ProcessExecutionError ? error61 : new ProcessExecutionError("process_output_limit", "The executable produced too much output", {
20359
+ cause: error61
20360
+ });
20907
20361
  interrupt(failure);
20908
20362
  }
20909
20363
  };
20910
20364
  child.stdout?.on("data", collectStdout);
20911
20365
  child.stderr?.on("data", collectStderr);
20912
20366
  const timeout = setTimeout(() => {
20913
- interrupt(
20914
- new ProcessExecutionError(
20915
- "process_timeout",
20916
- "The executable probe timed out"
20917
- )
20918
- );
20367
+ interrupt(new ProcessExecutionError("process_timeout", "The executable probe timed out"));
20919
20368
  }, options.timeoutMilliseconds);
20920
20369
  const abort = () => interrupt(
20921
- new ProcessExecutionError(
20922
- "process_cancelled",
20923
- "The executable probe was cancelled",
20924
- { cause: options.signal.reason }
20925
- )
20370
+ new ProcessExecutionError("process_cancelled", "The executable probe was cancelled", {
20371
+ cause: options.signal.reason
20372
+ })
20926
20373
  );
20927
20374
  options.signal.addEventListener("abort", abort, { once: true });
20928
20375
  if (options.signal.aborted) {
@@ -20933,10 +20380,7 @@ async function runBoundedProcess(options) {
20933
20380
  child.once("error", rejectExit);
20934
20381
  child.once("exit", (code) => resolveExit(code ?? 1));
20935
20382
  });
20936
- const exitCode = await Promise.race([
20937
- exit,
20938
- interrupted.promise.then(() => -1)
20939
- ]);
20383
+ const exitCode = await Promise.race([exit, interrupted.promise.then(() => -1)]);
20940
20384
  if (interruptionCleanupFailure !== null) {
20941
20385
  throw interruptionCleanupFailure;
20942
20386
  }
@@ -20944,24 +20388,16 @@ async function runBoundedProcess(options) {
20944
20388
  throw interruptionFailure;
20945
20389
  }
20946
20390
  if (exitCode !== 0) {
20947
- throw new ProcessExecutionError(
20948
- "process_exit_failed",
20949
- "The executable probe failed"
20950
- );
20391
+ throw new ProcessExecutionError("process_exit_failed", "The executable probe failed");
20951
20392
  }
20952
- return new ProcessResult(
20953
- Buffer.concat(stdout).toString("utf8"),
20954
- Buffer.concat(stderr).toString("utf8")
20955
- );
20393
+ return new ProcessResult(Buffer.concat(stdout).toString("utf8"), Buffer.concat(stderr).toString("utf8"));
20956
20394
  } catch (error61) {
20957
20395
  if (error61 instanceof ProcessExecutionError) {
20958
20396
  throw error61;
20959
20397
  }
20960
- throw new ProcessExecutionError(
20961
- "process_spawn_failed",
20962
- "The executable could not be started",
20963
- { cause: error61 }
20964
- );
20398
+ throw new ProcessExecutionError("process_spawn_failed", "The executable could not be started", {
20399
+ cause: error61
20400
+ });
20965
20401
  } finally {
20966
20402
  clearTimeout(timeout);
20967
20403
  options.signal.removeEventListener("abort", abort);
@@ -20996,11 +20432,12 @@ var LocalAgentDefinition = class {
20996
20432
  agentVersion;
20997
20433
  arguments;
20998
20434
  command;
20435
+ capabilities;
20999
20436
  environment;
21000
20437
  id;
21001
20438
  label;
21002
20439
  promptTimeoutMilliseconds;
21003
- constructor(id, label, command, arguments_, environment = {}, adapterVersion = "", agentVersion = "", adapterIdentity = readTrustedIdentity(command), agentIdentity = adapterIdentity, promptTimeoutMilliseconds = 30 * 60 * 1e3) {
20440
+ constructor(id, label, command, arguments_, environment = {}, adapterVersion = "", agentVersion = "", adapterIdentity = readTrustedIdentity(command), agentIdentity = adapterIdentity, promptTimeoutMilliseconds = 30 * 60 * 1e3, capabilities = unsupportedSessionCapabilities()) {
21004
20441
  if (!Number.isSafeInteger(promptTimeoutMilliseconds) || promptTimeoutMilliseconds < 1) {
21005
20442
  throw new Error("The local Agent prompt deadline is invalid");
21006
20443
  }
@@ -21009,6 +20446,7 @@ var LocalAgentDefinition = class {
21009
20446
  this.adapterVersion = adapterVersion;
21010
20447
  this.agentIdentity = agentIdentity;
21011
20448
  this.agentVersion = agentVersion;
20449
+ this.capabilities = Object.freeze({ ...capabilities });
21012
20450
  this.id = id;
21013
20451
  this.label = label;
21014
20452
  this.promptTimeoutMilliseconds = promptTimeoutMilliseconds;
@@ -21139,9 +20577,7 @@ function loadDaemonConfig() {
21139
20577
  defaultWorkspace: loadDefaultWorkspace(),
21140
20578
  auditDatabasePath: (
21141
20579
  // biome-ignore lint/complexity/useLiteralKeys: Environment variables use an index signature.
21142
- process.env["MOBIUS_AUDIT_DATABASE"] ?? fileURLToPath(
21143
- new URL("../../../.mobius/daemon.sqlite", import.meta.url)
21144
- )
20580
+ process.env["MOBIUS_AUDIT_DATABASE"] ?? fileURLToPath(new URL("../../../.mobius/daemon.sqlite", import.meta.url))
21145
20581
  ),
21146
20582
  // biome-ignore lint/complexity/useLiteralKeys: Environment variables use an index signature.
21147
20583
  channelId: process.env["MOBIUS_CHANNEL_ID"] ?? "local",
@@ -21179,11 +20615,7 @@ var AcpActivity = class _AcpActivity {
21179
20615
  toolKind;
21180
20616
  content;
21181
20617
  detail;
21182
- constructor(activityId, activityType, input2, locations, name, output2, sequence, status, title2, toolKind, content = [], detail = captureActivityDetail(
21183
- content,
21184
- input2,
21185
- output2
21186
- )) {
20618
+ constructor(activityId, activityType, input2, locations, name, output2, sequence, status, title2, toolKind, content = [], detail = captureActivityDetail(content, input2, output2)) {
21187
20619
  this.activityId = activityId;
21188
20620
  this.activityType = activityType;
21189
20621
  this.input = input2;
@@ -21385,10 +20817,7 @@ function normalizeLocations(locations) {
21385
20817
  break;
21386
20818
  }
21387
20819
  const suffix = typeof location.line === "number" ? `:${location.line.toString()}` : "";
21388
- const value = truncate(
21389
- `${location.path}${suffix}`,
21390
- AGENT_ACTIVITY_LOCATION_LENGTH_LIMIT
21391
- );
20820
+ const value = truncate(`${location.path}${suffix}`, AGENT_ACTIVITY_LOCATION_LENGTH_LIMIT);
21392
20821
  if (value.length > 0 && !unique.has(value)) {
21393
20822
  unique.add(value);
21394
20823
  normalized.push(value);
@@ -21606,9 +21035,7 @@ var AcpActivityTracker = class {
21606
21035
  };
21607
21036
  finish = async () => {
21608
21037
  await this.finishNarrative();
21609
- const entries = [...this.#activities.entries()].sort(
21610
- (left, right) => left[1].sequence - right[1].sequence
21611
- );
21038
+ const entries = [...this.#activities.entries()].sort((left, right) => left[1].sequence - right[1].sequence);
21612
21039
  for (const [key, activity] of entries) {
21613
21040
  const completed = activity.complete();
21614
21041
  if (completed !== activity) {
@@ -21621,10 +21048,7 @@ var AcpActivityTracker = class {
21621
21048
  if (existing !== void 0) {
21622
21049
  return existing;
21623
21050
  }
21624
- const identity2 = new ActivityIdentity(
21625
- `activity-${crypto.randomUUID()}`,
21626
- this.#nextSequence
21627
- );
21051
+ const identity2 = new ActivityIdentity(`activity-${crypto.randomUUID()}`, this.#nextSequence);
21628
21052
  this.#nextSequence += 1;
21629
21053
  this.#identities.set(key, identity2);
21630
21054
  return identity2;
@@ -21697,10 +21121,7 @@ function normalizeConfigValue(option, groupId = "", groupName = "") {
21697
21121
  description: truncate2(readString2(option["description"]), 500),
21698
21122
  groupId: truncate2(groupId, 128),
21699
21123
  groupName: truncate2(groupName, 255),
21700
- name: truncate2(
21701
- readString2(option["name"], readString2(option["value"])),
21702
- 255
21703
- ),
21124
+ name: truncate2(readString2(option["name"], readString2(option["value"])), 255),
21704
21125
  value: truncate2(readString2(option["value"]), 500)
21705
21126
  };
21706
21127
  }
@@ -21719,9 +21140,7 @@ function normalizeConfigValues(value) {
21719
21140
  const groupName = readString2(entry["name"]);
21720
21141
  for (const groupedOption of groupedOptions) {
21721
21142
  if (isRecord3(groupedOption)) {
21722
- normalized.push(
21723
- normalizeConfigValue(groupedOption, groupId, groupName)
21724
- );
21143
+ normalized.push(normalizeConfigValue(groupedOption, groupId, groupName));
21725
21144
  }
21726
21145
  }
21727
21146
  continue;
@@ -21837,11 +21256,7 @@ function ensureReasoningEffortOption(current) {
21837
21256
  if (modelIndex < 0) {
21838
21257
  return [...current, unavailable];
21839
21258
  }
21840
- return [
21841
- ...current.slice(0, modelIndex + 1),
21842
- unavailable,
21843
- ...current.slice(modelIndex + 1)
21844
- ];
21259
+ return [...current.slice(0, modelIndex + 1), unavailable, ...current.slice(modelIndex + 1)];
21845
21260
  }
21846
21261
  if (modelIndex < 0) {
21847
21262
  return [...current.slice(0, MAXIMUM_CONFIG_OPTIONS - 1), unavailable];
@@ -21861,22 +21276,15 @@ function ensureReasoningEffortOption(current) {
21861
21276
  }
21862
21277
  function normalizeStandardLifecycle(response) {
21863
21278
  const lifecycle = isRecord3(response) ? response : {};
21864
- return ensureReasoningEffortOption(
21865
- normalizeConfigOptions(lifecycle["configOptions"], lifecycle["modes"])
21866
- );
21279
+ return ensureReasoningEffortOption(normalizeConfigOptions(lifecycle["configOptions"], lifecycle["modes"]));
21867
21280
  }
21868
21281
  function replaceStandardConfigOptions(current, value) {
21869
21282
  const next = normalizeConfigOptions(value, void 0);
21870
- const withMode = next.some((option) => option.category === "mode") ? next : [
21871
- ...current.filter((option) => option.category === "mode"),
21872
- ...next
21873
- ].slice(0, 100);
21283
+ const withMode = next.some((option) => option.category === "mode") ? next : [...current.filter((option) => option.category === "mode"), ...next].slice(0, 100);
21874
21284
  return ensureReasoningEffortOption(withMode);
21875
21285
  }
21876
21286
  function updateCurrentValue(current, configId, value) {
21877
- return current.map(
21878
- (option) => option.id === configId ? { ...option, currentValue: value } : option
21879
- );
21287
+ return current.map((option) => option.id === configId ? { ...option, currentValue: value } : option);
21880
21288
  }
21881
21289
  var StandardSessionConfigProtocol = class {
21882
21290
  configure = async (current, change, nativeSessionId, transport) => {
@@ -21910,9 +21318,7 @@ var StandardSessionConfigProtocol = class {
21910
21318
  change.signal
21911
21319
  );
21912
21320
  if (!isRecord3(response) || !Array.isArray(response["configOptions"])) {
21913
- throw new SessionConfigProtocolError(
21914
- "The Agent returned an invalid session configuration response"
21915
- );
21321
+ throw new SessionConfigProtocolError("The Agent returned an invalid session configuration response");
21916
21322
  }
21917
21323
  return replaceStandardConfigOptions(current, response["configOptions"]);
21918
21324
  };
@@ -21986,9 +21392,7 @@ function legacyModelOptions(response) {
21986
21392
  }
21987
21393
  }
21988
21394
  }
21989
- const selected = options.find(
21990
- (option) => option["category"] === "model" && option["selected"] === true
21991
- );
21395
+ const selected = options.find((option) => option["category"] === "model" && option["selected"] === true);
21992
21396
  const currentValue = readString2(
21993
21397
  models["currentModelId"],
21994
21398
  selected === void 0 ? "" : readString2(selected["id"])
@@ -22023,9 +21427,7 @@ function legacyReasoningEffortOptions(response) {
22023
21427
  if (values.length === 0) {
22024
21428
  return [];
22025
21429
  }
22026
- const selected = options.find(
22027
- (option) => option["category"] === "mode" && option["selected"] === true
22028
- );
21430
+ const selected = options.find((option) => option["category"] === "mode" && option["selected"] === true);
22029
21431
  if (selected === void 0) {
22030
21432
  values.unshift({
22031
21433
  description: "Use the selected model's default reasoning effort",
@@ -22053,10 +21455,7 @@ function legacyReasoningEffortOptions(response) {
22053
21455
  }
22054
21456
  function normalizeGrokLifecycle(response) {
22055
21457
  const lifecycle = isRecord3(response) ? response : {};
22056
- const standard = normalizeConfigOptions(
22057
- lifecycle["configOptions"],
22058
- lifecycle["modes"]
22059
- );
21458
+ const standard = normalizeConfigOptions(lifecycle["configOptions"], lifecycle["modes"]);
22060
21459
  const normalized = [...standard];
22061
21460
  if (!normalized.some((option) => option.category === "model")) {
22062
21461
  normalized.push(...legacyModelOptions(response));
@@ -22064,47 +21463,30 @@ function normalizeGrokLifecycle(response) {
22064
21463
  if (!normalized.some((option) => option.category === "thought_level")) {
22065
21464
  const efforts = legacyReasoningEffortOptions(response);
22066
21465
  if (efforts.length > 0) {
22067
- const modelIndex = normalized.findIndex(
22068
- (option) => option.category === "model"
22069
- );
22070
- normalized.splice(
22071
- modelIndex < 0 ? normalized.length : modelIndex + 1,
22072
- 0,
22073
- ...efforts
22074
- );
21466
+ const modelIndex = normalized.findIndex((option) => option.category === "model");
21467
+ normalized.splice(modelIndex < 0 ? normalized.length : modelIndex + 1, 0, ...efforts);
22075
21468
  }
22076
21469
  }
22077
21470
  return ensureReasoningEffortOption(normalized.slice(0, 100));
22078
21471
  }
22079
21472
  function updateCurrentValue2(current, category, value) {
22080
- return current.map(
22081
- (option) => option.category === category ? { ...option, currentValue: value } : option
22082
- );
21473
+ return current.map((option) => option.category === category ? { ...option, currentValue: value } : option);
22083
21474
  }
22084
21475
  function validateGrokResponse(response, modelId) {
22085
21476
  if (!isRecord3(response) || !isRecord3(response["_meta"])) {
22086
- throw new SessionConfigProtocolError(
22087
- "Grok Build returned an invalid session configuration response"
22088
- );
21477
+ throw new SessionConfigProtocolError("Grok Build returned an invalid session configuration response");
22089
21478
  }
22090
21479
  const model = response["_meta"]["model"];
22091
21480
  const appliedModel = isRecord3(model) ? model["Ok"] : model;
22092
21481
  if (appliedModel !== modelId) {
22093
- throw new SessionConfigProtocolError(
22094
- "Grok Build returned an invalid session configuration response"
22095
- );
21482
+ throw new SessionConfigProtocolError("Grok Build returned an invalid session configuration response");
22096
21483
  }
22097
21484
  }
22098
21485
  var GrokBuildSessionConfigProtocol = class {
22099
21486
  configure = async (current, change, nativeSessionId, transport) => {
22100
21487
  const existing = current.find((option) => option.id === change.configId);
22101
21488
  if (existing === void 0 || existing.id !== LEGACY_MODEL_CONFIG_ID && existing.id !== LEGACY_REASONING_EFFORT_CONFIG_ID) {
22102
- return await standardSessionConfigProtocol.configure(
22103
- current,
22104
- change,
22105
- nativeSessionId,
22106
- transport
22107
- );
21489
+ return await standardSessionConfigProtocol.configure(current, change, nativeSessionId, transport);
22108
21490
  }
22109
21491
  const model = current.find((option) => option.category === "model");
22110
21492
  if (model === void 0) {
@@ -22130,17 +21512,11 @@ var GrokBuildSessionConfigProtocol = class {
22130
21512
  change.signal
22131
21513
  );
22132
21514
  validateGrokResponse(response, modelId);
22133
- const updated = updateCurrentValue2(
22134
- current,
22135
- existing.category,
22136
- change.value
22137
- );
21515
+ const updated = updateCurrentValue2(current, existing.category, change.value);
22138
21516
  return existing.category === "thought_level" ? updated.map(
22139
21517
  (option) => option.category === "thought_level" ? {
22140
21518
  ...option,
22141
- values: option.values.filter(
22142
- (value) => value.value !== AGENT_DEFAULT_REASONING_EFFORT
22143
- )
21519
+ values: option.values.filter((value) => value.value !== AGENT_DEFAULT_REASONING_EFFORT)
22144
21520
  } : option
22145
21521
  ) : updated;
22146
21522
  };
@@ -22162,17 +21538,21 @@ var AcpHistoryReplay = class {
22162
21538
  #imageCharacters = 0;
22163
21539
  #truncated = false;
22164
21540
  record = (update) => {
22165
- if (update.sessionUpdate !== "user_message_chunk" && update.sessionUpdate !== "agent_message_chunk")
21541
+ if (update.sessionUpdate !== "user_message_chunk" && update.sessionUpdate !== "agent_message_chunk") {
22166
21542
  return;
22167
- if (update.sessionUpdate === "agent_message_chunk" && isProgressMessage(update))
21543
+ }
21544
+ if (update.sessionUpdate === "agent_message_chunk" && isProgressMessage(update)) {
22168
21545
  return;
21546
+ }
22169
21547
  const role = update.sessionUpdate === "user_message_chunk" ? "user" : "assistant";
22170
21548
  const content = update.content;
22171
21549
  const parsed = parseNativeHistoryText(
22172
21550
  content.type === "text" ? content.text : content.type === "image" ? `[@image](data:${content.mimeType};base64,${content.data})` : `[${content.type} attachment]`
22173
21551
  );
22174
21552
  const text = parsed.text;
22175
- if (text.length === 0 && parsed.images.length === 0) return;
21553
+ if (text.length === 0 && parsed.images.length === 0) {
21554
+ return;
21555
+ }
22176
21556
  const previous = this.#messages.at(-1);
22177
21557
  const id = update.messageId ?? null;
22178
21558
  const continuation = previous?.role === role && id === this.#lastMessageId;
@@ -22183,10 +21563,7 @@ var AcpHistoryReplay = class {
22183
21563
  if (continuation) {
22184
21564
  this.#messages.pop();
22185
21565
  this.#characters -= previous.text.length;
22186
- this.#imageCharacters -= (previous.images ?? []).reduce(
22187
- (size, image) => size + image.data.length,
22188
- 0
22189
- );
21566
+ this.#imageCharacters -= (previous.images ?? []).reduce((size, image) => size + image.data.length, 0);
22190
21567
  }
22191
21568
  const bounded = combined.slice(-SESSION_HISTORY_CHARACTER_LIMIT);
22192
21569
  this.#truncated ||= bounded.length < combined.length;
@@ -22196,19 +21573,13 @@ var AcpHistoryReplay = class {
22196
21573
  ...images.length > 0 ? { images } : {}
22197
21574
  });
22198
21575
  this.#characters += bounded.length;
22199
- this.#imageCharacters += images.reduce(
22200
- (size, image) => size + image.data.length,
22201
- 0
22202
- );
21576
+ this.#imageCharacters += images.reduce((size, image) => size + image.data.length, 0);
22203
21577
  this.#lastMessageId = id;
22204
21578
  while (this.#messages.length > SESSION_HISTORY_PREVIEW_MESSAGE_LIMIT || this.#characters > SESSION_HISTORY_CHARACTER_LIMIT || this.#imageCharacters > SESSION_HISTORY_IMAGE_CHARACTER_LIMIT) {
22205
21579
  const removed = this.#messages.shift();
22206
21580
  if (removed !== void 0) {
22207
21581
  this.#characters -= removed.text.length;
22208
- this.#imageCharacters -= (removed.images ?? []).reduce(
22209
- (size, image) => size + image.data.length,
22210
- 0
22211
- );
21582
+ this.#imageCharacters -= (removed.images ?? []).reduce((size, image) => size + image.data.length, 0);
22212
21583
  }
22213
21584
  this.#truncated = true;
22214
21585
  }
@@ -22303,9 +21674,7 @@ var MemoryAcpSessionStore = class {
22303
21674
  (session) => session.agentId === agentId && session.nativeSessionId === nativeSessionId
22304
21675
  );
22305
21676
  markDeleted = (agentId, nativeSessionId) => {
22306
- const ids = this.findNative(agentId, nativeSessionId).map(
22307
- (session) => session.sessionId
22308
- );
21677
+ const ids = this.findNative(agentId, nativeSessionId).map((session) => session.sessionId);
22309
21678
  for (const id of ids) {
22310
21679
  this.#sessions.delete(id);
22311
21680
  this.#deleted.add(id);
@@ -22313,7 +21682,9 @@ var MemoryAcpSessionStore = class {
22313
21682
  return ids;
22314
21683
  };
22315
21684
  read = (sessionId) => {
22316
- if (this.#deleted.has(sessionId)) return new DeletedAcpStoredSession();
21685
+ if (this.#deleted.has(sessionId)) {
21686
+ return new DeletedAcpStoredSession();
21687
+ }
22317
21688
  const session = this.#sessions.get(sessionId);
22318
21689
  return session === void 0 ? new MissingAcpStoredSession() : new FoundAcpStoredSession(session);
22319
21690
  };
@@ -22353,10 +21724,9 @@ var SqliteAcpSessionStore = class {
22353
21724
  }
22354
21725
  }
22355
21726
  read = (sessionId) => {
22356
- if (this.#database.prepare(
22357
- "SELECT session_id FROM acp_deleted_sessions WHERE session_id = ?"
22358
- ).get(sessionId) !== void 0)
21727
+ if (this.#database.prepare("SELECT session_id FROM acp_deleted_sessions WHERE session_id = ?").get(sessionId) !== void 0) {
22359
21728
  return new DeletedAcpStoredSession();
21729
+ }
22360
21730
  const row = this.#database.prepare(
22361
21731
  `
22362
21732
  SELECT
@@ -22375,19 +21745,13 @@ var SqliteAcpSessionStore = class {
22375
21745
  remove = (sessionId) => {
22376
21746
  this.#database.prepare("DELETE FROM acp_sessions WHERE session_id = ?").run(sessionId);
22377
21747
  };
22378
- findNative = (agentId, nativeSessionId) => this.#database.prepare(
22379
- "SELECT * FROM acp_sessions WHERE agent_id = ? AND native_session_id = ?"
22380
- ).all(agentId, nativeSessionId).map(decodeSessionRow);
21748
+ findNative = (agentId, nativeSessionId) => this.#database.prepare("SELECT * FROM acp_sessions WHERE agent_id = ? AND native_session_id = ?").all(agentId, nativeSessionId).map(decodeSessionRow);
22381
21749
  markDeleted = (agentId, nativeSessionId) => {
22382
- const ids = this.findNative(agentId, nativeSessionId).map(
22383
- (session) => session.sessionId
22384
- );
21750
+ const ids = this.findNative(agentId, nativeSessionId).map((session) => session.sessionId);
22385
21751
  this.#database.exec("BEGIN");
22386
21752
  try {
22387
21753
  for (const id of ids) {
22388
- this.#database.prepare(
22389
- "INSERT OR IGNORE INTO acp_deleted_sessions (session_id) VALUES (?)"
22390
- ).run(id);
21754
+ this.#database.prepare("INSERT OR IGNORE INTO acp_deleted_sessions (session_id) VALUES (?)").run(id);
22391
21755
  this.remove(id);
22392
21756
  }
22393
21757
  this.#database.exec("COMMIT");
@@ -22565,22 +21929,6 @@ function readString4(value, fallback = "") {
22565
21929
  function arraysEqual(left, right) {
22566
21930
  return left.length === right.length && left.every((value, index) => value === right[index]);
22567
21931
  }
22568
- function normalizeCapabilities(capabilities) {
22569
- const session = capabilities.sessionCapabilities;
22570
- const prompt = capabilities.promptCapabilities;
22571
- return {
22572
- additionalDirectories: session?.additionalDirectories != null,
22573
- audioPrompt: prompt?.audio === true,
22574
- closeSession: session?.close != null,
22575
- deleteSession: session?.delete != null,
22576
- embeddedContextPrompt: prompt?.embeddedContext === true,
22577
- imagePrompt: prompt?.image === true,
22578
- listSessions: session?.list != null,
22579
- loadSession: capabilities.loadSession === true,
22580
- resumeSession: session?.resume != null,
22581
- unstableForkSession: session?.fork != null
22582
- };
22583
- }
22584
21932
  function elicitationFieldType(value) {
22585
21933
  if (value === "boolean") {
22586
21934
  return "boolean";
@@ -22659,13 +22007,9 @@ function normalizeElicitationFields(requestedSchema) {
22659
22007
  format: truncate3(readString4(property["format"]), 64),
22660
22008
  hasDefaultValue: defaultValue !== void 0 && defaultValue !== null,
22661
22009
  maximum: numericString(property["maximum"]),
22662
- maximumLength: numericString(
22663
- property["maxLength"] ?? property["maxItems"]
22664
- ),
22010
+ maximumLength: numericString(property["maxLength"] ?? property["maxItems"]),
22665
22011
  minimum: numericString(property["minimum"]),
22666
- minimumLength: numericString(
22667
- property["minLength"] ?? property["minItems"]
22668
- ),
22012
+ minimumLength: numericString(property["minLength"] ?? property["minItems"]),
22669
22013
  name: truncate3(name, 128),
22670
22014
  options,
22671
22015
  pattern: truncate3(readString4(property["pattern"]), 500),
@@ -22753,11 +22097,7 @@ function validateElicitationContent(encoded, requestedSchema) {
22753
22097
  );
22754
22098
  for (const name of required2) {
22755
22099
  if (!(name in decoded)) {
22756
- throw new AcpExecutionError(
22757
- `Elicitation field ${name} is required`,
22758
- {},
22759
- "invalid_elicitation_response"
22760
- );
22100
+ throw new AcpExecutionError(`Elicitation field ${name} is required`, {}, "invalid_elicitation_response");
22761
22101
  }
22762
22102
  }
22763
22103
  const validated = {};
@@ -22810,11 +22150,7 @@ function validateElicitationContent(encoded, requestedSchema) {
22810
22150
  validated[name] = value;
22811
22151
  continue;
22812
22152
  }
22813
- throw new AcpExecutionError(
22814
- `Elicitation field ${name} has the wrong type`,
22815
- {},
22816
- "invalid_elicitation_response"
22817
- );
22153
+ throw new AcpExecutionError(`Elicitation field ${name} has the wrong type`, {}, "invalid_elicitation_response");
22818
22154
  }
22819
22155
  return validated;
22820
22156
  }
@@ -22977,10 +22313,7 @@ var AcpProcessSession = class _AcpProcessSession {
22977
22313
  this.#child.once("error", resolve5);
22978
22314
  this.#child.once("exit", resolve5);
22979
22315
  });
22980
- const stream = ndJsonStream(
22981
- createWritableAcpStream(stdin),
22982
- readableWebStream(stdout)
22983
- );
22316
+ const stream = ndJsonStream(createWritableAcpStream(stdin), readableWebStream(stdout));
22984
22317
  this.#connection = createAcpClient(this).connect(stream);
22985
22318
  }
22986
22319
  static async #start(options, getObserver, store, initialize) {
@@ -23013,9 +22346,7 @@ var AcpProcessSession = class _AcpProcessSession {
23013
22346
  await runtime.closeProcess();
23014
22347
  options.signal.throwIfAborted();
23015
22348
  if (error61 instanceof RetryableAcpInitializationError && attempt === 1) {
23016
- console.warn(
23017
- `[${options.agent.id}-acp] ACP agent initialization failed; retrying once`
23018
- );
22349
+ console.warn(`[${options.agent.id}-acp] ACP agent initialization failed; retrying once`);
23019
22350
  continue;
23020
22351
  }
23021
22352
  if (error61 instanceof AcpExecutionError) {
@@ -23051,7 +22382,9 @@ var AcpProcessSession = class _AcpProcessSession {
23051
22382
  this.#restored
23052
22383
  );
23053
22384
  loadHistory = async (signal) => {
23054
- if (!this.#capabilities.loadSession) return { status: "unavailable" };
22385
+ if (!this.#capabilities.loadSession) {
22386
+ return { status: "unavailable" };
22387
+ }
23055
22388
  const history = new AcpHistoryReplay();
23056
22389
  this.#replay = { kind: "capture", history };
23057
22390
  try {
@@ -23105,11 +22438,8 @@ var AcpProcessSession = class _AcpProcessSession {
23105
22438
  );
23106
22439
  }
23107
22440
  const capabilities = initialized.agentCapabilities ?? {};
23108
- this.#capabilities = normalizeCapabilities(capabilities);
23109
- this.#agentName = truncate3(
23110
- initialized.agentInfo?.title ?? initialized.agentInfo?.name ?? this.#agentId,
23111
- 255
23112
- );
22441
+ this.#capabilities = normalizeAcpCapabilities(capabilities);
22442
+ this.#agentName = truncate3(initialized.agentInfo?.title ?? initialized.agentInfo?.name ?? this.#agentId, 255);
23113
22443
  this.#agentVersion = truncate3(
23114
22444
  this.#verifiedAgentVersion.length > 0 ? this.#verifiedAgentVersion : initialized.agentInfo?.version ?? "",
23115
22445
  128
@@ -23131,20 +22461,22 @@ var AcpProcessSession = class _AcpProcessSession {
23131
22461
  this.#store.remove(this.#mobiusSessionId);
23132
22462
  stored = this.#store.read(this.#mobiusSessionId);
23133
22463
  }
23134
- if (stored instanceof DeletedAcpStoredSession)
22464
+ if (stored instanceof DeletedAcpStoredSession) {
23135
22465
  throw new AcpExecutionError(
23136
22466
  "The native Agent session was deleted. Start a new chat.",
23137
22467
  {},
23138
22468
  "native_session_deleted"
23139
22469
  );
22470
+ }
23140
22471
  let lifecycleResponse;
23141
22472
  if (origin?.kind === "fork") {
23142
- if (!this.#capabilities.unstableForkSession)
22473
+ if (!this.#capabilities.unstableForkSession) {
23143
22474
  throw new AcpExecutionError(
23144
22475
  "This Agent does not support session forking",
23145
22476
  {},
23146
22477
  "native_session_unsupported"
23147
22478
  );
22479
+ }
23148
22480
  const forked = await this.race(
23149
22481
  this.#connection.agent.request(
23150
22482
  methods3.agent.session.fork,
@@ -23170,10 +22502,7 @@ var AcpProcessSession = class _AcpProcessSession {
23170
22502
  this.#prompted = true;
23171
22503
  this.#restored = true;
23172
22504
  lifecycleResponse = forked;
23173
- } else if (stored instanceof FoundAcpStoredSession && stored.session.agentId === this.#agentId && stored.session.cwd === this.#cwd && arraysEqual(
23174
- stored.session.additionalDirectories,
23175
- this.#additionalDirectories
23176
- )) {
22505
+ } else if (stored instanceof FoundAcpStoredSession && stored.session.agentId === this.#agentId && stored.session.cwd === this.#cwd && arraysEqual(stored.session.additionalDirectories, this.#additionalDirectories)) {
23177
22506
  this.selectNativeSession(stored.session.nativeSessionId);
23178
22507
  this.#prompted = stored.session.prompted;
23179
22508
  this.#restored = true;
@@ -23264,37 +22593,38 @@ var AcpProcessSession = class _AcpProcessSession {
23264
22593
  }
23265
22594
  };
23266
22595
  listNativeSessions = async (cursor, signal) => {
23267
- if (!this.#capabilities.listSessions)
22596
+ if (!this.#capabilities.listSessions) {
23268
22597
  throw new AcpExecutionError(
23269
22598
  "This Agent does not support native session listing",
23270
22599
  {},
23271
22600
  "native_session_unsupported"
23272
22601
  );
22602
+ }
23273
22603
  const response = await this.race(
23274
- this.#connection.agent.request(
23275
- methods3.agent.session.list,
23276
- cursor === null ? {} : { cursor },
23277
- { cancellationSignal: signal }
23278
- ),
22604
+ this.#connection.agent.request(methods3.agent.session.list, cursor === null ? {} : { cursor }, {
22605
+ cancellationSignal: signal
22606
+ }),
23279
22607
  "ACP agent exited while listing sessions",
23280
22608
  signal
23281
22609
  );
23282
22610
  const decoded = nativeSessionPageSchema.safeParse(response);
23283
- if (!decoded.success)
22611
+ if (!decoded.success) {
23284
22612
  throw new AcpExecutionError(
23285
22613
  "The Agent returned an invalid native session list",
23286
22614
  { cause: decoded.error },
23287
22615
  "invalid_native_session_response"
23288
22616
  );
22617
+ }
23289
22618
  return decoded.data;
23290
22619
  };
23291
22620
  deleteNativeSession = async (nativeSessionId, signal) => {
23292
- if (!this.#capabilities.deleteSession || !this.#capabilities.listSessions)
22621
+ if (!this.#capabilities.deleteSession || !this.#capabilities.listSessions) {
23293
22622
  throw new AcpExecutionError(
23294
22623
  "This Agent does not support native session deletion",
23295
22624
  {},
23296
22625
  "native_session_unsupported"
23297
22626
  );
22627
+ }
23298
22628
  await this.race(
23299
22629
  this.#connection.agent.request(
23300
22630
  methods3.agent.session.delete,
@@ -23307,9 +22637,7 @@ var AcpProcessSession = class _AcpProcessSession {
23307
22637
  };
23308
22638
  nativeSessionId = () => this.#nativeSessionId;
23309
22639
  configure = async (options) => {
23310
- const existing = this.#configOptions.find(
23311
- (option) => option.id === options.configId
23312
- );
22640
+ const existing = this.#configOptions.find((option) => option.id === options.configId);
23313
22641
  if (existing === void 0 || existing.type !== options.valueType) {
23314
22642
  throw new AcpExecutionError(
23315
22643
  "The requested ACP configuration option is unavailable",
@@ -23355,11 +22683,7 @@ var AcpProcessSession = class _AcpProcessSession {
23355
22683
  }
23356
22684
  } catch (error61) {
23357
22685
  if (error61 instanceof SessionConfigProtocolError) {
23358
- throw new AcpExecutionError(
23359
- error61.message,
23360
- { cause: error61 },
23361
- error61.code
23362
- );
22686
+ throw new AcpExecutionError(error61.message, { cause: error61 }, error61.code);
23363
22687
  }
23364
22688
  throw error61;
23365
22689
  }
@@ -23367,11 +22691,7 @@ var AcpProcessSession = class _AcpProcessSession {
23367
22691
  };
23368
22692
  prompt = async (options) => {
23369
22693
  if (this.#turn.running) {
23370
- throw new AcpExecutionError(
23371
- "Another prompt is already running in this conversation",
23372
- {},
23373
- "session_busy"
23374
- );
22694
+ throw new AcpExecutionError("Another prompt is already running in this conversation", {}, "session_busy");
23375
22695
  }
23376
22696
  if (options.images.length > 0 && !this.#capabilities.imagePrompt) {
23377
22697
  throw new AcpExecutionError(
@@ -23419,11 +22739,7 @@ var AcpProcessSession = class _AcpProcessSession {
23419
22739
  }
23420
22740
  }
23421
22741
  if (prompt.length === 0) {
23422
- throw new AcpExecutionError(
23423
- "A prompt must contain text or an attachment",
23424
- {},
23425
- "empty_prompt"
23426
- );
22742
+ throw new AcpExecutionError("A prompt must contain text or an attachment", {}, "empty_prompt");
23427
22743
  }
23428
22744
  this.#store.write(
23429
22745
  new AcpStoredSession(
@@ -23436,11 +22752,7 @@ var AcpProcessSession = class _AcpProcessSession {
23436
22752
  )
23437
22753
  );
23438
22754
  this.#prompted = true;
23439
- const running = new RunningAcpTurn(
23440
- options.commandId,
23441
- options.onActivity,
23442
- options.onText
23443
- );
22755
+ const running = new RunningAcpTurn(options.commandId, options.onActivity, options.onText);
23444
22756
  this.#turn = running;
23445
22757
  try {
23446
22758
  const response = await this.race(
@@ -23547,15 +22859,10 @@ var AcpProcessSession = class _AcpProcessSession {
23547
22859
  if (pending.elicitationId.length > 0) {
23548
22860
  resolved = pending.accept({});
23549
22861
  if (resolved) {
23550
- this.#acceptedUrlElicitations.set(
23551
- pending.elicitationId,
23552
- pending.interactionId
23553
- );
22862
+ this.#acceptedUrlElicitations.set(pending.elicitationId, pending.interactionId);
23554
22863
  }
23555
22864
  } else {
23556
- resolved = pending.accept(
23557
- validateElicitationContent(options.content, pending.requestedSchema)
23558
- );
22865
+ resolved = pending.accept(validateElicitationContent(options.content, pending.requestedSchema));
23559
22866
  }
23560
22867
  } else if (options.action === "decline") {
23561
22868
  resolved = pending.decline();
@@ -23592,10 +22899,7 @@ var AcpProcessSession = class _AcpProcessSession {
23592
22899
  "invalid_agent_permission_request"
23593
22900
  );
23594
22901
  }
23595
- const pending = new PendingPermission(
23596
- interactionId,
23597
- new Set(options.map((option) => option.optionId))
23598
- );
22902
+ const pending = new PendingPermission(interactionId, new Set(options.map((option) => option.optionId)));
23599
22903
  this.#pendingPermissions.set(interactionId, pending);
23600
22904
  const abort = () => {
23601
22905
  void this.cancelPermission(interactionId);
@@ -23640,11 +22944,7 @@ var AcpProcessSession = class _AcpProcessSession {
23640
22944
  const requestedSchema = request.mode === "form" ? schemaValue : {};
23641
22945
  const elicitationIdValue = Reflect.get(request, "elicitationId");
23642
22946
  const elicitationId = request.mode === "url" && typeof elicitationIdValue === "string" ? truncate3(elicitationIdValue, 255) : "";
23643
- const pending = new PendingElicitation(
23644
- interactionId,
23645
- elicitationId,
23646
- requestedSchema
23647
- );
22947
+ const pending = new PendingElicitation(interactionId, elicitationId, requestedSchema);
23648
22948
  this.#pendingElicitations.set(interactionId, pending);
23649
22949
  const abort = () => {
23650
22950
  void this.cancelElicitation(interactionId);
@@ -23670,9 +22970,7 @@ var AcpProcessSession = class _AcpProcessSession {
23670
22970
  }
23671
22971
  };
23672
22972
  onElicitationComplete = async (notification) => {
23673
- const interactionId = this.#acceptedUrlElicitations.get(
23674
- notification.elicitationId
23675
- );
22973
+ const interactionId = this.#acceptedUrlElicitations.get(notification.elicitationId);
23676
22974
  if (interactionId === void 0) {
23677
22975
  return;
23678
22976
  }
@@ -23703,9 +23001,7 @@ var AcpProcessSession = class _AcpProcessSession {
23703
23001
  return this.enqueueUpdate(notification);
23704
23002
  };
23705
23003
  enqueueUpdate = (notification) => {
23706
- this.#updateTail = this.#updateTail.then(
23707
- async () => await this.processUpdate(notification)
23708
- );
23004
+ this.#updateTail = this.#updateTail.then(async () => await this.processUpdate(notification));
23709
23005
  return this.#updateTail;
23710
23006
  };
23711
23007
  selectNativeSession = (sessionId) => {
@@ -23727,7 +23023,9 @@ var AcpProcessSession = class _AcpProcessSession {
23727
23023
  processUpdate = async (notification) => {
23728
23024
  this.assertNativeSession(notification.sessionId);
23729
23025
  const update = notification.update;
23730
- if (this.#replay.kind === "capture") this.#replay.history.record(update);
23026
+ if (this.#replay.kind === "capture") {
23027
+ this.#replay.history.record(update);
23028
+ }
23731
23029
  if (this.#replay.kind !== "idle" && (update.sessionUpdate === "user_message_chunk" || update.sessionUpdate === "agent_message_chunk" || update.sessionUpdate === "agent_thought_chunk" || update.sessionUpdate === "tool_call" || update.sessionUpdate === "tool_call_update" || update.sessionUpdate === "plan" || update.sessionUpdate === "plan_update" || update.sessionUpdate === "plan_removed")) {
23732
23030
  return;
23733
23031
  }
@@ -23853,9 +23151,7 @@ var AcpProcessSession = class _AcpProcessSession {
23853
23151
  methods3.agent.session.close,
23854
23152
  { sessionId: this.#nativeSessionId },
23855
23153
  {
23856
- cancellationSignal: AbortSignal.timeout(
23857
- PROCESS_STOP_TIMEOUT_MILLISECONDS
23858
- )
23154
+ cancellationSignal: AbortSignal.timeout(PROCESS_STOP_TIMEOUT_MILLISECONDS)
23859
23155
  }
23860
23156
  );
23861
23157
  } catch {
@@ -23909,11 +23205,7 @@ var AcpProcessSession = class _AcpProcessSession {
23909
23205
  };
23910
23206
  assertNativeSession = (sessionId) => {
23911
23207
  if (sessionId !== this.#nativeSessionId) {
23912
- throw new AcpExecutionError(
23913
- "ACP agent referenced an unknown session",
23914
- {},
23915
- "invalid_agent_session"
23916
- );
23208
+ throw new AcpExecutionError("ACP agent referenced an unknown session", {}, "invalid_agent_session");
23917
23209
  }
23918
23210
  };
23919
23211
  emitConfigUpdate = async () => {
@@ -24031,11 +23323,7 @@ var AcpSessionManager = class {
24031
23323
  async #startPreparation(options) {
24032
23324
  const operation = (async () => {
24033
23325
  try {
24034
- const runtime = await AcpProcessSession.start(
24035
- options,
24036
- () => this.#observer,
24037
- this.#store
24038
- );
23326
+ const runtime = await AcpProcessSession.start(options, () => this.#observer, this.#store);
24039
23327
  this.#sessions.set(options.sessionId, runtime);
24040
23328
  return runtime;
24041
23329
  } finally {
@@ -24051,11 +23339,7 @@ var AcpSessionManager = class {
24051
23339
  this.#sessions.delete(options.sessionId);
24052
23340
  await existing.close();
24053
23341
  this.#store.remove(options.sessionId);
24054
- const runtime = await AcpProcessSession.start(
24055
- options,
24056
- () => this.#observer,
24057
- this.#store
24058
- );
23342
+ const runtime = await AcpProcessSession.start(options, () => this.#observer, this.#store);
24059
23343
  this.#sessions.set(options.sessionId, runtime);
24060
23344
  return runtime;
24061
23345
  } finally {
@@ -24067,39 +23351,27 @@ var AcpSessionManager = class {
24067
23351
  }
24068
23352
  prepareSession = async (options) => {
24069
23353
  const stored = this.#store.read(options.sessionId);
24070
- if (stored instanceof DeletedAcpStoredSession)
23354
+ if (stored instanceof DeletedAcpStoredSession) {
24071
23355
  throw new AcpExecutionError(
24072
23356
  "The native Agent session was deleted. Start a new chat.",
24073
23357
  {},
24074
23358
  "native_session_deleted"
24075
23359
  );
24076
- if (stored instanceof FoundAcpStoredSession && this.#nativeOperations.has(
24077
- `${stored.session.agentId}:${stored.session.nativeSessionId}`
24078
- ))
24079
- throw new AcpExecutionError(
24080
- "The native session is being managed",
24081
- {},
24082
- "session_busy"
24083
- );
23360
+ }
23361
+ if (stored instanceof FoundAcpStoredSession && this.#nativeOperations.has(`${stored.session.agentId}:${stored.session.nativeSessionId}`)) {
23362
+ throw new AcpExecutionError("The native session is being managed", {}, "session_busy");
23363
+ }
24084
23364
  const pending = this.#preparing.get(options.sessionId);
24085
23365
  if (pending !== void 0) {
24086
23366
  const runtime2 = await pending;
24087
- if (runtime2.belongsTo(
24088
- options.agent.id,
24089
- options.cwd,
24090
- options.additionalDirectories
24091
- )) {
23367
+ if (runtime2.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
24092
23368
  return runtime2.prepared();
24093
23369
  }
24094
23370
  return await this.prepareSession(options);
24095
23371
  }
24096
23372
  const existing = this.#sessions.get(options.sessionId);
24097
23373
  if (existing !== void 0) {
24098
- if (existing.belongsTo(
24099
- options.agent.id,
24100
- options.cwd,
24101
- options.additionalDirectories
24102
- )) {
23374
+ if (existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
24103
23375
  return existing.prepared();
24104
23376
  }
24105
23377
  if (!existing.canRebind()) {
@@ -24119,22 +23391,14 @@ var AcpSessionManager = class {
24119
23391
  const pending = this.#nativeBrowserPreparing.get(options.sessionId);
24120
23392
  if (pending !== void 0) {
24121
23393
  const runtime2 = await pending;
24122
- if (runtime2.belongsTo(
24123
- options.agent.id,
24124
- options.cwd,
24125
- options.additionalDirectories
24126
- )) {
23394
+ if (runtime2.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
24127
23395
  return runtime2.prepared();
24128
23396
  }
24129
23397
  return await this.prepareNativeSessionBrowser(options);
24130
23398
  }
24131
23399
  const existing = this.#nativeBrowserSessions.get(options.sessionId);
24132
23400
  if (existing !== void 0) {
24133
- if (existing.belongsTo(
24134
- options.agent.id,
24135
- options.cwd,
24136
- options.additionalDirectories
24137
- )) {
23401
+ if (existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
24138
23402
  return existing.prepared();
24139
23403
  }
24140
23404
  if (!existing.canRebind()) {
@@ -24144,10 +23408,7 @@ var AcpSessionManager = class {
24144
23408
  "session_identity_mismatch"
24145
23409
  );
24146
23410
  }
24147
- const runtime2 = await this.#replaceNativeBrowserPreparation(
24148
- existing,
24149
- options
24150
- );
23411
+ const runtime2 = await this.#replaceNativeBrowserPreparation(existing, options);
24151
23412
  return runtime2.prepared();
24152
23413
  }
24153
23414
  const runtime = await this.#startNativeBrowserPreparation(options);
@@ -24172,21 +23433,11 @@ var AcpSessionManager = class {
24172
23433
  };
24173
23434
  runPrompt = async (options) => {
24174
23435
  const stored = this.#store.read(options.sessionId);
24175
- if (stored instanceof FoundAcpStoredSession && this.#nativeOperations.has(
24176
- `${stored.session.agentId}:${stored.session.nativeSessionId}`
24177
- )) {
24178
- throw new AcpExecutionError(
24179
- "The native session is being managed",
24180
- {},
24181
- "session_busy"
24182
- );
23436
+ if (stored instanceof FoundAcpStoredSession && this.#nativeOperations.has(`${stored.session.agentId}:${stored.session.nativeSessionId}`)) {
23437
+ throw new AcpExecutionError("The native session is being managed", {}, "session_busy");
24183
23438
  }
24184
23439
  if (this.#activeSessionIds.has(options.sessionId)) {
24185
- throw new AcpExecutionError(
24186
- "Another prompt is already running in this conversation",
24187
- {},
24188
- "session_busy"
24189
- );
23440
+ throw new AcpExecutionError("Another prompt is already running in this conversation", {}, "session_busy");
24190
23441
  }
24191
23442
  const deadlineController = new AbortController();
24192
23443
  const deadlineError = new AcpExecutionError(
@@ -24209,14 +23460,9 @@ var AcpSessionManager = class {
24209
23460
  return { stopReason: "cancelled" };
24210
23461
  }
24211
23462
  const runtime = await this.ensureSession(boundedOptions);
24212
- if (this.#nativeOperations.has(
24213
- `${options.agent.id}:${runtime.nativeSessionId()}`
24214
- ))
24215
- throw new AcpExecutionError(
24216
- "The native session is being managed",
24217
- {},
24218
- "session_busy"
24219
- );
23463
+ if (this.#nativeOperations.has(`${options.agent.id}:${runtime.nativeSessionId()}`)) {
23464
+ throw new AcpExecutionError("The native session is being managed", {}, "session_busy");
23465
+ }
24220
23466
  if (this.#cancellationRequests.has(options.sessionId)) {
24221
23467
  return { stopReason: "cancelled" };
24222
23468
  }
@@ -24254,22 +23500,14 @@ var AcpSessionManager = class {
24254
23500
  respondPermission = async (options) => {
24255
23501
  const runtime = this.#sessions.get(options.sessionId);
24256
23502
  if (runtime === void 0) {
24257
- throw new AcpExecutionError(
24258
- "The permission request session is unavailable",
24259
- {},
24260
- "session_not_found"
24261
- );
23503
+ throw new AcpExecutionError("The permission request session is unavailable", {}, "session_not_found");
24262
23504
  }
24263
23505
  await runtime.respondPermission(options);
24264
23506
  };
24265
23507
  respondElicitation = async (options) => {
24266
23508
  const runtime = this.#sessions.get(options.sessionId);
24267
23509
  if (runtime === void 0) {
24268
- throw new AcpExecutionError(
24269
- "The elicitation request session is unavailable",
24270
- {},
24271
- "session_not_found"
24272
- );
23510
+ throw new AcpExecutionError("The elicitation request session is unavailable", {}, "session_not_found");
24273
23511
  }
24274
23512
  await runtime.respondElicitation(options);
24275
23513
  };
@@ -24278,20 +23516,12 @@ var AcpSessionManager = class {
24278
23516
  const nativeBrowserSessions = [...this.#nativeBrowserSessions.values()];
24279
23517
  this.#sessions.clear();
24280
23518
  this.#nativeBrowserSessions.clear();
24281
- await Promise.all(
24282
- [...sessions, ...nativeBrowserSessions].map(
24283
- async (session) => await session.close()
24284
- )
24285
- );
23519
+ await Promise.all([...sessions, ...nativeBrowserSessions].map(async (session) => await session.close()));
24286
23520
  };
24287
23521
  ensureSession = async (options) => {
24288
23522
  const existing = this.#sessions.get(options.sessionId);
24289
23523
  if (existing !== void 0) {
24290
- if (!existing.belongsTo(
24291
- options.agent.id,
24292
- options.cwd,
24293
- options.additionalDirectories
24294
- )) {
23524
+ if (!existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
24295
23525
  throw new AcpExecutionError(
24296
23526
  "The agent or workspace cannot change after a conversation has started",
24297
23527
  {},
@@ -24310,11 +23540,7 @@ var AcpSessionManager = class {
24310
23540
  async #ensureNativeSessionBrowser(options) {
24311
23541
  const existing = this.#nativeBrowserSessions.get(options.sessionId);
24312
23542
  if (existing !== void 0) {
24313
- if (!existing.belongsTo(
24314
- options.agent.id,
24315
- options.cwd,
24316
- options.additionalDirectories
24317
- )) {
23543
+ if (!existing.belongsTo(options.agent.id, options.cwd, options.additionalDirectories)) {
24318
23544
  throw new AcpExecutionError(
24319
23545
  "The agent or workspace cannot change after a conversation has started",
24320
23546
  {},
@@ -24330,42 +23556,33 @@ var AcpSessionManager = class {
24330
23556
  }
24331
23557
  return started;
24332
23558
  }
24333
- listNativeSessions = async (options, cursor) => await (await this.#ensureNativeSessionBrowser(options)).listNativeSessions(
24334
- cursor,
24335
- options.signal
24336
- );
23559
+ listNativeSessions = async (options, cursor) => await (await this.#ensureNativeSessionBrowser(options)).listNativeSessions(cursor, options.signal);
24337
23560
  openNativeSession = async (options, origin) => {
24338
23561
  const key = `${options.agent.id}:${origin.nativeSessionId}`;
24339
- if (this.#nativeOperations.has(key))
24340
- throw new AcpExecutionError(
24341
- "The native session is being managed",
24342
- {},
24343
- "session_busy"
24344
- );
24345
- const linked = this.#store.findNative(
24346
- options.agent.id,
24347
- origin.nativeSessionId
24348
- );
24349
- if (linked.some(
24350
- (entry) => this.#activeSessionIds.has(entry.sessionId) || this.#preparing.has(entry.sessionId)
24351
- ))
23562
+ if (this.#nativeOperations.has(key)) {
23563
+ throw new AcpExecutionError("The native session is being managed", {}, "session_busy");
23564
+ }
23565
+ const linked = this.#store.findNative(options.agent.id, origin.nativeSessionId);
23566
+ if (linked.some((entry) => this.#activeSessionIds.has(entry.sessionId) || this.#preparing.has(entry.sessionId))) {
24352
23567
  throw new AcpExecutionError(
24353
23568
  "Wait for the native session's running operation to finish",
24354
23569
  {},
24355
23570
  "session_busy"
24356
23571
  );
23572
+ }
24357
23573
  const existing = linked[0];
24358
23574
  if (origin.kind === "import" && existing !== void 0) {
24359
23575
  const runtime = await this.ensureSession({
24360
23576
  ...options,
24361
23577
  sessionId: existing.sessionId
24362
23578
  });
24363
- if (this.#activeSessionIds.has(existing.sessionId) || this.#nativeOperations.has(key))
23579
+ if (this.#activeSessionIds.has(existing.sessionId) || this.#nativeOperations.has(key)) {
24364
23580
  throw new AcpExecutionError(
24365
23581
  "Wait for the native session's running operation to finish",
24366
23582
  {},
24367
23583
  "session_busy"
24368
23584
  );
23585
+ }
24369
23586
  this.#nativeOperations.add(key);
24370
23587
  try {
24371
23588
  const history = await runtime.loadHistory(options.signal);
@@ -24382,12 +23599,9 @@ var AcpSessionManager = class {
24382
23599
  this.#nativeOperations.delete(key);
24383
23600
  }
24384
23601
  }
24385
- if (this.#sessions.has(options.sessionId) || this.#preparing.has(options.sessionId) || this.#store.read(options.sessionId) instanceof FoundAcpStoredSession || this.#store.read(options.sessionId) instanceof DeletedAcpStoredSession)
24386
- throw new AcpExecutionError(
24387
- "The destination conversation already exists",
24388
- {},
24389
- "session_identity_mismatch"
24390
- );
23602
+ if (this.#sessions.has(options.sessionId) || this.#preparing.has(options.sessionId) || this.#store.read(options.sessionId) instanceof FoundAcpStoredSession || this.#store.read(options.sessionId) instanceof DeletedAcpStoredSession) {
23603
+ throw new AcpExecutionError("The destination conversation already exists", {}, "session_identity_mismatch");
23604
+ }
24391
23605
  this.#nativeOperations.add(key);
24392
23606
  try {
24393
23607
  const runtime = await this.#startPreparation({ ...options, origin });
@@ -24416,14 +23630,13 @@ var AcpSessionManager = class {
24416
23630
  const runtime = await this.#ensureNativeSessionBrowser(options);
24417
23631
  const key = `${options.agent.id}:${nativeSessionId}`;
24418
23632
  const linked = this.#store.findNative(options.agent.id, nativeSessionId);
24419
- if (this.#nativeOperations.has(key) || linked.some(
24420
- (entry) => this.#activeSessionIds.has(entry.sessionId) || this.#preparing.has(entry.sessionId)
24421
- ))
23633
+ if (this.#nativeOperations.has(key) || linked.some((entry) => this.#activeSessionIds.has(entry.sessionId) || this.#preparing.has(entry.sessionId))) {
24422
23634
  throw new AcpExecutionError(
24423
23635
  "Wait for the native session's running operation to finish",
24424
23636
  {},
24425
23637
  "session_busy"
24426
23638
  );
23639
+ }
24427
23640
  this.#nativeOperations.add(key);
24428
23641
  try {
24429
23642
  for (const entry of linked) {
@@ -24435,10 +23648,7 @@ var AcpSessionManager = class {
24435
23648
  }
24436
23649
  options.signal.throwIfAborted();
24437
23650
  await runtime.deleteNativeSession(nativeSessionId, options.signal);
24438
- const deleted = this.#store.markDeleted(
24439
- options.agent.id,
24440
- nativeSessionId
24441
- );
23651
+ const deleted = this.#store.markDeleted(options.agent.id, nativeSessionId);
24442
23652
  if (runtime.nativeSessionId() === nativeSessionId) {
24443
23653
  this.#nativeBrowserSessions.delete(options.sessionId);
24444
23654
  this.#nativeBrowserStore.remove(options.sessionId);
@@ -24457,12 +23667,7 @@ async function runAcpPrompt(options) {
24457
23667
  try {
24458
23668
  return await sessions.runPrompt({
24459
23669
  additionalDirectories: [],
24460
- agent: new LocalAgentDefinition(
24461
- "test-agent",
24462
- "Test agent",
24463
- options.agentCommand,
24464
- options.agentArguments
24465
- ),
23670
+ agent: new LocalAgentDefinition("test-agent", "Test agent", options.agentCommand, options.agentArguments),
24466
23671
  cwd: options.cwd,
24467
23672
  commandId: crypto.randomUUID(),
24468
23673
  images: [],
@@ -24499,9 +23704,7 @@ var AuditStore = class {
24499
23704
  `);
24500
23705
  const columns = this.database.prepare("PRAGMA table_info(audit_events)").all();
24501
23706
  if (!columns.some((column) => Reflect.get(column, "name") === "details_json")) {
24502
- this.database.exec(
24503
- "ALTER TABLE audit_events ADD COLUMN details_json TEXT NOT NULL DEFAULT '{}'"
24504
- );
23707
+ this.database.exec("ALTER TABLE audit_events ADD COLUMN details_json TEXT NOT NULL DEFAULT '{}'");
24505
23708
  }
24506
23709
  }
24507
23710
  record(record2) {
@@ -24539,14 +23742,7 @@ var LocalAuthorizationError = class extends Error {
24539
23742
 
24540
23743
  // src/pairing/pair-local-machine.ts
24541
23744
  import { randomUUID } from "node:crypto";
24542
- import {
24543
- mkdir as mkdir3,
24544
- open as open4,
24545
- realpath as realpath6,
24546
- rename as rename3,
24547
- stat as stat5,
24548
- writeFile as writeFile2
24549
- } from "node:fs/promises";
23745
+ import { mkdir as mkdir3, open as open4, realpath as realpath6, rename as rename3, stat as stat5, writeFile as writeFile2 } from "node:fs/promises";
24550
23746
  import { hostname as hostname3 } from "node:os";
24551
23747
  import { basename, join as join14, resolve as resolve3 } from "node:path";
24552
23748
  import { fetch as fetch2 } from "undici";
@@ -24648,10 +23844,7 @@ var LocalAgentInventory = class {
24648
23844
  this.discoveries = Object.freeze([...discoveries]);
24649
23845
  this.installable = Object.freeze(
24650
23846
  unavailable.map(
24651
- (discovery) => discovery instanceof UnavailableInstalledAgent ? discovery.agent : new MissingAgentDefinition(
24652
- discovery.specification.id,
24653
- discovery.specification.label
24654
- )
23847
+ (discovery) => discovery instanceof UnavailableInstalledAgent ? discovery.agent : new MissingAgentDefinition(discovery.specification.id, discovery.specification.label)
24655
23848
  )
24656
23849
  );
24657
23850
  this.unavailable = Object.freeze(unavailable);
@@ -24660,15 +23853,7 @@ var LocalAgentInventory = class {
24660
23853
  };
24661
23854
 
24662
23855
  // src/agent-installation/managed-npm-package.ts
24663
- import {
24664
- mkdir,
24665
- mkdtemp,
24666
- open as open2,
24667
- realpath as realpath2,
24668
- rename,
24669
- rm,
24670
- stat as stat2
24671
- } from "node:fs/promises";
23856
+ import { mkdir, mkdtemp, open as open2, realpath as realpath2, rename, rm, stat as stat2 } from "node:fs/promises";
24672
23857
  import { delimiter, dirname as dirname3, isAbsolute, join as join4, relative, sep } from "node:path";
24673
23858
  var INSTALL_TIMEOUT_MILLISECONDS = 5 * 60 * 1e3;
24674
23859
  var PACKAGE_METADATA_LIMIT_BYTES = 64 * 1024;
@@ -24737,9 +23922,7 @@ async function readJsonRecord(path2, maximumBytes) {
24737
23922
  "The managed npm package metadata is invalid"
24738
23923
  );
24739
23924
  }
24740
- const value = JSON.parse(
24741
- await handle.readFile({ encoding: "utf8" })
24742
- );
23925
+ const value = JSON.parse(await handle.readFile({ encoding: "utf8" }));
24743
23926
  if (!isRecord5(value)) {
24744
23927
  throw new ManagedNpmPackageError(
24745
23928
  "managed_package_verification_failed",
@@ -24827,19 +24010,14 @@ function verifyPackageLockEntry(lock, definition, verifyDependencyClosure) {
24827
24010
  }
24828
24011
  }
24829
24012
  async function verifyRequiredDependency(rootPath, lock, definition) {
24830
- const dependencyRoot = await realpath2(
24831
- packagePath(rootPath, definition.packageName)
24832
- );
24013
+ const dependencyRoot = await realpath2(packagePath(rootPath, definition.packageName));
24833
24014
  if (!isContainedPath(rootPath, dependencyRoot)) {
24834
24015
  throw new ManagedNpmPackageError(
24835
24016
  "managed_package_verification_failed",
24836
24017
  "The required managed npm dependency escaped its private cache"
24837
24018
  );
24838
24019
  }
24839
- const metadata = await readJsonRecord(
24840
- join4(dependencyRoot, "package.json"),
24841
- PACKAGE_METADATA_LIMIT_BYTES
24842
- );
24020
+ const metadata = await readJsonRecord(join4(dependencyRoot, "package.json"), PACKAGE_METADATA_LIMIT_BYTES);
24843
24021
  if (metadata["name"] !== definition.packageName || metadata["version"] !== definition.version) {
24844
24022
  throw new ManagedNpmPackageError(
24845
24023
  "managed_package_verification_failed",
@@ -24855,28 +24033,21 @@ async function validateManagedNpmPackage(root, definition) {
24855
24033
  if (error61 instanceof ManagedNpmPackageError) {
24856
24034
  throw error61;
24857
24035
  }
24858
- throw new ManagedNpmPackageError(
24859
- "managed_package_verification_failed",
24860
- "The managed npm package is invalid",
24861
- { cause: error61 }
24862
- );
24036
+ throw new ManagedNpmPackageError("managed_package_verification_failed", "The managed npm package is invalid", {
24037
+ cause: error61
24038
+ });
24863
24039
  }
24864
24040
  }
24865
24041
  async function validateManagedNpmPackageContents(root, definition) {
24866
24042
  const rootPath = await realpath2(root);
24867
- const packageRoot = await realpath2(
24868
- packagePath(rootPath, definition.packageName)
24869
- );
24043
+ const packageRoot = await realpath2(packagePath(rootPath, definition.packageName));
24870
24044
  if (!isContainedPath(rootPath, packageRoot)) {
24871
24045
  throw new ManagedNpmPackageError(
24872
24046
  "managed_package_verification_failed",
24873
24047
  "The managed npm package escaped its private cache"
24874
24048
  );
24875
24049
  }
24876
- const metadata = await readJsonRecord(
24877
- join4(packageRoot, "package.json"),
24878
- PACKAGE_METADATA_LIMIT_BYTES
24879
- );
24050
+ const metadata = await readJsonRecord(join4(packageRoot, "package.json"), PACKAGE_METADATA_LIMIT_BYTES);
24880
24051
  if (metadata["name"] !== definition.packageName || metadata["version"] !== definition.version) {
24881
24052
  throw new ManagedNpmPackageError(
24882
24053
  "managed_package_verification_failed",
@@ -24884,23 +24055,14 @@ async function validateManagedNpmPackageContents(root, definition) {
24884
24055
  );
24885
24056
  }
24886
24057
  if (definition instanceof SriManagedNpmPackageDefinition) {
24887
- const lock = await readJsonRecord(
24888
- join4(rootPath, "package-lock.json"),
24889
- PACKAGE_LOCK_LIMIT_BYTES
24890
- );
24891
- verifyPackageLockEntry(
24892
- lock,
24893
- definition,
24894
- definition.verifyDependencyClosure
24895
- );
24058
+ const lock = await readJsonRecord(join4(rootPath, "package-lock.json"), PACKAGE_LOCK_LIMIT_BYTES);
24059
+ verifyPackageLockEntry(lock, definition, definition.verifyDependencyClosure);
24896
24060
  for (const dependency of definition.requiredDependencies) {
24897
24061
  await verifyRequiredDependency(rootPath, lock, dependency);
24898
24062
  }
24899
24063
  }
24900
24064
  const declaredBin = readBinPath(metadata, definition.executableName);
24901
- const executable = await resolveExecutablePath(
24902
- join4(packageRoot, declaredBin)
24903
- );
24065
+ const executable = await resolveExecutablePath(join4(packageRoot, declaredBin));
24904
24066
  if (executable === null || !isContainedPath(rootPath, executable.path)) {
24905
24067
  throw new ManagedNpmPackageError(
24906
24068
  "managed_package_verification_failed",
@@ -24924,14 +24086,9 @@ var ManagedNpmPackageInstaller = class {
24924
24086
  }
24925
24087
  const parent = dirname3(root);
24926
24088
  await mkdir(parent, { mode: 448, recursive: true });
24927
- const staging = await mkdtemp(
24928
- join4(parent, `.${definition.version}.staging-`)
24929
- );
24089
+ const staging = await mkdtemp(join4(parent, `.${definition.version}.staging-`));
24930
24090
  try {
24931
- const npm = await findExecutableOnPath(
24932
- process.platform === "win32" ? "npm.cmd" : "npm",
24933
- environment
24934
- );
24091
+ const npm = await findExecutableOnPath(process.platform === "win32" ? "npm.cmd" : "npm", environment);
24935
24092
  if (npm === null) {
24936
24093
  throw new ManagedNpmPackageError(
24937
24094
  "package_manager_not_found",
@@ -25055,9 +24212,7 @@ var DirectAcpAgentDefinition = class extends LocalAgentSpecification {
25055
24212
  this.adapterOverrideVariable = executableOverrideVariable;
25056
24213
  this.agentOverrideVariable = executableOverrideVariable;
25057
24214
  this.launchArguments = Object.freeze([...launchArguments]);
25058
- this.managedAdapterExecutablePath = Object.freeze([
25059
- ...managedExecutablePath
25060
- ]);
24215
+ this.managedAdapterExecutablePath = Object.freeze([...managedExecutablePath]);
25061
24216
  this.managedAgentExecutablePath = this.managedAdapterExecutablePath;
25062
24217
  }
25063
24218
  };
@@ -25099,14 +24254,7 @@ var ClaudeCodeAgentSpecification = class extends BridgedAcpAgentDefinition {
25099
24254
  "dist",
25100
24255
  "index.js"
25101
24256
  ];
25102
- managedAgentExecutablePath = [
25103
- "agents",
25104
- "claude",
25105
- "home",
25106
- ".local",
25107
- "bin",
25108
- "claude"
25109
- ];
24257
+ managedAgentExecutablePath = ["agents", "claude", "home", ".local", "bin", "claude"];
25110
24258
  };
25111
24259
 
25112
24260
  // src/agent-catalog/agents/codex-agent.ts
@@ -25146,9 +24294,7 @@ var AgentProbeError = class extends Error {
25146
24294
  };
25147
24295
 
25148
24296
  // src/agent-catalog/agents/verify-session-creation.ts
25149
- import {
25150
- methods as methods4
25151
- } from "@agentclientprotocol/sdk";
24297
+ import { methods as methods4 } from "@agentclientprotocol/sdk";
25152
24298
  async function verifySessionCreation(connection, capabilities, defaultWorkspace, signal, label) {
25153
24299
  const session = await connection.agent.request(
25154
24300
  methods4.agent.session.new,
@@ -25160,10 +24306,7 @@ async function verifySessionCreation(connection, capabilities, defaultWorkspace,
25160
24306
  { cancellationSignal: signal }
25161
24307
  );
25162
24308
  if (session.sessionId.length === 0) {
25163
- throw new AgentProbeError(
25164
- "acp_incompatible",
25165
- `${label} returned an invalid ACP session`
25166
- );
24309
+ throw new AgentProbeError("acp_incompatible", `${label} returned an invalid ACP session`);
25167
24310
  }
25168
24311
  if (capabilities.sessionCapabilities?.close != null) {
25169
24312
  await connection.agent.request(
@@ -25191,21 +24334,10 @@ var CursorCliAgentSpecification = class extends DirectAcpAgentDefinition {
25191
24334
  }
25192
24335
  verifyAcp = async (connection, initialized, defaultWorkspace, signal) => {
25193
24336
  const capabilities = initialized.agentCapabilities ?? {};
25194
- if (capabilities.loadSession !== true || capabilities.sessionCapabilities?.list == null || !(initialized.authMethods ?? []).some(
25195
- (method) => method.id === "cursor_login"
25196
- )) {
25197
- throw new AgentProbeError(
25198
- "acp_incompatible",
25199
- "Cursor CLI reported an unsupported ACP capability set"
25200
- );
24337
+ if (capabilities.loadSession !== true || capabilities.sessionCapabilities?.list == null || !(initialized.authMethods ?? []).some((method) => method.id === "cursor_login")) {
24338
+ throw new AgentProbeError("acp_incompatible", "Cursor CLI reported an unsupported ACP capability set");
25201
24339
  }
25202
- await verifySessionCreation(
25203
- connection,
25204
- capabilities,
25205
- defaultWorkspace,
25206
- signal,
25207
- this.label
25208
- );
24340
+ await verifySessionCreation(connection, capabilities, defaultWorkspace, signal, this.label);
25209
24341
  };
25210
24342
  };
25211
24343
 
@@ -25215,9 +24347,7 @@ import { isAbsolute as isAbsolute2, join as join6, normalize } from "node:path";
25215
24347
 
25216
24348
  // src/agent-installation/deepseek-managed-package.ts
25217
24349
  var DeepSeekHarnessManagedPackage = class extends SriManagedNpmPackageDefinition {
25218
- dependencyResolutionArguments = Object.freeze([
25219
- "--before=2026-09-03T06:31:52.107Z"
25220
- ]);
24350
+ dependencyResolutionArguments = Object.freeze(["--before=2026-09-03T06:31:52.107Z"]);
25221
24351
  includeOptionalDependencies = true;
25222
24352
  verifyDependencyClosure = true;
25223
24353
  };
@@ -25232,10 +24362,7 @@ var DEEPSEEK_HARNESS_PACKAGE = new DeepSeekHarnessManagedPackage(
25232
24362
  // src/agent-catalog/agents/deepseek-harness-agent.ts
25233
24363
  async function validateAgentHome(path2) {
25234
24364
  if (!isAbsolute2(path2) || normalize(path2) !== path2) {
25235
- throw new AgentProbeError(
25236
- "agent_environment_invalid",
25237
- "The configured Agent home is invalid"
25238
- );
24365
+ throw new AgentProbeError("agent_environment_invalid", "The configured Agent home is invalid");
25239
24366
  }
25240
24367
  try {
25241
24368
  const resolved = await realpath3(path2);
@@ -25248,11 +24375,9 @@ async function validateAgentHome(path2) {
25248
24375
  if (error61 instanceof AgentProbeError) {
25249
24376
  throw error61;
25250
24377
  }
25251
- throw new AgentProbeError(
25252
- "agent_environment_invalid",
25253
- "The configured Agent home is invalid",
25254
- { cause: error61 }
25255
- );
24378
+ throw new AgentProbeError("agent_environment_invalid", "The configured Agent home is invalid", {
24379
+ cause: error61
24380
+ });
25256
24381
  }
25257
24382
  }
25258
24383
  var DeepSeekHarnessAgentSpecification = class extends DirectAcpAgentDefinition {
@@ -25286,12 +24411,7 @@ var DeepSeekHarnessAgentSpecification = class extends DirectAcpAgentDefinition {
25286
24411
  context.signal
25287
24412
  );
25288
24413
  if (managed.path === agent.path) {
25289
- selectedHome = join6(
25290
- readStateDirectory(context.environment),
25291
- "agents",
25292
- this.id,
25293
- "home"
25294
- );
24414
+ selectedHome = join6(readStateDirectory(context.environment), "agents", this.id, "home");
25295
24415
  }
25296
24416
  } catch {
25297
24417
  context.signal.throwIfAborted();
@@ -25334,9 +24454,7 @@ import { isAbsolute as isAbsolute3, join as join7, relative as relative2, sep as
25334
24454
  // src/agent-installation/grok-managed-package.ts
25335
24455
  var GROK_BUILD_MANAGED_VERSION = "1.0.21";
25336
24456
  var GrokBuildManagedPackage = class extends SriManagedNpmPackageDefinition {
25337
- dependencyResolutionArguments = Object.freeze([
25338
- "--before=2026-09-04T19:51:47.325Z"
25339
- ]);
24457
+ dependencyResolutionArguments = Object.freeze(["--before=2026-09-04T19:51:47.325Z"]);
25340
24458
  includeOptionalDependencies = true;
25341
24459
  requiredDependencies;
25342
24460
  verifyDependencyClosure = true;
@@ -25408,14 +24526,7 @@ var GrokBuildAgentSpecification = class extends DirectAcpAgentDefinition {
25408
24526
  super(
25409
24527
  "MOBIUS_GROK_BUILD_PATH",
25410
24528
  ["--no-auto-update", "agent", "stdio"],
25411
- [
25412
- "agents",
25413
- "grok-build",
25414
- GROK_BUILD_MANAGED_VERSION,
25415
- "home",
25416
- "bin",
25417
- "grok"
25418
- ]
24529
+ ["agents", "grok-build", GROK_BUILD_MANAGED_VERSION, "home", "bin", "grok"]
25419
24530
  );
25420
24531
  }
25421
24532
  createLaunchEnvironment = async (agent, context) => {
@@ -25429,13 +24540,7 @@ var GrokBuildAgentSpecification = class extends DirectAcpAgentDefinition {
25429
24540
  if (managed.path === agent.path) {
25430
24541
  return Object.freeze({
25431
24542
  GROK_HOME: await realpath4(
25432
- join7(
25433
- stateDirectory,
25434
- "agents",
25435
- this.id,
25436
- GROK_BUILD_MANAGED_VERSION,
25437
- "home"
25438
- )
24543
+ join7(stateDirectory, "agents", this.id, GROK_BUILD_MANAGED_VERSION, "home")
25439
24544
  )
25440
24545
  });
25441
24546
  }
@@ -25446,44 +24551,22 @@ var GrokBuildAgentSpecification = class extends DirectAcpAgentDefinition {
25446
24551
  };
25447
24552
  resolveManagedAgent = async (stateDirectory, platform, signal) => {
25448
24553
  signal.throwIfAborted();
25449
- const versionRoot = await realpath4(
25450
- join7(stateDirectory, "agents", this.id, GROK_BUILD_MANAGED_VERSION)
25451
- );
25452
- await validateManagedNpmPackage(
25453
- join7(versionRoot, "package"),
25454
- grokBuildManagedPackage(platform, process.arch)
25455
- );
25456
- const executable = await resolveExecutablePath(
25457
- join7(versionRoot, "home", "bin", "grok"),
25458
- platform
25459
- );
24554
+ const versionRoot = await realpath4(join7(stateDirectory, "agents", this.id, GROK_BUILD_MANAGED_VERSION));
24555
+ await validateManagedNpmPackage(join7(versionRoot, "package"), grokBuildManagedPackage(platform, process.arch));
24556
+ const executable = await resolveExecutablePath(join7(versionRoot, "home", "bin", "grok"), platform);
25460
24557
  signal.throwIfAborted();
25461
24558
  if (executable === null || !isContainedPath2(versionRoot, executable.path)) {
25462
- throw new AgentProbeError(
25463
- "managed_agent_invalid",
25464
- "The managed Grok Build executable is invalid"
25465
- );
24559
+ throw new AgentProbeError("managed_agent_invalid", "The managed Grok Build executable is invalid");
25466
24560
  }
25467
24561
  return executable;
25468
24562
  };
25469
24563
  verifyAcp = async (connection, initialized, defaultWorkspace, signal) => {
25470
24564
  const capabilities = initialized.agentCapabilities ?? {};
25471
24565
  const session = capabilities.sessionCapabilities;
25472
- if (capabilities.loadSession !== true || session?.close == null || session.list == null || session.resume == null || !(initialized.authMethods ?? []).some(
25473
- (method) => method.id === "xai.api_key" || method.id === "grok.com"
25474
- )) {
25475
- throw new AgentProbeError(
25476
- "acp_incompatible",
25477
- "Grok Build reported an unsupported ACP capability set"
25478
- );
24566
+ if (capabilities.loadSession !== true || session?.close == null || session.list == null || session.resume == null || !(initialized.authMethods ?? []).some((method) => method.id === "xai.api_key" || method.id === "grok.com")) {
24567
+ throw new AgentProbeError("acp_incompatible", "Grok Build reported an unsupported ACP capability set");
25479
24568
  }
25480
- await verifySessionCreation(
25481
- connection,
25482
- capabilities,
25483
- defaultWorkspace,
25484
- signal,
25485
- this.label
25486
- );
24569
+ await verifySessionCreation(connection, capabilities, defaultWorkspace, signal, this.label);
25487
24570
  };
25488
24571
  };
25489
24572
 
@@ -25493,18 +24576,7 @@ import { join as join9 } from "node:path";
25493
24576
  // src/agent-installation/managed-agent-archive.ts
25494
24577
  import { createHash } from "node:crypto";
25495
24578
  import { createReadStream } from "node:fs";
25496
- import {
25497
- chmod,
25498
- copyFile,
25499
- mkdir as mkdir2,
25500
- mkdtemp as mkdtemp2,
25501
- open as open3,
25502
- realpath as realpath5,
25503
- rename as rename2,
25504
- rm as rm2,
25505
- stat as stat4,
25506
- writeFile
25507
- } from "node:fs/promises";
24579
+ import { chmod, copyFile, mkdir as mkdir2, mkdtemp as mkdtemp2, open as open3, realpath as realpath5, rename as rename2, rm as rm2, stat as stat4, writeFile } from "node:fs/promises";
25508
24580
  import { dirname as dirname4, isAbsolute as isAbsolute4, join as join8, relative as relative3, sep as sep3 } from "node:path";
25509
24581
 
25510
24582
  // src/agent-installation/verified-download.ts
@@ -25534,19 +24606,23 @@ var ManagedAgentArchiveDefinition = class {
25534
24606
  };
25535
24607
  var ZipManagedAgentArchiveDefinition = class extends ManagedAgentArchiveDefinition {
25536
24608
  extractor = "/usr/bin/unzip";
25537
- extractArguments = (archivePath, destination) => ["-q", archivePath, "-d", destination];
25538
- listArguments = (archivePath) => [
25539
- "-Z1",
25540
- archivePath
24609
+ extractArguments = (archivePath, destination) => [
24610
+ "-q",
24611
+ archivePath,
24612
+ "-d",
24613
+ destination
25541
24614
  ];
24615
+ listArguments = (archivePath) => ["-Z1", archivePath];
25542
24616
  };
25543
24617
  var TarGzipManagedAgentArchiveDefinition = class extends ManagedAgentArchiveDefinition {
25544
24618
  extractor = "/usr/bin/tar";
25545
- extractArguments = (archivePath, destination) => ["-xzf", archivePath, "-C", destination];
25546
- listArguments = (archivePath) => [
25547
- "-tzf",
25548
- archivePath
24619
+ extractArguments = (archivePath, destination) => [
24620
+ "-xzf",
24621
+ archivePath,
24622
+ "-C",
24623
+ destination
25549
24624
  ];
24625
+ listArguments = (archivePath) => ["-tzf", archivePath];
25550
24626
  };
25551
24627
  var ManagedAgentArchiveError = class extends Error {
25552
24628
  code;
@@ -25612,9 +24688,7 @@ async function readManifest(path2) {
25612
24688
  "The managed Agent archive manifest is invalid"
25613
24689
  );
25614
24690
  }
25615
- const parsed = JSON.parse(
25616
- await handle.readFile({ encoding: "utf8" })
25617
- );
24691
+ const parsed = JSON.parse(await handle.readFile({ encoding: "utf8" }));
25618
24692
  if (!isRecord6(parsed)) {
25619
24693
  throw new ManagedAgentArchiveError(
25620
24694
  "managed_archive_verification_failed",
@@ -25646,9 +24720,7 @@ async function validateManagedAgentArchive(root, definition, signal) {
25646
24720
  if (manifest["archiveSha256"] !== definition.archiveSha256 || manifest["archiveUrl"] !== definition.archiveUrl.toString() || manifest["version"] !== definition.version || typeof manifest["executableSha256"] !== "string") {
25647
24721
  throw new Error("Managed Agent archive identity is invalid");
25648
24722
  }
25649
- const executable = await resolveExecutablePath(
25650
- join8(rootPath, "bin", definition.executableName)
25651
- );
24723
+ const executable = await resolveExecutablePath(join8(rootPath, "bin", definition.executableName));
25652
24724
  if (executable === null || !isContainedPath3(rootPath, executable.path) || await hashFile(executable.path, signal) !== manifest["executableSha256"]) {
25653
24725
  throw new Error("Managed Agent executable is invalid");
25654
24726
  }
@@ -25671,9 +24743,7 @@ async function validateManagedAgentArchive(root, definition, signal) {
25671
24743
  // src/agent-installation/opencode-managed-release.ts
25672
24744
  var OPENCODE_MANAGED_VERSION = "1.18.29";
25673
24745
  function releaseUrl(asset) {
25674
- return new URL(
25675
- `https://github.com/anomalyco/opencode/releases/download/v${OPENCODE_MANAGED_VERSION}/${asset}`
25676
- );
24746
+ return new URL(`https://github.com/anomalyco/opencode/releases/download/v${OPENCODE_MANAGED_VERSION}/${asset}`);
25677
24747
  }
25678
24748
  function openCodeManagedArchive(platform, architecture) {
25679
24749
  if (platform === "darwin" && architecture === "arm64") {
@@ -25716,9 +24786,7 @@ function openCodeManagedArchive(platform, architecture) {
25716
24786
  "opencode"
25717
24787
  );
25718
24788
  }
25719
- throw new Error(
25720
- "OpenCode does not publish an approved archive for this platform"
25721
- );
24789
+ throw new Error("OpenCode does not publish an approved archive for this platform");
25722
24790
  }
25723
24791
 
25724
24792
  // src/agent-catalog/agents/opencode-agent.ts
@@ -25830,10 +24898,7 @@ var PiAgentSpecification = class extends BridgedAcpAgentDefinition {
25830
24898
  verifyAcp = async (connection, initialized, defaultWorkspace, signal) => {
25831
24899
  const capabilities = initialized.agentCapabilities ?? {};
25832
24900
  if (capabilities.loadSession !== true) {
25833
- throw new AgentProbeError(
25834
- "acp_incompatible",
25835
- "Pi ACP adapter does not support session recovery"
25836
- );
24901
+ throw new AgentProbeError("acp_incompatible", "Pi ACP adapter does not support session recovery");
25837
24902
  }
25838
24903
  const session = await connection.agent.request(
25839
24904
  methods5.agent.session.new,
@@ -25845,10 +24910,7 @@ var PiAgentSpecification = class extends BridgedAcpAgentDefinition {
25845
24910
  { cancellationSignal: signal }
25846
24911
  );
25847
24912
  if (session.sessionId.length === 0) {
25848
- throw new AgentProbeError(
25849
- "acp_incompatible",
25850
- "Pi ACP adapter returned an invalid session"
25851
- );
24913
+ throw new AgentProbeError("acp_incompatible", "Pi ACP adapter returned an invalid session");
25852
24914
  }
25853
24915
  const prompt = await connection.agent.request(
25854
24916
  methods5.agent.session.prompt,
@@ -25859,10 +24921,7 @@ var PiAgentSpecification = class extends BridgedAcpAgentDefinition {
25859
24921
  { cancellationSignal: signal }
25860
24922
  );
25861
24923
  if (prompt.stopReason !== "end_turn") {
25862
- throw new AgentProbeError(
25863
- "acp_incompatible",
25864
- "Pi ACP adapter did not complete its conformance prompt"
25865
- );
24924
+ throw new AgentProbeError("acp_incompatible", "Pi ACP adapter did not complete its conformance prompt");
25866
24925
  }
25867
24926
  };
25868
24927
  };
@@ -25873,9 +24932,7 @@ import { isAbsolute as isAbsolute5, join as join11 } from "node:path";
25873
24932
  // src/agent-installation/workbuddy-managed-package.ts
25874
24933
  var WORKBUDDY_MANAGED_VERSION = "2.146.0";
25875
24934
  var WorkBuddyManagedPackage = class extends SriManagedNpmPackageDefinition {
25876
- dependencyResolutionArguments = Object.freeze([
25877
- "--before=2026-09-05T12:39:25.295Z"
25878
- ]);
24935
+ dependencyResolutionArguments = Object.freeze(["--before=2026-09-05T12:39:25.295Z"]);
25879
24936
  includeOptionalDependencies = true;
25880
24937
  verifyDependencyClosure = true;
25881
24938
  };
@@ -25934,14 +24991,10 @@ var WorkBuddyAgentSpecification = class extends DirectAcpAgentDefinition {
25934
24991
  if ((context.platform ?? process.platform) !== "darwin") {
25935
24992
  return [];
25936
24993
  }
25937
- const requestedPaths = [
25938
- join11("/Applications", ...WORKBUDDY_MACOS_EXECUTABLE_PATH)
25939
- ];
24994
+ const requestedPaths = [join11("/Applications", ...WORKBUDDY_MACOS_EXECUTABLE_PATH)];
25940
24995
  const homeDirectory = context.environment["HOME"];
25941
24996
  if (homeDirectory !== void 0 && isAbsolute5(homeDirectory)) {
25942
- requestedPaths.unshift(
25943
- join11(homeDirectory, "Applications", ...WORKBUDDY_MACOS_EXECUTABLE_PATH)
25944
- );
24997
+ requestedPaths.unshift(join11(homeDirectory, "Applications", ...WORKBUDDY_MACOS_EXECUTABLE_PATH));
25945
24998
  }
25946
24999
  const executables = [];
25947
25000
  for (const requestedPath of requestedPaths) {
@@ -25956,18 +25009,9 @@ var WorkBuddyAgentSpecification = class extends DirectAcpAgentDefinition {
25956
25009
  verifyAcp = async (connection, initialized, defaultWorkspace, signal) => {
25957
25010
  const capabilities = initialized.agentCapabilities ?? {};
25958
25011
  if (capabilities.loadSession !== true || (initialized.authMethods ?? []).length === 0) {
25959
- throw new AgentProbeError(
25960
- "acp_incompatible",
25961
- "WorkBuddy reported an unsupported ACP capability set"
25962
- );
25012
+ throw new AgentProbeError("acp_incompatible", "WorkBuddy reported an unsupported ACP capability set");
25963
25013
  }
25964
- await verifySessionCreation(
25965
- connection,
25966
- capabilities,
25967
- defaultWorkspace,
25968
- signal,
25969
- this.label
25970
- );
25014
+ await verifySessionCreation(connection, capabilities, defaultWorkspace, signal, this.label);
25971
25015
  };
25972
25016
  };
25973
25017
 
@@ -26034,18 +25078,13 @@ function translateError(error61) {
26034
25078
  );
26035
25079
  }
26036
25080
  }
26037
- return new ManagedAdapterInstallError(
26038
- "adapter_install_failed",
26039
- "The pinned ACP adapter could not be installed",
26040
- { cause: error61 }
26041
- );
25081
+ return new ManagedAdapterInstallError("adapter_install_failed", "The pinned ACP adapter could not be installed", {
25082
+ cause: error61
25083
+ });
26042
25084
  }
26043
25085
  async function validateManagedAdapter(root, specification) {
26044
25086
  try {
26045
- return await validateManagedNpmPackage(
26046
- root,
26047
- specification.adapterPackageDefinition
26048
- );
25087
+ return await validateManagedNpmPackage(root, specification.adapterPackageDefinition);
26049
25088
  } catch (error61) {
26050
25089
  throw translateError(error61);
26051
25090
  }
@@ -26060,12 +25099,7 @@ var ManagedAdapterInstaller = class {
26060
25099
  this.#stateDirectory = options.stateDirectory;
26061
25100
  }
26062
25101
  install = async (specification, signal) => {
26063
- const root = join12(
26064
- this.#stateDirectory,
26065
- "adapters",
26066
- specification.id,
26067
- specification.adapterVersion
26068
- );
25102
+ const root = join12(this.#stateDirectory, "adapters", specification.id, specification.adapterVersion);
26069
25103
  try {
26070
25104
  return await this.#npmInstaller.install(
26071
25105
  root,
@@ -26099,12 +25133,7 @@ async function resolveManagedAdapterExecutable(specification, context) {
26099
25133
  let managed;
26100
25134
  try {
26101
25135
  managed = await validateManagedAdapter(
26102
- join13(
26103
- readStateDirectory(context.environment),
26104
- "adapters",
26105
- specification.id,
26106
- specification.adapterVersion
26107
- ),
25136
+ join13(readStateDirectory(context.environment), "adapters", specification.id, specification.adapterVersion),
26108
25137
  specification
26109
25138
  );
26110
25139
  } catch {
@@ -26121,11 +25150,7 @@ async function resolveSpecificationExecutables(executableName, overrideVariable,
26121
25150
  const executable = await resolveExecutablePath(override, context.platform);
26122
25151
  return executable === null ? [] : [executable];
26123
25152
  }
26124
- const external = await findExecutableOnPath(
26125
- executableName,
26126
- context.environment,
26127
- context.platform
26128
- );
25153
+ const external = await findExecutableOnPath(executableName, context.environment, context.platform);
26129
25154
  const installed = await resolveInstalled();
26130
25155
  const managed = await resolveManaged();
26131
25156
  const executables = [];
@@ -26187,10 +25212,7 @@ async function probeVersion(executable, arguments_, environment, defaultWorkspac
26187
25212
  });
26188
25213
  const version2 = normalizedVersion(result.stdout || result.stderr);
26189
25214
  if (version2.length === 0) {
26190
- throw new ProcessExecutionError(
26191
- "process_exit_failed",
26192
- "The executable did not report a version"
26193
- );
25215
+ throw new ProcessExecutionError("process_exit_failed", "The executable did not report a version");
26194
25216
  }
26195
25217
  return version2;
26196
25218
  }
@@ -26226,6 +25248,14 @@ async function findVerifiedAgentExecutable(specification, context) {
26226
25248
 
26227
25249
  // src/agent-catalog/acp-readiness-probe.ts
26228
25250
  var ACP_OUTPUT_LIMIT_BYTES = 1024 * 1024;
25251
+ var VerifiedAcpReadiness = class {
25252
+ adapterVersion;
25253
+ capabilities;
25254
+ constructor(adapterVersion, capabilities) {
25255
+ this.adapterVersion = adapterVersion;
25256
+ this.capabilities = capabilities;
25257
+ }
25258
+ };
26229
25259
  var DiscoveryAcpHandler = class {
26230
25260
  onElicitation = (_request, _signal) => Promise.reject(new Error("ACP probe does not accept elicitations"));
26231
25261
  onElicitationComplete = (_notification) => Promise.resolve();
@@ -26311,17 +25341,16 @@ async function probeAcpReadiness(specification, agent, environment, defaultWorks
26311
25341
  const rejectExit = () => reject(new Error("ACP adapter exited during initialization"));
26312
25342
  child.once("error", reject);
26313
25343
  child.once("exit", rejectExit);
26314
- if (child.exitCode !== null || child.signalCode !== null) rejectExit();
25344
+ if (child.exitCode !== null || child.signalCode !== null) {
25345
+ rejectExit();
25346
+ }
26315
25347
  });
26316
25348
  const stdin = child.stdin;
26317
25349
  const stdout = child.stdout;
26318
25350
  const stderr = child.stderr;
26319
25351
  if (stdin === null || stdout === null || stderr === null) {
26320
25352
  await stopProcessTree(child);
26321
- throw new AgentProbeError(
26322
- "acp_incompatible",
26323
- "ACP adapter streams are unavailable"
26324
- );
25353
+ throw new AgentProbeError("acp_incompatible", "ACP adapter streams are unavailable");
26325
25354
  }
26326
25355
  let stderrBytes = 0;
26327
25356
  const consumeStderr = (chunk) => {
@@ -26331,9 +25360,9 @@ async function probeAcpReadiness(specification, agent, environment, defaultWorks
26331
25360
  }
26332
25361
  };
26333
25362
  stderr.on("data", consumeStderr);
26334
- const connection = createAcpClient(
26335
- new DiscoveryAcpHandler()
26336
- ).connect(ndJsonStream2(writableAcpStream(stdin), readableAcpStream(stdout)));
25363
+ const connection = createAcpClient(new DiscoveryAcpHandler()).connect(
25364
+ ndJsonStream2(writableAcpStream(stdin), readableAcpStream(stdout))
25365
+ );
26337
25366
  try {
26338
25367
  const initialized = await Promise.race([
26339
25368
  connection.agent.request(
@@ -26348,44 +25377,27 @@ async function probeAcpReadiness(specification, agent, environment, defaultWorks
26348
25377
  processExit
26349
25378
  ]);
26350
25379
  if (initialized.protocolVersion !== PROTOCOL_VERSION2) {
26351
- throw new AgentProbeError(
26352
- "acp_incompatible",
26353
- "ACP adapter selected an unsupported protocol version"
26354
- );
25380
+ throw new AgentProbeError("acp_incompatible", "ACP adapter selected an unsupported protocol version");
26355
25381
  }
26356
- await specification.verifyAcp(
26357
- connection,
26358
- initialized,
26359
- defaultWorkspace,
26360
- controller.signal
25382
+ await specification.verifyAcp(connection, initialized, defaultWorkspace, controller.signal);
25383
+ return new VerifiedAcpReadiness(
25384
+ normalizedVersion(initialized.agentInfo?.version ?? ""),
25385
+ normalizeAcpCapabilities(initialized.agentCapabilities ?? {})
26361
25386
  );
26362
- return normalizedVersion(initialized.agentInfo?.version ?? "");
26363
25387
  } catch (error61) {
26364
25388
  if (signal.aborted) {
26365
25389
  signal.throwIfAborted();
26366
25390
  }
26367
25391
  if (timedOut) {
26368
- throw new AgentProbeError(
26369
- "adapter_probe_timeout",
26370
- "ACP adapter probe timed out",
26371
- { cause: error61 }
26372
- );
25392
+ throw new AgentProbeError("adapter_probe_timeout", "ACP adapter probe timed out", { cause: error61 });
26373
25393
  }
26374
25394
  if (error61 instanceof AgentProbeError) {
26375
25395
  throw error61;
26376
25396
  }
26377
25397
  if (error61 instanceof RequestError2 && error61.code === -32e3 && specification.authenticationCommand().length > 0) {
26378
- throw new AgentProbeError(
26379
- "authentication_required",
26380
- "Agent authentication is required",
26381
- { cause: error61 }
26382
- );
25398
+ throw new AgentProbeError("authentication_required", "Agent authentication is required", { cause: error61 });
26383
25399
  }
26384
- throw new AgentProbeError(
26385
- "acp_incompatible",
26386
- "ACP adapter initialization failed",
26387
- { cause: error61 }
26388
- );
25400
+ throw new AgentProbeError("acp_incompatible", "ACP adapter initialization failed", { cause: error61 });
26389
25401
  } finally {
26390
25402
  clearTimeout(timeout);
26391
25403
  signal.removeEventListener("abort", abort);
@@ -26403,45 +25415,22 @@ function agentProbeFailure(specification, error61) {
26403
25415
  }
26404
25416
  if (error61 instanceof ProcessExecutionError) {
26405
25417
  const code = error61.code === "process_timeout" ? "agent_probe_timeout" : "agent_probe_failed";
26406
- return new AgentProbeFailed(
26407
- specification,
26408
- code,
26409
- "Agent version probe failed"
26410
- );
25418
+ return new AgentProbeFailed(specification, code, "Agent version probe failed");
26411
25419
  }
26412
- return new AgentProbeFailed(
26413
- specification,
26414
- "agent_probe_failed",
26415
- "Agent probe failed"
26416
- );
25420
+ return new AgentProbeFailed(specification, "agent_probe_failed", "Agent probe failed");
26417
25421
  }
26418
25422
  function integrationProbeFailure(specification, agent, error61) {
26419
25423
  if (error61 instanceof AgentProbeError) {
26420
25424
  if (error61.code === "authentication_required") {
26421
25425
  return new AuthenticationRequiredAgent(specification, agent);
26422
25426
  }
26423
- return error61.code === "acp_incompatible" ? new IncompatibleAdapter(specification, agent) : new IntegrationProbeFailed(
26424
- specification,
26425
- agent,
26426
- error61.code,
26427
- error61.message
26428
- );
25427
+ return error61.code === "acp_incompatible" ? new IncompatibleAdapter(specification, agent) : new IntegrationProbeFailed(specification, agent, error61.code, error61.message);
26429
25428
  }
26430
25429
  if (error61 instanceof ProcessExecutionError) {
26431
25430
  const code = error61.code === "process_timeout" ? "adapter_probe_timeout" : "adapter_probe_failed";
26432
- return new IntegrationProbeFailed(
26433
- specification,
26434
- agent,
26435
- code,
26436
- "Adapter version probe failed"
26437
- );
25431
+ return new IntegrationProbeFailed(specification, agent, code, "Adapter version probe failed");
26438
25432
  }
26439
- return new IntegrationProbeFailed(
26440
- specification,
26441
- agent,
26442
- "adapter_probe_failed",
26443
- "Adapter probe failed"
26444
- );
25433
+ return new IntegrationProbeFailed(specification, agent, "adapter_probe_failed", "Adapter probe failed");
26445
25434
  }
26446
25435
  async function discoverAgent(specification, context) {
26447
25436
  context.signal.throwIfAborted();
@@ -26487,10 +25476,7 @@ async function discoverAgent(specification, context) {
26487
25476
  let adapterVersion = "";
26488
25477
  let launchEnvironment;
26489
25478
  try {
26490
- launchEnvironment = await specification.createLaunchEnvironment(
26491
- agent,
26492
- context
26493
- );
25479
+ launchEnvironment = await specification.createLaunchEnvironment(agent, context);
26494
25480
  if (specification.adapterVersionArguments.length > 0) {
26495
25481
  adapterVersion = await probeVersion(
26496
25482
  adapter,
@@ -26508,11 +25494,7 @@ async function discoverAgent(specification, context) {
26508
25494
  if (context.signal.aborted) {
26509
25495
  context.signal.throwIfAborted();
26510
25496
  }
26511
- lastFailure = integrationProbeFailure(
26512
- specification,
26513
- installedAgent,
26514
- error61
26515
- );
25497
+ lastFailure = integrationProbeFailure(specification, installedAgent, error61);
26516
25498
  continue;
26517
25499
  }
26518
25500
  const definition = new LocalAgentDefinition(
@@ -26528,19 +25510,16 @@ async function discoverAgent(specification, context) {
26528
25510
  specification.promptTimeoutMilliseconds
26529
25511
  );
26530
25512
  try {
26531
- const acpVersion = await probeAcpReadiness(
25513
+ const readiness = await probeAcpReadiness(
26532
25514
  specification,
26533
25515
  definition,
26534
25516
  context.environment,
26535
25517
  context.defaultWorkspace,
26536
25518
  context.signal
26537
25519
  );
26538
- const verifiedAdapterVersion = adapterVersion.length > 0 ? adapterVersion : acpVersion;
25520
+ const verifiedAdapterVersion = adapterVersion.length > 0 ? adapterVersion : readiness.adapterVersion;
26539
25521
  if (verifiedAdapterVersion.length === 0) {
26540
- throw new AgentProbeError(
26541
- "acp_incompatible",
26542
- "ACP adapter did not report a version"
26543
- );
25522
+ throw new AgentProbeError("acp_incompatible", "ACP adapter did not report a version");
26544
25523
  }
26545
25524
  return new AvailableAgent(
26546
25525
  specification,
@@ -26554,18 +25533,15 @@ async function discoverAgent(specification, context) {
26554
25533
  agentVersion,
26555
25534
  adapter.identity,
26556
25535
  agent.identity,
26557
- specification.promptTimeoutMilliseconds
25536
+ specification.promptTimeoutMilliseconds,
25537
+ readiness.capabilities
26558
25538
  )
26559
25539
  );
26560
25540
  } catch (error61) {
26561
25541
  if (context.signal.aborted) {
26562
25542
  context.signal.throwIfAborted();
26563
25543
  }
26564
- const failure = integrationProbeFailure(
26565
- specification,
26566
- installedAgent,
26567
- error61
26568
- );
25544
+ const failure = integrationProbeFailure(specification, installedAgent, error61);
26569
25545
  if (failure instanceof AuthenticationRequiredAgent) {
26570
25546
  return failure;
26571
25547
  }
@@ -26580,9 +25556,7 @@ async function discoverAgent(specification, context) {
26580
25556
  async function discoverLocalAgentInventory(options) {
26581
25557
  const specifications = options.specifications ?? supportedLocalAgentSpecifications();
26582
25558
  const discoveries = await Promise.all(
26583
- specifications.map(
26584
- async (specification) => await discoverAgent(specification, options)
26585
- )
25559
+ specifications.map(async (specification) => await discoverAgent(specification, options))
26586
25560
  );
26587
25561
  return new LocalAgentInventory(discoveries);
26588
25562
  }
@@ -26590,20 +25564,11 @@ async function discoverLocalAgentInventory(options) {
26590
25564
  // src/pairing/pair-local-machine.ts
26591
25565
  var PAIRING_TIMEOUT_MILLISECONDS = 2e4;
26592
25566
  var PAIRING_CODE_PATTERN = /^[A-HJ-NP-Z2-9]{4}(?:-[A-HJ-NP-Z2-9]{4}){4}$/;
26593
- var IDENTIFIER_PATTERN5 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
25567
+ var IDENTIFIER_PATTERN4 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
26594
25568
  var TOKEN_PATTERN = /^[a-zA-Z0-9_-]{32,256}$/;
26595
25569
  var MAX_CONNECTION_FILE_LENGTH = 16 * 1024;
26596
- var CLAIM_RESPONSE_KEYS = [
26597
- "channelId",
26598
- "daemonToken",
26599
- "runtimeId"
26600
- ];
26601
- var SAVED_CONNECTION_KEYS = [
26602
- "defaultWorkspace",
26603
- "channelId",
26604
- "daemonToken",
26605
- "relayOrigin"
26606
- ];
25570
+ var CLAIM_RESPONSE_KEYS = ["channelId", "daemonToken", "runtimeId"];
25571
+ var SAVED_CONNECTION_KEYS = ["defaultWorkspace", "channelId", "daemonToken", "relayOrigin"];
26607
25572
  var PairingClientError = class extends Error {
26608
25573
  code;
26609
25574
  constructor(code, message, options = {}) {
@@ -26627,19 +25592,13 @@ function readSingleOption(arguments_, option) {
26627
25592
  }
26628
25593
  const value = arguments_[index + 1];
26629
25594
  if (value === void 0 || value.startsWith("--")) {
26630
- throw new PairingClientError(
26631
- "invalid_arguments",
26632
- `${option} requires a value`
26633
- );
25595
+ throw new PairingClientError("invalid_arguments", `${option} requires a value`);
26634
25596
  }
26635
25597
  values.push(value);
26636
25598
  index += 1;
26637
25599
  }
26638
25600
  if (values.length !== 1) {
26639
- throw new PairingClientError(
26640
- "invalid_arguments",
26641
- `${option} must be provided exactly once`
26642
- );
25601
+ throw new PairingClientError("invalid_arguments", `${option} must be provided exactly once`);
26643
25602
  }
26644
25603
  return values[0] ?? "";
26645
25604
  }
@@ -26647,10 +25606,7 @@ function assertKnownArguments(arguments_) {
26647
25606
  for (let index = 0; index < arguments_.length; index += 2) {
26648
25607
  const option = arguments_[index];
26649
25608
  if (option !== "--url" && option !== "--code" && option !== "--workspace") {
26650
- throw new PairingClientError(
26651
- "invalid_arguments",
26652
- `Unknown pairing option: ${option ?? "missing option"}`
26653
- );
25609
+ throw new PairingClientError("invalid_arguments", `Unknown pairing option: ${option ?? "missing option"}`);
26654
25610
  }
26655
25611
  }
26656
25612
  }
@@ -26659,29 +25615,16 @@ function parseRelayOrigin(value) {
26659
25615
  try {
26660
25616
  url2 = new URL(value);
26661
25617
  } catch (error61) {
26662
- throw new PairingClientError(
26663
- "invalid_relay_url",
26664
- "The relay URL is invalid",
26665
- { cause: error61 }
26666
- );
25618
+ throw new PairingClientError("invalid_relay_url", "The relay URL is invalid", { cause: error61 });
26667
25619
  }
26668
25620
  if (url2.protocol !== "https:" && url2.protocol !== "http:") {
26669
- throw new PairingClientError(
26670
- "invalid_relay_url",
26671
- "The relay URL must use http or https"
26672
- );
25621
+ throw new PairingClientError("invalid_relay_url", "The relay URL must use http or https");
26673
25622
  }
26674
25623
  if (url2.username.length > 0 || url2.password.length > 0) {
26675
- throw new PairingClientError(
26676
- "invalid_relay_url",
26677
- "The relay URL cannot contain credentials"
26678
- );
25624
+ throw new PairingClientError("invalid_relay_url", "The relay URL cannot contain credentials");
26679
25625
  }
26680
25626
  if (url2.protocol === "http:" && url2.hostname !== "127.0.0.1" && url2.hostname !== "localhost") {
26681
- throw new PairingClientError(
26682
- "invalid_relay_url",
26683
- "A remote relay must use https"
26684
- );
25627
+ throw new PairingClientError("invalid_relay_url", "A remote relay must use https");
26685
25628
  }
26686
25629
  url2.hash = "";
26687
25630
  url2.pathname = "/";
@@ -26708,17 +25651,11 @@ function parsePairCommand(arguments_) {
26708
25651
  }
26709
25652
  function parseChannelArgument(arguments_) {
26710
25653
  if (arguments_.length !== 2 || arguments_[0] !== "--channel") {
26711
- throw new PairingClientError(
26712
- "invalid_arguments",
26713
- "Usage: mobius start --channel <channel-id>"
26714
- );
25654
+ throw new PairingClientError("invalid_arguments", "Usage: mobius start --channel <channel-id>");
26715
25655
  }
26716
25656
  const channelId = arguments_[1] ?? "";
26717
- if (!IDENTIFIER_PATTERN5.test(channelId)) {
26718
- throw new PairingClientError(
26719
- "invalid_channel_id",
26720
- "The saved channel ID is invalid"
26721
- );
25657
+ if (!IDENTIFIER_PATTERN4.test(channelId)) {
25658
+ throw new PairingClientError("invalid_channel_id", "The saved channel ID is invalid");
26722
25659
  }
26723
25660
  return channelId;
26724
25661
  }
@@ -26729,21 +25666,14 @@ async function resolveDefaultWorkspace(path2) {
26729
25666
  const defaultWorkspace = await realpath6(requestedWorkspace);
26730
25667
  const metadata = await stat5(defaultWorkspace);
26731
25668
  if (!metadata.isDirectory()) {
26732
- throw new PairingClientError(
26733
- "invalid_workspace",
26734
- "The default workspace is not a directory"
26735
- );
25669
+ throw new PairingClientError("invalid_workspace", "The default workspace is not a directory");
26736
25670
  }
26737
25671
  return defaultWorkspace;
26738
25672
  } catch (error61) {
26739
25673
  if (error61 instanceof PairingClientError) {
26740
25674
  throw error61;
26741
25675
  }
26742
- throw new PairingClientError(
26743
- "invalid_workspace",
26744
- "The default workspace cannot be resolved",
26745
- { cause: error61 }
26746
- );
25676
+ throw new PairingClientError("invalid_workspace", "The default workspace cannot be resolved", { cause: error61 });
26747
25677
  }
26748
25678
  }
26749
25679
  async function readJsonResponse(response) {
@@ -26757,11 +25687,9 @@ async function readJsonResponse(response) {
26757
25687
  try {
26758
25688
  return JSON.parse(encoded);
26759
25689
  } catch (error61) {
26760
- throw new PairingClientError(
26761
- "invalid_relay_response",
26762
- "The relay returned an invalid response",
26763
- { cause: error61 }
26764
- );
25690
+ throw new PairingClientError("invalid_relay_response", "The relay returned an invalid response", {
25691
+ cause: error61
25692
+ });
26765
25693
  }
26766
25694
  }
26767
25695
  function readRelayError(value) {
@@ -26775,26 +25703,17 @@ function readRelayError(value) {
26775
25703
  }
26776
25704
  }
26777
25705
  }
26778
- return new PairingClientError(
26779
- "pairing_failed",
26780
- "The relay could not pair this machine"
26781
- );
25706
+ return new PairingClientError("pairing_failed", "The relay could not pair this machine");
26782
25707
  }
26783
25708
  function decodeClaimResponse(value) {
26784
25709
  if (!isRecord7(value) || !hasExactKeys(value, CLAIM_RESPONSE_KEYS)) {
26785
- throw new PairingClientError(
26786
- "invalid_relay_response",
26787
- "The relay returned an invalid pairing response"
26788
- );
25710
+ throw new PairingClientError("invalid_relay_response", "The relay returned an invalid pairing response");
26789
25711
  }
26790
25712
  const channelId = value["channelId"];
26791
25713
  const daemonToken = value["daemonToken"];
26792
25714
  const runtimeId = value["runtimeId"];
26793
- if (typeof channelId !== "string" || !IDENTIFIER_PATTERN5.test(channelId) || typeof daemonToken !== "string" || !TOKEN_PATTERN.test(daemonToken) || typeof runtimeId !== "string" || !IDENTIFIER_PATTERN5.test(runtimeId)) {
26794
- throw new PairingClientError(
26795
- "invalid_relay_response",
26796
- "The relay returned an invalid pairing response"
26797
- );
25715
+ if (typeof channelId !== "string" || !IDENTIFIER_PATTERN4.test(channelId) || typeof daemonToken !== "string" || !TOKEN_PATTERN.test(daemonToken) || typeof runtimeId !== "string" || !IDENTIFIER_PATTERN4.test(runtimeId)) {
25716
+ throw new PairingClientError("invalid_relay_response", "The relay returned an invalid pairing response");
26798
25717
  }
26799
25718
  return { channelId, daemonToken, runtimeId };
26800
25719
  }
@@ -26802,6 +25721,7 @@ async function claimPairing(options, defaultWorkspace, localAgents, installableA
26802
25721
  const agents = localAgents.map((agent) => ({
26803
25722
  agentPath: agent.agentIdentity.requestedPath,
26804
25723
  agentVersion: agent.agentVersion,
25724
+ capabilities: agent.capabilities,
26805
25725
  id: agent.id,
26806
25726
  label: agent.label
26807
25727
  }));
@@ -26819,17 +25739,10 @@ async function claimPairing(options, defaultWorkspace, localAgents, installableA
26819
25739
  dispatcher: environmentProxyDispatcher,
26820
25740
  headers: { "content-type": "application/json" },
26821
25741
  method: "POST",
26822
- signal: AbortSignal.any([
26823
- signal,
26824
- AbortSignal.timeout(PAIRING_TIMEOUT_MILLISECONDS)
26825
- ])
25742
+ signal: AbortSignal.any([signal, AbortSignal.timeout(PAIRING_TIMEOUT_MILLISECONDS)])
26826
25743
  });
26827
25744
  } catch (error61) {
26828
- throw new PairingClientError(
26829
- "relay_unavailable",
26830
- "The pairing relay could not be reached",
26831
- { cause: error61 }
26832
- );
25745
+ throw new PairingClientError("relay_unavailable", "The pairing relay could not be reached", { cause: error61 });
26833
25746
  }
26834
25747
  const value = await readJsonResponse(response);
26835
25748
  if (!response.ok) {
@@ -26841,10 +25754,7 @@ async function persistConnection(channelId, relayOrigin, daemonToken, defaultWor
26841
25754
  const connectionsDirectory = join14(readStateDirectory(), "connections");
26842
25755
  await mkdir3(connectionsDirectory, { mode: 448, recursive: true });
26843
25756
  const connectionPath = join14(connectionsDirectory, `${channelId}.json`);
26844
- const temporaryPath = join14(
26845
- connectionsDirectory,
26846
- `.${channelId}.${randomUUID()}.tmp`
26847
- );
25757
+ const temporaryPath = join14(connectionsDirectory, `.${channelId}.${randomUUID()}.tmp`);
26848
25758
  await writeFile2(
26849
25759
  temporaryPath,
26850
25760
  `${JSON.stringify(
@@ -26865,20 +25775,14 @@ async function persistConnection(channelId, relayOrigin, daemonToken, defaultWor
26865
25775
  }
26866
25776
  function decodeSavedConnection(value, expectedChannelId) {
26867
25777
  if (!isRecord7(value) || !hasExactKeys(value, SAVED_CONNECTION_KEYS)) {
26868
- throw new PairingClientError(
26869
- "invalid_connection",
26870
- "The saved connection is invalid"
26871
- );
25778
+ throw new PairingClientError("invalid_connection", "The saved connection is invalid");
26872
25779
  }
26873
25780
  const defaultWorkspace = value["defaultWorkspace"];
26874
25781
  const channelId = value["channelId"];
26875
25782
  const daemonToken = value["daemonToken"];
26876
25783
  const relayOrigin = value["relayOrigin"];
26877
- if (typeof defaultWorkspace !== "string" || typeof channelId !== "string" || channelId !== expectedChannelId || !IDENTIFIER_PATTERN5.test(channelId) || typeof daemonToken !== "string" || !TOKEN_PATTERN.test(daemonToken) || typeof relayOrigin !== "string") {
26878
- throw new PairingClientError(
26879
- "invalid_connection",
26880
- "The saved connection is invalid"
26881
- );
25784
+ if (typeof defaultWorkspace !== "string" || typeof channelId !== "string" || channelId !== expectedChannelId || !IDENTIFIER_PATTERN4.test(channelId) || typeof daemonToken !== "string" || !TOKEN_PATTERN.test(daemonToken) || typeof relayOrigin !== "string") {
25785
+ throw new PairingClientError("invalid_connection", "The saved connection is invalid");
26882
25786
  }
26883
25787
  return {
26884
25788
  defaultWorkspace,
@@ -26888,20 +25792,13 @@ function decodeSavedConnection(value, expectedChannelId) {
26888
25792
  };
26889
25793
  }
26890
25794
  async function readSavedConnection(channelId) {
26891
- const connectionPath = join14(
26892
- readStateDirectory(),
26893
- "connections",
26894
- `${channelId}.json`
26895
- );
25795
+ const connectionPath = join14(readStateDirectory(), "connections", `${channelId}.json`);
26896
25796
  let encoded = "";
26897
25797
  const handle = await open4(connectionPath, "r");
26898
25798
  try {
26899
25799
  const metadata = await handle.stat();
26900
25800
  if (!metadata.isFile() || metadata.size > MAX_CONNECTION_FILE_LENGTH) {
26901
- throw new PairingClientError(
26902
- "invalid_connection",
26903
- "The saved connection is invalid"
26904
- );
25801
+ throw new PairingClientError("invalid_connection", "The saved connection is invalid");
26905
25802
  }
26906
25803
  encoded = await handle.readFile({ encoding: "utf8" });
26907
25804
  } finally {
@@ -26911,17 +25808,11 @@ async function readSavedConnection(channelId) {
26911
25808
  try {
26912
25809
  value = JSON.parse(encoded);
26913
25810
  } catch (error61) {
26914
- throw new PairingClientError(
26915
- "invalid_connection",
26916
- "The saved connection is invalid",
26917
- { cause: error61 }
26918
- );
25811
+ throw new PairingClientError("invalid_connection", "The saved connection is invalid", { cause: error61 });
26919
25812
  }
26920
25813
  const connection = decodeSavedConnection(value, channelId);
26921
25814
  return {
26922
- defaultWorkspace: await resolveDefaultWorkspace(
26923
- connection.defaultWorkspace
26924
- ),
25815
+ defaultWorkspace: await resolveDefaultWorkspace(connection.defaultWorkspace),
26925
25816
  channelId: connection.channelId,
26926
25817
  daemonToken: connection.daemonToken,
26927
25818
  relayOrigin: connection.relayOrigin
@@ -26929,10 +25820,7 @@ async function readSavedConnection(channelId) {
26929
25820
  }
26930
25821
  function assertInventoryUsable(inventory) {
26931
25822
  if (inventory.available.length + inventory.installable.length === 0) {
26932
- throw new PairingClientError(
26933
- "no_supported_agent",
26934
- "No supported Agent is available for local discovery"
26935
- );
25823
+ throw new PairingClientError("no_supported_agent", "No supported Agent is available for local discovery");
26936
25824
  }
26937
25825
  }
26938
25826
  function buildPairedDaemon(connection, connectionPath, inventory) {
@@ -26943,16 +25831,9 @@ function buildPairedDaemon(connection, connectionPath, inventory) {
26943
25831
  );
26944
25832
  relayUrl.protocol = relayUrl.protocol === "https:" ? "wss:" : "ws:";
26945
25833
  relayUrl.searchParams.set("token", connection.daemonToken);
26946
- const auditDatabasePath = join14(
26947
- readStateDirectory(),
26948
- "audit",
26949
- `${connection.channelId}.sqlite`
26950
- );
25834
+ const auditDatabasePath = join14(readStateDirectory(), "audit", `${connection.channelId}.sqlite`);
26951
25835
  return {
26952
- channelUrl: new URL(
26953
- `/channels/${encodeURIComponent(connection.channelId)}`,
26954
- connection.relayOrigin
26955
- ).toString(),
25836
+ channelUrl: new URL(`/channels/${encodeURIComponent(connection.channelId)}`, connection.relayOrigin).toString(),
26956
25837
  config: createDaemonConfig(
26957
25838
  {
26958
25839
  defaultWorkspace: connection.defaultWorkspace,
@@ -26976,13 +25857,7 @@ async function pairLocalMachine(arguments_, signal = new AbortController().signa
26976
25857
  });
26977
25858
  assertInventoryUsable(inventory);
26978
25859
  const agents = inventory.readyAgents();
26979
- const claim2 = await claimPairing(
26980
- options,
26981
- defaultWorkspace,
26982
- agents,
26983
- inventory.installable,
26984
- signal
26985
- );
25860
+ const claim2 = await claimPairing(options, defaultWorkspace, agents, inventory.installable, signal);
26986
25861
  const connectionPath = await persistConnection(
26987
25862
  claim2.channelId,
26988
25863
  options.relayOrigin,
@@ -27002,11 +25877,7 @@ async function pairLocalMachine(arguments_, signal = new AbortController().signa
27002
25877
  }
27003
25878
  async function resumeLocalMachine(arguments_, signal = new AbortController().signal) {
27004
25879
  const channelId = parseChannelArgument(arguments_);
27005
- const connectionPath = join14(
27006
- readStateDirectory(),
27007
- "connections",
27008
- `${channelId}.json`
27009
- );
25880
+ const connectionPath = join14(readStateDirectory(), "connections", `${channelId}.json`);
27010
25881
  const connection = await readSavedConnection(channelId);
27011
25882
  const inventory = await discoverLocalAgentInventory({
27012
25883
  defaultWorkspace: connection.defaultWorkspace,
@@ -27019,7 +25890,7 @@ async function resumeLocalMachine(arguments_, signal = new AbortController().sig
27019
25890
  // src/run-daemon.ts
27020
25891
  import { basename as basename3 } from "node:path";
27021
25892
  import { styleText } from "node:util";
27022
- import { fetch as fetch4, WebSocket as WebSocket2 } from "undici";
25893
+ import { fetch as fetch5, WebSocket as WebSocket2 } from "undici";
27023
25894
 
27024
25895
  // src/agent-catalog/publish-agent-catalog.ts
27025
25896
  import { fetch as fetch3 } from "undici";
@@ -27042,9 +25913,7 @@ function catalogEndpoint(relayUrl) {
27042
25913
  }
27043
25914
  async function publishAgentCatalog(config2, signal) {
27044
25915
  signal.throwIfAborted();
27045
- const timeoutSignal = AbortSignal.timeout(
27046
- CATALOG_UPDATE_TIMEOUT_MILLISECONDS
27047
- );
25916
+ const timeoutSignal = AbortSignal.timeout(CATALOG_UPDATE_TIMEOUT_MILLISECONDS);
27048
25917
  const requestSignal = AbortSignal.any([signal, timeoutSignal]);
27049
25918
  let response;
27050
25919
  const catalog = config2.catalog.read();
@@ -27054,6 +25923,7 @@ async function publishAgentCatalog(config2, signal) {
27054
25923
  agents: catalog.agents.map((agent) => ({
27055
25924
  agentPath: agent.agentIdentity.requestedPath,
27056
25925
  agentVersion: agent.agentVersion,
25926
+ capabilities: agent.capabilities,
27057
25927
  id: agent.id,
27058
25928
  label: agent.label
27059
25929
  })),
@@ -27075,9 +25945,7 @@ async function publishAgentCatalog(config2, signal) {
27075
25945
  }
27076
25946
  await response.body?.cancel();
27077
25947
  if (!response.ok) {
27078
- throw new AgentCatalogPublishError(
27079
- "The Relay rejected the Agent catalog update"
27080
- );
25948
+ throw new AgentCatalogPublishError("The Relay rejected the Agent catalog update");
27081
25949
  }
27082
25950
  }
27083
25951
 
@@ -27163,11 +26031,9 @@ function executionFailure(error61) {
27163
26031
  if (error61 instanceof InstallationManagerError) {
27164
26032
  return error61;
27165
26033
  }
27166
- return new InstallationManagerError(
27167
- "installation_failed",
27168
- "The local Agent integration installation failed",
27169
- { cause: error61 }
27170
- );
26034
+ return new InstallationManagerError("installation_failed", "The local Agent integration installation failed", {
26035
+ cause: error61
26036
+ });
27171
26037
  }
27172
26038
  var AgentInstallationManager = class {
27173
26039
  #activeAgents = /* @__PURE__ */ new Map();
@@ -27203,15 +26069,8 @@ var AgentInstallationManager = class {
27203
26069
  await this.#observer.onState(existing.state);
27204
26070
  return await existing.completion.promise;
27205
26071
  }
27206
- this.#audit.record(
27207
- "agent_installation_requested",
27208
- command.requestId,
27209
- command.agentId
27210
- );
27211
- const specification = authorizedSpecificationFor(
27212
- this.#specifications,
27213
- command.agentId
27214
- );
26072
+ this.#audit.record("agent_installation_requested", command.requestId, command.agentId);
26073
+ const specification = authorizedSpecificationFor(this.#specifications, command.agentId);
27215
26074
  if (specification === null) {
27216
26075
  const unknown2 = new FailedInstallation(
27217
26076
  command.requestId,
@@ -27223,11 +26082,7 @@ var AgentInstallationManager = class {
27223
26082
  job2.state = unknown2;
27224
26083
  job2.completion.resolve(unknown2);
27225
26084
  this.#jobs.set(command.requestId, job2);
27226
- this.#audit.record(
27227
- "agent_installation_failed_unknown_agent",
27228
- command.requestId,
27229
- command.agentId
27230
- );
26085
+ this.#audit.record("agent_installation_failed_unknown_agent", command.requestId, command.agentId);
27231
26086
  await this.#observer.onState(unknown2);
27232
26087
  return unknown2;
27233
26088
  }
@@ -27259,20 +26114,13 @@ var AgentInstallationManager = class {
27259
26114
  cancel = async (requestId) => {
27260
26115
  const job = this.#jobs.get(requestId);
27261
26116
  if (job === void 0) {
27262
- throw new InstallationManagerError(
27263
- "installation_not_found",
27264
- "The installation request was not found"
27265
- );
26117
+ throw new InstallationManagerError("installation_not_found", "The installation request was not found");
27266
26118
  }
27267
26119
  if (job.state instanceof SucceededInstallation || job.state instanceof FailedInstallation || job.state instanceof CancelledInstallation) {
27268
26120
  await this.#observer.onState(job.state);
27269
26121
  return job.state;
27270
26122
  }
27271
- this.#audit.record(
27272
- "agent_installation_cancellation_requested",
27273
- job.requestId,
27274
- job.agentId
27275
- );
26123
+ this.#audit.record("agent_installation_cancellation_requested", job.requestId, job.agentId);
27276
26124
  job.controller.abort(new Error("Agent integration installation cancelled"));
27277
26125
  return await job.completion.promise;
27278
26126
  };
@@ -27312,36 +26160,21 @@ var AgentInstallationManager = class {
27312
26160
  const signal = job.controller.signal;
27313
26161
  try {
27314
26162
  signal.throwIfAborted();
27315
- this.#audit.record(
27316
- "agent_installation_authorized",
27317
- job.requestId,
27318
- specification.id
27319
- );
26163
+ this.#audit.record("agent_installation_authorized", job.requestId, specification.id);
27320
26164
  await this.#executor.execute(
27321
26165
  specification.id,
27322
26166
  job.requestId,
27323
26167
  async (stage) => {
27324
26168
  signal.throwIfAborted();
27325
- await this.#transition(
27326
- job,
27327
- new RunningInstallation(job.requestId, job.agentId, stage)
27328
- );
27329
- this.#audit.record(
27330
- `agent_installation_${stage}`,
27331
- job.requestId,
27332
- job.agentId
27333
- );
26169
+ await this.#transition(job, new RunningInstallation(job.requestId, job.agentId, stage));
26170
+ this.#audit.record(`agent_installation_${stage}`, job.requestId, job.agentId);
27334
26171
  },
27335
26172
  signal
27336
26173
  );
27337
26174
  signal.throwIfAborted();
27338
26175
  const succeeded = new SucceededInstallation(job.requestId, job.agentId);
27339
26176
  await this.#transition(job, succeeded);
27340
- this.#audit.record(
27341
- "agent_installation_completed",
27342
- job.requestId,
27343
- job.agentId
27344
- );
26177
+ this.#audit.record("agent_installation_completed", job.requestId, job.agentId);
27345
26178
  job.completion.resolve(succeeded);
27346
26179
  } catch (error61) {
27347
26180
  if (signal.aborted) {
@@ -27353,36 +26186,19 @@ var AgentInstallationManager = class {
27353
26186
  signal.reason.message
27354
26187
  );
27355
26188
  await this.#transition(job, timedOut);
27356
- this.#audit.record(
27357
- "agent_installation_failed_installation_timeout",
27358
- job.requestId,
27359
- job.agentId
27360
- );
26189
+ this.#audit.record("agent_installation_failed_installation_timeout", job.requestId, job.agentId);
27361
26190
  job.completion.resolve(timedOut);
27362
26191
  return;
27363
26192
  }
27364
26193
  const cancelled = new CancelledInstallation(job.requestId, job.agentId);
27365
26194
  await this.#transition(job, cancelled);
27366
- this.#audit.record(
27367
- "agent_installation_cancelled",
27368
- job.requestId,
27369
- job.agentId
27370
- );
26195
+ this.#audit.record("agent_installation_cancelled", job.requestId, job.agentId);
27371
26196
  job.completion.resolve(cancelled);
27372
26197
  } else {
27373
26198
  const failure = executionFailure(error61);
27374
- const failed = new FailedInstallation(
27375
- job.requestId,
27376
- job.agentId,
27377
- failure.code,
27378
- failure.message
27379
- );
26199
+ const failed = new FailedInstallation(job.requestId, job.agentId, failure.code, failure.message);
27380
26200
  await this.#transition(job, failed);
27381
- this.#audit.record(
27382
- `agent_installation_failed_${failure.code}`,
27383
- job.requestId,
27384
- job.agentId
27385
- );
26201
+ this.#audit.record(`agent_installation_failed_${failure.code}`, job.requestId, job.agentId);
27386
26202
  job.completion.resolve(failed);
27387
26203
  }
27388
26204
  } finally {
@@ -27404,10 +26220,7 @@ function findSpecification(specifications, agentId) {
27404
26220
  return specification;
27405
26221
  }
27406
26222
  }
27407
- throw new InstallationManagerError(
27408
- "unknown_agent",
27409
- "The requested Agent is not supported"
27410
- );
26223
+ throw new InstallationManagerError("unknown_agent", "The requested Agent is not supported");
27411
26224
  }
27412
26225
  function resolveDefaultWorkspace2(path2) {
27413
26226
  try {
@@ -27449,11 +26262,9 @@ function translateExecutionError(error61) {
27449
26262
  cause: error61
27450
26263
  });
27451
26264
  }
27452
- return new InstallationManagerError(
27453
- "installation_failed",
27454
- "The local Agent integration installation failed",
27455
- { cause: error61 }
27456
- );
26265
+ return new InstallationManagerError("installation_failed", "The local Agent integration installation failed", {
26266
+ cause: error61
26267
+ });
27457
26268
  }
27458
26269
  function requiresAdapterReplacement(code) {
27459
26270
  return code === "adapter_not_found" || code === "adapter_probe_failed" || code === "adapter_probe_timeout" || code === "acp_incompatible";
@@ -27468,9 +26279,7 @@ var FixedInstallationExecutor = class {
27468
26279
  #specifications;
27469
26280
  constructor(options, specifications = supportedLocalAgentSpecifications(), adapterInstaller) {
27470
26281
  const defaultWorkspace = resolveDefaultWorkspace2(options.defaultWorkspace);
27471
- const stateDirectory = resolveIntegrationStateDirectory(
27472
- options.stateDirectory
27473
- );
26282
+ const stateDirectory = resolveIntegrationStateDirectory(options.stateDirectory);
27474
26283
  this.#defaultWorkspace = defaultWorkspace;
27475
26284
  this.#audit = options.audit;
27476
26285
  this.#catalog = options.catalog;
@@ -27495,25 +26304,18 @@ var FixedInstallationExecutor = class {
27495
26304
  specifications: this.#specifications
27496
26305
  });
27497
26306
  const previous = this.#catalog.read();
27498
- this.#catalog.transition(
27499
- initialInventory.readyAgents(),
27500
- initialInventory.installable
27501
- );
26307
+ this.#catalog.transition(initialInventory.readyAgents(), initialInventory.installable);
27502
26308
  try {
27503
26309
  await this.#publishCatalog(signal);
27504
26310
  } catch (error61) {
27505
26311
  this.#catalog.transition(previous.agents, previous.installableAgents);
27506
26312
  throw error61;
27507
26313
  }
27508
- const alreadyReady = initialInventory.available.find(
27509
- (candidate2) => candidate2.specification.id === agentId
27510
- );
26314
+ const alreadyReady = initialInventory.available.find((candidate2) => candidate2.specification.id === agentId);
27511
26315
  if (alreadyReady instanceof AvailableAgent) {
27512
26316
  return;
27513
26317
  }
27514
- const candidate = initialInventory.installable.find(
27515
- (agent2) => agent2.id === agentId
27516
- );
26318
+ const candidate = initialInventory.installable.find((agent2) => agent2.id === agentId);
27517
26319
  if (candidate instanceof MissingAgentDefinition) {
27518
26320
  throw new InstallationManagerError(
27519
26321
  "agent_not_installed",
@@ -27526,10 +26328,7 @@ var FixedInstallationExecutor = class {
27526
26328
  "The local Agent discovery result is unavailable"
27527
26329
  );
27528
26330
  }
27529
- const verifiedAgent = await findVerifiedAgentExecutable(
27530
- specification,
27531
- discoveryOptions
27532
- );
26331
+ const verifiedAgent = await findVerifiedAgentExecutable(specification, discoveryOptions);
27533
26332
  if (verifiedAgent === null) {
27534
26333
  throw new InstallationManagerError(
27535
26334
  "agent_not_installed",
@@ -27570,38 +26369,23 @@ var FixedInstallationExecutor = class {
27570
26369
  signal,
27571
26370
  specifications: this.#specifications
27572
26371
  });
27573
- const verified = inventory.available.find(
27574
- (candidate2) => candidate2.specification.id === agentId
27575
- );
26372
+ const verified = inventory.available.find((candidate2) => candidate2.specification.id === agentId);
27576
26373
  if (verified instanceof AvailableAgent) {
27577
- this.#audit.record(
27578
- "agent_installation_acp_verified",
27579
- requestId,
27580
- agentId,
27581
- {
27582
- adapterVersion: verified.agent.adapterVersion,
27583
- agentVersion: verified.agent.agentVersion
27584
- }
27585
- );
26374
+ this.#audit.record("agent_installation_acp_verified", requestId, agentId, {
26375
+ adapterVersion: verified.agent.adapterVersion,
26376
+ agentVersion: verified.agent.agentVersion
26377
+ });
27586
26378
  const previousCatalog = this.#catalog.read();
27587
- this.#catalog.transition(
27588
- inventory.readyAgents(),
27589
- inventory.installable
27590
- );
26379
+ this.#catalog.transition(inventory.readyAgents(), inventory.installable);
27591
26380
  try {
27592
26381
  await this.#publishCatalog(signal);
27593
26382
  } catch (error61) {
27594
- this.#catalog.transition(
27595
- previousCatalog.agents,
27596
- previousCatalog.installableAgents
27597
- );
26383
+ this.#catalog.transition(previousCatalog.agents, previousCatalog.installableAgents);
27598
26384
  throw error61;
27599
26385
  }
27600
26386
  return;
27601
26387
  }
27602
- const unavailable = inventory.unavailable.find(
27603
- (candidate2) => candidate2.specification.id === agentId
27604
- );
26388
+ const unavailable = inventory.unavailable.find((candidate2) => candidate2.specification.id === agentId);
27605
26389
  if (unavailable === void 0) {
27606
26390
  throw new InstallationManagerError(
27607
26391
  "agent_verification_failed",
@@ -27617,10 +26401,7 @@ var FixedInstallationExecutor = class {
27617
26401
  });
27618
26402
  continue;
27619
26403
  }
27620
- throw new InstallationManagerError(
27621
- unavailable.code,
27622
- unavailable.message
27623
- );
26404
+ throw new InstallationManagerError(unavailable.code, unavailable.message);
27624
26405
  }
27625
26406
  } catch (error61) {
27626
26407
  if (signal.aborted) {
@@ -27634,14 +26415,7 @@ var FixedInstallationExecutor = class {
27634
26415
  // src/authorization/workspace-directory.ts
27635
26416
  import { readdir, realpath as realpath7, stat as stat6 } from "node:fs/promises";
27636
26417
  import { homedir as homedir2 } from "node:os";
27637
- import {
27638
- basename as basename2,
27639
- dirname as dirname5,
27640
- isAbsolute as isAbsolute7,
27641
- join as join15,
27642
- normalize as normalize2,
27643
- relative as relative4
27644
- } from "node:path";
26418
+ import { basename as basename2, dirname as dirname5, isAbsolute as isAbsolute7, join as join15, normalize as normalize2, relative as relative4 } from "node:path";
27645
26419
  var WorkspaceDirectoryListing = class {
27646
26420
  directoryId;
27647
26421
  directoryLabel;
@@ -27657,19 +26431,19 @@ var WorkspaceDirectoryListing = class {
27657
26431
  function encodePath(path2) {
27658
26432
  const encoded = Buffer.from(path2, "utf8").toString("base64url");
27659
26433
  if (encoded.length === 0 || encoded.length > 2e3) {
27660
- throw new LocalAuthorizationError(
27661
- "The local directory path is too long to select"
27662
- );
26434
+ throw new LocalAuthorizationError("The local directory path is too long to select");
27663
26435
  }
27664
26436
  return `path-${encoded}`;
27665
26437
  }
27666
26438
  function decodePath(value, prefix) {
27667
26439
  const encoded = value.slice(prefix.length);
27668
- if (encoded.length === 0 || encoded.length > 2e3 || !/^[a-zA-Z0-9_-]+$/.test(encoded))
26440
+ if (encoded.length === 0 || encoded.length > 2e3 || !/^[a-zA-Z0-9_-]+$/.test(encoded)) {
27669
26441
  throw new LocalAuthorizationError("The directory identifier is invalid");
26442
+ }
27670
26443
  const decoded = Buffer.from(encoded, "base64url").toString("utf8");
27671
- if (Buffer.from(decoded, "utf8").toString("base64url") !== encoded || decoded.includes("\0") || normalize2(decoded) !== decoded)
26444
+ if (Buffer.from(decoded, "utf8").toString("base64url") !== encoded || decoded.includes("\0") || normalize2(decoded) !== decoded) {
27672
26445
  throw new LocalAuthorizationError("The directory identifier is invalid");
26446
+ }
27673
26447
  return decoded;
27674
26448
  }
27675
26449
  var WorkspaceDirectoryService = class {
@@ -27680,41 +26454,47 @@ var WorkspaceDirectoryService = class {
27680
26454
  this.#defaultWorkspace = defaultWorkspace;
27681
26455
  }
27682
26456
  authorizeMachine = (bindingId) => {
27683
- if (bindingId !== this.#bindingId)
27684
- throw new LocalAuthorizationError(
27685
- "The runtime binding is not authorized"
27686
- );
26457
+ if (bindingId !== this.#bindingId) {
26458
+ throw new LocalAuthorizationError("The runtime binding is not authorized");
26459
+ }
27687
26460
  };
27688
26461
  requestedPath = (id) => {
27689
- if (id === "default") return this.#defaultWorkspace;
27690
- if (id === "home") return homedir2();
26462
+ if (id === "default") {
26463
+ return this.#defaultWorkspace;
26464
+ }
26465
+ if (id === "home") {
26466
+ return homedir2();
26467
+ }
27691
26468
  if (id.startsWith("path-")) {
27692
26469
  const path2 = decodePath(id, "path-");
27693
- if (isAbsolute7(path2)) return path2;
26470
+ if (isAbsolute7(path2)) {
26471
+ return path2;
26472
+ }
27694
26473
  }
27695
26474
  throw new LocalAuthorizationError("The directory identifier is invalid");
27696
26475
  };
27697
26476
  resolvePath = async (requested, signal) => {
27698
26477
  signal.throwIfAborted();
27699
- if (!isAbsolute7(requested) || requested.includes("\0") || normalize2(requested) !== requested)
26478
+ if (!isAbsolute7(requested) || requested.includes("\0") || normalize2(requested) !== requested) {
27700
26479
  throw new LocalAuthorizationError("The local directory path is invalid");
26480
+ }
27701
26481
  try {
27702
26482
  const target = await realpath7(requested);
27703
26483
  signal.throwIfAborted();
27704
26484
  const metadata = await stat6(target);
27705
26485
  signal.throwIfAborted();
27706
- if (!isAbsolute7(target) || normalize2(target) !== target || !metadata.isDirectory())
27707
- throw new LocalAuthorizationError(
27708
- "The selected location is not a directory"
27709
- );
26486
+ if (!isAbsolute7(target) || normalize2(target) !== target || !metadata.isDirectory()) {
26487
+ throw new LocalAuthorizationError("The selected location is not a directory");
26488
+ }
27710
26489
  return target;
27711
26490
  } catch (cause) {
27712
26491
  signal.throwIfAborted();
27713
- if (cause instanceof LocalAuthorizationError) throw cause;
27714
- throw new LocalAuthorizationError(
27715
- "This directory is missing or unavailable to your user account",
27716
- { cause }
27717
- );
26492
+ if (cause instanceof LocalAuthorizationError) {
26493
+ throw cause;
26494
+ }
26495
+ throw new LocalAuthorizationError("This directory is missing or unavailable to your user account", {
26496
+ cause
26497
+ });
27718
26498
  }
27719
26499
  };
27720
26500
  label = (path2) => {
@@ -27742,7 +26522,9 @@ var WorkspaceDirectoryService = class {
27742
26522
  signal.throwIfAborted();
27743
26523
  const entries = [];
27744
26524
  for (const child of children) {
27745
- if (entries.length === 500) break;
26525
+ if (entries.length === 500) {
26526
+ break;
26527
+ }
27746
26528
  if (child.isFile() || child.isBlockDevice() || child.isCharacterDevice() || child.isFIFO() || child.isSocket()) {
27747
26529
  continue;
27748
26530
  }
@@ -27751,7 +26533,9 @@ var WorkspaceDirectoryService = class {
27751
26533
  entries.push({ directoryId: encodePath(path2), name: child.name });
27752
26534
  } catch (cause) {
27753
26535
  signal.throwIfAborted();
27754
- if (!(cause instanceof LocalAuthorizationError)) throw cause;
26536
+ if (!(cause instanceof LocalAuthorizationError)) {
26537
+ throw cause;
26538
+ }
27755
26539
  }
27756
26540
  }
27757
26541
  entries.sort((a, b) => a.name.localeCompare(b.name));
@@ -27764,16 +26548,17 @@ var WorkspaceDirectoryService = class {
27764
26548
  );
27765
26549
  } catch (cause) {
27766
26550
  signal.throwIfAborted();
27767
- if (cause instanceof LocalAuthorizationError) throw cause;
27768
- throw new LocalAuthorizationError(
27769
- "This directory cannot be browsed by your user account",
27770
- { cause }
27771
- );
26551
+ if (cause instanceof LocalAuthorizationError) {
26552
+ throw cause;
26553
+ }
26554
+ throw new LocalAuthorizationError("This directory cannot be browsed by your user account", { cause });
27772
26555
  }
27773
26556
  };
27774
26557
  resolveMany = async (bindingId, ids, signal) => {
27775
26558
  const paths = /* @__PURE__ */ new Set();
27776
- for (const id of ids) paths.add(await this.resolve(bindingId, id, signal));
26559
+ for (const id of ids) {
26560
+ paths.add(await this.resolve(bindingId, id, signal));
26561
+ }
27777
26562
  return [...paths];
27778
26563
  };
27779
26564
  };
@@ -27823,9 +26608,12 @@ function decodeHistory(thread, value) {
27823
26608
  const parsed = parseNativeHistoryText(
27824
26609
  content.map((block) => {
27825
26610
  const { type: type2 } = itemTypeSchema.parse(block);
27826
- if (type2 === "text") return textSchema.parse(block).text;
27827
- if (type2 === "image")
26611
+ if (type2 === "text") {
26612
+ return textSchema.parse(block).text;
26613
+ }
26614
+ if (type2 === "image") {
27828
26615
  return `[@image](${imageSchema.parse(block).url})`;
26616
+ }
27829
26617
  return "[Attachment]";
27830
26618
  }).join("")
27831
26619
  );
@@ -27836,28 +26624,26 @@ function decodeHistory(thread, value) {
27836
26624
  };
27837
26625
  } else if (type === "agentMessage") {
27838
26626
  const agent = agentMessageSchema.parse(item);
27839
- if (agent.phase === "commentary") continue;
26627
+ if (agent.phase === "commentary") {
26628
+ continue;
26629
+ }
27840
26630
  message = { role: "assistant", text: agent.text };
27841
26631
  } else {
27842
26632
  continue;
27843
26633
  }
27844
26634
  const text = message.text.slice(-SESSION_HISTORY_CHARACTER_LIMIT);
27845
- if (text.length === 0 && (message.images?.length ?? 0) === 0) continue;
26635
+ if (text.length === 0 && (message.images?.length ?? 0) === 0) {
26636
+ continue;
26637
+ }
27846
26638
  truncated ||= text.length < message.text.length;
27847
26639
  messages.push({ ...message, text });
27848
26640
  characters += text.length;
27849
- imageCharacters += (message.images ?? []).reduce(
27850
- (size, image) => size + image.data.length,
27851
- 0
27852
- );
26641
+ imageCharacters += (message.images ?? []).reduce((size, image) => size + image.data.length, 0);
27853
26642
  while (messages.length > SESSION_HISTORY_PREVIEW_MESSAGE_LIMIT || characters > SESSION_HISTORY_CHARACTER_LIMIT || imageCharacters > SESSION_HISTORY_IMAGE_CHARACTER_LIMIT) {
27854
26643
  const removed = messages.shift();
27855
26644
  if (removed !== void 0) {
27856
26645
  characters -= removed.text.length;
27857
- imageCharacters -= (removed.images ?? []).reduce(
27858
- (size, image) => size + image.data.length,
27859
- 0
27860
- );
26646
+ imageCharacters -= (removed.images ?? []).reduce((size, image) => size + image.data.length, 0);
27861
26647
  }
27862
26648
  truncated = true;
27863
26649
  }
@@ -27878,12 +26664,13 @@ function decodeHistory(thread, value) {
27878
26664
  async function readCodexHistory(agent, cwd, nativeSessionId, signal) {
27879
26665
  signal.throwIfAborted();
27880
26666
  nativeSessionIdSchema.parse(nativeSessionId);
27881
- if (agent.id !== "codex" || !await revalidateExecutable(agent.agentIdentity))
26667
+ if (agent.id !== "codex" || !await revalidateExecutable(agent.agentIdentity)) {
27882
26668
  throw new AcpExecutionError(
27883
26669
  "The local Codex executable changed. Restart Mobius to discover it again.",
27884
26670
  {},
27885
26671
  "agent_executable_changed"
27886
26672
  );
26673
+ }
27887
26674
  signal.throwIfAborted();
27888
26675
  const child = spawn4(agent.agentIdentity.realPath, ["app-server"], {
27889
26676
  cwd,
@@ -27910,28 +26697,34 @@ async function readCodexHistory(agent, cwd, nativeSessionId, signal) {
27910
26697
  const onData = (chunk) => {
27911
26698
  try {
27912
26699
  receivedBytes += Buffer.byteLength(chunk);
27913
- if (receivedBytes > 32 * 1024 * 1024)
26700
+ if (receivedBytes > 32 * 1024 * 1024) {
27914
26701
  throw new AcpExecutionError(
27915
26702
  "This saved conversation is too large to preview.",
27916
26703
  {},
27917
26704
  "native_history_too_large"
27918
26705
  );
26706
+ }
27919
26707
  pending += chunk;
27920
26708
  let newline = pending.indexOf("\n");
27921
26709
  while (newline >= 0) {
27922
26710
  const line = pending.slice(0, newline);
27923
26711
  pending = pending.slice(newline + 1);
27924
26712
  newline = pending.indexOf("\n");
27925
- if (line.trim().length === 0) continue;
26713
+ if (line.trim().length === 0) {
26714
+ continue;
26715
+ }
27926
26716
  const value = JSON.parse(line);
27927
26717
  const message = responseSchema.parse(value);
27928
- if (!("id" in message)) continue;
27929
- if (message.id !== state.requestId)
26718
+ if (!("id" in message)) {
26719
+ continue;
26720
+ }
26721
+ if (message.id !== state.requestId) {
27930
26722
  throw new AcpExecutionError(
27931
26723
  "Codex returned an invalid history response.",
27932
26724
  {},
27933
26725
  "invalid_native_session_response"
27934
26726
  );
26727
+ }
27935
26728
  if ("error" in message) {
27936
26729
  fail(
27937
26730
  new AcpExecutionError(
@@ -27989,13 +26782,7 @@ async function readCodexHistory(agent, cwd, nativeSessionId, signal) {
27989
26782
  )
27990
26783
  );
27991
26784
  const timeout = setTimeout(
27992
- () => fail(
27993
- new AcpExecutionError(
27994
- "Reading saved Codex history timed out.",
27995
- {},
27996
- "native_history_timeout"
27997
- )
27998
- ),
26785
+ () => fail(new AcpExecutionError("Reading saved Codex history timed out.", {}, "native_history_timeout")),
27999
26786
  15e3
28000
26787
  );
28001
26788
  child.stdout.setEncoding("utf8");
@@ -28005,19 +26792,23 @@ async function readCodexHistory(agent, cwd, nativeSessionId, signal) {
28005
26792
  child.on("exit", onExit);
28006
26793
  signal.addEventListener("abort", abort, { once: true });
28007
26794
  try {
28008
- if (signal.aborted) abort();
28009
- else
26795
+ if (signal.aborted) {
26796
+ abort();
26797
+ } else {
28010
26798
  send2({
28011
26799
  id: 1,
28012
26800
  method: "initialize",
28013
26801
  params: { clientInfo: { name: "mobius_history", version: "1.0.0" } }
28014
26802
  });
26803
+ }
28015
26804
  return await response.promise;
28016
26805
  } finally {
28017
26806
  clearTimeout(timeout);
28018
26807
  signal.removeEventListener("abort", abort);
28019
26808
  child.stdout.removeListener("data", onData);
28020
- if (child.pid !== void 0) await stopProcessTree(child);
26809
+ if (child.pid !== void 0) {
26810
+ await stopProcessTree(child);
26811
+ }
28021
26812
  child.stdin.removeListener("error", fail);
28022
26813
  child.removeListener("error", fail);
28023
26814
  child.removeListener("exit", onExit);
@@ -28040,11 +26831,7 @@ var NativeSessionService = class {
28040
26831
  }
28041
26832
  execute = async (command, signal) => {
28042
26833
  signal.throwIfAborted();
28043
- const cwd = await this.#directories.resolve(
28044
- this.#config.bindingId,
28045
- command.directoryId,
28046
- signal
28047
- );
26834
+ const cwd = await this.#directories.resolve(this.#config.bindingId, command.directoryId, signal);
28048
26835
  const additionalDirectories = await this.#directories.resolveMany(
28049
26836
  this.#config.bindingId,
28050
26837
  command.additionalDirectoryIds,
@@ -28059,17 +26846,14 @@ var NativeSessionService = class {
28059
26846
  signal
28060
26847
  };
28061
26848
  const prepared = await this.#sessions.prepareNativeSessionBrowser(options);
28062
- if (!prepared.capabilities.listSessions)
26849
+ if (!prepared.capabilities.listSessions) {
28063
26850
  throw new AcpExecutionError(
28064
26851
  "This Agent does not support native session listing",
28065
26852
  {},
28066
26853
  "native_session_unsupported"
28067
26854
  );
28068
- const entryScope = JSON.stringify([
28069
- command.agentId,
28070
- command.bindingId,
28071
- command.sessionId
28072
- ]);
26855
+ }
26856
+ const entryScope = JSON.stringify([command.agentId, command.bindingId, command.sessionId]);
28073
26857
  const cursorScope = JSON.stringify([entryScope, cwd]);
28074
26858
  const envelope2 = {
28075
26859
  kind: "native.session.result",
@@ -28080,21 +26864,26 @@ var NativeSessionService = class {
28080
26864
  let cursor = null;
28081
26865
  if (command.cursor !== null) {
28082
26866
  const known = this.#cursors.get(command.cursor);
28083
- if (known?.scope !== cursorScope)
26867
+ if (known?.scope !== cursorScope) {
28084
26868
  throw new AcpExecutionError(
28085
26869
  "Refresh the native session list before continuing",
28086
26870
  {},
28087
26871
  "native_session_cursor_expired"
28088
26872
  );
26873
+ }
28089
26874
  cursor = known.cursor;
28090
26875
  }
28091
26876
  const page = await this.#sessions.listNativeSessions(options, cursor);
28092
26877
  const entries = [];
28093
26878
  for (const info of page.sessions) {
28094
26879
  const authorized = await this.authorizeEntry(command, options, info);
28095
- if (authorized === null) continue;
26880
+ if (authorized === null) {
26881
+ continue;
26882
+ }
28096
26883
  const entryId = randomUUID2();
28097
- if (this.#entries.size >= 5e3) this.#entries.clear();
26884
+ if (this.#entries.size >= 5e3) {
26885
+ this.#entries.clear();
26886
+ }
28098
26887
  this.#entries.set(entryId, {
28099
26888
  scope: entryScope,
28100
26889
  nativeSessionId: info.sessionId,
@@ -28112,14 +26901,17 @@ var NativeSessionService = class {
28112
26901
  }
28113
26902
  let nextCursor = null;
28114
26903
  if (page.nextCursor != null) {
28115
- if (page.nextCursor === cursor)
26904
+ if (page.nextCursor === cursor) {
28116
26905
  throw new AcpExecutionError(
28117
26906
  "The Agent returned a repeated session cursor",
28118
26907
  {},
28119
26908
  "invalid_native_session_response"
28120
26909
  );
26910
+ }
28121
26911
  nextCursor = randomUUID2();
28122
- if (this.#cursors.size >= 500) this.#cursors.clear();
26912
+ if (this.#cursors.size >= 500) {
26913
+ this.#cursors.clear();
26914
+ }
28123
26915
  this.#cursors.set(nextCursor, {
28124
26916
  scope: cursorScope,
28125
26917
  cursor: page.nextCursor
@@ -28135,32 +26927,32 @@ var NativeSessionService = class {
28135
26927
  };
28136
26928
  }
28137
26929
  const selected = this.#entries.get(command.entryId);
28138
- if (selected?.scope !== entryScope)
26930
+ if (selected?.scope !== entryScope) {
28139
26931
  throw new AcpExecutionError(
28140
26932
  "Select a session from a fresh native session list",
28141
26933
  {},
28142
26934
  "native_session_not_found"
28143
26935
  );
28144
- if (selected.cwd !== cwd)
26936
+ }
26937
+ if (selected.cwd !== cwd) {
28145
26938
  throw new AcpExecutionError(
28146
26939
  "The selected session belongs to a different workspace. Refresh the list before continuing.",
28147
26940
  {},
28148
26941
  "native_session_target_changed"
28149
26942
  );
26943
+ }
28150
26944
  const target = await this.resolveTarget(command, options, selected);
28151
26945
  if (command.action === "delete") {
28152
- if (!prepared.capabilities.deleteSession)
26946
+ if (!prepared.capabilities.deleteSession) {
28153
26947
  throw new AcpExecutionError(
28154
26948
  "This Agent does not support native session deletion",
28155
26949
  {},
28156
26950
  "native_session_unsupported"
28157
26951
  );
26952
+ }
28158
26953
  signal.throwIfAborted();
28159
26954
  this.record(command, "native_session_delete_authorized");
28160
- const deletedSessionIds = await this.#sessions.deleteNativeSession(
28161
- options,
28162
- target.info.sessionId
28163
- );
26955
+ const deletedSessionIds = await this.#sessions.deleteNativeSession(options, target.info.sessionId);
28164
26956
  this.record(command, "native_session_deleted");
28165
26957
  return {
28166
26958
  ...envelope2,
@@ -28169,24 +26961,23 @@ var NativeSessionService = class {
28169
26961
  deletedSessionIds
28170
26962
  };
28171
26963
  }
28172
- if (command.action === "import" && !prepared.capabilities.loadSession && !prepared.capabilities.resumeSession)
28173
- throw new AcpExecutionError(
28174
- "This Agent cannot import native sessions",
28175
- {},
28176
- "native_session_unsupported"
28177
- );
28178
- if (command.action === "fork" && !prepared.capabilities.unstableForkSession)
26964
+ if (command.action === "import" && !prepared.capabilities.loadSession && !prepared.capabilities.resumeSession) {
26965
+ throw new AcpExecutionError("This Agent cannot import native sessions", {}, "native_session_unsupported");
26966
+ }
26967
+ if (command.action === "fork" && !prepared.capabilities.unstableForkSession) {
28179
26968
  throw new AcpExecutionError(
28180
26969
  "This Agent does not support session forking",
28181
26970
  {},
28182
26971
  "native_session_unsupported"
28183
26972
  );
28184
- if (target.additionalDirectories.length > 0 && !prepared.capabilities.additionalDirectories)
26973
+ }
26974
+ if (target.additionalDirectories.length > 0 && !prepared.capabilities.additionalDirectories) {
28185
26975
  throw new AcpExecutionError(
28186
26976
  "This Agent cannot restore additional working directories",
28187
26977
  {},
28188
26978
  "native_session_unsupported"
28189
26979
  );
26980
+ }
28190
26981
  const opening = this.#sessions.openNativeSession(
28191
26982
  {
28192
26983
  ...options,
@@ -28198,30 +26989,23 @@ var NativeSessionService = class {
28198
26989
  );
28199
26990
  const opened = await opening.catch(async (cause) => {
28200
26991
  signal.throwIfAborted();
28201
- if (command.action !== "import" || options.agent.id !== "codex" || !(cause instanceof AcpExecutionError) || cause.code !== "acp_execution_failed")
26992
+ if (command.action !== "import" || options.agent.id !== "codex" || !(cause instanceof AcpExecutionError) || cause.code !== "acp_execution_failed") {
28202
26993
  throw cause;
28203
- const snapshot = await readCodexHistory(
28204
- options.agent,
28205
- target.cwd,
28206
- target.info.sessionId,
28207
- signal
28208
- );
28209
- const resolved = await this.#directories.identify(
28210
- command.bindingId,
28211
- snapshot.cwd,
28212
- signal
28213
- );
28214
- if (snapshot.nativeSessionId !== target.info.sessionId || resolved.path !== target.cwd)
26994
+ }
26995
+ const snapshot = await readCodexHistory(options.agent, target.cwd, target.info.sessionId, signal);
26996
+ const resolved = await this.#directories.identify(command.bindingId, snapshot.cwd, signal);
26997
+ if (snapshot.nativeSessionId !== target.info.sessionId || resolved.path !== target.cwd) {
28215
26998
  throw new AcpExecutionError(
28216
26999
  "Codex returned history for a different session or workspace.",
28217
27000
  { cause },
28218
27001
  "invalid_native_session_response"
28219
27002
  );
27003
+ }
28220
27004
  signal.throwIfAborted();
28221
27005
  this.record(command, "native_session_previewed");
28222
27006
  return { kind: "preview", history: snapshot.history };
28223
27007
  });
28224
- if ("kind" in opened)
27008
+ if ("kind" in opened) {
28225
27009
  return {
28226
27010
  ...envelope2,
28227
27011
  action: "preview",
@@ -28231,6 +27015,7 @@ var NativeSessionService = class {
28231
27015
  title: target.info.title ?? "Untitled session",
28232
27016
  history: opened.history
28233
27017
  };
27018
+ }
28234
27019
  signal.throwIfAborted();
28235
27020
  const ready = {
28236
27021
  additionalDirectories: target.additionalEntries,
@@ -28247,10 +27032,7 @@ var NativeSessionService = class {
28247
27032
  restored: true,
28248
27033
  sessionId: opened.sessionId
28249
27034
  };
28250
- this.record(
28251
- command,
28252
- command.action === "fork" ? "native_session_forked" : "native_session_imported"
28253
- );
27035
+ this.record(command, command.action === "fork" ? "native_session_forked" : "native_session_imported");
28254
27036
  return {
28255
27037
  ...envelope2,
28256
27038
  action: command.action,
@@ -28262,24 +27044,15 @@ var NativeSessionService = class {
28262
27044
  };
28263
27045
  authorizeEntry = async (command, options, info) => {
28264
27046
  try {
28265
- const primary = await this.#directories.identify(
28266
- command.bindingId,
28267
- info.cwd,
28268
- options.signal
28269
- );
27047
+ const primary = await this.#directories.identify(command.bindingId, info.cwd, options.signal);
28270
27048
  const additionalDirectories = [];
28271
27049
  const additionalEntries = [];
28272
27050
  const paths = /* @__PURE__ */ new Set([primary.path]);
28273
27051
  for (const path2 of info.additionalDirectories) {
28274
- const directory = await this.#directories.identify(
28275
- command.bindingId,
28276
- path2,
28277
- options.signal
28278
- );
28279
- if (paths.has(directory.path))
28280
- throw new LocalAuthorizationError(
28281
- "Native session roots must be distinct"
28282
- );
27052
+ const directory = await this.#directories.identify(command.bindingId, path2, options.signal);
27053
+ if (paths.has(directory.path)) {
27054
+ throw new LocalAuthorizationError("Native session roots must be distinct");
27055
+ }
28283
27056
  paths.add(directory.path);
28284
27057
  additionalDirectories.push(directory.path);
28285
27058
  additionalEntries.push({
@@ -28297,7 +27070,9 @@ var NativeSessionService = class {
28297
27070
  };
28298
27071
  } catch (error61) {
28299
27072
  options.signal.throwIfAborted();
28300
- if (error61 instanceof LocalAuthorizationError) return null;
27073
+ if (error61 instanceof LocalAuthorizationError) {
27074
+ return null;
27075
+ }
28301
27076
  throw error61;
28302
27077
  }
28303
27078
  };
@@ -28306,33 +27081,32 @@ var NativeSessionService = class {
28306
27081
  const visited = /* @__PURE__ */ new Set();
28307
27082
  for (let index = 0; index < 100; index += 1) {
28308
27083
  const page = await this.#sessions.listNativeSessions(options, cursor);
28309
- const info = page.sessions.find(
28310
- (entry) => entry.sessionId === selected.nativeSessionId
28311
- );
27084
+ const info = page.sessions.find((entry) => entry.sessionId === selected.nativeSessionId);
28312
27085
  if (info !== void 0) {
28313
27086
  const target = await this.authorizeEntry(command, options, info);
28314
- if (target === null)
28315
- throw new LocalAuthorizationError(
28316
- "The selected native session is not authorized"
28317
- );
28318
- if (target.cwd !== selected.cwd || target.additionalDirectories.length !== selected.additionalDirectories.length || target.additionalDirectories.some(
28319
- (path2, index2) => path2 !== selected.additionalDirectories[index2]
28320
- ))
27087
+ if (target === null) {
27088
+ throw new LocalAuthorizationError("The selected native session is not authorized");
27089
+ }
27090
+ if (target.cwd !== selected.cwd || target.additionalDirectories.length !== selected.additionalDirectories.length || target.additionalDirectories.some((path2, index2) => path2 !== selected.additionalDirectories[index2])) {
28321
27091
  throw new AcpExecutionError(
28322
27092
  "This session's directory changed. Refresh the list before continuing.",
28323
27093
  {},
28324
27094
  "native_session_target_changed"
28325
27095
  );
27096
+ }
28326
27097
  return target;
28327
27098
  }
28328
27099
  cursor = page.nextCursor ?? null;
28329
- if (cursor === null) break;
28330
- if (visited.has(cursor))
27100
+ if (cursor === null) {
27101
+ break;
27102
+ }
27103
+ if (visited.has(cursor)) {
28331
27104
  throw new AcpExecutionError(
28332
27105
  "The Agent returned a repeated session cursor",
28333
27106
  {},
28334
27107
  "invalid_native_session_response"
28335
27108
  );
27109
+ }
28336
27110
  visited.add(cursor);
28337
27111
  }
28338
27112
  throw new AcpExecutionError(
@@ -28351,6 +27125,212 @@ var NativeSessionService = class {
28351
27125
  };
28352
27126
  };
28353
27127
 
27128
+ // src/prompt-artifact-resolver.ts
27129
+ import { createHash as createHash2 } from "node:crypto";
27130
+ import { fetch as fetch4 } from "undici";
27131
+ var ARTIFACT_SCHEME = "mobius-artifact:";
27132
+ var ARTIFACT_DOWNLOAD_TIMEOUT_MILLISECONDS = 2e4;
27133
+ var MAX_AGENT_IMAGE_BASE64_LENGTH = 4e6;
27134
+ var MAX_AGENT_RESOURCE_BYTE_LENGTH = 1e6;
27135
+ var IDENTIFIER_PATTERN5 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
27136
+ var PromptArtifactError = class extends Error {
27137
+ code;
27138
+ constructor(code, message, options = {}) {
27139
+ super(message, options);
27140
+ this.code = code;
27141
+ this.name = "PromptArtifactError";
27142
+ }
27143
+ };
27144
+ var ResolvedPromptArtifacts = class {
27145
+ images;
27146
+ resources;
27147
+ constructor(images, resources) {
27148
+ this.images = images;
27149
+ this.resources = resources;
27150
+ }
27151
+ };
27152
+ var PromptArtifactReference = class {
27153
+ artifactId;
27154
+ byteLength;
27155
+ resource;
27156
+ sha256;
27157
+ constructor(artifactId, byteLength, sha256, resource) {
27158
+ this.artifactId = artifactId;
27159
+ this.byteLength = byteLength;
27160
+ this.resource = resource;
27161
+ this.sha256 = sha256;
27162
+ }
27163
+ };
27164
+ function parseReference(resource) {
27165
+ let url2;
27166
+ try {
27167
+ url2 = new URL(resource.uri);
27168
+ } catch (cause) {
27169
+ throw new PromptArtifactError("artifact_reference_invalid", "The prompt artifact reference is invalid", {
27170
+ cause
27171
+ });
27172
+ }
27173
+ const keys = [...url2.searchParams.keys()].sort();
27174
+ const artifactId = url2.pathname;
27175
+ const encodedByteLength2 = url2.searchParams.get("byteLength") ?? "";
27176
+ const sha256 = url2.searchParams.get("sha256") ?? "";
27177
+ const byteLength = Number(encodedByteLength2);
27178
+ if (url2.protocol !== ARTIFACT_SCHEME || url2.hash.length > 0 || resource.type !== "link" || resource.text.length > 0 || !IDENTIFIER_PATTERN5.test(artifactId) || keys.length !== 2 || keys[0] !== "byteLength" || keys[1] !== "sha256" || !/^[1-9][0-9]*$/.test(encodedByteLength2) || !Number.isSafeInteger(byteLength) || !/^[a-f0-9]{64}$/.test(sha256)) {
27179
+ throw new PromptArtifactError("artifact_reference_invalid", "The prompt artifact reference is invalid");
27180
+ }
27181
+ return new PromptArtifactReference(artifactId, byteLength, sha256, resource);
27182
+ }
27183
+ function downloadUrl(config2, command, reference) {
27184
+ const url2 = new URL(config2.relayUrl);
27185
+ url2.protocol = url2.protocol === "wss:" ? "https:" : "http:";
27186
+ if (!url2.pathname.endsWith("/daemon")) {
27187
+ throw new PromptArtifactError("artifact_endpoint_invalid", "The Relay artifact endpoint is invalid");
27188
+ }
27189
+ url2.pathname = `${url2.pathname.slice(0, -"/daemon".length)}/sessions/${encodeURIComponent(command.sessionId)}/commands/${encodeURIComponent(command.commandId)}/artifacts/${encodeURIComponent(reference.artifactId)}/content`;
27190
+ url2.searchParams.delete("liveness");
27191
+ return url2;
27192
+ }
27193
+ async function responseBytes(response, expectedByteLength, signal) {
27194
+ const declaredLength = response.headers.get("content-length") ?? "";
27195
+ if (!/^(0|[1-9][0-9]*)$/.test(declaredLength) || Number(declaredLength) !== expectedByteLength || response.body === null) {
27196
+ throw new PromptArtifactError("artifact_integrity_failed", "The prompt artifact failed integrity validation");
27197
+ }
27198
+ const reader = response.body.getReader();
27199
+ const chunks = [];
27200
+ let byteLength = 0;
27201
+ try {
27202
+ while (true) {
27203
+ signal.throwIfAborted();
27204
+ const chunk = await reader.read();
27205
+ signal.throwIfAborted();
27206
+ if (chunk.done) {
27207
+ break;
27208
+ }
27209
+ byteLength += chunk.value.byteLength;
27210
+ if (byteLength > expectedByteLength) {
27211
+ await reader.cancel("Artifact response exceeded its authorization");
27212
+ throw new PromptArtifactError(
27213
+ "artifact_integrity_failed",
27214
+ "The prompt artifact failed integrity validation"
27215
+ );
27216
+ }
27217
+ chunks.push(chunk.value);
27218
+ }
27219
+ } finally {
27220
+ reader.releaseLock();
27221
+ }
27222
+ if (byteLength !== expectedByteLength) {
27223
+ throw new PromptArtifactError("artifact_integrity_failed", "The prompt artifact failed integrity validation");
27224
+ }
27225
+ const bytes = new Uint8Array(byteLength);
27226
+ let offset = 0;
27227
+ for (const chunk of chunks) {
27228
+ bytes.set(chunk, offset);
27229
+ offset += chunk.byteLength;
27230
+ }
27231
+ return bytes;
27232
+ }
27233
+ async function download(config2, command, reference, signal) {
27234
+ signal.throwIfAborted();
27235
+ const timeoutSignal = AbortSignal.timeout(ARTIFACT_DOWNLOAD_TIMEOUT_MILLISECONDS);
27236
+ const requestSignal = AbortSignal.any([signal, timeoutSignal]);
27237
+ let response;
27238
+ try {
27239
+ response = await fetch4(downloadUrl(config2, command, reference), {
27240
+ dispatcher: environmentProxyDispatcher,
27241
+ headers: { accept: reference.resource.mimeType },
27242
+ signal: requestSignal
27243
+ });
27244
+ if (!response.ok) {
27245
+ await response.body?.cancel();
27246
+ throw new PromptArtifactError(
27247
+ "artifact_download_rejected",
27248
+ "The Relay rejected the prompt artifact download"
27249
+ );
27250
+ }
27251
+ if (response.headers.get("content-type") !== reference.resource.mimeType || response.headers.get("x-mobius-artifact-id") !== reference.artifactId || response.headers.get("x-mobius-sha256") !== reference.sha256) {
27252
+ await response.body?.cancel();
27253
+ throw new PromptArtifactError(
27254
+ "artifact_integrity_failed",
27255
+ "The prompt artifact failed integrity validation"
27256
+ );
27257
+ }
27258
+ const bytes = await responseBytes(response, reference.byteLength, requestSignal);
27259
+ if (createHash2("sha256").update(bytes).digest("hex") !== reference.sha256) {
27260
+ throw new PromptArtifactError(
27261
+ "artifact_integrity_failed",
27262
+ "The prompt artifact failed integrity validation"
27263
+ );
27264
+ }
27265
+ return bytes;
27266
+ } catch (error61) {
27267
+ signal.throwIfAborted();
27268
+ if (error61 instanceof PromptArtifactError) {
27269
+ throw error61;
27270
+ }
27271
+ throw new PromptArtifactError(
27272
+ timeoutSignal.aborted ? "artifact_download_timeout" : "artifact_download_failed",
27273
+ timeoutSignal.aborted ? "The prompt artifact download timed out" : "The prompt artifact could not be downloaded",
27274
+ { cause: error61 }
27275
+ );
27276
+ }
27277
+ }
27278
+ function isTextMediaType(mediaType) {
27279
+ return mediaType.startsWith("text/") || mediaType === "application/json" || mediaType.endsWith("+json") || mediaType === "application/xml" || mediaType.endsWith("+xml");
27280
+ }
27281
+ async function resolvePromptArtifacts(config2, command, signal) {
27282
+ const images = [...command.images];
27283
+ const resources = [];
27284
+ for (const resource of command.resources) {
27285
+ signal.throwIfAborted();
27286
+ if (!resource.uri.startsWith(ARTIFACT_SCHEME)) {
27287
+ resources.push(resource);
27288
+ continue;
27289
+ }
27290
+ const reference = parseReference(resource);
27291
+ const bytes = await download(config2, command, reference, signal);
27292
+ if (resource.mimeType.startsWith("image/")) {
27293
+ const data = Buffer.from(bytes).toString("base64");
27294
+ if (data.length > MAX_AGENT_IMAGE_BASE64_LENGTH || images.length >= 8) {
27295
+ throw new PromptArtifactError(
27296
+ "artifact_too_large_for_agent",
27297
+ "The prompt artifact exceeds the Agent image limit"
27298
+ );
27299
+ }
27300
+ images.push({ data, mimeType: resource.mimeType, name: resource.name });
27301
+ continue;
27302
+ }
27303
+ if (!isTextMediaType(resource.mimeType)) {
27304
+ throw new PromptArtifactError(
27305
+ "artifact_media_type_unsupported",
27306
+ "The Agent cannot consume this prompt artifact media type"
27307
+ );
27308
+ }
27309
+ if (bytes.byteLength > MAX_AGENT_RESOURCE_BYTE_LENGTH || resources.length >= 16) {
27310
+ throw new PromptArtifactError(
27311
+ "artifact_too_large_for_agent",
27312
+ "The prompt artifact exceeds the Agent resource limit"
27313
+ );
27314
+ }
27315
+ let text;
27316
+ try {
27317
+ text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
27318
+ } catch (cause) {
27319
+ throw new PromptArtifactError("artifact_encoding_invalid", "The prompt artifact is not valid UTF-8 text", {
27320
+ cause
27321
+ });
27322
+ }
27323
+ resources.push({
27324
+ mimeType: resource.mimeType,
27325
+ name: resource.name,
27326
+ text,
27327
+ type: "embedded",
27328
+ uri: resource.uri
27329
+ });
27330
+ }
27331
+ return new ResolvedPromptArtifacts(images, resources);
27332
+ }
27333
+
28354
27334
  // src/relay-connection/connect.ts
28355
27335
  import { WebSocket } from "undici";
28356
27336
  var CONNECTION_TIMEOUT_MILLISECONDS = 15e3;
@@ -28388,28 +27368,16 @@ function connectRelay(url2, signal) {
28388
27368
  };
28389
27369
  const onAbort = () => {
28390
27370
  fail(
28391
- new RelayConnectionError(
28392
- "relay_connection_cancelled",
28393
- "Relay connection was cancelled",
28394
- { cause: signal.reason }
28395
- )
27371
+ new RelayConnectionError("relay_connection_cancelled", "Relay connection was cancelled", {
27372
+ cause: signal.reason
27373
+ })
28396
27374
  );
28397
27375
  };
28398
27376
  const onClose = () => {
28399
- fail(
28400
- new RelayConnectionError(
28401
- "relay_connection_closed",
28402
- "Relay connection closed before it was ready"
28403
- )
28404
- );
27377
+ fail(new RelayConnectionError("relay_connection_closed", "Relay connection closed before it was ready"));
28405
27378
  };
28406
27379
  const onError = () => {
28407
- fail(
28408
- new RelayConnectionError(
28409
- "relay_connection_failed",
28410
- "Relay connection failed"
28411
- )
28412
- );
27380
+ fail(new RelayConnectionError("relay_connection_failed", "Relay connection failed"));
28413
27381
  };
28414
27382
  const onOpen = () => {
28415
27383
  if (finished) {
@@ -28420,12 +27388,7 @@ function connectRelay(url2, signal) {
28420
27388
  resolve5(socket);
28421
27389
  };
28422
27390
  function onTimeout() {
28423
- fail(
28424
- new RelayConnectionError(
28425
- "relay_connection_timeout",
28426
- "Relay connection timed out"
28427
- )
28428
- );
27391
+ fail(new RelayConnectionError("relay_connection_timeout", "Relay connection timed out"));
28429
27392
  }
28430
27393
  signal.addEventListener("abort", onAbort, { once: true });
28431
27394
  socket.addEventListener("close", onClose, { once: true });
@@ -28480,10 +27443,7 @@ var RelayConnectionLiveness = class {
28480
27443
  }
28481
27444
  this.#state.timeout.cancel();
28482
27445
  this.#state = new WaitingForHeartbeatState(
28483
- this.#timer.schedule(
28484
- this.#sendHeartbeat,
28485
- HEARTBEAT_INTERVAL_MILLISECONDS
28486
- )
27446
+ this.#timer.schedule(this.#sendHeartbeat, HEARTBEAT_INTERVAL_MILLISECONDS)
28487
27447
  );
28488
27448
  };
28489
27449
  close = () => {
@@ -28532,10 +27492,7 @@ var RelayConnectionLiveness = class {
28532
27492
  const heartbeatId = randomUUID3();
28533
27493
  this.#state = new AwaitingHeartbeatAckState(
28534
27494
  heartbeatId,
28535
- this.#timer.schedule(
28536
- this.#handleTimeout,
28537
- HEARTBEAT_ACK_TIMEOUT_MILLISECONDS
28538
- )
27495
+ this.#timer.schedule(this.#handleTimeout, HEARTBEAT_ACK_TIMEOUT_MILLISECONDS)
28539
27496
  );
28540
27497
  this.#transport.send(
28541
27498
  encodeRuntimeHeartbeatEvent({
@@ -28602,9 +27559,7 @@ var SessionEventOutbox = class {
28602
27559
  const attemptId2 = Reflect.get(existing, "attempt_id");
28603
27560
  const state = Reflect.get(existing, "state");
28604
27561
  if (storedSessionId !== sessionId || storedCommand !== commandJson || typeof attemptId2 !== "string" || !isDaemonExecutionState(state)) {
28605
- throw new Error(
28606
- "The daemon command identity conflicts with its durable receipt"
28607
- );
27562
+ throw new Error("The daemon command identity conflicts with its durable receipt");
28608
27563
  }
28609
27564
  this.#database.exec("COMMIT");
28610
27565
  return { attemptId: attemptId2, commandId, kind: "duplicate", state };
@@ -28718,6 +27673,7 @@ var systemDaemonTimer = new SystemDaemonTimer();
28718
27673
  var RELAY_RECONNECT_DELAY_MILLISECONDS = 500;
28719
27674
  var RELAY_CONNECTION_REFRESH_MILLISECONDS = 20 * 60 * 1e3;
28720
27675
  var ACTIVE_TURN_RECONCILIATION_TIMEOUT_MILLISECONDS = 2e4;
27676
+ var ACTIVE_TURN_RECONCILIATION_CLOSE_CODE = 4009;
28721
27677
  var RelayConnectionRefreshState = class {
28722
27678
  };
28723
27679
  var ScheduledRelayConnectionRefreshState = class extends RelayConnectionRefreshState {
@@ -28734,10 +27690,7 @@ var RelayConnectionRefresh = class {
28734
27690
  constructor(timer, isSafe, refresh) {
28735
27691
  this.#isSafe = isSafe;
28736
27692
  this.#refresh = refresh;
28737
- this.#scheduledTask = timer.schedule(
28738
- this.#request,
28739
- RELAY_CONNECTION_REFRESH_MILLISECONDS
28740
- );
27693
+ this.#scheduledTask = timer.schedule(this.#request, RELAY_CONNECTION_REFRESH_MILLISECONDS);
28741
27694
  }
28742
27695
  afterTurnFinished = () => {
28743
27696
  if (this.#state instanceof DueRelayConnectionRefreshState) {
@@ -28787,10 +27740,7 @@ var DaemonAcpObserver = class {
28787
27740
  return Promise.resolve();
28788
27741
  };
28789
27742
  onElicitation = (event) => {
28790
- this.#record(
28791
- event.sessionId,
28792
- encodeSessionElicitationRequestedEvent(event)
28793
- );
27743
+ this.#record(event.sessionId, encodeSessionElicitationRequestedEvent(event));
28794
27744
  return Promise.resolve();
28795
27745
  };
28796
27746
  onElicitationResolved = (event) => {
@@ -28977,13 +27927,11 @@ function activeTurnReconciliationEndpoint(config2, turn) {
28977
27927
  }
28978
27928
  async function reconcileActiveTurn(config2, turn, signal) {
28979
27929
  signal.throwIfAborted();
28980
- const timeoutSignal = AbortSignal.timeout(
28981
- ACTIVE_TURN_RECONCILIATION_TIMEOUT_MILLISECONDS
28982
- );
27930
+ const timeoutSignal = AbortSignal.timeout(ACTIVE_TURN_RECONCILIATION_TIMEOUT_MILLISECONDS);
28983
27931
  const requestSignal = AbortSignal.any([signal, timeoutSignal]);
28984
27932
  let response;
28985
27933
  try {
28986
- response = await fetch4(activeTurnReconciliationEndpoint(config2, turn), {
27934
+ response = await fetch5(activeTurnReconciliationEndpoint(config2, turn), {
28987
27935
  body: JSON.stringify({ outcome: { kind: "running" } }),
28988
27936
  dispatcher: environmentProxyDispatcher,
28989
27937
  headers: { "content-type": "application/json" },
@@ -29002,14 +27950,12 @@ async function reconcileActiveTurn(config2, turn, signal) {
29002
27950
  await response.body?.cancel();
29003
27951
  if (!response.ok) {
29004
27952
  throw new ActiveTurnReconciliationError(
29005
- "The Relay rejected the active Agent turn reconciliation"
27953
+ `The Relay rejected the active Agent turn reconciliation with status ${response.status.toString()}`
29006
27954
  );
29007
27955
  }
29008
27956
  }
29009
27957
  async function reconcileActiveTurns(config2, turns, signal) {
29010
- await Promise.all(
29011
- turns.map(async (turn) => await reconcileActiveTurn(config2, turn, signal))
29012
- );
27958
+ await Promise.all(turns.map(async (turn) => await reconcileActiveTurn(config2, turn, signal)));
29013
27959
  }
29014
27960
  function send(socket, message) {
29015
27961
  if (socket.readyState !== WebSocket2.OPEN) {
@@ -29017,6 +27963,18 @@ function send(socket, message) {
29017
27963
  }
29018
27964
  socket.send(message);
29019
27965
  }
27966
+ function closeRelaySocket(socket, code, reason) {
27967
+ try {
27968
+ socket.close(code, reason);
27969
+ } catch (error61) {
27970
+ console.error("Mobius daemon could not close the Relay WebSocket", error61);
27971
+ try {
27972
+ socket.close();
27973
+ } catch (fallbackError) {
27974
+ console.error("Mobius daemon could not release the Relay WebSocket", fallbackError);
27975
+ }
27976
+ }
27977
+ }
29020
27978
  var DaemonSessionEventConnectionState = class {
29021
27979
  };
29022
27980
  var DisconnectedDaemonSessionEventState = class extends DaemonSessionEventConnectionState {
@@ -29076,13 +28034,13 @@ function reportFailure(publisher, command, code, message, attemptId) {
29076
28034
  );
29077
28035
  }
29078
28036
  function operationErrorCode(error61) {
29079
- if (error61 instanceof AcpExecutionError || error61 instanceof LocalAuthorizationError || error61 instanceof LocalAgentCatalogError) {
28037
+ if (error61 instanceof AcpExecutionError || error61 instanceof LocalAuthorizationError || error61 instanceof LocalAgentCatalogError || error61 instanceof PromptArtifactError) {
29080
28038
  return error61.code;
29081
28039
  }
29082
28040
  return "session_operation_failed";
29083
28041
  }
29084
28042
  function operationErrorMessage(error61) {
29085
- if (error61 instanceof AcpExecutionError || error61 instanceof LocalAuthorizationError || error61 instanceof LocalAgentCatalogError) {
28043
+ if (error61 instanceof AcpExecutionError || error61 instanceof LocalAuthorizationError || error61 instanceof LocalAgentCatalogError || error61 instanceof PromptArtifactError) {
29086
28044
  return error61.message;
29087
28045
  }
29088
28046
  return "The local agent operation could not be completed";
@@ -29108,15 +28066,9 @@ async function resolveSessionDirectories(directories, bindingId, directoryId2, a
29108
28066
  const additionalDirectoryEntries = [];
29109
28067
  const unique = /* @__PURE__ */ new Set([cwd]);
29110
28068
  for (const additionalDirectoryId of additionalDirectoryIds) {
29111
- const directory = await directories.resolve(
29112
- bindingId,
29113
- additionalDirectoryId,
29114
- signal
29115
- );
28069
+ const directory = await directories.resolve(bindingId, additionalDirectoryId, signal);
29116
28070
  if (unique.has(directory)) {
29117
- throw new LocalAuthorizationError(
29118
- "Workspace directories must resolve to distinct locations"
29119
- );
28071
+ throw new LocalAuthorizationError("Workspace directories must resolve to distinct locations");
29120
28072
  }
29121
28073
  unique.add(directory);
29122
28074
  additionalDirectories.push(directory);
@@ -29125,19 +28077,11 @@ async function resolveSessionDirectories(directories, bindingId, directoryId2, a
29125
28077
  name: basename3(directory)
29126
28078
  });
29127
28079
  }
29128
- return new ResolvedSessionDirectories(
29129
- cwd,
29130
- additionalDirectories,
29131
- additionalDirectoryEntries
29132
- );
28080
+ return new ResolvedSessionDirectories(cwd, additionalDirectories, additionalDirectoryEntries);
29133
28081
  }
29134
28082
  async function executeWorkspaceList(socket, command, directories, audit, signal) {
29135
28083
  try {
29136
- const listing = await directories.list(
29137
- command.bindingId,
29138
- command.directoryId,
29139
- signal
29140
- );
28084
+ const listing = await directories.list(command.bindingId, command.directoryId, signal);
29141
28085
  audit.record({
29142
28086
  commandId: command.requestId,
29143
28087
  event: "workspace_list_authorized",
@@ -29176,11 +28120,7 @@ async function executeSessionPrepare(publisher, socket, command, config2, direct
29176
28120
  sessionId: command.sessionId,
29177
28121
  signal
29178
28122
  });
29179
- const listing = await directories.list(
29180
- config2.bindingId,
29181
- command.directoryId,
29182
- signal
29183
- );
28123
+ const listing = await directories.list(config2.bindingId, command.directoryId, signal);
29184
28124
  audit.record({
29185
28125
  commandId: command.requestId,
29186
28126
  event: "session_prepared",
@@ -29282,12 +28222,13 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
29282
28222
  }),
29283
28223
  attemptId
29284
28224
  );
28225
+ const attachments = await resolvePromptArtifacts(config2, command, signal);
29285
28226
  const result = await sessions.runPrompt({
29286
28227
  additionalDirectories: resolved.additionalDirectories,
29287
28228
  agent,
29288
28229
  commandId: command.commandId,
29289
28230
  cwd: resolved.cwd,
29290
- images: command.images,
28231
+ images: attachments.images,
29291
28232
  onActivity: (activity) => {
29292
28233
  publisher.recordAttempt(
29293
28234
  command.sessionId,
@@ -29326,7 +28267,7 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
29326
28267
  return Promise.resolve();
29327
28268
  },
29328
28269
  prompt: command.prompt,
29329
- resources: command.resources,
28270
+ resources: attachments.resources,
29330
28271
  sessionId: command.sessionId,
29331
28272
  signal
29332
28273
  });
@@ -29340,10 +28281,7 @@ async function executePrompt(outbox, publisher, command, config2, directories, a
29340
28281
  }),
29341
28282
  attemptId
29342
28283
  );
29343
- outbox.transitionExecution(
29344
- command.commandId,
29345
- result.stopReason === "cancelled" ? "cancelled" : "succeeded"
29346
- );
28284
+ outbox.transitionExecution(command.commandId, result.stopReason === "cancelled" ? "cancelled" : "succeeded");
29347
28285
  audit.record({
29348
28286
  commandId: command.commandId,
29349
28287
  event: result.stopReason === "cancelled" ? "session_cancelled" : "session_completed",
@@ -29443,17 +28381,17 @@ async function runRelayConnection(config2, directories, audit, sessions, install
29443
28381
  reject(new Error("Relay WebSocket failed"));
29444
28382
  };
29445
28383
  const stop = () => {
29446
- socket.close(1e3, "Daemon stopped");
28384
+ closeRelaySocket(socket, 1e3, "Daemon stopped");
29447
28385
  resolveConnection();
29448
28386
  };
29449
28387
  const refreshConnection = () => {
29450
- socket.close(1e3, "Refreshing idle relay connection");
28388
+ closeRelaySocket(socket, 1e3, "Refreshing idle relay connection");
29451
28389
  resolveConnection();
29452
28390
  };
29453
28391
  const connectionLiveness = new RelayConnectionLiveness(timer, {
29454
28392
  send: (message) => send(socket, message),
29455
28393
  unresponsive: () => {
29456
- socket.close(4001, "Relay liveness check timed out");
28394
+ closeRelaySocket(socket, 4001, "Relay liveness check timed out");
29457
28395
  resolveConnection();
29458
28396
  }
29459
28397
  });
@@ -29476,7 +28414,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
29476
28414
  const handleMessage = (event) => {
29477
28415
  const encoded = event.data;
29478
28416
  if (typeof encoded !== "string") {
29479
- socket.close(4003, "Text message required");
28417
+ closeRelaySocket(socket, 4003, "Text message required");
29480
28418
  rejectConnection();
29481
28419
  return;
29482
28420
  }
@@ -29489,7 +28427,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
29489
28427
  if (kind === NATIVE_SESSION_CANCEL_KIND) {
29490
28428
  const command2 = decodeNativeSessionCancel(encoded);
29491
28429
  const pending = nativeRequests.get(command2.requestId);
29492
- if (pending?.sessionId === command2.sessionId)
28430
+ if (pending?.sessionId === command2.sessionId) {
29493
28431
  pending.controller.abort(
29494
28432
  new AcpExecutionError(
29495
28433
  "Native session operation cancelled",
@@ -29497,6 +28435,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
29497
28435
  "native_session_cancelled"
29498
28436
  )
29499
28437
  );
28438
+ }
29500
28439
  return;
29501
28440
  }
29502
28441
  if (kind === NATIVE_SESSION_REQUEST_KIND) {
@@ -29518,10 +28457,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
29518
28457
  return;
29519
28458
  }
29520
28459
  const controller = new AbortController();
29521
- const operationSignal = AbortSignal.any([
29522
- connectionController.signal,
29523
- controller.signal
29524
- ]);
28460
+ const operationSignal = AbortSignal.any([connectionController.signal, controller.signal]);
29525
28461
  const timeout = timer.schedule(
29526
28462
  () => controller.abort(
29527
28463
  new AcpExecutionError(
@@ -29541,9 +28477,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
29541
28477
  operationSignal.addEventListener("abort", cancel, {
29542
28478
  once: true
29543
28479
  });
29544
- void Promise.all(
29545
- previous.map((request) => request.completion)
29546
- ).then(
28480
+ void Promise.all(previous.map((request) => request.completion)).then(
29547
28481
  () => {
29548
28482
  operationSignal.removeEventListener("abort", cancel);
29549
28483
  resolve6();
@@ -29556,12 +28490,10 @@ async function runRelayConnection(config2, directories, audit, sessions, install
29556
28490
  });
29557
28491
  }
29558
28492
  operationSignal.throwIfAborted();
29559
- const result = await nativeSessions.execute(
29560
- command2,
29561
- operationSignal
29562
- );
29563
- if (socket.readyState === WebSocket2.OPEN)
28493
+ const result = await nativeSessions.execute(command2, operationSignal);
28494
+ if (socket.readyState === WebSocket2.OPEN) {
29564
28495
  send(socket, encodeNativeSessionResult(result));
28496
+ }
29565
28497
  } catch (error61) {
29566
28498
  const failure = operationSignal.aborted ? controller.signal.reason ?? new AcpExecutionError(
29567
28499
  "Native session operation cancelled",
@@ -29574,12 +28506,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
29574
28506
  event: "native_session_operation_failed",
29575
28507
  details: { code: operationErrorCode(failure) }
29576
28508
  });
29577
- reportOperationFailure(
29578
- socket,
29579
- command2.requestId,
29580
- command2.sessionId,
29581
- failure
29582
- );
28509
+ reportOperationFailure(socket, command2.requestId, command2.sessionId, failure);
29583
28510
  } finally {
29584
28511
  timeout.cancel();
29585
28512
  nativeRequests.delete(command2.requestId);
@@ -29599,18 +28526,14 @@ async function runRelayConnection(config2, directories, audit, sessions, install
29599
28526
  return;
29600
28527
  }
29601
28528
  if (kind === RUNTIME_HEARTBEAT_ACK_KIND) {
29602
- connectionLiveness.acknowledge(
29603
- decodeRuntimeHeartbeatAckEvent(encoded)
29604
- );
28529
+ connectionLiveness.acknowledge(decodeRuntimeHeartbeatAckEvent(encoded));
29605
28530
  return;
29606
28531
  }
29607
28532
  if (kind === SESSION_CANCEL_KIND) {
29608
28533
  const cancellation = decodeSessionCancelCommand(encoded);
29609
28534
  const turn2 = activeTurns.get(cancellation.commandId);
29610
28535
  if (turn2 === void 0 || !turn2.matches(cancellation)) {
29611
- console.warn(
29612
- "Mobius daemon ignored cancellation for an inactive turn"
29613
- );
28536
+ console.warn("Mobius daemon ignored cancellation for an inactive turn");
29614
28537
  return;
29615
28538
  }
29616
28539
  if (!turn2.requestCancellation()) {
@@ -29622,22 +28545,13 @@ async function runRelayConnection(config2, directories, audit, sessions, install
29622
28545
  sessionId: cancellation.sessionId
29623
28546
  });
29624
28547
  void sessions.cancelPrompt(cancellation.sessionId).catch((error61) => {
29625
- console.error(
29626
- "Mobius daemon could not cancel the agent turn",
29627
- error61
29628
- );
28548
+ console.error("Mobius daemon could not cancel the agent turn", error61);
29629
28549
  });
29630
28550
  return;
29631
28551
  }
29632
28552
  if (kind === WORKSPACE_LIST_KIND) {
29633
28553
  const command2 = decodeWorkspaceListCommand(encoded);
29634
- void executeWorkspaceList(
29635
- socket,
29636
- command2,
29637
- directories,
29638
- audit,
29639
- connectionController.signal
29640
- );
28554
+ void executeWorkspaceList(socket, command2, directories, audit, connectionController.signal);
29641
28555
  return;
29642
28556
  }
29643
28557
  if (kind === SESSION_PREPARE_KIND) {
@@ -29677,12 +28591,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
29677
28591
  sessionId: command2.sessionId
29678
28592
  });
29679
28593
  }).catch((error61) => {
29680
- reportOperationFailure(
29681
- socket,
29682
- command2.interactionId,
29683
- command2.sessionId,
29684
- error61
29685
- );
28594
+ reportOperationFailure(socket, command2.interactionId, command2.sessionId, error61);
29686
28595
  });
29687
28596
  return;
29688
28597
  }
@@ -29695,22 +28604,14 @@ async function runRelayConnection(config2, directories, audit, sessions, install
29695
28604
  sessionId: command2.sessionId
29696
28605
  });
29697
28606
  }).catch((error61) => {
29698
- reportOperationFailure(
29699
- socket,
29700
- command2.interactionId,
29701
- command2.sessionId,
29702
- error61
29703
- );
28607
+ reportOperationFailure(socket, command2.interactionId, command2.sessionId, error61);
29704
28608
  });
29705
28609
  return;
29706
28610
  }
29707
28611
  if (kind === AGENT_INSTALL_REQUEST_KIND) {
29708
28612
  const command2 = decodeAgentInstallRequestCommand(encoded);
29709
28613
  void installations.request(command2, signal).catch((error61) => {
29710
- console.error(
29711
- "Mobius Agent integration installation failed",
29712
- error61
29713
- );
28614
+ console.error("Mobius Agent integration installation failed", error61);
29714
28615
  });
29715
28616
  return;
29716
28617
  }
@@ -29728,11 +28629,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
29728
28629
  if (activeTurns.has(command.commandId)) {
29729
28630
  return;
29730
28631
  }
29731
- const receipt = outbox.claimExecution(
29732
- command.commandId,
29733
- command.sessionId,
29734
- encoded
29735
- );
28632
+ const receipt = outbox.claimExecution(command.commandId, command.sessionId, encoded);
29736
28633
  if (receipt.kind === "duplicate") {
29737
28634
  return;
29738
28635
  }
@@ -29761,32 +28658,33 @@ async function runRelayConnection(config2, directories, audit, sessions, install
29761
28658
  });
29762
28659
  } catch (error61) {
29763
28660
  console.error("Mobius daemon rejected a message", error61);
29764
- socket.close(4008, "Invalid protocol message");
28661
+ closeRelaySocket(socket, 4008, "Invalid protocol message");
29765
28662
  rejectConnection();
29766
28663
  }
29767
28664
  };
29768
28665
  socket.addEventListener("close", handleClose);
29769
28666
  socket.addEventListener("error", handleError);
29770
28667
  socket.addEventListener("message", handleMessage);
29771
- void reconcileActiveTurns(
29772
- config2,
29773
- reconnectingTurns,
29774
- connectionController.signal
29775
- ).then(
28668
+ void reconcileActiveTurns(config2, reconnectingTurns, connectionController.signal).then(
29776
28669
  () => {
29777
28670
  if (finished) {
29778
28671
  return;
29779
28672
  }
29780
28673
  publisher.connect(socket);
29781
- void Promise.all(
29782
- reconnectingTurns.map((turn) => turn.completion)
29783
- ).then(connectionRefresh.afterTurnFinished);
28674
+ void Promise.all(reconnectingTurns.map((turn) => turn.completion)).then(
28675
+ connectionRefresh.afterTurnFinished
28676
+ );
29784
28677
  },
29785
- () => {
28678
+ (error61) => {
29786
28679
  if (finished) {
29787
28680
  return;
29788
28681
  }
29789
- socket.close(1011, "Active Agent turn reconciliation failed");
28682
+ console.error("Mobius daemon could not reconcile active Agent turns", error61);
28683
+ closeRelaySocket(
28684
+ socket,
28685
+ ACTIVE_TURN_RECONCILIATION_CLOSE_CODE,
28686
+ "Active Agent turn reconciliation failed"
28687
+ );
29790
28688
  rejectConnection();
29791
28689
  }
29792
28690
  );
@@ -29796,9 +28694,7 @@ async function runRelayConnection(config2, directories, audit, sessions, install
29796
28694
  });
29797
28695
  } finally {
29798
28696
  connectionController.abort();
29799
- await Promise.all(
29800
- [...nativeRequests.values()].map((request) => request.completion)
29801
- );
28697
+ await Promise.all([...nativeRequests.values()].map((request) => request.completion));
29802
28698
  }
29803
28699
  }
29804
28700
  async function runDaemon(config2, audit, signal, timer = systemDaemonTimer) {
@@ -29826,21 +28722,10 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer) {
29826
28722
  }
29827
28723
  publisher.recordAttempt(sessionId, payload, attemptId);
29828
28724
  };
29829
- const sessions = new AcpSessionManager(
29830
- new DaemonAcpObserver(recordSessionEvent),
29831
- sessionStore
29832
- );
29833
- const directories = new WorkspaceDirectoryService(
29834
- config2.bindingId,
29835
- config2.defaultWorkspace
29836
- );
28725
+ const sessions = new AcpSessionManager(new DaemonAcpObserver(recordSessionEvent), sessionStore);
28726
+ const directories = new WorkspaceDirectoryService(config2.bindingId, config2.defaultWorkspace);
29837
28727
  const installationObserver = new DaemonInstallationObserver();
29838
- const nativeSessions = new NativeSessionService(
29839
- config2,
29840
- directories,
29841
- sessions,
29842
- audit
29843
- );
28728
+ const nativeSessions = new NativeSessionService(config2, directories, sessions, audit);
29844
28729
  const installations = new AgentInstallationManager(
29845
28730
  specifications,
29846
28731
  installationExecutor,
@@ -29857,20 +28742,13 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer) {
29857
28742
  const reconnectCommand = `npx --yes @moxt-ai/mobius start --channel ${config2.channelId}`;
29858
28743
  process.stdout.write("Mobius daemon connected to the relay.\n\n");
29859
28744
  process.stdout.write(
29860
- `${styleText(
29861
- ["bold", "yellow"],
29862
- `Reconnect this channel later:
29863
- ${reconnectCommand}`
29864
- )}
28745
+ `${styleText(["bold", "yellow"], `Reconnect this channel later:
28746
+ ${reconnectCommand}`)}
29865
28747
 
29866
28748
  `
29867
28749
  );
29868
28750
  };
29869
- const catalogPublication = publishAgentCatalogUntilAvailable(
29870
- config2,
29871
- signal,
29872
- timer
29873
- );
28751
+ const catalogPublication = publishAgentCatalogUntilAvailable(config2, signal, timer);
29874
28752
  try {
29875
28753
  while (!signal.aborted) {
29876
28754
  try {