@blackbelt-technology/pi-agent-dashboard 0.9.0 → 0.10.0

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 (439) hide show
  1. package/README.md +38 -5
  2. package/docs/architecture.md +1673 -75
  3. package/package.json +23 -15
  4. package/packages/extension/package.json +8 -8
  5. package/packages/extension/src/ask-user-tool.ts +65 -3
  6. package/packages/extension/src/auto-session-namer.ts +190 -50
  7. package/packages/extension/src/bridge-handlers/dispatch.ts +450 -0
  8. package/packages/extension/src/bridge-handlers/forwarders.ts +616 -0
  9. package/packages/extension/src/bridge-handlers/instance.ts +220 -0
  10. package/packages/extension/src/bridge-handlers/lifecycle.ts +1030 -0
  11. package/packages/extension/src/bridge-handlers/ui-prompt-patch.ts +198 -0
  12. package/packages/extension/src/bridge-identity-log.ts +45 -0
  13. package/packages/extension/src/bridge.ts +480 -2510
  14. package/packages/extension/src/command-handler.ts +180 -11
  15. package/packages/extension/src/connection.ts +265 -18
  16. package/packages/extension/src/dashboard-context-injector.ts +26 -47
  17. package/packages/extension/src/empty-actionable-guard.ts +8 -3
  18. package/packages/extension/src/flow-event-wiring.ts +1 -1
  19. package/packages/extension/src/followup-buffer.ts +1 -1
  20. package/packages/extension/src/followup-drain.ts +79 -0
  21. package/packages/extension/src/local-token-header.ts +161 -17
  22. package/packages/extension/src/message-update-coalescer.ts +3 -1
  23. package/packages/extension/src/model-refresh.ts +19 -0
  24. package/packages/extension/src/multiselect-list.ts +6 -2
  25. package/packages/extension/src/multiselect-polyfill.ts +2 -2
  26. package/packages/extension/src/openspec-cli-shim.ts +1 -1
  27. package/packages/extension/src/path-gate/decide.ts +15 -41
  28. package/packages/extension/src/path-gate/grant-cache.ts +3 -1
  29. package/packages/extension/src/path-gate/handler.ts +51 -2
  30. package/packages/extension/src/path-gate/index.ts +12 -1
  31. package/packages/extension/src/path-gate/resolve.ts +6 -124
  32. package/packages/extension/src/path-gate/roots.ts +4 -1
  33. package/packages/extension/src/path-gate/suppression.ts +4 -1
  34. package/packages/extension/src/path-gate/yolo-link.ts +104 -0
  35. package/packages/extension/src/plugin-event-forward-registry.ts +200 -0
  36. package/packages/extension/src/project-trust.ts +119 -25
  37. package/packages/extension/src/prompt-expander.ts +5 -1
  38. package/packages/extension/src/prompt-meta.ts +64 -0
  39. package/packages/extension/src/provider-register.ts +87 -20
  40. package/packages/extension/src/role-manager.ts +5 -4
  41. package/packages/extension/src/server-auto-start.ts +12 -5
  42. package/packages/extension/src/server-launcher.ts +11 -13
  43. package/packages/extension/src/session-move.ts +19 -0
  44. package/packages/extension/src/session-sync.ts +31 -38
  45. package/packages/extension/src/spawn-token.ts +46 -0
  46. package/packages/extension/src/stream-forward-buffer.ts +161 -0
  47. package/packages/extension/src/subagent-frame-buffer.ts +6 -2
  48. package/packages/extension/src/subagent-tick-throttle.ts +3 -1
  49. package/packages/extension/src/vault-delivery.ts +394 -0
  50. package/packages/extension/src/vault-forwarder.ts +128 -0
  51. package/packages/extension/src/vault-masker.ts +165 -0
  52. package/packages/extension/src/vault-redaction.ts +181 -0
  53. package/packages/extension/src/vcs-info.ts +5 -2
  54. package/packages/server/bin/pi-dashboard.mjs +26 -89
  55. package/packages/server/package.json +29 -15
  56. package/packages/server/src/access/access-grants.ts +18 -0
  57. package/packages/server/src/access/agent-confirm-registry.ts +31 -13
  58. package/packages/server/src/access/agent-grant.ts +1 -1
  59. package/packages/server/src/access/agent-yolo.ts +91 -0
  60. package/packages/server/src/access/containment-gate.ts +28 -1
  61. package/packages/server/src/access/cwd-admission-log.ts +46 -0
  62. package/packages/server/src/access/cwd-verdict.ts +144 -0
  63. package/packages/server/src/access/grant-coordinator.ts +3 -1
  64. package/packages/server/src/access/pi-trust-mirror-service.ts +374 -0
  65. package/packages/server/src/access/planes.ts +10 -1
  66. package/packages/server/src/access/refusal-ledger.ts +6 -6
  67. package/packages/server/src/access/yolo-session.ts +73 -12
  68. package/packages/server/src/acp-bridge/acp-connection.ts +225 -0
  69. package/packages/server/src/acp-bridge/acp-restore.ts +41 -0
  70. package/packages/server/src/acp-bridge/acp-session-adapter.ts +544 -0
  71. package/packages/server/src/acp-bridge/child-env.ts +73 -0
  72. package/packages/server/src/acp-bridge/event-log.ts +194 -0
  73. package/packages/server/src/acp-bridge/gateway-client.ts +136 -0
  74. package/packages/server/src/acp-bridge/local-bridge-socket.ts +67 -0
  75. package/packages/server/src/acp-bridge/local-host.ts +132 -0
  76. package/packages/server/src/acp-bridge/main.ts +118 -0
  77. package/packages/server/src/acp-bridge/models.ts +33 -0
  78. package/packages/server/src/acp-bridge/permission-bridge.ts +106 -0
  79. package/packages/server/src/acp-bridge/server-requests.ts +136 -0
  80. package/packages/server/src/acp-bridge/session-state.ts +127 -0
  81. package/packages/server/src/addons/addon-toggle-restore.ts +110 -0
  82. package/packages/server/src/addons/addons-catalog.ts +408 -0
  83. package/packages/server/src/addons/addons-folder-service.ts +347 -0
  84. package/packages/server/src/addons/addons-folder.ts +310 -0
  85. package/packages/server/src/addons/addons-service.ts +470 -0
  86. package/packages/server/src/addons/package-contents.ts +99 -0
  87. package/packages/server/src/addons/settings-entries.ts +120 -0
  88. package/packages/server/src/attachments/fit-worker-pool.ts +12 -17
  89. package/packages/server/src/auth/approval-refusal.ts +87 -0
  90. package/packages/server/src/auth/auth-plugin.ts +292 -79
  91. package/packages/server/src/auth/auth.ts +78 -7
  92. package/packages/server/src/auth/bearer-auth.ts +23 -1
  93. package/packages/server/src/auth/cors-origin.ts +10 -0
  94. package/packages/server/src/auth/csp.ts +6 -0
  95. package/packages/server/src/auth/host-admission.ts +26 -0
  96. package/packages/server/src/auth/host-gate.ts +6 -1
  97. package/packages/server/src/auth/local-credential.ts +258 -0
  98. package/packages/server/src/auth/local-proof.ts +7 -4
  99. package/packages/server/src/auth/local-token.ts +16 -0
  100. package/packages/server/src/auth/localhost-guard.ts +251 -8
  101. package/packages/server/src/auth/network-trust-telemetry.ts +126 -0
  102. package/packages/server/src/auth/node-guard.ts +43 -0
  103. package/packages/server/src/auth/operate-required.ts +126 -0
  104. package/packages/server/src/auth/passkey/challenge-store.ts +90 -0
  105. package/packages/server/src/auth/passkey/passkey-log.ts +34 -0
  106. package/packages/server/src/auth/passkey/passkey-pages.ts +173 -0
  107. package/packages/server/src/auth/passkey/passkey-routes.ts +224 -0
  108. package/packages/server/src/auth/passkey/passkey-service.ts +247 -0
  109. package/packages/server/src/auth/passkey/phone-signin.ts +211 -0
  110. package/packages/server/src/auth/passkey/requester.ts +83 -0
  111. package/packages/server/src/auth/passkey/rp-context.ts +98 -0
  112. package/packages/server/src/auth/passkey/user-directory.ts +348 -0
  113. package/packages/server/src/auth/pi-legacy-credentials.ts +321 -0
  114. package/packages/server/src/auth/provider-auth-registry.ts +35 -1
  115. package/packages/server/src/auth/provider-auth-storage.ts +55 -8
  116. package/packages/server/src/auth/radius-override.ts +13 -0
  117. package/packages/server/src/auth/route-tier-gate.ts +27 -11
  118. package/packages/server/src/auth/runtime-provider-catalogue.ts +107 -0
  119. package/packages/server/src/auth/scan-legacy-provider-ids.ts +80 -0
  120. package/packages/server/src/auth/serve-app-host.ts +97 -0
  121. package/packages/server/src/auth/trust-mode-boot.ts +93 -0
  122. package/packages/server/src/auth/trust-mode.ts +83 -0
  123. package/packages/server/src/auto-name-outcome-store.ts +4 -1
  124. package/packages/server/src/browse.ts +114 -2
  125. package/packages/server/src/browser-handlers/acp-guard.ts +79 -0
  126. package/packages/server/src/browser-handlers/directory-handler.ts +128 -6
  127. package/packages/server/src/browser-handlers/session-action-handler.ts +129 -62
  128. package/packages/server/src/browser-handlers/session-meta-handler.ts +16 -6
  129. package/packages/server/src/browser-handlers/spawn-choice.ts +99 -0
  130. package/packages/server/src/cli.ts +883 -97
  131. package/packages/server/src/config-api.ts +143 -1
  132. package/packages/server/src/config-snapshot.ts +5 -0
  133. package/packages/server/src/directory-service.ts +435 -32
  134. package/packages/server/src/embed-lifecycle/caps.ts +35 -4
  135. package/packages/server/src/embed-lifecycle/embed-lifecycle-controller.ts +45 -4
  136. package/packages/server/src/embed-lifecycle/idle-reaper.ts +195 -20
  137. package/packages/server/src/embed-lifecycle/lifecycle-metrics.ts +38 -0
  138. package/packages/server/src/embed-lifecycle/plugin-session-close.ts +123 -0
  139. package/packages/server/src/embed-lifecycle/quiescence.ts +29 -3
  140. package/packages/server/src/embed-lifecycle/reclaim-give-up.ts +54 -0
  141. package/packages/server/src/event-wiring.ts +208 -35
  142. package/packages/server/src/file-watch-manager.ts +187 -39
  143. package/packages/server/src/git-worktree/git-operations.ts +16 -5
  144. package/packages/server/src/git-worktree/worktree-init-trust.ts +48 -5
  145. package/packages/server/src/git-worktree/worktree-init.ts +7 -56
  146. package/packages/server/src/identity/host-resources.ts +3 -0
  147. package/packages/server/src/identity/http-road-classification.ts +18 -0
  148. package/packages/server/src/identity/identity-registration-tracker.ts +4 -1
  149. package/packages/server/src/identity/plugin-identity.ts +19 -0
  150. package/packages/server/src/identity/policy-registry.ts +4 -1
  151. package/packages/server/src/identity/resolver-registry.ts +12 -3
  152. package/packages/server/src/identity/ws-message-scope.ts +9 -0
  153. package/packages/server/src/identity/ws-road-classification.ts +9 -0
  154. package/packages/server/src/known-server-moves.ts +175 -0
  155. package/packages/server/src/lib/browse-roots.ts +36 -0
  156. package/packages/server/src/lib/digest-gate.ts +82 -0
  157. package/packages/server/src/lib/file-write-lock.ts +24 -0
  158. package/packages/server/src/lib/folder-project.ts +439 -0
  159. package/packages/server/src/lib/purify.ts +13 -5
  160. package/packages/server/src/lib/writable-handler-target.ts +66 -0
  161. package/packages/server/src/lib/writable-md-target.ts +12 -1
  162. package/packages/server/src/lifecycle/classify-dashboard-port.ts +134 -0
  163. package/packages/server/src/lifecycle/home-lock.ts +344 -130
  164. package/packages/server/src/lifecycle/home-rendezvous.ts +41 -11
  165. package/packages/server/src/lifecycle/recovery-server.ts +77 -1
  166. package/packages/server/src/lifecycle/stop-ownership.ts +97 -11
  167. package/packages/server/src/live-server/live-capability.ts +254 -0
  168. package/packages/server/src/live-server/live-server-proxy.ts +173 -26
  169. package/packages/server/src/metrics/eventloop-spike-metrics.ts +2 -2
  170. package/packages/server/src/model-proxy/internal-auth-storage.ts +27 -26
  171. package/packages/server/src/model-proxy/internal-registry.ts +6 -0
  172. package/packages/server/src/model-proxy/server-model-runtime.ts +6 -0
  173. package/packages/server/src/openspec/openspec-change-watcher.ts +109 -16
  174. package/packages/server/src/openspec/openspec-poll-fs-helpers.ts +132 -0
  175. package/packages/server/src/openspec/openspec-poll-worker-pool.ts +90 -35
  176. package/packages/server/src/openspec/openspec-poll-worker.ts +200 -44
  177. package/packages/server/src/openspec/proposal-attach-naming.ts +5 -3
  178. package/packages/server/src/openspec/readiness.ts +9 -0
  179. package/packages/server/src/openspec/workflow-schema.ts +1128 -0
  180. package/packages/server/src/package/installed-package-enricher.ts +38 -3
  181. package/packages/server/src/package/package-health-scanner.ts +133 -0
  182. package/packages/server/src/package/package-manager-wrapper.ts +18 -2
  183. package/packages/server/src/package/provider-catalogue-cache.ts +17 -3
  184. package/packages/server/src/package/provider-probe.ts +5 -3
  185. package/packages/server/src/pairing/browser-gateway.ts +108 -8
  186. package/packages/server/src/pairing/knock-admission.ts +277 -0
  187. package/packages/server/src/pairing/pairing.ts +154 -27
  188. package/packages/server/src/pairing/subagent-resync-routing.ts +4 -1
  189. package/packages/server/src/pairing/ws-tier-gate.ts +34 -0
  190. package/packages/server/src/peer-servers.ts +77 -0
  191. package/packages/server/src/pending/pending-plugin-ref-registry.ts +57 -2
  192. package/packages/server/src/persistence/boot-state.ts +48 -1
  193. package/packages/server/src/persistence/memory-event-store.ts +216 -237
  194. package/packages/server/src/persistence/meta-persistence.ts +12 -1
  195. package/packages/server/src/persistence/preferences-store.ts +116 -7
  196. package/packages/server/src/pi/bridge-upgrade-auth.ts +32 -21
  197. package/packages/server/src/pi/folder-commands.ts +141 -0
  198. package/packages/server/src/pi/gateway-socket-bind.ts +9 -3
  199. package/packages/server/src/pi/gateway-transport-policy.ts +13 -0
  200. package/packages/server/src/pi/host-project-trust.ts +158 -33
  201. package/packages/server/src/pi/pi-gateway.ts +93 -9
  202. package/packages/server/src/pi/pi-resource-scanner.ts +15 -0
  203. package/packages/server/src/pi/resource-activation-toggle.ts +6 -0
  204. package/packages/server/src/pi/resource-toggle-trust.ts +34 -2
  205. package/packages/server/src/pi/session-skill-registry.ts +13 -3
  206. package/packages/server/src/pi/settings-write-lock.ts +32 -0
  207. package/packages/server/src/pi/trust-challenges.ts +38 -0
  208. package/packages/server/src/pi-agent-settings.ts +701 -100
  209. package/packages/server/src/pi-settings-themes.ts +104 -0
  210. package/packages/server/src/questions/brief-generator.ts +138 -0
  211. package/packages/server/src/questions/brief-model.ts +55 -0
  212. package/packages/server/src/questions/brief-policy.ts +36 -0
  213. package/packages/server/src/questions/brief-prompt.ts +92 -0
  214. package/packages/server/src/questions/brief-runtime.ts +50 -0
  215. package/packages/server/src/questions/question-answer.ts +55 -0
  216. package/packages/server/src/questions/question-broadcast.ts +106 -0
  217. package/packages/server/src/questions/question-files.ts +128 -0
  218. package/packages/server/src/questions/question-routes.ts +126 -0
  219. package/packages/server/src/questions/question-snapshot.ts +150 -0
  220. package/packages/server/src/questions/question-stack.ts +57 -0
  221. package/packages/server/src/questions/question-store.ts +477 -0
  222. package/packages/server/src/routes/access-prompt-routes.ts +5 -3
  223. package/packages/server/src/routes/access-routes.ts +123 -5
  224. package/packages/server/src/routes/acme-routes.ts +190 -0
  225. package/packages/server/src/routes/acp-routes.ts +16 -0
  226. package/packages/server/src/routes/addons-routes.ts +221 -0
  227. package/packages/server/src/routes/file-routes.ts +366 -75
  228. package/packages/server/src/routes/file-write-binary-routes.ts +473 -0
  229. package/packages/server/src/routes/folder-project-routes.ts +99 -0
  230. package/packages/server/src/routes/git-routes.ts +17 -2
  231. package/packages/server/src/routes/known-servers-routes.ts +333 -53
  232. package/packages/server/src/routes/live-server-routes.ts +72 -4
  233. package/packages/server/src/routes/local-proof-routes.ts +12 -7
  234. package/packages/server/src/routes/mermaid-repair-routes.ts +254 -0
  235. package/packages/server/src/routes/model-proxy-routes.ts +4 -2
  236. package/packages/server/src/routes/openspec-routes.ts +270 -40
  237. package/packages/server/src/routes/package-health-routes.ts +140 -0
  238. package/packages/server/src/routes/package-routes.ts +28 -1
  239. package/packages/server/src/routes/pairing-routes.ts +158 -24
  240. package/packages/server/src/routes/pi-retry-routes.ts +18 -2
  241. package/packages/server/src/routes/pi-settings-routes.ts +264 -0
  242. package/packages/server/src/routes/plugin-activation-routes.ts +87 -27
  243. package/packages/server/src/routes/provider-auth-routes.ts +22 -5
  244. package/packages/server/src/routes/provider-routes.ts +29 -0
  245. package/packages/server/src/routes/resource-activation-routes.ts +16 -32
  246. package/packages/server/src/routes/session-routes.ts +49 -5
  247. package/packages/server/src/routes/system-routes.ts +207 -23
  248. package/packages/server/src/routes/tls-routes.ts +55 -0
  249. package/packages/server/src/routes/user-routes.ts +192 -0
  250. package/packages/server/src/runtime-overlay/runtime-stager.ts +15 -2
  251. package/packages/server/src/runtime-overlay/runtime-update-checker.ts +11 -2
  252. package/packages/server/src/server.ts +919 -139
  253. package/packages/server/src/services/attached-driver.ts +175 -0
  254. package/packages/server/src/services/change-notifier.ts +55 -0
  255. package/packages/server/src/services/cli-service.ts +450 -0
  256. package/packages/server/src/services/command-runner.ts +92 -0
  257. package/packages/server/src/services/definitions-store.ts +121 -0
  258. package/packages/server/src/services/driver.ts +112 -0
  259. package/packages/server/src/services/health.ts +94 -0
  260. package/packages/server/src/services/leases.ts +117 -0
  261. package/packages/server/src/services/log-text.ts +97 -0
  262. package/packages/server/src/services/native-driver.ts +283 -0
  263. package/packages/server/src/services/oci-driver.ts +590 -0
  264. package/packages/server/src/services/output-capture.ts +183 -0
  265. package/packages/server/src/services/paths.ts +82 -0
  266. package/packages/server/src/services/ports.ts +26 -0
  267. package/packages/server/src/services/routes.ts +140 -0
  268. package/packages/server/src/services/runtime-detect.ts +108 -0
  269. package/packages/server/src/services/secret-delivery.ts +61 -0
  270. package/packages/server/src/services/secrets-resolver.ts +145 -0
  271. package/packages/server/src/services/secrets-store.ts +137 -0
  272. package/packages/server/src/services/service-manager.ts +1565 -0
  273. package/packages/server/src/services/start-record.ts +66 -0
  274. package/packages/server/src/services/state-machine.ts +241 -0
  275. package/packages/server/src/session/archive-sweeper.ts +92 -3
  276. package/packages/server/src/session/custom-event-group-matcher.ts +4 -3
  277. package/packages/server/src/session/in-flight-tool-calls.ts +74 -0
  278. package/packages/server/src/session/memory-session-manager.ts +53 -0
  279. package/packages/server/src/session/name-provenance.ts +102 -0
  280. package/packages/server/src/session/open-tool-calls.ts +15 -6
  281. package/packages/server/src/session/session-api.ts +47 -12
  282. package/packages/server/src/session/session-archive.ts +56 -4
  283. package/packages/server/src/session/session-diff-cache.ts +11 -4
  284. package/packages/server/src/session/session-load-worker-pool.ts +4 -3
  285. package/packages/server/src/session/session-scanner.ts +73 -3
  286. package/packages/server/src/session/session-to-meta.ts +15 -0
  287. package/packages/server/src/spawn-process/abort-spawned-run.ts +55 -0
  288. package/packages/server/src/spawn-process/acp-spawn.ts +131 -0
  289. package/packages/server/src/spawn-process/process-manager.ts +164 -30
  290. package/packages/server/src/spawn-process/restart-helper.ts +9 -8
  291. package/packages/server/src/spawn-process/server-pid.ts +16 -7
  292. package/packages/server/src/spawn-process/session-terminator.ts +218 -0
  293. package/packages/server/src/spawn-process/spawn-env-contributors.ts +159 -0
  294. package/packages/server/src/spawn-process/spawn-register-watchdog.ts +10 -1
  295. package/packages/server/src/terminal/terminal-manager.ts +67 -1
  296. package/packages/server/src/tls/cert-files.ts +228 -0
  297. package/packages/server/src/tls/cert-manager.ts +703 -0
  298. package/packages/server/src/tls/cert-store.ts +69 -0
  299. package/packages/server/src/tls/source-registry.ts +71 -0
  300. package/packages/server/src/tls/sources/acme/accounts.ts +76 -0
  301. package/packages/server/src/tls/sources/acme/acme-source.ts +508 -0
  302. package/packages/server/src/tls/sources/acme/config-projection.ts +34 -0
  303. package/packages/server/src/tls/sources/acme/credentials.ts +185 -0
  304. package/packages/server/src/tls/sources/acme/dns.ts +303 -0
  305. package/packages/server/src/tls/sources/acme/e2e-overrides.ts +49 -0
  306. package/packages/server/src/tls/sources/acme/entry.ts +180 -0
  307. package/packages/server/src/tls/sources/acme/gc.ts +78 -0
  308. package/packages/server/src/tls/sources/acme/runtime.ts +51 -0
  309. package/packages/server/src/tls/sources/acme/solvers/acme-dns.ts +154 -0
  310. package/packages/server/src/tls/sources/acme/solvers/cloudflare.ts +147 -0
  311. package/packages/server/src/tls/sources/acme/types.ts +72 -0
  312. package/packages/server/src/tls/sources/tailscale-cert.ts +172 -0
  313. package/packages/server/src/tls/tls-config-validation.ts +92 -0
  314. package/packages/server/src/tls/tls-listener.ts +351 -0
  315. package/packages/server/src/tls/types.ts +80 -0
  316. package/packages/server/src/tunnel/tunnel-block-events.ts +4 -1
  317. package/packages/server/src/tunnel/tunnel-core.ts +4 -1
  318. package/packages/server/src/tunnel/tunnel-endpoints.ts +4 -0
  319. package/packages/server/src/tunnel-providers/tailscale.ts +27 -6
  320. package/packages/server/src/vault/vault-bindings.ts +101 -0
  321. package/packages/server/src/vault/vault-delivery-hub.ts +294 -0
  322. package/packages/server/src/vault/vault-grants.ts +260 -0
  323. package/packages/server/src/vault/vault-import.ts +161 -0
  324. package/packages/server/src/vault/vault-permissions.ts +39 -0
  325. package/packages/server/src/vault/vault-plugin-read.ts +64 -0
  326. package/packages/server/src/vault/vault-projects.ts +156 -0
  327. package/packages/server/src/vault/vault-routes.ts +277 -0
  328. package/packages/server/src/vault/vault-store.ts +371 -0
  329. package/packages/shared/package.json +5 -2
  330. package/packages/shared/src/acp/acp-config.ts +123 -0
  331. package/packages/shared/src/acp/normalize-v1.ts +92 -0
  332. package/packages/shared/src/acp/paths.ts +36 -0
  333. package/packages/shared/src/acp/to-dashboard-events.ts +533 -0
  334. package/packages/shared/src/acp/update-model.ts +574 -0
  335. package/packages/shared/src/anthropic-messages-source.ts +8 -0
  336. package/packages/shared/src/bind-reachability.ts +21 -2
  337. package/packages/shared/src/boot-state.ts +6 -0
  338. package/packages/shared/src/browser-host-identity.ts +49 -0
  339. package/packages/shared/src/browser-host-ipc.ts +107 -0
  340. package/packages/shared/src/browser-protocol.ts +385 -71
  341. package/packages/shared/src/canonical-subject.ts +27 -2
  342. package/packages/shared/src/card-sections.ts +185 -1
  343. package/packages/shared/src/chrome-profiles.ts +188 -0
  344. package/packages/shared/src/config.ts +473 -26
  345. package/packages/shared/src/custom-event-groups.ts +5 -2
  346. package/packages/shared/src/cwd-guard.ts +381 -1
  347. package/packages/shared/src/dashboard-paths.ts +12 -0
  348. package/packages/shared/src/dashboard-plugin/editor-pane-tab.ts +26 -0
  349. package/packages/shared/src/dashboard-plugin/file-handler.ts +71 -0
  350. package/packages/shared/src/dashboard-plugin/index.ts +7 -3
  351. package/packages/shared/src/dashboard-plugin/manifest-types.ts +106 -2
  352. package/packages/shared/src/dashboard-plugin/project-identity.ts +42 -0
  353. package/packages/shared/src/dashboard-plugin/project-markers.ts +60 -0
  354. package/packages/shared/src/dashboard-plugin/slot-props.ts +95 -0
  355. package/packages/shared/src/dashboard-plugin/slot-types.ts +64 -4
  356. package/packages/shared/src/dashboard-plugin/ui-primitives.ts +22 -3
  357. package/packages/shared/src/dashboard-starter.ts +30 -0
  358. package/packages/shared/src/display-name.ts +42 -0
  359. package/packages/shared/src/doctor-core.ts +25 -107
  360. package/packages/shared/src/enabled-models-match.ts +47 -0
  361. package/packages/shared/src/event-forward-declaration.ts +187 -0
  362. package/packages/shared/src/file-kind.ts +54 -2
  363. package/packages/shared/src/git-worktree-helpers.ts +8 -4
  364. package/packages/shared/src/grammar-types.ts +3 -1
  365. package/packages/shared/src/host-admission.ts +2 -1
  366. package/packages/shared/src/host-port.ts +34 -0
  367. package/packages/shared/src/launcher-origin.ts +26 -0
  368. package/packages/shared/src/local-credential-proof.ts +219 -0
  369. package/packages/shared/src/markup-repair/asciidoc.ts +130 -0
  370. package/packages/shared/src/markup-repair/types.ts +13 -0
  371. package/packages/shared/src/md-table-cell.ts +11 -0
  372. package/packages/shared/src/mdns-discovery.ts +392 -42
  373. package/packages/shared/src/models-json-reader.ts +6 -0
  374. package/packages/shared/src/openspec-design-evidence.ts +25 -1
  375. package/packages/shared/src/openspec-poller.ts +210 -9
  376. package/packages/shared/src/openspec-status-all.ts +393 -0
  377. package/packages/shared/src/operate-required.ts +29 -0
  378. package/packages/shared/src/pairing-knock-client.ts +261 -0
  379. package/packages/shared/src/pairing-knock.ts +71 -0
  380. package/packages/shared/src/pairing-refusal.ts +32 -0
  381. package/packages/shared/src/path-containment-guard-name.ts +8 -0
  382. package/packages/shared/src/pi-settings-keys.ts +9 -0
  383. package/packages/shared/src/pi-settings-schema.ts +285 -0
  384. package/packages/shared/src/pi-trust-mirror-snapshot.ts +200 -0
  385. package/packages/shared/src/pi-trust-mirror-types.ts +57 -0
  386. package/packages/shared/src/pi-trust-mirror.ts +328 -0
  387. package/packages/shared/src/platform/binary-lookup.ts +2 -194
  388. package/packages/shared/src/platform/git.ts +204 -4
  389. package/packages/shared/src/platform/native-ts-hooks.mjs +93 -40
  390. package/packages/shared/src/platform/native-ts-register.mjs +22 -10
  391. package/packages/shared/src/platform/native-ts-tier.d.mts +1 -0
  392. package/packages/shared/src/platform/native-ts-tier.mjs +17 -0
  393. package/packages/shared/src/platform/node-spawn.ts +1 -2
  394. package/packages/shared/src/platform/openspec.ts +129 -31
  395. package/packages/shared/src/platform/process-scan.ts +199 -1
  396. package/packages/shared/src/platform/process.ts +51 -0
  397. package/packages/shared/src/platform/runner.ts +46 -2
  398. package/packages/shared/src/platform/spawn-mechanism.ts +14 -2
  399. package/packages/shared/src/platform/ts-loader-select.d.mts +1 -7
  400. package/packages/shared/src/platform/ts-loader-select.mjs +14 -43
  401. package/packages/shared/src/plugin-bridge-register.ts +24 -1
  402. package/packages/shared/src/project-name.ts +42 -0
  403. package/packages/shared/src/prompt-answer.ts +183 -0
  404. package/packages/shared/src/protocol.ts +133 -8
  405. package/packages/shared/src/question-types.ts +73 -0
  406. package/packages/shared/src/recommended-extensions.ts +80 -23
  407. package/packages/shared/src/recovery-timing.ts +12 -0
  408. package/packages/shared/src/redaction.ts +50 -0
  409. package/packages/shared/src/rest-api.ts +484 -1
  410. package/packages/shared/src/role-config-disk.ts +23 -0
  411. package/packages/shared/src/role-schema.ts +79 -0
  412. package/packages/shared/src/route-tiers.ts +127 -0
  413. package/packages/shared/src/runtime-overlay/materialize-plugins.d.mts +17 -0
  414. package/packages/shared/src/runtime-overlay/materialize-plugins.mjs +119 -8
  415. package/packages/shared/src/server-identity.ts +51 -15
  416. package/packages/shared/src/server-launcher.ts +12 -33
  417. package/packages/shared/src/server-pinning.ts +81 -0
  418. package/packages/shared/src/services/offers.ts +114 -0
  419. package/packages/shared/src/services/schema.ts +628 -0
  420. package/packages/shared/src/services/status.ts +169 -0
  421. package/packages/shared/src/session-meta.ts +59 -2
  422. package/packages/shared/src/session-name.ts +8 -0
  423. package/packages/shared/src/skill-block-parser.ts +14 -0
  424. package/packages/shared/src/source-matching.ts +5 -1
  425. package/packages/shared/src/state-replay.ts +19 -0
  426. package/packages/shared/src/terminal-safe.ts +24 -0
  427. package/packages/shared/src/tls-status.ts +69 -0
  428. package/packages/shared/src/tool-path-resolve.ts +243 -0
  429. package/packages/shared/src/tool-registry/definitions.ts +26 -4
  430. package/packages/shared/src/tool-registry/index.ts +2 -2
  431. package/packages/shared/src/tool-registry/pi-tools.ts +32 -3
  432. package/packages/shared/src/tunnel-provider.ts +3 -2
  433. package/packages/shared/src/types.ts +104 -9
  434. package/packages/shared/src/vault-delivery.ts +73 -0
  435. package/packages/shared/src/vault-origin.ts +51 -0
  436. package/packages/shared/src/vault-project-key.ts +53 -0
  437. package/packages/shared/src/worktree-init-hook.ts +69 -0
  438. package/packages/shared/src/ws-message-tiers.ts +135 -0
  439. package/tsconfig.base.json +1 -0
@@ -0,0 +1,628 @@
1
+ /**
2
+ * Managed-services definition schema: types, defaults, the closed reason set,
3
+ * and the strict validator shared by `services.json` entries (user or
4
+ * offer-origin) and `pi.services` offers.
5
+ *
6
+ * Strict by construction (`parseSkillTools` style): every object has an exact
7
+ * key set, unknown keys are rejected AND named, and every rejection names the
8
+ * offending key. `pi.services` / `services.json` are public file formats that
9
+ * third-party packages depend on, so the parser is the compatibility gate.
10
+ * See change: add-service-registry-core (D2, D5, D6, D7).
11
+ */
12
+
13
+ export const SERVICE_SCHEMA_VERSION = 1 as const;
14
+
15
+ export type ServiceMode = "managed" | "attached" | "external";
16
+ export const SERVICE_MODES: readonly ServiceMode[] = ["managed", "attached", "external"];
17
+
18
+ export type ManagedDriverId = "oci:docker" | "oci:podman" | "native";
19
+ export const MANAGED_DRIVERS: readonly ManagedDriverId[] = ["oci:docker", "oci:podman", "native"];
20
+
21
+ /** Every concrete driver, including the mode-implied ones. */
22
+ export type DriverName = ManagedDriverId | "attached" | "external";
23
+
24
+ /** Closed set of `unavailable` reasons (D2 + `duplicate-instances`). */
25
+ export const UNAVAILABLE_REASONS = [
26
+ "runtime-missing",
27
+ "runtime-unreachable",
28
+ "host-vm-stopped",
29
+ "image-absent",
30
+ "runner-absent",
31
+ "package-absent",
32
+ "secret-unavailable",
33
+ "unsupported-platform",
34
+ "invalid-definition",
35
+ "adoption-uncertain",
36
+ "owner-conflict",
37
+ "duplicate-instances",
38
+ ] as const;
39
+ export type UnavailableReason = (typeof UNAVAILABLE_REASONS)[number];
40
+
41
+ /** Lifecycle states (spec: exactly one per service). */
42
+ export const SERVICE_STATES = [
43
+ "stopped",
44
+ "starting",
45
+ "healthy",
46
+ "idle",
47
+ "stopping",
48
+ "stop-failed",
49
+ "blocked",
50
+ "failed",
51
+ "unavailable",
52
+ ] as const;
53
+ export type ServiceState = (typeof SERVICE_STATES)[number];
54
+
55
+ /** States an `ensure` payload can carry (D9). `idle`/`stopped` never surface. */
56
+ export type EnsureState =
57
+ | "healthy"
58
+ | "starting"
59
+ | "blocked"
60
+ | "failed"
61
+ | "unavailable"
62
+ | "not-added"
63
+ | "no-server"
64
+ | "stop-failed";
65
+
66
+ export type Exposure = "loopback" | "all-interfaces" | "unknown";
67
+
68
+ /** The ensure payload (D9). Never carries a secret value. */
69
+ export interface EnsurePayload {
70
+ id: string;
71
+ state: EnsureState;
72
+ reason?: UnavailableReason;
73
+ retryAt?: string;
74
+ endpoints?: Record<string, string>;
75
+ leaseId?: string;
76
+ driver?: DriverName;
77
+ exposure?: Exposure;
78
+ updateAvailable?: boolean;
79
+ restartRequired?: boolean;
80
+ tried?: Array<{ driver: DriverName; reason: UnavailableReason }>;
81
+ hint?: string;
82
+ }
83
+
84
+ // ── Definition types ────────────────────────────────────────────────────────
85
+
86
+ export type EndpointProtocol = "http" | "tcp" | "ws";
87
+
88
+ export type HealthProbe =
89
+ | { kind: "http"; endpoint: string; path?: string; timeoutMs?: number }
90
+ | { kind: "tcp"; endpoint: string; timeoutMs?: number }
91
+ | { kind: "ws-first-message"; endpoint: string; path?: string; timeoutMs?: number }
92
+ | { kind: "oci-healthcheck" };
93
+
94
+ export interface SecretSpec {
95
+ /** `store:<id>/<name>` (default), `env:<NAME>`, or `keychain:<service>/<account>`. */
96
+ ref?: string;
97
+ /** Generate a random value at add time (implies the store). */
98
+ generate?: { bytes: number };
99
+ /** Env var the started process sees (native/attached) or that holds the mount path (oci). */
100
+ env?: string;
101
+ }
102
+
103
+ export interface OciSpec {
104
+ image: string;
105
+ ports: Record<string, { container: number; protocol?: EndpointProtocol }>;
106
+ /** Named volumes: volume name → container path. */
107
+ volumes?: Record<string, string>;
108
+ /** Host bind mounts (user-origin entries only): host path → container path. */
109
+ binds?: Record<string, string>;
110
+ /** Non-secret env. */
111
+ env?: Record<string, string>;
112
+ command?: string[];
113
+ /** `--init` is on unless explicitly false. */
114
+ init?: boolean;
115
+ }
116
+
117
+ export type NativeRunner = "uvx" | "npx";
118
+ export const NATIVE_RUNNERS: readonly NativeRunner[] = ["uvx", "npx"];
119
+
120
+ export interface NativeRecipe {
121
+ runner: NativeRunner;
122
+ /** `<name>@<exact version>`. */
123
+ package: string;
124
+ bin?: string;
125
+ /** Literal args; the only substitution is `${port.<name>}`. */
126
+ args: string[];
127
+ ports: Record<string, { protocol?: EndpointProtocol }>;
128
+ env?: Record<string, string>;
129
+ }
130
+
131
+ export type PlatformArgv = Partial<Record<"darwin" | "linux" | "win32", string[]>>;
132
+
133
+ export type ServiceOrigin = "user" | { package: string; version: string; templateHash: string };
134
+
135
+ export interface ServiceDefinition {
136
+ id: string;
137
+ mode: ServiceMode;
138
+ description?: string;
139
+ /** managed only, preference order. */
140
+ drivers?: ManagedDriverId[];
141
+ oci?: OciSpec;
142
+ native?: NativeRecipe;
143
+ /** attached / external: name → URL. */
144
+ endpoints?: Record<string, string>;
145
+ /** attached + user origin only. */
146
+ lifecycle?: { start?: PlatformArgv; stop?: PlatformArgv };
147
+ /** attached: exact executable basename matcher. */
148
+ process?: { name: string };
149
+ health: HealthProbe;
150
+ secrets?: Record<string, SecretSpec>;
151
+ startTimeoutSec?: number;
152
+ stopTimeoutSec?: number;
153
+ idleStopMinutes?: number | null;
154
+ origin: ServiceOrigin;
155
+ }
156
+
157
+ /** A `pi.services` entry: a definition without `origin`, plus `schemaVersion`. */
158
+ export type ServiceTemplate = Omit<ServiceDefinition, "origin"> & { schemaVersion: 1 };
159
+
160
+ // ── Defaults ────────────────────────────────────────────────────────────────
161
+
162
+ export const DEFAULT_START_TIMEOUT_SEC = 120;
163
+ export const DEFAULT_STOP_TIMEOUT_SEC = 15;
164
+ export const DEFAULT_IDLE_STOP_MINUTES = 15;
165
+ export const DEFAULT_LEASE_TTL_SEC = 300;
166
+
167
+ export interface EffectiveTimings {
168
+ startTimeoutMs: number;
169
+ stopTimeoutMs: number;
170
+ /** null disables idle-stop (default for `attached`). */
171
+ idleStopMinutes: number | null;
172
+ }
173
+
174
+ export function effectiveTimings(def: ServiceDefinition): EffectiveTimings {
175
+ const idle =
176
+ def.idleStopMinutes !== undefined
177
+ ? def.idleStopMinutes
178
+ : def.mode === "attached"
179
+ ? null
180
+ : DEFAULT_IDLE_STOP_MINUTES;
181
+ return {
182
+ startTimeoutMs: (def.startTimeoutSec ?? DEFAULT_START_TIMEOUT_SEC) * 1000,
183
+ stopTimeoutMs: (def.stopTimeoutSec ?? DEFAULT_STOP_TIMEOUT_SEC) * 1000,
184
+ idleStopMinutes: idle,
185
+ };
186
+ }
187
+
188
+ // ── Validation ──────────────────────────────────────────────────────────────
189
+
190
+ export const SERVICE_ID_PATTERN = /^[a-z0-9][a-z0-9-]{0,62}$/;
191
+ const NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
192
+ const ENV_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
193
+ const VOLUME_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_.-]*$/;
194
+ const BIN_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_.-]*$/;
195
+ /** `<name>@<exact semver>`; npm scopes allowed. No ranges, tags or `latest`. */
196
+ const EXACT_PACKAGE_PATTERN = /^(@[a-z0-9][\w.-]*\/)?[A-Za-z0-9][\w.-]*@\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/;
197
+ const SECRET_REF_PATTERN = /^(store:[a-z0-9][a-z0-9-]*\/[A-Za-z][A-Za-z0-9_]*|env:[A-Za-z_][A-Za-z0-9_]*|keychain:[^/\s]+\/[^\s]+)$/;
198
+ const PORT_PLACEHOLDER = /\$\{port\.([A-Za-z][A-Za-z0-9_]*)\}/g;
199
+ const PLATFORMS = ["darwin", "linux", "win32"] as const;
200
+ const PROTOCOLS: readonly EndpointProtocol[] = ["http", "tcp", "ws"];
201
+
202
+ const TOP_KEYS = [
203
+ "id", "mode", "description", "drivers", "oci", "native", "endpoints", "lifecycle",
204
+ "process", "health", "secrets", "startTimeoutSec", "stopTimeoutSec", "idleStopMinutes", "origin",
205
+ ] as const;
206
+ const OCI_KEYS = ["image", "ports", "volumes", "binds", "env", "command", "init"] as const;
207
+ const NATIVE_KEYS = ["runner", "package", "bin", "args", "ports", "env"] as const;
208
+ const SECRET_KEYS = ["ref", "generate", "env"] as const;
209
+ const HEALTH_KEYS: Record<HealthProbe["kind"], readonly string[]> = {
210
+ http: ["kind", "endpoint", "path", "timeoutMs"],
211
+ tcp: ["kind", "endpoint", "timeoutMs"],
212
+ "ws-first-message": ["kind", "endpoint", "path", "timeoutMs"],
213
+ "oci-healthcheck": ["kind"],
214
+ };
215
+
216
+ /** Keys with a dedicated, more specific rejection than "unknown key". */
217
+ const DANGEROUS_KEY_MESSAGES: Record<string, string> = {
218
+ privileged: "privileged mode is never allowed",
219
+ network: "host / custom networking is never allowed",
220
+ networkMode: "host / custom networking is never allowed",
221
+ hostNetwork: "host networking is never allowed",
222
+ pid: "host pid namespace is never allowed",
223
+ cap_add: "added capabilities are never allowed",
224
+ capAdd: "added capabilities are never allowed",
225
+ devices: "device passthrough is never allowed",
226
+ host: "non-loopback port bindings are never allowed (ports publish on 127.0.0.1 only)",
227
+ hostIp: "non-loopback port bindings are never allowed (ports publish on 127.0.0.1 only)",
228
+ hostPort: "fixed host ports are not allowed (the runtime assigns a loopback port)",
229
+ };
230
+
231
+ export interface ValidateOptions {
232
+ /** `offer`: a `pi.services` template (no `origin`, `schemaVersion` required). */
233
+ kind?: "definition" | "offer";
234
+ /**
235
+ * Whether the OCI image declares a HEALTHCHECK, when known (checked at add
236
+ * time). `false` makes an `oci-healthcheck` probe invalid.
237
+ */
238
+ imageHasHealthcheck?: boolean;
239
+ }
240
+
241
+ export type ValidateResult<T> = { ok: true; value: T } | { ok: false; errors: string[] };
242
+
243
+ function isPlainObject(v: unknown): v is Record<string, unknown> {
244
+ return v !== null && typeof v === "object" && !Array.isArray(v);
245
+ }
246
+
247
+ function extraKeys(obj: Record<string, unknown>, allowed: readonly string[]): string[] {
248
+ return Object.keys(obj).filter((k) => !allowed.includes(k));
249
+ }
250
+
251
+ function rejectKeys(where: string, obj: Record<string, unknown>, allowed: readonly string[], errors: string[]): void {
252
+ for (const k of extraKeys(obj, allowed)) {
253
+ const special = DANGEROUS_KEY_MESSAGES[k];
254
+ errors.push(special ? `${where}.${k}: ${special}` : `${where}.${k}: unknown key`);
255
+ }
256
+ }
257
+
258
+ function isStringArray(v: unknown): v is string[] {
259
+ return Array.isArray(v) && v.every((x) => typeof x === "string");
260
+ }
261
+
262
+ function isPositiveNumber(v: unknown): v is number {
263
+ return typeof v === "number" && Number.isFinite(v) && v > 0;
264
+ }
265
+
266
+ function isValidUrl(v: unknown): boolean {
267
+ if (typeof v !== "string") return false;
268
+ try {
269
+ const u = new URL(v);
270
+ return ["http:", "https:", "ws:", "wss:", "tcp:"].includes(u.protocol) && u.hostname.length > 0;
271
+ } catch {
272
+ return false;
273
+ }
274
+ }
275
+
276
+ /** Names of the endpoints a definition exposes (for health / secret validation). */
277
+ export function endpointNames(def: Pick<ServiceDefinition, "mode" | "oci" | "native" | "endpoints">): string[] {
278
+ if (def.mode !== "managed") return Object.keys(def.endpoints ?? {});
279
+ return [...new Set([...Object.keys(def.oci?.ports ?? {}), ...Object.keys(def.native?.ports ?? {})])];
280
+ }
281
+
282
+ function validateOci(oci: unknown, isUser: boolean, id: unknown, errors: string[]): void {
283
+ if (!isPlainObject(oci)) {
284
+ errors.push("oci: must be an object");
285
+ return;
286
+ }
287
+ rejectKeys("oci", oci, OCI_KEYS, errors);
288
+ if (typeof oci.image !== "string" || oci.image.trim() === "") {
289
+ errors.push("oci.image: must be a non-empty string");
290
+ } else if (oci.image.startsWith("-")) {
291
+ errors.push("oci.image: must not start with '-' (it would be read as a runtime flag)");
292
+ } else if (!isUser && !/@sha256:[0-9a-f]{64}$/.test(oci.image)) {
293
+ errors.push(`oci.image: offer images must be digest-pinned (@sha256:…), got ${JSON.stringify(oci.image)}`);
294
+ }
295
+ if (!isPlainObject(oci.ports) || Object.keys(oci.ports).length === 0) {
296
+ errors.push("oci.ports: must name at least one port");
297
+ } else {
298
+ for (const [name, spec] of Object.entries(oci.ports)) {
299
+ if (!NAME_PATTERN.test(name)) errors.push(`oci.ports.${name}: invalid port name`);
300
+ if (!isPlainObject(spec)) {
301
+ errors.push(`oci.ports.${name}: must be { container, protocol? } — non-loopback port bindings (e.g. ${JSON.stringify(spec)}) are not allowed`);
302
+ continue;
303
+ }
304
+ rejectKeys(`oci.ports.${name}`, spec, ["container", "protocol"], errors);
305
+ const c = spec.container;
306
+ if (typeof c !== "number" || !Number.isInteger(c) || c < 1 || c > 65535) {
307
+ errors.push(`oci.ports.${name}.container: must be a port number`);
308
+ }
309
+ if (spec.protocol !== undefined && !PROTOCOLS.includes(spec.protocol as EndpointProtocol)) {
310
+ errors.push(`oci.ports.${name}.protocol: must be one of ${PROTOCOLS.join(", ")}`);
311
+ }
312
+ }
313
+ }
314
+ if (oci.volumes !== undefined) {
315
+ if (!isPlainObject(oci.volumes)) errors.push("oci.volumes: must be an object");
316
+ else {
317
+ for (const [vol, target] of Object.entries(oci.volumes)) {
318
+ if (!VOLUME_NAME_PATTERN.test(vol)) {
319
+ errors.push(`oci.volumes.${vol}: bind mounts are not allowed here — a volume must be a named volume`);
320
+ } else if (!isUser && typeof id === "string" && !vol.startsWith(`${id}-`)) {
321
+ // Volume names are runtime-global: a package template may only own
322
+ // volumes in its own namespace, never mount (or purge) a stranger's.
323
+ errors.push(`oci.volumes.${vol}: a package template's volume names must start with "${id}-"`);
324
+ }
325
+ if (typeof target !== "string" || !target.startsWith("/")) {
326
+ errors.push(`oci.volumes.${vol}: container path must be absolute`);
327
+ }
328
+ }
329
+ }
330
+ }
331
+ if (oci.binds !== undefined) {
332
+ if (!isUser) errors.push("oci.binds: bind mounts are not allowed in a package offer");
333
+ else if (!isPlainObject(oci.binds)) errors.push("oci.binds: must be an object");
334
+ else {
335
+ for (const [host, target] of Object.entries(oci.binds)) {
336
+ if (!host.startsWith("/")) errors.push(`oci.binds.${host}: host path must be absolute`);
337
+ if (typeof target !== "string" || !target.startsWith("/")) {
338
+ errors.push(`oci.binds.${host}: container path must be absolute`);
339
+ }
340
+ }
341
+ }
342
+ }
343
+ if (oci.env !== undefined) {
344
+ if (!isPlainObject(oci.env) || !Object.values(oci.env).every((v) => typeof v === "string")) {
345
+ errors.push("oci.env: must map names to strings");
346
+ } else {
347
+ for (const k of Object.keys(oci.env)) if (!ENV_NAME_PATTERN.test(k)) errors.push(`oci.env.${k}: invalid env name`);
348
+ }
349
+ }
350
+ if (oci.command !== undefined && !isStringArray(oci.command)) errors.push("oci.command: must be an argv array");
351
+ if (oci.init !== undefined && typeof oci.init !== "boolean") errors.push("oci.init: must be a boolean");
352
+ }
353
+
354
+ function validateNative(native: unknown, errors: string[]): void {
355
+ if (!isPlainObject(native)) {
356
+ errors.push("native: must be an object");
357
+ return;
358
+ }
359
+ rejectKeys("native", native, NATIVE_KEYS, errors);
360
+ if (!NATIVE_RUNNERS.includes(native.runner as NativeRunner)) {
361
+ errors.push(`native.runner: ${JSON.stringify(native.runner)} is not an allowed runner (${NATIVE_RUNNERS.join(", ")})`);
362
+ }
363
+ if (typeof native.package !== "string" || !EXACT_PACKAGE_PATTERN.test(native.package)) {
364
+ errors.push(`native.package: must pin an exact version (<name>@<x.y.z>), got ${JSON.stringify(native.package)}`);
365
+ }
366
+ if (native.bin !== undefined && (typeof native.bin !== "string" || !BIN_PATTERN.test(native.bin))) {
367
+ errors.push("native.bin: invalid binary name");
368
+ }
369
+ const ports = isPlainObject(native.ports) ? native.ports : null;
370
+ if (!ports || Object.keys(ports).length === 0) errors.push("native.ports: must name at least one port");
371
+ else {
372
+ for (const [name, spec] of Object.entries(ports)) {
373
+ if (!NAME_PATTERN.test(name)) errors.push(`native.ports.${name}: invalid port name`);
374
+ if (!isPlainObject(spec)) {
375
+ errors.push(`native.ports.${name}: must be { protocol? }`);
376
+ continue;
377
+ }
378
+ rejectKeys(`native.ports.${name}`, spec, ["protocol"], errors);
379
+ if (spec.protocol !== undefined && !PROTOCOLS.includes(spec.protocol as EndpointProtocol)) {
380
+ errors.push(`native.ports.${name}.protocol: must be one of ${PROTOCOLS.join(", ")}`);
381
+ }
382
+ }
383
+ }
384
+ if (!isStringArray(native.args)) {
385
+ errors.push("native.args: must be an argv array of strings");
386
+ } else {
387
+ native.args.forEach((arg, i) => {
388
+ // Only `${port.<name>}` may appear; anything shell-like is rejected so an
389
+ // arg can never be read as a command substitution by any runner.
390
+ const stripped = arg.replace(PORT_PLACEHOLDER, (_m, name: string) => {
391
+ if (ports && !(name in ports)) errors.push(`native.args[${i}]: placeholder \${port.${name}} names no declared port`);
392
+ return "";
393
+ });
394
+ if (/\$|`/.test(stripped)) {
395
+ errors.push(`native.args[${i}]: only \${port.<name>} placeholders are allowed, got ${JSON.stringify(arg)}`);
396
+ }
397
+ });
398
+ }
399
+ if (native.env !== undefined) {
400
+ if (!isPlainObject(native.env) || !Object.values(native.env).every((v) => typeof v === "string")) {
401
+ errors.push("native.env: must map names to strings");
402
+ } else {
403
+ for (const k of Object.keys(native.env)) if (!ENV_NAME_PATTERN.test(k)) errors.push(`native.env.${k}: invalid env name`);
404
+ }
405
+ }
406
+ }
407
+
408
+ function validatePlatformArgv(where: string, v: unknown, errors: string[]): void {
409
+ if (!isPlainObject(v)) {
410
+ errors.push(`${where}: must map platforms to argv arrays`);
411
+ return;
412
+ }
413
+ rejectKeys(where, v, PLATFORMS, errors);
414
+ for (const p of PLATFORMS) {
415
+ if (v[p] !== undefined && (!isStringArray(v[p]) || (v[p] as string[]).length === 0)) {
416
+ errors.push(`${where}.${p}: must be a non-empty argv array (no shell string)`);
417
+ }
418
+ }
419
+ }
420
+
421
+ function validateHealth(health: unknown, def: Record<string, unknown>, opts: ValidateOptions, errors: string[]): void {
422
+ if (!isPlainObject(health)) {
423
+ errors.push("health: every definition must declare a health probe");
424
+ return;
425
+ }
426
+ const kind = health.kind as HealthProbe["kind"];
427
+ if (!(kind in HEALTH_KEYS)) {
428
+ errors.push(`health.kind: must be one of ${Object.keys(HEALTH_KEYS).join(", ")}`);
429
+ return;
430
+ }
431
+ rejectKeys("health", health, HEALTH_KEYS[kind], errors);
432
+ if (kind === "oci-healthcheck") {
433
+ const drivers = Array.isArray(def.drivers) ? (def.drivers as string[]) : [];
434
+ if (def.mode !== "managed" || !drivers.some((d) => d.startsWith("oci:"))) {
435
+ errors.push("health.kind: oci-healthcheck needs a managed OCI service");
436
+ }
437
+ if (opts.imageHasHealthcheck === false) {
438
+ errors.push("health.kind: oci-healthcheck requires an image that declares a HEALTHCHECK");
439
+ }
440
+ return;
441
+ }
442
+ const names = endpointNames(def as unknown as ServiceDefinition);
443
+ if (typeof health.endpoint !== "string" || !names.includes(health.endpoint)) {
444
+ errors.push(`health.endpoint: must name a declared endpoint/port (${names.join(", ") || "none"})`);
445
+ }
446
+ if (health.path !== undefined && (typeof health.path !== "string" || !health.path.startsWith("/"))) {
447
+ errors.push("health.path: must start with /");
448
+ }
449
+ if (health.timeoutMs !== undefined && !isPositiveNumber(health.timeoutMs)) errors.push("health.timeoutMs: must be positive");
450
+ }
451
+
452
+ function validateSecrets(secrets: unknown, isPackage: boolean, id: unknown, errors: string[]): void {
453
+ if (!isPlainObject(secrets)) {
454
+ errors.push("secrets: must be an object");
455
+ return;
456
+ }
457
+ const seen = new Set<string>();
458
+ for (const [name, spec] of Object.entries(secrets)) {
459
+ if (!NAME_PATTERN.test(name)) errors.push(`secrets.${name}: invalid secret name`);
460
+ // Names become files under secrets/ and SVC_<ID>_<NAME> env vars: a
461
+ // case-only difference would collide on case-insensitive volumes.
462
+ if (seen.has(name.toLowerCase())) errors.push(`secrets.${name}: differs from another secret name only by case`);
463
+ seen.add(name.toLowerCase());
464
+ if (!isPlainObject(spec)) {
465
+ errors.push(`secrets.${name}: must be an object`);
466
+ continue;
467
+ }
468
+ rejectKeys(`secrets.${name}`, spec, SECRET_KEYS, errors);
469
+ if (spec.ref !== undefined) {
470
+ if (typeof spec.ref !== "string" || !SECRET_REF_PATTERN.test(spec.ref)) {
471
+ errors.push(`secrets.${name}.ref: must be store:<id>/<name>, env:<NAME> or keychain:<service>/<account>`);
472
+ } else if (isPackage && spec.ref !== `store:${String(id)}/${name}`) {
473
+ // A package template may only use its OWN store slot: never env:,
474
+ // keychain:, or another service's stored secret.
475
+ errors.push(`secrets.${name}.ref: a package template may only reference store:${String(id)}/${name}`);
476
+ }
477
+ }
478
+ if (spec.generate !== undefined) {
479
+ const bytes = isPlainObject(spec.generate) ? spec.generate.bytes : undefined;
480
+ if (!isPlainObject(spec.generate) || extraKeys(spec.generate, ["bytes"]).length > 0 ||
481
+ typeof bytes !== "number" || !Number.isInteger(bytes) || bytes < 16 || bytes > 1024) {
482
+ errors.push(`secrets.${name}.generate: must be { bytes: 16..1024 }`);
483
+ }
484
+ if (spec.ref !== undefined && !String(spec.ref).startsWith("store:")) {
485
+ errors.push(`secrets.${name}: a generated secret lives in the store; it cannot also carry an ${String(spec.ref).split(":")[0]}: ref`);
486
+ }
487
+ }
488
+ if (spec.env !== undefined && (typeof spec.env !== "string" || !ENV_NAME_PATTERN.test(spec.env))) {
489
+ errors.push(`secrets.${name}.env: invalid env name`);
490
+ }
491
+ }
492
+ }
493
+
494
+ /**
495
+ * Validate a definition (`kind: "definition"`, needs `origin`) or an offer
496
+ * template (`kind: "offer"`, needs `schemaVersion: 1`, no `origin`).
497
+ * Every error names the offending key.
498
+ */
499
+ export function validateDefinition(input: unknown, opts: ValidateOptions = {}): ValidateResult<ServiceDefinition> {
500
+ const errors: string[] = [];
501
+ const isOffer = opts.kind === "offer";
502
+ if (!isPlainObject(input)) return { ok: false, errors: ["definition: must be an object"] };
503
+ const def = input;
504
+
505
+ if (isOffer) {
506
+ if (def.schemaVersion !== SERVICE_SCHEMA_VERSION) {
507
+ errors.push(`schemaVersion: must be ${SERVICE_SCHEMA_VERSION}`);
508
+ }
509
+ rejectKeys("offer", def, [...TOP_KEYS.filter((k) => k !== "origin"), "schemaVersion"], errors);
510
+ if ("origin" in def) errors.push("offer.origin: an offer may not declare its own origin");
511
+ } else {
512
+ rejectKeys("definition", def, TOP_KEYS, errors);
513
+ }
514
+
515
+ const origin = def.origin;
516
+ const isUser = !isOffer && origin === "user";
517
+ if (!isOffer) {
518
+ const pkgOrigin =
519
+ isPlainObject(origin) &&
520
+ typeof origin.package === "string" &&
521
+ typeof origin.version === "string" &&
522
+ typeof origin.templateHash === "string" &&
523
+ extraKeys(origin, ["package", "version", "templateHash"]).length === 0;
524
+ if (origin !== "user" && !pkgOrigin) {
525
+ errors.push('origin: must be "user" or { package, version, templateHash }');
526
+ }
527
+ }
528
+
529
+ if (typeof def.id !== "string" || !SERVICE_ID_PATTERN.test(def.id)) {
530
+ errors.push(`id: must match ${SERVICE_ID_PATTERN}`);
531
+ }
532
+ if (def.description !== undefined && typeof def.description !== "string") errors.push("description: must be a string");
533
+
534
+ const mode = def.mode;
535
+ if (mode === "native") {
536
+ errors.push('mode: "native" is a driver, not a mode — use mode "managed" with drivers ["native"]');
537
+ } else if (!SERVICE_MODES.includes(mode as ServiceMode)) {
538
+ errors.push(`mode: must be one of ${SERVICE_MODES.join(", ")}`);
539
+ }
540
+
541
+ if (mode === "managed") {
542
+ const drivers = def.drivers;
543
+ if (!Array.isArray(drivers) || drivers.length === 0 ||
544
+ !drivers.every((d) => MANAGED_DRIVERS.includes(d as ManagedDriverId)) ||
545
+ new Set(drivers).size !== drivers.length) {
546
+ errors.push(`drivers: must be a non-empty, duplicate-free list of ${MANAGED_DRIVERS.join(", ")}`);
547
+ } else {
548
+ if (drivers.some((d) => String(d).startsWith("oci:")) && def.oci === undefined) errors.push("oci: required by an oci driver");
549
+ if (drivers.includes("native") && def.native === undefined) errors.push("native: required by the native driver");
550
+ }
551
+ if (def.oci !== undefined) validateOci(def.oci, isUser, def.id, errors);
552
+ if (def.native !== undefined) validateNative(def.native, errors);
553
+ for (const k of ["endpoints", "lifecycle", "process"] as const) {
554
+ if (def[k] !== undefined) errors.push(`${k}: not allowed for a managed service`);
555
+ }
556
+ } else if (mode === "attached" || mode === "external") {
557
+ for (const k of ["drivers", "oci", "native"] as const) {
558
+ if (def[k] !== undefined) errors.push(`${k}: not allowed for an ${mode} service`);
559
+ }
560
+ if (!isPlainObject(def.endpoints) || Object.keys(def.endpoints).length === 0) {
561
+ errors.push("endpoints: must name at least one endpoint URL");
562
+ } else {
563
+ for (const [name, url] of Object.entries(def.endpoints)) {
564
+ if (!NAME_PATTERN.test(name)) errors.push(`endpoints.${name}: invalid endpoint name`);
565
+ if (!isValidUrl(url)) errors.push(`endpoints.${name}: must be an http(s)/ws(s)/tcp URL`);
566
+ }
567
+ }
568
+ if (mode === "external") {
569
+ for (const k of ["lifecycle", "process"] as const) {
570
+ if (def[k] !== undefined) errors.push(`${k}: an external service has no lifecycle`);
571
+ }
572
+ } else {
573
+ if (def.lifecycle !== undefined) {
574
+ if (!isUser) {
575
+ errors.push("lifecycle: lifecycle commands are allowed only in user-authored entries");
576
+ } else if (!isPlainObject(def.lifecycle)) {
577
+ errors.push("lifecycle: must be { start?, stop? }");
578
+ } else {
579
+ rejectKeys("lifecycle", def.lifecycle, ["start", "stop"], errors);
580
+ if (def.lifecycle.start !== undefined) validatePlatformArgv("lifecycle.start", def.lifecycle.start, errors);
581
+ if (def.lifecycle.stop !== undefined) validatePlatformArgv("lifecycle.stop", def.lifecycle.stop, errors);
582
+ }
583
+ }
584
+ if (def.process !== undefined) {
585
+ if (!isPlainObject(def.process) || typeof def.process.name !== "string" || def.process.name.trim() === "" ||
586
+ extraKeys(def.process, ["name"]).length > 0 || /[\\/]/.test(def.process.name)) {
587
+ errors.push("process: must be { name: <exact executable basename> }");
588
+ }
589
+ }
590
+ const hasStop = isPlainObject(def.lifecycle) && def.lifecycle.stop !== undefined;
591
+ if (hasStop && def.process === undefined) {
592
+ errors.push("process: an entry that declares lifecycle.stop must declare a process matcher");
593
+ }
594
+ if (!hasStop && def.idleStopMinutes !== undefined && def.idleStopMinutes !== null) {
595
+ errors.push("idleStopMinutes: must be null for an attached entry without lifecycle.stop (it cannot be stopped)");
596
+ }
597
+ }
598
+ }
599
+
600
+ validateHealth(def.health, def, opts, errors);
601
+ if (def.secrets !== undefined) validateSecrets(def.secrets, !isUser, def.id, errors);
602
+ for (const k of ["startTimeoutSec", "stopTimeoutSec"] as const) {
603
+ if (def[k] !== undefined && !isPositiveNumber(def[k])) errors.push(`${k}: must be a positive number`);
604
+ }
605
+ if (def.idleStopMinutes !== undefined && def.idleStopMinutes !== null && !isPositiveNumber(def.idleStopMinutes)) {
606
+ errors.push("idleStopMinutes: must be a positive number or null");
607
+ }
608
+
609
+ return errors.length > 0 ? { ok: false, errors } : { ok: true, value: def as unknown as ServiceDefinition };
610
+ }
611
+
612
+ /** Canonical JSON (sorted keys) — the input to every hash in this module. */
613
+ export function canonicalJson(value: unknown): string {
614
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
615
+ if (isPlainObject(value)) {
616
+ return `{${Object.keys(value)
617
+ .sort()
618
+ .filter((k) => value[k] !== undefined)
619
+ .map((k) => `${JSON.stringify(k)}:${canonicalJson(value[k])}`)
620
+ .join(",")}}`;
621
+ }
622
+ return JSON.stringify(value);
623
+ }
624
+
625
+ /** The env var `service exec` sets for a secret: `SVC_<ID>_<NAME>`, uppercased, non-alnum → `_`. */
626
+ export function execSecretEnvName(id: string, name: string): string {
627
+ return `SVC_${id}_${name}`.toUpperCase().replace(/[^A-Z0-9]/g, "_");
628
+ }