@skaile/workspaces 2.3.0 → 2.5.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 (217) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/README.md +32 -13
  3. package/dist/app-sdk/index.js +1 -1
  4. package/dist/{asset-feeds-DKNYRLED.js → asset-feeds-4AWAT5PW.js} +6 -6
  5. package/dist/{asset-feeds-DKNYRLED.js.map → asset-feeds-4AWAT5PW.js.map} +1 -1
  6. package/dist/asset-manager/catalog-deployer.js +1 -1
  7. package/dist/asset-manager/index.js +5 -5
  8. package/dist/asset-manager/installer.js +2 -2
  9. package/dist/bridge/drivers/claude-sdk.js +108 -5
  10. package/dist/bridge/drivers/claude-sdk.js.map +1 -1
  11. package/dist/bridge/drivers/codex.js +1 -1
  12. package/dist/bridge/drivers/continue.js +2 -2
  13. package/dist/bridge/drivers/echo.js +1 -1
  14. package/dist/bridge/drivers/gemini.js +3 -3
  15. package/dist/bridge/drivers/goose.js +2 -2
  16. package/dist/bridge/drivers/omp.js +1 -1
  17. package/dist/bridge/drivers/opencode.js +2 -2
  18. package/dist/bridge/drivers/qwen.js +3 -3
  19. package/dist/bridge/index.js +2 -2
  20. package/dist/bridge/src/drivers/claude-sdk.d.ts +33 -0
  21. package/dist/bridge/src/drivers/claude-sdk.d.ts.map +1 -1
  22. package/dist/{chunk-CERGXDGG.js → chunk-2OCYS5EP.js} +3 -3
  23. package/dist/{chunk-CERGXDGG.js.map → chunk-2OCYS5EP.js.map} +1 -1
  24. package/dist/{chunk-W3Q37HEF.js → chunk-3HVASHBF.js} +3 -3
  25. package/dist/{chunk-W3Q37HEF.js.map → chunk-3HVASHBF.js.map} +1 -1
  26. package/dist/{chunk-UQ3RJKDD.js → chunk-4O2RAXKJ.js} +179 -52
  27. package/dist/chunk-4O2RAXKJ.js.map +1 -0
  28. package/dist/{chunk-DZM33LQO.js → chunk-4QROZZ5Z.js} +15 -3
  29. package/dist/chunk-4QROZZ5Z.js.map +1 -0
  30. package/dist/{chunk-G2ILW47R.js → chunk-57RFYEVM.js} +3 -3
  31. package/dist/{chunk-G2ILW47R.js.map → chunk-57RFYEVM.js.map} +1 -1
  32. package/dist/{chunk-BLWNI5KW.js → chunk-AKVAZ5CB.js} +2 -2
  33. package/dist/{chunk-BLWNI5KW.js.map → chunk-AKVAZ5CB.js.map} +1 -1
  34. package/dist/{chunk-BFIK6NPZ.js → chunk-AM5LFRXJ.js} +3 -3
  35. package/dist/{chunk-BFIK6NPZ.js.map → chunk-AM5LFRXJ.js.map} +1 -1
  36. package/dist/{chunk-RDE43ORT.js → chunk-D4VHBAJC.js} +4 -4
  37. package/dist/{chunk-RDE43ORT.js.map → chunk-D4VHBAJC.js.map} +1 -1
  38. package/dist/{chunk-PTS3QN5P.js → chunk-EEHOMCRU.js} +1021 -115
  39. package/dist/chunk-EEHOMCRU.js.map +1 -0
  40. package/dist/{chunk-CXX3UGJP.js → chunk-ENBTXMPL.js} +7 -7
  41. package/dist/{chunk-CXX3UGJP.js.map → chunk-ENBTXMPL.js.map} +1 -1
  42. package/dist/{chunk-LD6YGIKZ.js → chunk-EUWN4EK4.js} +60 -21
  43. package/dist/chunk-EUWN4EK4.js.map +1 -0
  44. package/dist/{chunk-FB4GPWYC.js → chunk-FKBQRV4J.js} +57 -16
  45. package/dist/chunk-FKBQRV4J.js.map +1 -0
  46. package/dist/{chunk-WG3L5VHF.js → chunk-HY3MBSNC.js} +2 -2
  47. package/dist/{chunk-WG3L5VHF.js.map → chunk-HY3MBSNC.js.map} +1 -1
  48. package/dist/{chunk-7IRH7MGV.js → chunk-IHX2SN35.js} +9 -9
  49. package/dist/{chunk-7IRH7MGV.js.map → chunk-IHX2SN35.js.map} +1 -1
  50. package/dist/{chunk-3F54MH2T.js → chunk-JAFEMG7W.js} +4 -4
  51. package/dist/{chunk-3F54MH2T.js.map → chunk-JAFEMG7W.js.map} +1 -1
  52. package/dist/{chunk-X6BPVUV2.js → chunk-L3TS7ZO4.js} +3 -3
  53. package/dist/{chunk-X6BPVUV2.js.map → chunk-L3TS7ZO4.js.map} +1 -1
  54. package/dist/{chunk-RIEXN7WA.js → chunk-MADO7PH5.js} +2 -2
  55. package/dist/{chunk-RIEXN7WA.js.map → chunk-MADO7PH5.js.map} +1 -1
  56. package/dist/{chunk-BCTU4TN7.js → chunk-MWFYXUFK.js} +3 -3
  57. package/dist/{chunk-BCTU4TN7.js.map → chunk-MWFYXUFK.js.map} +1 -1
  58. package/dist/{chunk-TK66CMXV.js → chunk-NU4E7C5I.js} +7 -3
  59. package/dist/chunk-NU4E7C5I.js.map +1 -0
  60. package/dist/{chunk-ZE2KEPE2.js → chunk-OEGHKO5N.js} +258 -24
  61. package/dist/chunk-OEGHKO5N.js.map +1 -0
  62. package/dist/{chunk-63ZPKREA.js → chunk-P43HBWKK.js} +11 -4
  63. package/dist/chunk-P43HBWKK.js.map +1 -0
  64. package/dist/{chunk-7UZGKVSK.js → chunk-PJ6INYDD.js} +3 -3
  65. package/dist/{chunk-7UZGKVSK.js.map → chunk-PJ6INYDD.js.map} +1 -1
  66. package/dist/{chunk-CA5CWLGN.js → chunk-PKEAYYEJ.js} +7 -4
  67. package/dist/chunk-PKEAYYEJ.js.map +1 -0
  68. package/dist/{chunk-ETFETLLB.js → chunk-UZYTSIX6.js} +6 -6
  69. package/dist/{chunk-ETFETLLB.js.map → chunk-UZYTSIX6.js.map} +1 -1
  70. package/dist/{chunk-SIF5F5SN.js → chunk-V4ZLZJFN.js} +3 -3
  71. package/dist/{chunk-SIF5F5SN.js.map → chunk-V4ZLZJFN.js.map} +1 -1
  72. package/dist/{chunk-ZR5Q4KZK.js → chunk-VNIKF66R.js} +3 -3
  73. package/dist/{chunk-ZR5Q4KZK.js.map → chunk-VNIKF66R.js.map} +1 -1
  74. package/dist/{chunk-CILACPUC.js → chunk-WSARNOPP.js} +5 -5
  75. package/dist/{chunk-CILACPUC.js.map → chunk-WSARNOPP.js.map} +1 -1
  76. package/dist/{chunk-TAJBFYCT.js → chunk-YWPEDILM.js} +83 -36
  77. package/dist/chunk-YWPEDILM.js.map +1 -0
  78. package/dist/{chunk-UNP4M5ZZ.js → chunk-ZR2X4SIG.js} +4 -4
  79. package/dist/{chunk-UNP4M5ZZ.js.map → chunk-ZR2X4SIG.js.map} +1 -1
  80. package/dist/cli/index.js +50 -50
  81. package/dist/connectors/config.js +1 -1
  82. package/dist/connectors/index.js +6 -6
  83. package/dist/core/index.js +1 -1
  84. package/dist/core/src/subprocess.d.ts +5 -1
  85. package/dist/core/src/subprocess.d.ts.map +1 -1
  86. package/dist/deploy/index.js +1 -1
  87. package/dist/discovery/index.js +1 -1
  88. package/dist/{ensure-sources-R6KW7K3M.js → ensure-sources-QF72HVUM.js} +8 -8
  89. package/dist/{ensure-sources-R6KW7K3M.js.map → ensure-sources-QF72HVUM.js.map} +1 -1
  90. package/dist/factory-assets/connectors/box.js +6 -6
  91. package/dist/factory-assets/connectors/deploy.js +6 -6
  92. package/dist/factory-assets/connectors/devserver.js +6 -6
  93. package/dist/factory-assets/connectors/flow/CONNECTOR.md +61 -14
  94. package/dist/factory-assets/connectors/flow/adapter.d.ts +78 -34
  95. package/dist/factory-assets/connectors/flow/adapter.d.ts.map +1 -1
  96. package/dist/factory-assets/connectors/flow/adapter.js +6 -6
  97. package/dist/factory-assets/connectors/flow/contract/expression.d.ts +55 -0
  98. package/dist/factory-assets/connectors/flow/contract/expression.d.ts.map +1 -1
  99. package/dist/factory-assets/connectors/flow/contract/flow.v2.schema.json +61 -134
  100. package/dist/factory-assets/connectors/flow/contract/index.d.ts +1 -1
  101. package/dist/factory-assets/connectors/flow/contract/index.d.ts.map +1 -1
  102. package/dist/factory-assets/connectors/flow/contract/normalize.d.ts.map +1 -1
  103. package/dist/factory-assets/connectors/flow/contract/schema.d.ts +14 -2
  104. package/dist/factory-assets/connectors/flow/contract/schema.d.ts.map +1 -1
  105. package/dist/factory-assets/connectors/flow/contract.js +2 -2
  106. package/dist/factory-assets/connectors/flow/engine/bindings.d.ts +9 -0
  107. package/dist/factory-assets/connectors/flow/engine/bindings.d.ts.map +1 -0
  108. package/dist/factory-assets/connectors/flow/engine/engine.d.ts +11 -6
  109. package/dist/factory-assets/connectors/flow/engine/engine.d.ts.map +1 -1
  110. package/dist/factory-assets/connectors/flow/engine/flow-kind-provider.d.ts.map +1 -1
  111. package/dist/factory-assets/connectors/flow/engine/index.d.ts +2 -0
  112. package/dist/factory-assets/connectors/flow/engine/index.d.ts.map +1 -1
  113. package/dist/factory-assets/connectors/flow/engine/node-shape.d.ts +22 -0
  114. package/dist/factory-assets/connectors/flow/engine/node-shape.d.ts.map +1 -1
  115. package/dist/factory-assets/connectors/flow/engine/output-schema.d.ts +18 -0
  116. package/dist/factory-assets/connectors/flow/engine/output-schema.d.ts.map +1 -0
  117. package/dist/factory-assets/connectors/flow/engine/types.d.ts +21 -15
  118. package/dist/factory-assets/connectors/flow/engine/types.d.ts.map +1 -1
  119. package/dist/factory-assets/connectors/flow/engine.js +4 -4
  120. package/dist/factory-assets/connectors/flow/index.d.ts +3 -0
  121. package/dist/factory-assets/connectors/flow/index.d.ts.map +1 -1
  122. package/dist/factory-assets/connectors/flow/inline-sub-flow-host.d.ts +48 -0
  123. package/dist/factory-assets/connectors/flow/inline-sub-flow-host.d.ts.map +1 -0
  124. package/dist/factory-assets/connectors/flow/node-executor.d.ts +45 -0
  125. package/dist/factory-assets/connectors/flow/node-executor.d.ts.map +1 -0
  126. package/dist/factory-assets/connectors/flow/prompt-fragments.d.ts +3 -2
  127. package/dist/factory-assets/connectors/flow/prompt-fragments.d.ts.map +1 -1
  128. package/dist/factory-assets/connectors/flow/prompt-fragments.js +2 -2
  129. package/dist/factory-assets/connectors/flow/run-flow.d.ts +10 -9
  130. package/dist/factory-assets/connectors/flow/run-flow.d.ts.map +1 -1
  131. package/dist/factory-assets/connectors/flow/run-flow.js +7 -7
  132. package/dist/factory-assets/connectors/flow/sub-flow-runner.d.ts +73 -0
  133. package/dist/factory-assets/connectors/flow/sub-flow-runner.d.ts.map +1 -0
  134. package/dist/factory-assets/connectors/flow.js +6 -6
  135. package/dist/factory-assets/connectors/git.js +6 -6
  136. package/dist/factory-assets/connectors/gmail.js +6 -6
  137. package/dist/factory-assets/connectors/googledrive.js +6 -6
  138. package/dist/factory-assets/connectors/local.js +6 -6
  139. package/dist/factory-assets/connectors/mattermost.js +6 -6
  140. package/dist/factory-assets/connectors/memory.js +6 -6
  141. package/dist/factory-assets/connectors/minio.js +6 -6
  142. package/dist/factory-assets/connectors/postgres.js +6 -6
  143. package/dist/factory-assets/connectors/s3.js +6 -6
  144. package/dist/factory-assets/connectors/sharepoint.js +6 -6
  145. package/dist/factory-assets/connectors/sqlite.js +6 -6
  146. package/dist/factory-assets/connectors/static-server.js +6 -6
  147. package/dist/factory-assets/connectors/tunnel.js +6 -6
  148. package/dist/factory-assets/connectors/webdav.js +6 -6
  149. package/dist/factory-assets/connectors/xstate-store.js +6 -6
  150. package/dist/factory-assets/connectors/xstate.js +6 -6
  151. package/dist/{flows-F3CJNMK6.js → flows-YIW4HL3L.js} +4 -4
  152. package/dist/{flows-F3CJNMK6.js.map → flows-YIW4HL3L.js.map} +1 -1
  153. package/dist/{helpers-KPOLCGKX.js → helpers-LURCZHA4.js} +8 -8
  154. package/dist/{helpers-KPOLCGKX.js.map → helpers-LURCZHA4.js.map} +1 -1
  155. package/dist/library/index.js +3 -3
  156. package/dist/library/install.js +1 -1
  157. package/dist/{library-publish-ZAPZS64O.js → library-publish-2GMJM3NZ.js} +14 -14
  158. package/dist/{library-publish-ZAPZS64O.js.map → library-publish-2GMJM3NZ.js.map} +1 -1
  159. package/dist/{open-library-I4F2UNOY.js → open-library-POFOXZWH.js} +12 -12
  160. package/dist/{open-library-I4F2UNOY.js.map → open-library-POFOXZWH.js.map} +1 -1
  161. package/dist/{paths-KBACHM5B.js → paths-ZLX4ITAQ.js} +6 -6
  162. package/dist/{paths-KBACHM5B.js.map → paths-ZLX4ITAQ.js.map} +1 -1
  163. package/dist/{plugin-store-CYSNVZIX.js → plugin-store-YIMNH2FH.js} +3 -3
  164. package/dist/{plugin-store-CYSNVZIX.js.map → plugin-store-YIMNH2FH.js.map} +1 -1
  165. package/dist/{project-SIHZBTGB.js → project-GVOPZEJZ.js} +9 -9
  166. package/dist/{project-SIHZBTGB.js.map → project-GVOPZEJZ.js.map} +1 -1
  167. package/dist/resolver/index.js +1 -1
  168. package/dist/runner/index.js +15 -12
  169. package/dist/runner/src/serve.d.ts +3 -1
  170. package/dist/runner/src/serve.d.ts.map +1 -1
  171. package/dist/sdk/asset-manager.js +5 -5
  172. package/dist/sdk/bridge.js +2 -2
  173. package/dist/sdk/core.js +1 -1
  174. package/dist/sdk/flow.js +4 -4
  175. package/dist/sdk/index.js +15 -12
  176. package/dist/sdk/index.js.map +1 -1
  177. package/dist/sdk/resolver.js +1 -1
  178. package/dist/sdk/runner.js +15 -12
  179. package/dist/sdk/session.js +2 -2
  180. package/dist/sdk/types.js +1 -1
  181. package/dist/session/index.js +2 -2
  182. package/dist/session/src/dispatcher.d.ts.map +1 -1
  183. package/dist/{setup-KMBXMV25.js → setup-RHWARBBB.js} +5 -5
  184. package/dist/{setup-KMBXMV25.js.map → setup-RHWARBBB.js.map} +1 -1
  185. package/dist/{skills-LHS4TOKK.js → skills-HGVH6UTA.js} +5 -5
  186. package/dist/{skills-LHS4TOKK.js.map → skills-HGVH6UTA.js.map} +1 -1
  187. package/dist/{source-X226ZJPR.js → source-FB3T4IHP.js} +13 -13
  188. package/dist/{source-X226ZJPR.js.map → source-FB3T4IHP.js.map} +1 -1
  189. package/dist/{source-manifest-publish-N2QVUR5U.js → source-manifest-publish-XTRDVPSC.js} +15 -15
  190. package/dist/{source-manifest-publish-N2QVUR5U.js.map → source-manifest-publish-XTRDVPSC.js.map} +1 -1
  191. package/dist/tui/index.js +15 -12
  192. package/dist/tui/index.js.map +1 -1
  193. package/dist/types/index.js +1 -1
  194. package/dist/types/src/events.d.ts +20 -1
  195. package/dist/types/src/events.d.ts.map +1 -1
  196. package/dist/types/src/flow.d.ts +26 -0
  197. package/dist/types/src/flow.d.ts.map +1 -1
  198. package/dist/types/src/index.d.ts +1 -1
  199. package/dist/types/src/index.d.ts.map +1 -1
  200. package/dist/types/src/protocol.d.ts +1 -0
  201. package/dist/types/src/protocol.d.ts.map +1 -1
  202. package/dist/types/src/version.d.ts +12 -1
  203. package/dist/types/src/version.d.ts.map +1 -1
  204. package/dist/workspace-plugin/adapters/mcp.js +4 -4
  205. package/dist/workspace-plugin/adapters/omp.js +7 -7
  206. package/dist/workspace-plugin/index.js +1 -1
  207. package/package.json +1 -1
  208. package/dist/chunk-63ZPKREA.js.map +0 -1
  209. package/dist/chunk-CA5CWLGN.js.map +0 -1
  210. package/dist/chunk-DZM33LQO.js.map +0 -1
  211. package/dist/chunk-FB4GPWYC.js.map +0 -1
  212. package/dist/chunk-LD6YGIKZ.js.map +0 -1
  213. package/dist/chunk-PTS3QN5P.js.map +0 -1
  214. package/dist/chunk-TAJBFYCT.js.map +0 -1
  215. package/dist/chunk-TK66CMXV.js.map +0 -1
  216. package/dist/chunk-UQ3RJKDD.js.map +0 -1
  217. package/dist/chunk-ZE2KEPE2.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../core/src/lock.ts","../core/src/manifest-yaml-editor.ts","../core/src/conformance.ts","../core/src/patch.ts","../core/src/settings.ts","../core/src/subprocess.ts","../core/src/workspace-yaml-editor.ts"],"names":["path","existsSync","readFileSync","writeFileSync","join","spawnSync","parseDocument","Document","isMap","isSeq"],"mappings":";;;;;;;;;;AA8BO,SAAS,SAAA,CAAU,UAAkB,IAAA,EAAsB;AAChE,EAAA,aAAA,CAAc,UAAU,SAAA,CAAU,IAAA,EAAM,EAAE,SAAA,EAAW,GAAA,EAAK,CAAC,CAAA;AAC7D;AAUO,SAAS,SAAS,QAAA,EAAmC;AAC1D,EAAA,IAAI,CAAC,UAAA,CAAW,QAAQ,CAAA,EAAG,OAAO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IAAI,CAAA,EAAG,CAAA,GAAI,IAAA,CAAK,KAAA,CAAM,QAAQ,CAAA,EAAA,EAAK;AAC1C,MAAA,MAAM,IAAA,GAAO,IAAA,CAAK,KAAA,CAAM,CAAC,CAAA;AACzB,MAAA,IAAID,MAAM,IAAI,CAAA,IAAM,KAAiB,GAAA,CAAI,KAAK,MAAM,GAAA,EAAK;AACvD,QAAA,IAAA,CAAK,OAAO,CAAC,CAAA;AACb,QAAA,OAAO,IAAA;AAAA,MACT;AAAA,IACF;AACA,IAAA,OAAO,KAAA;AAAA,EACT;AAAA;AAAA;AAAA,EAKA,IAAI,QAAA,GAAqB;AACvB,IAAA,OAAO,IAAA,CAAK,GAAA;AAAA,EACd;AACF","file":"chunk-63ZPKREA.js","sourcesContent":["/**\n * Lock file I/O and integrity verification (schema v3).\n *\n * The lock file (skaile.lock.yaml) captures the complete resolved state: every\n * asset keyed by its canonical ref `<kind>:@<publisher>/<name>#<version>`, the\n * upstream source + commit it resolved from, a per-file + composite content\n * hash for drift detection, and whether an `overrides[]` entry pinned it. A\n * top-level `sources:` block records every contributing source URL at its\n * resolved commit.\n *\n * Old v1 lockfiles (`lockfile_version: 1`, `repositories:`) are rejected with a\n * clear regenerate-from-scratch error.\n */\n\nimport { createHash } from \"node:crypto\";\nimport { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { parse, stringify } from \"yaml\";\nimport type { LockEntry, LockFile, LockPluginEntry, LockSourceEntry } from \"./models.js\";\nimport type { ProvenanceCandidate } from \"./walker.js\";\n\n// ── Lock file I/O ────────────────────────────────────────────────────────────\n\n/**\n * Serialize a `LockFile` to YAML and write it to disk.\n *\n * @param lockPath - Absolute path to write the lock file (e.g. `skaile.lock.yaml`)\n * @param data - Lock file data to serialize\n * @docLink packages/core/api-reference#write-lock\n */\nexport function writeLock(lockPath: string, data: LockFile): void {\n writeFileSync(lockPath, stringify(data, { lineWidth: 120 }));\n}\n\n/**\n * Read and parse a lock file from disk.\n *\n * @param lockPath - Absolute path to the lock file\n * @returns Parsed `LockFile`, or `null` if the file is missing or unparseable\n * @throws When the file is a legacy v1 lock — the shape changed and it must be regenerated.\n * @docLink packages/core/api-reference#read-lock\n */\nexport function readLock(lockPath: string): LockFile | null {\n if (!existsSync(lockPath)) return null;\n let raw: unknown;\n try {\n raw = parse(readFileSync(lockPath, \"utf8\"));\n } catch {\n return null;\n }\n if (!raw || typeof raw !== \"object\") return null;\n const r = raw as Record<string, unknown>;\n if (r.schema_version !== 3) {\n throw new Error(\n \"outdated lockfile schema detected — the lockfile shape changed. \" +\n \"Regenerate: `rm skaile.lock.yaml && skaile install`.\",\n );\n }\n return r as unknown as LockFile;\n}\n\n// ── Hashing ──────────────────────────────────────────────────────────────────\n\n/**\n * Compute the SHA-256 hash of a file's content (hex digest, no prefix).\n *\n * @param filePath - Absolute path to the file\n * @returns Hex-encoded SHA-256 hash string\n * @docLink packages/core/api-reference#compute-hash\n */\nexport function computeHash(filePath: string): string {\n const content = readFileSync(filePath);\n return createHash(\"sha256\").update(content).digest(\"hex\");\n}\n\n/**\n * Composite hash: SHA-256 (bare 64-hex) over `localeCompare`-sorted\n * `<path>:<sha256>\\n` rows. Matches the walker's `compositeSha256`, the store's\n * `computeCompositeSha256`, and the `InstallManifest.sha256` rollup.\n */\nfunction compositeHash(files: Array<{ path: string; sha256: string }>): string {\n const lines = files\n .slice()\n .sort((a, b) => a.path.localeCompare(b.path))\n .map((f) => `${f.path}:${f.sha256}\\n`)\n .join(\"\");\n return createHash(\"sha256\").update(lines).digest(\"hex\");\n}\n\n// ── Lock file construction ───────────────────────────────────────────────────\n\n/**\n * Build a v3 `LockFile` from the resolver's output.\n *\n * Assets are keyed by canonical ref `<kind>:@<publisher>/<name>#<version>`; the\n * top-level `sources:` block lists every contributing source URL pinned to its\n * resolved commit.\n *\n * @param resolved - Resolved provenance candidates (the resolver's `resolved` array).\n * @param overridesApplied - Canonical refs that an `overrides[]` entry pinned.\n * @returns Complete v2 `LockFile` ready for serialization.\n * @docLink packages/core/api-reference#build-lock-file\n */\nexport function buildLockFile(\n resolved: ProvenanceCandidate[],\n overridesApplied: Set<string>,\n): LockFile {\n const assets: Record<string, LockEntry> = {};\n const sourceMap = new Map<string, LockSourceEntry>();\n\n for (const c of resolved) {\n const canonicalRef = `${c.kind}:@${c.publisher}/${c.name}#${c.version}`;\n assets[canonicalRef] = {\n sha256: c.sha256,\n source: { url: c.sourceUrl, commit: c.commit },\n files: c.files,\n override_applied: overridesApplied.has(canonicalRef),\n };\n if (!sourceMap.has(c.sourceUrl)) {\n sourceMap.set(c.sourceUrl, { url: c.sourceUrl, commit: c.commit });\n }\n }\n\n return {\n schema_version: 3,\n locked_at: new Date().toISOString(),\n assets,\n sources: Array.from(sourceMap.values()).sort((a, b) => a.url.localeCompare(b.url)),\n };\n}\n\n// ── Plugins slice ────────────────────────────────────────────────────────────\n\n/** Absolute path to a project's lock file. */\nfunction lockPathFor(projectDir: string): string {\n return join(projectDir, \"skaile.lock.yaml\");\n}\n\n/**\n * Read the `plugins` slice from a project's `skaile.lock.yaml`.\n *\n * Total — never throws on a missing/unparseable/legacy lock file (returns\n * `undefined`). The plugin-store reconciler folds this into its reconcile-hash\n * so a lock edit invalidates the hash even without a manifest change.\n *\n * @param projectDir - Project root containing `skaile.lock.yaml`\n * @returns The `plugins` record, or `undefined` when absent\n */\nexport function readPluginsLockSlice(\n projectDir: string,\n): Record<string, LockPluginEntry> | undefined {\n try {\n return readLock(lockPathFor(projectDir))?.plugins;\n } catch {\n // Legacy v1 lock — no usable plugins slice.\n return undefined;\n }\n}\n\n/**\n * Merge a `plugins` slice into a project's `skaile.lock.yaml`, preserving all\n * other fields. Creates a minimal v3 lock file when none exists (or the\n * existing one is an outdated schema that can't be read).\n *\n * @param projectDir - Project root containing `skaile.lock.yaml`\n * @param slice - The `plugins` record to persist\n */\nexport function writePluginsLockSlice(\n projectDir: string,\n slice: Record<string, LockPluginEntry>,\n): void {\n const lockPath = lockPathFor(projectDir);\n let existing: LockFile | null = null;\n try {\n existing = readLock(lockPath);\n } catch {\n existing = null; // outdated schema — overwrite with a fresh v3 shell\n }\n const next: LockFile = existing ?? {\n schema_version: 3,\n locked_at: new Date().toISOString(),\n assets: {},\n sources: [],\n };\n next.plugins = slice;\n writeLock(lockPath, next);\n}\n\n// ── Verification ─────────────────────────────────────────────────────────────\n\n/**\n * Result of verifying a lock file against the current repository state.\n * @docLink packages/core/api-reference#verify-result\n */\nexport interface VerifyResult {\n /** `true` when no drift or missing assets were found. */\n ok: boolean;\n /** Canonical refs whose content hash no longer matches. */\n drifted: string[];\n /** Canonical refs whose files cannot be found on disk. */\n missing: string[];\n}\n\n/**\n * Verify a v2 lock file against the current on-disk source clones.\n *\n * For each locked asset, resolve its source clone directory via `resolveCloneDir`\n * (URL → on-disk path), re-hash the recorded files, and compare the recomputed\n * composite against the locked `sha256`. Reports assets whose hash changed\n * (`drifted`) and assets whose files are missing (`missing`).\n *\n * @param lock - Previously generated v2 `LockFile`.\n * @param resolveCloneDir - Maps a source URL to its on-disk clone root (or null).\n * @returns `VerifyResult` indicating drift and missing assets.\n * @docLink packages/core/api-reference#verify-lock\n */\nexport function verifyLock(\n lock: LockFile,\n resolveCloneDir: (sourceUrl: string) => string | null,\n): VerifyResult {\n const drifted: string[] = [];\n const missing: string[] = [];\n\n for (const [ref, entry] of Object.entries(lock.assets)) {\n const cloneDir = resolveCloneDir(entry.source.url);\n if (!cloneDir) {\n missing.push(ref);\n continue;\n }\n let allPresent = true;\n const recomputed: Array<{ path: string; sha256: string }> = [];\n for (const f of entry.files) {\n const abs = join(cloneDir, f.path);\n if (!existsSync(abs)) {\n allPresent = false;\n break;\n }\n recomputed.push({ path: f.path, sha256: computeHash(abs) });\n }\n if (!allPresent) {\n missing.push(ref);\n continue;\n }\n if (compositeHash(recomputed) !== entry.sha256) {\n drifted.push(ref);\n }\n }\n\n return { ok: drifted.length === 0 && missing.length === 0, drifted, missing };\n}\n","/**\n * Comment-preserving editor for `skaile.manifest.yaml` files.\n *\n * The publication counterpart to {@link WorkspaceYamlEditor}: it owns the\n * `publisher` / `version` / `assets[]` accessors that used to sit on the\n * workspace editor before the 2026-06-03 manifest/workspace file split. Uses the\n * `yaml` library's Document AST so untouched sections stay byte-identical.\n *\n * Usage:\n *\n * import { ManifestYamlEditor } from '@skaile/workspaces/core'\n *\n * const editor = ManifestYamlEditor.load('/project/skaile.manifest.yaml')\n * editor.setPublisher('skaile-ai')\n * editor.setAsset({ kind: 'skill', name: 'audit', root: 'skills/audit' })\n * editor.save()\n */\n\nimport { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { Document, isMap, isSeq, parseDocument, type YAMLMap } from \"yaml\";\nimport type { AssetEntry } from \"./publish-manifest.js\";\n\n/**\n * Comment-preserving editor for `skaile.manifest.yaml` files.\n * Create with `ManifestYamlEditor.load(filePath)` or `ManifestYamlEditor.create(filePath)`.\n * @docLink packages/core/publish-manifest#manifest-yaml-editor\n */\nexport class ManifestYamlEditor {\n readonly path: string;\n private doc: Document;\n\n private constructor(path: string, doc: Document) {\n this.path = path;\n this.doc = doc;\n }\n\n /** Load an existing skaile.manifest.yaml file. */\n static load(filePath: string): ManifestYamlEditor {\n if (!existsSync(filePath)) {\n throw new Error(`File not found: ${filePath}`);\n }\n const raw = readFileSync(filePath, \"utf-8\");\n return new ManifestYamlEditor(filePath, parseDocument(raw));\n }\n\n /** Create a new empty document (for use when no file exists yet). */\n static create(filePath: string): ManifestYamlEditor {\n return new ManifestYamlEditor(filePath, new Document({}));\n }\n\n /** Write the document back to disk, preserving comments and formatting. */\n save(): void {\n writeFileSync(this.path, this.doc.toString());\n }\n\n /** Return the serialized YAML string without writing to disk. */\n toString(): string {\n return this.doc.toString();\n }\n\n // ── Publisher / version / repo-level defaults ───────────────────────────────\n\n /** Get the `publisher:` field. */\n getPublisher(): string | undefined {\n const v = this.doc.get(\"publisher\");\n return v != null ? String(v) : undefined;\n }\n\n /** Set the `publisher:` field. */\n setPublisher(p: string): void {\n this.doc.set(\"publisher\", p);\n }\n\n /** Get the `version:` field. */\n getVersion(): string | undefined {\n const v = this.doc.get(\"version\");\n return v != null ? String(v) : undefined;\n }\n\n /** Set the `version:` field. */\n setVersion(v: string): void {\n this.doc.set(\"version\", v);\n }\n\n /** Get the repo-level `license:` default. */\n getLicense(): string | undefined {\n const v = this.doc.get(\"license\");\n return v != null ? String(v) : undefined;\n }\n\n /** Set the repo-level `license:` default. */\n setLicense(v: string): void {\n this.doc.set(\"license\", v);\n }\n\n /** Get the repo-level `homepage:` default. */\n getHomepage(): string | undefined {\n const v = this.doc.get(\"homepage\");\n return v != null ? String(v) : undefined;\n }\n\n /** Set the repo-level `homepage:` default. */\n setHomepage(v: string): void {\n this.doc.set(\"homepage\", v);\n }\n\n // ── Assets ──────────────────────────────────────────────────────────────────\n\n /** Get all `assets:` entries. */\n getAssets(): AssetEntry[] {\n const node = this.doc.get(\"assets\", true);\n if (!isSeq(node)) return [];\n return node.toJSON() as AssetEntry[];\n }\n\n /** Add or update an asset entry, matched by `kind` + `name`. */\n setAsset(entry: AssetEntry): void {\n const node = this.doc.get(\"assets\", true);\n if (!node || !isSeq(node)) {\n this.doc.set(\"assets\", this.doc.createNode([entry]));\n return;\n }\n let found = false;\n for (let i = 0; i < node.items.length; i++) {\n const item = node.items[i];\n if (\n isMap(item) &&\n (item as YAMLMap).get(\"kind\") === entry.kind &&\n (item as YAMLMap).get(\"name\") === entry.name\n ) {\n node.set(i, this.doc.createNode(entry));\n found = true;\n break;\n }\n }\n if (!found) node.add(this.doc.createNode(entry));\n }\n\n /** Remove an asset entry by kind + name. Returns true when removed. */\n removeAsset(kind: string, name: string): boolean {\n const node = this.doc.get(\"assets\", true);\n if (!node || !isSeq(node)) return false;\n for (let i = 0; i < node.items.length; i++) {\n const item = node.items[i];\n if (\n isMap(item) &&\n (item as YAMLMap).get(\"kind\") === kind &&\n (item as YAMLMap).get(\"name\") === name\n ) {\n node.delete(i);\n return true;\n }\n }\n return false;\n }\n\n // ── Raw access (escape hatch) ─────────────────────────────────────────────\n\n /** Get the underlying yaml Document for advanced manipulation. */\n get document(): Document {\n return this.doc;\n }\n}\n","/**\n * Agent Skills (agentskills.io) open-standard conformance lint for SKILL.md\n * frontmatter — pure, advisory, never a hard gate.\n * See devlog: 2026-06-21-agentskills-conformance-shipped.\n * @docLink core/conformance\n */\n\n/** A single agentskills.io conformance finding. */\nexport interface ConformanceFinding {\n /** `error` = hard standard violation; `warn` = portability risk. */\n level: \"error\" | \"warn\";\n /** Frontmatter field the finding concerns (e.g. \"name\", \"metadata.tags\"). */\n field: string;\n /** Human-readable, ready to print after a file path. */\n message: string;\n}\n\n/** Options for {@link checkAgentSkillConformance}. */\nexport interface ConformanceOptions {\n /**\n * Parent directory name, for the standard's `name === <dir>` rule.\n * Omit to skip that check (e.g. when validating a detached frontmatter blob).\n */\n dirName?: string;\n}\n\n// Standard limits — see https://agentskills.io/specification.\nconst NAME_MAX = 64;\nconst DESCRIPTION_MAX = 1024;\nconst COMPATIBILITY_MAX = 500;\n\n/**\n * Check a SKILL.md frontmatter object against the Agent Skills open standard.\n * Returns findings only — the caller maps severity to exit codes.\n *\n * @param frontmatter Parsed SKILL.md YAML frontmatter.\n * @param opts Optional context (`dirName` enables the name==dir rule).\n * @returns Zero or more {@link ConformanceFinding}s.\n */\nexport function checkAgentSkillConformance(\n frontmatter: Record<string, unknown>,\n opts: ConformanceOptions = {},\n): ConformanceFinding[] {\n const out: ConformanceFinding[] = [];\n const name = frontmatter.name;\n\n if (typeof name === \"string\") {\n if (name.length > NAME_MAX) {\n out.push({\n level: \"error\",\n field: \"name\",\n message: `name is ${name.length} chars (standard max ${NAME_MAX})`,\n });\n }\n if (opts.dirName !== undefined && name !== opts.dirName) {\n out.push({\n level: \"warn\",\n field: \"name\",\n message: `name \"${name}\" does not match parent directory \"${opts.dirName}\" (standard requires equality)`,\n });\n }\n }\n\n const description = frontmatter.description;\n if (typeof description === \"string\" && description.length > DESCRIPTION_MAX) {\n out.push({\n level: \"error\",\n field: \"description\",\n message: `description is ${description.length} chars (standard max ${DESCRIPTION_MAX})`,\n });\n }\n\n const compatibility = frontmatter.compatibility;\n if (typeof compatibility === \"string\" && compatibility.length > COMPATIBILITY_MAX) {\n out.push({\n level: \"error\",\n field: \"compatibility\",\n message: `compatibility is ${compatibility.length} chars (standard max ${COMPATIBILITY_MAX})`,\n });\n }\n\n // The standard defines metadata as a string→string map. skaile nests objects\n // here by design — report as a portability WARN, never an error, never rewrite.\n const metadata = frontmatter.metadata;\n if (metadata !== undefined && typeof metadata === \"object\" && metadata !== null) {\n for (const [k, v] of Object.entries(metadata as Record<string, unknown>)) {\n if (typeof v !== \"string\") {\n out.push({\n level: \"warn\",\n field: `metadata.${k}`,\n message: `metadata.${k} is ${Array.isArray(v) ? \"an array\" : typeof v}, not a string — non-portable to strict skills-ref consumers`,\n });\n }\n }\n }\n\n const allowedTools = frontmatter[\"allowed-tools\"];\n if (allowedTools !== undefined && typeof allowedTools !== \"string\") {\n out.push({\n level: \"warn\",\n field: \"allowed-tools\",\n message: \"allowed-tools must be a space-separated string\",\n });\n }\n\n return out;\n}\n","/**\n * Patch operations — extract, generate, apply patches for skill improvement.\n *\n * Patches allow editing deployed assets from remote repos and contributing\n * changes back upstream via PR.\n */\n\nimport { spawnSync } from \"node:child_process\";\nimport { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { basename, dirname, join } from \"node:path\";\nimport type { CatalogEntry } from \"./models.js\";\n\n/**\n * Copy an asset's source directory into a patch working directory for editing.\n *\n * @param entry - The catalog entry to extract\n * @param patchDir - Base directory where extracted copies are placed\n * @returns Absolute path to the extracted copy (`<patchDir>/<kind>-<name>`)\n * @docLink packages/core/api-reference#extract-for-patch\n */\nexport function extractForPatch(entry: CatalogEntry, patchDir: string): string {\n const ref = `${entry.kind}-${entry.name}`;\n const dest = join(patchDir, ref);\n mkdirSync(dest, { recursive: true });\n\n // Copy the asset's source directory (or file) to the patch dir\n const sourceDir = dirname(entry.source);\n const sourceName = basename(entry.source);\n\n // If source is a file in a directory (e.g., skills/overview/SKILL.md), copy the whole dir\n if (existsSync(sourceDir)) {\n cpSync(sourceDir, dest, { recursive: true });\n }\n\n return dest;\n}\n\n/**\n * Generate a unified diff between an original and patched directory using `diff -ruN`.\n *\n * @param originalDir - Unmodified copy of the asset directory\n * @param patchedDir - Modified copy of the asset directory\n * @returns Patch content string, or `null` if there are no differences (or on error)\n * @docLink packages/core/api-reference#generate-patch\n */\nexport function generatePatch(originalDir: string, patchedDir: string): string | null {\n const r = spawnSync(\"diff\", [\"-ruN\", originalDir, patchedDir], {\n encoding: \"utf8\",\n stdio: \"pipe\",\n });\n\n // diff returns 0 if no differences, 1 if differences, 2 on error\n if (r.status === 0) return null; // no differences\n if (r.status === 1) return r.stdout;\n return null; // error\n}\n\n/**\n * Apply a unified diff patch file to a directory using `patch -p1`.\n *\n * @param targetDir - Directory to apply the patch to\n * @param patchFile - Path to the `.patch` file\n * @returns `true` on success, `false` if the patch file is missing or the command fails\n * @docLink packages/core/api-reference#apply-patch\n */\nexport function applyPatch(targetDir: string, patchFile: string): boolean {\n if (!existsSync(patchFile)) return false;\n const r = spawnSync(\"patch\", [\"-p1\", \"-d\", targetDir, \"-i\", patchFile], {\n stdio: \"pipe\",\n });\n return r.status === 0;\n}\n\n/**\n * Return the paths of all `.patch` files in a directory.\n *\n * @param patchDir - Directory to scan for `.patch` files\n * @returns Array of absolute paths; empty array when `patchDir` does not exist\n * @docLink packages/core/api-reference#list-patches\n */\nexport function listPatches(patchDir: string): string[] {\n if (!existsSync(patchDir)) return [];\n return readdirSync(patchDir)\n .filter((f) => f.endsWith(\".patch\"))\n .map((f) => join(patchDir, f));\n}\n\n/**\n * Write patch content to a file, creating parent directories as needed.\n *\n * @param patchPath - Destination file path (including `.patch` extension)\n * @param content - Unified diff content to write\n * @docLink packages/core/api-reference#save-patch\n */\nexport function savePatch(patchPath: string, content: string): void {\n mkdirSync(dirname(patchPath), { recursive: true });\n writeFileSync(patchPath, content, \"utf8\");\n}\n\n/**\n * Read the content of a patch file.\n *\n * @param patchPath - Path to the `.patch` file\n * @returns File content as a string, or `null` if the file does not exist\n * @docLink packages/core/api-reference#read-patch\n */\nexport function readPatch(patchPath: string): string | null {\n if (!existsSync(patchPath)) return null;\n return readFileSync(patchPath, \"utf8\");\n}\n","/**\n * User-layer runtime settings.\n *\n * SkaileSettings represents the personal, machine-specific overrides stored in\n * .skaile/settings.json (gitignored). Project-level defaults (framework, agent\n * definition, resource connections, hooks) belong in skaile.yaml via SkWorkspaceConfig.\n *\n * Resolution order (highest priority first):\n * 1. CLI flags / API overrides\n * 2. Environment variables (API keys only)\n * 3. .skaile/settings.json (project-local, walking upward)\n * 4. ~/.skaile/settings.json (user global)\n * 5. skaile.yaml defaults: (via resolveSkWorkspaceConfig — no duplicate YAML parser)\n * 6. Built-in SETTINGS_DEFAULTS\n */\n\nimport fs from \"node:fs\";\nimport fsp from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport {\n cloudConfigFromProfile,\n type CloudTransportConfig,\n resolveSkWorkspaceConfig,\n} from \"./workspace-config.js\";\n\n// ── Types ──────────────────────────────────────────────────────────────────\n\n/**\n * All supported LLM and voice provider identifiers.\n * @docLink packages/core/settings#all-providers\n */\nexport const ALL_PROVIDERS = [\n \"anthropic\",\n \"openai\",\n \"google\",\n \"mistral\",\n \"groq\",\n \"openrouter\",\n \"deepseek\",\n \"xai\",\n \"together\",\n \"fireworks\",\n \"deepgram\",\n \"elevenlabs\",\n] as const;\n\n/**\n * Union of supported LLM and voice provider identifiers.\n * @docLink packages/core/settings#provider\n */\nexport type Provider = (typeof ALL_PROVIDERS)[number];\n\n/**\n * Personal runtime settings — stored in .skaile/settings.json (gitignored).\n * Contains only user-specific overrides: credentials, preferred model/driver.\n *\n * Project-level config (framework, resources, hooks, agent definition) lives\n * in skaile.yaml as SkWorkspaceConfig. App-specific fields (voice, domains)\n * are added by forge-common-backend via AppSettings.\n * @docLink packages/core/settings#skaile-settings\n */\nexport interface SkaileSettings {\n /** Active LLM provider identifier (e.g. \"anthropic\", \"openai\"). */\n provider?: string;\n /** Active model identifier (e.g. \"claude-sonnet-4-6\"). */\n model?: string;\n /** Bridge driver to use: \"omp\", \"claude-sdk\", or \"codex\". */\n driver?: string;\n /**\n * AI cloud transport for claude-sdk (`default|bedrock|vertex|azure|gateway`).\n * Absent = default (provider's native API). Sourced from skaile.yaml\n * `agent-config.<profile>.cloud`; string-typed for forward compat.\n *\n * @since 1.3.0\n */\n cloud?: string;\n /**\n * Non-secret cloud transport settings (camelCase; converted once from the\n * skaile.yaml `cloud_config` snake_case wire shape).\n *\n * @since 1.3.0\n */\n cloudConfig?: CloudTransportConfig;\n /** API keys keyed by provider identifier. Merged with env-var keys at resolution time. */\n apiKeys?: Record<string, string>;\n /** Framework install path overrides. Normally derived from skaile.yaml defaults. */\n skillsDir?: string;\n /** Override for the agents directory. Normally derived from skaile.yaml defaults. */\n agentsDir?: string;\n /** Override for the prompts directory. Normally derived from skaile.yaml defaults. */\n promptsDir?: string;\n /** AI Asset Store API URL (default: https://store.skaile.ai) */\n storeUrl?: string;\n /** JWT access token for the AI Asset Store */\n storeJwt?: string;\n /** Refresh token for JWT renewal */\n storeRefreshToken?: string;\n}\n\n/**\n * Built-in default settings. Lowest-priority layer in resolveSettings().\n * Override via .skaile/settings.json, ~/.skaile/settings.json, or env vars.\n * @docLink packages/core/settings#settings-defaults\n */\nexport const SETTINGS_DEFAULTS: SkaileSettings = {\n apiKeys: {},\n driver: \"omp\",\n provider: \"anthropic\",\n model: \"claude-sonnet-4-6\",\n};\n\n// ── Legacy field mapping ───────────────────────────────────────────────────\n\nconst LEGACY_FIELD_MAP: Record<string, keyof SkaileSettings> = {\n defaultProvider: \"provider\",\n defaultModel: \"model\",\n defaultAgentType: \"driver\",\n};\n\n/**\n * Rename legacy field names in a raw parsed settings object to their current equivalents.\n * Maps `defaultProvider` → `provider`, `defaultModel` → `model`, `defaultAgentType` → `driver`.\n *\n * @param raw - Raw object from JSON.parse of a settings file\n * @returns Settings with legacy keys renamed to current ones\n * @docLink packages/core/settings#map-legacy-fields\n */\nexport function mapLegacyFields(raw: Record<string, unknown>): SkaileSettings {\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(raw)) {\n const mapped = LEGACY_FIELD_MAP[key];\n if (mapped) {\n if (!(mapped in result) || result[mapped] == null) result[mapped] = value;\n } else {\n result[key] = value;\n }\n }\n return result as SkaileSettings;\n}\n\n// ── Paths ──────────────────────────────────────────────────────────────────\n\nconst SKAILE_DIR = \".skaile\";\nconst SETTINGS_FILE = \"settings.json\";\n\n/**\n * Return the path to the user-global settings file: `~/.skaile/settings.json`.\n * @docLink packages/core/settings#global-settings-path\n */\nexport function globalSettingsPath(): string {\n return path.join(os.homedir(), SKAILE_DIR, SETTINGS_FILE);\n}\n\n/**\n * Return the path to the project-local settings file: `<projectDir>/.skaile/settings.json`.\n *\n * @param projectDir - Absolute path to the project root\n * @returns Absolute path to the project settings file\n * @docLink packages/core/settings#project-settings-path\n */\nexport function projectSettingsPath(projectDir: string): string {\n return path.join(projectDir, SKAILE_DIR, SETTINGS_FILE);\n}\n\n// ── I/O ────────────────────────────────────────────────────────────────────\n\n/**\n * Load and parse a settings JSON file, merging over SETTINGS_DEFAULTS.\n * Returns defaults if the file does not exist or cannot be parsed.\n *\n * @param filePath - Absolute path to a settings.json file\n * @returns Parsed settings merged with built-in defaults\n * @docLink packages/core/settings#load-settings\n */\nexport async function loadSettings(filePath: string): Promise<SkaileSettings> {\n try {\n const raw = await fsp.readFile(filePath, \"utf-8\");\n return { ...SETTINGS_DEFAULTS, ...mapLegacyFields(JSON.parse(raw)) };\n } catch {\n return { ...SETTINGS_DEFAULTS };\n }\n}\n\n/**\n * Persist settings to a JSON file, creating parent directories as needed.\n *\n * @param settings - Settings object to serialize\n * @param filePath - Absolute path to write the settings.json file\n * @docLink packages/core/settings#save-settings\n */\nexport async function saveSettings(settings: SkaileSettings, filePath: string): Promise<void> {\n await fsp.mkdir(path.dirname(filePath), { recursive: true });\n await fsp.writeFile(filePath, JSON.stringify(settings, null, 2), \"utf-8\");\n}\n\n/**\n * Walk upward from `projectDir` (max 10 levels) and collect all\n * `.skaile/settings.json` paths found along the way.\n * Results are ordered nearest-to-root first.\n *\n * @param projectDir - Starting directory for the upward walk\n * @returns Array of absolute paths to settings files found\n * @docLink packages/core/settings#walk-for-settings\n */\nexport function walkForSettings(projectDir: string): string[] {\n const found: string[] = [];\n let dir = path.resolve(projectDir);\n const root = path.parse(dir).root;\n for (let i = 0; i < 10; i++) {\n const candidate = path.join(dir, SKAILE_DIR, SETTINGS_FILE);\n if (fs.existsSync(candidate)) found.push(candidate);\n const parent = path.dirname(dir);\n if (parent === dir || parent === root) break;\n dir = parent;\n }\n return found;\n}\n\n// ── Resolution ─────────────────────────────────────────────────────────────\n\nfunction mergeSettings(base: SkaileSettings, source: Partial<SkaileSettings>): SkaileSettings {\n const result = { ...base };\n for (const [key, value] of Object.entries(source)) {\n if (value !== undefined && value !== null && value !== \"\") {\n if (key === \"apiKeys\" && typeof value === \"object\") {\n result.apiKeys = { ...result.apiKeys, ...(value as Record<string, string>) };\n } else {\n (result as any)[key] = value;\n }\n }\n }\n return result;\n}\n\n/** Derive a SkaileSettings-compatible layer from SkWorkspaceConfig agent_config.default. */\nfunction settingsFromWorkspaceConfig(projectDir: string): SkaileSettings {\n try {\n const ws = resolveSkWorkspaceConfig(projectDir);\n // Read agent_config.default\n const p = ws.agent_config?.default;\n if (!p) return {};\n const result: SkaileSettings = {};\n if (p.driver) result.driver = p.driver;\n if (p.provider) result.provider = p.provider;\n if (p.cloud) result.cloud = p.cloud;\n const cloudConfig = cloudConfigFromProfile(p);\n if (cloudConfig) result.cloudConfig = cloudConfig;\n if (p.model) result.model = p.model;\n if (p.skills_dir) result.skillsDir = p.skills_dir;\n if (p.agents_dir) result.agentsDir = p.agents_dir;\n if (p.prompts_dir) result.promptsDir = p.prompts_dir;\n return result;\n } catch {\n return {};\n }\n}\n\n// ── Migration ──────────────────────────────────────────────────────────────\n\nconst _migrated = new Set<string>();\n\n/**\n * One-time migration from old config locations to .skaile/settings.json.\n * Does not delete old files — user can do that manually.\n * @docLink packages/core/settings#migrate-settings\n */\nexport async function migrateSettings(projectDir: string): Promise<void> {\n const resolved = path.resolve(projectDir);\n if (_migrated.has(resolved)) return;\n\n const targetPath = projectSettingsPath(resolved);\n if (fs.existsSync(targetPath)) {\n _migrated.add(resolved);\n return;\n }\n\n const sources: Record<string, unknown>[] = [];\n\n // Old location 1: data/settings.json (forge-project)\n const dataSettings = path.join(resolved, \"data\", \"settings.json\");\n if (fs.existsSync(dataSettings)) {\n try {\n sources.push(JSON.parse(fs.readFileSync(dataSettings, \"utf-8\")));\n } catch {}\n }\n\n // Old location 2: .cf/settings.json (forge-concept)\n const cfSettings = path.join(resolved, \".cf\", \"settings.json\");\n if (fs.existsSync(cfSettings)) {\n try {\n sources.push(JSON.parse(fs.readFileSync(cfSettings, \"utf-8\")));\n } catch {}\n }\n\n // Old location 3: .skaile/config.json (old SkailConfig)\n const oldConfig = path.join(resolved, \".skaile\", \"config.json\");\n if (fs.existsSync(oldConfig)) {\n try {\n sources.push(JSON.parse(fs.readFileSync(oldConfig, \"utf-8\")));\n } catch {}\n }\n\n if (sources.length > 0) {\n let merged: SkaileSettings = {};\n for (const source of sources) {\n merged = mergeSettings(merged, mapLegacyFields(source as Record<string, unknown>));\n }\n await saveSettings(merged, targetPath);\n }\n\n _migrated.add(resolved);\n}\n\n/**\n * Resolve effective settings through the 6-layer priority chain:\n * overrides > env vars (PREFERRED_PROVIDER, PREFERRED_MODEL, *_API_KEY) >\n * .skaile/settings.json (walks upward) > ~/.skaile/settings.json >\n * skaile.yaml agent_config defaults > SETTINGS_DEFAULTS.\n *\n * @param projectDir - Root directory of the project being operated on\n * @param overrides - Optional top-priority overrides (CLI flags, API body)\n * @returns Merged effective settings\n * @docLink packages/core/settings#resolve-settings\n */\nexport async function resolveSettings(\n projectDir: string,\n overrides?: Partial<SkaileSettings>,\n): Promise<SkaileSettings> {\n await migrateSettings(projectDir);\n\n // Base: built-in defaults\n let merged: SkaileSettings = { ...SETTINGS_DEFAULTS };\n\n // Layer: workspace config defaults (skaile.yaml via resolveSkWorkspaceConfig)\n merged = mergeSettings(merged, settingsFromWorkspaceConfig(projectDir));\n\n // Layer: user global settings\n const globalPath = globalSettingsPath();\n if (fs.existsSync(globalPath)) {\n try {\n const raw = JSON.parse(fs.readFileSync(globalPath, \"utf-8\"));\n merged = mergeSettings(merged, mapLegacyFields(raw));\n } catch {}\n }\n\n // Layer: project-local .skaile/settings.json (walking upward, farthest first)\n const settingsFiles = walkForSettings(projectDir);\n for (const filePath of settingsFiles.reverse()) {\n if (path.resolve(filePath) === path.resolve(globalPath)) continue;\n try {\n const raw = JSON.parse(fs.readFileSync(filePath, \"utf-8\"));\n merged = mergeSettings(merged, mapLegacyFields(raw));\n } catch {}\n }\n\n // Layer: environment variables (API keys + preferred provider/model)\n const envKeys = detectEnvApiKeys();\n if (Object.keys(envKeys).length > 0) {\n merged.apiKeys = { ...merged.apiKeys, ...envKeys };\n }\n if (process.env.PREFERRED_PROVIDER) merged.provider = process.env.PREFERRED_PROVIDER;\n if (process.env.PREFERRED_MODEL) merged.model = process.env.PREFERRED_MODEL;\n\n // Layer: explicit overrides\n if (overrides) merged = mergeSettings(merged, overrides);\n\n return merged;\n}\n\n// ── Provider / API key helpers ─────────────────────────────────────────────\n\n/**\n * Return the environment variable name for a provider's API key.\n * e.g. `providerEnvKey('anthropic')` → `'ANTHROPIC_API_KEY'`\n *\n * @param provider - Provider identifier (e.g. \"anthropic\", \"openai\")\n * @returns Environment variable name for that provider's API key\n * @docLink packages/core/settings#provider-env-key\n */\nexport function providerEnvKey(provider: string): string {\n return `${provider.toUpperCase().replace(/[^A-Z0-9]/g, \"_\")}_API_KEY`;\n}\n\n/**\n * Return the active API key for the given provider.\n * The matching environment variable (`*_API_KEY`) takes priority over\n * the value stored in `settings.apiKeys`.\n * Applies to `cloud: default`/`gateway` only — bedrock/vertex/azure sessions\n * carry their credentials as env bundles resolved by the runner instead.\n *\n * @param provider - Provider identifier (e.g. \"anthropic\")\n * @param settings - Current effective settings\n * @returns API key string, or undefined if not configured\n * @docLink packages/core/settings#resolve-api-key\n */\nexport function resolveApiKey(provider: string, settings: SkaileSettings): string | undefined {\n return process.env[providerEnvKey(provider)] || settings.apiKeys?.[provider];\n}\n\n/**\n * Return a masked version of an API key for safe logging.\n * Shows only the last four characters (e.g. `'****abc1'`).\n *\n * @param key - Raw API key to mask\n * @returns Masked key string, or empty string if key is falsy\n * @docLink packages/core/settings#mask-api-key\n */\nexport function maskApiKey(key: string): string {\n return key ? `****${key.slice(-4)}` : \"\";\n}\n\n/**\n * An API key resolved with information about where it came from.\n * @docLink packages/core/settings#resolved-key\n */\nexport interface ResolvedKey {\n /** Masked API key value (last 4 chars visible). */\n key: string;\n /** Whether the key came from an environment variable or stored settings. */\n source: \"env\" | \"stored\";\n}\n\n/**\n * Scan process.env (plus any `extraEnv` overrides) for recognized API key\n * variables and return them as a partial `apiKeys` record keyed by provider id.\n *\n * @param extraEnv - Additional environment entries to merge over process.env\n * @returns Partial apiKeys record containing only providers whose key was found\n * @docLink packages/core/settings#detect-env-api-keys\n */\nexport function detectEnvApiKeys(extraEnv?: Record<string, string>): Record<string, string> {\n const env = { ...process.env, ...extraEnv };\n const detected: Record<string, string> = {};\n for (const provider of ALL_PROVIDERS) {\n const val = env[providerEnvKey(provider)];\n if (val) detected[provider] = val;\n }\n return detected;\n}\n\n/**\n * Build a resolved key map for all known providers with source info and masked values.\n * Env-var keys take priority over stored keys when both exist.\n *\n * @param settings - Current effective settings (provides stored apiKeys)\n * @param envKeys - Keys detected from environment (e.g. from detectEnvApiKeys())\n * @returns Map from provider id to resolved key info; omits providers with no key\n * @docLink packages/core/settings#resolve-all-keys\n */\nexport function resolveAllKeys(\n settings: SkaileSettings,\n envKeys: Record<string, string>,\n): Record<string, ResolvedKey> {\n const result: Record<string, ResolvedKey> = {};\n for (const provider of ALL_PROVIDERS) {\n const envVal = envKeys[provider];\n const storedVal = settings.apiKeys?.[provider];\n if (envVal) {\n result[provider] = { key: maskApiKey(envVal), source: \"env\" };\n } else if (storedVal) {\n result[provider] = { key: maskApiKey(storedVal), source: \"stored\" };\n }\n }\n return result;\n}\n","/**\n * Runtime-portable subprocess spawning.\n *\n * `node:child_process` is implemented by both Node and Bun, so it is the\n * portable choice — no runtime detection needed (unlike embedded SQLite,\n * which has no shared API; see `logging/sinks/sqlite-runtime.ts`).\n *\n * These helpers wrap `node:child_process` to present a `Bun.Subprocess`-shaped\n * result — web `ReadableStream` stdio plus an `exited` promise — so call sites\n * migrated off `Bun.spawn` keep their stream-reading code unchanged.\n */\nimport { spawn, spawnSync } from \"node:child_process\";\nimport { Readable } from \"node:stream\";\n\nexport interface PortableSpawnOptions {\n cwd?: string;\n env?: Record<string, string | undefined>;\n detached?: boolean;\n}\n\n/**\n * Options for {@link portableSpawnSync}.\n *\n * `timeoutMs` is **required**, and deliberately so. A synchronous spawn blocks\n * the single-threaded event loop until the child exits; if the child stalls —\n * classically on a wedged network/FUSE mount reachable from `cwd` — the whole\n * process stops serving. An unbounded `spawnSync` is therefore not a call that\n * should be expressible, so the deadline is part of the type rather than an\n * optional extra a caller can forget.\n */\nexport interface PortableSpawnSyncOptions extends PortableSpawnOptions {\n /** Wall-clock limit for the child, in milliseconds. Must be > 0. */\n timeoutMs: number;\n}\n\n/** A spawned process with stdout/stderr piped. Mirrors the shape of `Bun.Subprocess`. */\nexport interface PortableSubprocess {\n /** OS process id, or -1 if the process failed to spawn. */\n readonly pid: number;\n readonly stdout: ReadableStream<Uint8Array>;\n readonly stderr: ReadableStream<Uint8Array>;\n /** Resolves with the exit code once the process closes (-1 on spawn error). */\n readonly exited: Promise<number>;\n kill(signal?: number | NodeJS.Signals): void;\n}\n\nexport interface PortableSpawnSyncResult {\n /** Exit code; -1 when the process did not exit cleanly. */\n exitCode: number;\n stdout: string;\n stderr: string;\n /**\n * `true` when the child was killed for exceeding\n * {@link PortableSpawnSyncOptions.timeoutMs}. Lets a caller tell \"the command\n * failed\" apart from \"the command never finished\", which are different\n * operational events.\n */\n timedOut: boolean;\n}\n\n/**\n * Spawn a subprocess with stdout/stderr piped. Works under Node and Bun.\n *\n * @param cmd - Command and arguments, e.g. `[\"docker\", \"ps\"]`.\n */\nexport function portableSpawn(cmd: string[], opts: PortableSpawnOptions = {}): PortableSubprocess {\n const [bin, ...args] = cmd;\n if (!bin) throw new Error(\"portableSpawn: empty command\");\n const child = spawn(bin, args, {\n cwd: opts.cwd,\n env: opts.env ?? process.env,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n detached: opts.detached,\n });\n const exited = new Promise<number>((resolve) => {\n child.on(\"close\", (code) => resolve(code ?? 0));\n child.on(\"error\", () => resolve(-1));\n });\n return {\n pid: child.pid ?? -1,\n stdout: Readable.toWeb(child.stdout as Readable) as unknown as ReadableStream<Uint8Array>,\n stderr: Readable.toWeb(child.stderr as Readable) as unknown as ReadableStream<Uint8Array>,\n exited,\n kill: (signal) => {\n if (opts.detached && child.pid) {\n try {\n process.kill(-child.pid, signal);\n return;\n } catch {\n /* fall back to killing the direct child */\n }\n }\n child.kill(signal);\n },\n };\n}\n\n/**\n * Run a subprocess to completion synchronously, capturing stdout/stderr as\n * UTF-8 strings. Works under Node and Bun.\n *\n * Blocks the event loop for the child's whole lifetime, so `opts.timeoutMs`\n * is required — see {@link PortableSpawnSyncOptions}. Prefer\n * {@link portableSpawn} wherever an async call is possible; only reach for this\n * when the caller genuinely cannot await (process teardown, CLI entry points).\n *\n * The child is killed with `SIGKILL` rather than `SIGTERM` on expiry: a process\n * blocked in an uninterruptible kernel wait (`D` state, e.g. a dead FUSE\n * connection) never runs a `SIGTERM` handler, so a graceful signal would leave\n * the deadline unenforced.\n *\n * @param cmd - Command and arguments, e.g. `[\"docker\", \"info\"]`.\n * @param opts - Spawn options; `timeoutMs` is mandatory.\n */\nexport function portableSpawnSync(\n cmd: string[],\n opts: PortableSpawnSyncOptions,\n): PortableSpawnSyncResult {\n const [bin, ...args] = cmd;\n if (!bin) throw new Error(\"portableSpawnSync: empty command\");\n if (!(opts.timeoutMs > 0)) {\n throw new Error(`portableSpawnSync: timeoutMs must be > 0 (got ${opts.timeoutMs})`);\n }\n const result = spawnSync(bin, args, {\n cwd: opts.cwd,\n env: opts.env ?? process.env,\n encoding: \"utf8\",\n timeout: opts.timeoutMs,\n killSignal: \"SIGKILL\",\n });\n // Node reports the expiry as `error.code === \"ETIMEDOUT\"`; Bun surfaces the\n // same case as a SIGKILL with no status, so accept either signal.\n const timedOut =\n (result.error as NodeJS.ErrnoException | undefined)?.code === \"ETIMEDOUT\" ||\n (result.status === null && result.signal === \"SIGKILL\");\n let stderr = result.stderr ?? \"\";\n if (timedOut) {\n // Surface the reason on the channel every caller already inspects — an\n // exitCode of -1 alone reads as \"command failed\" and hides the stall.\n stderr += `${stderr.endsWith(\"\\n\") || stderr === \"\" ? \"\" : \"\\n\"}${bin}: timed out after ${opts.timeoutMs}ms\\n`;\n }\n return {\n exitCode: result.status ?? -1,\n stdout: result.stdout ?? \"\",\n stderr,\n timedOut,\n };\n}\n","/**\n * Comment-preserving editor for skaile.yaml files.\n *\n * Uses the `yaml` library's Document API to parse into an AST that retains\n * comments, blank lines, and formatting. Mutations are applied to the AST\n * and serialized back — untouched sections remain byte-identical.\n *\n * Usage:\n *\n * import { WorkspaceYamlEditor } from '@skaile/workspaces/core'\n *\n * const editor = WorkspaceYamlEditor.load('/project/skaile.yaml')\n * editor.setAgentConfig('default', { driver: 'claude-sdk', model: 'claude-sonnet-4-6' })\n * editor.setSource({ url: 'https://github.com/skaile-ai/ai-assets' })\n * editor.save()\n */\n\nimport { existsSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { Document, isMap, isSeq, parseDocument, type YAMLMap } from \"yaml\";\nimport type {\n AgentConfigProfile,\n ConnectorDeclaration,\n McpServerDeclaration,\n OverrideEntry,\n SourceEntry,\n StoreEntry,\n} from \"./workspace-config.js\";\n\n/**\n * Comment-preserving editor for `skaile.yaml` files.\n * Uses the `yaml` library's Document AST so untouched sections remain byte-identical.\n * Create with `WorkspaceYamlEditor.load(filePath)` or `WorkspaceYamlEditor.create(filePath)`.\n * @docLink packages/core/workspace-config#workspace-yaml-editor\n */\nexport class WorkspaceYamlEditor {\n readonly path: string;\n private doc: Document;\n\n private constructor(path: string, doc: Document) {\n this.path = path;\n this.doc = doc;\n }\n\n /** Load an existing skaile.yaml file. */\n static load(filePath: string): WorkspaceYamlEditor {\n if (!existsSync(filePath)) {\n throw new Error(`File not found: ${filePath}`);\n }\n const raw = readFileSync(filePath, \"utf-8\");\n const doc = parseDocument(raw);\n return new WorkspaceYamlEditor(filePath, doc);\n }\n\n /** Create a new empty document (for use when no file exists yet). */\n static create(filePath: string): WorkspaceYamlEditor {\n const doc = new Document({});\n return new WorkspaceYamlEditor(filePath, doc);\n }\n\n /** Write the document back to disk, preserving comments and formatting. */\n save(): void {\n writeFileSync(this.path, this.doc.toString());\n }\n\n /** Return the serialized YAML string without writing to disk. */\n toString(): string {\n return this.doc.toString();\n }\n\n // ── Scalar fields ──────────────────────────────────────────────────────────\n\n /** Get a top-level scalar field (name, description). */\n get(key: \"name\" | \"description\"): string | undefined {\n const val = this.doc.get(key);\n return val != null ? String(val) : undefined;\n }\n\n /** Set a top-level scalar field. */\n set(key: \"name\" | \"description\", value: string): void {\n this.doc.set(key, value);\n }\n\n // ── Agent config ──────────────────────────────────────────────────────────\n\n /**\n * Get an agent config profile by name (usually \"default\").\n * Reads from `agent-config` (canonical YAML key).\n */\n getAgentConfig(profile = \"default\"): AgentConfigProfile | undefined {\n const section = this._getAgentConfigSection();\n if (!section) return undefined;\n const val = section.get(profile);\n return val && typeof val === \"object\" ? (val as unknown as AgentConfigProfile) : undefined;\n }\n\n /**\n * Set fields on an agent config profile. Merges with existing values —\n * only the provided fields are overwritten.\n */\n setAgentConfig(profile: string, values: Partial<AgentConfigProfile>): void {\n let section = this._getAgentConfigSection();\n if (!section) {\n // Create the section. Use 'agent-config' as the canonical YAML key.\n this.doc.set(\"agent-config\", { [profile]: {} });\n section = this._getAgentConfigSection()!;\n }\n\n const existing = section.get(profile, true);\n if (!existing || !isMap(existing)) {\n section.set(profile, { ...values });\n return;\n }\n\n for (const [k, v] of Object.entries(values)) {\n if (v === undefined) continue;\n existing.set(k, v);\n }\n }\n\n /**\n * Delete a field from an agent config profile.\n */\n deleteAgentConfigField(profile: string, field: string): void {\n const section = this._getAgentConfigSection();\n if (!section) return;\n const profileNode = section.get(profile, true);\n if (isMap(profileNode)) {\n profileNode.delete(field);\n }\n }\n\n private _getAgentConfigSection(): YAMLMap | undefined {\n // Try canonical 'agent-config' first, then 'agent_config'\n const node = this.doc.get(\"agent-config\", true) ?? this.doc.get(\"agent_config\", true);\n return isMap(node) ? (node as YAMLMap) : undefined;\n }\n\n // ── Connectors ─────────────────────────────────────────────────────────────\n\n /** Get all connectors. */\n getConnectors(): ConnectorDeclaration[] {\n const node = this.doc.get(\"connectors\", true) ?? this.doc.get(\"data_resources\", true);\n if (!isSeq(node)) return [];\n return node.toJSON() as ConnectorDeclaration[];\n }\n\n /** Add or update a connector by id. */\n setConnector(connector: ConnectorDeclaration): void {\n const key = \"connectors\";\n const node = this.doc.get(key, true);\n\n if (!node || !isSeq(node)) {\n this.doc.set(key, this.doc.createNode([connector]));\n return;\n }\n\n let found = false;\n for (let i = 0; i < node.items.length; i++) {\n const item = node.items[i];\n if (isMap(item) && (item as YAMLMap).get(\"id\") === connector.id) {\n node.set(i, this.doc.createNode(connector));\n found = true;\n break;\n }\n }\n\n if (!found) {\n node.add(this.doc.createNode(connector));\n }\n }\n\n /** Remove a connector by id. */\n removeConnector(id: string): boolean {\n const key = this.doc.has(\"connectors\") ? \"connectors\" : \"data_resources\";\n const node = this.doc.get(key, true);\n if (!node || !isSeq(node)) return false;\n\n for (let i = 0; i < node.items.length; i++) {\n const item = node.items[i];\n if (isMap(item) && (item as YAMLMap).get(\"id\") === id) {\n node.delete(i);\n return true;\n }\n }\n return false;\n }\n\n // ── MCP servers ────────────────────────────────────────────────────────────\n\n /**\n * Add or replace an mcp server entry, matched by `id`.\n * Mirrors {@link setConnector}: an existing entry with the same `id` is\n * replaced in place; otherwise the declaration is appended.\n */\n setMcpServer(mcp: McpServerDeclaration): void {\n const key = \"mcp_servers\";\n const node = this.doc.get(key, true);\n\n if (!node || !isSeq(node)) {\n this.doc.set(key, this.doc.createNode([mcp]));\n return;\n }\n\n let found = false;\n for (let i = 0; i < node.items.length; i++) {\n const item = node.items[i];\n if (isMap(item) && (item as YAMLMap).get(\"id\") === mcp.id) {\n node.set(i, this.doc.createNode(mcp));\n found = true;\n break;\n }\n }\n\n if (!found) {\n node.add(this.doc.createNode(mcp));\n }\n }\n\n // ── Dependencies ───────────────────────────────────────────────────────────\n\n /**\n * Append a dependency ref to `dependencies:`, deduped by exact ref string.\n *\n * @param ref - Canonical dependency ref (e.g. `skill:@skaile/foo#1.0.0`).\n * @returns `true` when the ref was newly added, `false` when it was already present.\n */\n addDependency(ref: string): boolean {\n const node = this.doc.get(\"dependencies\", true);\n if (!node || !isSeq(node)) {\n this.doc.set(\"dependencies\", this.doc.createNode([ref]));\n return true;\n }\n for (const item of node.items) {\n const cur = item != null && typeof item === \"object\" && \"value\" in item ? item.value : item;\n if (cur === ref) return false;\n }\n node.add(this.doc.createNode(ref));\n return true;\n }\n\n // ── Plugins ────────────────────────────────────────────────────────────────\n\n /** Get all `plugins:` specifiers. */\n getPlugins(): string[] {\n const node = this.doc.get(\"plugins\", true);\n if (!isSeq(node)) return [];\n const out: string[] = [];\n for (const item of node.items) {\n const cur = item != null && typeof item === \"object\" && \"value\" in item ? item.value : item;\n if (typeof cur === \"string\") out.push(cur);\n }\n return out;\n }\n\n /**\n * Add a plugin specifier to `plugins:`, deduped by package name.\n * If an entry with the same package name exists it is replaced (so a version\n * bump re-pins in place); otherwise the spec is appended.\n *\n * @param spec - npm specifier, e.g. `\"@skaile/provider-fly@^0.1.0\"`.\n * @param nameOf - Extracts the package name from a spec (caller passes `parseSpec`-derived names).\n * @returns `true` when an existing entry was replaced, `false` when appended.\n */\n addPlugin(spec: string, nameOf: (s: string) => string): boolean {\n const node = this.doc.get(\"plugins\", true);\n if (!node || !isSeq(node)) {\n this.doc.set(\"plugins\", this.doc.createNode([spec]));\n return false;\n }\n\n const wantName = nameOf(spec);\n for (let i = 0; i < node.items.length; i++) {\n const item = node.items[i];\n const cur = item != null && typeof item === \"object\" && \"value\" in item ? item.value : item;\n if (typeof cur === \"string\" && nameOf(cur) === wantName) {\n node.set(i, this.doc.createNode(spec));\n return true;\n }\n }\n node.add(this.doc.createNode(spec));\n return false;\n }\n\n /**\n * Remove the `plugins:` entry whose package name matches `name`.\n *\n * @param name - Package name to remove (e.g. `\"@skaile/provider-fly\"`).\n * @param nameOf - Extracts the package name from a spec.\n * @returns `true` when an entry was removed.\n */\n removePlugin(name: string, nameOf: (s: string) => string): boolean {\n const node = this.doc.get(\"plugins\", true);\n if (!node || !isSeq(node)) return false;\n\n for (let i = 0; i < node.items.length; i++) {\n const item = node.items[i];\n const cur = item != null && typeof item === \"object\" && \"value\" in item ? item.value : item;\n if (typeof cur === \"string\" && nameOf(cur) === name) {\n node.delete(i);\n return true;\n }\n }\n return false;\n }\n\n // ── Sources ────────────────────────────────────────────────────────────────\n\n /** Get all source entries (`{url, pin?}`). */\n getSources(): SourceEntry[] {\n const node = this.doc.get(\"sources\", true);\n if (!isSeq(node)) return [];\n return node.toJSON() as SourceEntry[];\n }\n\n /**\n * Add or update a source entry, matched by `url`.\n * If an entry with the same url exists, it is replaced.\n */\n setSource(entry: SourceEntry): void {\n const node = this.doc.get(\"sources\", true);\n if (!node || !isSeq(node)) {\n this.doc.set(\"sources\", this.doc.createNode([entry]));\n return;\n }\n let found = false;\n for (let i = 0; i < node.items.length; i++) {\n const item = node.items[i];\n if (isMap(item) && (item as YAMLMap).get(\"url\") === entry.url) {\n node.set(i, this.doc.createNode(entry));\n found = true;\n break;\n }\n }\n if (!found) node.add(this.doc.createNode(entry));\n }\n\n /** Remove a source entry by url. Returns true when an entry was removed. */\n removeSource(url: string): boolean {\n const node = this.doc.get(\"sources\", true);\n if (!node || !isSeq(node)) return false;\n for (let i = 0; i < node.items.length; i++) {\n const item = node.items[i];\n if (isMap(item) && (item as YAMLMap).get(\"url\") === url) {\n node.delete(i);\n return true;\n }\n }\n return false;\n }\n\n // ── Stores ─────────────────────────────────────────────────────────────────\n\n /** Get all store entries (`{url}`). */\n getStores(): StoreEntry[] {\n const node = this.doc.get(\"stores\", true);\n if (!isSeq(node)) return [];\n return node.toJSON() as StoreEntry[];\n }\n\n /** Add or update a store entry, matched by `url`. */\n setStore(entry: StoreEntry): void {\n const node = this.doc.get(\"stores\", true);\n if (!node || !isSeq(node)) {\n this.doc.set(\"stores\", this.doc.createNode([entry]));\n return;\n }\n let found = false;\n for (let i = 0; i < node.items.length; i++) {\n const item = node.items[i];\n if (isMap(item) && (item as YAMLMap).get(\"url\") === entry.url) {\n node.set(i, this.doc.createNode(entry));\n found = true;\n break;\n }\n }\n if (!found) node.add(this.doc.createNode(entry));\n }\n\n /** Remove a store entry by url. Returns true when an entry was removed. */\n removeStore(url: string): boolean {\n const node = this.doc.get(\"stores\", true);\n if (!node || !isSeq(node)) return false;\n for (let i = 0; i < node.items.length; i++) {\n const item = node.items[i];\n if (isMap(item) && (item as YAMLMap).get(\"url\") === url) {\n node.delete(i);\n return true;\n }\n }\n return false;\n }\n\n // ── Overrides ────────────────────────────────────────────────────────────────\n\n /** Get all override entries (`{ref, source, reason}`). */\n getOverrides(): OverrideEntry[] {\n const node = this.doc.get(\"overrides\", true);\n if (!isSeq(node)) return [];\n return node.toJSON() as OverrideEntry[];\n }\n\n /** Add or update an override entry, matched by `ref`. */\n setOverride(entry: OverrideEntry): void {\n const node = this.doc.get(\"overrides\", true);\n if (!node || !isSeq(node)) {\n this.doc.set(\"overrides\", this.doc.createNode([entry]));\n return;\n }\n let found = false;\n for (let i = 0; i < node.items.length; i++) {\n const item = node.items[i];\n if (isMap(item) && (item as YAMLMap).get(\"ref\") === entry.ref) {\n node.set(i, this.doc.createNode(entry));\n found = true;\n break;\n }\n }\n if (!found) node.add(this.doc.createNode(entry));\n }\n\n /** Remove an override entry by ref. Returns true when an entry was removed. */\n removeOverride(ref: string): boolean {\n const node = this.doc.get(\"overrides\", true);\n if (!node || !isSeq(node)) return false;\n for (let i = 0; i < node.items.length; i++) {\n const item = node.items[i];\n if (isMap(item) && (item as YAMLMap).get(\"ref\") === ref) {\n node.delete(i);\n return true;\n }\n }\n return false;\n }\n\n // ── Raw access (escape hatch) ─────────────────────────────────────────────\n\n /** Get the underlying yaml Document for advanced manipulation. */\n get document(): Document {\n return this.doc;\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../session/src/dispatcher.ts","../session/src/mentions.ts"],"names":[],"mappings":";;;AAsDA,IAAM,eAAA,uBAAsB,GAAA,CAAI;AAAA,EAC9B,kBAAA;AAAA,EACA,mBAAA;AAAA,EACA,qBAAA;AAAA,EACA,oBAAA;AAAA,EACA,eAAA;AAAA,EACA,QAAA;AAAA,EACA,QAAA;AAAA,EACA,cAAA;AAAA;AAAA,EAEA,cAAA;AAAA;AAAA,EAEA,WAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKA,kBAAA;AAAA,EACA,iBAAA;AAAA,EACA,0BAAA;AAAA;AAAA;AAAA;AAAA,EAIA;AACF,CAAC,CAAA;AAiCM,IAAM,oBAAN,MAAwB;AAAA;AAAA,EAEpB,SAAA;AAAA,EACD,MAAA;AAAA,EACA,KAAA;AAAA,EACA,SAAA;AAAA,EACA,WAAA,uBAA+B,GAAA,EAAI;AAAA,EACnC,cAAA,uBAAkD,GAAA,EAAI;AAAA,EACtD,GAAA,GAAc,CAAA;AAAA,EACd,mBAAA,GAAoE;A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,CAAY,QAAgB,QAAA,EAA8B;AACxE,EAAA,KAAA,MAAW,KAAK,QAAA,EAAU;AACxB,IAAA,IAAI,EAAE,IAAA,KAAS,MAAA,IAAU,CAAA,CAAE,MAAA,KAAW,QAAQ,OAAO,IAAA;AACrD,IAAA,IAAI,CAAA,CAAE,SAAS,OAAA,IAAW,CAAA,CAAE,SAAS,QAAA,CAAS,MAAM,GAAG,OAAO,IAAA;AAC9D,IAAA,IAAI,CAAA,CAAE,SAAS,QAAA,IAAY,CAAA,CAAE,SAAS,QAAA,CAAS,MAAM,GAAG,OAAO,IAAA;AAAA,EACjE;AACA,EAAA,OAAO,KAAA;AACT;AAgBO,SAAS,iBAAA,CAAkB,UAAqB,IAAA,EAAuB;AAC5E,EAAA,OAAO,QAAA,CAAS,KAAK,CAAC,CAAA,KAAM,EAAE,IAAA,KAAS,QAAA,IAAY,CAAA,CAAE,IAAA,KAAS,IAAI,CAAA;AACpE;AAOA,IAAM,+BAA0C,IAAI,GAAA,CAAI,CAAC,OAAA,EAAS,MAAA,EAAQ,KAAK,CAAC,CAAA;AAYzE,SAAS,iBAAiB,QAAA,EAA8B;AAC7D,EAAA,OAAO,QAAA,CAAS,IAAA,CAAK,CAAC,CAAA,KAAM,CAAA,CAAE,IAAA,KAAS,OAAA,IAAW,YAAA,CAAa,GAAA,CAAI,CAAA,CAAE,KAAK,CAAC,CAAA;AAC7E","file":"chunk-CA5CWLGN.js","sourcesContent":["import type { AgentClient } from \"@skaile/workspaces/client\";\nimport type {\n AgentCommand,\n AgentEvent,\n ConnectorRequestCommand,\n ConnectorResponseEvent,\n Mention,\n ReplyRef,\n} from \"@skaile/workspaces/types\";\nimport type { Message, MessageStore, SubscriberInfo, SubscriberTransport } from \"./types.js\";\n\n/**\n * Construction options for {@link SessionDispatcher}.\n *\n * All three infrastructure objects (`client`, `store`, `transport`) are\n * injected by the caller so the dispatcher remains testable and framework-agnostic.\n *\n * @docLink packages/session/api-reference#session-dispatcher\n */\nexport interface SessionDispatcherOptions {\n /** Unique identifier for the session this dispatcher manages. */\n sessionId: string;\n /** Connected agent client used to send commands and receive events. */\n client: AgentClient;\n /** Persistence layer for all non-transient messages. */\n store: MessageStore;\n /** Fan-out transport for broadcasting events to connected frontends. */\n transport: SubscriberTransport;\n /**\n * When true, the dispatcher prepends conversation history to every prompt\n * command sent to the agent. Enable for agents without native session\n * continuity (e.g. mock mode). Agents with native multi-turn support\n * (Claude SDK, OMP) should set this to false to avoid duplicate context.\n * Default: false.\n */\n injectConversationHistory?: boolean;\n /** Max conversation history messages to include in enriched prompts (default: 50). */\n historyLimit?: number;\n /**\n * Optional callback to transform prompt text before forwarding to the agent.\n * The original (untransformed) prompt is persisted and broadcast to subscribers.\n * Applied after conversation history enrichment. Use this to inject context\n * (e.g. UI state) that the agent should see but subscribers should not.\n */\n transformPrompt?: (prompt: string, senderId: string | undefined, replyTo?: ReplyRef) => string;\n}\n\n/**\n * Command and event types classified as transient RPC — high-frequency,\n * ephemeral, and not part of the conversation history.\n *\n * Matching payloads are forwarded and broadcast but never persisted\n * or assigned a sequence number, preventing bloat in the message log.\n */\nconst TRANSIENT_TYPES = new Set([\n \"resource_request\",\n \"resource_response\",\n \"resources_available\",\n \"commands_available\",\n \"state_changed\",\n \"status\",\n \"typing\",\n \"user_message\",\n // OMP session tracking — forwarded to subscribers but not persisted\n \"session_info\",\n // Structured log forwarding — high-volume; persisted in per-session SQLite, not the message store\n \"log_entry\",\n // Generic connector dispatch — system RPC, not chat messages.\n // Replaces the 6 typed flow commands removed in Protocol 2.2 (Phase 4 of the\n // flow-connector extraction). `connector_mutate` against the `flow` connector\n // is now how hosts drive flow execution between turns.\n \"connector_mutate\",\n \"connector_query\",\n \"connector_query_response\",\n // Mandatory, not cosmetic: `shouldPersist` is a pure denylist with no escape\n // hatch, so an unlisted ack is stored as a chat Message and flushes the\n // in-flight streaming-text buffer, splitting the assistant's bubble mid-turn.\n \"connector_mutate_response\",\n]);\n\n/**\n * Bridges a single agent session between an {@link AgentClient} and one or more\n * frontend subscribers.\n *\n * Responsibilities:\n * - Persists every non-transient command and event as a {@link Message} with a\n * monotonic sequence number via the injected {@link MessageStore}.\n * - Fans agent events out to all connected frontends via the injected\n * {@link SubscriberTransport}.\n * - Optionally enriches prompt commands with conversation history so agents\n * without native multi-turn support maintain context across turns.\n *\n * **Lifecycle:** call {@link init} before any other method, and {@link disconnect}\n * when the session ends.\n *\n * @example\n * ```ts\n * const dispatcher = new SessionDispatcher({\n * sessionId: 'sess-123',\n * client: agentClient,\n * store: prismaMessageStore,\n * transport: trpcTransport,\n * })\n * await dispatcher.init()\n * const history = await dispatcher.subscribe('ws-conn-abc', { limit: 50 })\n * const msg = await dispatcher.sendCommand({ type: 'prompt', prompt: 'Hello' }, 'user-42')\n * await dispatcher.disconnect()\n * ```\n *\n * @docLink packages/session/api-reference#session-dispatcher\n */\nexport class SessionDispatcher {\n /** The session identifier this dispatcher is bound to. */\n readonly sessionId: string;\n private client: AgentClient;\n private store: MessageStore;\n private transport: SubscriberTransport;\n private subscribers: Set<string> = new Set();\n private subscriberMeta: Map<string, SubscriberInfo> = new Map();\n private seq: number = 0;\n private _availableResources: { mounts: unknown[]; connectors: unknown[] } = {\n mounts: [],\n connectors: [],\n };\n\n /** Whether to inject conversation history into prompt commands. */\n private readonly injectConversationHistory: boolean;\n /** Maximum number of history messages to include in enriched prompts. */\n private readonly historyLimit: number;\n /** Optional prompt transformer applied before forwarding (after persistence). */\n private _transformPrompt?: (\n prompt: string,\n senderId: string | undefined,\n replyTo?: ReplyRef,\n ) => string;\n /** Whether the dispatcher is currently in compaction mode. */\n private _compacting = false;\n /** Accumulated text content during compaction. */\n private _compactionText = \"\";\n\n /**\n * One-shot waiters registered via {@link onceNextFinished}. Each is invoked\n * exactly once with the text of the next `finished` assistant event, then\n * the list is cleared. Backs the A2A router's synchronous `ask` answer\n * capture.\n */\n private nextFinishedWaiters: Array<(text: string) => void> = [];\n /**\n * Text streamed by the agent since the last `finished` event. Used as the\n * fallback answer text for {@link onceNextFinished} when a `finished` event\n * carries an empty `summary` (drivers that stream `text` chunks and leave\n * the summary blank).\n */\n private _turnText = \"\";\n\n /**\n * @param opts - Dispatcher configuration — see {@link SessionDispatcherOptions}.\n */\n constructor(opts: SessionDispatcherOptions) {\n this.sessionId = opts.sessionId;\n this.client = opts.client;\n this.store = opts.store;\n this.transport = opts.transport;\n this.injectConversationHistory = opts.injectConversationHistory ?? false;\n this.historyLimit = opts.historyLimit ?? 50;\n this._transformPrompt = opts.transformPrompt;\n }\n\n /**\n * Replace the prompt transformer at runtime.\n *\n * Useful when additional context (e.g. a UI state cache) becomes available\n * after the dispatcher is constructed but before the first prompt is sent.\n */\n set transformPrompt(fn:\n | ((prompt: string, senderId: string | undefined, replyTo?: ReplyRef) => string)\n | undefined,) {\n this._transformPrompt = fn;\n }\n\n /**\n * Initialize the dispatcher for this session.\n *\n * Restores the monotonic sequence counter from the store and wires up the\n * agent event listener. Must be called once before any other method.\n *\n * @throws If {@link MessageStore.getLatestSeq} rejects.\n */\n async init(): Promise<void> {\n this.seq = await this.store.getLatestSeq(this.sessionId);\n this.client.onEvent((event: AgentEvent) => {\n void this.handleAgentEvent(event);\n });\n }\n\n /**\n * Register a frontend subscriber and return recent message history.\n *\n * Subsequent agent events are pushed to this subscriber via the\n * {@link SubscriberTransport} until {@link unsubscribe} is called.\n *\n * @param subscriberId - Opaque connection ID (e.g. WebSocket session ID).\n * @param opts - Optional subscription options.\n * @param opts.limit - Number of recent messages to return (default: 50).\n * @returns Recent messages ordered by seq ascending.\n */\n async subscribe(\n subscriberId: string,\n opts?: { limit?: number; userId?: string; roles?: string[] },\n ): Promise<Message[]> {\n this.subscribers.add(subscriberId);\n if (opts?.userId !== undefined || opts?.roles !== undefined) {\n this.subscriberMeta.set(subscriberId, {\n userId: opts.userId,\n roles: opts.roles,\n });\n }\n return this.store.getMessages(this.sessionId, {\n limit: opts?.limit ?? 50,\n });\n }\n\n /**\n * Remove a frontend subscriber and release transport resources.\n *\n * @param subscriberId - The ID passed to {@link subscribe}.\n */\n unsubscribe(subscriberId: string): void {\n this.subscribers.delete(subscriberId);\n this.subscriberMeta.delete(subscriberId);\n this.transport.remove(subscriberId);\n }\n\n /**\n * Send a command from a frontend to the agent.\n *\n * Persistent commands are wrapped in a Message envelope and stored before\n * forwarding. Transient commands (resource RPC) are forwarded directly\n * without persistence — returns null in that case.\n *\n * For `prompt` commands, the original message is persisted, but an enriched\n * version (with conversation history prepended) is sent to the agent so it\n * maintains context across turns.\n *\n * @param command - The command to dispatch to the agent (a prompt or tool result).\n * @param senderId - ID of the user sending the command, if known.\n * @param mentions - Resolved mention objects extracted from the prompt text.\n * @param visibility - Optional platform visibility envelope (F-23). When\n * `visibilityMode` is `HumansOnly`, or `Private` without the `\"__agent__\"`\n * sentinel in `privateRecipientIds` (B-30), the message is persisted and\n * broadcast to subscribers but NOT forwarded to the agent.\n * @param outgoingPrefix - Optional text prepended to the outgoing command's\n * user-text field ({@link command.prompt} / `command.answer` /\n * `command.content`) AFTER persistence but BEFORE history enrichment and\n * {@link transformPrompt}. The persisted {@link Message} envelope is built\n * from the original `command` and never sees the prefix. Use this to\n * inject one-shot wake-time context (Option B1 pending restoration\n * prompt) that the agent must see but UI subscribers must not.\n * @returns The persisted Message envelope, or null for transient command types.\n */\n async sendCommand(\n command: AgentCommand,\n senderId?: string,\n mentions?: Mention[],\n visibility?: NonNullable<Message[\"visibility\"]>,\n outgoingPrefix?: string,\n ): Promise<Message | null> {\n if (!this.shouldPersist(command)) {\n this.client.send(command);\n return null;\n }\n // Persist the original command (unenriched/untransformed/un-prefixed).\n // `outgoingPrefix` is intentionally NOT applied here — it must only\n // reach the agent client, never the MessageStore.\n const message = this.createMessage(command, senderId);\n // @TODO: Code-Review: v1 back-compat — mentions field no longer used by Protocol v2+ persistence layers; remove once platform PrismaMessageStore is migrated\n if (mentions?.length) message.mentions = mentions;\n // F-23: platform-extension visibility metadata (3.2.0). The platform\n // MessageStore reads this off the envelope and writes the\n // Message.visibilityMode column + recipient rows atomically with\n // the message itself — no post-send patch, no race window where a\n // concurrent send could mis-tag the wrong message id.\n if (visibility) message.visibility = visibility;\n await this.store.append(message);\n\n // Build the outgoing command — enrich and transform prompt commands\n // while leaving the persisted message untouched.\n let outgoing: AgentCommand = command;\n if (command.type === \"prompt\") {\n let prompt = command.prompt;\n // Restoration prefix lands FIRST (innermost) so the user's typed\n // text remains adjacent to its own framing, with history and reply\n // preambles wrapping the combined block from the outside in.\n if (outgoingPrefix) {\n prompt = `${outgoingPrefix}${prompt}`;\n }\n if (this.injectConversationHistory) {\n prompt = await this.enrichPromptWithHistory(prompt);\n }\n if (this._transformPrompt) {\n prompt = this._transformPrompt(prompt, senderId, command.replyTo);\n }\n if (prompt !== command.prompt) {\n outgoing = { ...command, prompt };\n }\n } else if (outgoingPrefix && command.type === \"reply\") {\n // `reply` carries user text in `answer`. Prefix is invisible to\n // subscribers (who see the persisted Message.payload.answer) but\n // visible to the agent driver.\n outgoing = { ...command, answer: `${outgoingPrefix}${command.answer}` };\n } else if (outgoingPrefix && command.type === \"custom_message\") {\n // `custom_message` carries user text in `content`. Same persist/send\n // split as the `reply` branch above.\n outgoing = { ...command, content: `${outgoingPrefix}${command.content}` };\n }\n\n // F-23 P3 review (B1) — HumansOnly visibility means the message is\n // intended for human recipients only; the agent must NOT see the\n // prompt content. Persist + broadcast (humans read it via\n // SubscriberTransport) but skip the agent forward. This closes a\n // critical privacy hole where `@user: secret` was persisted with\n // visibilityMode='HumansOnly' yet still reached the LLM. Threads\n // starting HumansOnly stay agent-invisible even on Public follow-ups\n // (parent-thread visibility threading is intentionally out of scope\n // for v1; only the immediate message is gated). See\n // platform/_concept/plans/f-23-p3-review-blockers.md.\n if (visibility?.visibilityMode === \"HumansOnly\") {\n return message;\n }\n\n // B-30 — Private visibility (F-23 `@mention_` underscore suffix) means the\n // message is addressed to an explicit recipient set. The agent is only a\n // recipient when the sender wrote `@agent_`, which the platform encodes as\n // the `\"__agent__\"` sentinel in `privateRecipientIds`. When the sentinel is\n // absent the message is a private human-to-human exchange: persist +\n // broadcast (the named human recipients read it via SubscriberTransport)\n // but skip the agent forward so the LLM never sees private content.\n if (\n visibility?.visibilityMode === \"Private\" &&\n !visibility.privateRecipientIds?.includes(\"__agent__\")\n ) {\n return message;\n }\n\n this.client.send(outgoing);\n return message;\n }\n\n /**\n * Persist a synthetic event (not received from the agent) and broadcast it.\n *\n * Used by the platform to inject events like a partial-text `finished` record\n * before a cancel command.\n *\n * @param event - The agent event to persist.\n * @param mentions - Resolved mentions from the originating command.\n */\n async persistEvent(event: AgentEvent, mentions?: Mention[]): Promise<Message | null> {\n return this.handleAgentEvent(event, mentions);\n }\n\n /**\n * Load paginated message history for this session.\n *\n * @param opts.before - Return messages with seq strictly less than this value.\n * @param opts.limit - Maximum number of messages to return.\n */\n async getMessages(opts?: { before?: number; limit?: number }): Promise<Message[]> {\n return this.store.getMessages(this.sessionId, opts);\n }\n\n /**\n * Available mounts and connectors captured from the most recent\n * `resources_available` event emitted by the agent on connect.\n *\n * Empty until the agent emits the event or {@link seedResources} is called.\n */\n get availableResources(): { mounts: unknown[]; connectors: unknown[] } {\n return this._availableResources;\n }\n\n /**\n * Seed the available resources from an external cache.\n *\n * This is needed when the dispatcher is created after the agent has already\n * emitted `resources_available` on WebSocket connect. Without seeding, the\n * dispatcher would report an empty resource list until the next reconnect.\n *\n * @param resources - Resource handles to register before the session starts.\n */\n seedResources(resources: { mounts: unknown[]; connectors: unknown[] }): void {\n const empty =\n this._availableResources.mounts.length === 0 &&\n this._availableResources.connectors.length === 0;\n if (empty && (resources.mounts.length > 0 || resources.connectors.length > 0)) {\n this._availableResources = resources;\n }\n }\n\n /**\n * Deliver a prompt to the agent that triggers a turn but is NOT persisted.\n *\n * Unlike {@link sendCommand}, this never touches the {@link MessageStore}:\n * the prompt is forwarded straight to the agent client. The caller owns\n * persistence of whatever conversation rows should represent this turn.\n *\n * Used by the platform's A2A router to deliver a `from-peer` prompt to a\n * target session: the router writes the authoritative A2A `Message` rows\n * itself, so persisting the framed prompt here too would create an extra,\n * un-attributed plain `prompt` row. The dispatcher's job for this prompt is\n * delivery only.\n *\n * The agent still produces a normal turn, so an A2A `ask` round-trip can\n * capture the answer via {@link onceNextFinished}.\n *\n * @param prompt - The fully-formed prompt text to deliver to the agent.\n */\n deliverPrompt(prompt: string): void {\n this.client.send({ type: \"prompt\", prompt });\n }\n\n /**\n * Send a resource request and await the correlated response.\n *\n * This is a convenience method for request/response resource RPC.\n * The request is transient (not persisted). A one-shot event listener\n * waits for the matching `resource_response` by `requestId`.\n *\n * @param command - A ConnectorRequestCommand (caller must set requestId).\n * @param timeoutMs - How long to wait before rejecting (default: 30s).\n */\n async requestResource(\n command: ConnectorRequestCommand,\n timeoutMs = 30_000,\n ): Promise<ConnectorResponseEvent> {\n return new Promise<ConnectorResponseEvent>((resolve, reject) => {\n const timer = setTimeout(() => {\n this.client.offEvent(handler);\n reject(\n new Error(\n `Resource request timed out after ${timeoutMs}ms: ${command.operation} ${command.connectorId}`,\n ),\n );\n }, timeoutMs);\n\n const handler = (event: AgentEvent) => {\n if (event.type === \"resource_response\" && event.requestId === command.requestId) {\n clearTimeout(timer);\n this.client.offEvent(handler);\n resolve(event);\n }\n };\n\n this.client.onEvent(handler);\n this.client.send(command);\n });\n }\n\n /**\n * Broadcast a transient event to all subscribers without persisting it.\n *\n * Used for ephemeral signals like typing indicators or user-command\n * echoes that other subscribers need to see in real time.\n */\n broadcast(event: AgentEvent): void {\n for (const subscriberId of this.subscribers) {\n this.transport.send(subscriberId, event);\n }\n }\n\n /** Disconnect the agent client and clean up all subscribers. */\n async disconnect(): Promise<void> {\n for (const id of this.subscribers) {\n this.transport.remove(id);\n }\n this.subscribers.clear();\n this.subscriberMeta.clear();\n // Clear any pending A2A waiters so they don't leak if the session\n // disconnects before the target ever emits a `finished` event.\n this.nextFinishedWaiters = [];\n await this.client.dispose();\n }\n\n /**\n * Enter compaction mode. While active, events from the agent are captured\n * but NOT persisted. Text content is accumulated for the snapshot.\n */\n beginCompaction(): void {\n this._compacting = true;\n this._compactionText = \"\";\n }\n\n /**\n * Exit compaction mode and return the accumulated text.\n * The caller is responsible for creating and emitting the snapshot event.\n */\n endCompaction(): string {\n this._compacting = false;\n const text = this._compactionText;\n this._compactionText = \"\";\n return text;\n }\n\n /** Whether the dispatcher is currently in compaction mode. */\n get isCompacting(): boolean {\n return this._compacting;\n }\n\n /**\n * Register a one-shot callback fired with the text of this session's next\n * finished assistant turn. Returns an unsubscribe function.\n *\n * Semantics:\n * - The callback fires **at most once** — on the first `finished` event\n * observed after registration. Later finished turns do not re-fire it.\n * - A waiter registered after a `finished` event waits for the *following*\n * one. The hook captures the *next* finished turn, not a past one.\n * - The answer text is the `finished` event's `summary`; when that is\n * empty (drivers that stream `text` and leave the summary blank), the\n * text accumulated since the previous finished turn is used instead.\n * - Calling the returned function removes the waiter; if it has already\n * fired this is a no-op.\n *\n * Used by the platform's A2A router (`A2ARouterService.ask`) to capture a\n * peer session's answer to a `from-peer` question. v1 captures the first\n * finished turn after delivery — see the busy-target notes in the A2A\n * design spec for the known turn-matching limitation.\n *\n * @param cb - Invoked once with the next finished turn's text.\n * @returns Unsubscribe function that removes this waiter.\n */\n onceNextFinished(cb: (text: string) => void): () => void {\n this.nextFinishedWaiters.push(cb);\n return () => {\n const idx = this.nextFinishedWaiters.indexOf(cb);\n if (idx !== -1) {\n this.nextFinishedWaiters.splice(idx, 1);\n }\n };\n }\n\n // -- Private ----------------------------------------------------------------\n\n /**\n * Build an enriched prompt by prepending conversation history.\n *\n * Loads recent persisted messages, formats user/assistant turns, and\n * wraps them in a `<conversation_history>` block. The current user\n * message (just persisted) is excluded since it is already the prompt.\n *\n * Each turn is rendered as a self-closing `<turn role=\"...\">` element\n * rather than a bare `[User]:` / `[Assistant]:` transcript line. A plain\n * role-prefixed transcript invites the model to *continue* it — completing\n * the next `[User]:` turn as plaintext inside its own answer (a fabricated\n * follow-up that swallows the real next message). XML-tagged, explicitly\n * read-only turns remove that completion affordance while preserving the\n * same information.\n *\n * Returns the original prompt unchanged if there is no prior history.\n */\n private async enrichPromptWithHistory(currentPrompt: string): Promise<string> {\n const messages = await this.store.getMessages(this.sessionId, {\n limit: this.historyLimit,\n });\n\n // Filter to conversation-relevant types and exclude the message we just appended\n const history = messages\n .filter((m) => {\n const type = m.payload.type;\n return type === \"prompt\" || type === \"finished\" || type === \"question\";\n })\n .slice(0, -1); // Exclude the current message (last by seq)\n\n if (history.length === 0) {\n return currentPrompt;\n }\n\n // Escape so message content (which may itself contain `</turn>` or other\n // angle brackets) cannot break out of the XML structure or inject a forged\n // turn. The model reads entity-encoded text fine; this is read-only context.\n const esc = (s: string): string =>\n s.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\n\n const turns = history.map((m) => {\n const p = m.payload as Record<string, unknown>;\n if (p.type === \"prompt\") {\n return `<turn role=\"user\">${esc(String(p.prompt ?? \"\"))}</turn>`;\n }\n // finished (assistant response) or question\n const content = String(p.summary ?? p.question ?? \"\");\n return `<turn role=\"assistant\">${esc(content)}</turn>`;\n });\n\n return (\n \"<conversation_history>\\n\" +\n \"The following is prior conversation context, provided read-only so you \" +\n \"have continuity. Do NOT continue, echo, or complete it — it is history, \" +\n \"not a turn for you to extend. Respond only to the user message that \" +\n \"follows the closing tag.\\n\" +\n `${turns.join(\"\\n\")}\\n` +\n \"</conversation_history>\\n\\n\" +\n currentPrompt\n );\n }\n\n private async handleAgentEvent(event: AgentEvent, mentions?: Mention[]): Promise<Message | null> {\n // ── Compaction mode: capture text but don't persist ─────────────────\n if (this._compacting) {\n if (event.type === \"text\") {\n this._compactionText += (event as { content: string }).content;\n }\n // Still broadcast to subscribers (UI shows compaction progress)\n for (const subscriberId of this.subscribers) {\n this.transport.send(subscriberId, event);\n }\n return null;\n }\n\n // Capture resource metadata when the server announces available resources\n if (event.type === \"resources_available\") {\n const payload = event as { mounts?: unknown[]; connectors?: unknown[] };\n this._availableResources = {\n mounts: payload.mounts ?? [],\n connectors: payload.connectors ?? [],\n };\n }\n\n // ── onceNextFinished — one-shot \"next finished turn\" answer capture ──\n // Accumulate streamed text across the turn so the answer is available\n // even when a driver emits an empty `finished.summary`. On `finished`,\n // drain every queued waiter exactly once, then reset the accumulator.\n if (event.type === \"text\") {\n this._turnText += (event as { content: string }).content;\n } else if (event.type === \"finished\") {\n const summary = (event as { summary?: string }).summary ?? \"\";\n const answer = summary.length > 0 ? summary : this._turnText;\n this._turnText = \"\";\n if (this.nextFinishedWaiters.length > 0) {\n const waiters = this.nextFinishedWaiters;\n this.nextFinishedWaiters = [];\n for (const cb of waiters) {\n cb(answer);\n }\n }\n }\n\n let message: Message | null = null;\n if (this.shouldPersist(event)) {\n message = this.createMessage(event);\n if (mentions?.length) message.mentions = mentions;\n await this.store.append(message);\n }\n\n for (const subscriberId of this.subscribers) {\n this.transport.send(subscriberId, event);\n }\n return message;\n }\n\n private shouldPersist(payload: AgentCommand | AgentEvent): boolean {\n return !TRANSIENT_TYPES.has(payload.type);\n }\n\n private createMessage(payload: AgentCommand | AgentEvent, senderId?: string): Message {\n this.seq++;\n return {\n id: crypto.randomUUID(),\n seq: this.seq,\n timestamp: new Date().toISOString(),\n sessionId: this.sessionId,\n ...(senderId ? { senderId } : {}),\n payload,\n };\n }\n}\n","import type { Mention, MentionGroup } from \"@skaile/workspaces/types\";\nimport { MENTION_GROUPS } from \"@skaile/workspaces/types\";\n\n/**\n * Re-exported from `@skaile/workspaces/types` so consumers can import mention\n * types directly from `@skaile/workspaces/session` without a separate dependency.\n */\nexport type { Mention, MentionGroup };\n\n// ---------------------------------------------------------------------------\n// MentionResolver\n// ---------------------------------------------------------------------------\n\n/**\n * Consumer-provided resolver that maps @mention tokens to users and groups.\n *\n * The platform provides an implementation backed by Prisma and the live\n * presence service. Tests use lightweight mocks.\n *\n * @example\n * ```ts\n * const resolver: MentionResolver = {\n * resolveUser: (name) => db.users.findByName(name),\n * resolveGroup: (group) => presence.getMemberIds(group),\n * getOnlineUserIds: () => presence.getOnlineIds(),\n * }\n * ```\n *\n * @docLink packages/session/api-reference#mention-resolver\n */\nexport interface MentionResolver {\n /**\n * Resolve a `@name` token to a user record.\n *\n * @param name - The token after the `@` symbol (case-insensitive lookup).\n * @returns User record, or null if the name is not found.\n */\n resolveUser(name: string): { userId: string; name: string } | null;\n /**\n * Resolve a group mention token to the list of member user IDs.\n *\n * @param group - The well-known group name (e.g. `\"agent\"`, `\"all\"`).\n * @returns Array of member user IDs belonging to the group.\n */\n resolveGroup(group: MentionGroup): string[];\n /** Return the IDs of users currently online (used by the `here` and `humans_here` groups). */\n getOnlineUserIds(): string[];\n}\n\n// ---------------------------------------------------------------------------\n// parseMentions\n// ---------------------------------------------------------------------------\n\nconst MENTION_RE = /@(\\w+)/g;\nconst MENTION_GROUP_SET: ReadonlySet<string> = new Set(MENTION_GROUPS);\n\n/**\n * Scan `text` for @token patterns and return resolved {@link Mention} objects.\n *\n * - Well-known group tokens (`agent`, `humans`, `humans_here`, `here`, `all`)\n * are resolved via {@link MentionResolver.resolveGroup}.\n * - All other tokens are resolved via {@link MentionResolver.resolveUser}.\n * - Tokens that cannot be resolved are silently ignored.\n * - Results are sorted by character offset ascending.\n *\n * @param text - Raw message text to scan for `@token` patterns.\n * @param resolver - Resolver that maps tokens to users and groups.\n * @returns Resolved mentions ordered by position in text.\n * @docLink packages/session/api-reference#mention-resolver\n */\nexport function parseMentions(text: string, resolver: MentionResolver): Mention[] {\n const mentions: Mention[] = [];\n\n for (const match of text.matchAll(MENTION_RE)) {\n const token = match[1]!;\n const offset = match.index!;\n const length = match[0].length; // includes the @\n\n if (MENTION_GROUP_SET.has(token)) {\n const group = token as MentionGroup;\n mentions.push({\n type: \"group\",\n group,\n resolved: resolver.resolveGroup(group),\n offset,\n length,\n });\n } else {\n const user = resolver.resolveUser(token);\n if (user) {\n mentions.push({\n type: \"user\",\n userId: user.userId,\n name: user.name,\n offset,\n length,\n });\n }\n }\n }\n\n // matchAll iterates left-to-right, so mentions are already offset-ascending.\n return mentions;\n}\n\n// ---------------------------------------------------------------------------\n// isMentioned\n// ---------------------------------------------------------------------------\n\n/**\n * Returns true if `userId` is directly mentioned or is a member of any\n * group mention's resolved list.\n *\n * @param userId - The user ID to check (e.g. from the auth context).\n * @param mentions - Parsed mentions from {@link parseMentions}.\n * @docLink packages/session/api-reference#mention-resolver\n */\nexport function isMentioned(userId: string, mentions: Mention[]): boolean {\n for (const m of mentions) {\n if (m.type === \"user\" && m.userId === userId) return true;\n if (m.type === \"group\" && m.resolved.includes(userId)) return true;\n if (m.type === \"custom\" && m.resolved.includes(userId)) return true;\n }\n return false;\n}\n\n// ---------------------------------------------------------------------------\n// isAddressedByKind\n// ---------------------------------------------------------------------------\n\n/**\n * True if any mention is a custom mention of the given kind.\n *\n * Consumers use this to check for platform-specific mention kinds (e.g.\n * `\"assistant\"`) that the SDK parser does not produce — only consumers\n * construct custom mentions.\n *\n * @param mentions - Mention list from the message or consumer-constructed.\n * @param kind - The consumer-defined kind string to match.\n */\nexport function isAddressedByKind(mentions: Mention[], kind: string): boolean {\n return mentions.some((m) => m.type === \"custom\" && m.kind === kind);\n}\n\n// ---------------------------------------------------------------------------\n// isAgentAddressed\n// ---------------------------------------------------------------------------\n\n/** Groups that include the agent in their resolved membership. */\nconst AGENT_GROUPS: ReadonlySet<MentionGroup> = new Set([\"agent\", \"here\", \"all\"]);\n\n/**\n * Returns true if the agent is addressed by any mention in the list.\n *\n * The groups `@agent`, `@here`, and `@all` address the agent. `@humans`\n * and `@humans_here` do not. Individual user mentions are also not matched\n * here — agent addressing is group-based.\n *\n * @param mentions - Parsed mentions from {@link parseMentions}.\n * @docLink packages/session/api-reference#mention-resolver\n */\nexport function isAgentAddressed(mentions: Mention[]): boolean {\n return mentions.some((m) => m.type === \"group\" && AGENT_GROUPS.has(m.group));\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../factory-assets/connectors/flow/engine/node-shape.ts"],"names":[],"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C7E,EAAC;AACL,EAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,IAAA,KAAS,OAAA,IAAW,IAAA,CAAK,IAAA,EAAM,KAAA,GAAQ,CAAA,MAAA,EAAS,IAAA,CAAK,IAAA,CAAK,KAAK,CAAA,CAAA,GAAK,MAAA;AACvF,EAAA,OAAO,KAAA,GAAQ,CAAC,KAAA,EAAO,GAAG,YAAY,CAAA,GAAI,YAAA;AAC5C;AAGO,SAAS,aAAa,IAAA,EAAyC;AACpE,EAAA,IAAI,IAAA,CAAK,QAAA,EAAU,KAAA,EAAO,OAAO,KAAK,QAAA,CAAS,KAAA;AAC/C,EAAA,OAAO,IAAA,CAAK,IAAA,EAAM,UAAA,IAAc,EAAC;AACnC;AAGO,SAAS,gBAAgB,IAAA,EAAoC;AAClE,EAAA,OAAO,KAAK,GAAA,EAAK,IAAA,KAAS,OAAA,GAAU,IAAA,CAAK,IAAI,WAAA,GAAc,MAAA;AAC7D;AAGO,SAAS,aAAa,IAAA,EAA+C;AAC1E,EAAA,OAAO,IAAA,CAAK,QAAA,IAAY,IAAA,CAAK,OAAA,IAAW,EAAC;AAC3C","file":"chunk-DZM33LQO.js","sourcesContent":["import type { FlowDefinition, FlowNode } from \"./types.js\";\n\n/** Returns whether a node is executable by the currently active agent-turn runtime. */\nexport function isAgentNode(node: FlowNode): boolean {\n return node.type === \"skill\" || node.run?.kind === \"agent\";\n}\n\n/** Returns the node's optional policy across strict v2 and legacy definitions. */\nexport function nodeIsOptional(node: FlowNode): boolean {\n return node.control?.optional ?? node.data?.optional ?? false;\n}\n\n/** Returns the node's mandatory approval policy across strict v2 and legacy definitions. */\nexport function nodeRequiresApproval(node: FlowNode): boolean {\n return node.gate?.approval === \"mandatory\" || node.data?.approval?.mandatory === true;\n}\n\n/** Returns the first declared skill requirement without making it the node identity. */\nexport function nodeSkillId(node: FlowNode): string {\n if (node.type === \"skill\") return node.data?.skill ?? node.id;\n const skillAsset = node.run?.assets?.find((asset) => asset.startsWith(\"skill:\"));\n return skillAsset?.slice(\"skill:\".length).replace(/#.*$/, \"\") ?? node.id;\n}\n\n/** Returns the user-facing node label across strict v2 and legacy definitions. */\nexport function nodeLabel(node: FlowNode): string {\n return node.label ?? node.data?.label ?? nodeSkillId(node);\n}\n\n/** Returns strict v2 run assets or the equivalent legacy declarations. */\nexport function nodeAssets(node: FlowNode): string[] {\n if (node.run?.assets) return node.run.assets;\n const legacyAssets = Array.isArray(node.data?.assets)\n ? node.data.assets.filter((asset): asset is string => typeof asset === \"string\")\n : [];\n const skill = node.type === \"skill\" && node.data?.skill ? `skill:${node.data.skill}` : undefined;\n return skill ? [skill, ...legacyAssets] : legacyAssets;\n}\n\n/** Returns the binding values already supplied at the node boundary. */\nexport function nodeBindings(node: FlowNode): Record<string, unknown> {\n if (node.contract?.input) return node.contract.input;\n return node.data?.parameters ?? {};\n}\n\n/** Returns the first-class instruction for a strict v2 agent node. */\nexport function nodeInstruction(node: FlowNode): string | undefined {\n return node.run?.kind === \"agent\" ? node.run.instruction : undefined;\n}\n\n/** Returns run-scoped defaults across strict v2 and legacy definitions. */\nexport function flowDefaults(flow: FlowDefinition): Record<string, unknown> {\n return flow.defaults ?? flow.globals ?? {};\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../factory-assets/connectors/flow/prompt-fragments.ts"],"names":[],"mappings":";;;AAyDO,SAAS,qBAAqB,QAAA,EAAgC;AACnE,EAAA,QAAQ,SAAS,IAAA;AAAM,IACrB,KAAK,cAAA;AACH,MAAA,OAAO,iKAAA;AAAA,IACT,KAAK,mBAAA,EAAqB;AACxB,MAAA,MAAM,EAAE,MAAA,EAAQ,QAAA,EAAU,SAAA,EAAW,UAAS,GAAI,QAAA;AAClD,MAAA,IAAI,aAAa,UAAA,EAAY;AAC3B,QAAA,OAAO,CAAA,OAAA,EAAU,MAAM,CAAA,uBAAA,EAA0B,SAAS,CAAA,yGAAA,CAAA;AAAA,MAC5D;AACA,MAAA,MAAM,EAAA,GAAK,QAA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EAAE,CAAA,EAAA,EAAK,QAAQ,OAAO,CAAA;;AAAA;;AAAA;AAAA;AAAA,EAMlF,QAAQ;;AAAA;;AAAA;;AAAA,EAMR,YAAY;;AAAA,EAEZ,cAAc,CAAA;;AAAA,EAEd,iBAAiB;;AAAA;;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CAAA;AA0BnB;AAUO,SAAS,iBAAiB,QAAA,EAAgC;AAC/D,EAAA,QAAQ,SAAS,IAAA;AAAM,IACrB,KAAK,cAAA;AACH,MAAA,OAAO,cAAA;AAAA,IACT,KAAK,mBAAA;AACH,MAAA,OAAO,CAAA,kBAAA,EAAqB,QAAA,CAAS,MAAM,CAAA,CAAA,EAAI,SAAS,QAAQ,CAAA,CAAA;AAAA,IAClE,KAAK,gBAAA;AACH,MAAA,OAAO,CAAA,eAAA,EAAkB,SAAS,MAAM,CAAA,CAAA;AAAA,IAC1C,KAAK,iBAAA;AACH,MAAA,OAAO,CAAA,gBAAA,EAAmB,SAAS,MAAM,CAAA,CAAA;AAAA,IAC3C,KAAK,cAAA;AACH,MAAA,OAAO,CAAA,aAAA,EAAgB,SAAS,QAAQ,CAAA,CAAA;AAAA,IAC1C,KAAK,2BAAA;AACH,MAAA,OAAO,2BAAA;AAAA,IACT,KAAK,WAAA;AACH,MAAA,OAAO,WAAA;AAAA,IACT,KAAK,eAAA;AACH,MAAA,OAAO,eAAA;AAAA;AAEb","file":"chunk-FB4GPWYC.js","sourcesContent":["/**\n * Prompt fragments for the flow connector.\n *\n * Pure functions that translate a {@link TurnStimulus} into the strings the\n * runner's flow orchestrator splices into the per-turn agent prompt.\n * Extracted from `runner/src/flow-orchestrator.ts` in Phase 3 of the\n * flow-connector extraction (2026-05-08) so the connector owns its\n * prompt-rendering surface without a runtime dep on the orchestrator.\n *\n * The contract is byte-identical to the previous inline implementation —\n * any divergence is a regression.\n *\n * @docLink packages/factory-assets/flow#prompt-fragments\n */\n\nimport type { FlowExecution } from \"@skaile/workspaces/types\";\nimport type { FlowDefinition } from \"./engine/types.js\";\nimport {\n flowDefaults,\n isAgentNode,\n nodeIsOptional,\n nodeLabel,\n nodeRequiresApproval,\n} from \"./engine/node-shape.js\";\n\n/**\n * Reasons why a new turn is starting. The flow orchestrator's prompt template\n * renders a stimulus-specific paragraph (via {@link renderStimulusPrompt}) so\n * the agent knows exactly why it has been invoked.\n *\n * @docLink packages/factory-assets/flow#turn-stimulus\n */\nexport type TurnStimulus =\n | { kind: \"flow_started\" }\n | {\n kind: \"approval_received\";\n nodeId: string;\n decision: \"approved\" | \"rejected\";\n feedback?: string;\n decidedBy: string;\n }\n | { kind: \"input_received\"; nodeId: string; response: unknown; providedBy: string }\n | { kind: \"retry_requested\"; nodeId: string; requestedBy: string }\n | { kind: \"user_message\"; text: string; senderId: string }\n | { kind: \"resumed_after_hibernation\" }\n | { kind: \"cancelled\" }\n | { kind: \"state_changed\" };\n\n/**\n * Render the stimulus paragraph the agent sees at turn start.\n *\n * The output is a single paragraph (one or more sentences, no surrounding\n * whitespace) describing why the runner has woken the agent. Spliced into\n * the orchestrator prompt under the `## Why this turn is happening` heading.\n *\n * @docLink packages/factory-assets/flow#render-stimulus-prompt\n */\nexport function renderStimulusPrompt(stimulus: TurnStimulus): string {\n switch (stimulus.kind) {\n case \"flow_started\":\n return \"The user just started this flow. Begin with the first available node — call `get_available`, then `build_handoff` for your chosen node, then `start_node`.\";\n case \"approval_received\": {\n const { nodeId, decision, decidedBy, feedback } = stimulus;\n if (decision === \"approved\") {\n return `Node \\`${nodeId}\\` was **approved** by ${decidedBy}. Call \\`complete_node\\` for this node with the approved output, then advance to the next available node.`;\n }\n const fb = feedback ? ` Feedback: \"${feedback}\".` : \"\";\n return `Node \\`${nodeId}\\` was **rejected** by ${decidedBy}.${fb} Decide how to proceed: retry the node (the engine returned it to \\`available\\`), ask clarifying questions via \\`request_input\\`, or call \\`fail_node(..., recoverable: false)\\` if the issue cannot be addressed.`;\n }\n case \"input_received\":\n return `The user just provided input for node \\`${stimulus.nodeId}\\` (provided by ${stimulus.providedBy}). The node has returned to its prior status. Continue executing the node with this input.`;\n case \"retry_requested\":\n return `A user requested a retry of node \\`${stimulus.nodeId}\\` (requested by ${stimulus.requestedBy}). The node has been returned to \\`available\\` with its prior error preserved in history. Start a fresh attempt — review the error context if relevant and try a different approach.`;\n case \"user_message\":\n return `A user sent a message: \"${stimulus.text}\" (from ${stimulus.senderId}). You can respond directly without touching the flow, continue flow work, or both. If the message is a question about the flow, answer it; if it signals a new direction, consider whether to pause.`;\n case \"resumed_after_hibernation\":\n return \"This session was hibernated and has just resumed. Review the current state above and continue where you left off. No state was lost.\";\n case \"cancelled\":\n return \"The user has cancelled this flow. Wrap up cleanly: do not start any new nodes. You may record a short summary if relevant, then stop.\";\n case \"state_changed\":\n return \"The flow state changed. Review the current state above and continue work accordingly.\";\n }\n}\n\n/**\n * Build the full agent-orchestrator prompt for a flow turn.\n *\n * Reassembles the five-section prompt from the current FlowExecution snapshot\n * and the supplied stimulus:\n *\n * 1. Flow definition (markdown table of nodes)\n * 2. Current state (progress, available/blocked, interaction pointers)\n * 3. Why this turn is happening (stimulus-specific paragraph)\n * 4. Flow tools available (static documentation)\n * 5. Rules\n *\n * Originally a byte-identical lift of the (since-deleted)\n * `FlowOrchestrator.buildOrchestratorPrompt`; the contract now is simply\n * this function's own output. When strict v2 defaults or legacy globals are\n * non-empty, a `## Flow globals` section exposes those run-scoped values. The\n * flow-wide node table stays bounded to selection metadata; `build_handoff`\n * supplies the selected agent node's execution payload.\n * Pure — depends only on its inputs.\n *\n * @docLink packages/factory-assets/flow#build-orchestrator-prompt\n * @since 2.2.0\n */\nexport function buildOrchestratorPrompt(\n flowDef: FlowDefinition,\n state: FlowExecution,\n stimulus: TurnStimulus,\n): string {\n const agentNodes = flowDef.nodes.filter(isAgentNode);\n\n // ── Section 1: definition table ──\n const nodeRows = agentNodes\n .map((n) => {\n const deps =\n flowDef.edges\n .filter((e) => e.target === n.id && e.type === \"flow\")\n .map((e) => e.source)\n .join(\", \") || \"—\";\n const required = nodeIsOptional(n) ? \"optional\" : \"required\";\n const gate = nodeRequiresApproval(n) ? \"mandatory\" : \"—\";\n const nodeState = state.nodes[n.id];\n const status = nodeState?.status ?? \"not_started\";\n const description = (n.description ?? n.data?.description ?? \"—\")\n .replace(/\\s+/g, \" \")\n .replaceAll(\"|\", \"\\\\|\");\n return `| ${n.id} | ${nodeLabel(n)} | ${description} | ${required} | ${gate} | ${status} | ${deps} |`;\n })\n .join(\"\\n\");\n\n // ── Section 2: current state summary ──\n const nodesByStatus = (s: string) =>\n Object.values(state.nodes)\n .filter((n) => n.status === s)\n .map((n) => n.id);\n const available = nodesByStatus(\"available\");\n const awaitingApproval = nodesByStatus(\"awaiting_approval\");\n const awaitingInput = nodesByStatus(\"awaiting_input\");\n const running = nodesByStatus(\"running\");\n const failed = nodesByStatus(\"failed\");\n const completed = nodesByStatus(\"complete\");\n const totalRequired = agentNodes.filter((n) => !nodeIsOptional(n)).length;\n\n const stateSummary = [\n `- Run ID: ${state.runId}`,\n `- Status: ${state.status}`,\n `- Autonomous mode: ${state.autonomousMode}`,\n `- Progress: ${completed.length} / ${totalRequired} required nodes complete`,\n `- Available now: ${available.join(\", \") || \"(none)\"}`,\n `- Currently running: ${running.join(\", \") || \"(none)\"}`,\n `- Awaiting approval: ${awaitingApproval.join(\", \") || \"(none)\"}`,\n `- Awaiting input: ${awaitingInput.join(\", \") || \"(none)\"}`,\n `- Failed: ${failed.join(\", \") || \"(none)\"}`,\n ].join(\"\\n\");\n\n // ── Section 2b: flow globals (additive — omitted entirely when empty so\n // flows without globals keep the byte-identical Phase 3 prompt) ──\n const globals = flowDefaults(flowDef);\n const globalsSection =\n Object.keys(globals).length > 0\n ? `## Flow globals\n\nRun-scoped parameters set by the flow author or by the host that started this run. When \\`run_input\\` is present it carries the payload this run was started with (e.g. a scheduled or webhook-triggered run) — treat it as the run's initial input instead of asking the user for it.\n\n\\`\\`\\`json\n${JSON.stringify(globals, null, 2)}\n\\`\\`\\`\n\n`\n : \"\";\n\n // ── Section 3: stimulus paragraph ──\n const stimulusParagraph = renderStimulusPrompt(stimulus);\n\n // ── Section 4+5: static tool surface and rules ──\n return `# Flow Execution Context\n\nYou are orchestrating the flow **${flowDef.name}** (${flowDef.id} v${flowDef.version}). This is a governed flow execution: your job is to run nodes through the flow tools, summarize their outputs for human review, and yield control at approval gates.\n\n## Flow definition\n\n| ID | Label | Description | Required | Gate | Status | Depends on |\n|----|-------|-------------|----------|------|--------|------------|\n${nodeRows}\n\nNodes with **Gate = mandatory** are hard approval gates: they always require \\`request_approval\\` and a human decision, even when autonomous mode is on. They cannot be skipped — \\`request_approval\\` → approval is their only completion path.\n\n## Current state\n\n${stateSummary}\n\n${globalsSection}## Why this turn is happening\n\n${stimulusParagraph}\n\n## Flow tools available\n\nAll tools are exposed by the \\`flow\\` connector:\n\n- \\`get_available()\\` — list node IDs that are ready to start\n- \\`get_state()\\` — full current state including approvals, inputs, outputs\n- \\`get_globals()\\` — the flow's run-scoped globals (e.g. the \\`run_input\\` payload for scheduled/params-bound runs)\n- \\`build_handoff(nodeId)\\` — selected node instruction, supplied bindings, required assets, and upstream context\n- \\`start_node(nodeId)\\` — transition \\`available\\` → \\`running\\`; call before executing the agent node\n- \\`request_approval(nodeId, summary, artifacts)\\` — transition \\`running\\` → \\`awaiting_approval\\`. **This ends your turn.**\n- \\`request_input(nodeId, prompt, schema)\\` — transition to \\`awaiting_input\\`. **This ends your turn.** Legal from \\`available\\`, \\`running\\`, or \\`awaiting_approval\\`.\n- \\`complete_node(nodeId, output)\\` — transition to \\`complete\\`. Valid only if the node was approved, OR autonomousMode is true and the node is not a mandatory gate.\n- \\`fail_node(nodeId, message, recoverable)\\` — transition to \\`failed\\`. \\`recoverable=true\\` returns the node to \\`available\\`.\n- \\`skip_node(nodeId)\\` — transition to \\`skipped\\`. Only valid for optional nodes.\n\n## Rules\n\n1. Before executing an agent node, call \\`build_handoff(nodeId)\\` and follow its instruction with the supplied bindings, assets, and upstream context; then call \\`start_node(nodeId)\\`.\n2. After executing the node, call \\`request_approval\\` unless \\`autonomousMode\\` is true — in which case call \\`complete_node\\` directly. Exception: nodes marked **Gate = mandatory** always require \\`request_approval\\` and a human decision, even in autonomous mode.\n3. If you need information from the user before or during execution, call \\`request_input\\`. This ends your turn until the user responds.\n4. On unrecoverable failure, call \\`fail_node(..., recoverable: false)\\`. On recoverable failure, call \\`fail_node(..., recoverable: true)\\` and the engine returns the node to \\`available\\`.\n5. When all required nodes are \\`complete\\` or \\`skipped\\`, stop. The runner marks the flow done automatically.\n6. Free-chat user messages do not require flow action. Respond directly, continue flow work, or both — your call.\n`;\n}\n\n/**\n * Single-line tag suitable for telemetry / logging. Derives a short, stable\n * summary of a stimulus that's safe to attach to spans, log entries, and\n * trace events. The kind is always included; node-specific stimuli also\n * include their `nodeId` so log queries can pivot on it.\n *\n * @docLink packages/factory-assets/flow#describe-stimulus\n */\nexport function describeStimulus(stimulus: TurnStimulus): string {\n switch (stimulus.kind) {\n case \"flow_started\":\n return \"flow_started\";\n case \"approval_received\":\n return `approval_received:${stimulus.nodeId}:${stimulus.decision}`;\n case \"input_received\":\n return `input_received:${stimulus.nodeId}`;\n case \"retry_requested\":\n return `retry_requested:${stimulus.nodeId}`;\n case \"user_message\":\n return `user_message:${stimulus.senderId}`;\n case \"resumed_after_hibernation\":\n return \"resumed_after_hibernation\";\n case \"cancelled\":\n return \"cancelled\";\n case \"state_changed\":\n return \"state_changed\";\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../factory-assets/connectors/flow/run-flow.ts"],"names":["c"],"mappings":";;;;;;;;;;;;;AAyDA,IAAI,aAAA;AAEJ,eAAe,gBAAA,GAAiC;AAC9C,EAAA,IAAI,eAAe,OAAO,aAAA;AAC1B,EAAA,aAAA,GAAgB,MAAM,OAAO,mBAA2B,CAA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.ts` to `factory-assets/connectors/flow/run-flow.ts`\n * in Phase 3 of the flow-connector extraction (2026-05-08). Behaviour is\n * byte-identical to the previous runner-side implementation; only the log\n * source changes from `runner:flow:<runId>` to `flow-connector:run:<runId>`.\n *\n * The runner re-exports these symbols with a deprecation warning for one\n * release. CLI consumers should switch to\n * `import { runFlow, resumeFlow } from \"@skaile/workspaces/factory-assets/connectors/flow/run-flow\"`.\n *\n * Internal runner helpers (FlowOrchestrator, bootstrapRunnerLogStore,\n * createAgentSession, resolveDriverPaths, session helpers) are loaded lazily\n * via dynamic `await import(\"@skaile/workspaces/runner\")` inside\n * `loadRunnerModule()` below. The lazy load avoids a static package-level\n * cycle (runner → connectors → factory-assets → runner) — the cycle exists at\n * the workspace level but never resolves at module-load time because\n * factory-assets only ever calls `import` from inside an async function body.\n * The string-literal specifier preserves `bun --compile` and tsup static\n * analysis.\n */\n\nimport fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { AgentEvent } from \"@skaile/workspaces/bridge\";\nimport {\n resolveAgentDir,\n resolveSettings,\n resolveSkWorkspaceConfig,\n} from \"@skaile/workspaces/core\";\nimport { createLogger } from \"@skaile/workspaces/core/logging\";\nimport { parseSkillFrontmatter, validateFlowVersions } from \"@skaile/workspaces/resolver\";\nimport { initTelemetry } from \"@skaile/workspaces/telemetry\";\nimport type { FlowExecution } from \"@skaile/workspaces/types\";\nimport * as z from \"zod\";\nimport { FlowAdapter } from \"./adapter.js\";\nimport { loadFlow } from \"./engine/index.js\";\nimport { nodeAssets } from \"./engine/node-shape.js\";\nimport {\n buildOrchestratorPrompt,\n renderStimulusPrompt,\n type TurnStimulus,\n} from \"./prompt-fragments.js\";\n\n/**\n * Lazy `import(\"@skaile/workspaces/runner\")` accessor. Cached on first call so\n * subsequent `runFlow` invocations don't re-evaluate the runner module.\n *\n * Dynamic ESM import is used (not `require`) so vitest and other ESM\n * bundlers honour their alias resolution — `require` would side-step the\n * configured aliases and pick up two distinct module instances when run\n * under vitest. The string-literal specifier ensures bun --compile keeps\n * the dependency (per the static-import-or-die rule in\n * connectors/CLAUDE.md).\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet _runnerModule: any | undefined;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nasync function loadRunnerModule(): Promise<any> {\n if (_runnerModule) return _runnerModule;\n _runnerModule = await import(\"@skaile/workspaces/runner\");\n return _runnerModule;\n}\n\n/** Type-only re-export of SessionState so the runner tombstone shim still works. */\nexport type SessionState = import(\"@skaile/workspaces/runner\").SessionState;\n\n/** Maximum agent session duration (4 hours). Configurable via {@link RunOptions.sessionTimeoutMs}. */\nconst DEFAULT_SESSION_TIMEOUT_MS = 4 * 60 * 60 * 1000; // 4 hours\n\nconst FLOW_AGENT_OPERATION_NAMES = new Set([\n \"get_available\",\n \"get_state\",\n \"get_globals\",\n \"build_handoff\",\n \"validate_node\",\n \"start_node\",\n \"request_approval\",\n \"request_input\",\n \"complete_node\",\n \"skip_node\",\n \"fail_node\",\n]);\n\n/**\n * Options for {@link runFlow}.\n *\n * Wraps `FlowOrchestrator` with autonomous mode turned on by default so\n * interactive approval/input gates don't block a terminal run.\n *\n * @docLink packages/factory-assets/flow#run-flow\n */\nexport interface RunOptions {\n /** The working directory for the project being orchestrated. */\n projectDir: string;\n /** Absolute path to the `.flow.yaml` or `.flow.json` definition file. */\n flowPath: string;\n /**\n * Directory containing `agent.yaml`, `SOUL.md`, `RULES.md`, `knowledge/`.\n * Resolved from `skaile.yaml` via `resolveAgentDir` when absent.\n */\n agentDir?: string;\n /**\n * Agent driver backend. Defaults to `settings.driver` (`\"omp\"` or `\"claude-sdk\"`).\n */\n driver?: string;\n /**\n * LLM provider override (e.g. `\"anthropic\"`, `\"openrouter\"`).\n * Falls back to `settings.provider` when absent.\n */\n provider?: string;\n /**\n * Model name override. Falls back to `settings.model` when absent.\n */\n model?: string;\n /**\n * Path to a specific `settings.json` to load instead of the default\n * layered resolution chain (project → parent → global → built-in defaults).\n */\n settingsFile?: string;\n /**\n * When `true`, prints the initial flow state without starting the agent\n * and returns immediately.\n */\n dryRun?: boolean;\n /**\n * Per-session timeout in milliseconds. Defaults to\n * {@link DEFAULT_SESSION_TIMEOUT_MS} (4 hours).\n */\n sessionTimeoutMs?: number;\n /** Optional human-readable label shown in the session list. */\n sessionLabel?: string;\n /** Autonomous mode for CLI runs — defaults to true so interactive approval gates are skipped. */\n autonomousMode?: boolean;\n /**\n * Called for each {@link AgentEvent} emitted during the run\n * (e.g. `text`, `tool_call`, `state_changed`).\n */\n onEvent?: (event: AgentEvent) => void;\n /**\n * Called for each diagnostic log line. Defaults to `process.stdout`.\n */\n onLog?: (line: string) => void;\n}\n\n/**\n * Options for resuming an existing CLI session.\n *\n * Reconnects the driver's conversation thread (conversation history is\n * preserved via the stored `driverSessionId`) but restarts flow execution\n * from scratch — flow state is not persisted in CLI mode. For governed,\n * resumable flow runs use a host that persists flow state (e.g. the Skaile\n * platform).\n *\n * @docLink packages/factory-assets/flow#resume-flow\n */\nexport interface ResumeOptions {\n /** The working directory for the project being orchestrated. */\n projectDir: string;\n /**\n * Specific run ID to resume. When absent, the current session pointer\n * at `<projectDir>/.skaile/current` is used.\n */\n sessionId?: string;\n /**\n * Agent definition directory override. Defaults to the directory stored\n * in the session file.\n */\n agentDir?: string;\n /**\n * When `true`, prints the initial flow state without starting the agent\n * and returns immediately.\n */\n dryRun?: boolean;\n /**\n * Per-session timeout in milliseconds. Defaults to\n * {@link DEFAULT_SESSION_TIMEOUT_MS} (4 hours).\n */\n sessionTimeoutMs?: number;\n /**\n * Called for each {@link AgentEvent} emitted during the run.\n */\n onEvent?: RunOptions[\"onEvent\"];\n /**\n * Called for each diagnostic log line. Defaults to `process.stdout`.\n */\n onLog?: RunOptions[\"onLog\"];\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Start a new flow session from the CLI.\n *\n * Wraps `FlowOrchestrator` with autonomous mode turned on by default so\n * interactive approval/input gates don't block a terminal run. The\n * runner remains idle between turns — for the CLI use case, a single\n * turn should carry the flow to completion in autonomous mode. Non-CLI\n * hosts (Skaile platform, Pichi) use the orchestrator directly via the\n * serve command surface and drive gates through user actions.\n *\n * @docLink packages/factory-assets/flow#run-flow\n */\nexport async function runFlow(opts: RunOptions): Promise<void> {\n const runner = await loadRunnerModule();\n const {\n bootstrapRunnerLogStore,\n bootstrapCapabilityRegistry,\n CapabilityRegistry,\n createAgentSession,\n createSessionStimulusBus,\n defineCapability,\n registerCompositionCapabilities,\n resolveDriverPaths,\n newSession,\n saveSession,\n touchSession,\n } = runner;\n\n const flow = loadFlow(opts.flowPath);\n const agentDir = opts.agentDir ?? resolveAgentDir(opts.projectDir);\n const settings = await resolveSettings(opts.projectDir, {\n driver: opts.driver,\n provider: opts.provider,\n model: opts.model,\n });\n\n const session = newSession({\n flowId: flow.id,\n projectDir: opts.projectDir,\n agentDir,\n driver: settings.driver ?? \"omp\",\n provider: settings.provider,\n model: settings.model,\n label: opts.sessionLabel,\n });\n\n await saveSession(opts.projectDir, session);\n\n // Bootstrap structured logging — registers a process-singleton LogStore.\n // OnLogBridgeSink mirrors entries to opts.onLog when caller provides one,\n // preserving back-compat with CLI hosts that consume plain text lines.\n const wsConfigEarly = resolveSkWorkspaceConfig(opts.projectDir);\n const { dispose: disposeLogStore } = bootstrapRunnerLogStore({\n sessionId: session.runId,\n projectDir: opts.projectDir,\n yamlBlock: (wsConfigEarly as { logging?: unknown }).logging,\n onLog: opts.onLog,\n });\n const flowLog = createLogger({\n kind: \"flow-connector\",\n subkind: \"run\",\n instance: session.runId,\n });\n const log = (line: string) => flowLog.info(line);\n const capabilityRegistry = new CapabilityRegistry();\n bootstrapCapabilityRegistry(capabilityRegistry);\n const capabilityHooks = {\n sessionId: session.runId,\n composeTools: () => capabilityRegistry.composeLLMTools(),\n resolve: (name: string) =>\n capabilityRegistry.list().find((cap: { name: string }) => cap.name === name) ?? null,\n invoke: (name: string, input: unknown) =>\n capabilityRegistry.invoke(name, input, { sessionId: session.runId }),\n };\n\n try {\n // ── Dry run ────────────────────────────────────────────────────────────\n if (opts.dryRun) {\n const adapter = new FlowAdapter();\n const handle = await adapter.connect(\n {\n id: \"flow\",\n driver: \"flow\",\n access: \"read-only\" as const,\n options: { flow, seed: { runId: session.runId, startedBy: \"cli\" } },\n },\n {}, // flow needs no connect context\n );\n const state = adapter.getExecution(handle);\n const available = Object.values(state.nodes)\n .filter((n) => n.status === \"available\")\n .map((n) => n.id);\n log(`[dry-run] Flow: ${flow.name} (${flow.id})`);\n log(`[dry-run] Available: ${available.join(\", \") || \"(none)\"}`);\n await adapter.disconnect(handle);\n return;\n }\n\n await validatePinnedVersions(flow, opts.projectDir, log);\n\n // ── Telemetry initialization ────────────────────────────────────────────\n const wsConfig = wsConfigEarly;\n const telemetry = await initTelemetry(wsConfig.telemetry);\n const flowTrace = telemetry.startTrace({\n name: `flow:${flow.id}`,\n kind: \"flow_run\",\n attributes: {\n \"skaile.flow.id\": flow.id,\n \"skaile.flow.run_id\": session.runId,\n },\n });\n\n // ── Agent session setup ─────────────────────────────────────────────────\n const driverPaths = resolveDriverPaths(settings);\n const agentSession = await createAgentSession({\n projectDir: opts.projectDir,\n agentDir: session.agentDir,\n driver: session.driver,\n model: session.model,\n provider: session.provider,\n resumeSessionId: session.driverSessionId,\n projectClaudeMd: path.join(opts.projectDir, \"CLAUDE.md\"),\n promptsDir: path.join(opts.projectDir, driverPaths.promptsDir),\n sessionId: session.runId,\n onLog: log,\n telemetry,\n trace: flowTrace,\n wsConfig,\n capabilities: capabilityHooks,\n capabilityRegistry,\n });\n if (agentSession.composition?.discoverableEntries.length) {\n registerCompositionCapabilities(\n capabilityRegistry,\n agentSession.composition.discoverableEntries,\n );\n }\n const { driver } = agentSession;\n const updatedSession = { ...session };\n\n // Track driver session ID so future resumes can reconnect the SDK thread.\n driver.on(\"agent-event\", () => {\n const runtimeSessionId = driver.runtimeSessionId;\n if (!runtimeSessionId || runtimeSessionId === updatedSession.driverSessionId) return;\n updatedSession.driverSessionId = runtimeSessionId;\n void saveSession(opts.projectDir, updatedSession).catch(() => {});\n });\n\n // ── FlowAdapter + stimulus bus ─────────────────────────────────────────\n //\n // Phase 4 of the flow-connector extraction: SessionStimulusBus is the sole\n // turn driver. The legacy FlowOrchestrator + onStateChange subscription\n // are gone — every turn is initiated either by the bus (after an adapter\n // mutation observed via `useBusForStimulus: true`) or by an explicit\n // `bus.signal()` call from this function (the initial flow_started turn).\n //\n // The bus's `driveTurn` callback receives the stimulus paragraph the\n // adapter rendered (not the full orchestrator prompt). It rebuilds the\n // five-section orchestrator prompt around that fragment using\n // `buildOrchestratorPrompt` so the agent sees the same flow context the\n // legacy orchestrator produced.\n const flowConnectorId = \"flow\";\n const turnTimeoutMs = opts.sessionTimeoutMs ?? DEFAULT_SESSION_TIMEOUT_MS;\n\n // Forward declaration so `driveTurn` can read the live execution\n // snapshot. Assigned just below, before the bus can fire.\n let flowAdapterRef: FlowAdapter | null = null;\n let flowHandleRef: import(\"@skaile/workspaces/connectors\").ConnectorHandle | null = null;\n\n const stimulusBus = createSessionStimulusBus({\n driveTurn: async (\n promptFragment: string,\n metas: Array<Record<string, unknown>>,\n ): Promise<void> => {\n // The adapter signal carries `meta.kind` per stimulus. Use that to\n // reconstruct the typed `TurnStimulus`; for compound batches, fall\n // back to `state_changed` (the union element that means \"look at\n // current state and continue\").\n const lastKind = metas[metas.length - 1]?.kind;\n let stimulus: TurnStimulus;\n if (lastKind === \"flow_started\") {\n stimulus = { kind: \"flow_started\" };\n } else if (\n lastKind === \"user_message\" &&\n typeof metas[metas.length - 1]?.text === \"string\"\n ) {\n const meta = metas[metas.length - 1] as Record<string, unknown>;\n stimulus = {\n kind: \"user_message\",\n text: String(meta.text ?? \"\"),\n senderId: String(meta.senderId ?? \"user\"),\n };\n } else {\n stimulus = { kind: \"state_changed\" };\n }\n // The fragment passed in by the bus is the adapter's\n // `renderStimulusPrompt(stim)` joined across coalesced signals.\n // For the initial / explicit-stimulus path, we build the full prompt\n // around the fragment via `buildOrchestratorPrompt`. The fragment is\n // discarded in favour of the structured stimulus to keep the prompt\n // shape stable; the structured form already contains everything the\n // fragment encoded.\n void promptFragment;\n if (!flowAdapterRef || !flowHandleRef) {\n throw new Error(\"driveTurn fired before FlowAdapter was wired\");\n }\n const fullPrompt = buildOrchestratorPrompt(\n flow,\n flowAdapterRef.getExecution(flowHandleRef),\n stimulus,\n );\n await awaitAgentEnd(driver, fullPrompt, opts.onEvent, turnTimeoutMs);\n },\n log: flowLog,\n });\n\n const flowAdapter = new FlowAdapter();\n const flowHandle = await flowAdapter.connect(\n {\n id: flowConnectorId,\n driver: \"flow\",\n access: \"read-write\" as const,\n options: {\n flow,\n seed: {\n runId: session.runId,\n startedBy: \"cli\",\n autonomousMode: opts.autonomousMode ?? true,\n },\n stimulusBus,\n useBusForStimulus: true,\n },\n },\n {}, // flow needs no connect context\n );\n flowAdapterRef = flowAdapter;\n flowHandleRef = flowHandle;\n\n // Flow operations retain the connector's published bare protocol names;\n // this is the intentional exception to generic capability namespaces.\n for (const operation of flowAdapter.tools\n .describeOperations(flowHandle)\n .filter(({ name }) => FLOW_AGENT_OPERATION_NAMES.has(name))) {\n const shape: Record<string, z.ZodType> = {};\n for (const arg of operation.args) {\n let schema: z.ZodType;\n switch (arg.type) {\n case \"boolean\":\n schema = z.boolean();\n break;\n case \"number\":\n schema = z.number();\n break;\n case \"json\":\n schema = z.union([z.string(), z.record(z.string(), z.unknown()), z.array(z.unknown())]);\n break;\n default:\n schema = z.string();\n }\n shape[arg.name] = arg.required ? schema : schema.optional();\n }\n capabilityRegistry.register(\n defineCapability({\n name: operation.name,\n displayName: operation.name,\n description: operation.description,\n input: z.object(shape),\n side: \"agent\",\n origin: { kind: \"flow\", flowId: flow.id },\n scope: \"session\",\n audience: [\"llm\"],\n kind: operation.accessLevel === \"read\" ? \"query\" : \"effect\",\n handler: async (args: Record<string, unknown>) =>\n flowAdapter.executeOp(flowHandle, operation.name, args),\n }),\n \"agent\",\n );\n }\n\n // Forward state_changed events to the caller. The bus computes a\n // turn-kicking stimulus on each adapter mutation; the host-facing\n // event stream still observes the full snapshot via onChange.\n flowAdapter.onStateChange(flowHandle, (state: FlowExecution) => {\n opts.onEvent?.({\n type: \"state_changed\",\n store: `flow:${state.runId}`,\n state: state as unknown as Record<string, unknown>,\n } as unknown as AgentEvent);\n });\n\n // ── Execute ────────────────────────────────────────────────────────────\n flowLog.info(\"starting flow\", {\n flowId: flow.id,\n flowName: flow.name,\n runId: session.runId,\n });\n\n try {\n // Kick the initial flow_started turn explicitly. Subsequent turns are\n // driven by the bus signaling whenever the adapter mutates.\n const initialStimulus: TurnStimulus = { kind: \"flow_started\" };\n await stimulusBus.signal(flowConnectorId, {\n promptFragment: renderStimulusPrompt(initialStimulus),\n meta: { kind: initialStimulus.kind },\n });\n\n const finalState = flowAdapter.getExecution(flowHandle);\n if (finalState.done) {\n flowLog.info(\"flow complete\", { flowId: flow.id, flowName: flow.name });\n } else if (finalState.status === \"failed\") {\n flowLog.error(\"flow failed\", undefined, { flowId: flow.id, flowName: flow.name });\n } else {\n flowLog.warn(\"flow paused after one turn\", {\n flowId: flow.id,\n status: finalState.status,\n note: \"CLI mode does not interact with approval/input gates\",\n });\n }\n } finally {\n driver.kill();\n const lastState = flowAdapter.getExecution(flowHandle);\n await saveSession(\n opts.projectDir,\n touchSession({\n ...updatedSession,\n driverSessionId: driver.runtimeSessionId ?? updatedSession.driverSessionId,\n status: lastState.status === \"complete\" ? \"complete\" : \"paused\",\n }),\n ).catch(() => {});\n await flowAdapter.disconnect(flowHandle).catch(() => {});\n await agentSession.dispose();\n telemetry.endTrace(flowTrace, {\n status: flowAdapter.getExecution(flowHandle).status === \"complete\" ? \"ok\" : \"error\",\n });\n await telemetry.flush().catch(() => {});\n }\n } finally {\n disposeLogStore();\n }\n}\n\n/**\n * Resume an existing session from the CLI.\n *\n * With the Phase 2 turn-based model, flow state is NOT persisted to\n * local session files — only the driver session ID is kept. The CLI\n * can resume the agent's conversation thread, but the flow execution\n * itself starts from scratch because the runner has no durable store\n * for per-run state.\n *\n * For a governed, resumable flow run, use a host that persists flow\n * state (e.g. the Skaile platform). CLI resume is retained as a\n * driver-level convenience only: we load the session, restart the\n * flow, and the SDK will reconnect to the prior conversation thread.\n *\n * @docLink packages/factory-assets/flow#resume-flow\n */\nexport async function resumeFlow(opts: ResumeOptions): Promise<void> {\n const runner = await loadRunnerModule();\n const { loadSession, loadSessionById, bootstrapRunnerLogStore } = runner;\n\n const session = opts.sessionId\n ? await loadSessionById(opts.projectDir, opts.sessionId)\n : await loadSession(opts.projectDir);\n\n if (!session) {\n const hint = opts.sessionId\n ? `session ${opts.sessionId}`\n : `current session in ${opts.projectDir}/.skaile`;\n throw new Error(`No session found (${hint}) — run 'start' first`);\n }\n\n const flowPath = resolveFlowPath(session.flowId, opts.projectDir);\n\n // Bootstrap a transient logger for the resume diagnostics. The inner\n // runFlow() call will register its own LogStore for the new run. Keep\n // OnLogBridgeSink wiring so callers passing onLog still see this line.\n const wsConfigEarly = resolveSkWorkspaceConfig(opts.projectDir);\n const { dispose: disposeLogStore } = bootstrapRunnerLogStore({\n sessionId: session.runId,\n projectDir: opts.projectDir,\n yamlBlock: (wsConfigEarly as { logging?: unknown }).logging,\n onLog: opts.onLog,\n });\n const flowLog = createLogger({\n kind: \"flow-connector\",\n subkind: \"run\",\n instance: session.runId,\n });\n flowLog.info(\"resuming session\", {\n runId: session.runId,\n flowId: session.flowId,\n note: \"CLI mode does not persist flow state — flow restarts from scratch; driver thread resumes\",\n });\n\n try {\n await runFlow({\n projectDir: opts.projectDir,\n flowPath,\n agentDir: opts.agentDir ?? session.agentDir,\n driver: session.driver,\n model: session.model,\n provider: session.provider,\n sessionLabel: session.label,\n dryRun: opts.dryRun,\n sessionTimeoutMs: opts.sessionTimeoutMs,\n onEvent: opts.onEvent,\n onLog: opts.onLog,\n });\n } finally {\n disposeLogStore();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nasync function validatePinnedVersions(\n flow: Awaited<ReturnType<typeof loadFlow>>,\n projectDir: string,\n log: (line: string) => void,\n): Promise<void> {\n const pinnedNodes = flow.nodes.flatMap((node) => {\n const fromAssets = nodeAssets(node).flatMap((asset) => {\n if (!asset.startsWith(\"skill:\")) return [];\n const hashIndex = asset.lastIndexOf(\"#\");\n if (hashIndex <= \"skill:\".length || hashIndex === asset.length - 1) return [];\n const identity = asset.slice(\"skill:\".length, hashIndex);\n const skillId = identity.slice(identity.lastIndexOf(\"/\") + 1);\n return [\n {\n nodeId: node.id,\n skillId,\n requestedVersion: asset.slice(hashIndex + 1),\n },\n ];\n });\n if (fromAssets.length > 0) return fromAssets;\n if (node.type !== \"skill\" || !node.data?.version) return [];\n return [\n {\n nodeId: node.id,\n skillId: node.data.skill ?? node.id,\n requestedVersion: node.data.version,\n },\n ];\n });\n if (pinnedNodes.length === 0) return;\n\n const skillVersions = new Map<string, string>();\n const aiResourcesDir = findAiResourcesDir(projectDir);\n if (aiResourcesDir) {\n for (const node of pinnedNodes) {\n const skillId = node.skillId;\n if (skillVersions.has(skillId)) continue;\n const skillPath = findSkillMd(aiResourcesDir, skillId);\n if (skillPath) {\n const content = fs.readFileSync(skillPath, \"utf-8\");\n const fm = parseSkillFrontmatter(content);\n skillVersions.set(skillId, fm.metadata?.version ?? fm.version ?? \"\");\n }\n }\n }\n\n const checks = validateFlowVersions(pinnedNodes, skillVersions);\n const failures = checks.filter((c) => !c.satisfied);\n if (failures.length > 0) {\n const lines = failures.map(\n (f) => ` ${f.nodeId}: wants ${f.requested}, found ${f.actual || \"(none)\"}`,\n );\n throw new Error(`Skill version mismatch:\\n${lines.join(\"\\n\")}`);\n }\n for (const c of checks.filter((c) => c.satisfied)) {\n log(` Version OK: ${c.skillId} ${c.actual} satisfies ${c.requested}`);\n }\n}\n\nfunction resolveFlowPath(flowId: string, projectDir: string): string {\n const armInstalled = path.join(projectDir, \".skaile\", \"flows\", flowId, `${flowId}.flow.yaml`);\n if (fs.existsSync(armInstalled)) return armInstalled;\n\n const manual = path.join(projectDir, \".skaile\", \"flows\", `${flowId}.flow.yaml`);\n if (fs.existsSync(manual)) return manual;\n\n let dir = projectDir;\n for (let i = 0; i < 6; i++) {\n const aiResources = path.join(dir, \"ai-assets\");\n if (fs.existsSync(aiResources)) {\n for (const domain of fs.readdirSync(aiResources)) {\n const flowsDir = path.join(aiResources, domain, \"flows\");\n const candidate = path.join(flowsDir, `${flowId}.flow.yaml`);\n if (fs.existsSync(candidate)) return candidate;\n const legacy = path.join(flowsDir, `${flowId}.json`);\n if (fs.existsSync(legacy)) return legacy;\n }\n throw new Error(`Flow not found: ${flowId} (searched .skaile/flows/ and ${aiResources})`);\n }\n dir = path.dirname(dir);\n }\n throw new Error(\n `Flow not found: ${flowId} (no .skaile/flows/ entry and could not locate ai-assets from ${projectDir})`,\n );\n}\n\n/** Walk up from projectDir to find ai-assets/ */\nfunction findAiResourcesDir(projectDir: string): string | null {\n let dir = projectDir;\n for (let i = 0; i < 6; i++) {\n const candidate = path.join(dir, \"ai-assets\");\n if (fs.existsSync(candidate)) return candidate;\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return null;\n}\n\n/** Find SKILL.md for a given skill ID by walking ai-assets domains */\nfunction findSkillMd(aiResourcesDir: string, skillId: string): string | null {\n for (const domain of fs.readdirSync(aiResourcesDir, { withFileTypes: true })) {\n if (!domain.isDirectory()) continue;\n const skillsDir = path.join(aiResourcesDir, domain.name, \"skills\");\n if (!fs.existsSync(skillsDir)) continue;\n const found = walkForSkill(skillsDir, skillId);\n if (found) return found;\n }\n return null;\n}\n\n// ---------------------------------------------------------------------------\n// Turn-wait helper\n// ---------------------------------------------------------------------------\n\n/**\n * Minimal driver surface needed by the bus's `driveTurn` callback. Mirrors\n * the slice the legacy `FlowOrchestrator` consumed (`prompt` + `on` +\n * `removeAllListeners`) so we can keep the wait helper private to this\n * module without pulling in a runtime dep on `@skaile/workspaces/bridge`.\n */\ninterface TurnDriverSurface {\n prompt(message: string): Promise<void>;\n on(event: \"agent-event\", handler: (event: AgentEvent) => void): void;\n removeAllListeners(event: \"agent-event\"): void;\n}\n\n/**\n * Send a prompt to the driver and resolve when the agent emits\n * `agent_end` (or reject on `error`). Identical contract to the legacy\n * `awaitAgentEnd` helper from `flow-orchestrator.ts`. Phase 4 lifts the\n * helper into `run-flow.ts` because the bus now owns turn driving.\n */\nfunction awaitAgentEnd(\n driver: TurnDriverSurface,\n prompt: string,\n onEvent: ((event: AgentEvent) => void) | undefined,\n timeoutMs: number,\n): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n let settled = false;\n\n const done = (err?: Error) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n driver.removeAllListeners(\"agent-event\");\n if (err) reject(err);\n else resolve();\n };\n\n const timer = setTimeout(\n () => done(new Error(`Flow turn timed out after ${timeoutMs / 1000}s`)),\n timeoutMs,\n );\n\n driver.on(\"agent-event\", (event: AgentEvent) => {\n onEvent?.(event);\n if (event.type === \"agent_end\") done();\n else if (event.type === \"error\") {\n const msg =\n (event as { error?: string; message?: string }).error ??\n (event as { message?: string }).message ??\n \"Agent error\";\n done(new Error(msg));\n }\n });\n\n driver.prompt(prompt).catch(done);\n });\n}\n\nfunction walkForSkill(dir: string, skillId: string): string | null {\n for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {\n if (!entry.isDirectory()) continue;\n const full = path.join(dir, entry.name);\n const skillMd = path.join(full, \"SKILL.md\");\n if (fs.existsSync(skillMd)) {\n if (entry.name === skillId) return skillMd;\n } else {\n const found = walkForSkill(full, skillId);\n if (found) return found;\n }\n }\n return null;\n}\n"]}