@jadelclemens/pi-forge 0.0.0-stage → 0.6.1

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 (440) hide show
  1. package/CHANGELOG.md +486 -0
  2. package/LICENSE +21 -0
  3. package/PUBLIC_API.md +5 -0
  4. package/README.md +204 -2
  5. package/README.zh-CN.md +128 -0
  6. package/SUBAGENT_ADAPTER_CONTRACT.md +7 -0
  7. package/dist/active-state.d.ts +148 -0
  8. package/dist/active-state.d.ts.map +1 -0
  9. package/dist/active-state.js +374 -0
  10. package/dist/active-state.js.map +1 -0
  11. package/dist/agent-profile.d.ts +51 -0
  12. package/dist/agent-profile.d.ts.map +1 -0
  13. package/dist/agent-profile.js +197 -0
  14. package/dist/agent-profile.js.map +1 -0
  15. package/dist/capabilities.d.ts +39 -0
  16. package/dist/capabilities.d.ts.map +1 -0
  17. package/dist/capabilities.js +160 -0
  18. package/dist/capabilities.js.map +1 -0
  19. package/dist/capability-anchors.d.ts +45 -0
  20. package/dist/capability-anchors.d.ts.map +1 -0
  21. package/dist/capability-anchors.js +263 -0
  22. package/dist/capability-anchors.js.map +1 -0
  23. package/dist/capability-command.d.ts +4 -0
  24. package/dist/capability-command.d.ts.map +1 -0
  25. package/dist/capability-command.js +164 -0
  26. package/dist/capability-command.js.map +1 -0
  27. package/dist/capability-events.d.ts +79 -0
  28. package/dist/capability-events.d.ts.map +1 -0
  29. package/dist/capability-events.js +478 -0
  30. package/dist/capability-events.js.map +1 -0
  31. package/dist/capability-projection.d.ts +22 -0
  32. package/dist/capability-projection.d.ts.map +1 -0
  33. package/dist/capability-projection.js +273 -0
  34. package/dist/capability-projection.js.map +1 -0
  35. package/dist/capability-protocol.d.ts +21 -0
  36. package/dist/capability-protocol.d.ts.map +1 -0
  37. package/dist/capability-protocol.js +15 -0
  38. package/dist/capability-protocol.js.map +1 -0
  39. package/dist/capability-state.d.ts +74 -0
  40. package/dist/capability-state.d.ts.map +1 -0
  41. package/dist/capability-state.js +43 -0
  42. package/dist/capability-state.js.map +1 -0
  43. package/dist/capability-tool.d.ts +11 -0
  44. package/dist/capability-tool.d.ts.map +1 -0
  45. package/dist/capability-tool.js +25 -0
  46. package/dist/capability-tool.js.map +1 -0
  47. package/dist/capability-web-host.d.ts +11 -0
  48. package/dist/capability-web-host.d.ts.map +1 -0
  49. package/dist/capability-web-host.js +105 -0
  50. package/dist/capability-web-host.js.map +1 -0
  51. package/dist/catalog.d.ts +27 -0
  52. package/dist/catalog.d.ts.map +1 -0
  53. package/dist/catalog.js +59 -0
  54. package/dist/catalog.js.map +1 -0
  55. package/dist/codecs/agent-profile.d.ts +53 -0
  56. package/dist/codecs/agent-profile.d.ts.map +1 -0
  57. package/dist/codecs/agent-profile.js +176 -0
  58. package/dist/codecs/agent-profile.js.map +1 -0
  59. package/dist/codecs/capability.d.ts +71 -0
  60. package/dist/codecs/capability.d.ts.map +1 -0
  61. package/dist/codecs/capability.js +363 -0
  62. package/dist/codecs/capability.js.map +1 -0
  63. package/dist/codecs/index.d.ts +5 -0
  64. package/dist/codecs/index.d.ts.map +1 -0
  65. package/dist/codecs/index.js +3 -0
  66. package/dist/codecs/index.js.map +1 -0
  67. package/dist/codecs/prompt-stack.d.ts +18 -0
  68. package/dist/codecs/prompt-stack.d.ts.map +1 -0
  69. package/dist/codecs/prompt-stack.js +623 -0
  70. package/dist/codecs/prompt-stack.js.map +1 -0
  71. package/dist/command-contribution/index.d.ts +21 -0
  72. package/dist/command-contribution/index.d.ts.map +1 -0
  73. package/dist/command-contribution/index.js +14 -0
  74. package/dist/command-contribution/index.js.map +1 -0
  75. package/dist/compile-cycle.d.ts +26 -0
  76. package/dist/compile-cycle.d.ts.map +1 -0
  77. package/dist/compile-cycle.js +16 -0
  78. package/dist/compile-cycle.js.map +1 -0
  79. package/dist/compiler.d.ts +22 -0
  80. package/dist/compiler.d.ts.map +1 -0
  81. package/dist/compiler.js +737 -0
  82. package/dist/compiler.js.map +1 -0
  83. package/dist/context-diff-history.d.ts +69 -0
  84. package/dist/context-diff-history.d.ts.map +1 -0
  85. package/dist/context-diff-history.js +107 -0
  86. package/dist/context-diff-history.js.map +1 -0
  87. package/dist/context-diff-snapshot.d.ts +19 -0
  88. package/dist/context-diff-snapshot.d.ts.map +1 -0
  89. package/dist/context-diff-snapshot.js +146 -0
  90. package/dist/context-diff-snapshot.js.map +1 -0
  91. package/dist/context-diff.d.ts +70 -0
  92. package/dist/context-diff.d.ts.map +1 -0
  93. package/dist/context-diff.js +259 -0
  94. package/dist/context-diff.js.map +1 -0
  95. package/dist/extension-registry.d.ts +25 -0
  96. package/dist/extension-registry.d.ts.map +1 -0
  97. package/dist/extension-registry.js +9 -0
  98. package/dist/extension-registry.js.map +1 -0
  99. package/dist/forge-command.d.ts +10 -0
  100. package/dist/forge-command.d.ts.map +1 -0
  101. package/dist/forge-command.js +106 -0
  102. package/dist/forge-command.js.map +1 -0
  103. package/dist/forge-config.d.ts +9 -0
  104. package/dist/forge-config.d.ts.map +1 -0
  105. package/dist/forge-config.js +15 -0
  106. package/dist/forge-config.js.map +1 -0
  107. package/dist/forge-extensions.d.ts +28 -0
  108. package/dist/forge-extensions.d.ts.map +1 -0
  109. package/dist/forge-extensions.js +198 -0
  110. package/dist/forge-extensions.js.map +1 -0
  111. package/dist/forge-v1/analyzer.d.ts +3 -0
  112. package/dist/forge-v1/analyzer.d.ts.map +1 -0
  113. package/dist/forge-v1/analyzer.js +50 -0
  114. package/dist/forge-v1/analyzer.js.map +1 -0
  115. package/dist/forge-v1/index.d.ts +6 -0
  116. package/dist/forge-v1/index.d.ts.map +1 -0
  117. package/dist/forge-v1/index.js +13 -0
  118. package/dist/forge-v1/index.js.map +1 -0
  119. package/dist/forge-v1/parser.d.ts +3 -0
  120. package/dist/forge-v1/parser.d.ts.map +1 -0
  121. package/dist/forge-v1/parser.js +186 -0
  122. package/dist/forge-v1/parser.js.map +1 -0
  123. package/dist/forge-v1/renderer.d.ts +9 -0
  124. package/dist/forge-v1/renderer.d.ts.map +1 -0
  125. package/dist/forge-v1/renderer.js +181 -0
  126. package/dist/forge-v1/renderer.js.map +1 -0
  127. package/dist/forge-v1/types.d.ts +87 -0
  128. package/dist/forge-v1/types.d.ts.map +1 -0
  129. package/dist/forge-v1/types.js +4 -0
  130. package/dist/forge-v1/types.js.map +1 -0
  131. package/dist/host-compatibility.d.ts +13 -0
  132. package/dist/host-compatibility.d.ts.map +1 -0
  133. package/dist/host-compatibility.js +41 -0
  134. package/dist/host-compatibility.js.map +1 -0
  135. package/dist/index.d.ts +15 -0
  136. package/dist/index.d.ts.map +1 -0
  137. package/dist/index.js +183 -0
  138. package/dist/index.js.map +1 -0
  139. package/dist/json-fingerprint.d.ts +11 -0
  140. package/dist/json-fingerprint.d.ts.map +1 -0
  141. package/dist/json-fingerprint.js +66 -0
  142. package/dist/json-fingerprint.js.map +1 -0
  143. package/dist/lifecycle.d.ts +46 -0
  144. package/dist/lifecycle.d.ts.map +1 -0
  145. package/dist/lifecycle.js +330 -0
  146. package/dist/lifecycle.js.map +1 -0
  147. package/dist/loader.d.ts +21 -0
  148. package/dist/loader.d.ts.map +1 -0
  149. package/dist/loader.js +58 -0
  150. package/dist/loader.js.map +1 -0
  151. package/dist/macro-engine.d.ts +18 -0
  152. package/dist/macro-engine.d.ts.map +1 -0
  153. package/dist/macro-engine.js +29 -0
  154. package/dist/macro-engine.js.map +1 -0
  155. package/dist/payload-capture.d.ts +31 -0
  156. package/dist/payload-capture.d.ts.map +1 -0
  157. package/dist/payload-capture.js +253 -0
  158. package/dist/payload-capture.js.map +1 -0
  159. package/dist/payload-command.d.ts +12 -0
  160. package/dist/payload-command.d.ts.map +1 -0
  161. package/dist/payload-command.js +197 -0
  162. package/dist/payload-command.js.map +1 -0
  163. package/dist/payload-state.d.ts +20 -0
  164. package/dist/payload-state.d.ts.map +1 -0
  165. package/dist/payload-state.js +20 -0
  166. package/dist/payload-state.js.map +1 -0
  167. package/dist/policy.d.ts +7 -0
  168. package/dist/policy.d.ts.map +1 -0
  169. package/dist/policy.js +41 -0
  170. package/dist/policy.js.map +1 -0
  171. package/dist/preset-command.d.ts +19 -0
  172. package/dist/preset-command.d.ts.map +1 -0
  173. package/dist/preset-command.js +261 -0
  174. package/dist/preset-command.js.map +1 -0
  175. package/dist/preview-inspection.d.ts +68 -0
  176. package/dist/preview-inspection.d.ts.map +1 -0
  177. package/dist/preview-inspection.js +293 -0
  178. package/dist/preview-inspection.js.map +1 -0
  179. package/dist/preview-text.d.ts +5 -0
  180. package/dist/preview-text.d.ts.map +1 -0
  181. package/dist/preview-text.js +27 -0
  182. package/dist/preview-text.js.map +1 -0
  183. package/dist/preview.d.ts +32 -0
  184. package/dist/preview.d.ts.map +1 -0
  185. package/dist/preview.js +272 -0
  186. package/dist/preview.js.map +1 -0
  187. package/dist/profile-command.d.ts +17 -0
  188. package/dist/profile-command.d.ts.map +1 -0
  189. package/dist/profile-command.js +385 -0
  190. package/dist/profile-command.js.map +1 -0
  191. package/dist/profile-service.d.ts +107 -0
  192. package/dist/profile-service.d.ts.map +1 -0
  193. package/dist/profile-service.js +248 -0
  194. package/dist/profile-service.js.map +1 -0
  195. package/dist/prompt-analysis.d.ts +24 -0
  196. package/dist/prompt-analysis.d.ts.map +1 -0
  197. package/dist/prompt-analysis.js +84 -0
  198. package/dist/prompt-analysis.js.map +1 -0
  199. package/dist/prompt-cache-warning.d.ts +23 -0
  200. package/dist/prompt-cache-warning.d.ts.map +1 -0
  201. package/dist/prompt-cache-warning.js +74 -0
  202. package/dist/prompt-cache-warning.js.map +1 -0
  203. package/dist/prompt-runtime.d.ts +19 -0
  204. package/dist/prompt-runtime.d.ts.map +1 -0
  205. package/dist/prompt-runtime.js +34 -0
  206. package/dist/prompt-runtime.js.map +1 -0
  207. package/dist/regex.d.ts +19 -0
  208. package/dist/regex.d.ts.map +1 -0
  209. package/dist/regex.js +507 -0
  210. package/dist/regex.js.map +1 -0
  211. package/dist/render-helpers.d.ts +38 -0
  212. package/dist/render-helpers.d.ts.map +1 -0
  213. package/dist/render-helpers.js +85 -0
  214. package/dist/render-helpers.js.map +1 -0
  215. package/dist/repositories/agent-profile.d.ts +36 -0
  216. package/dist/repositories/agent-profile.d.ts.map +1 -0
  217. package/dist/repositories/agent-profile.js +153 -0
  218. package/dist/repositories/agent-profile.js.map +1 -0
  219. package/dist/repositories/capability.d.ts +53 -0
  220. package/dist/repositories/capability.d.ts.map +1 -0
  221. package/dist/repositories/capability.js +294 -0
  222. package/dist/repositories/capability.js.map +1 -0
  223. package/dist/repositories/index.d.ts +3 -0
  224. package/dist/repositories/index.d.ts.map +1 -0
  225. package/dist/repositories/index.js +3 -0
  226. package/dist/repositories/index.js.map +1 -0
  227. package/dist/repositories/prompt-stack.d.ts +57 -0
  228. package/dist/repositories/prompt-stack.d.ts.map +1 -0
  229. package/dist/repositories/prompt-stack.js +175 -0
  230. package/dist/repositories/prompt-stack.js.map +1 -0
  231. package/dist/resource-identity.d.ts +33 -0
  232. package/dist/resource-identity.d.ts.map +1 -0
  233. package/dist/resource-identity.js +56 -0
  234. package/dist/resource-identity.js.map +1 -0
  235. package/dist/runtime/capability-runtime.d.ts +95 -0
  236. package/dist/runtime/capability-runtime.d.ts.map +1 -0
  237. package/dist/runtime/capability-runtime.js +991 -0
  238. package/dist/runtime/capability-runtime.js.map +1 -0
  239. package/dist/runtime/profile-runtime.d.ts +14 -0
  240. package/dist/runtime/profile-runtime.d.ts.map +1 -0
  241. package/dist/runtime/profile-runtime.js +56 -0
  242. package/dist/runtime/profile-runtime.js.map +1 -0
  243. package/dist/runtime/prompt-stack-runtime.d.ts +27 -0
  244. package/dist/runtime/prompt-stack-runtime.d.ts.map +1 -0
  245. package/dist/runtime/prompt-stack-runtime.js +149 -0
  246. package/dist/runtime/prompt-stack-runtime.js.map +1 -0
  247. package/dist/runtime/tool-policy-runtime.d.ts +25 -0
  248. package/dist/runtime/tool-policy-runtime.d.ts.map +1 -0
  249. package/dist/runtime/tool-policy-runtime.js +386 -0
  250. package/dist/runtime/tool-policy-runtime.js.map +1 -0
  251. package/dist/runtime/web-editor-runtime.d.ts +11 -0
  252. package/dist/runtime/web-editor-runtime.d.ts.map +1 -0
  253. package/dist/runtime/web-editor-runtime.js +141 -0
  254. package/dist/runtime/web-editor-runtime.js.map +1 -0
  255. package/dist/session-adapter.d.ts +30 -0
  256. package/dist/session-adapter.d.ts.map +1 -0
  257. package/dist/session-adapter.js +167 -0
  258. package/dist/session-adapter.js.map +1 -0
  259. package/dist/session-state.d.ts +23 -0
  260. package/dist/session-state.d.ts.map +1 -0
  261. package/dist/session-state.js +44 -0
  262. package/dist/session-state.js.map +1 -0
  263. package/dist/session-usage.d.ts +65 -0
  264. package/dist/session-usage.d.ts.map +1 -0
  265. package/dist/session-usage.js +134 -0
  266. package/dist/session-usage.js.map +1 -0
  267. package/dist/slot-renderers.d.ts +38 -0
  268. package/dist/slot-renderers.d.ts.map +1 -0
  269. package/dist/slot-renderers.js +285 -0
  270. package/dist/slot-renderers.js.map +1 -0
  271. package/dist/stack-migration.d.ts +35 -0
  272. package/dist/stack-migration.d.ts.map +1 -0
  273. package/dist/stack-migration.js +123 -0
  274. package/dist/stack-migration.js.map +1 -0
  275. package/dist/status-text.d.ts +6 -0
  276. package/dist/status-text.d.ts.map +1 -0
  277. package/dist/status-text.js +11 -0
  278. package/dist/status-text.js.map +1 -0
  279. package/dist/storage.d.ts +24 -0
  280. package/dist/storage.d.ts.map +1 -0
  281. package/dist/storage.js +94 -0
  282. package/dist/storage.js.map +1 -0
  283. package/dist/subagent/fingerprints.d.ts +12 -0
  284. package/dist/subagent/fingerprints.d.ts.map +1 -0
  285. package/dist/subagent/fingerprints.js +17 -0
  286. package/dist/subagent/fingerprints.js.map +1 -0
  287. package/dist/subagent/host-port.d.ts +296 -0
  288. package/dist/subagent/host-port.d.ts.map +1 -0
  289. package/dist/subagent/host-port.js +560 -0
  290. package/dist/subagent/host-port.js.map +1 -0
  291. package/dist/subagent/index.d.ts +16 -0
  292. package/dist/subagent/index.d.ts.map +1 -0
  293. package/dist/subagent/index.js +15 -0
  294. package/dist/subagent/index.js.map +1 -0
  295. package/dist/subagent-host.d.ts +125 -0
  296. package/dist/subagent-host.d.ts.map +1 -0
  297. package/dist/subagent-host.js +327 -0
  298. package/dist/subagent-host.js.map +1 -0
  299. package/dist/template-render.d.ts +18 -0
  300. package/dist/template-render.d.ts.map +1 -0
  301. package/dist/template-render.js +232 -0
  302. package/dist/template-render.js.map +1 -0
  303. package/dist/types.d.ts +213 -0
  304. package/dist/types.d.ts.map +1 -0
  305. package/dist/types.js +2 -0
  306. package/dist/types.js.map +1 -0
  307. package/dist/ui-contribution/contrib-port.d.ts +170 -0
  308. package/dist/ui-contribution/contrib-port.d.ts.map +1 -0
  309. package/dist/ui-contribution/contrib-port.js +640 -0
  310. package/dist/ui-contribution/contrib-port.js.map +1 -0
  311. package/dist/ui-contribution/index.d.ts +3 -0
  312. package/dist/ui-contribution/index.d.ts.map +1 -0
  313. package/dist/ui-contribution/index.js +2 -0
  314. package/dist/ui-contribution/index.js.map +1 -0
  315. package/dist/web-editor/client-script.d.ts +2 -0
  316. package/dist/web-editor/client-script.d.ts.map +1 -0
  317. package/dist/web-editor/client-script.generated.d.ts +2 -0
  318. package/dist/web-editor/client-script.generated.d.ts.map +1 -0
  319. package/dist/web-editor/client-script.generated.js +3 -0
  320. package/dist/web-editor/client-script.generated.js.map +1 -0
  321. package/dist/web-editor/client-script.js +2 -0
  322. package/dist/web-editor/client-script.js.map +1 -0
  323. package/dist/web-editor/client-styles.d.ts +2 -0
  324. package/dist/web-editor/client-styles.d.ts.map +1 -0
  325. package/dist/web-editor/client-styles.generated.d.ts +2 -0
  326. package/dist/web-editor/client-styles.generated.d.ts.map +1 -0
  327. package/dist/web-editor/client-styles.generated.js +3 -0
  328. package/dist/web-editor/client-styles.generated.js.map +1 -0
  329. package/dist/web-editor/client-styles.js +2 -0
  330. package/dist/web-editor/client-styles.js.map +1 -0
  331. package/dist/web-editor/contrib-service.d.ts +41 -0
  332. package/dist/web-editor/contrib-service.d.ts.map +1 -0
  333. package/dist/web-editor/contrib-service.js +174 -0
  334. package/dist/web-editor/contrib-service.js.map +1 -0
  335. package/dist/web-editor/index.d.ts +3 -0
  336. package/dist/web-editor/index.d.ts.map +1 -0
  337. package/dist/web-editor/index.js +2 -0
  338. package/dist/web-editor/index.js.map +1 -0
  339. package/dist/web-editor/line-diff.d.ts +28 -0
  340. package/dist/web-editor/line-diff.d.ts.map +1 -0
  341. package/dist/web-editor/line-diff.js +216 -0
  342. package/dist/web-editor/line-diff.js.map +1 -0
  343. package/dist/web-editor/page.d.ts +4 -0
  344. package/dist/web-editor/page.d.ts.map +1 -0
  345. package/dist/web-editor/page.js +26 -0
  346. package/dist/web-editor/page.js.map +1 -0
  347. package/dist/web-editor/schema-form.d.ts +63 -0
  348. package/dist/web-editor/schema-form.d.ts.map +1 -0
  349. package/dist/web-editor/schema-form.js +213 -0
  350. package/dist/web-editor/schema-form.js.map +1 -0
  351. package/dist/web-editor/server.d.ts +4 -0
  352. package/dist/web-editor/server.d.ts.map +1 -0
  353. package/dist/web-editor/server.js +637 -0
  354. package/dist/web-editor/server.js.map +1 -0
  355. package/dist/web-editor/styles.d.ts +2 -0
  356. package/dist/web-editor/styles.d.ts.map +1 -0
  357. package/dist/web-editor/styles.js +1744 -0
  358. package/dist/web-editor/styles.js.map +1 -0
  359. package/dist/web-editor/types.d.ts +304 -0
  360. package/dist/web-editor/types.d.ts.map +1 -0
  361. package/dist/web-editor/types.js +2 -0
  362. package/dist/web-editor/types.js.map +1 -0
  363. package/dist/web-host.d.ts +56 -0
  364. package/dist/web-host.d.ts.map +1 -0
  365. package/dist/web-host.js +750 -0
  366. package/dist/web-host.js.map +1 -0
  367. package/dist/workspace.d.ts +85 -0
  368. package/dist/workspace.d.ts.map +1 -0
  369. package/dist/workspace.js +409 -0
  370. package/dist/workspace.js.map +1 -0
  371. package/docs/README.md +49 -0
  372. package/docs/concepts/agent-profiles.md +62 -0
  373. package/docs/concepts/prompt-stacks.md +99 -0
  374. package/docs/design/0.5.1-plan.md +237 -0
  375. package/docs/design/README.md +37 -0
  376. package/docs/design/architecture-0.5.md +254 -0
  377. package/docs/design/archive/0.5-full-proposal/0.5-consumer-audit.md +62 -0
  378. package/docs/design/archive/0.5-full-proposal/0.5-inventory.md +208 -0
  379. package/docs/design/archive/0.5-full-proposal/0.5-phase0-decision-drafts.md +237 -0
  380. package/docs/design/archive/0.5-full-proposal/README.md +12 -0
  381. package/docs/design/archive/0.5-full-proposal/architecture-0.5.md +423 -0
  382. package/docs/design/archive/0.5-full-proposal/host-discovery-spike.md +103 -0
  383. package/docs/design/archive/0.5-full-proposal/template-language-spike.md +156 -0
  384. package/docs/design/archive/2026-09-12-system-update-design.md +229 -0
  385. package/docs/design/context-diff-plan.md +78 -0
  386. package/docs/design/decision-template.md +33 -0
  387. package/docs/design/pi-forge-system-update-design-notes.md +157 -0
  388. package/docs/design/roadmap-0.4-archive.md +216 -0
  389. package/docs/design/subagents/design-review.md +220 -0
  390. package/docs/design/subagents/interface-design.md +274 -0
  391. package/docs/design/subagents/sdk-spike-findings.md +117 -0
  392. package/docs/development/architecture-rules.md +148 -0
  393. package/docs/development/complexity-review.md +86 -0
  394. package/docs/development/release.md +59 -0
  395. package/docs/development/roadmap.md +117 -0
  396. package/docs/development/scoped-global-profiles-stacks.md +325 -0
  397. package/docs/development/setup.md +99 -0
  398. package/docs/getting-started.md +96 -0
  399. package/docs/guides/custom-macros-and-slots.md +69 -0
  400. package/docs/guides/debugging.md +39 -0
  401. package/docs/guides/delegation.md +105 -0
  402. package/docs/guides/migrating-to-0.5.md +136 -0
  403. package/docs/guides/pi-1-compatibility.md +160 -0
  404. package/docs/guides/use-cases.md +67 -0
  405. package/docs/guides/web-editor.md +161 -0
  406. package/docs/reference/active-state.md +77 -0
  407. package/docs/reference/capabilities.md +288 -0
  408. package/docs/reference/commands.md +89 -0
  409. package/docs/reference/configuration.md +70 -0
  410. package/docs/reference/features.md +305 -0
  411. package/docs/reference/macros-and-slots.md +103 -0
  412. package/docs/reference/provider-support.md +67 -0
  413. package/docs/reference/public-api.md +133 -0
  414. package/docs/reference/session-cache.md +112 -0
  415. package/docs/reference/stack-schema.md +243 -0
  416. package/docs/reference/subagent-host-port.md +57 -0
  417. package/docs/reference/ui-contribution-port.md +51 -0
  418. package/docs/zh-CN/README.md +41 -0
  419. package/docs/zh-CN/concepts/agent-profiles.md +48 -0
  420. package/docs/zh-CN/concepts/prompt-stacks.md +48 -0
  421. package/docs/zh-CN/getting-started.md +82 -0
  422. package/docs/zh-CN/guides/delegation.md +76 -0
  423. package/docs/zh-CN/guides/migrating-to-0.5.md +121 -0
  424. package/docs/zh-CN/guides/pi-1-compatibility.md +158 -0
  425. package/docs/zh-CN/guides/web-editor.md +134 -0
  426. package/docs/zh-CN/reference/capabilities.md +288 -0
  427. package/docs/zh-CN/reference/commands.md +89 -0
  428. package/docs/zh-CN/reference/provider-support.md +67 -0
  429. package/docs/zh-CN/reference/session-cache.md +112 -0
  430. package/examples/capabilities/review.json +12 -0
  431. package/examples/capabilities/write-tools.json +15 -0
  432. package/examples/custom-system-status-extension/index.ts +144 -0
  433. package/examples/custom-system-status-extension/prompt-stack.json +40 -0
  434. package/examples/default-prompt-stack.json +125 -0
  435. package/examples/fake-assistant-direct-output-prompt-stack.json +48 -0
  436. package/examples/hack-prompt-stack.json +118 -0
  437. package/examples/minimal-prompt-stack.json +40 -0
  438. package/examples/read-first-worker-prompt-stack.json +49 -0
  439. package/examples/validation-issues-prompt-stack.json +38 -0
  440. package/package.json +114 -4
@@ -0,0 +1,750 @@
1
+ import { parsePromptStack, serializePromptStack } from "./codecs/prompt-stack.js";
2
+ import { capabilityOperation } from "./capability-web-host.js";
3
+ import { createHash, randomUUID } from "node:crypto";
4
+ import { closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
5
+ import { basename, dirname, join } from "node:path";
6
+ import { agentProfilePath, agentProfilesDir, isResolvedAgentProfileUsable, validateAgentProfile, validateAgentProfilePromptStackScope, } from "./agent-profile.js";
7
+ import { isValidPromptStackId, validatePromptStack, } from "./loader.js";
8
+ import { getRegisteredMacros } from "./macro-engine.js";
9
+ import { deletePromptStackFile, promptStackTargetPath, writePromptStackFile, } from "./repositories/prompt-stack.js";
10
+ import { globalAgentProfilePath } from "./storage.js";
11
+ import { formatResourceKey, parseResourceSelector } from "./resource-identity.js";
12
+ import { getRegisteredSlots } from "./slot-renderers.js";
13
+ import { resolveResourceSelector } from "./catalog.js";
14
+ import { createAgentProfilePreview, deleteAgentProfile, getAgentProfileRuntimeStatus, writeAgentProfile, } from "./profile-service.js";
15
+ import { isCapabilityStateMutation, isCapabilityEnableRequest, } from "./capability-state.js";
16
+ export function createWebEditorHost(ctx, runtime) {
17
+ return {
18
+ cwd: ctx.cwd,
19
+ capabilityOperation: (action, selector, input) => capabilityOperation(ctx, runtime, action, selector, input),
20
+ isProjectTrusted: () => ctx.isProjectTrusted(),
21
+ readCapabilityState: () => {
22
+ if (!runtime.readCapabilityState) {
23
+ return { ok: false, status: 503, error: "Capability runtime is unavailable." };
24
+ }
25
+ return runtime.readCapabilityState();
26
+ },
27
+ previewCapabilities: () => {
28
+ if (!runtime.readCapabilityState) {
29
+ return { ok: false, status: 503, error: "Capability runtime is unavailable." };
30
+ }
31
+ try {
32
+ const initial = runtime.readCapabilityState();
33
+ if (!initial.ok)
34
+ return initial;
35
+ if (!initial.state.trusted)
36
+ return { ok: false, status: 403, error: "Project is not trusted." };
37
+ if (initial.state.restoring)
38
+ return { ok: false, status: 503, error: "Capability session is restoring." };
39
+ if (!capabilityGuardMatchesContext(ctx, initial.state.guard)) {
40
+ return { ok: false, status: 409, error: "Session or branch changed. Refresh and review." };
41
+ }
42
+ const target = runtime.getActive();
43
+ if (!target)
44
+ return { ok: false, status: 409, error: "No active preset is selected for capability preview." };
45
+ const built = runtime.buildPreview(target);
46
+ const final = runtime.readCapabilityState();
47
+ if (!final.ok)
48
+ return final;
49
+ if (!sameCapabilityGuard(initial.state.guard, final.state.guard)
50
+ || initial.state.presetRevision !== final.state.presetRevision
51
+ || !capabilityGuardMatchesContext(ctx, final.state.guard)
52
+ || runtime.getActive() !== target) {
53
+ return { ok: false, status: 409, error: "Session, branch, capability state, or active preset changed during preview. Refresh and review." };
54
+ }
55
+ return {
56
+ ok: true,
57
+ state: final.state,
58
+ preset: {
59
+ selector: formatResourceKey(target.key),
60
+ ...(target.stack.name === undefined ? {} : { name: target.stack.name }),
61
+ },
62
+ text: built.text,
63
+ preview: built.preview,
64
+ diagnostics: built.diagnostics,
65
+ };
66
+ }
67
+ catch (error) {
68
+ return { ok: false, status: 503, error: `Capability preview unavailable: ${error instanceof Error ? error.message : String(error)}` };
69
+ }
70
+ },
71
+ readCapabilityChoices: () => {
72
+ if (!runtime.readCapabilityChoices) {
73
+ return { ok: false, status: 503, error: "Capability runtime is unavailable." };
74
+ }
75
+ return runtime.readCapabilityChoices();
76
+ },
77
+ mutateCapabilityState: (input) => {
78
+ try {
79
+ if (!ctx.isProjectTrusted()) {
80
+ return { ok: false, status: 403, error: "Project is not trusted; refusing to mutate capabilities." };
81
+ }
82
+ }
83
+ catch {
84
+ return { ok: false, status: 503, error: "Capability session is unavailable." };
85
+ }
86
+ if (!runtime.mutateCapabilityState) {
87
+ return { ok: false, status: 503, error: "Capability runtime is unavailable." };
88
+ }
89
+ if (!isCapabilityStateMutation(input)) {
90
+ return { ok: false, status: 400, error: "Invalid capability state mutation payload." };
91
+ }
92
+ return runtime.mutateCapabilityState(input);
93
+ },
94
+ enableCapability: (input) => {
95
+ try {
96
+ if (!ctx.isProjectTrusted())
97
+ return { ok: false, status: 403, error: "Project is not trusted; refusing to activate capabilities." };
98
+ }
99
+ catch {
100
+ return { ok: false, status: 503, error: "Capability session is unavailable." };
101
+ }
102
+ if (!runtime.enableCapability)
103
+ return { ok: false, status: 503, error: "Capability runtime is unavailable." };
104
+ if (!isCapabilityEnableRequest(input))
105
+ return { ok: false, status: 400, error: "Invalid capability activation payload." };
106
+ return runtime.enableCapability(input);
107
+ },
108
+ getEditorConfig: () => ({ locale: loadWebEditorSettings(ctx).locale ?? "auto" }),
109
+ setEditorLocale: (locale) => saveWebEditorLocale(ctx, locale),
110
+ listStacks: () => stackSummaries(runtime.getStacks(), runtime.getActive()),
111
+ listProfiles: () => profileCollection(ctx, runtime),
112
+ reloadProfiles: async () => {
113
+ await runtime.reloadProfiles();
114
+ return { ok: true, ...profileCollection(ctx, runtime) };
115
+ },
116
+ validateProfile: (profile, existingId, scope) => profileValidation(ctx, runtime, profile, existingId, scope),
117
+ createProfile: (profile, scope) => createProfileFile(ctx, runtime, profile, scope),
118
+ saveProfile: (selector, profile) => saveProfileFile(ctx, runtime, selector, profile),
119
+ applyProfile: (selector) => applyProfileRuntime(ctx, runtime, selector),
120
+ deleteProfile: (selector) => deleteProfileFile(ctx, runtime, selector),
121
+ listResources: () => editorResources(runtime.getPolicyResources()),
122
+ getStack: (selector) => {
123
+ const loaded = resolveStack(runtime, selector);
124
+ if (!loaded)
125
+ return undefined;
126
+ // The revision and editable definition must describe the SAME bytes,
127
+ // not cached authorization paired with a newly-read hash.
128
+ const source = readFileSync(loaded.filePath);
129
+ const fresh = parsePromptStack(source.toString("utf8"), loaded.filePath, loaded.scope);
130
+ return { stack: fresh.stack, filePath: loaded.filePath, diagnostics: fresh.diagnostics,
131
+ selector: formatResourceKey(loaded.key), scope: loaded.scope,
132
+ sourceRevision: createHash("sha256").update(source).digest("hex") };
133
+ },
134
+ createStack: (stack, options) => createStackFile(ctx, runtime, stack, options),
135
+ saveStack: (id, stack, expectedSourceRevision) => saveStackFile(ctx, runtime, id, stack, expectedSourceRevision),
136
+ deleteStack: (id) => deleteStackFile(ctx, runtime, id),
137
+ validateStack: (stack) => validatePromptStack(stack),
138
+ previewStack: (id, stack) => {
139
+ const hostError = runtime.activationError?.();
140
+ if (hostError)
141
+ return { ok: false, status: 409, error: hostError };
142
+ const target = resolveStack(runtime, id);
143
+ if (!target)
144
+ return { ok: false, status: 404, error: `Unknown preset: ${id}` };
145
+ const diagnostics = validatePromptStack(stack);
146
+ const preview = runtime.buildPreview({ stack, filePath: target.filePath, scope: target.scope, key: target.key, diagnostics });
147
+ return { ok: true, text: preview.text, preview: preview.preview, diagnostics: preview.diagnostics };
148
+ },
149
+ getPayload: () => runtime.getPayload(),
150
+ armPayload: (savePath) => runtime.armPayload(savePath),
151
+ clearPayload: () => runtime.clearPayload(),
152
+ getContextDiff: () => runtime.getContextDiff(),
153
+ activateStack: (selector) => {
154
+ const hostError = runtime.activationError?.();
155
+ if (hostError)
156
+ return { ok: false, status: 409, error: hostError };
157
+ if (!runtime.setActive(selector)) {
158
+ const error = runtime.lastActivationError?.() ?? `Unknown preset: ${selector}`;
159
+ const status = !ctx.isProjectTrusted() ? 403 : resolveStack(runtime, selector) ? 409 : 404;
160
+ return { ok: false, status, error };
161
+ }
162
+ return { ok: true, activeId: runtime.getActiveId(), stacks: stackSummaries(runtime.getStacks(), runtime.getActive()) };
163
+ },
164
+ disableStacks: () => {
165
+ if (!runtime.setActive("none")) {
166
+ const error = runtime.lastActivationError?.() ?? "Failed to disable preset";
167
+ const status = !ctx.isProjectTrusted() ? 403 : 409;
168
+ return { ok: false, status, error };
169
+ }
170
+ return { ok: true, activeId: runtime.getActiveId(), stacks: stackSummaries(runtime.getStacks(), runtime.getActive()) };
171
+ },
172
+ reloadStacks: async () => {
173
+ await runtime.reloadStacks(runtime.getSelectedActiveId());
174
+ return { ok: true, activeId: runtime.getActiveId(), stacks: stackSummaries(runtime.getStacks(), runtime.getActive()) };
175
+ },
176
+ };
177
+ }
178
+ function editorResources(policy) {
179
+ const extensionResource = (definition) => ({
180
+ name: definition.name,
181
+ ...(definition.description ? { description: definition.description } : {}),
182
+ ...(definition.source ? { source: definition.source } : {}),
183
+ dependencies: [...(definition.dependencies ?? [])],
184
+ });
185
+ const byName = (a, b) => a.name.localeCompare(b.name);
186
+ return {
187
+ ...policy,
188
+ macros: getRegisteredMacros().map(extensionResource).sort(byName),
189
+ slots: getRegisteredSlots().map(extensionResource).sort(byName),
190
+ };
191
+ }
192
+ /** Unqualified selectors address project profiles only; global profiles require `global:<id>`. */
193
+ function resolveProfilesForMutation(runtime, selector) {
194
+ const parsed = parseResourceSelector(selector);
195
+ if (!parsed.ok)
196
+ return [];
197
+ const scope = parsed.selector.scope ?? "project";
198
+ return runtime.getProfiles().filter((loaded) => loaded.scope === scope && loaded.profile.id === parsed.selector.id);
199
+ }
200
+ function profileCollection(ctx, runtime) {
201
+ const profiles = runtime.getProfiles();
202
+ const current = runtime.getCurrentProfileRuntime();
203
+ const lastApplied = runtime.getLastAppliedProfile();
204
+ const availableModels = new Set(ctx.modelRegistry.getAvailable().map((model) => modelKey(model.provider, model.id)));
205
+ return {
206
+ trusted: ctx.isProjectTrusted(),
207
+ profileDirectory: agentProfilesDir(ctx.cwd),
208
+ profiles: profiles.map((loaded) => {
209
+ const resolved = runtime.resolveProfile(loaded);
210
+ const targetEffectiveTools = resolved.promptStack || resolved.loaded.profile.promptStack === null
211
+ ? runtime.previewToolNames(resolved.promptStack?.stack)
212
+ : [];
213
+ const preview = createAgentProfilePreview(resolved, current, targetEffectiveTools);
214
+ return {
215
+ profile: structuredClone(loaded.profile),
216
+ filePath: loaded.filePath,
217
+ selector: formatResourceKey(loaded.key),
218
+ scope: loaded.scope,
219
+ preview,
220
+ errors: preview.diagnostics.filter((diagnostic) => diagnostic.level === "error").length,
221
+ warnings: preview.diagnostics.filter((diagnostic) => diagnostic.level === "warning").length,
222
+ lastApplied: lastApplied?.sourcePath === loaded.filePath,
223
+ };
224
+ }),
225
+ status: getAgentProfileRuntimeStatus(profiles, lastApplied, current),
226
+ models: ctx.modelRegistry.getAll().map((model) => ({
227
+ provider: model.provider,
228
+ id: model.id,
229
+ name: model.name,
230
+ available: availableModels.has(modelKey(model.provider, model.id)),
231
+ })),
232
+ promptStacks: runtime.getStacks().map((loaded) => ({
233
+ id: loaded.stack.id,
234
+ name: loaded.stack.name,
235
+ selector: formatResourceKey(loaded.key),
236
+ scope: loaded.scope,
237
+ })),
238
+ };
239
+ }
240
+ function profileValidation(ctx, runtime, profile, existingId, validationScope) {
241
+ const profiles = runtime.getProfiles();
242
+ const existingSelector = existingId ? parseResourceSelector(existingId) : undefined;
243
+ const existingMatches = existingSelector?.ok
244
+ ? profiles.filter((loaded) => loaded.scope === (existingSelector.selector.scope ?? "project") && loaded.profile.id === existingSelector.selector.id)
245
+ : [];
246
+ const existing = existingMatches.length === 1 ? existingMatches[0] : undefined;
247
+ const scope = existing?.scope ?? validationScope ?? "project";
248
+ const filePath = existing?.filePath ?? (scope === "global" ? globalAgentProfilePath(profile.id) : agentProfilePath(ctx.cwd, profile.id));
249
+ const diagnostics = [
250
+ ...validateAgentProfile(profile),
251
+ ...validateAgentProfilePromptStackScope(profile, scope),
252
+ ];
253
+ const otherProfiles = existing
254
+ ? profiles.filter((loaded) => loaded.scope === scope && loaded.filePath !== filePath)
255
+ : profiles.filter((loaded) => loaded.scope === scope);
256
+ if (otherProfiles.some((loaded) => loaded.profile.id === profile.id)) {
257
+ diagnostics.push({
258
+ level: "error",
259
+ field: "id",
260
+ message: `Duplicate profile id: ${profile.id} already exists in another file.`,
261
+ });
262
+ }
263
+ if (!existing && existsSync(filePath)) {
264
+ diagnostics.push({
265
+ level: "error",
266
+ field: "id",
267
+ message: `Profile file already exists: ${filePath}`,
268
+ });
269
+ }
270
+ if (profile.autoActivate && otherProfiles.some((loaded) => loaded.profile.autoActivate === true)) {
271
+ diagnostics.push({
272
+ level: "error",
273
+ field: "autoActivate",
274
+ message: "Multiple profiles request auto-activation; exactly one is allowed.",
275
+ });
276
+ }
277
+ const resolved = runtime.resolveProfile({ profile, filePath, scope, key: { scope, id: profile.id }, diagnostics });
278
+ const targetEffectiveTools = resolved.promptStack || profile.promptStack === null
279
+ ? runtime.previewToolNames(resolved.promptStack?.stack)
280
+ : [];
281
+ const preview = createAgentProfilePreview(resolved, runtime.getCurrentProfileRuntime(), targetEffectiveTools);
282
+ return {
283
+ preview,
284
+ diagnostics: preview.diagnostics,
285
+ errors: preview.diagnostics.filter((diagnostic) => diagnostic.level === "error").length,
286
+ warnings: preview.diagnostics.filter((diagnostic) => diagnostic.level === "warning").length,
287
+ };
288
+ }
289
+ async function createProfileFile(ctx, runtime, profile, scope = "project") {
290
+ if (!ctx.isProjectTrusted()) {
291
+ return { ok: false, status: 403, error: "Project is not trusted; refusing to create agent profiles." };
292
+ }
293
+ if (runtime.getProfiles().some((loaded) => loaded.scope === scope && loaded.profile.id === profile.id)) {
294
+ return { ok: false, status: 409, error: `Agent profile already exists: ${profile.id}` };
295
+ }
296
+ const conflict = autoActivateConflictError(runtime.getProfiles(), profile, scope);
297
+ if (conflict)
298
+ return { ok: false, status: 409, error: conflict };
299
+ const result = writeAgentProfile(ctx.cwd, profile, { scope });
300
+ if (!result.ok)
301
+ return profileWriteError(profile.id, result);
302
+ await runtime.reloadProfiles();
303
+ return {
304
+ ok: true,
305
+ collection: profileCollection(ctx, runtime),
306
+ selectedPath: result.filePath,
307
+ };
308
+ }
309
+ async function saveProfileFile(ctx, runtime, id, profile) {
310
+ if (!ctx.isProjectTrusted()) {
311
+ return { ok: false, status: 403, error: "Project is not trusted; refusing to save agent profiles." };
312
+ }
313
+ const matches = resolveProfilesForMutation(runtime, id);
314
+ if (matches.length === 0)
315
+ return { ok: false, status: 404, error: `Unknown agent profile: ${id}` };
316
+ if (matches.length > 1) {
317
+ return { ok: false, status: 409, error: `Cannot save agent profile ${id} while duplicate profile ids exist.` };
318
+ }
319
+ if (profile.id !== matches[0].profile.id) {
320
+ return { ok: false, status: 400, error: "Profile id is immutable during save; create a new profile to use a different id." };
321
+ }
322
+ const conflict = autoActivateConflictError(runtime.getProfiles(), profile, matches[0].scope, matches[0].profile.id);
323
+ if (conflict)
324
+ return { ok: false, status: 409, error: conflict };
325
+ const result = writeAgentProfile(ctx.cwd, profile, {
326
+ filePath: matches[0].filePath,
327
+ overwrite: true,
328
+ scope: matches[0].scope,
329
+ });
330
+ if (!result.ok)
331
+ return profileWriteError(id, result);
332
+ await runtime.reloadProfiles();
333
+ return {
334
+ ok: true,
335
+ collection: profileCollection(ctx, runtime),
336
+ selectedPath: result.filePath,
337
+ };
338
+ }
339
+ function autoActivateConflictError(profiles, profile, scope, excludeId) {
340
+ if (profile.autoActivate !== true)
341
+ return undefined;
342
+ const conflict = profiles.find((loaded) => loaded.scope === scope && loaded.profile.autoActivate === true && loaded.profile.id !== excludeId);
343
+ return conflict
344
+ ? `Multiple ${scope} profiles request auto-activation; exactly one is allowed (already requested by ${conflict.profile.id}).`
345
+ : undefined;
346
+ }
347
+ async function applyProfileRuntime(ctx, runtime, id) {
348
+ const hostError = runtime.activationError?.();
349
+ if (hostError)
350
+ return { ok: false, status: 409, error: hostError };
351
+ if (!ctx.isProjectTrusted()) {
352
+ return { ok: false, status: 403, error: "Project is not trusted; refusing to apply agent profiles." };
353
+ }
354
+ if (!runtime.isIdle()) {
355
+ return { ok: false, status: 409, error: "Wait for the current agent operation to finish before applying a profile." };
356
+ }
357
+ const matches = resolveProfilesForMutation(runtime, id);
358
+ if (matches.length === 0)
359
+ return { ok: false, status: 404, error: `Unknown agent profile: ${id}` };
360
+ if (matches.length > 1) {
361
+ return { ok: false, status: 409, error: `Cannot apply agent profile ${id} while duplicate profile ids exist.` };
362
+ }
363
+ const resolved = runtime.resolveProfile(matches[0]);
364
+ if (!isResolvedAgentProfileUsable(resolved) || !resolved.model) {
365
+ return { ok: false, status: 400, error: `Agent profile ${id} failed preflight; runtime state was not changed.` };
366
+ }
367
+ const result = await runtime.applyProfile(resolved);
368
+ if (!result.ok) {
369
+ const rollback = result.rollbackErrors.length
370
+ ? ` Rollback problems: ${result.rollbackErrors.join("; ")}.`
371
+ : " Previous runtime state was restored.";
372
+ return { ok: false, status: 500, error: `${result.detail}${result.detail.endsWith(".") ? "" : "."}${rollback}` };
373
+ }
374
+ return {
375
+ ok: true,
376
+ collection: profileCollection(ctx, runtime),
377
+ selectedPath: matches[0].filePath,
378
+ };
379
+ }
380
+ async function deleteProfileFile(ctx, runtime, id) {
381
+ if (!ctx.isProjectTrusted()) {
382
+ return { ok: false, status: 403, error: "Project is not trusted; refusing to delete agent profiles." };
383
+ }
384
+ const matches = resolveProfilesForMutation(runtime, id);
385
+ if (matches.length === 0)
386
+ return { ok: false, status: 404, error: `Unknown agent profile: ${id}` };
387
+ if (matches.length > 1) {
388
+ return { ok: false, status: 409, error: `Cannot delete agent profile ${id} while duplicate profile ids exist.` };
389
+ }
390
+ const result = deleteAgentProfile(ctx.cwd, matches[0]);
391
+ if (!result.ok) {
392
+ if (result.reason === "invalid-path")
393
+ return { ok: false, status: 403, error: "Refusing to delete outside agent-profile storage." };
394
+ if (result.reason === "missing")
395
+ return { ok: false, status: 404, error: `Agent profile file is missing: ${result.filePath}` };
396
+ if (result.reason === "changed") {
397
+ return { ok: false, status: 409, error: `Agent profile ${id} changed on disk; refresh before deleting it.` };
398
+ }
399
+ return { ok: false, status: 500, error: result.error ?? `Failed to delete agent profile ${id}.` };
400
+ }
401
+ await runtime.reloadProfiles();
402
+ const collection = profileCollection(ctx, runtime);
403
+ return {
404
+ ok: true,
405
+ collection,
406
+ selectedPath: collection.profiles[0]?.filePath ?? "",
407
+ };
408
+ }
409
+ function profileWriteError(id, result) {
410
+ if (result.reason === "exists")
411
+ return { ok: false, status: 409, error: `Agent profile already exists: ${id}` };
412
+ if (result.reason === "invalid-path")
413
+ return { ok: false, status: 403, error: result.error ?? "Refusing to write outside agent-profile storage." };
414
+ if (result.reason === "validation") {
415
+ return {
416
+ ok: false,
417
+ status: 400,
418
+ error: result.diagnostics.map((diagnostic) => diagnostic.message).join(" "),
419
+ };
420
+ }
421
+ return { ok: false, status: 500, error: result.error ?? `Failed to write agent profile ${id}.` };
422
+ }
423
+ function modelKey(provider, id) {
424
+ return `${provider}\0${id}`;
425
+ }
426
+ function sameCapabilityGuard(a, b) {
427
+ return a.sessionId === b.sessionId && a.leafId === b.leafId && a.revision === b.revision;
428
+ }
429
+ function capabilityGuardMatchesContext(ctx, guard) {
430
+ return ctx.sessionManager.getSessionId() === guard.sessionId
431
+ && ctx.sessionManager.getLeafId() === guard.leafId;
432
+ }
433
+ function resolveStack(runtime, selector) {
434
+ const parsed = parseResourceSelector(selector);
435
+ if (!parsed.ok)
436
+ return undefined;
437
+ return resolveResourceSelector(runtime.getStacks(), parsed.selector);
438
+ }
439
+ export function stackSummary(loaded, active) {
440
+ const errors = loaded.diagnostics.filter((d) => d.level === "error").length;
441
+ const warnings = loaded.diagnostics.filter((d) => d.level === "warning").length;
442
+ return {
443
+ id: loaded.stack.id,
444
+ selector: formatResourceKey(loaded.key),
445
+ scope: loaded.scope,
446
+ name: loaded.stack.name,
447
+ filePath: loaded.filePath,
448
+ active: loaded === active,
449
+ autoActivate: loaded.stack.autoActivate,
450
+ mode: loaded.stack.mode ?? "replace",
451
+ itemCount: loaded.stack.items.length,
452
+ errors,
453
+ warnings,
454
+ diagnostics: loaded.diagnostics,
455
+ };
456
+ }
457
+ export function stackSummaries(stacks, active) {
458
+ return stacks.map((loaded) => stackSummary(loaded, active));
459
+ }
460
+ const WEB_EDITOR_LOCALES = new Set(["en", "zh-CN", "auto"]);
461
+ export function loadWebEditorSettings(ctx) {
462
+ const configPath = join(ctx.cwd, ".pi", "forge", "config.json");
463
+ if (!ctx.isProjectTrusted() || !existsSync(configPath)) {
464
+ return { configPath, warnings: [] };
465
+ }
466
+ let raw;
467
+ try {
468
+ raw = JSON.parse(readFileSync(configPath, "utf8"));
469
+ }
470
+ catch (error) {
471
+ return {
472
+ configPath,
473
+ warnings: [`pi-forge: failed to read ${configPath}; using editor defaults. ${error instanceof Error ? error.message : String(error)}`],
474
+ };
475
+ }
476
+ if (!isPlainObject(raw)) {
477
+ return {
478
+ configPath,
479
+ warnings: [`pi-forge: ${configPath} must be a JSON object; using editor defaults.`],
480
+ };
481
+ }
482
+ const settings = { configPath, warnings: [] };
483
+ const webEditorConfig = isPlainObject(raw.webEditor) ? raw.webEditor : undefined;
484
+ const rawPort = webEditorConfig?.port ?? raw.webEditorPort;
485
+ if (rawPort !== undefined) {
486
+ if (typeof rawPort === "number" && Number.isInteger(rawPort) && rawPort >= 1 && rawPort <= 65535) {
487
+ settings.preferredPort = rawPort;
488
+ }
489
+ else {
490
+ settings.warnings.push(`pi-forge: ${configPath} webEditor.port must be an integer from 1 to 65535; using an available editor port.`);
491
+ }
492
+ }
493
+ const rawLocale = webEditorConfig?.locale;
494
+ if (rawLocale !== undefined) {
495
+ if (typeof rawLocale === "string" && WEB_EDITOR_LOCALES.has(rawLocale)) {
496
+ settings.locale = rawLocale;
497
+ }
498
+ else {
499
+ settings.warnings.push(`pi-forge: ${configPath} webEditor.locale must be "en", "zh-CN", or "auto"; using "auto".`);
500
+ }
501
+ }
502
+ return settings;
503
+ }
504
+ function saveWebEditorLocale(ctx, locale) {
505
+ if (!ctx.isProjectTrusted()) {
506
+ return { ok: false, status: 403, error: "Project is not trusted; refusing to change editor settings." };
507
+ }
508
+ if (!WEB_EDITOR_LOCALES.has(locale)) {
509
+ return { ok: false, status: 400, error: 'webEditor.locale must be "en", "zh-CN", or "auto".' };
510
+ }
511
+ const configPath = join(ctx.cwd, ".pi", "forge", "config.json");
512
+ let raw = {};
513
+ if (existsSync(configPath)) {
514
+ try {
515
+ const parsed = JSON.parse(readFileSync(configPath, "utf8"));
516
+ if (!isPlainObject(parsed)) {
517
+ return { ok: false, status: 400, error: `pi-forge: ${configPath} must be a JSON object; fix it before changing editor settings.` };
518
+ }
519
+ raw = parsed;
520
+ }
521
+ catch (error) {
522
+ return { ok: false, status: 400, error: `pi-forge: failed to read ${configPath}; fix it before changing editor settings. ${error instanceof Error ? error.message : String(error)}` };
523
+ }
524
+ }
525
+ const webEditor = isPlainObject(raw.webEditor) ? { ...raw.webEditor } : {};
526
+ if (locale === "auto")
527
+ delete webEditor.locale;
528
+ else
529
+ webEditor.locale = locale;
530
+ if (Object.keys(webEditor).length > 0)
531
+ raw.webEditor = webEditor;
532
+ else
533
+ delete raw.webEditor;
534
+ try {
535
+ mkdirSync(dirname(configPath), { recursive: true });
536
+ writeTextFileAtomically(configPath, `${JSON.stringify(raw, null, 2)}\n`);
537
+ }
538
+ catch (error) {
539
+ return { ok: false, status: 500, error: `pi-forge: failed to write ${configPath}: ${error instanceof Error ? error.message : String(error)}` };
540
+ }
541
+ return { ok: true, locale };
542
+ }
543
+ function writeTextFileAtomically(filePath, content) {
544
+ const tempPath = join(dirname(filePath), `.${basename(filePath)}.${process.pid}.${randomUUID()}.tmp`);
545
+ let descriptor;
546
+ try {
547
+ descriptor = openSync(tempPath, "wx", 0o600);
548
+ writeFileSync(descriptor, content, "utf8");
549
+ fsyncSync(descriptor);
550
+ closeSync(descriptor);
551
+ descriptor = undefined;
552
+ renameSync(tempPath, filePath);
553
+ }
554
+ catch (error) {
555
+ if (descriptor !== undefined)
556
+ closeSync(descriptor);
557
+ if (existsSync(tempPath))
558
+ unlinkSync(tempPath);
559
+ throw error;
560
+ }
561
+ }
562
+ /** Saving the active resource changes live policy just like selecting it. */
563
+ function activePresetWriteConflict(runtime, target, stack) {
564
+ const active = runtime.getActive();
565
+ if (!active || formatResourceKey(active.key) !== formatResourceKey(target.key))
566
+ return undefined;
567
+ try {
568
+ // Validate the same normalized policy that reload will consume, but keep
569
+ // the original authored object for the existing lossless write path.
570
+ const prospective = parsePromptStack(serializePromptStack(stack), target.filePath, target.scope);
571
+ const error = runtime.validatePresetSwitch?.(prospective);
572
+ return error ? `Cannot save active preset "${stack.id}": ${error} Disable conflicting capabilities before saving.` : undefined;
573
+ }
574
+ catch (error) {
575
+ return error instanceof Error ? error.message : String(error);
576
+ }
577
+ }
578
+ async function saveStackFile(ctx, runtime, id, stack, expectedSourceRevision) {
579
+ if (!ctx.isProjectTrusted()) {
580
+ return { ok: false, status: 403, error: "Project is not trusted; refusing to save presets." };
581
+ }
582
+ const target = resolveStack(runtime, id);
583
+ if (!target)
584
+ return { ok: false, status: 404, error: `Unknown preset: ${id}` };
585
+ const idError = validateWebStackId(stack.id);
586
+ if (idError)
587
+ return { ok: false, status: 400, error: idError };
588
+ if (stack.id !== target.stack.id) {
589
+ return { ok: false, status: 400, error: "Preset id is immutable during save; fork the preset to create a new id." };
590
+ }
591
+ // Binding-bearing stacks use a stale-view check because their authorization
592
+ // can be revoked outside this editor. Keep the check immediately adjacent to
593
+ // the synchronous write; this is deliberately not a cross-process CAS.
594
+ if (hasRejectedLegacyPromptStackKey(stack)) {
595
+ return { ok: false, status: 400, error: rejectedLegacyPromptStackMessage() };
596
+ }
597
+ let diskHasBindings = false;
598
+ try {
599
+ const diskStack = JSON.parse(readFileSync(target.filePath, "utf8"));
600
+ if (hasRejectedLegacyPromptStackKey(diskStack)) {
601
+ return { ok: false, status: 409, error: rejectedLegacyPromptStackMessage() };
602
+ }
603
+ diskHasBindings = isPlainObject(diskStack) && diskStack.capabilities !== undefined;
604
+ }
605
+ catch {
606
+ return { ok: false, status: 409, error: "Preset source unavailable or malformed; reload before saving." };
607
+ }
608
+ const requiresSourceRevision = diskHasBindings || target.stack.capabilities !== undefined || stack.capabilities !== undefined;
609
+ if (expectedSourceRevision !== undefined || requiresSourceRevision) {
610
+ let currentSourceRevision;
611
+ try {
612
+ currentSourceRevision = promptStackSourceRevision(target.filePath);
613
+ }
614
+ catch {
615
+ return { ok: false, status: 409, error: "Preset source changed and could not be verified; reload before saving." };
616
+ }
617
+ if (expectedSourceRevision === undefined || expectedSourceRevision !== currentSourceRevision) {
618
+ return { ok: false, status: 409, error: "Preset source changed; reload before saving to avoid overwriting capability bindings." };
619
+ }
620
+ }
621
+ const policyConflict = activePresetWriteConflict(runtime, target, stack);
622
+ if (policyConflict)
623
+ return { ok: false, status: 409, error: policyConflict };
624
+ const write = writePromptStackFile(ctx.cwd, target.scope, target.filePath, stack, { overwrite: true });
625
+ if (!write.ok) {
626
+ // With overwrite: true the repository can fail on containment (403) or I/O (500).
627
+ const status = stackMutationStatus(write.reason);
628
+ return { ok: false, status, error: write.error };
629
+ }
630
+ // Receipt for precisely this write, not a later read after the asynchronous reload.
631
+ const sourceRevision = createHash("sha256").update(serializePromptStack(stack)).digest("hex");
632
+ const preferredId = runtime.getActive() === target ? formatResourceKey(target.key) : runtime.getSelectedActiveId();
633
+ await runtime.reloadStacks(preferredId);
634
+ const saved = runtime.getStacks().find((candidate) => candidate.scope === target.scope && candidate.stack.id === target.stack.id)
635
+ ?? runtime.getStacks().find((candidate) => candidate.filePath === target.filePath);
636
+ if (!saved)
637
+ return { ok: false, status: 500, error: "Saved preset could not be reloaded." };
638
+ return { ok: true, stack: stackSummary(saved, runtime.getActive()), stacks: stackSummaries(runtime.getStacks(), runtime.getActive()), sourceRevision };
639
+ }
640
+ async function createStackFile(ctx, runtime, stack, options) {
641
+ if (!ctx.isProjectTrusted()) {
642
+ return { ok: false, status: 403, error: "Project is not trusted; refusing to create presets." };
643
+ }
644
+ if (hasRejectedLegacyPromptStackKey(stack)) {
645
+ return { ok: false, status: 400, error: rejectedLegacyPromptStackMessage() };
646
+ }
647
+ const idError = validateWebStackId(stack.id);
648
+ if (idError)
649
+ return { ok: false, status: 400, error: idError };
650
+ const scope = options.scope ?? "project";
651
+ const existingById = runtime.getStacks().find((candidate) => candidate.scope === scope && candidate.stack.id === stack.id);
652
+ if (existingById && !options.overwrite) {
653
+ return { ok: false, status: 409, error: `Preset already exists: ${stack.id}` };
654
+ }
655
+ const targetPath = existingById && options.overwrite
656
+ ? existingById.filePath
657
+ : promptStackTargetPath(ctx.cwd, scope, stack.id);
658
+ // Check the current raw source, not cached diagnostics: normalization intentionally
659
+ // omits rejected legacy fields, and external edits may postdate the catalog.
660
+ if (options.overwrite && existsSync(targetPath)) {
661
+ try {
662
+ if (hasRejectedLegacyPromptStackKey(JSON.parse(readFileSync(targetPath, "utf8")))) {
663
+ return { ok: false, status: 409, error: rejectedLegacyPromptStackMessage() };
664
+ }
665
+ }
666
+ catch {
667
+ return { ok: false, status: 409, error: "Preset source unavailable or malformed; reload before overwriting." };
668
+ }
669
+ }
670
+ if (existingById && options.overwrite) {
671
+ const policyConflict = activePresetWriteConflict(runtime, existingById, stack);
672
+ if (policyConflict)
673
+ return { ok: false, status: 409, error: policyConflict };
674
+ }
675
+ const write = writePromptStackFile(ctx.cwd, scope, targetPath, stack, { overwrite: options.overwrite ?? false });
676
+ if (!write.ok) {
677
+ const status = stackMutationStatus(write.reason);
678
+ return { ok: false, status, error: write.error };
679
+ }
680
+ const previousSelection = runtime.getSelectedActiveId();
681
+ const createdSelector = formatResourceKey({ scope, id: stack.id });
682
+ // Discover the new file without selecting it before activation preflight.
683
+ await runtime.reloadStacks(previousSelection ?? "none");
684
+ if (options.activate) {
685
+ if (!runtime.setActive(createdSelector)) {
686
+ const error = `Preset "${createdSelector}" was created, but activation failed: ${runtime.lastActivationError?.() ?? "Could not activate created preset."}`;
687
+ return { ok: false, status: 409, error };
688
+ }
689
+ }
690
+ const created = runtime.getStacks().find((candidate) => candidate.scope === scope && candidate.filePath === targetPath);
691
+ if (!created)
692
+ return { ok: false, status: 500, error: "Created preset could not be reloaded." };
693
+ return { ok: true, stack: stackSummary(created, runtime.getActive()), stacks: stackSummaries(runtime.getStacks(), runtime.getActive()) };
694
+ }
695
+ async function deleteStackFile(ctx, runtime, id) {
696
+ if (!ctx.isProjectTrusted()) {
697
+ return { ok: false, status: 403, error: "Project is not trusted; refusing to delete presets." };
698
+ }
699
+ const target = resolveStack(runtime, id);
700
+ if (!target)
701
+ return { ok: false, status: 404, error: `Unknown preset: ${id}` };
702
+ const deleted = deletePromptStackFile(ctx.cwd, target.scope, target.filePath);
703
+ if (!deleted.ok) {
704
+ const status = stackMutationStatus(deleted.reason);
705
+ return { ok: false, status, error: deleted.error };
706
+ }
707
+ const wasActive = runtime.getActive() === target;
708
+ if (wasActive) {
709
+ runtime.setActive("none");
710
+ await runtime.reloadStacks("none");
711
+ }
712
+ else {
713
+ await runtime.reloadStacks(runtime.getSelectedActiveId());
714
+ }
715
+ return { ok: true, activeId: runtime.getActiveId(), stacks: stackSummaries(runtime.getStacks(), runtime.getActive()) };
716
+ }
717
+ /** HTTP status mapping for repository write/delete failures surfaced to the web editor. */
718
+ export function stackMutationStatus(reason) {
719
+ switch (reason) {
720
+ case "invalid-path":
721
+ return 403;
722
+ case "exists":
723
+ return 409;
724
+ case "missing":
725
+ return 404;
726
+ default:
727
+ return 500;
728
+ }
729
+ }
730
+ function promptStackSourceRevision(filePath) {
731
+ return createHash("sha256").update(readFileSync(filePath)).digest("hex");
732
+ }
733
+ function validateWebStackId(id) {
734
+ if (!id.trim())
735
+ return "Preset id must not be empty.";
736
+ if (!isValidPromptStackId(id)) {
737
+ return "Preset id must start with a letter or number and contain only letters, numbers, dots, underscores, and hyphens.";
738
+ }
739
+ return undefined;
740
+ }
741
+ function hasRejectedLegacyPromptStackKey(value) {
742
+ return isPlainObject(value) && Object.prototype.hasOwnProperty.call(value, "instructionModes");
743
+ }
744
+ function rejectedLegacyPromptStackMessage() {
745
+ return 'Preset key "instructionModes" is no longer supported; convert it to "capabilities" before saving.';
746
+ }
747
+ function isPlainObject(value) {
748
+ return !!value && typeof value === "object" && !Array.isArray(value);
749
+ }
750
+ //# sourceMappingURL=web-host.js.map