@modootoday/pmcp 0.17.4 → 0.18.2

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 (272) hide show
  1. package/.agents/plugins/marketplace.json +1 -1
  2. package/.claude-plugin/marketplace.json +1 -1
  3. package/.claude-plugin/plugin.json +2 -2
  4. package/.mcp.json +1 -1
  5. package/CHANGELOG.md +152 -0
  6. package/CONTRIBUTING.md +71 -0
  7. package/README.md +98 -201
  8. package/SECURITY.md +17 -1
  9. package/dist/apply-JUTGS5WZ.js +242 -0
  10. package/dist/{attachment-tU5FZrgZ.d.ts → attachment-D84OGI6n.d.ts} +1 -1
  11. package/dist/available-DBSIVVJ6.js +73 -0
  12. package/dist/broadcast-CBMVOV3G.js +18 -0
  13. package/dist/chunk-26WLNWDG.js +93 -0
  14. package/dist/chunk-2FIV63WC.js +252 -0
  15. package/dist/chunk-2P4Z2NUX.js +28 -0
  16. package/dist/chunk-34DECPVC.js +22 -0
  17. package/dist/chunk-3FCFAQDG.js +42 -0
  18. package/dist/chunk-3IDXEV5E.js +1934 -0
  19. package/dist/chunk-3PW4FI7U.js +32 -0
  20. package/dist/chunk-3Y3HDMHA.js +108 -0
  21. package/dist/chunk-47O3X4VS.js +113 -0
  22. package/dist/chunk-4NDEP7HU.js +26 -0
  23. package/dist/chunk-5OMOPUE6.js +39 -0
  24. package/dist/chunk-5QQWS4US.js +53 -0
  25. package/dist/chunk-5ZABTVSW.js +48 -0
  26. package/dist/chunk-65KAQSJP.js +7 -0
  27. package/dist/chunk-6STKGOCW.js +27 -0
  28. package/dist/chunk-6WXMJOMI.js +9 -0
  29. package/dist/chunk-73AKO4UL.js +24 -0
  30. package/dist/chunk-7DLZC73N.js +29 -0
  31. package/dist/chunk-7GBYECSK.js +72 -0
  32. package/dist/chunk-7HFIGCSL.js +419 -0
  33. package/dist/chunk-7TD53M7L.js +13 -0
  34. package/dist/chunk-7UCZAN4J.js +778 -0
  35. package/dist/chunk-A4PKLESO.js +112 -0
  36. package/dist/chunk-A7VF7A35.js +1025 -0
  37. package/dist/chunk-ABTJQ4QV.js +74 -0
  38. package/dist/chunk-AJ4VXM2U.js +349 -0
  39. package/dist/chunk-BBTBJCFA.js +380 -0
  40. package/dist/chunk-BU65MNVU.js +13 -0
  41. package/dist/chunk-C4NHQGHL.js +142 -0
  42. package/dist/chunk-CJTKR6K6.js +1213 -0
  43. package/dist/chunk-D77IRGHO.js +1246 -0
  44. package/dist/chunk-DCU2EXQV.js +78 -0
  45. package/dist/chunk-DMZHQZ7P.js +104 -0
  46. package/dist/chunk-DZ2MRTYT.js +135 -0
  47. package/dist/chunk-E2YOZ2FF.js +207 -0
  48. package/dist/chunk-E3DQB5LS.js +48 -0
  49. package/dist/chunk-EATCUWGG.js +66 -0
  50. package/dist/chunk-EAWPJHJ7.js +155 -0
  51. package/dist/chunk-EIDIVIAD.js +33 -0
  52. package/dist/chunk-F5QYZK7E.js +396 -0
  53. package/dist/chunk-F5XMGOOX.js +28 -0
  54. package/dist/chunk-FENOGX3U.js +31 -0
  55. package/dist/chunk-GZHHEHKY.js +44 -0
  56. package/dist/chunk-HDMBVLCZ.js +53 -0
  57. package/dist/chunk-HQOB7OQS.js +81 -0
  58. package/dist/chunk-I2ZP2PSA.js +211 -0
  59. package/dist/chunk-IG33DXLT.js +151 -0
  60. package/dist/chunk-IJBSOWHK.js +86 -0
  61. package/dist/chunk-INT7QLEU.js +114 -0
  62. package/dist/chunk-J7UYNJCR.js +9 -0
  63. package/dist/chunk-JEL35P7S.js +53 -0
  64. package/dist/chunk-JGJ4INEN.js +32 -0
  65. package/dist/chunk-JS5RTH4I.js +84 -0
  66. package/dist/chunk-JWRZDYB5.js +59 -0
  67. package/dist/chunk-KMXRRSKT.js +660 -0
  68. package/dist/chunk-LBXO4VPG.js +73 -0
  69. package/dist/chunk-LLBPVZXM.js +67 -0
  70. package/dist/chunk-LLT5FQBE.js +57 -0
  71. package/dist/chunk-LMT3PPXJ.js +17 -0
  72. package/dist/chunk-LMUBBIE2.js +83 -0
  73. package/dist/chunk-LTZH5E3G.js +479 -0
  74. package/dist/chunk-LW4TG7EL.js +39 -0
  75. package/dist/chunk-MPSQXSC6.js +346 -0
  76. package/dist/chunk-MVFH26QT.js +97 -0
  77. package/dist/chunk-NLEXKE7U.js +67 -0
  78. package/dist/chunk-NQPURJT5.js +44 -0
  79. package/dist/chunk-NRBQK6UX.js +105 -0
  80. package/dist/chunk-OEH47H6A.js +48 -0
  81. package/dist/chunk-OG7QR2DP.js +75 -0
  82. package/dist/chunk-OPYFEHKG.js +52 -0
  83. package/dist/chunk-P4N7DBD5.js +83 -0
  84. package/dist/chunk-PAX3QXX2.js +140 -0
  85. package/dist/chunk-PKODFR5F.js +102 -0
  86. package/dist/chunk-PMJG2CXF.js +122 -0
  87. package/dist/chunk-Q5H3L6Y4.js +23 -0
  88. package/dist/chunk-QEF7EK3T.js +28 -0
  89. package/dist/chunk-QEW4J3IZ.js +74 -0
  90. package/dist/chunk-QPL7E2HW.js +464 -0
  91. package/dist/chunk-R2GPCZUX.js +22 -0
  92. package/dist/chunk-R5MT42JS.js +284 -0
  93. package/dist/chunk-RMATE45Z.js +197 -0
  94. package/dist/chunk-RPQOBHVU.js +87 -0
  95. package/dist/chunk-S3PIAMXV.js +230 -0
  96. package/dist/chunk-T3LKX23M.js +168 -0
  97. package/dist/chunk-T6GOWHK6.js +30 -0
  98. package/dist/chunk-TIA4SPU2.js +10 -0
  99. package/dist/chunk-TNCZ6444.js +57 -0
  100. package/dist/chunk-TVL5RTE6.js +269 -0
  101. package/dist/chunk-TXQ7L33K.js +45 -0
  102. package/dist/chunk-UPQTAHUK.js +189 -0
  103. package/dist/chunk-V4NPDK6X.js +14 -0
  104. package/dist/chunk-VJFEN6DJ.js +38 -0
  105. package/dist/chunk-VMHUEOT5.js +643 -0
  106. package/dist/chunk-VRPMYPZU.js +4985 -0
  107. package/dist/chunk-WIW772I3.js +25 -0
  108. package/dist/chunk-XELAZAIM.js +136 -0
  109. package/dist/chunk-XNML2KIC.js +23 -0
  110. package/dist/chunk-XP2U3LO3.js +30 -0
  111. package/dist/chunk-YGOWIJPE.js +51 -0
  112. package/dist/chunk-YIXDHQYE.js +11 -0
  113. package/dist/chunk-YSAWTGNA.js +117 -0
  114. package/dist/claude-U2JC2DNQ.js +77 -0
  115. package/dist/cli-MI4ZCAZ3.js +41 -0
  116. package/dist/cli-ZN7ZVDEZ.js +46 -0
  117. package/dist/cli.js +144 -16197
  118. package/dist/completion-ILSRB3LW.js +142 -0
  119. package/dist/config-DnpLL2kT.d.ts +46 -0
  120. package/dist/{service-qpCsOXkQ.d.ts → core-C1LPjxK6.d.ts} +2 -6
  121. package/dist/diagnostics-XKXVVQWH.js +93 -0
  122. package/dist/doctor-O2E63YGO.js +538 -0
  123. package/dist/entry-X6CSYQRQ.js +305 -0
  124. package/dist/exec-mcp-2PMWBPD7.js +365 -0
  125. package/dist/harness-L2KSI2ZB.js +177 -0
  126. package/dist/harness-egress-bridge.js +4 -4
  127. package/dist/harness-launch-gate.js +47 -940
  128. package/dist/harness-pane-runner.js +13 -80
  129. package/dist/harness-worker.js +21 -2703
  130. package/dist/hook-body.js +5222 -0
  131. package/dist/hook-spec-C5fWTSCH.d.ts +100 -0
  132. package/dist/hook.js +26 -0
  133. package/dist/hooks-BHTA44X7.js +21 -0
  134. package/dist/host-UIZAXXQH.js +22 -0
  135. package/dist/host-UWK754BW.js +210 -0
  136. package/dist/host-run-BI2OTZDZ.js +307 -0
  137. package/dist/http.d.ts +5 -42
  138. package/dist/http.js +21 -2234
  139. package/dist/import-mcp-GPKJI7DI.js +400 -0
  140. package/dist/index.d.ts +146 -168
  141. package/dist/index.js +133 -4948
  142. package/dist/init-3C2Y7BNJ.js +14 -0
  143. package/dist/install-GG7HHZK2.js +796 -0
  144. package/dist/invoke-44CJRVMK.js +23 -0
  145. package/dist/list-MCP2FXUF.js +68 -0
  146. package/dist/list-WL6L4J5H.js +65 -0
  147. package/dist/load-BEUBABtB.d.ts +21 -0
  148. package/dist/logout-F5EJ5MOU.js +44 -0
  149. package/dist/logs-TBUA4UWU.js +107 -0
  150. package/dist/mailbox/index.d.ts +10 -5
  151. package/dist/mailbox/index.js +53 -1572
  152. package/dist/mailbox-BMTZOSZ7.js +285 -0
  153. package/dist/mailbox-GDJ7BWQN.js +189 -0
  154. package/dist/mainline-KAD2ERLP.js +639 -0
  155. package/dist/marketplace-G4VQET5W.js +191 -0
  156. package/dist/mcp-235QZN2A.js +15 -0
  157. package/dist/mcp-FJ2UQ4RH.js +193 -0
  158. package/dist/models-ISU4DCMA.js +32 -0
  159. package/dist/opencode-CN7JLQYO.js +60 -0
  160. package/dist/pause-7LILUVGL.js +18 -0
  161. package/dist/preview-DT7DWG5F.js +91 -0
  162. package/dist/project/hook-adapter.d.ts +5 -2
  163. package/dist/project/hook-adapter.js +41 -27
  164. package/dist/project-5YV5CUEG.js +70 -0
  165. package/dist/pty-XTJ4MIWK.js +94 -0
  166. package/dist/recovery-U6QB3PMT.js +100 -0
  167. package/dist/reindex-Y27QJFDB.js +22 -0
  168. package/dist/resume-26VFAAMH.js +18 -0
  169. package/dist/run-3AXTZSR7.js +126 -0
  170. package/dist/run-3SOVRQIA.js +19 -0
  171. package/dist/serve-DQMKTFIV.js +104 -0
  172. package/dist/session-XM2CR425.js +159 -0
  173. package/dist/setup-DTKZLZUT.js +18 -0
  174. package/dist/start-login-YTZV6KMF.js +416 -0
  175. package/dist/status-A2OUTNGK.js +9 -0
  176. package/dist/status-H2VAHIDV.js +10 -0
  177. package/dist/status-MROQ7WR7.js +43 -0
  178. package/dist/status-RO55QPKV.js +55 -0
  179. package/dist/status-UME2L33L.js +286 -0
  180. package/dist/stdio.d.ts +3 -13
  181. package/dist/stdio.js +16 -3186
  182. package/dist/sweep-35LGQTTO.js +18 -0
  183. package/dist/test-AGZOJLRZ.js +561 -0
  184. package/dist/tools-gpHNq9Dh.d.ts +328 -0
  185. package/dist/tui-G5LLWCSV.js +153 -0
  186. package/dist/unbroadcast-5QNGAJR2.js +18 -0
  187. package/dist/validate-IU52H2IC.js +46 -0
  188. package/dist/worker-QZ5T6LJD.js +80 -0
  189. package/dist/worktree-create-PZSRB7PH.js +89 -0
  190. package/dist/worktree-list-JYB6VXLW.js +51 -0
  191. package/dist/worktree-sync-UF5CXPWV.js +30 -0
  192. package/docs/authoring.md +82 -0
  193. package/docs/browser-and-desktop.md +46 -0
  194. package/docs/commands.md +325 -0
  195. package/docs/compare.md +35 -0
  196. package/docs/compatibility.md +55 -0
  197. package/docs/embeddings.md +1 -1
  198. package/docs/getting-started.md +105 -0
  199. package/docs/git-workflow.md +60 -0
  200. package/docs/glossary.md +31 -0
  201. package/docs/hooks/capabilities/antigravity.json +199 -0
  202. package/docs/hooks/capabilities/claude.json +179 -0
  203. package/docs/hooks/capabilities/codex.json +179 -0
  204. package/docs/hooks/capabilities/gemini.json +196 -0
  205. package/docs/hooks/capabilities/grok.json +192 -0
  206. package/docs/hooks/capabilities/opencode.json +184 -0
  207. package/docs/hooks.md +264 -0
  208. package/docs/install.md +72 -0
  209. package/docs/library-skills.md +132 -0
  210. package/docs/mailbox.md +16 -5
  211. package/docs/project-configuration.md +540 -58
  212. package/docs/sessions.md +64 -0
  213. package/docs/skills.md +4 -45
  214. package/docs/terminal-harness.md +92 -44
  215. package/docs/terminal-workspace.md +81 -169
  216. package/gemini-extension.json +2 -2
  217. package/mcp.json +1 -1
  218. package/package.json +16 -2
  219. package/plugin.json +2 -2
  220. package/plugins/pmcp/.claude-plugin/plugin.json +4 -2
  221. package/plugins/pmcp/.mcp.json +1 -1
  222. package/plugins/pmcp/gemini-extension.json +2 -2
  223. package/plugins/pmcp/mcp.json +1 -1
  224. package/plugins/pmcp/mod/commands.ts +72 -0
  225. package/plugins/pmcp/mod/contract.d.ts +39 -0
  226. package/plugins/pmcp/mod/draw.tsx +216 -0
  227. package/plugins/pmcp/mod/guard.ts +42 -0
  228. package/plugins/pmcp/mod/hooks.json +4 -0
  229. package/plugins/pmcp/mod/host.ts +46 -0
  230. package/plugins/pmcp/mod/model.ts +144 -0
  231. package/plugins/pmcp/mod/reader/index.ts +18 -0
  232. package/plugins/pmcp/mod/reader/read.ts +76 -0
  233. package/plugins/pmcp/mod/reader/settings.ts +54 -0
  234. package/plugins/pmcp/mod/reader/types.ts +38 -0
  235. package/plugins/pmcp/mod/register.tsx +73 -0
  236. package/plugins/pmcp/mod/sessions/format.ts +91 -0
  237. package/plugins/pmcp/mod/sessions/types.ts +162 -0
  238. package/plugins/pmcp/mod/snapshot.ts +75 -0
  239. package/plugins/pmcp/mod/spinner.tsx +30 -0
  240. package/plugins/pmcp/mod/state.ts +28 -0
  241. package/plugins/pmcp/plugin.json +2 -2
  242. package/plugins/pmcp/skills/agent-assets-migrate/SKILL.md +96 -0
  243. package/plugins/pmcp/skills/headless-agents-ci-scaffold/SKILL.md +101 -0
  244. package/plugins/pmcp/skills/marketplace-plugin-scaffold/SKILL.md +87 -0
  245. package/plugins/pmcp/skills/package-skill-catalog/SKILL.md +51 -15
  246. package/plugins/pmcp/skills/pmcp-browser/SKILL.md +27 -0
  247. package/plugins/pmcp/skills/pmcp-desktop/SKILL.md +25 -0
  248. package/plugins/pmcp/skills/pmcp-project-init/SKILL.md +153 -0
  249. package/plugins/pmcp/skills/pmcp-sessions-and-git/SKILL.md +96 -0
  250. package/plugins/pmcp/skills/skill-package-scaffold/SKILL.md +89 -0
  251. package/schema/catalog-v1.json +187 -0
  252. package/schema/library.json +196 -0
  253. package/schema/marketplace-manifest.json +144 -0
  254. package/schema/plugin-manifest.json +59 -0
  255. package/schema/skill-frontmatter.json +170 -0
  256. package/schema/skill-metadata-core.json +131 -0
  257. package/skills/agent-assets-migrate/SKILL.md +96 -0
  258. package/skills/headless-agents-ci-scaffold/SKILL.md +101 -0
  259. package/skills/marketplace-plugin-scaffold/SKILL.md +87 -0
  260. package/skills/package-skill-catalog/SKILL.md +51 -15
  261. package/skills/pmcp-browser/SKILL.md +27 -0
  262. package/skills/pmcp-desktop/SKILL.md +25 -0
  263. package/skills/pmcp-project-init/SKILL.md +153 -0
  264. package/skills/pmcp-sessions-and-git/SKILL.md +96 -0
  265. package/skills/skill-package-scaffold/SKILL.md +89 -0
  266. package/dist/config-BkSpjUG6.d.ts +0 -50
  267. package/dist/embed-DRROSD3F.d.ts +0 -53
  268. package/dist/hook-spec-CSJJySsH.d.ts +0 -11
  269. package/dist/server-VWSY3Shw.d.ts +0 -543
  270. package/dist/tui-worker.js +0 -6549
  271. package/docs/manual-library-skills.md +0 -74
  272. /package/dist/{tui-worker.d.ts → hook.d.ts} +0 -0
@@ -0,0 +1,1934 @@
1
+ import {
2
+ assertNativeHost
3
+ } from "./chunk-LW4TG7EL.js";
4
+ import {
5
+ locateExecutable
6
+ } from "./chunk-R2GPCZUX.js";
7
+ import {
8
+ Connection,
9
+ LaunchJournal,
10
+ RecordStore,
11
+ artifact,
12
+ assertBridge,
13
+ assertProfileAvailable,
14
+ assertProfileIdentity,
15
+ assertProof,
16
+ assertResourceFresh,
17
+ assertResourceOwner,
18
+ bridgeDigest,
19
+ budgetSlice,
20
+ captureProfile,
21
+ configurationDigest,
22
+ containerEntrypoint,
23
+ containerLabels,
24
+ containerName,
25
+ controllerExited,
26
+ inspectResource,
27
+ launchJournals,
28
+ panePresent,
29
+ pendingLaunches,
30
+ prepareBridge,
31
+ processIdentity,
32
+ resourceAbsent,
33
+ resourceClaim,
34
+ resourceRunning,
35
+ runtimeUnit
36
+ } from "./chunk-7UCZAN4J.js";
37
+ import {
38
+ command
39
+ } from "./chunk-34DECPVC.js";
40
+ import {
41
+ GroupStore,
42
+ dockerPolicy,
43
+ privateJson,
44
+ profileName,
45
+ readPrivateJson,
46
+ selectedProfile
47
+ } from "./chunk-TVL5RTE6.js";
48
+ import {
49
+ id,
50
+ integer,
51
+ object,
52
+ strings,
53
+ text
54
+ } from "./chunk-5OMOPUE6.js";
55
+ import {
56
+ runtimeExecutables
57
+ } from "./chunk-BU65MNVU.js";
58
+
59
+ // src/harness/groups/service.ts
60
+ import { randomUUID as randomUUID2 } from "crypto";
61
+ import { realpathSync as realpathSync4, statSync, unlinkSync as unlinkSync2 } from "fs";
62
+ import { join as join9 } from "path";
63
+
64
+ // src/harness/adapters/terminal/lifecycle.ts
65
+ import { randomUUID } from "crypto";
66
+ import { existsSync as existsSync2 } from "fs";
67
+ import { setTimeout } from "timers/promises";
68
+ import { join as join5 } from "path";
69
+
70
+ // src/harness/adapters/systemd/units.ts
71
+ function unitActive(unit) {
72
+ if (process.platform !== "linux") return false;
73
+ let state;
74
+ try {
75
+ state = command("systemctl", [
76
+ "--user",
77
+ "show",
78
+ unit,
79
+ "--property=ActiveState",
80
+ "--value"
81
+ ]).trim();
82
+ } catch (error) {
83
+ const failure = error;
84
+ if (/not found|could not be found|No such/i.test(String(failure.stderr)))
85
+ return false;
86
+ throw error;
87
+ }
88
+ return ["active", "activating", "deactivating"].includes(state);
89
+ }
90
+ function stopUnit(unit) {
91
+ if (!unitActive(unit)) return;
92
+ try {
93
+ command("systemctl", ["--user", "stop", unit]);
94
+ } catch (error) {
95
+ const stderr = String(error.stderr);
96
+ if (!stderr.includes(unit) || !/not loaded|not found|could not be found/i.test(stderr))
97
+ throw error;
98
+ if (unitActive(unit)) throw error;
99
+ }
100
+ if (unitActive(unit)) throw new Error("runtime_stop_unconfirmed");
101
+ }
102
+
103
+ // src/harness/launch/recovery.ts
104
+ import { existsSync } from "fs";
105
+
106
+ // src/harness/adapters/docker/lifecycle.ts
107
+ function stopResource(resource) {
108
+ let actual;
109
+ try {
110
+ actual = inspectResource(resource, false);
111
+ } catch (error) {
112
+ if (resourceAbsent(error, resource.id)) return;
113
+ throw error;
114
+ }
115
+ const state = object(actual.State);
116
+ if (state.Running === true)
117
+ command("docker", ["stop", "--timeout", "2", resource.id]);
118
+ if (object(inspectResource(resource, false).State).Running !== false)
119
+ throw new Error("container_stop_unconfirmed");
120
+ if (resource.managed) {
121
+ command("docker", ["rm", resource.id]);
122
+ try {
123
+ inspectResource(resource, false);
124
+ } catch (error) {
125
+ if (resourceAbsent(error, resource.id)) return;
126
+ throw error;
127
+ }
128
+ throw new Error("container_removal_unconfirmed");
129
+ }
130
+ }
131
+
132
+ // src/harness/adapters/docker/creation.ts
133
+ import { mkdirSync } from "fs";
134
+ import { join as join4 } from "path";
135
+
136
+ // src/harness/adapters/docker/admission.ts
137
+ import { lstatSync as lstatSync3, realpathSync as realpathSync3 } from "fs";
138
+ import { join as join2, relative as relative2 } from "path";
139
+
140
+ // src/harness/adapters/docker/profile.ts
141
+ import { homedir } from "os";
142
+ import { lstatSync, realpathSync } from "fs";
143
+ import { relative } from "path";
144
+ function assertLocalDocker() {
145
+ if (process.env.DOCKER_HOST)
146
+ throw new Error("explicit_docker_host_not_admitted");
147
+ const endpoint = JSON.parse(
148
+ command("docker", [
149
+ "context",
150
+ "inspect",
151
+ "--format",
152
+ "{{json .Endpoints.docker.Host}}"
153
+ ])
154
+ );
155
+ if (new URL(endpoint).protocol !== "unix:")
156
+ throw new Error("remote_docker_context_not_admitted");
157
+ }
158
+ function loadDockerPolicy(path, projectRoot, runtimes) {
159
+ if (projectRoot === "/" || projectRoot === realpathSync(homedir()))
160
+ throw new Error("docker_project_root_too_broad");
161
+ const inputPath = text(path, "docker_policy_file");
162
+ if (lstatSync(inputPath).isSymbolicLink())
163
+ throw new Error("symlink_docker_policy_not_admitted");
164
+ const source = realpathSync(inputPath);
165
+ const scope = relative(projectRoot, source);
166
+ if (scope === ".." || scope.startsWith("../"))
167
+ throw new Error("docker_policy_outside_project");
168
+ const policy = dockerPolicy(readPrivateJson(source));
169
+ if (policy.privateProfiles) {
170
+ for (const [name, grant] of Object.entries(policy.privateProfiles)) {
171
+ if (!runtimes.includes(grant.runtime))
172
+ throw new Error("private_profile_runtime_not_granted");
173
+ policy.privateProfiles[name] = captureProfile(grant, projectRoot);
174
+ }
175
+ }
176
+ if (runtimes.some((runtime) => !policy.commands[runtime]))
177
+ throw new Error("docker_runtime_command_not_granted");
178
+ assertLocalDocker();
179
+ const images = JSON.parse(
180
+ command("docker", ["image", "inspect", policy.image])
181
+ );
182
+ if (!Array.isArray(images) || images.length !== 1 || images[0]?.Id !== policy.image)
183
+ throw new Error("docker_image_not_available");
184
+ return policy;
185
+ }
186
+
187
+ // src/harness/adapters/docker/mounts.ts
188
+ import { lstatSync as lstatSync2, realpathSync as realpathSync2 } from "fs";
189
+ import { join } from "path";
190
+ function assertContainerMounts(actual, statePath, projectRoot, directory, nonce, policy, privateProfile, runtime) {
191
+ const state = text(statePath, "container_state_directory");
192
+ const profile = selectedProfile(policy, privateProfile, runtime ?? "");
193
+ if (profile) assertProfileIdentity(profile, projectRoot);
194
+ const expected = profile?.directory ?? join(directory, "containers", nonce, "profile");
195
+ if (state !== expected || realpathSync2(state) !== expected)
196
+ throw new Error("foreign_container_state_directory");
197
+ const stat = lstatSync2(state);
198
+ if (!stat.isDirectory() || stat.uid !== process.getuid?.() || (stat.mode & 63) !== 0)
199
+ throw new Error("unsafe_container_state_directory");
200
+ if (!Array.isArray(actual.Mounts) || actual.Mounts.length !== 2)
201
+ throw new Error("ungranted_container_mount");
202
+ if (new Set(actual.Mounts.map((value) => object(value).Destination)).size !== 2)
203
+ throw new Error("ungranted_container_mount");
204
+ const expectedMounts = [
205
+ {
206
+ Source: projectRoot,
207
+ Destination: "/workspace",
208
+ RW: policy.workspaceAccess === "read-write"
209
+ },
210
+ { Source: state, Destination: "/state", RW: true }
211
+ ];
212
+ for (const value of actual.Mounts) {
213
+ const mount = object(value);
214
+ if (mount.Type !== "bind" || mount.Propagation !== "rprivate" || !expectedMounts.some(
215
+ (expected2) => mount.Source === expected2.Source && mount.Destination === expected2.Destination && mount.RW === expected2.RW
216
+ ))
217
+ throw new Error("ungranted_container_mount");
218
+ }
219
+ const host = object(actual.HostConfig);
220
+ if (!Array.isArray(host.Mounts) || host.Mounts.length !== 2 || host.Mounts.some(
221
+ (value) => object(object(value).BindOptions).NonRecursive !== true
222
+ ))
223
+ throw new Error("recursive_container_mount_not_admitted");
224
+ }
225
+
226
+ // src/harness/adapters/docker/security.ts
227
+ function assertContainerIsolation(host, network) {
228
+ if (host.ReadonlyRootfs !== true || host.Privileged !== false || host.NetworkMode !== network || host.CgroupnsMode !== "private")
229
+ throw new Error("invalid_container_isolation_policy");
230
+ if (JSON.stringify(host.CapDrop) !== '["ALL"]' || JSON.stringify(host.SecurityOpt) !== '["no-new-privileges"]' || object(host.RestartPolicy).Name !== "no")
231
+ throw new Error("invalid_container_execution_policy");
232
+ if (host.CapAdd !== null || host.PidMode !== "" || host.UTSMode !== "" || host.UsernsMode !== "" || host.CgroupParent !== "" || host.IpcMode !== "private" || hasDevices(host.Devices) || hasDevices(host.DeviceRequests) || host.AutoRemove !== false || host.VolumesFrom !== null || host.GroupAdd !== null || host.Binds !== null || Object.keys(object(host.PortBindings)).length)
233
+ throw new Error("ungranted_container_host_authority");
234
+ }
235
+ function hasDevices(value) {
236
+ if (value === null) return false;
237
+ return !Array.isArray(value) || value.length !== 0;
238
+ }
239
+
240
+ // src/harness/adapters/docker/admission.ts
241
+ function admitResource(path, group, role, directory, memoryMb, runtime) {
242
+ if (group.profile !== "docker" || !group.dockerPolicy)
243
+ throw new Error("container_requires_docker_profile");
244
+ const { projectRoot } = group;
245
+ assertLocalDocker();
246
+ const inputPath = text(path, "container_file");
247
+ if (lstatSync3(inputPath).isSymbolicLink())
248
+ throw new Error("symlink_container_file_not_admitted");
249
+ const source = realpathSync3(inputPath);
250
+ const scope = relative2(projectRoot, source);
251
+ if (scope === ".." || scope.startsWith("../"))
252
+ throw new Error("container_file_outside_project");
253
+ const claim = object(readPrivateJson(source));
254
+ if (claim.privateProfile !== void 0)
255
+ throw new Error("private_profile_requires_cli_owned_creation");
256
+ return admitClaim(claim, group, role, directory, memoryMb, runtime);
257
+ }
258
+ function admitClaim(value, group, role, directory, memoryMb, runtime, cwd = group.projectRoot) {
259
+ if (group.profile !== "docker" || !group.dockerPolicy)
260
+ throw new Error("container_requires_docker_profile");
261
+ assertLocalDocker();
262
+ const policy = group.dockerPolicy;
263
+ const { owner, projectRoot } = group;
264
+ const claim = object(value);
265
+ if (claim.owner !== owner || claim.role !== role || claim.runtime !== runtime)
266
+ throw new Error("foreign_container_resource");
267
+ const resource = {
268
+ kind: "docker",
269
+ id: text(claim.id, "container_id"),
270
+ owner,
271
+ nonce: text(claim.nonce, "container_nonce"),
272
+ role,
273
+ image: text(claim.image, "container_image"),
274
+ configurationDigest: "",
275
+ memoryMb: 0,
276
+ cpuQuota: 0,
277
+ ...claim.privateProfile === void 0 ? {} : { privateProfile: profileName(claim.privateProfile) }
278
+ };
279
+ if (!/^[a-f0-9]{64}$/.test(resource.id) || !/^sha256:[a-f0-9]{64}$/.test(resource.image) || !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(
280
+ resource.nonce
281
+ ))
282
+ throw new Error("invalid_container_resource");
283
+ const actual = inspectResource(resource, false);
284
+ const state = object(actual.State);
285
+ const config = object(actual.Config);
286
+ const host = object(actual.HostConfig);
287
+ if (resource.image !== policy.image || JSON.stringify(config.Entrypoint) !== JSON.stringify(
288
+ containerEntrypoint(
289
+ policy,
290
+ runtime,
291
+ resource.nonce,
292
+ resource.privateProfile
293
+ )
294
+ ))
295
+ throw new Error("container_runtime_image_not_granted");
296
+ if (config.WorkingDir !== join2("/workspace", relative2(projectRoot, cwd)))
297
+ throw new Error("container_cwd_not_granted");
298
+ assertContainerMounts(
299
+ actual,
300
+ claim.state,
301
+ projectRoot,
302
+ directory,
303
+ resource.nonce,
304
+ policy,
305
+ resource.privateProfile,
306
+ runtime
307
+ );
308
+ if (state.Status !== "created" || state.Pid !== 0 || state.Running !== false)
309
+ throw new Error("container_requires_fresh_creation");
310
+ if (config.User !== `${process.getuid?.()}:${process.getgid?.()}` || config.Tty !== true || config.OpenStdin !== true || config.StdinOnce !== false || !Array.isArray(config.Env) || JSON.stringify(
311
+ config.Env.filter(
312
+ (value2) => typeof value2 === "string" && value2.startsWith("HOME=")
313
+ )
314
+ ) !== '["HOME=/state"]')
315
+ throw new Error("invalid_container_terminal_policy");
316
+ assertContainerIsolation(host, policy.network);
317
+ resource.memoryMb = integer(
318
+ Number(host.Memory) / 1048576,
319
+ "container_memory",
320
+ 32,
321
+ 1472
322
+ );
323
+ if (host.MemorySwap !== host.Memory || memoryMb - resource.memoryMb < 64)
324
+ throw new Error("container_proxy_memory_unreserved");
325
+ integer(host.PidsLimit, "container_tasks", 1, 128);
326
+ if (host.CpuPeriod !== 1e5)
327
+ throw new Error("invalid_container_cpu_period");
328
+ resource.cpuQuota = integer(host.CpuQuota, "container_cpu", 1, 5e4);
329
+ resource.configurationDigest = configurationDigest(actual);
330
+ return resource;
331
+ }
332
+
333
+ // src/harness/adapters/docker/engine.ts
334
+ import { request } from "http";
335
+ var DockerEngine = class {
336
+ async create(name, configuration) {
337
+ assertLocalDocker();
338
+ const endpoint = JSON.parse(
339
+ command("docker", [
340
+ "context",
341
+ "inspect",
342
+ "--format",
343
+ "{{json .Endpoints.docker.Host}}"
344
+ ])
345
+ );
346
+ const version = command("docker", [
347
+ "version",
348
+ "--format",
349
+ "{{.Server.APIVersion}}"
350
+ ]).trim();
351
+ if (!/^1\.\d+$/.test(version))
352
+ throw new Error("invalid_docker_api_version");
353
+ const payload = JSON.stringify(configuration);
354
+ return new Promise((resolve, reject) => {
355
+ const req = request(
356
+ {
357
+ socketPath: new URL(endpoint).pathname,
358
+ path: `/v${version}/containers/create?name=${encodeURIComponent(name)}`,
359
+ method: "POST",
360
+ headers: {
361
+ "Content-Type": "application/json",
362
+ "Content-Length": Buffer.byteLength(payload)
363
+ }
364
+ },
365
+ (response) => {
366
+ const chunks = [];
367
+ let bytes = 0;
368
+ response.on("data", (chunk) => {
369
+ bytes += chunk.length;
370
+ if (bytes > 65536) {
371
+ req.destroy(new Error("docker_response_too_large"));
372
+ return;
373
+ }
374
+ chunks.push(chunk);
375
+ });
376
+ response.once("error", reject);
377
+ response.once("end", () => {
378
+ if (response.statusCode !== 201) {
379
+ reject(new Error(`docker_create_status_${response.statusCode}`));
380
+ return;
381
+ }
382
+ try {
383
+ const id2 = text(
384
+ object(JSON.parse(Buffer.concat(chunks).toString("utf8"))).Id,
385
+ "container_id"
386
+ );
387
+ if (!/^[a-f0-9]{64}$/.test(id2))
388
+ throw new Error("invalid_container_id");
389
+ resolve(id2);
390
+ } catch (error) {
391
+ reject(error);
392
+ }
393
+ });
394
+ }
395
+ );
396
+ req.setTimeout(
397
+ 1e4,
398
+ () => req.destroy(new Error("docker_create_timeout"))
399
+ );
400
+ req.once("error", reject);
401
+ req.end(payload);
402
+ });
403
+ }
404
+ };
405
+
406
+ // src/harness/adapters/docker/creation-plan.ts
407
+ import { join as join3, relative as relative3 } from "path";
408
+ function creationPlan(group, directory, id2, nonce, role, runtime, cwd, preparation) {
409
+ if (group.profile !== "docker" || !group.dockerPolicy)
410
+ throw new Error("container_requires_docker_profile");
411
+ assertLocalDocker();
412
+ const policy = group.dockerPolicy;
413
+ const images = JSON.parse(
414
+ command("docker", ["image", "inspect", policy.image])
415
+ );
416
+ if (!Array.isArray(images) || images.length !== 1 || object(images[0]).Id !== policy.image)
417
+ throw new Error("docker_image_not_available");
418
+ const imageConfig = object(object(images[0]).Config);
419
+ const environment = imageConfig.Env;
420
+ if (!Array.isArray(environment) || environment.some((entry) => typeof entry !== "string"))
421
+ throw new Error("invalid_container_image_environment");
422
+ const profile = selectedProfile(policy, preparation.privateProfile, runtime);
423
+ if (profile) assertProfileAvailable(profile, group.projectRoot);
424
+ const state = profile?.directory ?? join3(directory, "containers", nonce, "profile");
425
+ return {
426
+ name: containerName(group.owner, id2),
427
+ nonce,
428
+ state,
429
+ ...preparation.privateProfile ? { privateProfile: preparation.privateProfile } : {},
430
+ ...policy.egress ? { egress: policy.egress } : {},
431
+ ...policy.egress?.bridgeExecutable ? { bridgeSha256: bridgeDigest() } : {},
432
+ configuration: {
433
+ Image: policy.image,
434
+ Entrypoint: containerEntrypoint(
435
+ policy,
436
+ runtime,
437
+ nonce,
438
+ preparation.privateProfile
439
+ ),
440
+ Cmd: preparation.args.length ? preparation.args : null,
441
+ WorkingDir: join3("/workspace", relative3(group.projectRoot, cwd)),
442
+ User: `${process.getuid?.()}:${process.getgid?.()}`,
443
+ Env: [
444
+ ...environment.filter(
445
+ (entry) => !/^(HOME|TERM|PMCP_HTTPS_PROXY_SOCKET)=/.test(entry)
446
+ ),
447
+ "HOME=/state",
448
+ "TERM=xterm-256color",
449
+ ...policy.egress ? [`PMCP_HTTPS_PROXY_SOCKET=/state/e${nonce.slice(0, 8)}`] : []
450
+ ],
451
+ Tty: true,
452
+ OpenStdin: true,
453
+ StdinOnce: false,
454
+ AttachStdin: false,
455
+ AttachStdout: true,
456
+ AttachStderr: true,
457
+ Labels: {
458
+ ...imageConfig.Labels ?? {},
459
+ [containerLabels.owner]: group.owner,
460
+ [containerLabels.nonce]: nonce,
461
+ [containerLabels.role]: role
462
+ },
463
+ HostConfig: {
464
+ NetworkMode: policy.network,
465
+ CgroupnsMode: "private",
466
+ ReadonlyRootfs: true,
467
+ CapDrop: ["ALL"],
468
+ SecurityOpt: ["no-new-privileges"],
469
+ Memory: preparation.memoryMb * 1048576,
470
+ MemorySwap: preparation.memoryMb * 1048576,
471
+ PidsLimit: 64,
472
+ CpuPeriod: 1e5,
473
+ CpuQuota: preparation.cpuQuota,
474
+ RestartPolicy: { Name: "no" },
475
+ LogConfig: { Type: "none" },
476
+ Tmpfs: { "/tmp": "rw,nosuid,noexec,size=16m" },
477
+ Mounts: [
478
+ {
479
+ Type: "bind",
480
+ Source: group.projectRoot,
481
+ Target: "/workspace",
482
+ ...policy.workspaceAccess === "read-only" ? { ReadOnly: true } : {},
483
+ BindOptions: { NonRecursive: true }
484
+ },
485
+ {
486
+ Type: "bind",
487
+ Source: state,
488
+ Target: "/state",
489
+ BindOptions: { NonRecursive: true }
490
+ }
491
+ ]
492
+ }
493
+ }
494
+ };
495
+ }
496
+ function assertCreationConfiguration(actual, creation) {
497
+ if (actual.Name !== `/${creation.name}`)
498
+ throw new Error("foreign_container_creation");
499
+ const expected = creation.configuration;
500
+ const config = object(actual.Config);
501
+ const host = object(actual.HostConfig);
502
+ for (const [key, value] of Object.entries(expected)) {
503
+ if (key === "HostConfig" || key === "Image") continue;
504
+ if (!matchesFields(config[key], value))
505
+ throw new Error(`container_creation_configuration_changed_${key}`);
506
+ }
507
+ for (const [key, value] of Object.entries(object(expected.HostConfig))) {
508
+ if (!matchesFields(host[key], value))
509
+ throw new Error(`container_creation_configuration_changed_${key}`);
510
+ }
511
+ }
512
+ function matchesFields(actual, expected) {
513
+ if (Array.isArray(expected))
514
+ return Array.isArray(actual) && actual.length === expected.length && expected.every((value2, index) => matchesFields(actual[index], value2));
515
+ if (expected === null || typeof expected !== "object")
516
+ return actual === expected;
517
+ if (actual === null || typeof actual !== "object" || Array.isArray(actual))
518
+ return false;
519
+ const value = actual;
520
+ return Object.entries(expected).every(
521
+ ([key, field]) => matchesFields(value[key], field)
522
+ );
523
+ }
524
+
525
+ // src/harness/adapters/docker/creation.ts
526
+ async function prepareCreation(journal) {
527
+ const intent = journal.intent();
528
+ const creation = intent.dockerCreation;
529
+ if (!creation) throw new Error("container_creation_missing");
530
+ const group = new GroupStore(join4(journal.records.directory, "group.json")).state.group;
531
+ const profile = selectedProfile(
532
+ group.dockerPolicy,
533
+ creation.privateProfile,
534
+ intent.runtime
535
+ );
536
+ if (profile) assertProfileAvailable(profile, group.projectRoot);
537
+ if (!profile) mkdirSync(creation.state, { recursive: true, mode: 448 });
538
+ prepareBridge(creation);
539
+ assertBridge(creation);
540
+ const id2 = await new DockerEngine().create(
541
+ creation.name,
542
+ creation.configuration
543
+ );
544
+ const current = new GroupStore(join4(journal.records.directory, "group.json")).state.group;
545
+ if (current.id !== intent.groupId || current.generation !== intent.generation)
546
+ throw new Error("launch_group_generation_mismatch");
547
+ const resource = {
548
+ ...admitClaim(
549
+ {
550
+ id: id2,
551
+ owner: intent.owner,
552
+ role: intent.role,
553
+ runtime: intent.runtime,
554
+ image: current.dockerPolicy?.image,
555
+ nonce: creation.nonce,
556
+ state: creation.state,
557
+ ...creation.privateProfile ? { privateProfile: creation.privateProfile } : {}
558
+ },
559
+ current,
560
+ intent.role,
561
+ journal.records.directory,
562
+ intent.memoryMb,
563
+ intent.runtime,
564
+ intent.cwd
565
+ ),
566
+ managed: true
567
+ };
568
+ assertCreationConfiguration(
569
+ object(JSON.parse(command("docker", ["inspect", id2]))[0]),
570
+ creation
571
+ );
572
+ privateJson(journal.path("intent"), {
573
+ ...intent,
574
+ resource,
575
+ argv: [intent.argv[0], "start", "--attach", "--interactive", id2]
576
+ });
577
+ return resource;
578
+ }
579
+ function findCreation(journal) {
580
+ const intent = journal.intent();
581
+ const creation = intent.dockerCreation;
582
+ if (!creation) return intent.resource;
583
+ assertLocalDocker();
584
+ let actual;
585
+ try {
586
+ const values = JSON.parse(
587
+ command("docker", ["inspect", creation.name])
588
+ );
589
+ if (!Array.isArray(values) || values.length !== 1)
590
+ throw new Error("invalid_container_inspection");
591
+ actual = object(values[0]);
592
+ } catch (error) {
593
+ if (resourceAbsent(error, creation.name)) return;
594
+ throw error;
595
+ }
596
+ const resource = {
597
+ kind: "docker",
598
+ id: text(actual.Id, "container_id"),
599
+ owner: intent.owner,
600
+ nonce: creation.nonce,
601
+ role: intent.role,
602
+ image: text(creation.configuration.Image, "container_image"),
603
+ configurationDigest: configurationDigest(actual),
604
+ memoryMb: Number(object(actual.HostConfig).Memory) / 1048576,
605
+ cpuQuota: Number(object(actual.HostConfig).CpuQuota),
606
+ managed: true,
607
+ ...creation.privateProfile ? { privateProfile: creation.privateProfile } : {}
608
+ };
609
+ assertResourceOwner(resource, actual);
610
+ assertCreationConfiguration(actual, creation);
611
+ if (!intent.resource) {
612
+ const group = new GroupStore(join4(journal.records.directory, "group.json")).state.group;
613
+ return {
614
+ ...admitClaim(
615
+ { ...resource, runtime: intent.runtime, state: creation.state },
616
+ group,
617
+ intent.role,
618
+ journal.records.directory,
619
+ intent.memoryMb,
620
+ intent.runtime,
621
+ intent.cwd
622
+ ),
623
+ managed: true
624
+ };
625
+ }
626
+ if (intent.resource && (resource.id !== intent.resource.id || resource.configurationDigest !== intent.resource.configurationDigest))
627
+ throw new Error("container_creation_configuration_changed");
628
+ return resource;
629
+ }
630
+
631
+ // src/harness/launch/recovery.ts
632
+ function abortLaunch(connection, journal) {
633
+ const intent = journal.intent();
634
+ if (!controllerExited(intent.controllerIdentity))
635
+ throw new Error("launch_controller_alive");
636
+ const previous = journal.abortRecord();
637
+ const resource = intent.dockerCreation ? findCreation(journal) : intent.resource;
638
+ if (previous?.state === "stopped") {
639
+ if (resource) stopResource(resource);
640
+ if (unitActive(intent.unit)) throw new Error("runtime_stop_unconfirmed");
641
+ return {
642
+ stopped: true,
643
+ alreadyStopped: true,
644
+ adopted: false,
645
+ inputReplayed: false
646
+ };
647
+ }
648
+ if (!existsSync(journal.path("proof"))) {
649
+ const named = () => (connection.must({ op: "list" })["sessions"] ?? []).some((s) => s["name"] === `pmcp-${intent.id}`);
650
+ const paneUnknown = connection.alive() && (!intent.dockerCreation || named());
651
+ if (paneUnknown || unitActive(intent.unit))
652
+ throw new Error("launch_identity_unknown");
653
+ if (resource) stopResource(resource);
654
+ privateJson(journal.path("aborted"), {
655
+ id: intent.id,
656
+ owner: intent.owner,
657
+ state: "stopped",
658
+ noRuntimeBorn: true
659
+ });
660
+ return { stopped: true, adopted: false, inputReplayed: false };
661
+ }
662
+ const proof = journal.proof();
663
+ const present = panePresent(connection, proof);
664
+ if (present) assertProof(connection, proof);
665
+ if (resource) stopResource(resource);
666
+ privateJson(journal.path("aborted"), {
667
+ id: intent.id,
668
+ owner: intent.owner,
669
+ state: "stopping"
670
+ });
671
+ stopUnit(intent.unit);
672
+ if (present) {
673
+ assertProof(connection, proof);
674
+ connection.must({
675
+ op: "kill",
676
+ id: proof.session.ptySession,
677
+ expect: connection.expect(proof.session)
678
+ });
679
+ }
680
+ if (existsSync(journal.records.path(intent.id)))
681
+ journal.records.save({
682
+ ...proof.session,
683
+ stoppedAt: (/* @__PURE__ */ new Date()).toISOString()
684
+ });
685
+ privateJson(journal.path("aborted"), {
686
+ id: intent.id,
687
+ owner: intent.owner,
688
+ state: "stopped"
689
+ });
690
+ return { stopped: true, adopted: false, inputReplayed: false };
691
+ }
692
+
693
+ // src/harness/adapters/terminal/lifecycle.ts
694
+ async function start(connection, spec) {
695
+ const records = connection.records;
696
+ if (spec.budgetSlice !== budgetSlice(records.owner))
697
+ throw new Error("foreign_budget_slice");
698
+ integer(spec.memoryMb, "session_memory", 32, 1536);
699
+ runtimeUnit(spec.groupId);
700
+ runtimeUnit(spec.generation);
701
+ if (spec.role !== "main" && spec.role !== "worker")
702
+ throw new Error("invalid_launch_role");
703
+ const id2 = randomUUID();
704
+ const nonce = randomUUID();
705
+ const journal = new LaunchJournal(records, id2);
706
+ const dockerCreation = spec.dockerPreparation ? creationPlan(
707
+ new GroupStore(join5(records.directory, "group.json")).state.group,
708
+ records.directory,
709
+ id2,
710
+ nonce,
711
+ spec.role,
712
+ spec.runtime,
713
+ spec.cwd,
714
+ spec.dockerPreparation
715
+ ) : void 0;
716
+ privateJson(journal.path("intent"), {
717
+ id: id2,
718
+ owner: records.owner,
719
+ controllerIdentity: processIdentity(process.pid),
720
+ groupId: spec.groupId,
721
+ generation: spec.generation,
722
+ role: spec.role,
723
+ nonce,
724
+ unit: runtimeUnit(id2),
725
+ slice: spec.budgetSlice,
726
+ socket: records.socket,
727
+ runtime: spec.runtime,
728
+ memoryMb: spec.memoryMb,
729
+ argv: spec.argv,
730
+ cwd: spec.cwd,
731
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
732
+ ...spec.resource ? { resource: spec.resource } : {},
733
+ ...dockerCreation ? { dockerCreation } : {}
734
+ });
735
+ if (dockerCreation) await prepareCreation(journal);
736
+ const intent = journal.intent();
737
+ const gate = [
738
+ process.execPath,
739
+ artifact("launch-gate"),
740
+ records.directory,
741
+ id2
742
+ ];
743
+ const argv = process.platform === "linux" ? [
744
+ "systemd-run",
745
+ "--user",
746
+ "--scope",
747
+ "--collect",
748
+ "--quiet",
749
+ `--unit=${intent.unit}`,
750
+ `--slice=${intent.slice}`,
751
+ `--property=MemoryMax=${spec.memoryMb - (intent.resource?.memoryMb ?? 0)}M`,
752
+ "--property=TasksMax=128",
753
+ "--property=CPUQuota=100%",
754
+ ...gate
755
+ ] : gate;
756
+ connection.ensure();
757
+ connection.must(
758
+ spawnRequest(connection, id2, nonce, argv, spec.cwd, spec.runtime)
759
+ );
760
+ const deadline = Date.now() + 5e3;
761
+ while (!existsSync2(journal.path("proof"))) {
762
+ if (Date.now() >= deadline) throw new Error("launch_proof_timeout");
763
+ await setTimeout(25);
764
+ }
765
+ const proof = journal.proof();
766
+ assertProof(connection, proof);
767
+ records.save(proof.session);
768
+ return proof.session;
769
+ }
770
+ function spawnRequest(connection, id2, nonce, argv, cwd, runtime) {
771
+ return {
772
+ op: "spawn",
773
+ name: `pmcp-${id2}`,
774
+ argv,
775
+ cwd,
776
+ cols: 160,
777
+ rows: 42,
778
+ profile: profileOf(runtime),
779
+ env: { PMCP_PTY_BIN: connection.binary() },
780
+ labels: {
781
+ "pmcp.owner": connection.records.owner,
782
+ "pmcp.session": id2,
783
+ "pmcp.launch": nonce
784
+ }
785
+ };
786
+ }
787
+ function stop(connection, id2) {
788
+ const journal = new LaunchJournal(connection.records, id2);
789
+ if (existsSync2(journal.path("intent"))) {
790
+ abortLaunch(connection, journal);
791
+ return;
792
+ }
793
+ const record = connection.inspect(id2);
794
+ if (record.resource) stopResource(record.resource);
795
+ stopUnit(record.unit);
796
+ connection.inspect(id2);
797
+ connection.must({
798
+ op: "kill",
799
+ id: record.ptySession,
800
+ expect: connection.expect(record)
801
+ });
802
+ connection.records.save({ ...record, stoppedAt: (/* @__PURE__ */ new Date()).toISOString() });
803
+ }
804
+ function cleanup(connection) {
805
+ for (const journal of pendingLaunches(connection.records))
806
+ abortLaunch(connection, journal);
807
+ const records = connection.records.all();
808
+ if (connection.alive()) {
809
+ const listed = connection.must({ op: "list" });
810
+ const panes = (listed["sessions"] ?? []).map(
811
+ (s) => {
812
+ const tags = s["labels"] ?? {};
813
+ return `${tags["pmcp.owner"]}|${tags["pmcp.session"]}`;
814
+ }
815
+ );
816
+ if (panes.some(
817
+ (pane) => !records.some((record) => pane === `${record.owner}|${record.id}`)
818
+ ))
819
+ throw new Error("cleanup_foreign_pane");
820
+ for (const record of records) {
821
+ if (!record.stoppedAt) connection.inspect(record.id);
822
+ }
823
+ }
824
+ for (const record of records) {
825
+ if (record.resource) stopResource(record.resource);
826
+ if (record.stoppedAt || !existsSync2(
827
+ new LaunchJournal(connection.records, record.id).path("intent")
828
+ )) {
829
+ stopUnit(record.unit);
830
+ continue;
831
+ }
832
+ stop(connection, record.id);
833
+ }
834
+ if (connection.alive()) connection.call({ op: "shutdown" }, 3e4);
835
+ }
836
+ function profileOf(runtime) {
837
+ const profiles = {
838
+ "codex-cli": "codex",
839
+ "claude-code": "claude",
840
+ "gemini-cli": "gemini",
841
+ "grok-cli": "grok",
842
+ antigravity: "agy"
843
+ };
844
+ return profiles[runtime] ?? "default";
845
+ }
846
+
847
+ // src/harness/adapters/terminal/input.ts
848
+ import { closeSync, openSync, unlinkSync, writeFileSync } from "fs";
849
+ import { join as join6 } from "path";
850
+ function validateText(text3) {
851
+ if (typeof text3 !== "string" || Buffer.byteLength(text3) > 16384)
852
+ throw new Error("invalid_text");
853
+ if (/[\x00-\x08\x0b-\x1f\x7f]/.test(text3))
854
+ throw new Error("control_character_rejected");
855
+ if (/[\r\n\t]/.test(text3))
856
+ throw new Error("unqualified_terminal_control_input");
857
+ }
858
+ function delivered(reply) {
859
+ if (reply["ok"] !== true) {
860
+ const code = String(reply["code"] ?? "");
861
+ throw new Error(
862
+ code === "lease" ? "native_writer_active" : "delivery_uncertain"
863
+ );
864
+ }
865
+ if (reply["accepted"] === false) throw new Error("delivery_uncertain");
866
+ }
867
+ function write(connection, id2, text3, submit, lease) {
868
+ validateText(text3);
869
+ const session = connection.inspect(id2);
870
+ if (!session.alive) throw new Error("runtime_exited");
871
+ const lock = join6(connection.records.directory, `${id2}.input.lock`);
872
+ const descriptor = openSync(lock, "wx", 384);
873
+ try {
874
+ writeFileSync(
875
+ descriptor,
876
+ JSON.stringify({ id: id2, controller: processIdentity(process.pid) })
877
+ );
878
+ const expect = connection.expect(session, lease);
879
+ if (text3.length > 0 || submit)
880
+ delivered(
881
+ connection.call({
882
+ op: "write",
883
+ id: session.ptySession,
884
+ text: text3,
885
+ submit,
886
+ guard: "none",
887
+ expect
888
+ })
889
+ );
890
+ return {
891
+ id: id2,
892
+ verdict: "input_written",
893
+ submitted: submit,
894
+ processingConfirmed: false
895
+ };
896
+ } finally {
897
+ closeSync(descriptor);
898
+ unlinkSync(lock);
899
+ }
900
+ }
901
+ function interrupt(connection, id2, lease) {
902
+ const session = connection.inspect(id2);
903
+ if (!session.alive) throw new Error("runtime_exited");
904
+ const expect = connection.expect(session, lease);
905
+ delivered(
906
+ connection.call({ op: "key", id: session.ptySession, key: "C-c", expect })
907
+ );
908
+ }
909
+
910
+ // src/harness/adapters/terminal/read.ts
911
+ function read(connection, id2, options = {}) {
912
+ const lines = integer(options.lines ?? 100, "lines", 1, 2e3);
913
+ const maxBytes = integer(options.maxBytes ?? 16384, "max_bytes", 1, 65536);
914
+ const session = connection.inspect(id2);
915
+ let output;
916
+ if (options.alternate === true) {
917
+ const screen = connection.must({ op: "screen", id: session.ptySession });
918
+ output = (screen["rows"] ?? []).join("\n");
919
+ } else {
920
+ const tail = connection.must({
921
+ op: "tail",
922
+ id: session.ptySession,
923
+ bytes: 4 * maxBytes,
924
+ strip: true
925
+ });
926
+ output = String(tail["text"] ?? "").replace(/\r\n?/gu, "\n").split("\n").slice(-lines).join("\n");
927
+ }
928
+ const bytes = Buffer.from(output);
929
+ const truncated = bytes.length > maxBytes;
930
+ const content = truncated ? bytes.subarray(bytes.length - maxBytes).toString("utf8").replace(/^�+/, "") : output;
931
+ return { content, source: "terminal-screen", truncated };
932
+ }
933
+
934
+ // src/harness/adapters/terminal/backend.ts
935
+ var Backend = class {
936
+ constructor(recordStore) {
937
+ this.recordStore = recordStore;
938
+ this.connection = new Connection(recordStore);
939
+ this.owner = recordStore.owner;
940
+ this.socket = recordStore.socket;
941
+ this.runDirectory = recordStore.directory;
942
+ this.metadataPath = recordStore.metadataPath;
943
+ }
944
+ recordStore;
945
+ connection;
946
+ owner;
947
+ socket;
948
+ runDirectory;
949
+ metadataPath;
950
+ records() {
951
+ return this.recordStore.all();
952
+ }
953
+ start(spec) {
954
+ return start(this.connection, spec);
955
+ }
956
+ inspect(id2) {
957
+ return this.connection.inspect(id2);
958
+ }
959
+ read(id2, options) {
960
+ return read(this.connection, id2, options);
961
+ }
962
+ validateText(text3) {
963
+ validateText(text3);
964
+ }
965
+ write(id2, text3, options = {}) {
966
+ return write(
967
+ this.connection,
968
+ id2,
969
+ text3,
970
+ options.submit === true,
971
+ options.lease
972
+ );
973
+ }
974
+ interrupt(id2, lease) {
975
+ interrupt(this.connection, id2, lease);
976
+ }
977
+ stop(id2) {
978
+ stop(this.connection, id2);
979
+ }
980
+ cleanup() {
981
+ cleanup(this.connection);
982
+ }
983
+ attachers(id2) {
984
+ const session = this.inspect(id2);
985
+ const reply = this.connection.must({
986
+ op: "attachers",
987
+ id: session.ptySession
988
+ });
989
+ return (reply["attachers"] ?? []).map((a) => ({
990
+ pid: typeof a["pid"] === "number" ? a["pid"] : null,
991
+ readOnly: a["read_only"] === true
992
+ }));
993
+ }
994
+ detach(id2) {
995
+ const session = this.inspect(id2);
996
+ const reply = this.connection.must({
997
+ op: "detach",
998
+ id: session.ptySession
999
+ });
1000
+ return Number(reply["detached"] ?? 0);
1001
+ }
1002
+ // The harness lease mirrored into pmcp-pty, which then refuses input without its token.
1003
+ lease(id2, token, previous) {
1004
+ const session = this.inspect(id2);
1005
+ const request2 = token ? {
1006
+ op: "lease",
1007
+ id: session.ptySession,
1008
+ token,
1009
+ current: previous ?? token,
1010
+ ttl_ms: 9e4
1011
+ } : {
1012
+ op: "lease",
1013
+ id: session.ptySession,
1014
+ current: previous,
1015
+ release: true
1016
+ };
1017
+ this.connection.must(request2);
1018
+ }
1019
+ };
1020
+ function createBackend() {
1021
+ return new Backend(RecordStore.create());
1022
+ }
1023
+ function openBackend(directory) {
1024
+ return new Backend(new RecordStore(directory));
1025
+ }
1026
+ function assertOwnedRecords(backend) {
1027
+ backend.records();
1028
+ }
1029
+ function writableClients(backend, sessionId) {
1030
+ return backend.attachers(sessionId).filter((a) => !a.readOnly).length;
1031
+ }
1032
+
1033
+ // src/harness/adapters/systemd/budget.ts
1034
+ import { join as join7 } from "path";
1035
+ async function budgetOperation(directory, operation) {
1036
+ const backend = openBackend(directory);
1037
+ const path = join7(directory, "runtime-policy.json");
1038
+ const metadata = object(readPrivateJson(backend.metadataPath));
1039
+ const slice = budgetSlice(backend.owner);
1040
+ if (operation.action === "configure") {
1041
+ if (metadata.budgetSlice || backend.records().length)
1042
+ throw new Error("budget_already_initialized");
1043
+ const memoryMb2 = integer(operation.memoryMb, "memory_budget", 128, 4096);
1044
+ const maxActive = integer(operation.maxActive, "max_active", 1, 5);
1045
+ privateJson(backend.metadataPath, { ...metadata, budgetSlice: slice });
1046
+ privateJson(path, { owner: backend.owner, slice, memoryMb: memoryMb2, maxActive });
1047
+ if (process.platform !== "linux") return { ok: true, memoryCapped: false };
1048
+ command("systemctl", ["--user", "start", slice]);
1049
+ command("systemctl", [
1050
+ "--user",
1051
+ "set-property",
1052
+ "--runtime",
1053
+ slice,
1054
+ `MemoryMax=${memoryMb2}M`,
1055
+ `MemoryHigh=${Math.floor(memoryMb2 * 0.8)}M`,
1056
+ "TasksMax=256",
1057
+ "CPUQuota=100%"
1058
+ ]);
1059
+ return { ok: true };
1060
+ }
1061
+ const policy = object(readPrivateJson(path));
1062
+ if (policy.owner !== backend.owner || metadata.budgetSlice !== slice || policy.slice !== slice)
1063
+ throw new Error("foreign_budget_policy");
1064
+ if (operation.action === "cleanup") {
1065
+ backend.cleanup();
1066
+ if (process.platform === "linux") {
1067
+ command("systemctl", ["--user", "stop", slice]);
1068
+ command("systemctl", ["--user", "revert", slice]);
1069
+ }
1070
+ return { ok: true, budgetStopped: true };
1071
+ }
1072
+ if (operation.action === "stop") {
1073
+ backend.stop(text(operation.id, "session_id"));
1074
+ return { ok: true, stopped: true };
1075
+ }
1076
+ if (operation.action !== "start") throw new Error("invalid_budget_operation");
1077
+ const active = backend.records().filter((record) => {
1078
+ if (record.resource && resourceRunning(record.resource) && !backend.inspect(record.id).alive)
1079
+ throw new Error("container_running_without_proxy");
1080
+ if (record.stoppedAt) {
1081
+ if (unitActive(record.unit)) throw new Error("runtime_stop_unconfirmed");
1082
+ return false;
1083
+ }
1084
+ const observation = backend.inspect(record.id);
1085
+ if (!observation.alive && unitActive(record.unit))
1086
+ throw new Error("runtime_lifecycle_uncertain");
1087
+ return observation.alive;
1088
+ });
1089
+ if (active.length >= integer(policy.maxActive, "max_active", 1, 5))
1090
+ throw new Error("runtime_capacity_exceeded");
1091
+ const spec = object(operation.spec);
1092
+ const memoryMb = integer(spec.memoryMb, "session_memory", 32, 1536);
1093
+ const resource = spec.resource === void 0 ? void 0 : resourceClaim(spec.resource, backend.owner);
1094
+ const dockerPreparation = spec.dockerPreparation;
1095
+ const cpuQuota = resource?.cpuQuota ?? dockerPreparation?.cpuQuota;
1096
+ if (cpuQuota !== void 0) {
1097
+ const reservedCpu = backend.records().filter((record) => !record.stoppedAt).reduce((total, record) => total + (record.resource?.cpuQuota ?? 0), 0);
1098
+ if (reservedCpu + cpuQuota > 5e4)
1099
+ throw new Error("aggregate_container_cpu_budget_exceeded");
1100
+ }
1101
+ if (active.reduce((total, session2) => total + session2.memoryMb, 0) + memoryMb > integer(policy.memoryMb, "memory_budget", 128, 4096))
1102
+ throw new Error("aggregate_memory_budget_exceeded");
1103
+ if (resource || dockerPreparation)
1104
+ command("systemctl", [
1105
+ "--user",
1106
+ "set-property",
1107
+ "--runtime",
1108
+ slice,
1109
+ "CPUQuota=50%"
1110
+ ]);
1111
+ const session = await backend.start({
1112
+ runtime: text(spec.runtime, "runtime"),
1113
+ argv: spec.argv,
1114
+ cwd: text(spec.cwd, "cwd"),
1115
+ memoryMb,
1116
+ budgetSlice: slice,
1117
+ groupId: text(spec.groupId, "group_id"),
1118
+ generation: text(spec.generation, "generation"),
1119
+ role: spec.role,
1120
+ ...resource ? { resource } : {},
1121
+ ...dockerPreparation ? { dockerPreparation } : {}
1122
+ });
1123
+ return { ok: true, session };
1124
+ }
1125
+
1126
+ // src/harness/adapters/systemd/configure.ts
1127
+ import { execFileSync } from "child_process";
1128
+ import { join as join8 } from "path";
1129
+ function configureBudget(context, input) {
1130
+ const { store, backend } = context;
1131
+ assertOwnedRecords(backend);
1132
+ const group = store.state.group;
1133
+ const memoryMb = integer(
1134
+ input.memoryMb ?? group.memoryMb,
1135
+ "memory_budget",
1136
+ 128,
1137
+ 4096
1138
+ );
1139
+ const maxActive = integer(
1140
+ input.maxActive ?? group.maxActive,
1141
+ "max_active",
1142
+ 1,
1143
+ 5
1144
+ );
1145
+ const active = backend.records().filter((record) => !record.stoppedAt && backend.inspect(record.id).alive);
1146
+ if (active.length > maxActive)
1147
+ throw new Error("capacity_below_active_sessions");
1148
+ if (active.reduce((total, session) => total + session.memoryMb, 0) > memoryMb)
1149
+ throw new Error("budget_below_reserved_memory");
1150
+ const path = join8(backend.runDirectory, "runtime-policy.json");
1151
+ const policy = object(readPrivateJson(path));
1152
+ const metadata = object(readPrivateJson(backend.metadataPath));
1153
+ const slice = budgetSlice(backend.owner);
1154
+ if (policy.owner !== backend.owner || policy.slice !== slice || metadata.budgetSlice !== slice)
1155
+ throw new Error("foreign_budget_policy");
1156
+ execFileSync(
1157
+ "systemctl",
1158
+ [
1159
+ "--user",
1160
+ "set-property",
1161
+ "--runtime",
1162
+ slice,
1163
+ `MemoryMax=${memoryMb}M`,
1164
+ `MemoryHigh=${Math.floor(memoryMb * 0.8)}M`
1165
+ ],
1166
+ { timeout: 5e3 }
1167
+ );
1168
+ privateJson(path, {
1169
+ ...policy,
1170
+ memoryMb,
1171
+ maxActive,
1172
+ memoryHighMb: Math.floor(memoryMb * 0.8)
1173
+ });
1174
+ return { memoryMb, maxActive };
1175
+ }
1176
+
1177
+ // src/harness/groups/service.ts
1178
+ async function createGroup(input) {
1179
+ const projectRoot = realpathSync4(text(input.projectRoot, "project_root"));
1180
+ if (!statSync(projectRoot).isDirectory())
1181
+ throw new Error("invalid_project_root");
1182
+ const allowedRuntimes = strings(input.allowedRuntimes, "allowed_runtimes");
1183
+ const profile = input.profile ?? "native";
1184
+ if (profile !== "native" && profile !== "docker")
1185
+ throw new Error("invalid_profile");
1186
+ if (profile === "native" && input.dockerPolicyFile !== void 0)
1187
+ throw new Error("docker_policy_requires_docker_profile");
1188
+ const supported = Object.keys(runtimeExecutables);
1189
+ if (allowedRuntimes.some((runtime) => !supported.includes(runtime)))
1190
+ throw new Error("unsupported_runtime");
1191
+ const memoryMb = integer(input.memoryMb ?? 2048, "memory_budget", 128, 4096);
1192
+ const maxActive = integer(input.maxActive ?? 1, "max_active", 1, 5);
1193
+ const dockerPolicy2 = profile === "docker" ? loadDockerPolicy(input.dockerPolicyFile, projectRoot, allowedRuntimes) : void 0;
1194
+ assertNativeHost();
1195
+ const backend = createBackend();
1196
+ const group = {
1197
+ schemaVersion: 1,
1198
+ owner: backend.owner,
1199
+ id: randomUUID2(),
1200
+ generation: randomUUID2(),
1201
+ projectRoot,
1202
+ allowedRuntimes,
1203
+ profile,
1204
+ state: "ready",
1205
+ memoryMb,
1206
+ maxActive,
1207
+ sessions: [],
1208
+ ...dockerPolicy2 ? { dockerPolicy: dockerPolicy2 } : {}
1209
+ };
1210
+ const groupFile = join9(backend.runDirectory, "group.json");
1211
+ privateJson(groupFile, { group, leases: [], deliveries: [] });
1212
+ try {
1213
+ await budgetOperation(backend.runDirectory, {
1214
+ action: "configure",
1215
+ memoryMb,
1216
+ maxActive
1217
+ });
1218
+ } catch (error) {
1219
+ try {
1220
+ await budgetOperation(backend.runDirectory, { action: "cleanup" });
1221
+ unlinkSync2(groupFile);
1222
+ } catch (cleanupError) {
1223
+ privateJson(join9(backend.runDirectory, "initialization-failure.json"), {
1224
+ error: String(error),
1225
+ cleanupError: String(cleanupError),
1226
+ recoveryRequired: true
1227
+ });
1228
+ }
1229
+ throw error;
1230
+ }
1231
+ return { groupFile, group };
1232
+ }
1233
+ async function groupOperation(context, action, input = {}) {
1234
+ const { store, backend } = context;
1235
+ if (action === "inspect") return { group: store.state.group };
1236
+ if (action === "configure") {
1237
+ if (store.state.group.state === "stopped") throw new Error("group_stopped");
1238
+ if (input.profile !== void 0 || input.dockerPolicyFile !== void 0)
1239
+ throw new Error("profile_change_requires_new_group");
1240
+ const allowedRuntimes = input.allowedRuntimes === void 0 ? store.state.group.allowedRuntimes : strings(input.allowedRuntimes, "allowed_runtimes");
1241
+ if (allowedRuntimes.some(
1242
+ (runtime) => !store.state.group.allowedRuntimes.includes(runtime)
1243
+ ))
1244
+ throw new Error("runtime_grant_expansion_requires_new_group");
1245
+ Object.assign(store.state.group, configureBudget(context, input), {
1246
+ allowedRuntimes
1247
+ });
1248
+ store.save();
1249
+ return { group: store.state.group, nativePermissionsChanged: false };
1250
+ }
1251
+ if (action === "pause" || action === "resume") {
1252
+ if (store.state.group.state === "stopped") throw new Error("group_stopped");
1253
+ store.state.group.state = action === "pause" ? "paused" : "ready";
1254
+ store.save();
1255
+ return { group: store.state.group, runtimesInterrupted: false };
1256
+ }
1257
+ if (action !== "stop") throw new Error("unsupported_group_operation");
1258
+ if (store.state.group.state !== "stopped") {
1259
+ assertOwnedRecords(backend);
1260
+ await budgetOperation(backend.runDirectory, { action: "cleanup" });
1261
+ store.state.group.state = "stopped";
1262
+ store.state.leases = [];
1263
+ store.state.group.sessions.forEach((session) => {
1264
+ session.stopped = true;
1265
+ });
1266
+ store.save();
1267
+ }
1268
+ return { group: store.state.group, inputReplayed: false };
1269
+ }
1270
+
1271
+ // src/harness/application/effects.ts
1272
+ var observations = /* @__PURE__ */ new Set([
1273
+ "group:inspect",
1274
+ "session:list",
1275
+ "session:inspect",
1276
+ "session:read",
1277
+ "session:watch",
1278
+ "delivery:list",
1279
+ "delivery:inspect",
1280
+ "recovery:inspect",
1281
+ "attach:inspect"
1282
+ ]);
1283
+ function isReadOnly(operation) {
1284
+ if (operation.family === "attach" && operation.action === "open")
1285
+ return (operation.mode ?? "observe") === "observe";
1286
+ return observations.has(`${operation.family}:${operation.action}`);
1287
+ }
1288
+
1289
+ // src/harness/control/leases.ts
1290
+ import { randomUUID as randomUUID3 } from "crypto";
1291
+ import { join as join10 } from "path";
1292
+ function resolveLease(context, file, allowExpired = false) {
1293
+ const credential = object(readPrivateJson(file));
1294
+ const lease = context.store.state.leases.find(
1295
+ (entry) => entry.token === credential.token
1296
+ );
1297
+ if (!lease || lease.generation !== context.store.state.group.generation)
1298
+ throw new Error("stale_control");
1299
+ if (!Number.isFinite(Date.parse(lease.expiresAt)))
1300
+ throw new Error("invalid_control_expiry");
1301
+ if (!allowExpired && Date.parse(lease.expiresAt) <= Date.now())
1302
+ throw new Error("expired_control");
1303
+ context.store.session(lease.sessionId);
1304
+ context.backend.inspect(lease.sessionId);
1305
+ return lease;
1306
+ }
1307
+ function acquireControl(context, sessionId, controller, mode) {
1308
+ const { store, backend } = context;
1309
+ if (store.state.group.state === "stopped") throw new Error("group_stopped");
1310
+ store.session(sessionId);
1311
+ const observation = backend.inspect(sessionId);
1312
+ if (!observation.alive) throw new Error("runtime_exited");
1313
+ const current = store.state.leases.find(
1314
+ (entry) => entry.sessionId === sessionId
1315
+ );
1316
+ if (current && Date.parse(current.expiresAt) > Date.now())
1317
+ throw new Error("control_busy");
1318
+ if (writableClients(backend, sessionId) > 0)
1319
+ throw new Error("native_writer_active");
1320
+ if (mode !== "cli" && mode !== "native")
1321
+ throw new Error("invalid_control_mode");
1322
+ const lease = {
1323
+ token: randomUUID3(),
1324
+ sessionId,
1325
+ generation: store.state.group.generation,
1326
+ controller: id(controller, "controller"),
1327
+ mode,
1328
+ expiresAt: new Date(Date.now() + 6e4).toISOString()
1329
+ };
1330
+ store.state.leases = store.state.leases.filter(
1331
+ (entry) => entry.sessionId !== sessionId
1332
+ );
1333
+ store.state.leases.push(lease);
1334
+ backend.lease(sessionId, lease.token, current?.token);
1335
+ store.save();
1336
+ const leaseFile = join10(backend.runDirectory, `lease-${randomUUID3()}.json`);
1337
+ privateJson(leaseFile, { token: lease.token });
1338
+ return { sessionId, controller, mode, expiresAt: lease.expiresAt, leaseFile };
1339
+ }
1340
+ function controlOperation(context, action, leaseFile) {
1341
+ const lease = resolveLease(context, leaseFile, action === "release");
1342
+ if (action === "renew") {
1343
+ lease.expiresAt = new Date(Date.now() + 6e4).toISOString();
1344
+ context.backend.lease(lease.sessionId, lease.token);
1345
+ context.store.save();
1346
+ return { sessionId: lease.sessionId, expiresAt: lease.expiresAt };
1347
+ }
1348
+ if (action !== "release") throw new Error("unsupported_control_operation");
1349
+ if (writableClients(context.backend, lease.sessionId) > 0)
1350
+ throw new Error("native_writer_active");
1351
+ context.backend.lease(lease.sessionId, null, lease.token);
1352
+ context.store.state.leases = context.store.state.leases.filter(
1353
+ (entry) => entry.token !== lease.token
1354
+ );
1355
+ context.store.save();
1356
+ return { sessionId: lease.sessionId, released: true, inputReplayed: false };
1357
+ }
1358
+ function attachment(context, sessionId, mode, leaseFile) {
1359
+ context.store.session(sessionId);
1360
+ const session = context.backend.inspect(sessionId);
1361
+ if (!session.alive) throw new Error("runtime_exited");
1362
+ if (mode === "observe")
1363
+ return {
1364
+ socket: context.backend.socket,
1365
+ session: session.ptySession,
1366
+ readOnly: true
1367
+ };
1368
+ if (mode !== "write") throw new Error("invalid_attach_mode");
1369
+ const lease = resolveLease(context, text(leaseFile, "lease_file"));
1370
+ if (lease.sessionId !== sessionId || lease.mode !== "native")
1371
+ throw new Error("native_control_required");
1372
+ if (writableClients(context.backend, sessionId) > 0)
1373
+ throw new Error("native_writer_active");
1374
+ return {
1375
+ socket: context.backend.socket,
1376
+ session: session.ptySession,
1377
+ readOnly: false,
1378
+ lease: lease.token
1379
+ };
1380
+ }
1381
+
1382
+ // src/harness/delivery/service.ts
1383
+ import { createHash } from "crypto";
1384
+ function deliver(context, operation, leaseFile, requestId, text3) {
1385
+ const { store, backend } = context;
1386
+ const lease = resolveLease(context, leaseFile);
1387
+ if (lease.mode !== "cli") throw new Error("native_control_held");
1388
+ backend.inspect(lease.sessionId);
1389
+ if (writableClients(backend, lease.sessionId) > 0)
1390
+ throw new Error("native_writer_active");
1391
+ if (operation !== "write" && operation !== "submit")
1392
+ throw new Error("unsupported_input_operation");
1393
+ if (operation === "submit" && text3 !== "")
1394
+ throw new Error("submit_does_not_accept_text");
1395
+ backend.validateText(text3);
1396
+ if (/[\r\n\t]/.test(text3))
1397
+ throw new Error("unqualified_terminal_control_input");
1398
+ id(requestId, "request_id");
1399
+ const digest = createHash("sha256").update(
1400
+ JSON.stringify({
1401
+ operation,
1402
+ text: text3,
1403
+ sessionId: lease.sessionId,
1404
+ generation: lease.generation
1405
+ })
1406
+ ).digest("hex");
1407
+ const previous = store.state.deliveries.find(
1408
+ (entry) => entry.requestId === requestId
1409
+ );
1410
+ if (previous) {
1411
+ if (previous.digest !== digest) throw new Error("request_conflict");
1412
+ return {
1413
+ ...previous,
1414
+ ok: previous.state === "input_written",
1415
+ duplicate: true,
1416
+ resendAllowed: false,
1417
+ processingConfirmed: false
1418
+ };
1419
+ }
1420
+ if (store.state.deliveries.some(
1421
+ (entry) => entry.sessionId === lease.sessionId && entry.state !== "input_written"
1422
+ )) {
1423
+ throw new Error("session_delivery_uncertain");
1424
+ }
1425
+ const delivery = {
1426
+ controller: lease.controller,
1427
+ requestId,
1428
+ sessionId: lease.sessionId,
1429
+ generation: lease.generation,
1430
+ digest,
1431
+ operation,
1432
+ state: "intent"
1433
+ };
1434
+ store.state.deliveries.push(delivery);
1435
+ store.save();
1436
+ try {
1437
+ const receipt = backend.write(lease.sessionId, text3, {
1438
+ submit: operation === "submit",
1439
+ lease: lease.token
1440
+ });
1441
+ delivery.state = "input_written";
1442
+ store.save();
1443
+ return {
1444
+ ...receipt,
1445
+ requestId,
1446
+ generation: lease.generation,
1447
+ resendAllowed: false
1448
+ };
1449
+ } catch (error) {
1450
+ delivery.state = "delivery_uncertain";
1451
+ store.save();
1452
+ throw error;
1453
+ }
1454
+ }
1455
+ function interrupt2(context, leaseFile) {
1456
+ const lease = resolveLease(context, leaseFile);
1457
+ if (lease.mode !== "cli") throw new Error("native_control_held");
1458
+ context.backend.inspect(lease.sessionId);
1459
+ if (writableClients(context.backend, lease.sessionId) > 0)
1460
+ throw new Error("native_writer_active");
1461
+ context.backend.interrupt(lease.sessionId, lease.token);
1462
+ return {
1463
+ sessionId: lease.sessionId,
1464
+ signal: "terminal-interrupt",
1465
+ processingConfirmed: false
1466
+ };
1467
+ }
1468
+
1469
+ // src/harness/observation/options.ts
1470
+ function readOptions(input) {
1471
+ if (input === void 0) return {};
1472
+ const allowed = ["lines", "maxBytes", "alternate"];
1473
+ if (Object.keys(input).some((key) => !allowed.includes(key)))
1474
+ throw new Error("invalid_read_option");
1475
+ if (input.alternate !== void 0 && typeof input.alternate !== "boolean")
1476
+ throw new Error("invalid_alternate");
1477
+ return {
1478
+ ...input.lines === void 0 ? {} : { lines: integer(input.lines, "lines", 1, 2e3) },
1479
+ ...input.maxBytes === void 0 ? {} : { maxBytes: integer(input.maxBytes, "max_bytes", 1, 65536) },
1480
+ ...input.alternate === void 0 ? {} : { alternate: input.alternate }
1481
+ };
1482
+ }
1483
+
1484
+ // src/harness/observation/service.ts
1485
+ function listSessions(context) {
1486
+ const { store, backend } = context;
1487
+ const sessions = store.state.group.sessions.map((reference) => {
1488
+ if (reference.stopped) return { ...reference, observed: "stopped" };
1489
+ try {
1490
+ return {
1491
+ ...backend.inspect(reference.id),
1492
+ role: reference.role,
1493
+ observed: "terminal-process"
1494
+ };
1495
+ } catch (error) {
1496
+ return {
1497
+ ...reference,
1498
+ observed: "unavailable",
1499
+ reason: error instanceof Error ? error.message : "observation_failed"
1500
+ };
1501
+ }
1502
+ });
1503
+ return {
1504
+ generation: store.state.group.generation,
1505
+ sessions,
1506
+ providerStateInferred: false
1507
+ };
1508
+ }
1509
+ function observeSession(context, action, sessionId, input) {
1510
+ context.store.session(sessionId);
1511
+ if (action === "inspect") {
1512
+ return {
1513
+ session: context.backend.inspect(sessionId),
1514
+ providerStateInferred: false
1515
+ };
1516
+ }
1517
+ if (action !== "read") throw new Error("unsupported_observation_operation");
1518
+ return {
1519
+ sessionId,
1520
+ ...context.backend.read(sessionId, readOptions(input)),
1521
+ providerStateInferred: false
1522
+ };
1523
+ }
1524
+ function inspectDeliveries(context, requestId) {
1525
+ const deliveries = context.store.state.deliveries.filter(
1526
+ (entry) => !requestId || entry.requestId === requestId
1527
+ );
1528
+ if (requestId && deliveries.length === 0)
1529
+ throw new Error("request_not_found");
1530
+ return {
1531
+ generation: context.store.state.group.generation,
1532
+ deliveries,
1533
+ processingConfirmed: false
1534
+ };
1535
+ }
1536
+
1537
+ // src/harness/recovery/service.ts
1538
+ import { randomUUID as randomUUID4 } from "crypto";
1539
+
1540
+ // src/harness/adapters/process/recover-lock.ts
1541
+ import { existsSync as existsSync3, lstatSync as lstatSync4, unlinkSync as unlinkSync3 } from "fs";
1542
+ import { join as join11 } from "path";
1543
+ function recoverInputLock(backend, sessionId) {
1544
+ backend.inspect(sessionId);
1545
+ const path = join11(backend.runDirectory, `${sessionId}.input.lock`);
1546
+ if (!existsSync3(path)) return;
1547
+ const before = lstatSync4(path);
1548
+ const record = object(readPrivateJson(path));
1549
+ if (record.id !== sessionId) throw new Error("foreign_writer_lock");
1550
+ if (!controllerExited(text(record.controller, "controller_identity")))
1551
+ throw new Error("writer_still_alive");
1552
+ if (lstatSync4(path).ino !== before.ino)
1553
+ throw new Error("writer_lock_changed");
1554
+ unlinkSync3(path);
1555
+ }
1556
+
1557
+ // src/harness/sessions/service.ts
1558
+ import { realpathSync as realpathSync5 } from "fs";
1559
+ import { relative as relative4 } from "path";
1560
+
1561
+ // src/harness/launch/service.ts
1562
+ import { existsSync as existsSync4 } from "fs";
1563
+ function assertLaunchAdmission(records) {
1564
+ for (const journal of launchJournals(records)) {
1565
+ if (journal.abortRecord()?.state === "stopped" && unitActive(journal.intent().unit))
1566
+ throw new Error("runtime_stop_unconfirmed");
1567
+ }
1568
+ if (pendingLaunches(records).length)
1569
+ throw new Error("launch_requires_reconciliation");
1570
+ }
1571
+ function authorizeSession(context, sessionId) {
1572
+ const journal = new LaunchJournal(context.backend.recordStore, sessionId);
1573
+ if (journal.intent().controllerIdentity !== processIdentity(process.pid))
1574
+ throw new Error("foreign_launch_controller");
1575
+ assertProof(new Connection(context.backend.recordStore), journal.proof());
1576
+ const resource = journal.intent().resource;
1577
+ if (resource) assertResourceFresh(resource);
1578
+ journal.authorize();
1579
+ journal.commit();
1580
+ }
1581
+ function inspectPendingStarts(context) {
1582
+ return pendingLaunches(context.backend.recordStore).map((journal) => ({
1583
+ sessionId: journal.id,
1584
+ role: journal.intent().role,
1585
+ runtime: journal.intent().runtime,
1586
+ controllerExited: controllerExited(journal.intent().controllerIdentity),
1587
+ proofPresent: existsSync4(journal.path("proof")),
1588
+ recordPresent: existsSync4(journal.records.path(journal.id)),
1589
+ registered: context.store.state.group.sessions.some(
1590
+ (session) => session.id === journal.id
1591
+ ),
1592
+ authorizationPresent: existsSync4(journal.path("grant")),
1593
+ processingConfirmed: false,
1594
+ inputReplayed: false
1595
+ }));
1596
+ }
1597
+
1598
+ // src/harness/sessions/service.ts
1599
+ async function startSession(context, input) {
1600
+ const { store, backend } = context;
1601
+ const group = store.state.group;
1602
+ assertOwnedRecords(backend);
1603
+ assertLaunchAdmission(backend.recordStore);
1604
+ if (backend.records().some(
1605
+ (record) => !record.stoppedAt && !group.sessions.some((session2) => session2.id === record.id)
1606
+ )) {
1607
+ throw new Error("unregistered_session_requires_recovery");
1608
+ }
1609
+ if (group.state !== "ready") throw new Error("group_not_ready");
1610
+ const runtime = text(input.runtime, "runtime");
1611
+ if (!group.allowedRuntimes.includes(runtime))
1612
+ throw new Error("runtime_not_granted");
1613
+ const role = input.role;
1614
+ if (role !== "main" && role !== "worker") throw new Error("invalid_role");
1615
+ if (role === "main" && group.sessions.some(
1616
+ (session2) => session2.role === "main" && !session2.stopped
1617
+ )) {
1618
+ throw new Error("main_already_assigned");
1619
+ }
1620
+ if (role === "worker" && !group.sessions.some(
1621
+ (session2) => session2.role === "main" && !session2.stopped
1622
+ )) {
1623
+ throw new Error("main_required");
1624
+ }
1625
+ if (role === "worker") {
1626
+ const main = group.sessions.find(
1627
+ (session2) => session2.role === "main" && !session2.stopped
1628
+ );
1629
+ if (!backend.inspect(main.id).alive) throw new Error("main_unavailable");
1630
+ }
1631
+ const cwd = realpathSync5(text(input.cwd ?? group.projectRoot, "cwd"));
1632
+ const scope = relative4(group.projectRoot, cwd);
1633
+ if (scope === ".." || scope.startsWith("../"))
1634
+ throw new Error("cwd_outside_project");
1635
+ const memoryMb = integer(input.memoryMb ?? 384, "session_memory", 32, 1536);
1636
+ const executable = runtimeExecutables[runtime];
1637
+ if (!executable) throw new Error("unsupported_runtime");
1638
+ const args = input.args === void 0 || Array.isArray(input.args) && input.args.length === 0 ? [] : strings(input.args, "runtime_args");
1639
+ if (group.profile === "native" && input.containerFile !== void 0)
1640
+ throw new Error("container_requires_docker_profile");
1641
+ if (group.dockerPolicy?.egress && input.containerFile !== void 0)
1642
+ throw new Error("egress_requires_cli_owned_creation");
1643
+ const privateProfile = input.privateProfile === void 0 ? void 0 : profileName(input.privateProfile);
1644
+ if (privateProfile && (group.profile !== "docker" || input.containerFile !== void 0))
1645
+ throw new Error("private_profile_requires_cli_owned_creation");
1646
+ if (privateProfile) {
1647
+ const profile = selectedProfile(
1648
+ group.dockerPolicy,
1649
+ privateProfile,
1650
+ runtime
1651
+ );
1652
+ assertProfileAvailable(profile, group.projectRoot);
1653
+ }
1654
+ const resource = input.containerFile === void 0 ? void 0 : admitResource(
1655
+ input.containerFile,
1656
+ group,
1657
+ role,
1658
+ backend.runDirectory,
1659
+ memoryMb,
1660
+ runtime
1661
+ );
1662
+ if (resource && args.length)
1663
+ throw new Error("container_args_are_fixed_at_creation");
1664
+ if (resource && backend.records().some((record) => record.resource?.id === resource.id))
1665
+ throw new Error("container_already_bound");
1666
+ const profileOptions = privateProfile ? { privateProfile } : {};
1667
+ const dockerPreparation = group.profile === "docker" && !resource ? {
1668
+ args,
1669
+ memoryMb: integer(memoryMb - 64, "container_memory", 32, 1472),
1670
+ cpuQuota: integer(
1671
+ input.containerCpuQuota ?? Math.floor(5e4 / group.maxActive),
1672
+ "container_cpu",
1673
+ 1,
1674
+ 5e4
1675
+ ),
1676
+ ...profileOptions
1677
+ } : void 0;
1678
+ const executablePath = locateExecutable(
1679
+ resource || dockerPreparation ? "docker" : executable,
1680
+ cwd
1681
+ );
1682
+ if (!executablePath) throw new Error("runtime_executable_unavailable");
1683
+ const argv = resource ? [executablePath, "start", "--attach", "--interactive", resource.id] : [executablePath, ...args];
1684
+ const result = await budgetOperation(backend.runDirectory, {
1685
+ action: "start",
1686
+ spec: {
1687
+ runtime,
1688
+ argv,
1689
+ cwd,
1690
+ memoryMb,
1691
+ groupId: group.id,
1692
+ generation: group.generation,
1693
+ role,
1694
+ ...resource ? { resource } : {},
1695
+ ...dockerPreparation ? { dockerPreparation } : {}
1696
+ }
1697
+ });
1698
+ const session = result.session;
1699
+ group.sessions.push({ id: session.id, role, stopped: false });
1700
+ store.save();
1701
+ authorizeSession(context, session.id);
1702
+ return { session, role, generation: group.generation };
1703
+ }
1704
+ async function stopSession(context, sessionId) {
1705
+ const { store, backend } = context;
1706
+ store.session(sessionId);
1707
+ assertOwnedRecords(backend);
1708
+ const reference = store.state.group.sessions.find(
1709
+ (session) => session.id === sessionId
1710
+ );
1711
+ if (!reference.stopped) {
1712
+ await budgetOperation(backend.runDirectory, {
1713
+ action: "stop",
1714
+ id: sessionId
1715
+ });
1716
+ reference.stopped = true;
1717
+ store.state.leases = store.state.leases.filter(
1718
+ (lease) => lease.sessionId !== sessionId
1719
+ );
1720
+ store.save();
1721
+ }
1722
+ return { sessionId, stopped: true };
1723
+ }
1724
+
1725
+ // src/harness/recovery/service.ts
1726
+ function inspectRecovery(context, includeStarts = false) {
1727
+ const pendingStarts = includeStarts ? inspectPendingStarts(context) : [];
1728
+ return {
1729
+ ...listSessions(context),
1730
+ control: context.store.state.leases.map(({ token, ...lease }) => ({
1731
+ ...lease,
1732
+ expired: Date.parse(lease.expiresAt) <= Date.now()
1733
+ })),
1734
+ deliveries: context.store.state.deliveries,
1735
+ unregisteredOwnedSessions: context.backend.records().filter(
1736
+ (record) => !record.stoppedAt && !context.store.state.group.sessions.some(
1737
+ (session) => session.id === record.id
1738
+ )
1739
+ ).map((record) => ({ id: record.id, runtime: record.runtime })),
1740
+ inputReplayed: false,
1741
+ ...includeStarts ? { pendingStarts } : {}
1742
+ };
1743
+ }
1744
+ function abortStart(context, sessionId) {
1745
+ const records = context.backend.recordStore;
1746
+ const journal = new LaunchJournal(records, sessionId);
1747
+ if (!pendingLaunches(records).some((entry) => entry.id === sessionId) && !journal.abortRecord())
1748
+ throw new Error("start_already_committed");
1749
+ const result = abortLaunch(new Connection(records), journal);
1750
+ const reference = context.store.state.group.sessions.find(
1751
+ (session) => session.id === sessionId
1752
+ );
1753
+ if (reference) reference.stopped = true;
1754
+ context.store.state.leases = context.store.state.leases.filter(
1755
+ (lease) => lease.sessionId !== sessionId
1756
+ );
1757
+ context.store.save();
1758
+ return { ...result, sessionId };
1759
+ }
1760
+ function reconcile(context) {
1761
+ const { store, backend } = context;
1762
+ for (const delivery of store.state.deliveries) {
1763
+ if (delivery.state === "intent") delivery.state = "delivery_uncertain";
1764
+ }
1765
+ store.save();
1766
+ assertOwnedRecords(backend);
1767
+ for (const session of store.state.group.sessions) {
1768
+ if (!session.stopped) recoverInputLock(backend, session.id);
1769
+ }
1770
+ const retained = [];
1771
+ for (const lease of store.state.leases) {
1772
+ if (Date.parse(lease.expiresAt) > Date.now()) {
1773
+ retained.push(lease);
1774
+ continue;
1775
+ }
1776
+ if (writableClients(backend, lease.sessionId) > 0) {
1777
+ retained.push(lease);
1778
+ }
1779
+ }
1780
+ store.state.leases = retained;
1781
+ store.save();
1782
+ return inspectRecovery(context);
1783
+ }
1784
+ async function stopOrphan(context, sessionId) {
1785
+ if (context.store.state.group.sessions.some(
1786
+ (session) => session.id === sessionId
1787
+ ))
1788
+ throw new Error("session_is_registered");
1789
+ assertOwnedRecords(context.backend);
1790
+ context.backend.inspect(sessionId);
1791
+ await budgetOperation(context.backend.runDirectory, {
1792
+ action: "stop",
1793
+ id: sessionId
1794
+ });
1795
+ return { sessionId, stopped: true, adopted: false };
1796
+ }
1797
+ async function replaceMain(context, input) {
1798
+ const { store, backend } = context;
1799
+ const previous = store.state.group.sessions.find(
1800
+ (session) => session.role === "main" && !session.stopped
1801
+ );
1802
+ if (previous) {
1803
+ const observation = backend.inspect(previous.id);
1804
+ if (observation.alive) throw new Error("main_still_alive");
1805
+ previous.stopped = true;
1806
+ }
1807
+ store.state.group.generation = randomUUID4();
1808
+ store.state.leases = [];
1809
+ store.save();
1810
+ const result = await startSession(context, { ...input, role: "main" });
1811
+ return {
1812
+ ...result,
1813
+ previousMain: previous?.id ?? null,
1814
+ inputReplayed: false
1815
+ };
1816
+ }
1817
+
1818
+ // src/harness/application/context.ts
1819
+ import { dirname } from "path";
1820
+ function openGroup(path) {
1821
+ const store = new GroupStore(path);
1822
+ const backend = openBackend(dirname(store.path));
1823
+ if (store.state.group.owner !== backend.owner)
1824
+ throw new Error("foreign_group");
1825
+ return { store, backend };
1826
+ }
1827
+
1828
+ // src/harness/adapters/terminal/detach.ts
1829
+ function detachClients(context, sessionId) {
1830
+ context.store.session(sessionId);
1831
+ const detached = context.backend.detach(sessionId);
1832
+ return {
1833
+ sessionId,
1834
+ clientsDetached: true,
1835
+ detached,
1836
+ runtimeStopRequested: false
1837
+ };
1838
+ }
1839
+
1840
+ // src/harness/adapters/terminal/clients.ts
1841
+ function attachedClients(backend, sessionId) {
1842
+ const session = backend.inspect(sessionId);
1843
+ if (!session.alive) throw new Error("session_unavailable");
1844
+ return backend.attachers(sessionId);
1845
+ }
1846
+
1847
+ // src/harness/observation/attachments.ts
1848
+ function inspectAttachments(context, sessionId) {
1849
+ context.store.session(sessionId);
1850
+ return { sessionId, clients: attachedClients(context.backend, sessionId) };
1851
+ }
1852
+
1853
+ // src/harness/application/dispatch.ts
1854
+ async function runOperation(operation) {
1855
+ const context = openGroup(text(operation.groupFile, "group_file"));
1856
+ if (!isReadOnly(operation) && operation.generation !== context.store.state.group.generation) {
1857
+ throw new Error("stale_group_generation");
1858
+ }
1859
+ const { family, action } = operation;
1860
+ if (family === "group")
1861
+ return groupOperation(context, action, operation.input);
1862
+ if (family === "session") {
1863
+ if (action === "start")
1864
+ return startSession(context, object(operation.input));
1865
+ if (action === "list") return listSessions(context);
1866
+ const sessionId = text(operation.sessionId, "session_id");
1867
+ if (action === "stop") return stopSession(context, sessionId);
1868
+ return observeSession(context, action, sessionId, operation.input);
1869
+ }
1870
+ if (family === "control") {
1871
+ if (action === "acquire") {
1872
+ return acquireControl(
1873
+ context,
1874
+ text(operation.sessionId, "session_id"),
1875
+ text(operation.controller, "controller"),
1876
+ operation.mode ?? "cli"
1877
+ );
1878
+ }
1879
+ return controlOperation(
1880
+ context,
1881
+ action,
1882
+ text(operation.leaseFile, "lease_file")
1883
+ );
1884
+ }
1885
+ if (family === "input") {
1886
+ const leaseFile = text(operation.leaseFile, "lease_file");
1887
+ if (action === "interrupt") return interrupt2(context, leaseFile);
1888
+ return deliver(
1889
+ context,
1890
+ action,
1891
+ leaseFile,
1892
+ text(operation.requestId, "request_id"),
1893
+ operation.text ?? ""
1894
+ );
1895
+ }
1896
+ if (family === "attach") {
1897
+ if (action === "inspect")
1898
+ return inspectAttachments(
1899
+ context,
1900
+ text(operation.sessionId, "session_id")
1901
+ );
1902
+ if (action === "detach")
1903
+ return detachClients(context, text(operation.sessionId, "session_id"));
1904
+ return attachment(
1905
+ context,
1906
+ text(operation.sessionId, "session_id"),
1907
+ operation.mode ?? "observe",
1908
+ operation.leaseFile
1909
+ );
1910
+ }
1911
+ if (family === "delivery")
1912
+ return inspectDeliveries(context, operation.requestId);
1913
+ if (family === "recovery") {
1914
+ if (action === "abort-start")
1915
+ return abortStart(context, text(operation.sessionId, "session_id"));
1916
+ if (action === "inspect")
1917
+ return inspectRecovery(context, operation.includeStarts === true);
1918
+ if (action === "reconcile") return reconcile(context);
1919
+ if (action === "stop-orphan")
1920
+ return stopOrphan(context, text(operation.sessionId, "session_id"));
1921
+ if (action === "replace-main")
1922
+ return replaceMain(context, object(operation.input));
1923
+ }
1924
+ throw new Error("unsupported_operation");
1925
+ }
1926
+
1927
+ export {
1928
+ createGroup,
1929
+ openGroup,
1930
+ observeSession,
1931
+ isReadOnly,
1932
+ runOperation
1933
+ };
1934
+ //# sourceMappingURL=chunk-3IDXEV5E.js.map