@skaile/workspaces 0.22.0-beta.1 → 0.22.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 (164) hide show
  1. package/CHANGELOG.md +380 -0
  2. package/dist/{asset-feeds-QXCSAJRN.js → asset-feeds-Y2CDCM3W.js} +13 -14
  3. package/dist/asset-feeds-Y2CDCM3W.js.map +1 -0
  4. package/dist/asset-manager/index.js +7 -7
  5. package/dist/asset-manager/installer.js +6 -6
  6. package/dist/asset-manager/src/index.d.ts.map +1 -1
  7. package/dist/base-assets/connectors/deploy.js +7 -7
  8. package/dist/base-assets/connectors/devserver.js +7 -7
  9. package/dist/base-assets/connectors/flow/adapter.js +7 -7
  10. package/dist/base-assets/connectors/flow/run-flow.js +8 -8
  11. package/dist/base-assets/connectors/flow.js +7 -7
  12. package/dist/base-assets/connectors/git/driver.d.ts.map +1 -1
  13. package/dist/base-assets/connectors/git.js +7 -7
  14. package/dist/base-assets/connectors/gmail.js +7 -7
  15. package/dist/base-assets/connectors/googledrive.js +7 -7
  16. package/dist/base-assets/connectors/local.js +7 -7
  17. package/dist/base-assets/connectors/mattermost.js +7 -7
  18. package/dist/base-assets/connectors/memory.js +7 -7
  19. package/dist/base-assets/connectors/minio.js +7 -7
  20. package/dist/base-assets/connectors/postgres.js +7 -7
  21. package/dist/base-assets/connectors/s3.js +7 -7
  22. package/dist/base-assets/connectors/sharepoint.js +7 -7
  23. package/dist/base-assets/connectors/sqlite.js +7 -7
  24. package/dist/base-assets/connectors/static-server.js +7 -7
  25. package/dist/base-assets/connectors/tunnel.js +7 -7
  26. package/dist/base-assets/connectors/webdav.js +7 -7
  27. package/dist/base-assets/connectors/xstate-store.js +7 -7
  28. package/dist/base-assets/connectors/xstate.js +7 -7
  29. package/dist/{chunk-PTIHB2TV.js → chunk-2RYQERIT.js} +4 -4
  30. package/dist/{chunk-PTIHB2TV.js.map → chunk-2RYQERIT.js.map} +1 -1
  31. package/dist/chunk-32NA4TVC.js +30 -0
  32. package/dist/chunk-32NA4TVC.js.map +1 -0
  33. package/dist/{chunk-DKGDOALM.js → chunk-53UNDY6K.js} +5 -5
  34. package/dist/{chunk-DKGDOALM.js.map → chunk-53UNDY6K.js.map} +1 -1
  35. package/dist/{chunk-VCYXVP2S.js → chunk-7HSXUKNB.js} +24 -13
  36. package/dist/chunk-7HSXUKNB.js.map +1 -0
  37. package/dist/chunk-7QBNJTTQ.js +3 -0
  38. package/dist/{chunk-W2O5LWYU.js.map → chunk-7QBNJTTQ.js.map} +1 -1
  39. package/dist/{chunk-UMOENHVH.js → chunk-ETMUGBHF.js} +3 -3
  40. package/dist/{chunk-UMOENHVH.js.map → chunk-ETMUGBHF.js.map} +1 -1
  41. package/dist/{chunk-7PTP3SQJ.js → chunk-GTS2FODO.js} +32 -7
  42. package/dist/chunk-GTS2FODO.js.map +1 -0
  43. package/dist/{chunk-D7K72XEY.js → chunk-JN2CUVSU.js} +3 -3
  44. package/dist/{chunk-D7K72XEY.js.map → chunk-JN2CUVSU.js.map} +1 -1
  45. package/dist/{chunk-3ECS5PFD.js → chunk-K2HDYSAM.js} +4 -4
  46. package/dist/{chunk-3ECS5PFD.js.map → chunk-K2HDYSAM.js.map} +1 -1
  47. package/dist/{chunk-4AZKT2BU.js → chunk-K7WPR77X.js} +33 -50
  48. package/dist/chunk-K7WPR77X.js.map +1 -0
  49. package/dist/{chunk-JHF66MCK.js → chunk-MNAHNDUI.js} +5 -3
  50. package/dist/chunk-MNAHNDUI.js.map +1 -0
  51. package/dist/{chunk-APAOQLPT.js → chunk-NBJ5TOEC.js} +3 -3
  52. package/dist/{chunk-APAOQLPT.js.map → chunk-NBJ5TOEC.js.map} +1 -1
  53. package/dist/{chunk-NJLHHZIW.js → chunk-NDD5VMN5.js} +2 -2
  54. package/dist/{chunk-NJLHHZIW.js.map → chunk-NDD5VMN5.js.map} +1 -1
  55. package/dist/{chunk-LT4DLEYE.js → chunk-OJN25VJO.js} +24 -8
  56. package/dist/chunk-OJN25VJO.js.map +1 -0
  57. package/dist/{chunk-GFNW72LW.js → chunk-PFOXL4SH.js} +4 -4
  58. package/dist/{chunk-GFNW72LW.js.map → chunk-PFOXL4SH.js.map} +1 -1
  59. package/dist/{chunk-V3QMSM5I.js → chunk-SKXCTV55.js} +13 -14
  60. package/dist/chunk-SKXCTV55.js.map +1 -0
  61. package/dist/{chunk-J3VKAEQP.js → chunk-V5TBKO5Q.js} +64 -14
  62. package/dist/chunk-V5TBKO5Q.js.map +1 -0
  63. package/dist/{chunk-I3UEM3FX.js → chunk-VUCPJBAG.js} +9 -4
  64. package/dist/chunk-VUCPJBAG.js.map +1 -0
  65. package/dist/{chunk-XIHFJVOD.js → chunk-WH2EB2SF.js} +3 -3
  66. package/dist/{chunk-XIHFJVOD.js.map → chunk-WH2EB2SF.js.map} +1 -1
  67. package/dist/{chunk-PBWMV5GM.js → chunk-WQ7DE5UC.js} +18 -4
  68. package/dist/chunk-WQ7DE5UC.js.map +1 -0
  69. package/dist/cli/index.js +199 -200
  70. package/dist/cli/index.js.map +1 -1
  71. package/dist/cli/src/commands/manage.d.ts +23 -32
  72. package/dist/cli/src/commands/manage.d.ts.map +1 -1
  73. package/dist/cli/src/commands/npx.d.ts +5 -3
  74. package/dist/cli/src/commands/npx.d.ts.map +1 -1
  75. package/dist/cli/src/commands/source.d.ts +7 -0
  76. package/dist/cli/src/commands/source.d.ts.map +1 -1
  77. package/dist/connectors/config.js +6 -6
  78. package/dist/connectors/index.js +7 -7
  79. package/dist/core/index.js +5 -5
  80. package/dist/core/manifest.js +2 -2
  81. package/dist/core/models.js +1 -1
  82. package/dist/core/runtime-assets.js +4 -4
  83. package/dist/core/src/index.d.ts +2 -2
  84. package/dist/core/src/index.d.ts.map +1 -1
  85. package/dist/core/src/manifest.d.ts +16 -0
  86. package/dist/core/src/manifest.d.ts.map +1 -1
  87. package/dist/core/src/models.d.ts +8 -2
  88. package/dist/core/src/models.d.ts.map +1 -1
  89. package/dist/core/src/repo-manager.d.ts +17 -2
  90. package/dist/core/src/repo-manager.d.ts.map +1 -1
  91. package/dist/core/src/walker.d.ts +4 -0
  92. package/dist/core/src/walker.d.ts.map +1 -1
  93. package/dist/core/src/workspace-config.d.ts +14 -0
  94. package/dist/core/src/workspace-config.d.ts.map +1 -1
  95. package/dist/core/workspace-config.js +3 -3
  96. package/dist/deploy/index.js +138 -42
  97. package/dist/deploy/index.js.map +1 -1
  98. package/dist/deploy/src/index.d.ts +4 -3
  99. package/dist/deploy/src/index.d.ts.map +1 -1
  100. package/dist/deploy/src/targets/container-runtime.d.ts.map +1 -1
  101. package/dist/deploy/src/targets/local.d.ts.map +1 -1
  102. package/dist/deploy/src/targets/nix.d.ts +36 -0
  103. package/dist/deploy/src/targets/nix.d.ts.map +1 -0
  104. package/dist/deploy/src/targets/process-handle.d.ts +34 -0
  105. package/dist/deploy/src/targets/process-handle.d.ts.map +1 -0
  106. package/dist/discovery/index.js +3 -3
  107. package/dist/{ensure-sources-SL2S4UEX.js → ensure-sources-REWWBH2K.js} +9 -9
  108. package/dist/{ensure-sources-SL2S4UEX.js.map → ensure-sources-REWWBH2K.js.map} +1 -1
  109. package/dist/library/index.js +4 -4
  110. package/dist/open-library-CT4VVESU.js +13 -0
  111. package/dist/{open-library-M4DB3D3J.js.map → open-library-CT4VVESU.js.map} +1 -1
  112. package/dist/plugin-registry/src/context.d.ts +30 -1
  113. package/dist/plugin-registry/src/context.d.ts.map +1 -1
  114. package/dist/plugin-registry/src/index.d.ts +1 -1
  115. package/dist/plugin-registry/src/index.d.ts.map +1 -1
  116. package/dist/{plugin-store-AJ3FGXIC.js → plugin-store-QS7TC5HY.js} +7 -7
  117. package/dist/{plugin-store-AJ3FGXIC.js.map → plugin-store-QS7TC5HY.js.map} +1 -1
  118. package/dist/plugins/src/catalog-source.d.ts +5 -0
  119. package/dist/plugins/src/catalog-source.d.ts.map +1 -1
  120. package/dist/runner/index.js +13 -12
  121. package/dist/runner/src/serve.d.ts +7 -0
  122. package/dist/runner/src/serve.d.ts.map +1 -1
  123. package/dist/sdk/asset-manager.js +7 -7
  124. package/dist/sdk/core.js +5 -5
  125. package/dist/sdk/index.js +13 -12
  126. package/dist/sdk/index.js.map +1 -1
  127. package/dist/sdk/runner.js +13 -12
  128. package/dist/sdk/transport/ws/client.js +2 -1
  129. package/dist/sdk/transport/ws/server.js +2 -1
  130. package/dist/sdk/transport/ws.js +4 -3
  131. package/dist/sdk/transport.js +4 -3
  132. package/dist/{setup-GBSQX7JF.js → setup-F6DGKL7J.js} +7 -7
  133. package/dist/{setup-GBSQX7JF.js.map → setup-F6DGKL7J.js.map} +1 -1
  134. package/dist/store-client-JP642EEI.js +14 -0
  135. package/dist/{store-client-5WBRUC5U.js.map → store-client-JP642EEI.js.map} +1 -1
  136. package/dist/transport/index.js +4 -3
  137. package/dist/transport/src/ws/auth.d.ts +34 -0
  138. package/dist/transport/src/ws/auth.d.ts.map +1 -0
  139. package/dist/transport/src/ws/client.d.ts +4 -0
  140. package/dist/transport/src/ws/client.d.ts.map +1 -1
  141. package/dist/transport/src/ws/index.d.ts +3 -2
  142. package/dist/transport/src/ws/index.d.ts.map +1 -1
  143. package/dist/transport/src/ws/server.d.ts +5 -0
  144. package/dist/transport/src/ws/server.d.ts.map +1 -1
  145. package/dist/transport/ws/client.js +2 -1
  146. package/dist/transport/ws/server.js +2 -1
  147. package/dist/transport/ws.js +4 -3
  148. package/dist/tui/index.js +13 -12
  149. package/dist/tui/index.js.map +1 -1
  150. package/dist/workspace-plugin/index.js +1 -1
  151. package/package.json +1 -1
  152. package/dist/asset-feeds-QXCSAJRN.js.map +0 -1
  153. package/dist/chunk-4AZKT2BU.js.map +0 -1
  154. package/dist/chunk-7PTP3SQJ.js.map +0 -1
  155. package/dist/chunk-I3UEM3FX.js.map +0 -1
  156. package/dist/chunk-J3VKAEQP.js.map +0 -1
  157. package/dist/chunk-JHF66MCK.js.map +0 -1
  158. package/dist/chunk-LT4DLEYE.js.map +0 -1
  159. package/dist/chunk-PBWMV5GM.js.map +0 -1
  160. package/dist/chunk-V3QMSM5I.js.map +0 -1
  161. package/dist/chunk-VCYXVP2S.js.map +0 -1
  162. package/dist/chunk-W2O5LWYU.js +0 -3
  163. package/dist/open-library-M4DB3D3J.js +0 -13
  164. package/dist/store-client-5WBRUC5U.js +0 -14
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../runner/src/logging-bootstrap.ts","../runner/src/markdown-stream.ts","../runner/src/context.ts","../runner/src/define-capability.ts","../runner/src/mixin-resolver.ts","../runner/src/composition/types.ts","../runner/src/composition/compile.ts","../runner/src/composition/resolve.ts","../runner/src/composition/bootstrap.ts","../runner/src/environment.ts","../runner/src/manifest.ts","../runner/src/recipe-resolver.ts","../runner/src/recipe-templating.ts","../runner/src/resources.ts","../runner/src/session-builder.ts","../runner/src/agent.ts","../runner/src/resource-handler.ts","../runner/src/ai-credential-refresh.ts","../runner/src/builtin-capabilities.ts","../runner/src/capability-registry.ts","../runner/src/capability-roundtrip.ts","../runner/src/compaction/strategy.ts","../runner/src/compaction/prompt.ts","../runner/src/compaction/orchestrator.ts","../runner/src/file-changed-rewriter.ts","../runner/src/refresh-flag-dispatcher.ts","../runner/src/runner-capabilities.ts","../runner/src/serve-credentials.ts","../runner/src/session-stimulus.ts","../runner/src/serve.ts","../runner/src/session.ts"],"names":["z","path","resolve","fs","content","createHash","z2","parseYaml","existsSync","recipeLog","resolvePath","readFileSync","readdirSync","join","statSync","z4","homedir","dirname","mkdirSync","writeFileSync","buildClientCapabilityHandler","secretProvider","wsConfig","_z","fsWatch"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoCO,IAAM,kBAAN,MAAyC;AAAA,EAC7B,OAAmB,EAAC;AAAA,EACpB,GAAA;AAAA,EAEjB,WAAA,CAAY,MAAM,GAAA,EAAK;AACrB,IAAA,IAAA,CAAK,GAAA,GAAM,GAAA;AAAA,EACb;AAAA,EAEA,MAAM,KAAA,EAAuB;AAC3B,IAAA,O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AAA,EAAY;AACnC,EAAA,OAAO,EAAE,GAAG,IAAA,EAAM,KAAA,EAAO,UAAA,EAAW,EAAG,SAAA,EAAW,GAAA,EAAK,SAAA,EAAW,GAAA,EAAK,MAAA,EAAQ,SAAA,EAAU;AAC3F;AAUO,SAAS,aAAa,KAAA,EAAmC;AAC9D,EAAA,OAAO,EAAE,GAAG,KAAA,EAAO,SAAA,EAAA,qBAAe,IAAA,EAAK,EAAE,aAAY,EAAE;AACzD","file":"chunk-SKXCTV55.js","sourcesContent":["import {\n type LogStore,\n OnLogBridgeSink,\n WsLogSink,\n createLogStoreFromConfig,\n getLogStore,\n registerLogStore,\n resetLogStore,\n resolveLogStoreConfig,\n} from \"@skaile/workspaces/core/logging\";\nimport type {\n LogEntry,\n LogEntryEvent,\n LogSink,\n LogQuery,\n LogQueryResult,\n} from \"@skaile/workspaces/types\";\n\n/**\n * Pre-init log sink. Active before the LogStore boots — i.e. during the\n * window between process start and `session_init` processing.\n *\n * Writes every entry to `process.stdout` (so early-boot operators / container\n * log shippers still see it). Entries are also captured in a bounded\n * in-memory ring (default cap 200 entries) so that, once the LogStore boots,\n * subscribers can read them via {@link entries} for diagnostic purposes.\n *\n * NOTE: backfilling the buffered entries into the LogStore's SQLite trail is\n * not done in v3.0 because `LogStore.record()` re-stamps id/timestamp/\n * sessionId, which would corrupt the original entries. A follow-up\n * (`AF-PV3 / F-LOG-BACKFILL`) will add a `replay()` API to LogStore so the\n * boot logs land in the persistent trail alongside the live stream.\n *\n * Spec: `_devlog/specs/2026-05-10-deterministic-session-bootstrap.md` §\n * Pre-init logging.\n */\nexport class PreInitRingSink implements LogSink {\n private readonly ring: LogEntry[] = [];\n private readonly cap: number;\n\n constructor(cap = 200) {\n this.cap = cap;\n }\n\n write(entry: LogEntry): void {\n process.stdout.write(formatForStdout(entry));\n this.ring.push(entry);\n if (this.ring.length > this.cap) this.ring.shift();\n }\n\n writeBatch(entries: LogEntry[]): void {\n for (const entry of entries) this.write(entry);\n }\n\n /** Optional query (no-op) — satisfies the LogSink contract. */\n query(_q: LogQuery): LogQueryResult {\n return { entries: this.ring.slice() };\n }\n\n /** Close hook — clears the ring so subsequent writes are dropped. */\n close(): void {\n this.ring.length = 0;\n }\n\n /** Number of entries currently buffered (capped at {@link cap}). */\n size(): number {\n return this.ring.length;\n }\n\n /** Snapshot of the currently-buffered entries. Used for diagnostics. */\n entries(): readonly LogEntry[] {\n return this.ring.slice();\n }\n\n /** Discard all buffered entries. Called by `bootstrapRunnerLogStore`. */\n clear(): void {\n this.ring.length = 0;\n }\n}\n\nfunction formatForStdout(entry: LogEntry): string {\n const ts = entry.timestamp ?? new Date().toISOString();\n const where = [entry.source?.kind, entry.source?.subkind, entry.source?.instance]\n .filter(Boolean)\n .join(\":\");\n const dataStr = entry.data ? ` ${JSON.stringify(entry.data)}` : \"\";\n return `[${ts}] [${entry.level}] [${where}] ${entry.message}${dataStr}\\n`;\n}\n\nlet activePreInitSink: PreInitRingSink | null = null;\n\n/**\n * Install (or return the existing) process-wide pre-init sink. Idempotent\n * so the first import wins; later calls reuse the same ring.\n *\n * Called from the top of every runner entry point (CLI, serve.ts) before\n * any other code emits structured logs.\n */\nexport function installPreInitRingSink(cap = 200): PreInitRingSink {\n if (activePreInitSink) return activePreInitSink;\n activePreInitSink = new PreInitRingSink(cap);\n return activePreInitSink;\n}\n\n/** Currently-installed pre-init sink, or `null` if none has been installed. */\nexport function getPreInitRingSink(): PreInitRingSink | null {\n return activePreInitSink;\n}\n\n/** Drop the reference to the installed sink. Used in tests + on dispose. */\nexport function clearPreInitRingSink(): void {\n activePreInitSink = null;\n}\n\n/**\n * Options for {@link bootstrapRunnerLogStore}.\n *\n * @docLink packages/runner/logging#bootstrap-options\n */\nexport interface BootstrapOptions {\n sessionId: string;\n projectDir: string;\n /** `skaile.yaml`'s `logging:` block, if pre-loaded. */\n yamlBlock?: unknown;\n /** Back-compat callback — every entry mirrored as a formatted line. */\n onLog?: (line: string) => void;\n /**\n * Transport send callback. When provided, a `WsLogSink` is installed so\n * every recorded LogEntry flows to the connected client as a `log_entry`\n * AgentEvent. Drops silently when the transport is disconnected — that\n * gating happens inside the transport's `send()`.\n */\n transportSend?: (event: LogEntryEvent) => void;\n}\n\n/**\n * Result from {@link bootstrapRunnerLogStore}.\n *\n * @docLink packages/runner/logging#bootstrap-result\n */\nexport interface BootstrapResult {\n store: LogStore;\n dispose: () => void;\n}\n\nlet currentSessionId: string | null = null;\n\n/**\n * Idempotent bootstrap. If the same sessionId is re-used, returns the existing\n * registered store. If a different sessionId arrives, the previous store is\n * closed and replaced.\n * @docLink packages/runner/logging#bootstrap-runner-log-store\n */\nexport function bootstrapRunnerLogStore(opts: BootstrapOptions): BootstrapResult {\n const existing = getLogStore();\n if (existing && currentSessionId === opts.sessionId) {\n return { store: existing, dispose: () => disposeStore(existing) };\n }\n\n const cfg = resolveLogStoreConfig({\n sessionId: opts.sessionId,\n workspacePath: opts.projectDir,\n // The skaile.yaml `logging:` block is loosely typed at the workspace-config\n // layer; the resolver validates `mode` / `level` strings at runtime.\n yamlBlock: opts.yamlBlock as Parameters<typeof resolveLogStoreConfig>[0][\"yamlBlock\"],\n });\n const store = createLogStoreFromConfig(cfg);\n\n if (opts.onLog) {\n store.addSink(new OnLogBridgeSink(opts.onLog));\n }\n\n if (opts.transportSend) {\n store.addSink(new WsLogSink({ send: opts.transportSend }));\n }\n\n if (existing) disposeStore(existing);\n registerLogStore(store);\n currentSessionId = opts.sessionId;\n\n // Clear any entries buffered during the pre-init window (between process\n // start and session_init processing). The entries are still visible on\n // stdout (the PreInitRingSink wrote them there as they happened);\n // backfilling them into LogStore.SQLite needs a LogStore.replay()\n // upgrade tracked under follow-up `AF-PV3 / F-LOG-BACKFILL`.\n const preInit = getPreInitRingSink();\n if (preInit) preInit.clear();\n\n return {\n store,\n dispose: () => {\n disposeStore(store);\n currentSessionId = null;\n },\n };\n}\n\n/**\n * Reset the runner's process-singleton LogStore.\n *\n * @docLink packages/runner/logging#reset-runner-log-store\n */\nexport function resetRunnerLogStore(): void {\n const s = getLogStore();\n if (s) disposeStore(s);\n resetLogStore();\n currentSessionId = null;\n}\n\nfunction disposeStore(store: LogStore): void {\n try {\n store.flush();\n store.close();\n } catch {\n /* swallow */\n }\n}\n","import { Marked } from \"marked\";\n// @ts-expect-error — no type declarations for marked-terminal\nimport { markedTerminal } from \"marked-terminal\";\n\nconst marked = new Marked(markedTerminal());\n\n/**\n * Accumulates streamed markdown text and renders it to the terminal\n * with ANSI formatting (bold, italic, code blocks, etc.).\n *\n * Strategy: accumulate full text, re-render on each write, output only\n * the newly rendered portion. Completed blocks (separated by double\n * newlines) are \"committed\" so re-rendering only processes the tail.\n * @docLink packages/runner/dev-guide#agent-chat-single-shot\n */\nexport class MarkdownStreamer {\n private buffer = \"\";\n private committedSource = \"\";\n // biome-ignore lint/correctness/noUnusedPrivateClassMembers: write-only accumulator kept for future diff-based rendering\n private committedRender = \"\";\n private output: NodeJS.WriteStream;\n\n constructor(output: NodeJS.WriteStream = process.stdout) {\n this.output = output;\n }\n\n write(chunk: string): void {\n this.buffer += chunk;\n this.flush();\n }\n\n /** Render any remaining content and reset state. */\n end(): void {\n if (this.buffer.length > this.committedSource.length) {\n const tail = this.buffer.slice(this.committedSource.length);\n if (tail.trim()) {\n const rendered = this.render(tail);\n this.output.write(rendered);\n }\n }\n this.buffer = \"\";\n this.committedRender = \"\";\n this.committedSource = \"\";\n }\n\n private flush(): void {\n // Find the last double-newline boundary — everything before it is\n // structurally complete markdown that won't change with more input.\n const uncommitted = this.buffer.slice(this.committedSource.length);\n const boundary = uncommitted.lastIndexOf(\"\\n\\n\");\n if (boundary === -1) return;\n\n const complete = uncommitted.slice(0, boundary + 2);\n const rendered = this.render(complete);\n this.output.write(rendered);\n\n this.committedSource += complete;\n this.committedRender += rendered;\n }\n\n private render(src: string): string {\n try {\n const result = marked.parse(src);\n if (typeof result === \"string\") return result;\n // marked v15 can return a Promise if async extensions are used,\n // but with marked-terminal it is always synchronous.\n return String(result);\n } catch {\n // Fallback: output raw text if rendering fails\n return src;\n }\n }\n}\n","/**\n * Build a markdown section describing the platform context in which the\n * agent is running. Rendered into the system prompt alongside resource and environment sections.\n */\n\nimport type { AgentContextConfig } from \"@skaile/workspaces/core\";\n\nconst PLATFORM_DESCRIPTIONS: Record<string, string> = {\n skaile:\n \"You are an AI assistant operating within the Skaile platform, an enterprise AI workspace. Users interact with you through a chat interface in their browser.\",\n};\n\n/**\n * Build a markdown section describing the platform context in which the\n * agent is running. Rendered into the system prompt alongside resource\n * and environment sections.\n *\n * @param context - Platform context configuration (platform, multi_user, session_model)\n * @returns Markdown section string, or undefined when no context is configured\n * @docLink packages/runner/dev-guide#flow-execution-turn-based-model\n */\nexport function buildContextSection(context: AgentContextConfig | undefined): string | undefined {\n if (!context) return undefined;\n const hasAny =\n context.platform !== undefined ||\n context.multi_user !== undefined ||\n context.session_model !== undefined;\n if (!hasAny) return undefined;\n\n const lines: string[] = [\"## Platform\", \"\"];\n\n if (context.platform) {\n const description = PLATFORM_DESCRIPTIONS[context.platform];\n if (description) {\n lines.push(description);\n } else {\n lines.push(`You are running inside the ${context.platform} platform.`);\n }\n lines.push(\"\");\n }\n\n if (context.multi_user === true) {\n lines.push(\n \"Multiple users may participate in the same session. Be aware that messages in this conversation may come from different users.\",\n );\n lines.push(\"\");\n } else if (context.multi_user === false) {\n lines.push(\"This is a single-user session.\");\n lines.push(\"\");\n }\n\n if (context.session_model === \"persistent\") {\n lines.push(\n \"Your work persists across interactions. Files you create or modify in the workspace are saved and available in future sessions.\",\n );\n lines.push(\"\");\n } else if (context.session_model === \"ephemeral\") {\n lines.push(\n \"This session is ephemeral. Work you do does not persist beyond the current interaction.\",\n );\n lines.push(\"\");\n }\n\n // Trim trailing empty line\n while (lines.length > 0 && lines[lines.length - 1] === \"\") lines.pop();\n\n return lines.join(\"\\n\");\n}\n","/**\n * `defineCapability` — author-friendly factory that builds a {@link DefinedCapability}\n * from a Zod-typed input/output schema.\n *\n * Authors declare a capability with Zod schemas; this factory derives the\n * wire-format `inputSchema` / `outputSchema` (JSON Schema) and packages the\n * handler so it can be invoked uniformly through {@link CapabilityRegistry}.\n *\n * The runtime per-handler logger (`ctx.log`) is wired by the registry at\n * invocation time — handlers MUST NOT construct their own logger; all output\n * goes through `ctx.log` so it lands under the\n * `capability:<origin>:<name>` slice (see protocol-v2 carry-forward L2).\n *\n * @category Capabilities\n * @since 2.0.0\n */\nimport * as z from \"zod\";\nimport type {\n Capability,\n CapabilityAudience,\n CapabilityOrigin,\n Logger,\n RenderSpec,\n} from \"@skaile/workspaces/types\";\n\n/**\n * Per-invocation context passed to a capability handler. The registry builds\n * a fresh context for each call and fills in `log` from\n * `createLogger({kind: 'capability', subkind: <origin.kind>, instance: <name>})`.\n *\n * Additional runtime hooks (cancellation signal, store accessors, etc.) can\n * be threaded in by the bridge layer in later phases; the minimum contract is\n * `sessionId` + `log`.\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/runner/capabilities#handlercontext-log-convention-carry-forward-l2\n */\nexport type HandlerContext = {\n /** Session this invocation belongs to. */\n sessionId: string;\n /**\n * Per-capability logger pre-configured as\n * `createLogger({kind: 'capability', subkind: <origin.kind>, instance: <name>})`.\n * Handlers MUST emit through this logger so invocations land under the\n * `capability:<origin>:<name>` slice and stay queryable from the debug\n * panel and `skaile session logs`.\n */\n log: Logger;\n};\n\n/**\n * Arguments to {@link defineCapability}. Mirrors the wire-format\n * {@link Capability} fields plus the Zod schemas (input + optional output)\n * and the handler.\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/runner/capabilities#registry-surface\n */\nexport type DefineCapabilityArgs<\n T extends z.ZodTypeAny,\n R extends z.ZodTypeAny | undefined = undefined,\n> = {\n /** Stable, session-unique name. Convention: `<namespace>.<verb>`. */\n name: string;\n /**\n * Human-readable label for user-facing surfaces (cmdK action palette,\n * debug panels). Falls back to `name` when omitted.\n */\n displayName?: string;\n /** Human/LLM-readable summary; shown to the LLM at tool registration. */\n description: string;\n /** Zod schema validating `args` at invocation time. Converted to JSON Schema. */\n input: T;\n /** Optional Zod schema for the return value. Converted to JSON Schema when present. */\n output?: R;\n /** Where the handler runs. */\n side: \"client\" | \"agent\";\n /** Discriminated tag identifying who registered the capability. */\n origin: CapabilityOrigin;\n /** Lifetime: `session` survives the whole session, `turn` is dropped at end-of-turn. */\n scope?: \"session\" | \"turn\";\n /** When true, the bridge auto-resolves with `{}` immediately and runs the handler in the background. */\n fireAndForget?: boolean;\n /** When true, the platform shows a confirm UI before dispatch. */\n requiresApproval?: boolean;\n /** Documentation hint: side-effect, render, or pure query. */\n kind?: \"effect\" | \"render\" | \"query\";\n /**\n * Whether this capability should be exposed in user-facing surfaces\n * (cmdK / capability menus). Defers to `isUserInvokable` inference rules\n * when omitted. See `@skaile/workspaces/types#isUserInvokable`.\n *\n * @deprecated Set {@link audience} instead. Kept for v2.x compatibility\n * with skill authors that haven't migrated.\n */\n userInvokable?: boolean;\n /**\n * Audience scoping for this capability. When omitted, consumers treat\n * the capability as `['llm', 'user']` (v2.x default). Host RPCs and\n * `runner.*` capabilities MUST set this to `['runtime']` so they never\n * reach the LLM tool list or the user-facing command palette.\n *\n * @since 3.0.0\n */\n audience?: CapabilityAudience[];\n /** Appended to the system prompt's `<CAPABILITIES>` section. */\n promptFragment?: string;\n /**\n * Per-capability override for the runner's `capability_result` round-trip\n * timeout. Omit to use `DEFAULT_CAPABILITY_CALL_TIMEOUT_MS` (60s). Set a\n * larger value for capabilities that block longer than a normal tool call\n * (e.g. `platform.ask_session`).\n */\n callTimeoutMs?: number;\n /** Render contract for capabilities that produce a UI surface. */\n render?: RenderSpec;\n /**\n * The handler. Receives validated input plus a {@link HandlerContext}.\n * When `output` is declared, the return type is inferred from the schema;\n * otherwise the handler may return any value (including `void` for pure\n * effects).\n */\n handler: (\n args: z.infer<T>,\n ctx: HandlerContext,\n ) => Promise<R extends z.ZodTypeAny ? z.infer<R> : unknown>;\n};\n\n/**\n * A registered capability. Carries the wire-format {@link Capability} fields\n * plus the original Zod schemas and the type-erased handler. The registry\n * stores `DefinedCapability`s; serialization to the wire (for replay or\n * remote registration) drops the runtime fields.\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/runner/capabilities#registry-surface\n */\nexport type DefinedCapability = Capability & {\n /** Original Zod schema for runtime input validation. Not serialized to the wire. */\n readonly inputZod: z.ZodTypeAny;\n /** Original Zod schema for the optional output, if declared. Not serialized. */\n readonly outputZod?: z.ZodTypeAny;\n /** Type-erased handler invoked through {@link CapabilityRegistry.invoke}. */\n handler: (args: unknown, ctx: HandlerContext) => Promise<unknown>;\n};\n\n/**\n * Build a {@link DefinedCapability} from author-friendly Zod-typed args.\n *\n * The resulting `inputSchema` / `outputSchema` on the capability are JSON\n * Schema records (per the wire contract); the original Zod schemas are kept\n * on `inputZod` / `outputZod` for runtime validation in\n * {@link CapabilityRegistry.invoke}.\n *\n * @example\n * ```ts\n * const reactCap = defineCapability({\n * name: 'platform.react',\n * description: 'Acknowledge a user message with a Unicode emoji.',\n * side: 'client',\n * origin: { kind: 'client' },\n * fireAndForget: true,\n * input: z.object({ emoji: z.string(), targetSeq: z.number().optional() }),\n * handler: async ({ emoji }, ctx) => { ctx.log.info('reacted', { emoji }) },\n * });\n * ```\n *\n * @category Capabilities\n * @since 2.0.0\n * @docLink packages/runner/capabilities#registry-surface\n */\nexport function defineCapability<\n T extends z.ZodTypeAny,\n R extends z.ZodTypeAny | undefined = undefined,\n>(args: DefineCapabilityArgs<T, R>): DefinedCapability {\n const inputSchema = z.toJSONSchema(args.input, {\n target: \"draft-07\",\n io: \"input\",\n }) as Record<string, unknown>;\n const outputSchema = args.output\n ? (z.toJSONSchema(args.output, {\n target: \"draft-07\",\n io: \"output\",\n }) as Record<string, unknown>)\n : undefined;\n\n return {\n name: args.name,\n displayName: args.displayName,\n description: args.description,\n inputSchema,\n outputSchema,\n side: args.side,\n origin: args.origin,\n scope: args.scope,\n fireAndForget: args.fireAndForget,\n requiresApproval: args.requiresApproval,\n kind: args.kind,\n userInvokable: args.userInvokable,\n audience: args.audience,\n promptFragment: args.promptFragment,\n callTimeoutMs: args.callTimeoutMs,\n render: args.render,\n inputZod: args.input,\n outputZod: args.output,\n handler: args.handler as (args: unknown, ctx: HandlerContext) => Promise<unknown>,\n };\n}\n","/**\n * mixin-resolver.ts\n *\n * Resolves agent composition mixin refs (persona, ruleset, knowledge) to text\n * for rendering into the agent definition at install time.\n *\n * Three ref forms:\n * Local path — \"./extra-rules.md\" or \"/abs/path/rules.md\"\n * Read directly relative to agentDir (or absolute).\n * Bare name — \"skaile-base\"\n * Resolved from repos as `${defaultKind}:skaile-base`\n * Qualified — \"persona:researcher@ext-repo#v2.0\"\n * Full AssetRef syntax; repo qualifier searches specific repo only.\n *\n * Knowledge bundles (kind=\"knowledge\") resolve to a directory — all *.md files\n * inside are loaded in priority order (same priority-based loadKnowledge logic used by the asset-manager).\n */\n\nimport fs from \"node:fs/promises\";\nimport { readdirSync } from \"node:fs\";\nimport path from \"node:path\";\nimport type { AgentManifest, CatalogEntry } from \"@skaile/workspaces/core\";\n\n// ── Types ─────────────────────────────────────────────────────────────────────\n\n/**\n * A resolved mixin with its content loaded from disk.\n *\n * @docLink packages/runner/dev-guide#key-conventions\n */\nexport interface ResolvedMixin {\n /** Text content ready for system prompt injection. */\n content: string;\n /** Absolute path to the source file, for debugging. */\n source: string;\n}\n\n/**\n * Pre-built repo catalog map: repoName → CatalogEntry[].\n * Built by the caller (session-builder) from wsConfig.repositories using\n * ensureRepo() + scanRepo() from @skaile/workspaces/core/repo-manager.\n * Local repos are scanned directly; remote repos use the global cache.\n * @docLink packages/runner/dev-guide#key-conventions\n */\nexport type RepoMap = Record<string, CatalogEntry[]>;\n\n/**\n * Content of an agent mixin, loaded from `CONVENTIONS.md` or `RULES.md`.\n *\n * @docLink packages/runner/dev-guide#key-conventions\n */\nexport interface AgentMixinContent {\n personas: ResolvedMixin[];\n rules: ResolvedMixin[];\n knowledge: ResolvedMixin[];\n}\n\n// ── Public API ────────────────────────────────────────────────────────────────\n\n/**\n * Resolve a single mixin ref to its text content.\n * Returns null if the ref cannot be resolved (missing file or unknown catalog name).\n * Never throws — callers filter nulls.\n * @docLink packages/runner/dev-guide#key-conventions\n */\nexport async function resolveMixin(\n ref: string,\n defaultKind: string,\n agentDir: string,\n repos: RepoMap,\n): Promise<ResolvedMixin | null> {\n // ── Local path ────────────────────────────────────────────────────────────\n if (ref.startsWith(\".\") || ref.startsWith(\"/\")) {\n const absPath = ref.startsWith(\"/\") ? ref : path.join(agentDir, ref);\n if (defaultKind === \"knowledge\") {\n return loadKnowledgeDir(absPath);\n }\n const content = await readFileSafe(absPath);\n if (!content) return null;\n return { content: stripFrontmatter(content).trim(), source: absPath };\n }\n\n // ── Catalog ref ───────────────────────────────────────────────────────────\n const { kind, name, repoQualifier } = parseRef(ref, defaultKind);\n const entry = findInRepos(repos, kind, name, repoQualifier);\n if (!entry) return null;\n\n if (entry.kind === \"knowledge\") {\n // knowledge.yaml source — load the sibling directory\n return loadKnowledgeDir(path.dirname(entry.source));\n }\n\n // persona, ruleset, skill, contract — read manifest file, strip frontmatter\n const raw = await readFileSafe(entry.source);\n if (!raw) return null;\n return { content: stripFrontmatter(raw).trim(), source: entry.source };\n}\n\n/**\n * Resolve all mixin arrays from a manifest.\n * All three kinds resolve concurrently. Unresolvable refs are silently skipped.\n * @docLink packages/runner/dev-guide#key-conventions\n */\nexport async function resolveAgentMixins(\n manifest: Pick<AgentManifest, \"persona\" | \"rules\" | \"knowledge\">,\n agentDir: string,\n repos: RepoMap,\n): Promise<AgentMixinContent> {\n const resolve = (\n refs: string[] | undefined,\n kind: \"persona\" | \"ruleset\" | \"knowledge\",\n ): Promise<(ResolvedMixin | null)[]> =>\n Promise.all((refs ?? []).map((r) => resolveMixin(r, kind, agentDir, repos)));\n\n const [personaResults, rulesResults, knowledgeResults] = await Promise.all([\n resolve(manifest.persona, \"persona\"),\n resolve(manifest.rules, \"ruleset\"),\n resolve(manifest.knowledge, \"knowledge\"),\n ]);\n\n return {\n personas: personaResults.filter((r): r is ResolvedMixin => r !== null),\n rules: rulesResults.filter((r): r is ResolvedMixin => r !== null),\n knowledge: knowledgeResults.filter((r): r is ResolvedMixin => r !== null),\n };\n}\n\n// ── Internal helpers ──────────────────────────────────────────────────────────\n\n/** Read a file, return empty string on any error. */\nasync function readFileSafe(filePath: string): Promise<string> {\n try {\n return await fs.readFile(filePath, \"utf-8\");\n } catch {\n return \"\";\n }\n}\n\n/** Strip YAML frontmatter (--- delimited) from markdown content. */\nfunction stripFrontmatter(text: string): string {\n return text.replace(/^---\\s*\\n[\\s\\S]*?\\n---\\s*\\n?/, \"\");\n}\n\n/**\n * Parse a mixin ref string into kind, name, and optional repo qualifier.\n * Handles: \"skaile-base\", \"persona:skaile-base\", \"ruleset:safety@skaile-ai#v2\"\n */\nfunction parseRef(\n ref: string,\n defaultKind: string,\n): { kind: string; name: string; repoQualifier: string | undefined } {\n let rest = ref.trim();\n let kind = defaultKind;\n\n // Extract kind: prefix\n const colonIdx = rest.indexOf(\":\");\n if (colonIdx !== -1) {\n kind = rest.slice(0, colonIdx).trim();\n rest = rest.slice(colonIdx + 1).trim();\n }\n\n // Extract #pin suffix (drop it — we use whatever's installed)\n const hashIdx = rest.indexOf(\"#\");\n if (hashIdx !== -1) rest = rest.slice(0, hashIdx).trim();\n\n // Extract @repo qualifier\n let repoQualifier: string | undefined;\n const atIdx = rest.indexOf(\"@\");\n if (atIdx !== -1) {\n repoQualifier = rest.slice(atIdx + 1).trim() || undefined;\n rest = rest.slice(0, atIdx).trim();\n }\n\n return { kind, name: rest, repoQualifier };\n}\n\n/** Find a CatalogEntry by kind + name across all repos (or a specific repo). */\nfunction findInRepos(\n repos: RepoMap,\n kind: string,\n name: string,\n repoQualifier: string | undefined,\n): CatalogEntry | undefined {\n const searchRepos = repoQualifier\n ? repos[repoQualifier]\n ? [repos[repoQualifier]]\n : []\n : Object.values(repos);\n\n for (const entries of searchRepos) {\n const found = entries.find((e) => e.kind === kind && e.name === name);\n if (found) return found;\n }\n return undefined;\n}\n\n/**\n * Load all *.md files from a knowledge directory, in priority order.\n * Reads index.yaml (same priority-based loadKnowledge format used by the asset-manager) when present.\n * Returns combined content joined with \\n\\n---\\n\\n.\n */\nasync function loadKnowledgeDir(dir: string): Promise<ResolvedMixin | null> {\n let entries: string[];\n try {\n entries = readdirSync(dir).filter((e) => e.endsWith(\".md\"));\n } catch {\n return null;\n }\n\n // Parse index.yaml for priority ordering\n const priorityMap: Record<string, number> = {};\n const indexContent = await readFileSafe(path.join(dir, \"index.yaml\"));\n if (indexContent) {\n const pathMatches = [...indexContent.matchAll(/path:\\s*(\\S+)/g)];\n const priorityMatches = [...indexContent.matchAll(/priority:\\s*(\\d+)/g)];\n pathMatches.forEach((m, i) => {\n const filename = m[1];\n if (!filename) return;\n const priority = priorityMatches[i] ? parseInt(priorityMatches[i][1] ?? \"99\", 10) : 99;\n priorityMap[filename] = priority;\n });\n }\n\n const docs = await Promise.all(\n entries.map(async (filename) => ({\n filename,\n priority: priorityMap[filename] ?? 99,\n content: (await readFileSafe(path.join(dir, filename))).trim(),\n })),\n );\n\n const sorted = docs\n .filter((d) => d.content)\n .sort((a, b) => a.priority - b.priority || a.filename.localeCompare(b.filename));\n\n if (sorted.length === 0) return null;\n\n return {\n content: sorted.map((d) => d.content).join(\"\\n\\n---\\n\\n\"),\n source: dir,\n };\n}\n","/**\n * composition/types.ts\n *\n * Shared types for the agent composition module (Task 1.7).\n *\n * Defines the binding system, compile manifest schema, and the\n * resolved composition result that the runner consumes at session start.\n */\n\nimport type { Binding, AgentComposeItem } from \"@skaile/workspaces/types/manifests\";\n\n// ---------------------------------------------------------------------------\n// Re-export from types\n// ---------------------------------------------------------------------------\n\nexport type { Binding, AgentComposeItem };\n\n// ---------------------------------------------------------------------------\n// Kind-to-binding defaults\n// ---------------------------------------------------------------------------\n\n/**\n * Default binding by asset kind.\n *\n * Per the spec: soul -> inline-snapshot, ruleset -> inline-live,\n * everything else (skill, knowledge, connector, mount, etc.) -> discoverable.\n */\nconst KIND_BINDING_DEFAULTS: Record<string, Binding> = {\n soul: \"inline-snapshot\",\n persona: \"inline-snapshot\",\n ruleset: \"inline-live\",\n skill: \"discoverable\",\n knowledge: \"discoverable\",\n connector: \"discoverable\",\n mount: \"discoverable\",\n prompt: \"inline-live\",\n flow: \"discoverable\",\n \"mcp-server\": \"discoverable\",\n contract: \"inline-live\",\n};\n\n/**\n * Resolve the effective binding for a composition item.\n * Uses explicit `binding` if set, otherwise falls back to kind default.\n *\n * @param item - A single entry from an agent manifest's `composes:` list.\n * @returns The effective {@link Binding} — explicit value when set, otherwise\n * the kind-specific default (e.g. `soul` → `inline-snapshot`, `skill` → `discoverable`).\n * @docLink packages/runner/capabilities#resolve-binding\n */\nexport function resolveBinding(item: AgentComposeItem): Binding {\n if (item.binding) return item.binding;\n return KIND_BINDING_DEFAULTS[item.kind] ?? \"discoverable\";\n}\n\n// ---------------------------------------------------------------------------\n// Compile manifest (written to <agent>/compile_manifest.json)\n// ---------------------------------------------------------------------------\n\n/**\n * Single entry in the agent's `compile_manifest.json`. Records the resolved\n * version, content hash, and effective binding for one composition item at\n * the time of the last `skaile rebuild` run.\n *\n * @docLink packages/runner/capabilities#compile-manifest-entry\n */\nexport interface CompileManifestEntry {\n /** Asset ref (e.g. '@skaile/sales-soul@1.2') */\n asset_ref: string;\n /** Resolved version (e.g. '1.2.3') */\n version: string | null;\n /** SHA256 of the resolved content */\n hash: string;\n /** Effective binding */\n binding: Binding;\n /** ISO timestamp when this entry was resolved */\n resolved_at: string;\n}\n\n/**\n * Root structure of `compile_manifest.json` written by `skaile rebuild`.\n * Tracks the prompt version counter and all resolved composition entries.\n * The runner reads this at session start to verify inline-snapshot content\n * against its stored hash.\n *\n * @docLink packages/runner/capabilities#compile-manifest\n */\nexport interface CompileManifest {\n /** Compile manifest schema version */\n schema_version: 1;\n /** Prompt version — bumped on every rebuild */\n prompt_version: number;\n /** Entries for each composition item */\n entries: CompileManifestEntry[];\n /** ISO timestamp of the last rebuild */\n compiled_at: string;\n}\n\n// ---------------------------------------------------------------------------\n// Resolved composition result (consumed by runner at session start)\n// ---------------------------------------------------------------------------\n\n/**\n * A resolved inline content block for system prompt injection.\n *\n * @docLink packages/runner/capabilities#inline-block\n */\nexport interface InlineBlock {\n /** Source ref for debugging */\n ref: string;\n /** Asset kind */\n kind: string;\n /** The text content to inject */\n content: string;\n /** Binding mode that produced this block */\n binding: \"inline-live\" | \"inline-snapshot\";\n}\n\n/**\n * A resolved discoverable item (becomes a tool-list entry).\n *\n * @docLink packages/runner/capabilities#discoverable-entry\n */\nexport interface DiscoverableEntry {\n /** Source ref */\n ref: string;\n /** Asset kind */\n kind: string;\n /** Tool name for capability registry */\n name: string;\n /** One-line description */\n description: string;\n /** Full content (loaded on demand when the tool is invoked) */\n content: string;\n}\n\n/**\n * The full result of resolving an agent's composes: field.\n *\n * @docLink packages/runner/capabilities#resolved-composition\n */\nexport interface ResolvedComposition {\n /** Blocks to inline into the system prompt (inline-live + inline-snapshot) */\n inlineBlocks: InlineBlock[];\n /** Items to register as discoverable capabilities */\n discoverableEntries: DiscoverableEntry[];\n /** Warnings (non-fatal — e.g. missing assets) */\n warnings: string[];\n}\n","/**\n * composition/compile.ts\n *\n * Implements `skaile rebuild <agent>` — re-snapshots all inline-snapshot items,\n * bumps the prompt version, and writes `<agent>/compile_manifest.json`.\n *\n * The compile manifest records what was resolved and when, so the runner can\n * verify content hasn't drifted without a rebuild.\n */\n\nimport { createHash } from \"node:crypto\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport type { AgentComposeItem } from \"@skaile/workspaces/types/manifests\";\nimport { resolveBinding, type CompileManifest, type CompileManifestEntry } from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\n/**\n * Filename for the agent compile manifest written by `skaile rebuild`.\n *\n * @docLink packages/runner/capabilities#compile-composition\n */\nexport const COMPILE_MANIFEST_FILENAME = \"compile_manifest.json\";\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\n/**\n * Options for {@link compileComposition}.\n *\n * @docLink packages/runner/capabilities#compile-composition\n */\nexport interface CompileOpts {\n /** Path to the agent directory (where agent.yaml and compile_manifest.json live) */\n agentDir: string;\n /** The agent's composes: items */\n items: AgentComposeItem[];\n /**\n * Content loader — given an asset ref + kind, returns the content text.\n * Returns null if the content cannot be loaded.\n */\n loadContent: (ref: string, kind: string) => Promise<string | null>;\n /**\n * Version extractor — given an asset ref, returns the resolved version string.\n * Returns null if unknown.\n */\n resolveVersion?: (ref: string) => Promise<string | null>;\n}\n\n/**\n * Result returned by {@link compileComposition}.\n *\n * @docLink packages/runner/capabilities#compile-composition\n */\nexport interface CompileResult {\n /** The written compile manifest */\n manifest: CompileManifest;\n /** Path to the written file */\n manifestPath: string;\n /** Number of entries that were successfully resolved */\n resolvedCount: number;\n /** Warnings for unresolvable items */\n warnings: string[];\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Compile (rebuild) the agent's composition.\n *\n * 1. Reads existing compile_manifest.json (if present) for version continuity\n * 2. Re-resolves ALL items (both snapshot and non-snapshot get recorded)\n * 3. Bumps prompt_version\n * 4. Writes compile_manifest.json\n *\n * @param opts - Compile options including agentDir, items, and content loader.\n * @returns A {@link CompileResult} with the written manifest and any warnings.\n * @docLink packages/runner/capabilities#compile-composition\n */\nexport async function compileComposition(opts: CompileOpts): Promise<CompileResult> {\n const { agentDir, items, loadContent, resolveVersion } = opts;\n const manifestPath = path.join(agentDir, COMPILE_MANIFEST_FILENAME);\n const warnings: string[] = [];\n\n // Read existing manifest for version continuity\n const existing = await loadCompileManifest(manifestPath);\n const nextVersion = (existing?.prompt_version ?? 0) + 1;\n\n // Resolve all items\n const entries: CompileManifestEntry[] = [];\n for (const item of items) {\n const binding = resolveBinding(item);\n const content = await loadContent(item.ref, item.kind);\n\n if (!content) {\n warnings.push(`\"${item.ref}\" (${item.kind}): content not found — skipped`);\n continue;\n }\n\n const hash = createHash(\"sha256\").update(content).digest(\"hex\");\n const version = resolveVersion ? await resolveVersion(item.ref) : null;\n\n entries.push({\n asset_ref: item.ref,\n version,\n hash,\n binding,\n resolved_at: new Date().toISOString(),\n });\n }\n\n const manifest: CompileManifest = {\n schema_version: 1,\n prompt_version: nextVersion,\n entries,\n compiled_at: new Date().toISOString(),\n };\n\n // Write atomically: temp file + rename to avoid corruption on interrupt\n const tmpPath = `${manifestPath}.tmp`;\n await fs.writeFile(tmpPath, `${JSON.stringify(manifest, null, 2)}\\n`, \"utf-8\");\n await fs.rename(tmpPath, manifestPath);\n\n return {\n manifest,\n manifestPath,\n resolvedCount: entries.length,\n warnings,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Load an existing compile_manifest.json, or return undefined if not found.\n *\n * @param manifestPath - Absolute path to the manifest file.\n * @returns The parsed {@link CompileManifest} or `undefined` when missing or malformed.\n * @docLink packages/runner/capabilities#load-compile-manifest\n */\nexport async function loadCompileManifest(\n manifestPath: string,\n): Promise<CompileManifest | undefined> {\n try {\n const raw = await fs.readFile(manifestPath, \"utf-8\");\n const parsed = JSON.parse(raw);\n if (parsed?.schema_version === 1 && typeof parsed.prompt_version === \"number\") {\n return parsed as CompileManifest;\n }\n return undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Load compile manifest from an agent directory, reading the file from\n * `<agentDir>/compile_manifest.json`.\n *\n * @param agentDir - Absolute path to the agent definition directory.\n * @returns The parsed {@link CompileManifest} or `undefined` when missing or malformed.\n * @docLink packages/runner/capabilities#load-compile-manifest-from-dir\n */\nexport async function loadCompileManifestFromDir(\n agentDir: string,\n): Promise<CompileManifest | undefined> {\n return loadCompileManifest(path.join(agentDir, COMPILE_MANIFEST_FILENAME));\n}\n","/**\n * composition/resolve.ts\n *\n * Resolves an agent's `composes:` items against the Library into a\n * ResolvedComposition — prompt blocks for inline items and discoverable\n * entries for tool-list items.\n *\n * Three resolution paths per binding:\n * - `inline-snapshot`: reads frozen content from compile_manifest.json\n * - `inline-live`: reads current content from Library (per invocation)\n * - `discoverable`: registers as a capability (name + description + content)\n *\n * This module is pure logic — no IO beyond the IAssetIndex calls.\n */\n\nimport { createHash } from \"node:crypto\";\nimport type { IAssetIndex } from \"@skaile/workspaces/library\";\nimport type { AgentComposeItem } from \"@skaile/workspaces/types/manifests\";\nimport { resolveBinding, type CompileManifest, type ResolvedComposition } from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\n/**\n * Options for {@link resolveComposition}.\n *\n * @docLink packages/runner/capabilities#resolve-composition\n */\nexport interface ResolveCompositionOpts {\n /** The agent's composes: items */\n items: AgentComposeItem[];\n /** Library for asset resolution */\n library: IAssetIndex;\n /**\n * Pre-loaded compile manifest for inline-snapshot items.\n * If absent, inline-snapshot items fall back to live resolution with a warning.\n */\n compileManifest?: CompileManifest;\n /**\n * Content loader — given an asset ref, returns the asset's prompt-injectable content.\n * For skill: the SKILL.md body. For persona/ruleset: the manifest body text.\n * Returns null if the content cannot be loaded.\n */\n loadContent: (ref: string, kind: string) => Promise<string | null>;\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve all composition items for an agent.\n *\n * Returns:\n * - inlineBlocks: content to inject into the system prompt\n * - discoverableEntries: items to register as LLM-visible capabilities\n * - warnings: non-fatal issues encountered during resolution\n *\n * @param opts - Resolution options with items, library, optional compile manifest and content loader.\n * @returns A {@link ResolvedComposition} with inline blocks, discoverable entries, and warnings.\n * @docLink packages/runner/capabilities#resolve-composition\n */\nexport async function resolveComposition(\n opts: ResolveCompositionOpts,\n): Promise<ResolvedComposition> {\n const { items, library, compileManifest, loadContent } = opts;\n const result: ResolvedComposition = {\n inlineBlocks: [],\n discoverableEntries: [],\n warnings: [],\n };\n\n for (const item of items) {\n const binding = resolveBinding(item);\n\n try {\n switch (binding) {\n case \"inline-snapshot\":\n await resolveInlineSnapshot(item, binding, compileManifest, loadContent, result);\n break;\n case \"inline-live\":\n await resolveInlineLive(item, binding, loadContent, result);\n break;\n case \"discoverable\":\n await resolveDiscoverable(item, library, loadContent, result);\n break;\n }\n } catch (err) {\n result.warnings.push(\n `Failed to resolve \"${item.ref}\" (${item.kind}): ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n\n return result;\n}\n\n// ---------------------------------------------------------------------------\n// Internal: per-binding resolution\n// ---------------------------------------------------------------------------\n\nasync function resolveInlineSnapshot(\n item: AgentComposeItem,\n binding: \"inline-snapshot\",\n compileManifest: CompileManifest | undefined,\n loadContent: (ref: string, kind: string) => Promise<string | null>,\n result: ResolvedComposition,\n): Promise<void> {\n // Try to find frozen content in the compile manifest\n if (compileManifest) {\n const entry = compileManifest.entries.find(\n (e) => e.asset_ref === item.ref && e.binding === \"inline-snapshot\",\n );\n if (entry) {\n const content = await loadContent(item.ref, item.kind);\n if (content) {\n // Verify content hasn't drifted since last rebuild\n const hash = createHash(\"sha256\").update(content).digest(\"hex\");\n if (hash !== entry.hash) {\n result.warnings.push(\n `\"${item.ref}\" (${item.kind}) content has changed since last rebuild (expected ${entry.hash.slice(0, 8)}…, got ${hash.slice(0, 8)}…). Run \"skaile rebuild\" to update the snapshot.`,\n );\n }\n result.inlineBlocks.push({ ref: item.ref, kind: item.kind, content, binding });\n return;\n }\n }\n }\n\n // Fallback: resolve live (with warning that rebuild is recommended)\n const content = await loadContent(item.ref, item.kind);\n if (content) {\n result.warnings.push(\n `\"${item.ref}\" (${item.kind}) is binding=inline-snapshot but no compile_manifest.json found — using live content. Run \"skaile rebuild\" to freeze.`,\n );\n result.inlineBlocks.push({ ref: item.ref, kind: item.kind, content, binding });\n } else {\n result.warnings.push(`\"${item.ref}\" (${item.kind}): content not found`);\n }\n}\n\nasync function resolveInlineLive(\n item: AgentComposeItem,\n binding: \"inline-live\",\n loadContent: (ref: string, kind: string) => Promise<string | null>,\n result: ResolvedComposition,\n): Promise<void> {\n const content = await loadContent(item.ref, item.kind);\n if (content) {\n result.inlineBlocks.push({ ref: item.ref, kind: item.kind, content, binding });\n } else {\n result.warnings.push(`\"${item.ref}\" (${item.kind}): content not found`);\n }\n}\n\nasync function resolveDiscoverable(\n item: AgentComposeItem,\n library: IAssetIndex,\n loadContent: (ref: string, kind: string) => Promise<string | null>,\n result: ResolvedComposition,\n): Promise<void> {\n // Look up the asset definition for metadata\n const assetDef = await library.getAssetDef(item.ref);\n\n // Build the tool name from the ref\n const name = buildToolName(item);\n const description = assetDef?.description ?? `${item.kind}: ${item.ref}`;\n\n // Load full content for on-demand usage\n const content = await loadContent(item.ref, item.kind);\n if (content) {\n result.discoverableEntries.push({\n ref: item.ref,\n kind: item.kind,\n name,\n description,\n content,\n });\n } else {\n result.warnings.push(`\"${item.ref}\" (${item.kind}): content not found for discoverable entry`);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Build a capability tool name from a compose item ref.\n * e.g. '@skaile/gmail@^1' -> 'skaile__gmail'\n * e.g. '@acme/sales-research@^3' -> 'acme__sales-research'\n * e.g. '@skaile/gmail' (no version) -> 'skaile__gmail'\n */\nfunction buildToolName(item: AgentComposeItem): string {\n // Strip version pin: only strip @<version> if it appears after the name\n // (i.e. after the last /). Scoped refs like @skaile/gmail have the @\n // as the publisher prefix — we must not strip that.\n const lastSlash = item.ref.lastIndexOf(\"/\");\n let refNoVersion: string;\n if (lastSlash !== -1) {\n const afterSlash = item.ref.slice(lastSlash + 1);\n const versionAt = afterSlash.indexOf(\"@\");\n refNoVersion = versionAt !== -1 ? item.ref.slice(0, lastSlash + 1 + versionAt) : item.ref;\n } else {\n // No slash — bare ref like 'gmail@^1'\n const versionAt = item.ref.indexOf(\"@\");\n refNoVersion = versionAt !== -1 ? item.ref.slice(0, versionAt) : item.ref;\n }\n // Strip leading @\n const cleaned = refNoVersion.replace(/^@/, \"\");\n // Replace / with __ for flat tool namespace\n return cleaned.replace(/\\//g, \"__\");\n}\n","/**\n * composition/bootstrap.ts\n *\n * Wires the composition resolver into the agent session lifecycle.\n *\n * This module provides:\n * - `resolveAgentComposition()` — called by session-builder.ts to produce\n * inline blocks (→ system prompt) and discoverable entries (→ capability\n * registry)\n * - `registerCompositionCapabilities()` — called by serve.ts to register\n * discoverable entries as Protocol v2 capabilities\n *\n * Phase 1 limitation: the content loader uses `resolveMixin()` which only\n * resolves local-path refs (./file.md, /abs/path). Scoped catalog refs\n * (@publisher/name) require a populated RepoMap from workspace config, which\n * Phase 2 / Library integration will provide. Unresolvable refs produce\n * warnings but do not block session start.\n */\n\nimport { existsSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport type { AgentManifest } from \"@skaile/workspaces/core\";\nimport type { IAssetIndex } from \"@skaile/workspaces/library\";\nimport type { Logger } from \"@skaile/workspaces/types\";\nimport * as z from \"zod\";\nimport type { CapabilityRegistry } from \"../capability-registry.js\";\nimport { defineCapability } from \"../define-capability.js\";\nimport { type RepoMap, resolveMixin } from \"../mixin-resolver.js\";\nimport { loadCompileManifestFromDir } from \"./compile.js\";\nimport { resolveComposition } from \"./resolve.js\";\nimport type { DiscoverableEntry, ResolvedComposition } from \"./types.js\";\n\n// Re-export for downstream convenience\nexport type { ResolvedComposition };\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\n/**\n * Options for {@link resolveAgentComposition}.\n *\n * @docLink packages/runner/capabilities#resolve-agent-composition\n */\nexport interface ResolveAgentCompositionOpts {\n /** Path to the agent definition directory (where agent.yaml lives) */\n agentDir: string;\n /** Parsed agent manifest (must have `composes` field) */\n manifest: AgentManifest;\n /**\n * Project root — reserved for Phase 2 workspace config resolution.\n * In Phase 1 this is unused but accepted so the call site doesn't\n * need updating when Library integration lands.\n */\n projectDir: string;\n /** Pre-built repo map for catalog resolution. Empty in Phase 1. */\n repos?: RepoMap;\n /** Logger for composition resolution warnings */\n log?: Logger;\n}\n\n// ---------------------------------------------------------------------------\n// Public API: Resolve\n// ---------------------------------------------------------------------------\n\n/**\n * Resolve an agent's `composes:` items into inline blocks and discoverable\n * entries. Called by session-builder.ts during the session creation pipeline.\n *\n * Returns null when the manifest has no `composes:` items.\n *\n * @param opts - Resolution options including agentDir, manifest, and optional repos/log.\n * @returns A {@link ResolvedComposition} or `null` when there are no composition items.\n * @docLink packages/runner/capabilities#resolve-agent-composition\n */\nexport async function resolveAgentComposition(\n opts: ResolveAgentCompositionOpts,\n): Promise<ResolvedComposition | null> {\n const { agentDir, manifest, repos = {}, log } = opts;\n\n const items = manifest.composes;\n if (!items || items.length === 0) return null;\n\n // Load compile manifest for inline-snapshot verification\n const compileManifest = await loadCompileManifestFromDir(agentDir);\n\n // Build a content loader using the existing mixin resolver.\n // Phase 1: only local-path refs resolve successfully. Scoped catalog refs\n // (@publisher/name) require a populated RepoMap which Phase 2 provides.\n // Non-matching kinds simply return null (surfaces as a compose warning).\n const loadContent = async (ref: string, kind: string): Promise<string | null> => {\n try {\n const resolved = await resolveMixin(ref, kind, agentDir, repos);\n return resolved?.content ?? null;\n } catch {\n return null;\n }\n };\n\n // Try to open the real LocalIndex for asset description enrichment.\n // Falls back to a null-returning stub when the library DB doesn't exist\n // (user hasn't run `skaile source add` + `skaile source sync` yet).\n const library = await openLocalIndexIfAvailable(log);\n\n const result = await resolveComposition({\n items,\n library,\n compileManifest,\n loadContent,\n });\n\n // Log warnings so they surface in session debug logs\n if (log && result.warnings.length > 0) {\n for (const warning of result.warnings) {\n log.warn(warning);\n }\n }\n\n return result;\n}\n\n// ---------------------------------------------------------------------------\n// Public API: Register Capabilities\n// ---------------------------------------------------------------------------\n\n/**\n * Register discoverable composition entries as Protocol v2 capabilities.\n *\n * Each discoverable entry becomes a tool the LLM can invoke to \"activate\"\n * that asset. When invoked, the handler returns the asset's full content\n * (e.g. a SKILL.md body for skills, connection instructions for connectors).\n *\n * The LLM sees a lean tool list (name + description only) and loads full\n * content on demand — this keeps the context window efficient for agents\n * that compose many assets.\n *\n * @param registry - The session capability registry to register capabilities onto.\n * @param entries - Discoverable entries from a prior {@link resolveAgentComposition} call.\n * @docLink packages/runner/capabilities#register-composition-capabilities\n */\nexport function registerCompositionCapabilities(\n registry: CapabilityRegistry,\n entries: DiscoverableEntry[],\n): void {\n for (const entry of entries) {\n const cap = defineCapability({\n name: entry.name,\n displayName: `${entry.kind}: ${entry.ref}`,\n description: entry.description,\n side: \"agent\",\n origin: { kind: \"skill\", skillId: entry.ref },\n scope: \"session\",\n kind: \"query\",\n userInvokable: false,\n input: z.strictObject({}),\n handler: async (_args, ctx) => {\n ctx.log.info(\"loading composed asset content\", {\n ref: entry.ref,\n kind: entry.kind,\n });\n return { content: entry.content, ref: entry.ref, kind: entry.kind };\n },\n });\n registry.register(cap, \"agent\");\n }\n}\n\n// ---------------------------------------------------------------------------\n// Internal: Library resolution\n// ---------------------------------------------------------------------------\n\n/**\n * Null-returning IAssetIndex stub used when no real Library is available.\n * All query methods return empty; write methods are no-ops.\n */\nconst STUB_LIBRARY: IAssetIndex = {\n getAssetDef: async () => null,\n listAssetDefs: async () => [],\n createInstance: async () => ({}) as any,\n getInstance: async () => null,\n listInstances: async () => [],\n updateInstance: async () => ({}) as any,\n deleteInstance: async () => {},\n subscribe: async () => ({}) as any,\n unsubscribe: async () => {},\n listSubscriptions: async () => [],\n getConsumptionGraph: async () => [],\n};\n\n/**\n * Try to open the LocalIndex SQLite store if it exists.\n * Returns a stub when the library DB is missing (user hasn't synced yet)\n * or when opening fails (e.g. corrupt DB).\n */\nasync function openLocalIndexIfAvailable(log?: Logger): Promise<IAssetIndex> {\n // Probe for the index file at the canonical 2026-05-27 location plus the\n // two legacy ones (lib.db inside libraries/ or library/). Migration to the\n // canonical path is handled by `createLibraryDb`; here we only need to know\n // whether *some* index file is present before constructing LocalIndex.\n const indexPath = process.env.SKAILE_INDEX_PATH ?? join(homedir(), \".skaile\", \"index.db\");\n const librariesDir = process.env.SKAILE_LIBRARIES_DIR ?? join(homedir(), \".skaile\", \"libraries\");\n const legacyHome = join(homedir(), \".skaile\", \"library\");\n const probes = [\n indexPath,\n join(librariesDir, \"index.db\"),\n join(librariesDir, \"lib.db\"),\n join(legacyHome, \"lib.db\"),\n ];\n\n if (!probes.some((p) => existsSync(p))) {\n return STUB_LIBRARY;\n }\n\n try {\n // Deferred import so the runner does not eagerly pull in the library\n // subpath when no local library DB exists.\n const { LocalIndex } = await import(\"@skaile/workspaces/library\");\n return new LocalIndex() as IAssetIndex;\n } catch (err) {\n log?.debug(`Could not open LocalIndex at ${indexPath}: ${(err as Error).message}`);\n return STUB_LIBRARY;\n }\n}\n","/**\n * Probe the runtime environment for available tools and runtimes, and build\n * a markdown section describing them for the system prompt.\n *\n * Runs once at session start. All probes execute in parallel with a per-probe\n * timeout so the total wall time is bounded by the slowest single probe.\n */\n\nimport { execFile } from \"node:child_process\";\nimport { promisify } from \"node:util\";\n\nconst execFileAsync = promisify(execFile);\n\nconst PROBE_TIMEOUT_MS = 1500;\n\ninterface VersionProbe {\n label: string;\n bin: string;\n args: string[];\n /** Extract version from stdout (first line by default). */\n extract?: (output: string) => string;\n}\n\nconst VERSION_PROBES: VersionProbe[] = [\n { label: \"Python\", bin: \"python3\", args: [\"--version\"] },\n { label: \"Node.js\", bin: \"node\", args: [\"--version\"] },\n { label: \"Bun\", bin: \"bun\", args: [\"--version\"] },\n { label: \"Git\", bin: \"git\", args: [\"--version\"] },\n { label: \"npm\", bin: \"npm\", args: [\"--version\"] },\n {\n label: \"pip\",\n bin: \"pip\",\n args: [\"--version\"],\n extract: (out) => out.split(\" \").slice(0, 2).join(\" \"),\n },\n];\n\nconst PRESENCE_PROBES = [\"curl\", \"jq\", \"ssh\", \"wget\", \"rg\"];\n\nasync function runProbe(bin: string, args: string[]): Promise<string | null> {\n try {\n const { stdout } = await execFileAsync(bin, args, { timeout: PROBE_TIMEOUT_MS });\n return stdout.trim().split(\"\\n\")[0] ?? null;\n } catch {\n return null;\n }\n}\n\nasync function checkPresence(bin: string): Promise<boolean> {\n try {\n await execFileAsync(\"which\", [bin], { timeout: PROBE_TIMEOUT_MS });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Probe the runtime environment for available tools and runtimes at\n * session start, and build a markdown section describing them for the\n * system prompt.\n *\n * All probes execute in parallel with a per-probe timeout so total wall\n * time is bounded by the slowest single probe.\n *\n * @param projectDir - The project working directory\n * @returns Markdown section string, or undefined when no tools are found\n * @docLink packages/runner/dev-guide#environment-variables\n */\nexport async function buildEnvironmentSection(projectDir: string): Promise<string | undefined> {\n const versionResults = await Promise.allSettled(\n VERSION_PROBES.map(async (probe) => {\n const raw = await runProbe(probe.bin, probe.args);\n if (!raw) return null;\n const version = probe.extract ? probe.extract(raw) : raw;\n return { label: probe.label, version };\n }),\n );\n\n const presenceResults = await Promise.allSettled(PRESENCE_PROBES.map(checkPresence));\n\n const runtimes: string[] = [];\n for (const result of versionResults) {\n if (result.status === \"fulfilled\" && result.value) {\n runtimes.push(`${result.value.label} (${result.value.version})`);\n }\n }\n\n const tools: string[] = [];\n for (let i = 0; i < PRESENCE_PROBES.length; i++) {\n const result = presenceResults[i];\n if (result?.status === \"fulfilled\" && result.value) {\n tools.push(PRESENCE_PROBES[i]!);\n }\n }\n\n if (runtimes.length === 0 && tools.length === 0) return undefined;\n\n const lines: string[] = [\n \"## Environment\",\n \"\",\n \"You are running inside an isolated container with the following tools available:\",\n \"\",\n ];\n\n if (runtimes.length > 0) {\n lines.push(\"**Runtimes:**\");\n for (const r of runtimes) lines.push(`- ${r}`);\n lines.push(\"\");\n }\n\n if (tools.length > 0) {\n lines.push(`**Tools:** ${tools.join(\", \")}`);\n lines.push(\"\");\n }\n\n const shell = process.env.SHELL ?? \"sh\";\n lines.push(`**Shell:** ${shell}`);\n lines.push(`**Working directory:** ${projectDir}`);\n\n return lines.join(\"\\n\");\n}\n","/**\n * manifest.ts\n *\n * Parses the agent definition manifest (agent.yaml) from a GitAgent directory.\n * This is the sole responsibility of this module — system prompt assembly for\n * SOUL/RULES/knowledge is handled by the renderers at install time and the\n * backend drivers at runtime (native identity).\n */\n\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { parse as parseYaml } from \"yaml\";\nimport type { AgentManifest } from \"@skaile/workspaces/core\";\n\n/** True if the given directory contains a valid GitAgent definition (agent.yaml present). */\n/**\n * Check whether an agent definition directory contains a valid agent.yaml.\n *\n * @param agentDir - Path to the agent definition directory\n * @returns true when agent.yaml exists at the given path\n * @docLink packages/runner/dev-guide#manifest-loading\n */\nexport async function agentDefinitionExists(agentDir: string): Promise<boolean> {\n try {\n await fs.access(path.join(agentDir, \"agent.yaml\"));\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Load and parse the agent manifest from `agent.yaml` in the given directory.\n *\n * Returns `undefined` when:\n * - The file does not exist\n * - The file is empty or whitespace-only\n * - The YAML is malformed\n *\n * This replaces the old `buildAgentImprint()` for the manifest-extraction use case.\n * The system prompt assembly that `buildAgentImprint()` used to do is no longer\n * a runtime concern — it is handled by the renderers at install time.\n * @docLink packages/runner/dev-guide#manifest-loading\n */\nexport async function loadAgentManifest(agentDir: string): Promise<AgentManifest | undefined> {\n const agentYamlPath = path.join(agentDir, \"agent.yaml\");\n let content: string;\n try {\n content = await fs.readFile(agentYamlPath, \"utf-8\");\n } catch {\n return undefined;\n }\n if (!content.trim()) return undefined;\n try {\n return parseYaml(content) as AgentManifest;\n } catch {\n return undefined;\n }\n}\n","/**\n * Resolves Nix flake attribute paths to /nix/store out-paths via\n * `nix path-info --offline <flakeRef>#<attr>`.\n *\n * Used by the MCP wiring path (and Phase 3+ connector/mount paths) to\n * turn `${recipe:<id>:<sub>}` markers into absolute store paths before\n * subprocess spawn.\n */\nimport { spawnSync } from \"node:child_process\";\nimport { readFileSync, statSync } from \"node:fs\";\nimport { validateAssetRecipeAttr } from \"@skaile/workspaces/core\";\nimport { createLogger } from \"@skaile/workspaces/core/logging\";\n\nexport class RecipeUnavailableError extends Error {\n constructor(\n public readonly flakeRef: string,\n public readonly attr: string,\n cause?: unknown,\n ) {\n super(\n `Recipe unavailable: ${flakeRef}#${attr}${cause instanceof Error ? ` - ${cause.message}` : \"\"}`,\n );\n this.name = \"RecipeUnavailableError\";\n }\n}\n\n/**\n * Per-resolve-pass cache. Created fresh by each call to\n * `loadMcpServerDeclarations` integration so values don't go stale across\n * sessions but multiple recipes within one pass dedupe.\n */\nexport type RecipeResolutionCache = Map<string, string>;\n\nexport function createRecipeCache(): RecipeResolutionCache {\n return new Map();\n}\n\nconst DEFAULT_RECIPE_MAP_PATH = \"/etc/skaile/mcps-out-paths.json\";\n\n/** Resolves the prebuilt attr->storePath map file path (env override). */\nfunction recipeMapPath(): string {\n return process.env.SKAILE_NIX_RECIPE_MAP || DEFAULT_RECIPE_MAP_PATH;\n}\n\ninterface RecipeMapMemo {\n path: string;\n mtimeMs: number;\n map: Record<string, unknown> | null;\n}\n\nlet recipeMapMemo: RecipeMapMemo | null = null;\n\n/** Test-only: clears the (path, mtime) recipe-map memo so module-level state does not leak between cases. */\nexport function __resetRecipeMapMemoForTest(): void {\n recipeMapMemo = null;\n}\n\n/**\n * Loads the prebuilt attr->storePath map, memoized by (file path + mtime).\n * Re-reads when the file's mtime changes so a live restage of\n * `/etc/skaile/mcps-out-paths.json` is picked up without a process restart.\n * Returns null (and falls through to nix) when the file is missing or its\n * JSON is malformed; a malformed map warns once per distinct (path, mtime)\n * version — re-reading the same corrupt file is served from memo without\n * re-warning, but a later corrupt version (new mtime) warns again.\n */\nfunction loadRecipeMap(): Record<string, unknown> | null {\n const path = recipeMapPath();\n\n let mtimeMs: number;\n try {\n mtimeMs = statSync(path).mtimeMs;\n } catch {\n // File missing — memo the absence keyed to this path, fall through. We\n // intentionally re-stat on every call (the memo never short-circuits the\n // statSync above) so a map staged later is detected and picked up live.\n recipeMapMemo = { path, mtimeMs: -1, map: null };\n return null;\n }\n\n if (recipeMapMemo && recipeMapMemo.path === path && recipeMapMemo.mtimeMs === mtimeMs) {\n // Same version already seen (valid or malformed); do not re-warn.\n return recipeMapMemo.map;\n }\n\n let map: Record<string, unknown> | null = null;\n try {\n const parsed: unknown = JSON.parse(readFileSync(path, \"utf8\"));\n map = parsed && typeof parsed === \"object\" ? (parsed as Record<string, unknown>) : null;\n } catch (err) {\n // Reached only on a NEW (path, mtime) — the memo short-circuits an unchanged\n // version above, so a corrupt map warns once per distinct file version, and\n // a later valid->corrupt->fixed->corrupt sequence warns on each corrupt one.\n createLogger({ kind: \"mcp\", subkind: \"recipe-resolve\" }).warn(\n \"recipe map malformed — falling back to nix path-info\",\n { path, error: err instanceof Error ? err.message : String(err) },\n );\n map = null;\n }\n\n recipeMapMemo = { path, mtimeMs, map };\n return map;\n}\n\n/**\n * Resolves a flake attribute to its /nix/store out-path.\n * Throws RecipeUnavailableError on missing closure / nix failure.\n */\nexport function resolveRecipePath(\n flakeRef: string,\n attr: string,\n cache: RecipeResolutionCache,\n): string {\n const key = `${flakeRef}#${attr}`;\n const cached = cache.get(key);\n if (cached) return cached;\n\n // Validate attr before it reaches the nix spawnSync arg — defense-in-depth\n // for Phase 3+ community catalogs where attr may be untrusted.\n try {\n validateAssetRecipeAttr(attr);\n } catch (err) {\n throw new RecipeUnavailableError(\n flakeRef,\n attr,\n err instanceof Error ? err : new Error(String(err)),\n );\n }\n\n const log = createLogger({ kind: \"mcp\", subkind: \"recipe-resolve\" });\n log.debug(\"resolving recipe\", { flakeRef, attr });\n\n // Map-first fast path: a prebuilt attr->storePath map lets deployed\n // containers skip the offline ai-assets flake eval entirely.\n const map = loadRecipeMap();\n if (map) {\n const hit = attr\n .split(\".\")\n .reduce<unknown>(\n (o, k) => (o && typeof o === \"object\" ? (o as Record<string, unknown>)[k] : undefined),\n map,\n );\n if (typeof hit === \"string\" && hit.startsWith(\"/nix/store/\")) {\n cache.set(key, hit);\n log.info(\"resolved recipe (map)\", { flakeRef, attr, outPath: hit });\n return hit;\n }\n }\n\n const result = spawnSync(\"nix\", [\"path-info\", \"--offline\", `${flakeRef}#${attr}`], {\n encoding: \"utf8\",\n });\n if (result.error) throw new RecipeUnavailableError(flakeRef, attr, result.error);\n if (result.status !== 0) {\n throw new RecipeUnavailableError(\n flakeRef,\n attr,\n new Error(`nix path-info exited ${result.status}: ${result.stderr.trim()}`),\n );\n }\n const outPath = result.stdout.trim().split(\"\\n\")[0];\n if (!outPath?.startsWith(\"/nix/store/\")) {\n throw new RecipeUnavailableError(\n flakeRef,\n attr,\n new Error(`Unexpected output: ${result.stdout}`),\n );\n }\n cache.set(key, outPath);\n log.info(\"resolved recipe\", { flakeRef, attr, outPath });\n return outPath;\n}\n","/**\n * Substitutes `${recipe:<id>}`, `${recipe:<id>:<sub>}`, `${recipe:<id>:bin}`,\n * and `${recipe:<id>:lib}` markers with absolute /nix/store paths.\n *\n * Matching rules:\n * ${recipe:excel} -> /nix/store/.../bin\n * ${recipe:excel:bin} -> /nix/store/.../bin\n * ${recipe:excel:lib} -> /nix/store/.../lib\n * ${recipe:excel:share} -> /nix/store/.../share (any sub path)\n *\n * The bare ${recipe:<id>} form is treated as `${recipe:<id>:bin}` for\n * ergonomic command-line use; explicit subpaths win.\n */\nimport { existsSync } from \"node:fs\";\n\n// Case-sensitive by design: markers must be lowercase to match the declaration\n// id map keys. Uppercase markers survive as literal text and are caught by the\n// unresolved-marker scan in resources.ts, which skips the declaration cleanly.\nconst RECIPE_MARKER = /\\$\\{recipe:([a-z0-9_-]+)(?::([a-z0-9_/.-]+))?\\}/g;\n\nexport function substituteRecipeTemplating(\n value: string,\n recipeOutPaths: ReadonlyMap<string, string>,\n): string {\n return value.replace(RECIPE_MARKER, (_match, id: string, sub: string | undefined) => {\n const outPath = recipeOutPaths.get(id);\n if (!outPath) {\n // Leave the marker in place so the caller can decide policy. The\n // wiring layer surfaces unresolved markers as a structured error\n // before subprocess spawn.\n return _match;\n }\n if (!sub) return `${outPath}/bin`;\n return `${outPath}/${sub}`;\n });\n}\n\nexport function substituteRecipeMap(\n obj: Record<string, string> | undefined,\n recipeOutPaths: ReadonlyMap<string, string>,\n): Record<string, string> | undefined {\n if (!obj) return obj;\n const out: Record<string, string> = {};\n for (const [k, v] of Object.entries(obj)) {\n out[k] = substituteRecipeTemplating(v, recipeOutPaths);\n }\n return out;\n}\n\nexport interface MissingSubstitutedPath {\n field: string;\n path: string;\n error: string;\n}\n\n/**\n * Checks that the resolved binary path (command and args[0]) produced by\n * recipe substitution actually exists on the filesystem.\n *\n * Only checks `command` and `args[0]` — these are the fields where ENOENT\n * is most user-visible (subprocess spawn fails immediately). Other args and\n * env values are not checked to keep this focused.\n *\n * Returns an array of missing-path entries; an empty array means all checks\n * passed. The caller in resources.ts skips the declaration when non-empty.\n */\nexport function validateSubstitutedPaths(\n command: string | undefined,\n args: string[] | undefined,\n): MissingSubstitutedPath[] {\n const missing: MissingSubstitutedPath[] = [];\n\n if (command?.startsWith(\"/nix/store/\") && !existsSync(command)) {\n missing.push({\n field: \"command\",\n path: command,\n error: `resolved path does not exist: ${command}`,\n });\n }\n\n const firstArg = args?.[0];\n if (firstArg?.startsWith(\"/nix/store/\") && !existsSync(firstArg)) {\n missing.push({\n field: \"args[0]\",\n path: firstArg,\n error: `resolved path does not exist: ${firstArg}`,\n });\n }\n\n return missing;\n}\n","/**\n * resources.ts\n *\n * Shared connector lifecycle for agent sessions — connect, watch, and build\n * tool injection for all connector types (filesystem-face and tool-face).\n *\n * Used by agent.ts (REPL), base-assets/connectors/flow/run-flow.ts (flow), and serve.ts (WebSocket server).\n * Extracted from duplicated inline blocks in each of those files.\n */\n\nimport {\n buildConnectorPromptSection,\n buildSdkConnectorTools,\n type ConnectorChangeEvent,\n ConnectorManager,\n ConnectorStartupError,\n findMissingPackages,\n installNpmPackages,\n loadConnectorDeclarations,\n type PreMintedSecretProvider,\n registerBuiltinConnectors,\n type SyncStatusPayload,\n type TokenMediator,\n} from \"@skaile/workspaces/connectors\";\nimport {\n loadMcpServerDeclarations,\n type McpServerDeclaration,\n type RuntimeAssetsResult,\n resolveRuntimeAssets,\n} from \"@skaile/workspaces/core\";\nimport { createLogger } from \"@skaile/workspaces/core/logging\";\nimport { WorkspacePlugin } from \"@skaile/workspaces/workspace-plugin\";\nimport { z } from \"zod\";\nimport { createRecipeCache, resolveRecipePath } from \"./recipe-resolver.js\";\nimport {\n substituteRecipeMap,\n substituteRecipeTemplating,\n validateSubstitutedPaths,\n} from \"./recipe-templating.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * Result of {@link buildAgentResources}.\n *\n * @docLink packages/runner/dev-guide#flow-execution-turn-based-model\n */\nexport interface AgentResourcesResult {\n /** Connected ConnectorManager instance — null if no connectors declared or package missing. */\n resourceManager: any | null;\n /** Markdown section to append to the system prompt — empty string if no resources. */\n resourcePromptSection: string;\n /**\n * In-process MCP server map to pass as `mcpServers` in `AgentConfig`.\n * Populated only for the `claude-sdk` driver; undefined for all others.\n */\n mcpServers: Record<string, unknown> | undefined;\n /**\n * Resolved runtime assets — catalog entries, implicit refs, npm deps, warnings.\n * Held by the session so live-update paths (add_resource, configure)\n * can call `runtimeAssets.refresh()` and consume the same shared view.\n * `null` only when @skaile/workspaces/connectors or skaile.yaml parsing failed.\n */\n runtimeAssets: RuntimeAssetsResult | null;\n /** Disconnect all connectors, unmount all mounts, and stop watchers. */\n dispose: () => Promise<void>;\n /**\n * Start filesystem and connector watchers. Call AFTER the transport is\n * listening — watching can be slow on large directory trees and must not\n * block session startup.\n */\n startWatching: () => void;\n}\n\n/**\n * Callback hooks for filesystem and connector lifecycle events.\n *\n * @docLink packages/runner/dev-guide#flow-execution-turn-based-model\n */\nexport interface ResourceWatchCallbacks {\n /**\n * Called by mountable adapters to report incremental sync progress.\n * Used by serve.ts to forward sync_status events to the frontend.\n */\n onSyncStatus?: (connectorId: string, status: SyncStatusPayload) => void;\n /**\n * Called when a watched connector detects an in-process change.\n * Used by serve.ts to forward file_changed events to the frontend.\n * Change events are deduplicated within `dedupTtlMs` per path.\n */\n onFileChanged?: (connectorId: string, event: ConnectorChangeEvent) => void;\n /** Dedup window for file_changed events in milliseconds. Default: 500. */\n dedupTtlMs?: number;\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Set up all connectors declared in `skaile.yaml` for an agent session.\n *\n * Steps:\n * 1. Register built-in connectors\n * 2. Load connector declarations from skaile.yaml\n * 3. Connect all connectors via ConnectorManager (filesystem + tool faces)\n * 4. Optionally start filesystem/connector watchers (serve.ts use case)\n * 5. Build the system prompt section (mount paths + connector tools)\n * 6. Build in-process MCP server (claude-sdk only)\n *\n * @param projectDir Workspace root — where skaile.yaml lives\n * @param driverType Active bridge driver ID: \"omp\" | \"claude-sdk\"\n * @param onLog Optional log callback; silently ignored if omitted\n * @param watch Optional watch callbacks; watching is skipped if omitted\n * @param secretProvider Optional secret provider chain for connector field\n * resolution and `env:NAME` lookups\n * @param sessionMeta Provider/model/sessionId metadata used for logging\n * @param tokenMediator Optional callback for `auth: backend` connectors to\n * mint short-lived tokens. Threaded into `ConnectorManager`.\n * @param preMintedSecrets Optional v3 pre-minted credential provider — when\n * supplied, `auth: backend` connectors find their initial\n * token in-process instead of paying a\n * `request_access_token` round-trip at connect time.\n * @docLink packages/runner/dev-guide#flow-execution-turn-based-model\n */\nexport async function buildAgentResources(\n projectDir: string,\n driverType: string,\n _onLog?: (line: string) => void,\n watch?: ResourceWatchCallbacks,\n secretProvider?: unknown,\n sessionMeta?: { provider?: string; model?: string; sessionId?: string },\n tokenMediator?: TokenMediator,\n preMintedSecrets?: PreMintedSecretProvider,\n): Promise<AgentResourcesResult> {\n const resLog = createLogger({\n kind: \"runner\",\n subkind: \"resources\",\n instance: sessionMeta?.sessionId ?? \"no-session\",\n });\n // `_onLog` is preserved in the public signature for back-compat with external\n // callers, but is unused internally — structured emission via `resLog` and the\n // per-source loggers below reaches the caller through the OnLogBridgeSink that\n // the runner bootstrap installs at the LogStore level.\n const noopResult: AgentResourcesResult = {\n resourceManager: null,\n resourcePromptSection: \"\",\n mcpServers: undefined,\n runtimeAssets: null,\n dispose: async () => {},\n startWatching: () => {},\n };\n\n try {\n registerBuiltinConnectors();\n\n // Resolve catalog entries + implicit refs from skaile.yaml + base-assets repo.\n // Held on the session result so live-update paths can call refresh().\n const runtimeAssets = await resolveRuntimeAssets(projectDir);\n for (const w of runtimeAssets.warnings) {\n resLog.warn(\"runtime asset warning\", { code: w.code, message: w.message });\n }\n\n // Optional: install missing npm peer deps before mountAll/connectAll runs.\n // Disabled by default for serve mode (no network or write access in\n // production agent containers); enable via SKAILE_AUTO_INSTALL_DEPS=true.\n // Asset-manager.install() is the canonical preflight install path.\n if (process.env.SKAILE_AUTO_INSTALL_DEPS === \"true\") {\n const required = runtimeAssets.requiredNpmDeps.required;\n if (required.length > 0) {\n const missing = findMissingPackages(required, projectDir);\n if (missing.length > 0) {\n resLog.info(\"installing missing npm peer deps\", { packages: missing });\n const r = await installNpmPackages(missing, projectDir);\n if (!r.success) resLog.error(\"npm install failed\", undefined, { output: r.output });\n }\n }\n }\n\n // --- Mounts ---\n // --- Connectors (filesystem + tool faces) ---\n // The unified ConnectorManager owns the full lifecycle for every connector\n // declared in skaile.yaml — mountable (filesystem-face) and tool-face alike.\n const connectorDeclarations = loadConnectorDeclarations(projectDir);\n let resourceManager: ConnectorManager | null = null;\n\n if (connectorDeclarations.length > 0) {\n resourceManager = new ConnectorManager(projectDir, {\n secrets: secretProvider as any,\n catalogEntries: runtimeAssets.catalogEntries,\n tokenMediator,\n preMintedSecrets,\n });\n // failOnReadWriteError: a read-write mountable-connector failure means\n // the agent workspace is unusable (e.g. expired SharePoint token leaves\n // the workspace empty). Surface as a session-start error rather than\n // silently degrading to \"agent sees no files.\"\n try {\n const report = await resourceManager.connectAll(connectorDeclarations, {\n failOnReadWriteError: true,\n });\n for (const r of report.results) {\n if (r.connected) {\n resLog.info(\"connector ok\", { id: r.id, mountPath: r.mountPath });\n } else {\n resLog.error(\"connector failed\", undefined, { id: r.id, error: r.error });\n }\n }\n } catch (err) {\n // Log the full per-connector status from the report carried on the\n // error before re-throwing so operators can see which connected.\n if (err instanceof ConnectorStartupError) {\n for (const r of err.report.results) {\n if (r.connected) {\n resLog.info(\"connector ok\", { id: r.id, mountPath: r.mountPath });\n } else {\n resLog.error(\"connector failed\", undefined, { id: r.id, error: r.error });\n }\n }\n }\n throw err;\n }\n }\n\n // Build the system prompt section (mount paths + connector tools).\n const resourcePromptSection = resourceManager\n ? buildConnectorPromptSection(resourceManager)\n : \"\";\n\n // Build MCP servers (claude-sdk only). Phase 2d: structured logging.\n const mcpLog = createLogger({\n kind: \"mcp\",\n subkind: \"wiring\",\n instance: sessionMeta?.sessionId ?? \"no-session\",\n });\n\n let mcpServers: Record<string, unknown> | undefined;\n let workspacePluginToShutdown: { shutdown(): Promise<void> } | null = null;\n\n if (driverType === \"claude-sdk\") {\n // Connector tools (only if connectors exist)\n if (resourceManager) {\n const connectorsLog = createLogger({ kind: \"mcp\", subkind: \"skaile-connectors\" });\n try {\n const server = await buildSdkConnectorTools(resourceManager, { z });\n if (server) {\n mcpServers = { \"skaile-connectors\": server };\n connectorsLog.info(\"server constructed\", {\n connectorCount: resourceManager.listConnectors().length,\n });\n } else {\n connectorsLog.debug(\"server skipped (no tools to expose)\");\n }\n } catch (err) {\n connectorsLog.error(\"server construction failed\", err);\n throw err;\n }\n }\n\n // Workspace plugin — always inject for claude-sdk.\n // `onLog` is intentionally NOT passed: structured emission via\n // `WorkspacePlugin.log` already reaches the caller's `onLog` through the\n // OnLogBridgeSink installed by the runner bootstrap. Passing `onLog` here\n // would cause double-emit for plugin lifecycle events (booted, warning).\n const workspacePlugin = new WorkspacePlugin({\n projectDir,\n connectorManager: resourceManager ?? undefined,\n driver: driverType,\n provider: sessionMeta?.provider,\n model: sessionMeta?.model,\n });\n const wsServer = await workspacePlugin.buildWorkspaceMcpServer();\n if (wsServer) {\n mcpServers = { ...(mcpServers ?? {}), \"skaile-workspace\": wsServer };\n }\n workspacePluginToShutdown = workspacePlugin;\n\n // Declarative MCP servers from skaile.yaml `mcp_servers:` section\n const mcpDeclarations = loadMcpServerDeclarations(projectDir);\n mcpLog.debug(\"loaded MCP declarations\", { count: mcpDeclarations.length });\n\n // One cache per resources.ts pass — dedupes nix path-info shell-outs for\n // multiple declarations that share the same flake attr.\n const recipeCache = createRecipeCache();\n const nixFlakeRef = process.env.SKAILE_NIX_FLAKE_REF ?? \"/etc/skaile/flake\";\n\n for (const decl of mcpDeclarations) {\n if (RESERVED_MCP_SERVER_IDS.has(decl.id)) {\n mcpLog.warn(\"MCP server skipped: reserved id\", { id: decl.id });\n continue;\n }\n\n // Recipe resolution: substitute ${recipe:<id>...} markers before spawn.\n let resolvedDecl = decl;\n if (decl.recipe) {\n // For BYO-flake recipes `attr` is the in-flake target (\"default\") and\n // may be absent on the decl; `flake` is the meaningful log key. Hoisted\n // above the try so the catch block can log it too.\n const recipeLogKey = decl.recipe.flake\n ? { flake: decl.recipe.flake }\n : { attr: decl.recipe.attr };\n try {\n // Lookup key: legacy platform-flake recipes resolve by their `attr`\n // (e.g. `mcps.excel`); BYO-flake recipes all build `#default`, so\n // `attr` is NOT a unique key — resolve by `mcps.<id>` instead, which\n // is the key the host-side builder writes into the recipe map.\n // The legacy `attr ?? mcps.<id>` fallback is dead code for recipes\n // emitted by mcpDeclFromCatalogEntry (it always sets `attr` for the\n // legacy form); it only guards a hand-built `{ recipe: {} }`, which\n // then misses the map and is skipped by the path check below.\n const recipeKey = decl.recipe.flake\n ? `mcps.${decl.id}`\n : (decl.recipe.attr ?? `mcps.${decl.id}`);\n const outPath = resolveRecipePath(nixFlakeRef, recipeKey, recipeCache);\n // Build a single-entry map keyed by this declaration's id.\n const outPaths: ReadonlyMap<string, string> = new Map([[decl.id, outPath]]);\n\n const resolvedCommand = decl.command\n ? substituteRecipeTemplating(decl.command, outPaths)\n : decl.command;\n const resolvedArgs = decl.args?.map((a) => substituteRecipeTemplating(a, outPaths));\n const resolvedEnv = substituteRecipeMap(decl.env, outPaths);\n\n resolvedDecl = {\n ...decl,\n command: resolvedCommand,\n args: resolvedArgs,\n env: resolvedEnv,\n };\n\n // Warn on any surviving markers (id mismatch in the template)\n const allResolved = [\n resolvedCommand ?? \"\",\n ...(resolvedArgs ?? []),\n ...Object.values(resolvedEnv ?? {}),\n ];\n for (const v of allResolved) {\n if (v.includes(\"${recipe:\")) {\n const recipeLog = createLogger({\n kind: \"mcp\",\n subkind: decl.id,\n instance: \"recipe-resolve\",\n });\n recipeLog.warn(\"unresolved recipe marker after substitution\", {\n value: v,\n declId: decl.id,\n });\n }\n }\n\n // Verify substituted /nix/store paths exist (catches recipes without bin/).\n const missingPaths = validateSubstitutedPaths(resolvedCommand, resolvedArgs);\n if (missingPaths.length > 0) {\n const recipeLog = createLogger({\n kind: \"mcp\",\n subkind: decl.id,\n instance: \"recipe-resolve\",\n });\n recipeLog.error(\"MCP server skipped: substituted path does not exist\", undefined, {\n id: decl.id,\n ...recipeLogKey,\n missing: missingPaths,\n });\n continue;\n }\n\n const recipeLog = createLogger({\n kind: \"mcp\",\n subkind: decl.id,\n instance: \"recipe-resolve\",\n });\n recipeLog.info(\"recipe substitution complete\", {\n ...recipeLogKey,\n outPath,\n });\n } catch (err) {\n // Catch all errors — not just RecipeUnavailableError — so a single\n // broken declaration cannot abort buildAgentResources for the entire\n // session. Log the full error and skip this declaration.\n const recipeLog = createLogger({\n kind: \"mcp\",\n subkind: decl.id,\n instance: \"recipe-resolve\",\n });\n recipeLog.error(\"MCP server skipped: recipe resolution failed\", err, {\n id: decl.id,\n ...recipeLogKey,\n flakeRef: nixFlakeRef,\n });\n continue;\n }\n }\n\n const serverConfig = toSdkMcpServerConfig(\n resolvedDecl,\n secretProvider as SecretProviderLike | undefined,\n );\n if (serverConfig) {\n mcpServers = { ...(mcpServers ?? {}), [decl.id]: serverConfig };\n const declLog = createLogger({ kind: \"mcp\", subkind: decl.id });\n declLog.info(\"MCP server registered\", {\n transport: decl.transport ?? \"stdio\",\n ...(decl.transport === \"stdio\" || !decl.transport\n ? { command: resolvedDecl.command, args: resolvedDecl.args }\n : { url: decl.url }),\n });\n } else {\n mcpLog.error(\"MCP server config invalid (translation returned null)\", undefined, {\n id: decl.id,\n transport: decl.transport,\n });\n }\n }\n }\n\n // If neither connectors nor workspace-plugin produced anything useful\n // for a non-claude-sdk driver, return noop to avoid overhead.\n if (!resourceManager && driverType !== \"claude-sdk\") return noopResult;\n\n // Deferred watch setup — called by the consumer after the transport is listening\n // so that slow filesystem scans (e.g. large node_modules over Docker bind mounts)\n // don't block session startup.\n const startWatching = () => {\n if (resourceManager && watch?.onFileChanged) {\n const dedupTtlMs = watch.dedupTtlMs ?? 500;\n const recentlyEmitted = new Map<string, number>();\n\n resourceManager.watchAll((connectorId: string, event: ConnectorChangeEvent) => {\n const dedupKey = `${connectorId}:${event.path}`;\n const now = Date.now();\n const lastEmit = recentlyEmitted.get(dedupKey);\n if (lastEmit && now - lastEmit < dedupTtlMs) return;\n recentlyEmitted.set(dedupKey, now);\n\n if (recentlyEmitted.size > 200) {\n for (const [key, ts] of recentlyEmitted) {\n if (now - ts > dedupTtlMs) recentlyEmitted.delete(key);\n }\n }\n\n watch.onFileChanged!(connectorId, event);\n });\n }\n };\n\n const dispose = async () => {\n if (workspacePluginToShutdown) {\n try {\n await workspacePluginToShutdown.shutdown();\n } catch {\n /* best-effort */\n }\n }\n try {\n await resourceManager?.disconnectAll();\n } catch {\n /* best-effort */\n }\n };\n\n return {\n resourceManager,\n resourcePromptSection,\n mcpServers,\n runtimeAssets,\n dispose,\n startWatching,\n };\n } catch {\n // @skaile/workspaces/connectors not installed or skaile.yaml parse error — resources disabled\n return noopResult;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/** IDs reserved for built-in MCP servers. Declarative servers must not shadow these. */\nconst RESERVED_MCP_SERVER_IDS = new Set([\"skaile-connectors\", \"skaile-workspace\"]);\n\n/**\n * Minimal interface for secret resolution — avoids a hard import of\n * `@skaile/workspaces/connectors` just for the SecretProvider type.\n */\ninterface SecretProviderLike {\n resolve(ref: string): string | undefined;\n}\n\n/**\n * Resolve secret references (`env:VAR`, `forge:KEY`, etc.) in a string-keyed\n * record. Returns a new record with resolved values; entries that fail to\n * resolve are passed through unchanged.\n */\nfunction resolveRecordSecrets(\n record: Record<string, string>,\n secrets: SecretProviderLike | undefined,\n): Record<string, string> {\n if (!secrets) return record;\n const resolved: Record<string, string> = {};\n for (const [k, v] of Object.entries(record)) {\n resolved[k] = secrets.resolve(v) ?? v;\n }\n return resolved;\n}\n\n/**\n * Convert a `McpServerDeclaration` from `skaile.yaml` into the SDK's\n * `McpServerConfig` shape accepted by `AgentConfig.mcpServers`.\n *\n * Secret references in `env` and `headers` values (e.g. `env:MY_TOKEN`) are\n * resolved through the session's `SecretProvider` chain when available.\n *\n * Returns `null` when the declaration is missing required fields for its\n * transport type (e.g. no `command` for a stdio server).\n */\nfunction toSdkMcpServerConfig(\n decl: McpServerDeclaration,\n secrets?: SecretProviderLike,\n): Record<string, unknown> | null {\n const transport = decl.transport ?? \"stdio\";\n\n if (transport === \"stdio\") {\n if (!decl.command) return null;\n const cfg: Record<string, unknown> = { type: \"stdio\", command: decl.command };\n if (decl.args?.length) cfg.args = decl.args;\n if (decl.env && Object.keys(decl.env).length > 0) {\n cfg.env = resolveRecordSecrets(decl.env, secrets);\n }\n return cfg;\n }\n\n if (transport === \"sse\" || transport === \"http\") {\n if (!decl.url) return null;\n const cfg: Record<string, unknown> = { type: transport, url: decl.url };\n if (decl.headers && Object.keys(decl.headers).length > 0) {\n cfg.headers = resolveRecordSecrets(decl.headers, secrets);\n }\n return cfg;\n }\n\n return null;\n}\n","/**\n * session-builder.ts\n *\n * Shared `createAgentSession()` factory — extracts the common agent\n * initialisation sequence from agent.ts (REPL), run-flow.ts (flow), and\n * serve.ts (WebSocket server) into a single reusable module.\n *\n * The shared setup pipeline:\n * 1. resolveSettings → driverType, provider, model, apiKey\n * 2. loadAgentManifest → manifest (model, maxTurns, tools, name)\n * 3. buildAgentResources → resourceManager, resourcePromptSection, mcpServers, dispose\n * 4. Load workspace config, build contextSection + environmentSection, load prompt-extensions\n * 5. assembleSystemPrompt (context + env + resources + extensions + additional sections)\n * 6. Resolve maxTurns (config override wins over manifest)\n * 7. createDriver (NOT started — caller calls driver.start() when ready)\n *\n * Agent identity (SOUL.md, RULES.md, knowledge/) is never assembled here.\n * It is rendered at install time by the renderers in asset-manager and read\n * natively by each backend driver at runtime.\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { resolve as resolvePath } from \"node:path\";\nimport { createDriver } from \"@skaile/workspaces/bridge\";\nimport { resolveApiKey, resolveSettings, resolveSkWorkspaceConfig } from \"@skaile/workspaces/core\";\nimport { createLogger } from \"@skaile/workspaces/core/logging\";\nimport type { AgentDriver, BridgeCapabilityHooks } from \"@skaile/workspaces/bridge\";\nimport type {\n AgentManifest,\n RuntimeAssetsResult,\n SkWorkspaceConfig,\n} from \"@skaile/workspaces/core\";\nimport type { TelemetryProvider, Trace } from \"@skaile/workspaces/telemetry\";\nimport type { SystemPromptSection } from \"@skaile/workspaces/types\";\nimport { buildContextSection } from \"./context.js\";\nimport { resolveAgentComposition, type ResolvedComposition } from \"./composition/bootstrap.js\";\nimport { buildEnvironmentSection } from \"./environment.js\";\nimport { loadAgentManifest } from \"./manifest.js\";\nimport { assembleSystemPrompt } from \"./prompt-assembly.js\";\nimport { buildAgentResources, type ResourceWatchCallbacks } from \"./resources.js\";\n\nexport type { ResourceWatchCallbacks };\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * Configuration for creating an agent session.\n *\n * Controls the driver backend, LLM provider and model, agent identity,\n * workspace layout, resource lifecycle, and protocol v2 capability hooks.\n *\n * @docLink packages/runner/dev-guide#flow-execution-turn-based-model\n */\nexport interface AgentSessionConfig {\n projectDir: string;\n /**\n * Agent working directory — where the agent reads/writes files.\n * Defaults to `projectDir` when omitted. Use this to separate the config\n * root (`projectDir` with `skaile.yaml`) from the actual working directory\n * (e.g. when the user is in a subdirectory or has no `skaile.yaml` in their CWD).\n */\n cwd?: string;\n agentDir?: string;\n driver?: string;\n model?: string;\n provider?: string;\n promptsDir?: string;\n projectClaudeMd?: string;\n sessionId?: string;\n resumeSessionId?: string;\n /**\n * Path to a file whose contents are prepended to the system prompt.\n * @deprecated Use `agent.prompt-extensions` in skaile.yaml instead. The runner\n * no longer injects this file's contents.\n */\n externalPromptFile?: string;\n /**\n * Pre-resolved workspace config. Avoids re-reading skaile.yaml when the caller\n * already has it. Optional — falls back to `resolveSkWorkspaceConfig(projectDir)`.\n */\n wsConfig?: SkWorkspaceConfig;\n /**\n * Platform-level maxTurns override. Takes precedence over manifest.runtime.max_turns.\n * Flow/REPL modes omit this field — they use the manifest value only.\n */\n maxTurns?: number;\n /** Thinking mode override. */\n thinking?: \"adaptive\" | \"enabled\" | \"disabled\";\n /** Reasoning effort level override. */\n effort?: \"low\" | \"medium\" | \"high\" | \"max\";\n /** Watch callbacks for filesystem/sync events (serve mode only). */\n watch?: ResourceWatchCallbacks;\n /** Secret provider for connector credential resolution. */\n secretProvider?: unknown;\n /**\n * Pre-resolved API key for the active provider. When supplied, it takes\n * precedence over the env-var lookup performed inside `resolveApiKey()`.\n * Used by `serve.ts` to feed the value from `provision_secrets` straight\n * into `AgentConfig.apiKeys` without writing it to `process.env`.\n */\n apiKey?: string;\n /**\n * Optional callback used by `auth: backend` git connectors to request\n * short-lived access tokens from the platform's credential mediator.\n * Threaded into the `ConnectorManager` constructor so all git connectors in\n * this session share the same mediator.\n */\n tokenMediator?: import(\"@skaile/workspaces/connectors\").TokenMediator;\n /**\n * Pre-minted credential provider populated from the v3 `session_init`\n * envelope's `credentials` map. Threaded into ConnectorManager so that\n * connectors with `auth: backend` find their token in-process instead of\n * paying a `request_access_token` round-trip at mount time.\n *\n * @since 3.0.0\n */\n preMintedSecrets?: import(\"@skaile/workspaces/connectors\").PreMintedSecretProvider;\n /**\n * Platform `AIProviderConfig.id` for the AI credential provisioned into\n * this session. Threaded into `AgentConfig.aiProviderConfigId` so that\n * driver recreates (tier-1 native SDK resume, subagents, etc.) preserve\n * the link to the platform mediator. The driver itself does not consume\n * this field; only the runner's 401-mediation handler reads it.\n */\n aiProviderConfigId?: string;\n /**\n * Optional auth-refresh callback threaded into the bridge driver. Invoked\n * by the driver when the underlying agent surfaces an\n * `authentication_error`; in v3 the runner mediates a fresh credential\n * via the `host.refresh_credential` capability and returns a typed\n * {@link CredentialMint}. The driver branches on the discriminator:\n * `ok: true` triggers a one-shot retry of the in-flight prompt;\n * `ok: false` surfaces the original auth error to the caller.\n *\n * Centralising auth-retry inside the driver removes the need to wrap\n * every `driver.prompt(...)` call site (compaction, flow turns, serve\n * handler) with a runner-side retry helper. Standalone CLI / forge\n * sessions leave it undefined.\n *\n * Spec: `_devlog/specs/2026-05-10-deterministic-session-bootstrap.md`\n * § \"Refresh-on-401 routes through host.refresh_credential\".\n */\n onAuthError?: (args: {\n configId: string;\n }) => Promise<import(\"@skaile/workspaces/types\").CredentialMint>;\n /**\n * Additional sections to append to the assembled system prompt.\n * Used by serve mode to inject the component catalog (AVAILABLE_COMPONENTS)\n * without modifying the session builder's core assembly logic.\n */\n additionalPromptSections?: string[];\n onLog?: (line: string) => void;\n /** Telemetry provider for observability. Optional — omit to disable tracing. */\n telemetry?: TelemetryProvider;\n /** Active trace to attach to this session's driver. */\n trace?: Trace;\n /**\n * Protocol v2 capability dispatch hooks built from the runner's\n * CapabilityRegistry. When present, the driver routes registered tool\n * calls through `hooks.invoke()` instead of the legacy in-driver dispatch.\n *\n * @since 2.0.0\n */\n capabilities?: BridgeCapabilityHooks;\n}\n\n/**\n * A configured agent session returned by {@link createAgentSession}.\n *\n * Carries a driver instance (not yet started), connected resource and\n * mount managers, resolved runtime assets, and the parsed agent manifest.\n *\n * @docLink packages/runner/dev-guide#flow-execution-turn-based-model\n */\nexport interface AgentSession {\n /** Driver configured but NOT started. Caller must call driver.start(). */\n driver: AgentDriver;\n /** Connected ConnectorManager — null if no connectors declared. any intentional (optional dep). */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n resourceManager: any | null;\n /**\n * Resolved runtime assets — catalog entries, implicit refs, npm deps,\n * warnings, plus refresh() / findEntry() helpers. Live-update paths\n * (add_resource, configure) hold this reference and call refresh() when\n * a new repository is cloned or driver installed mid-session.\n */\n runtimeAssets: RuntimeAssetsResult | null;\n /**\n * Resolved composition — inline blocks (already injected into systemPrompt)\n * and discoverable entries (caller registers these with CapabilityRegistry).\n * Null when the agent has no `composes:` field.\n */\n composition: ResolvedComposition | null;\n /** Parsed agent.yaml manifest — model, maxTurns, tools, name. */\n manifest: AgentManifest | undefined;\n /** Active driver type string ('omp' | 'claude-sdk'). */\n driverType: string;\n provider: string | undefined;\n model: string | undefined;\n /** Disconnect all connectors, unmount all mounts, and stop watchers. */\n dispose: () => Promise<void>;\n /** Start filesystem and connector watchers. Call after transport is listening. */\n startWatching: () => void;\n /** Telemetry provider for this session (noop if not configured). */\n telemetry?: TelemetryProvider;\n /**\n * Labeled per-section breakdown of the system prompt, in the same\n * order assembleSystemPrompt consumed them. Multi-entry sections\n * (prompt-extensions, composition, additional) appear as repeated\n * entries with `source` set.\n *\n * Consumed by serve.ts's emitSystemPromptComposed helper to emit\n * `system_prompt_composed` events to the platform.\n * @since 2026-05\n */\n systemPromptSections: SystemPromptSection[];\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Create an agent session by resolving settings, loading the agent\n * manifest, building resources (connectors, mounts, MCP servers),\n * and creating the driver.\n *\n * The returned driver is NOT started — the caller must call\n * `driver.start()` after optionally attaching event handlers.\n *\n * @param config - Session configuration\n * @returns A fully configured AgentSession ready for start()\n * @docLink packages/runner/dev-guide#flow-execution-turn-based-model\n */\nexport async function createAgentSession(config: AgentSessionConfig): Promise<AgentSession> {\n const {\n projectDir,\n cwd: cwdOverride,\n agentDir,\n driver: driverOverride,\n model: modelOverride,\n provider: providerOverride,\n sessionId,\n resumeSessionId,\n externalPromptFile,\n wsConfig: wsConfigOverride,\n maxTurns: maxTurnsOverride,\n watch,\n secretProvider,\n onLog,\n telemetry,\n trace,\n } = config;\n\n // Agent working directory — defaults to projectDir when not explicitly set.\n const agentCwd = cwdOverride ?? projectDir;\n\n const sessionLog = createLogger({\n kind: \"runner\",\n subkind: \"session\",\n instance: sessionId ?? \"no-session\",\n });\n\n // Step 1: resolve driver/model/provider/apiKey\n const settings = await resolveSettings(projectDir, {\n driver: driverOverride,\n provider: providerOverride,\n model: modelOverride,\n });\n const driverType = settings.driver ?? \"omp\";\n const provider = settings.provider;\n const model = settings.model;\n // Explicit `config.apiKey` wins over the env/settings cascade — used by\n // serve.ts to inject the platform-provisioned key without leaking it into\n // `process.env`.\n const apiKey = config.apiKey ?? resolveApiKey(provider ?? \"anthropic\", settings);\n\n // Step 2: load agent manifest (model, maxTurns, tools, name)\n const manifest = agentDir ? await loadAgentManifest(agentDir) : undefined;\n\n // Step 3: build resources (mounts + connectors lifecycle)\n const {\n resourceManager,\n resourcePromptSection,\n mcpServers,\n runtimeAssets,\n dispose,\n startWatching,\n } = await buildAgentResources(\n projectDir,\n driverType,\n onLog,\n watch,\n secretProvider,\n {\n provider,\n model,\n sessionId,\n },\n config.tokenMediator,\n config.preMintedSecrets,\n );\n\n // Step 4: resolve workspace config + build context/environment sections + load extensions\n const wsConfig = wsConfigOverride ?? resolveSkWorkspaceConfig(projectDir);\n const contextSection = buildContextSection(wsConfig.agent?.context);\n // Free-form user-authored prompt — placed immediately after the platform\n // context section. Empty / undefined values are dropped by assembleSystemPrompt\n // (filters falsies via `!!p`) so we skip an explicit guard here.\n const userPromptSection = wsConfig.agent?.prompt?.trim();\n const environmentSection = await buildEnvironmentSection(projectDir);\n const promptExtensions = loadPromptExtensions(\n wsConfig.agent?.[\"prompt-extensions\"],\n projectDir,\n sessionLog,\n );\n\n if (externalPromptFile) {\n sessionLog.warn(\n \"externalPromptFile is deprecated and no longer injected; use agent.prompt-extensions in skaile.yaml instead\",\n );\n }\n\n // Step 4.5: resolve agent composition (composes: field)\n // Produces inline blocks (injected into system prompt below) and discoverable\n // entries (caller registers these with CapabilityRegistry in serve.ts).\n let composition: ResolvedComposition | null = null;\n if (agentDir && manifest?.composes?.length) {\n composition = await resolveAgentComposition({\n agentDir,\n manifest,\n projectDir,\n log: sessionLog,\n });\n } else if (manifest?.composes?.length && !agentDir) {\n sessionLog.debug(\"skipping composition resolution — no agentDir available\");\n }\n\n // Step 5: assemble systemPrompt — context + prompt + env + resources + extensions + composition + additional\n // Agent identity (SOUL/RULES/knowledge) is NOT included here — it is rendered at install time\n // by the renderers in asset-manager and read natively by each backend driver at runtime.\n // Composition inline blocks ARE included here — they are the v2 equivalent of identity injection\n // for agents that use `composes:` (replaces the legacy persona/rules/knowledge fields).\n // The userPromptSection (free-form `agent.prompt`) sits between context and environment per\n // the platform-agent-prompt design spec (2026-05-13).\n const compositionBlocks = composition?.inlineBlocks ?? [];\n const additionalSections = config.additionalPromptSections ?? [];\n\n // Labeled per-section breakdown — order matches the assembleSystemPrompt input.\n // assembleSystemPrompt filters falsies; we mirror that here so only non-empty\n // sections appear in the breakdown emitted to the platform.\n const systemPromptSections: SystemPromptSection[] = [];\n if (contextSection) systemPromptSections.push({ label: \"context\", value: contextSection });\n if (userPromptSection) systemPromptSections.push({ label: \"prompt\", value: userPromptSection });\n if (environmentSection)\n systemPromptSections.push({ label: \"environment\", value: environmentSection });\n if (resourcePromptSection)\n systemPromptSections.push({ label: \"resources\", value: resourcePromptSection });\n for (const ext of promptExtensions) {\n systemPromptSections.push({\n label: \"prompt-extensions\",\n value: ext.value,\n source: ext.source,\n });\n }\n for (const block of compositionBlocks) {\n // InlineBlock (composition/types.ts) carries `ref` as the identifying field\n // (asset ref string like \"skill:foo\" or \"agent:bar\"); no separate `id`/`source` field.\n systemPromptSections.push({\n label: \"composition\",\n value: block.content,\n source: block.ref,\n });\n }\n additionalSections.forEach((value, idx) => {\n // additionalPromptSections is string[] today — no per-entry source label\n // available, so we synthesize a stable index-based descriptor.\n systemPromptSections.push({\n label: \"additional\",\n value,\n source: `additional[${idx}]`,\n });\n });\n\n const systemPrompt = assembleSystemPrompt([\n contextSection,\n userPromptSection,\n environmentSection,\n resourcePromptSection,\n ...promptExtensions.map((e) => e.value),\n ...compositionBlocks.map((b) => b.content),\n ...additionalSections,\n ]);\n\n // Log the assembled system prompt so it can be inspected via container logs.\n // No secrets flow through this string: API keys live in `apiKeys`, connector\n // credentials are resolved by the secret provider. Set SKAILE_LOG_SYSTEM_PROMPT=0\n // to suppress.\n if (process.env.SKAILE_LOG_SYSTEM_PROMPT !== \"0\") {\n const length = systemPrompt?.length ?? 0;\n sessionLog.debug(\"assembled system prompt\", { length });\n sessionLog.debug(\"system prompt content\", { content: systemPrompt ?? \"(empty)\" });\n }\n\n // Step 5b: resolve thinking/effort — explicit config wins over workspace config\n const thinking =\n config.thinking ?? (wsConfig.agent_config?.default?.thinking as AgentSessionConfig[\"thinking\"]);\n const effort =\n config.effort ?? (wsConfig.agent_config?.default?.effort as AgentSessionConfig[\"effort\"]);\n\n // Step 6: resolve maxTurns — platform override wins over manifest\n const maxTurns = maxTurnsOverride ?? manifest?.runtime?.max_turns;\n\n // Step 7: create driver (NOT started)\n // Driver CWD is the agent working directory (may differ from config root).\n const driver = await createDriver(driverType, {\n cwd: agentCwd,\n provider,\n model: model ?? manifest?.model?.preferred,\n maxTurns,\n apiKeys: apiKey ? { [provider ?? \"anthropic\"]: apiKey } : undefined,\n systemPrompt,\n tools: manifest?.tools,\n ...(thinking ? { thinking } : {}),\n ...(effort ? { effort } : {}),\n ...(sessionId ? { sessionId } : {}),\n ...(resumeSessionId ? { resumeSessionId } : {}),\n ...(mcpServers ? { mcpServers } : {}),\n // Protocol v2 capability dispatch hooks. When provided, the driver builds\n // a synthetic `skaile-capabilities` MCP server alongside any existing\n // mcpServers so capability invocations route through the registry's\n // `invoke()` (which logs + validates + handles fire-and-forget / render).\n ...(config.capabilities ? { capabilities: config.capabilities } : {}),\n ...(config.aiProviderConfigId ? { aiProviderConfigId: config.aiProviderConfigId } : {}),\n ...(config.onAuthError ? { onAuthError: config.onAuthError } : {}),\n // Always forward agentDir/agentName for native identity handling\n ...(agentDir ? { agentDir, agentName: manifest?.name } : {}),\n });\n\n // Attach telemetry to driver if provided\n if (telemetry && trace) {\n driver.setTelemetry(telemetry, trace);\n }\n\n return {\n driver,\n resourceManager,\n runtimeAssets,\n composition,\n manifest,\n driverType,\n provider,\n model,\n dispose,\n startWatching,\n telemetry,\n systemPromptSections,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * One loaded prompt-extension file. `source` carries the original relative\n * path from `skaile.yaml` so labeled breakdowns (system_prompt_composed event)\n * can attribute each section to a specific file.\n */\ntype LoadedPromptExtension = { value: string; source: string };\n\n/**\n * Load markdown files declared under `agent.prompt-extensions` in skaile.yaml.\n * Paths are resolved relative to the project root. Missing files are skipped\n * with a warning. Empty files are filtered out.\n */\nfunction loadPromptExtensions(\n paths: string[] | undefined,\n projectDir: string,\n log: ReturnType<typeof createLogger>,\n): LoadedPromptExtension[] {\n if (!paths?.length) return [];\n const result: LoadedPromptExtension[] = [];\n for (const relPath of paths) {\n const absPath = resolvePath(projectDir, relPath);\n if (!existsSync(absPath)) {\n log.warn(\"prompt-extension file not found\", { relPath });\n continue;\n }\n try {\n const content = readFileSync(absPath, \"utf-8\").trim();\n if (content.length > 0) result.push({ value: content, source: relPath });\n } catch (err) {\n log.warn(\"could not read prompt-extension\", {\n relPath,\n error: (err as Error).message,\n });\n }\n }\n return result;\n}\n","/**\n * agent.ts\n *\n * Single-shot agent chat — runs a driver session without a flow.\n * Useful for ad-hoc tasks and skill invocations.\n *\n * The interactive REPL lives at @skaile/workspaces/tui (startRepl).\n */\n\nimport type { AgentEvent, AgentMessage } from \"@skaile/workspaces/bridge\";\nimport { resolveAgentDir } from \"@skaile/workspaces/core\";\nimport { createLogger } from \"@skaile/workspaces/core/logging\";\nimport pc from \"picocolors\";\nimport { bootstrapRunnerLogStore } from \"./logging-bootstrap.js\";\nimport { MarkdownStreamer } from \"./markdown-stream.js\";\nimport { createAgentSession, type AgentSession } from \"./session-builder.js\";\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * Options for the agent REPL session (legacy).\n *\n * @docLink packages/runner/dev-guide#agent-chat-single-shot\n */\nexport interface AgentReplOptions {\n /** GitAgent definition directory (SOUL.md, RULES.md, knowledge/) */\n agentDir?: string;\n /** Project working directory for the agent */\n projectDir: string;\n /** Bridge driver: 'omp' | 'claude-sdk' | 'codex' (default: 'omp') */\n driver?: string;\n /** LLM model override */\n model?: string;\n /** LLM provider override */\n provider?: string;\n /** Path to settings.json for API key resolution */\n settingsFile?: string;\n /** Called for every raw agent event */\n onEvent?: (event: AgentEvent) => void;\n /** Called for log lines */\n onLog?: (line: string) => void;\n /** Prompts directory for deployed command files */\n promptsDir?: string;\n}\n\n/**\n * Options for a single-shot agent chat session.\n *\n * @docLink packages/runner/dev-guide#agent-chat-single-shot\n */\nexport interface AgentChatOptions extends AgentReplOptions {\n /** The message to send */\n message: string;\n /** Optional skill ID — if provided, the skill prompt is prepended */\n skill?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/** Extract printable text from an AgentMessage content field. */\nfunction _extractText(msg: AgentMessage | undefined): string {\n if (!msg) return \"\";\n if (typeof msg.content === \"string\") return msg.content;\n if (Array.isArray(msg.content)) {\n return msg.content\n .filter((b) => b.type === \"text\" && b.text)\n .map((b) => b.text!)\n .join(\"\");\n }\n return \"\";\n}\n\n// ---------------------------------------------------------------------------\n// Styling\n// ---------------------------------------------------------------------------\n\nconst PROMPT_AGENT = `${pc.magenta(pc.bold(\"agent\"))} ${pc.dim(\"▶\")} `;\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Send a single message to an agent and wait for the response.\n * Prints agent output to stdout, then exits.\n * @docLink packages/runner/dev-guide#agent-chat-single-shot\n */\nexport async function runAgentChat(opts: AgentChatOptions): Promise<void> {\n const sessionId = `chat-${Date.now().toString(36)}`;\n const { dispose: disposeLogStore } = bootstrapRunnerLogStore({\n sessionId,\n projectDir: opts.projectDir,\n onLog: opts.onLog,\n });\n const chatLog = createLogger({\n kind: \"runner\",\n subkind: \"session\",\n instance: sessionId,\n });\n // Diagnostic emission goes through chatLog. The user-facing markdown stream\n // and PROMPT_AGENT prefix continue to write directly to stdout — they are\n // agent output, not diagnostics.\n const agentSession = await buildDriver(opts);\n const driver = agentSession.driver;\n\n await driver.start();\n\n let firstChunk = true;\n const mdStream = new MarkdownStreamer();\n driver.on(\"agent-event\", (event: AgentEvent) => {\n opts.onEvent?.(event);\n if (event.type === \"message_update\") {\n const delta = (event as any)._textDelta;\n if (delta) {\n if (firstChunk) {\n process.stdout.write(PROMPT_AGENT);\n firstChunk = false;\n }\n mdStream.write(delta);\n }\n }\n });\n\n let message = opts.message;\n if (opts.skill) {\n message = `Skill: ${opts.skill}\\n\\n${message}`;\n }\n\n try {\n await new Promise<void>((resolve, reject) => {\n const onEvent = (event: AgentEvent) => {\n if (event.type === \"agent_end\") {\n driver.off(\"agent-event\", onEvent);\n mdStream.end();\n process.stdout.write(\"\\n\");\n driver.kill();\n resolve();\n } else if (event.type === \"error\") {\n driver.off(\"agent-event\", onEvent);\n const err = new Error(String((event as any).error));\n chatLog.error(\"agent emitted error event\", err);\n driver.kill();\n reject(err);\n }\n };\n driver.on(\"agent-event\", onEvent);\n driver.prompt(message).catch((err: Error) => {\n driver.off(\"agent-event\", onEvent);\n chatLog.error(\"prompt failed\", err);\n driver.kill();\n reject(err);\n });\n });\n } finally {\n await agentSession.dispose();\n disposeLogStore();\n }\n}\n\n// ---------------------------------------------------------------------------\n// Internal\n// ---------------------------------------------------------------------------\n\n// buildDriver is a thin wrapper — all setup logic lives in createAgentSession.\n// agentDir/agentName are always forwarded to the driver for native identity handling\n// (omp: PI_CODING_AGENT_DIR, claude-sdk: agent option).\nasync function buildDriver(opts: AgentReplOptions): Promise<AgentSession> {\n const agentDir = opts.agentDir ?? resolveAgentDir(opts.projectDir);\n return createAgentSession({\n projectDir: opts.projectDir,\n agentDir,\n driver: opts.driver,\n model: opts.model,\n provider: opts.provider,\n promptsDir: opts.promptsDir,\n onLog: opts.onLog,\n });\n}\n","/**\n * resource-handler.ts — handles resource_request commands from the frontend.\n *\n * Dispatches list/read/write/delete/search operations to the ConnectorManager.\n * Tool-face connectors are served through the manager's CRUD dispatch;\n * filesystem-face (mountable) connectors are served directly from their\n * projected mount directory. Emits resource_response events back through the\n * transport.\n */\n\nimport {\n closeSync,\n openSync,\n readSync,\n readdirSync,\n readFileSync,\n statSync,\n writeFileSync,\n unlinkSync,\n mkdirSync,\n} from \"node:fs\";\nimport { resolve, join, basename, dirname } from \"node:path\";\nimport mime from \"mime\";\nimport type { ConnectorManager } from \"@skaile/workspaces/connectors\";\nimport type {\n AgentEvent,\n ConnectorContent,\n ConnectorRequestCommand,\n} from \"@skaile/workspaces/types\";\n\n// ---------------------------------------------------------------------------\n// Connector resource handler\n// ---------------------------------------------------------------------------\n\n/**\n * Handle a resource_request command by dispatching to the ConnectorManager\n * and emitting a resource_response event.\n * @docLink packages/runner/dev-guide#flow-execution-turn-based-model\n */\nexport async function handleResourceRequest(\n command: ConnectorRequestCommand,\n manager: ConnectorManager,\n emit: (event: AgentEvent) => void,\n): Promise<void> {\n const { requestId, connectorId, operation, path, options, content } = command;\n\n try {\n let data: unknown;\n switch (operation) {\n case \"list\":\n data = await manager.list(\n connectorId,\n path,\n options as import(\"@skaile/workspaces/connectors\").ListOptions | undefined,\n );\n break;\n case \"read\":\n data = await manager.read(connectorId, path!);\n break;\n case \"write\":\n await manager.write(connectorId, path!, content!);\n data = true;\n break;\n case \"delete\":\n data = await manager.delete(connectorId, path!);\n break;\n case \"search\":\n data = await manager.search(\n connectorId,\n path!,\n options as import(\"@skaile/workspaces/connectors\").SearchOptions | undefined,\n );\n break;\n }\n emit({ type: \"resource_response\", requestId, resourceId: connectorId, operation, data });\n } catch (err) {\n emit({\n type: \"resource_response\",\n requestId,\n resourceId: connectorId,\n operation,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n}\n\n// ---------------------------------------------------------------------------\n// Mountable-connector resource handler — serves list/read/write from the\n// projected mount directory of a filesystem-face connector.\n// ---------------------------------------------------------------------------\n\n/** Resolve MIME type for a filename. Falls back to application/octet-stream. */\nfunction getMimeType(filename: string): string {\n return mime.getType(filename) ?? \"application/octet-stream\";\n}\n\n/**\n * Returns true if the file should be served as base64-encoded binary.\n *\n * Uses a byte-level heuristic: reads the first 8KB and checks for null bytes.\n * This correctly handles all code/config formats regardless of MIME type.\n */\nfunction isBinaryFile(filePath: string): boolean {\n try {\n const fd = openSync(filePath, \"r\");\n const buf = Buffer.alloc(8192);\n const bytesRead = readSync(fd, buf, 0, 8192, 0);\n closeSync(fd);\n for (let i = 0; i < bytesRead; i++) {\n if (buf[i] === 0) return true;\n }\n return false;\n } catch {\n return false;\n }\n}\n\n/**\n * Handle a resource request against a filesystem-face (mountable) connector.\n *\n * @docLink packages/runner/dev-guide#flow-execution-turn-based-model\n */\nexport function handleMountResourceRequest(\n command: ConnectorRequestCommand,\n manager: ConnectorManager,\n emit: (event: AgentEvent) => void,\n): void {\n const { requestId, connectorId: mountId, operation, path: reqPath, content } = command;\n\n try {\n const entry = manager.get(mountId);\n const mountPath = entry.handle.mountPath;\n if (!mountPath) {\n throw new Error(`Connector \"${mountId}\" has no projected mount directory`);\n }\n const targetPath = reqPath ? resolve(mountPath, reqPath) : mountPath;\n\n // Safety: prevent path traversal outside mount\n if (!targetPath.startsWith(mountPath)) {\n throw new Error(\"Path traversal outside mount\");\n }\n\n let data: unknown;\n switch (operation) {\n case \"list\": {\n const entries = readdirSync(targetPath, { withFileTypes: true });\n data = entries\n .filter((e) => !e.name.startsWith(\".\"))\n .map((e) => {\n const entryPath = reqPath ? join(reqPath, e.name) : e.name;\n const result: Record<string, unknown> = {\n name: e.name,\n path: entryPath,\n type: e.isDirectory() ? \"directory\" : \"file\",\n };\n if (!e.isDirectory()) {\n try {\n result.size = statSync(join(targetPath, e.name)).size;\n } catch {\n /* best-effort */\n }\n }\n return result;\n });\n break;\n }\n case \"read\": {\n const contentType = getMimeType(basename(targetPath));\n if (isBinaryFile(targetPath)) {\n const buf = readFileSync(targetPath);\n data = {\n data: buf.toString(\"base64\"),\n contentType,\n encoding: \"binary\",\n };\n } else {\n data = {\n data: readFileSync(targetPath, \"utf-8\"),\n contentType,\n encoding: \"utf-8\",\n };\n }\n break;\n }\n case \"write\": {\n mkdirSync(dirname(targetPath), { recursive: true });\n const writeContent =\n typeof content === \"string\"\n ? content\n : ((content as ConnectorContent | undefined)?.data ?? \"\");\n const encoding =\n typeof content === \"string\"\n ? undefined\n : (content as ConnectorContent | undefined)?.encoding;\n if (encoding === \"binary\") {\n writeFileSync(targetPath, Buffer.from(writeContent, \"base64\"));\n } else {\n writeFileSync(targetPath, writeContent, \"utf-8\");\n }\n data = true;\n break;\n }\n case \"delete\": {\n unlinkSync(targetPath);\n data = true;\n break;\n }\n default:\n throw new Error(`Unsupported operation for mount: ${operation}`);\n }\n emit({ type: \"resource_response\", requestId, resourceId: mountId, operation, data });\n } catch (err) {\n emit({\n type: \"resource_response\",\n requestId,\n resourceId: mountId,\n operation,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n}\n","/**\n * Proactive AI-credential refresh scheduler.\n *\n * Holds a single `setTimeout` that fires `PROACTIVE_AI_REFRESH_MARGIN_MS`\n * before the current access token expires, asks the platform mediator for\n * a fresh credential via the caller-supplied `refresh` callback, and\n * re-arms itself against the new expiry. Pure logic — does not invoke\n * `host.refresh_credential` itself; the caller threads that side-effect\n * through `refresh`.\n *\n * Pairs with the bridge-side `failTurn` deferral that suppresses\n * downstream auth-error events when a self-heal is about to run: the\n * proactive timer is the primary prevention of in-container 401s, the\n * reactive 401 path is the safety net.\n *\n * Spec: `_devlog/specs/2026-05-07-unified-credential-mediation.md`\n * § \"Proactive refresh\" (added 2026-05-20).\n *\n * @docLink packages/runner/dev-guide#ai-credential-mediation\n */\n\n/**\n * Safety margin between the scheduled refresh and the token's declared\n * expiry. Default 5 minutes: long enough that any in-flight prompt at\n * fire time still has a usable token, short enough that a server clock\n * skew of a few seconds does not push the fire-time past expiry.\n */\nexport const PROACTIVE_AI_REFRESH_MARGIN_MS = 5 * 60 * 1000;\n\n/**\n * Caller-supplied side effects the scheduler invokes.\n *\n * - `refresh()` runs the actual mint round-trip; returns the new ISO\n * expiry on success (or `null` for static tokens) and `undefined` on\n * failure (the scheduler stays idle until the next external arming).\n * - `log()` receives operator-facing single-line strings.\n * - `now()` is dependency-injected for deterministic timer tests; defaults\n * to `Date.now`.\n * - `setTimeoutImpl` / `clearTimeoutImpl` are injected for fake-timer\n * tests; default to the host's `setTimeout` / `clearTimeout`.\n */\nexport interface AiCredentialRefreshDeps {\n refresh: () => Promise<string | null | undefined>;\n log: (line: string) => void;\n now?: () => number;\n setTimeoutImpl?: (handler: () => void, ms: number) => { unref?: () => void };\n clearTimeoutImpl?: (handle: { unref?: () => void }) => void;\n marginMs?: number;\n}\n\nexport interface AiCredentialRefreshScheduler {\n /**\n * Arm the timer for `expiresAtIso - marginMs`. Cancels any prior pending\n * fire. `null` / `undefined` cancels without re-arming (static PAT\n * semantics). If the fire-time has already passed, runs `refresh()` on\n * the next tick.\n */\n schedule(expiresAtIso: string | null | undefined): void;\n /** Cancel any pending fire. Idempotent. */\n cancel(): void;\n /**\n * Whether a timer is currently armed. Exposed for tests; production\n * callers should not need this.\n */\n isPending(): boolean;\n}\n\n/**\n * Build a scheduler bound to the supplied dependencies. One scheduler\n * per session — the runner constructs it once at session_init and\n * disposes via `cancel()` during cleanup.\n */\nexport function createAiCredentialRefreshScheduler(\n deps: AiCredentialRefreshDeps,\n): AiCredentialRefreshScheduler {\n const now = deps.now ?? (() => Date.now());\n const setTimeoutImpl =\n deps.setTimeoutImpl ??\n ((handler: () => void, ms: number) => {\n const handle = setTimeout(handler, ms);\n // Node + Bun timers expose `unref` so this scheduler does not pin\n // the event loop alive.\n return handle as unknown as { unref?: () => void };\n });\n const clearTimeoutImpl =\n deps.clearTimeoutImpl ??\n ((handle: { unref?: () => void }) => {\n clearTimeout(handle as unknown as ReturnType<typeof setTimeout>);\n });\n const marginMs = deps.marginMs ?? PROACTIVE_AI_REFRESH_MARGIN_MS;\n\n let timer: { unref?: () => void } | null = null;\n\n function cancel(): void {\n if (timer !== null) {\n clearTimeoutImpl(timer);\n timer = null;\n }\n }\n\n async function fire(): Promise<void> {\n timer = null;\n let next: string | null | undefined;\n try {\n next = await deps.refresh();\n } catch (err) {\n deps.log(\n `[ai-credential-refresh] refresh threw: ${err instanceof Error ? err.message : String(err)}; reactive 401 path remains as safety net`,\n );\n return;\n }\n if (next === undefined) {\n deps.log(\n \"[ai-credential-refresh] refresh returned no expiry; reactive 401 path remains as safety net\",\n );\n return;\n }\n schedule(next);\n }\n\n function schedule(expiresAtIso: string | null | undefined): void {\n cancel();\n if (!expiresAtIso) {\n // Static token (PAT) or unknown expiry — nothing to schedule.\n return;\n }\n const expiresAtMs = Date.parse(expiresAtIso);\n if (!Number.isFinite(expiresAtMs)) return;\n const delayMs = expiresAtMs - now() - marginMs;\n if (delayMs <= 0) {\n deps.log(\n `[ai-credential-refresh] token within ${marginMs / 1000}s of expiry; refreshing now`,\n );\n timer = setTimeoutImpl(() => {\n void fire();\n }, 0);\n } else {\n deps.log(\n `[ai-credential-refresh] scheduled in ${Math.round(delayMs / 1000)}s (expiresAt=${expiresAtIso})`,\n );\n timer = setTimeoutImpl(() => {\n void fire();\n }, delayMs);\n }\n timer.unref?.();\n }\n\n return {\n schedule,\n cancel,\n isPending: () => timer !== null,\n };\n}\n","/**\n * Built-in framework capabilities. The runner registers these at boot via\n * {@link bootstrapCapabilityRegistry} so the LLM always has a discovery\n * surface for what is available in the session.\n *\n * All built-ins are agent-side, `origin: { kind: 'framework' }`, and\n * synchronous queries against the registry — they have no side-effects\n * outside the registry itself.\n *\n * @category Runtime\n * @since 2.0.0\n */\nimport * as z from \"zod\";\nimport type { Capability } from \"@skaile/workspaces/types\";\nimport type { CapabilityRegistry } from \"./capability-registry.js\";\nimport { defineCapability, type DefinedCapability } from \"./define-capability.js\";\n\n/**\n * Tokenize a free-text query and rank capabilities by case-insensitive\n * substring match count across `name`, `description`, and `promptFragment`.\n * Returns the top `limit` results, descending by score.\n */\nfunction keywordSearch(capabilities: Capability[], query: string, limit: number): Capability[] {\n const tokens = query\n .toLowerCase()\n .split(/\\s+/)\n .filter((t) => t.length > 0);\n if (tokens.length === 0) return capabilities.slice(0, limit);\n\n const scored = capabilities\n .map((cap) => {\n const haystack = [cap.name, cap.description, cap.promptFragment ?? \"\"]\n .join(\" \")\n .toLowerCase();\n let score = 0;\n for (const token of tokens) {\n if (haystack.includes(token)) score += 1;\n }\n return { cap, score };\n })\n .filter((x) => x.score > 0)\n .sort((a, b) => b.score - a.score);\n\n return scored.slice(0, limit).map((x) => x.cap);\n}\n\n/**\n * Build the three built-in discovery capabilities. They close over the\n * registry so the handlers stay in sync with mid-session register /\n * deregister events.\n *\n * @category Runtime\n * @since 2.0.0\n * @docLink packages/runner/capabilities#built-in-discovery-capabilities\n */\nexport function builtinCapabilities(registry: CapabilityRegistry): DefinedCapability[] {\n const listFilterSchema = z.strictObject({\n side: z.enum([\"client\", \"agent\"]).optional(),\n originKind: z\n .enum([\"framework\", \"client\", \"agent\", \"flow\", \"skill\", \"mcp\", \"connector\", \"mount\"])\n .optional(),\n scope: z.enum([\"session\", \"turn\"]).optional(),\n });\n return [\n defineCapability({\n name: \"__capabilities.list\",\n displayName: \"List capabilities\",\n description:\n \"List available capabilities in this session. Optionally filter by side, origin kind, or scope.\",\n side: \"agent\",\n origin: { kind: \"framework\" },\n kind: \"query\",\n userInvokable: false,\n input: listFilterSchema,\n handler: async (args) =>\n registry.list({\n side: args.side,\n origin: args.originKind,\n scope: args.scope,\n }),\n }),\n defineCapability({\n name: \"__capabilities.search\",\n displayName: \"Search capabilities\",\n description:\n \"Keyword search across capability names, descriptions, and prompt fragments. Returns the top matches by score (substring match count).\",\n side: \"agent\",\n origin: { kind: \"framework\" },\n kind: \"query\",\n userInvokable: false,\n input: z.strictObject({\n query: z.string(),\n limit: z.number().int().positive().optional(),\n }),\n handler: async ({ query, limit }) => keywordSearch(registry.list(), query, limit ?? 10),\n }),\n defineCapability({\n name: \"__capabilities.describe\",\n displayName: \"Describe capability\",\n description: \"Return the full Capability descriptor for a single capability by name.\",\n side: \"agent\",\n origin: { kind: \"framework\" },\n kind: \"query\",\n userInvokable: false,\n input: z.strictObject({ name: z.string() }),\n handler: async ({ name }) => {\n const cap = registry.resolve(name);\n if (!cap) return null;\n // Strip runtime-only fields by going through the wire-format `list`\n // and finding-by-name; cheaper than another method on the registry.\n const wire = registry.list().find((c) => c.name === name);\n return wire ?? null;\n },\n }),\n ];\n}\n\n/**\n * Register all framework built-ins onto a registry. Idempotent — the\n * registry's `register` is keyed by name and overwrites prior entries with\n * the same name.\n *\n * @category Runtime\n * @since 2.0.0\n * @docLink packages/runner/capabilities#built-in-discovery-capabilities\n */\nexport function bootstrapCapabilityRegistry(registry: CapabilityRegistry): void {\n for (const cap of builtinCapabilities(registry)) {\n registry.register(cap, \"agent\");\n }\n}\n","/**\n * `CapabilityRegistry` — single per-session registry of {@link Capability}s.\n *\n * The registry is the source of truth for everything the LLM can invoke\n * during a session. Both the platform (via `ConfigureCommand.capabilities`\n * and {@link CapabilityRegisterCommand}) and the runtime (skill loaders,\n * flow adapters, MCP/connector/mount surfaces) call {@link register}; the\n * bridge driver pulls the LLM tool list via {@link composeLLMTools}.\n *\n * Trust enforcement: each call to {@link register} carries the registering\n * `source` (`'client'` or `'agent'`); the registry rejects mismatches such\n * as the agent claiming a `'client'` origin or vice-versa, logging a warning\n * and dropping the capability.\n *\n * Per-invocation logging: {@link invoke} constructs a\n * `createLogger({kind: 'capability', subkind: origin.kind, instance: name})`\n * and threads it through {@link HandlerContext} so handler output lands under\n * the `capability:<origin>:<name>` slice.\n *\n * Hibernation: {@link serialize} / {@link hydrate} round-trip the wire-format\n * capabilities. Agent-side capabilities (skill / flow / mcp / connector /\n * mount) are expected to re-register from their original sources on wake;\n * client-side capabilities are pushed back via\n * {@link ConfigureCommandV2 ConfigureCommand} from the platform.\n *\n * @category Runtime\n * @since 2.0.0\n */\nimport { createHash } from \"node:crypto\";\nimport type {\n Capability,\n CapabilityAudience,\n CapabilityOrigin,\n Logger,\n} from \"@skaile/workspaces/types\";\nimport { createLogger } from \"@skaile/workspaces/core/logging\";\nimport type { DefinedCapability, HandlerContext } from \"./define-capability.js\";\n\n/**\n * Default audience scope applied when a {@link Capability} omits `audience`.\n * Matches the v2.x behaviour where every registered capability appears in\n * both the LLM tool list and the command palette.\n */\nconst DEFAULT_AUDIENCE: readonly CapabilityAudience[] = [\"llm\", \"user\"];\n\nfunction audienceOf(cap: Capability): readonly CapabilityAudience[] {\n return cap.audience ?? DEFAULT_AUDIENCE;\n}\n\nfunction hasAudience(cap: Capability, target: CapabilityAudience): boolean {\n return audienceOf(cap).includes(target);\n}\n\n/**\n * Function shape for the platform-bound capability invoker.\n *\n * The runner uses this to dispatch `host.*` capability invocations (e.g.\n * `host.refresh_credential`, `host.audit`, `host.notify_user`) over the\n * transport and await the matching `CapabilityResultCommand`. Implementations\n * own the wire serialization and the per-call pending map.\n *\n * The result value is the capability's domain payload (already\n * deserialised; for `host.refresh_credential` this is a `CredentialMint`).\n * Capability-dispatch infrastructure failures (timeout, schema validation,\n * transport disconnect) are thrown as `Error` so callers can distinguish\n * them from domain failures encoded in the payload.\n *\n * @category Runtime\n * @since 3.0.0\n * @docLink packages/runner/capabilities#remote-invoker\n */\nexport type RemoteCapabilityInvoker = (name: string, input: unknown) => Promise<unknown>;\n\n/**\n * Minimal LLM tool descriptor consumed by bridge drivers. Drivers translate\n * this into the provider-specific tool spec (Claude tool definition, OpenAI\n * function spec, etc.) at registration time.\n *\n * Only the fields needed for tool registration are surfaced here; runtime\n * dispatch flows through {@link CapabilityRegistry.invoke}.\n *\n * @category Runtime\n * @since 2.0.0\n * @docLink packages/runner/capabilities#registry-surface\n */\nexport type LLMTool = {\n /** Capability name; used as the LLM-visible tool name. */\n name: string;\n /** Human/LLM-readable description. */\n description: string;\n /** JSON Schema for the tool's input parameters. */\n parameters: Record<string, unknown>;\n};\n\n/**\n * Filter shape accepted by {@link CapabilityRegistry.list}. All fields are\n * optional and match exactly when present.\n *\n * @category Runtime\n * @since 2.0.0\n * @docLink packages/runner/capabilities#registry-surface\n */\nexport type CapabilityListFilter = {\n side?: \"client\" | \"agent\";\n origin?: CapabilityOrigin[\"kind\"];\n scope?: \"session\" | \"turn\";\n};\n\n/**\n * Side-tag declaring who is registering a capability. The registry uses\n * this to enforce origin trust — a client cannot register an `agent`-side\n * origin, and the agent cannot register `client` / external-origin\n * capabilities.\n *\n * @category Runtime\n * @since 2.0.0\n * @docLink packages/runner/capabilities#registry-surface\n */\nexport type RegisterSource = \"client\" | \"agent\";\n\nconst ORIGIN_PROMPT_ORDER: CapabilityOrigin[\"kind\"][] = [\n \"framework\",\n \"client\",\n \"agent\",\n \"flow\",\n \"skill\",\n \"mcp\",\n \"connector\",\n \"mount\",\n];\n\n/**\n * Per-session registry of capabilities. Construct one per\n * `startAgentServer` invocation; the runner threads it through serve mode's\n * command handlers and the bridge.\n *\n * @category Runtime\n * @since 2.0.0\n * @docLink packages/runner/capabilities#registry-surface\n */\nexport class CapabilityRegistry {\n private readonly byName = new Map<string, DefinedCapability>();\n private readonly logger: Logger;\n private remoteInvoker?: RemoteCapabilityInvoker;\n\n constructor(logger?: Logger) {\n this.logger = logger ?? createLogger({ kind: \"runner\", subkind: \"capability-registry\" });\n }\n\n /**\n * Install the platform-bound invoker used by {@link invokeRemote}.\n *\n * The runner wires this up after the transport is connected and the\n * per-session pending-call map is in place. Idempotent — repeated calls\n * replace the prior invoker.\n *\n * @category Runtime\n * @since 3.0.0\n */\n setRemoteInvoker(invoker: RemoteCapabilityInvoker | undefined): void {\n this.remoteInvoker = invoker;\n }\n\n /**\n * Invoke a `host.*` (or other peer-side) capability on the platform.\n *\n * Composes a `capability_invoked` event under the hood and resolves with\n * the matching `capability_result` payload. Infrastructure failures\n * (timeout, schema mismatch, transport disconnect) reject with `Error`;\n * domain failures (e.g. `{ ok: false, code }` for credential mints) ride\n * in the resolved payload.\n *\n * @category Runtime\n * @since 3.0.0\n */\n async invokeRemote(name: string, input: unknown): Promise<unknown> {\n if (!this.remoteInvoker) {\n throw new Error(\n `Capability '${name}' invoked remotely but no remote invoker is wired. ` +\n `Call CapabilityRegistry.setRemoteInvoker(...) before dispatch.`,\n );\n }\n return this.remoteInvoker(name, input);\n }\n\n /**\n * Register a capability. Validates that the registering `source` is\n * permitted to declare the capability's `origin.kind`; mismatches are\n * dropped with a warning so untrusted callers cannot impersonate other\n * registration sources.\n *\n * Allowed combinations:\n * - source `'agent'`: origins `framework | agent | flow | skill | mcp | connector | mount`\n * - source `'client'`: origin `client` only\n *\n * @param cap - capability to register (typically built via {@link defineCapability})\n * @param source - which side is doing the registration\n */\n register(cap: DefinedCapability, source: RegisterSource): void {\n if (!this.isOriginAllowed(source, cap.origin)) {\n this.logger.warn(\"capability registration rejected (origin mismatch)\", {\n name: cap.name,\n source,\n originKind: cap.origin.kind,\n });\n return;\n }\n this.byName.set(cap.name, cap);\n this.logger.info(\"capability registered\", {\n name: cap.name,\n side: cap.side,\n originKind: cap.origin.kind,\n });\n }\n\n /**\n * Remove a capability by name. No-op when the name is unknown.\n *\n * @param name - capability name\n */\n deregister(name: string): void {\n if (this.byName.delete(name)) {\n this.logger.info(\"capability deregistered\", { name });\n }\n }\n\n /**\n * List capabilities, optionally filtering by `side`, `origin` kind, or\n * `scope`. Returns the wire-format {@link Capability} shape (no internal\n * Zod schemas or handlers).\n */\n list(filter?: CapabilityListFilter): Capability[] {\n const all = Array.from(this.byName.values());\n const matching = filter\n ? all.filter(\n (c) =>\n (filter.side === undefined || c.side === filter.side) &&\n (filter.origin === undefined || c.origin.kind === filter.origin) &&\n (filter.scope === undefined || c.scope === filter.scope),\n )\n : all;\n return matching.map((c) => this.toWire(c));\n }\n\n /**\n * Resolve a capability by name. Returns the full {@link DefinedCapability}\n * (including the original Zod schemas + handler) for use by the bridge.\n *\n * @returns the capability or `null` when the name is not registered\n */\n resolve(name: string): DefinedCapability | null {\n return this.byName.get(name) ?? null;\n }\n\n /**\n * Build LLM tool descriptors for every registered capability whose\n * audience includes `'llm'` (the default when {@link Capability.audience}\n * is omitted). Bridge drivers consume this output directly when\n * assembling the tool list passed to the underlying LLM SDK.\n *\n * Capabilities scoped to `'runtime'` only (e.g. `host.refresh_credential`,\n * `runner.add_mount`) are filtered out so they never reach the model.\n */\n composeLLMTools(): LLMTool[] {\n return Array.from(this.byName.values())\n .filter((c) => hasAudience(c, \"llm\"))\n .map((c) => ({\n name: c.name,\n description: c.description,\n parameters: c.inputSchema,\n }));\n }\n\n /**\n * Compose a deterministic prompt section from every registered\n * capability whose audience includes `'llm'`. Ordering matches\n * `ORIGIN_PROMPT_ORDER` (framework first, then client, then agent-side\n * surfaces) so the agent sees a stable layout. Capabilities without a\n * `promptFragment` are skipped.\n */\n composePromptSection(): string {\n const groups = new Map<CapabilityOrigin[\"kind\"], string[]>();\n for (const cap of this.byName.values()) {\n if (!cap.promptFragment) continue;\n if (!hasAudience(cap, \"llm\")) continue;\n const arr = groups.get(cap.origin.kind) ?? [];\n arr.push(cap.promptFragment);\n groups.set(cap.origin.kind, arr);\n }\n const lines: string[] = [];\n for (const kind of ORIGIN_PROMPT_ORDER) {\n const fragments = groups.get(kind);\n if (!fragments?.length) continue;\n for (const fragment of fragments) {\n lines.push(fragment);\n }\n }\n return lines.join(\"\\n\\n\");\n }\n\n /**\n * Serialize the registry to wire-format capabilities for hibernation. The\n * runtime fields (`inputZod`, `outputZod`, `handler`) are dropped; only\n * the wire shape is kept.\n */\n serialize(): Capability[] {\n return Array.from(this.byName.values()).map((c) => this.toWire(c));\n }\n\n /**\n * Replay a wire snapshot taken via {@link serialize}. Wire-only capabilities\n * (no handler) are stored so {@link list} / {@link composeLLMTools} return\n * a complete picture; agent-side surfaces are expected to re-register\n * fully (with handlers) from their original sources on wake.\n *\n * Per the v2 design, only `client`-side capabilities are persisted across\n * hibernation by this method — agent-side ones come back via the\n * skill / flow / connector / mount adapters. Snapshot entries from other\n * origins are skipped on hydrate.\n */\n hydrate(snapshot: Capability[]): void {\n for (const cap of snapshot) {\n if (cap.origin.kind !== \"client\") continue;\n const stub: DefinedCapability = {\n ...cap,\n inputZod: HYDRATED_PASSTHROUGH_ZOD,\n outputZod: undefined,\n handler: HYDRATED_REJECT_HANDLER,\n };\n this.byName.set(cap.name, stub);\n }\n this.logger.info(\"capability registry hydrated\", { count: snapshot.length });\n }\n\n /**\n * Invoke a registered capability. Validates the input against the Zod\n * schema, builds the per-handler logger, and runs the handler. Logs\n * `info \"invoking\"` and `info \"ok\"` (or `error \"failed\"`) under the\n * `capability:<origin>:<name>` slice for every call.\n *\n * @throws when the capability is unknown or the input fails validation\n */\n async invoke(\n name: string,\n input: unknown,\n baseCtx: Omit<HandlerContext, \"log\">,\n ): Promise<unknown> {\n const cap = this.resolve(name);\n if (!cap) {\n throw new Error(`Unknown capability: ${name}`);\n }\n const log = createLogger({\n kind: \"capability\",\n subkind: cap.origin.kind,\n instance: cap.name,\n });\n log.info(\"invoking\", { input });\n try {\n const validated = cap.inputZod.parse(input);\n const result = await cap.handler(validated, { ...baseCtx, log });\n log.info(\"ok\", { output: result });\n return result;\n } catch (err) {\n log.error(\"failed\", err);\n throw err;\n }\n }\n\n /** True when `source` is allowed to register the given `origin`. */\n private isOriginAllowed(source: RegisterSource, origin: CapabilityOrigin): boolean {\n if (source === \"client\") {\n return origin.kind === \"client\";\n }\n // source === 'agent'\n return origin.kind !== \"client\";\n }\n\n /** Strip the runtime-only fields from a {@link DefinedCapability}. */\n private toWire(cap: DefinedCapability): Capability {\n return {\n name: cap.name,\n displayName: cap.displayName,\n description: cap.description,\n inputSchema: cap.inputSchema,\n outputSchema: cap.outputSchema,\n side: cap.side,\n origin: cap.origin,\n scope: cap.scope,\n fireAndForget: cap.fireAndForget,\n requiresApproval: cap.requiresApproval,\n kind: cap.kind,\n userInvokable: cap.userInvokable,\n audience: cap.audience,\n promptFragment: cap.promptFragment,\n callTimeoutMs: cap.callTimeoutMs,\n render: cap.render,\n };\n }\n}\n\n/**\n * Compute a deterministic signature over a registry's wire-format\n * capabilities. Used by the session-resume cascade (tier-1 native SDK\n * resume) to detect toolset drift between hibernate and wake.\n *\n * The signature hashes a canonicalized projection of each capability:\n * `name + origin.kind + sha256(inputSchema)`. Capabilities are sorted\n * by `name` so registration order does not affect the result.\n *\n * Excluded from the hash:\n * - `displayName` and `userInvokable` — UI metadata only; do not affect\n * what the LLM can call.\n * - `description` and `outputSchema` — text/shape changes that don't\n * alter the call surface.\n *\n * Spec: `_devlog/specs/2026-05-05-session-resume-restart-design.md`\n * § \"Capability signature\".\n *\n * @param caps - Wire-format capabilities from {@link CapabilityRegistry.list}.\n * @returns A hex SHA-256 string that uniquely identifies the toolset.\n * @category Resume\n * @since 3.2.0\n * @docLink packages/runner/capabilities#compute-capability-signature\n */\nexport function computeCapabilitySignature(caps: readonly Capability[]): string {\n const canonical = caps\n .slice()\n .sort((a, b) => a.name.localeCompare(b.name))\n .map((c) => ({\n name: c.name,\n origin: c.origin.kind,\n schemaSha256: sha256(JSON.stringify(c.inputSchema ?? {})),\n }));\n return sha256(JSON.stringify(canonical));\n}\n\nfunction sha256(input: string): string {\n return createHash(\"sha256\").update(input).digest(\"hex\");\n}\n\n// Sentinel Zod schema used by `hydrate()` to keep the wire-format snapshot\n// usable for `list`/`composeLLMTools` without forcing real handler reattach\n// at hibernate-restore time. Actual invocation must go through a re-registered\n// capability that comes back via `ConfigureCommand.capabilities` on wake.\nconst HYDRATED_PASSTHROUGH_ZOD: import(\"zod\").ZodTypeAny = {\n parse: (v: unknown) => v,\n // The full Zod surface is not required here — `parse` is the only method\n // used by `invoke`, and hydrated stubs are not expected to be invoked\n // before the platform resends the live capability via configure.\n} as unknown as import(\"zod\").ZodTypeAny;\n\nconst HYDRATED_REJECT_HANDLER = async (): Promise<never> => {\n throw new Error(\n \"Hydrated capability stub cannot be invoked — re-register via ConfigureCommand on wake.\",\n );\n};\n","/**\n * Client-side capability round-trip helpers.\n *\n * When the LLM invokes a `side: 'client'` capability, the runner does NOT\n * execute the handler in-process. Instead it:\n *\n * 1. Generates a `callId`.\n * 2. Emits a {@link CapabilityInvokedEvent} over the transport.\n * 3. Registers a pending promise keyed by `callId`.\n * 4. Awaits a {@link CapabilityResultCommand} from the platform; resolves\n * with `result` or rejects with `result.error`.\n *\n * `fireAndForget` short-circuits step 3 — the handler resolves with `{}`\n * immediately after emitting the invoke event. The bridge-level dispatch\n * also short-circuits before calling `hooks.invoke()`, so this is a\n * defence-in-depth guard.\n *\n * The helpers below are extracted for unit testing; the actual wiring\n * lives in `serve.ts` where the transport / pending map are owned.\n *\n * @category Capabilities\n * @since 2.0.0\n */\nimport type { AgentEvent, Capability, CapabilityResultCommand } from \"@skaile/workspaces/types\";\n\n/**\n * Registry of in-flight capability calls. The serve loop owns the map; this\n * type is exported so tests can pass a real `Map` instance and assert the\n * pending state across the round-trip.\n * @docLink packages/runner/capabilities#registry-surface\n */\nexport type PendingCallEntry = {\n resolve: (value: unknown) => void;\n reject: (err: Error) => void;\n timer: ReturnType<typeof setTimeout>;\n};\n\n/**\n * Default timeout (60s) for waiting on a capability result from the platform.\n * Mirrors the value used in `serve.ts`.\n *\n * @docLink packages/runner/capabilities#registry-surface\n */\nexport const DEFAULT_CAPABILITY_CALL_TIMEOUT_MS = 60_000;\n\n/**\n * Resolve the round-trip timeout for a wire-format client capability.\n *\n * Precedence:\n * 1. An explicit per-capability `callTimeoutMs` — set for capabilities that\n * legitimately block far longer than a normal tool call (e.g.\n * `platform.ask_session`, which suspends the caller's turn until a peer\n * session answers).\n * 2. `approvalTimeoutMs` when the capability is `requiresApproval` — human\n * approvals routinely take minutes.\n * 3. `DEFAULT_CAPABILITY_CALL_TIMEOUT_MS` (60s) otherwise.\n *\n * Extracted as a pure function so the precedence is unit-testable without\n * spinning up `startAgentServer`.\n *\n * @docLink packages/runner/capabilities#registry-surface\n */\nexport function resolveCapabilityCallTimeoutMs(\n cap: Pick<Capability, \"callTimeoutMs\" | \"requiresApproval\">,\n approvalTimeoutMs: number,\n): number {\n if (typeof cap.callTimeoutMs === \"number\") return cap.callTimeoutMs;\n if (cap.requiresApproval) return approvalTimeoutMs;\n return DEFAULT_CAPABILITY_CALL_TIMEOUT_MS;\n}\n\n/**\n * Build the runner-side handler for a wire-format client capability. The\n * returned function emits `capability_invoked` and waits for a matching\n * `capability_result` command via the supplied pending-calls map.\n *\n * Decoupled from `serve.ts` so it can be exercised in isolation without\n * spinning up `startAgentServer`.\n * @docLink packages/runner/capabilities#registry-surface\n */\nexport function buildClientCapabilityHandler(args: {\n wire: Capability;\n pending: Map<string, PendingCallEntry>;\n emit: (event: AgentEvent) => void;\n timeoutMs?: number;\n /** Override the callId factory for deterministic tests. */\n generateCallId?: () => string;\n}): (input: unknown) => Promise<unknown> {\n const timeoutMs = args.timeoutMs ?? DEFAULT_CAPABILITY_CALL_TIMEOUT_MS;\n const gen = args.generateCallId ?? (() => `cap-${Date.now()}-${Math.floor(Math.random() * 1e9)}`);\n return async (input: unknown) => {\n const callId = gen();\n if (args.wire.fireAndForget) {\n args.emit({\n type: \"capability_invoked\",\n callId,\n name: args.wire.name,\n input,\n invokedBy: \"agent\",\n });\n return {};\n }\n return new Promise<unknown>((resolve, reject) => {\n const timer = setTimeout(() => {\n args.pending.delete(callId);\n reject(\n new Error(\n `Capability ${args.wire.name} (callId=${callId}) timed out after ${timeoutMs}ms`,\n ),\n );\n }, timeoutMs);\n args.pending.set(callId, { resolve, reject, timer });\n args.emit({\n type: \"capability_invoked\",\n callId,\n name: args.wire.name,\n input,\n invokedBy: \"agent\",\n });\n });\n };\n}\n\n/**\n * Resolve / reject a pending capability call based on a `capability_result`\n * command from the platform. Returns `true` when the callId matched a\n * pending entry, `false` otherwise (for telemetry / debug logging).\n * @docLink packages/runner/capabilities#registry-surface\n */\nexport function resolveCapabilityResult(\n pending: Map<string, PendingCallEntry>,\n cmd: CapabilityResultCommand,\n): boolean {\n const entry = pending.get(cmd.callId);\n if (!entry) return false;\n clearTimeout(entry.timer);\n pending.delete(cmd.callId);\n const result = cmd.result;\n if (result && typeof result === \"object\" && \"error\" in result) {\n entry.reject(new Error(String((result as { error: unknown }).error)));\n } else {\n entry.resolve(result);\n }\n return true;\n}\n\n/**\n * Reject a pending capability call when the platform sends a\n * `capability_approve` with `decision: 'rejected'`. Used by capabilities\n * declared `requiresApproval: true` — the platform shows a confirm UI on\n * `capability_invoked`; on user denial it forwards the rejection back to the\n * runner via this command instead of dispatching the handler.\n *\n * Returns `true` when the callId matched a pending entry, `false` otherwise\n * (e.g. the call was already resolved via `capability_result`).\n *\n * Approvals (`decision: 'approved'`) are no-ops at this level — the platform\n * still drives dispatch and replies via `capability_result`. This function\n * only handles the rejection short-circuit.\n *\n * @param pending - Map of in-flight capability calls keyed by `callId`.\n * @param callId - ID of the call being denied.\n * @param feedback - Optional user-facing feedback message passed to the rejection error.\n * @returns `true` when the call was found and rejected; `false` when already resolved.\n * @category Capabilities\n * @since 2.1.0\n * @docLink packages/runner/capabilities#reject-capability-on-approval-deny\n */\nexport function rejectCapabilityOnApprovalDeny(\n pending: Map<string, PendingCallEntry>,\n callId: string,\n feedback?: string,\n): boolean {\n const entry = pending.get(callId);\n if (!entry) return false;\n clearTimeout(entry.timer);\n pending.delete(callId);\n entry.reject(new Error(feedback ?? \"declined by user\"));\n return true;\n}\n","/**\n * Runtime context data supplied to a {@link CompactionStrategy}\n * when deciding whether to compact the context window.\n *\n * @docLink packages/runner/dev-guide#compaction\n */\nexport interface CompactionContext {\n estimatedTokens: number;\n contextWindow: number;\n messageCount: number;\n lastCompactionSeq: number | null;\n timeSinceLastCompaction: number | null;\n}\n\n/**\n * Strategy for deciding when the context window should be compacted.\n *\n * Implementations receive the current {@link CompactionContext} and\n * return true when compaction should proceed.\n *\n * @docLink packages/runner/dev-guide#compaction\n */\nexport interface CompactionStrategy {\n shouldCompact(context: CompactionContext): boolean;\n}\n\n/**\n * Compaction strategy that triggers when estimated token usage\n * exceeds a percentage of the context window. A cooldown period\n * prevents thrashing.\n *\n * @docLink packages/runner/dev-guide#compaction\n */\nexport class TokenThresholdStrategy implements CompactionStrategy {\n private readonly thresholdPercent: number;\n private readonly minCooldownMs: number;\n\n constructor(opts: { thresholdPercent: number; minCooldownMs: number }) {\n this.thresholdPercent = opts.thresholdPercent;\n this.minCooldownMs = opts.minCooldownMs;\n }\n\n shouldCompact(context: CompactionContext): boolean {\n const fillPercent = (context.estimatedTokens / context.contextWindow) * 100;\n if (fillPercent < this.thresholdPercent) return false;\n\n // Respect cooldown\n if (\n context.timeSinceLastCompaction !== null &&\n context.timeSinceLastCompaction < this.minCooldownMs\n ) {\n return false;\n }\n\n return true;\n }\n}\n","const DEFAULT_COMPACTION_PROMPT = `You are being asked to compact this conversation into a structured summary.\nThis summary will replace the full conversation history when the session\nis restored. Produce a summary that lets you continue working effectively\nwithout access to the original messages.\n\n## Rules\n\nPRESERVE (include verbatim):\n- Current task/goal and its status\n- All file paths that were read, created, or modified\n- Function/class/variable names that are relevant to ongoing work\n- Key decisions made and the reasoning behind them\n- Errors encountered and how they were resolved\n- Active flow node and state (if any)\n- Unresolved questions or pending user input\n- User names and who said/requested what (multi-user sessions)\n- Test commands and verification criteria\n- Any explicit user instructions about preferences or constraints\n\nCOMPRESS (summarize in one line each):\n- Tool call / tool result pairs\n- Intermediate reasoning steps\n- Exploration paths that informed a decision\n\nDROP (omit entirely):\n- Full file contents (can be re-read from disk)\n- Verbose command output (build logs, test suite output)\n- Exploration that led nowhere and didn't inform decisions\n- Redundant back-and-forth (corrections already applied)\n- Transient UI state\n\n## Format\n\nWrite a structured summary using these sections. Omit any section that\nhas no content.\n\n### Goal\nWhat the user is trying to accomplish.\n\n### Progress\nWhat has been done so far, organized by sub-task.\n\n### Key Decisions\nDecisions made and why, as a bulleted list.\n\n### Active State\nCurrent work in progress -- what was happening when compaction triggered.\n\n### Files\nAll relevant file paths with a one-line note on each.\n\n### Pending\nWhat still needs to be done or is waiting on user input.\n\n### Context\nUser preferences, constraints, or instructions that must carry forward.`;\n\n/**\n * Assemble the final compaction prompt from layered sources.\n *\n * Resolution order:\n * base = agentPrompt ?? DEFAULT_COMPACTION_PROMPT\n * final = base + skillDirectives + focus\n * @docLink packages/runner/dev-guide#compaction\n */\nexport function buildCompactionPrompt(opts: {\n agentPrompt?: string;\n skillDirectives?: string[];\n mcpDirectives?: string[];\n focus?: string;\n}): string {\n const base = opts.agentPrompt ?? DEFAULT_COMPACTION_PROMPT;\n const parts = [base];\n\n const allDirectives = [...(opts.skillDirectives ?? []), ...(opts.mcpDirectives ?? [])];\n\n if (allDirectives.length > 0) {\n parts.push(\n `\\n\\n## Additional Compaction Directives\\n${allDirectives.map((d) => `- ${d}`).join(\"\\n\")}`,\n );\n }\n\n if (opts.focus) {\n parts.push(`\\n\\n## Focus\\n${opts.focus}`);\n }\n\n return parts.join(\"\");\n}\n","import type { AgentDriver } from \"@skaile/workspaces/bridge\";\nimport { classifyClaudeSdkError } from \"@skaile/workspaces/bridge\";\nimport type { CompactionConfig } from \"@skaile/workspaces/core\";\nimport { COMPACTION_DEFAULTS } from \"@skaile/workspaces/core\";\nimport type {\n CompactionAttemptEvent,\n CompactionTrigger,\n SnapshotEvent,\n} from \"@skaile/workspaces/types\";\nimport { buildCompactionPrompt } from \"./prompt.js\";\nimport { type CompactionStrategy, TokenThresholdStrategy } from \"./strategy.js\";\n\n/**\n * Minimum character length the LLM must produce to count as a meaningful summary.\n * Below this we mark the attempt `failed`/`too_short`. Tunable: 200 chars is roughly\n * 50 tokens, the floor for \"the model said anything substantive\".\n */\nconst MIN_SUMMARY_CHARS = 200;\n\n/**\n * Maximum compression ratio (outputTokens / tokensBefore) we accept as a successful\n * compaction. Above this the LLM essentially returned the input back; mark `poor_ratio`.\n */\nconst MAX_COMPRESSION_RATIO = 0.9;\n\n/**\n * Maximum length under which a captured response is still considered a candidate\n * for being a rate-limit error message rather than a real summary. Real\n * compactions are typically thousands of characters; rate-limit relays are\n * short.\n */\nconst RATE_LIMIT_TEXT_MAX_CHARS = 1500;\n\n/**\n * Phrases that strongly indicate the captured text is the LLM relaying a\n * rate-limit / quota error to the user rather than producing a summary.\n * Conservative on purpose — a real summary that mentions rate limits in\n * passing would only match if it is also short, see\n * {@link detectRateLimitInSummary}.\n */\nconst RATE_LIMIT_TEXT_PATTERNS: RegExp[] = [\n /you('?| ha)ve hit your (rate |usage )?limit/i,\n /you('?| ha)ve reached your (usage |rate )?limit/i,\n /you('?| ha)ve been rate[\\s-]?limited/i,\n /rate limit (exceeded|reached|hit)/i,\n /usage limit (exceeded|reached)/i,\n /quota (exceeded|reached)/i,\n /claude (ai )?usage limit reached/i,\n];\n\n/**\n * Detect whether the captured response from a compaction `prompt()` call is\n * actually a rate-limit error message returned as text (instead of as a\n * thrown error). Persisting such a \"summary\" would corrupt context\n * restoration on the next wake — the snapshot prompt would inject the error\n * text as if it were the conversation summary.\n *\n * Conservative: requires both a strong signal phrase AND a short response.\n * Real summaries are routinely 2k+ chars; rate-limit relays are short.\n *\n * Issue: I-29.\n */\nexport function detectRateLimitInSummary(text: string): boolean {\n if (text.length > RATE_LIMIT_TEXT_MAX_CHARS) return false;\n return RATE_LIMIT_TEXT_PATTERNS.some((p) => p.test(text));\n}\n\n/**\n * Validation of a compaction output's structural shape, run BEFORE we persist\n * it as a `success`. Cheap synchronous checks only — no LLM calls.\n *\n * Failed validation does NOT throw; it returns a structured verdict so the\n * orchestrator can record a `failed` Compaction row with the right errorCode.\n *\n * @param text The captured summary text from the driver.\n * @param tokensBefore Estimated input token count (from `driver.getTokenUsage()` before the call).\n * @param tokensAfter Output token count of the summary (from driver or chars/4 heuristic).\n * @returns `{ ok: true }` on pass, otherwise `{ ok: false, errorCode }` with one of:\n * `\"empty\"` | `\"too_short\"` | `\"poor_ratio\"` | `\"rate_limit\"`.\n *\n * Spec: `_devlog/specs/2026-05-05-session-resume-restart-design.md` § Validation at write time.\n * @docLink packages/runner/capabilities#validate-compaction-output\n */\nexport function validateCompactionOutput(\n text: string,\n tokensBefore: number,\n tokensAfter: number,\n): { ok: true } | { ok: false; errorCode: string } {\n if (!text.trim()) return { ok: false, errorCode: \"empty\" };\n if (detectRateLimitInSummary(text)) return { ok: false, errorCode: \"rate_limit\" };\n if (text.length < MIN_SUMMARY_CHARS) return { ok: false, errorCode: \"too_short\" };\n if (tokensBefore > 0 && tokensAfter / tokensBefore > MAX_COMPRESSION_RATIO) {\n return { ok: false, errorCode: \"poor_ratio\" };\n }\n return { ok: true };\n}\n\n/**\n * Options for the {@link CompactionOrchestrator}.\n *\n * @docLink packages/runner/dev-guide#compaction\n */\nexport interface CompactionOrchestratorOptions {\n driver: AgentDriver;\n config?: CompactionConfig;\n skillDirectives?: string[];\n mcpDirectives?: string[];\n agentCompactionPrompt?: string;\n onCompactionStart?: (trigger: CompactionTrigger) => void;\n onSnapshot?: (snapshot: SnapshotEvent) => void;\n /**\n * Emitted on EVERY compaction attempt, success or failure. Phase 1 sink for\n * the new `Compaction` table observability surface; the host's serve.ts wires\n * this to forward events on the agent transport.\n */\n onCompactionAttempt?: (event: CompactionAttemptEvent) => void;\n onCompactionEnd?: () => void;\n onLog?: (line: string) => void;\n /**\n * Phase 3 (resume cascade): supplies the current capability registry\n * signature at compaction time so it lands on the\n * {@link CompactionAttemptEvent}. The wake selector compares this against\n * the runner's current signature to decide tier-1 native SDK resume\n * eligibility.\n *\n * Returns `null` when the host cannot compute a signature (legacy boot\n * path, registry not yet bootstrapped); the orchestrator records `null`\n * in that case and the resulting compaction is tier-1 ineligible.\n */\n getCurrentCapabilitySignature?: () => string | null;\n}\n\n/**\n * Orchestrates context window compaction for a running agent session.\n *\n * Monitors token usage against the configured thresholds and triggers\n * compaction via snapshots when the strategy fires.\n *\n * @docLink packages/runner/dev-guide#compaction\n */\nexport class CompactionOrchestrator {\n private readonly driver: AgentDriver;\n private readonly strategy: CompactionStrategy;\n private readonly config: Required<CompactionConfig>;\n private readonly opts: CompactionOrchestratorOptions;\n\n private _isCompacting = false;\n private lastCompactionSeq: number | null = null;\n private lastCompactionTime: number | null = null;\n private currentSeq = 0;\n private messagesSinceCompaction = 0;\n\n constructor(opts: CompactionOrchestratorOptions) {\n this.driver = opts.driver;\n this.opts = opts;\n this.config = { ...COMPACTION_DEFAULTS, ...opts.config };\n this.strategy = new TokenThresholdStrategy({\n thresholdPercent: this.config.thresholdPercent,\n minCooldownMs: this.config.minCooldownMs,\n });\n }\n\n get hasNewMessagesSinceCompaction(): boolean {\n return this.messagesSinceCompaction > 0;\n }\n\n trackMessage(seq: number): void {\n this.currentSeq = seq;\n this.messagesSinceCompaction++;\n }\n\n shouldCompact(): boolean {\n if (!this.config.enabled) return false;\n const usage = this.driver.getTokenUsage();\n const contextWindow = this.driver.getContextWindow();\n if (!usage || !contextWindow || usage.inputTokens === undefined) return false;\n\n return this.strategy.shouldCompact({\n estimatedTokens: usage.inputTokens,\n contextWindow,\n messageCount: this.messagesSinceCompaction,\n lastCompactionSeq: this.lastCompactionSeq,\n timeSinceLastCompaction:\n this.lastCompactionTime !== null ? Date.now() - this.lastCompactionTime : null,\n });\n }\n\n async compact(trigger: CompactionTrigger, focus?: string): Promise<SnapshotEvent | null> {\n if (this._isCompacting) return null;\n this._isCompacting = true;\n try {\n return await this._doCompact(trigger, focus);\n } finally {\n this._isCompacting = false;\n }\n }\n\n private async _doCompact(\n trigger: CompactionTrigger,\n focus?: string,\n ): Promise<SnapshotEvent | null> {\n const tokensBefore = this.driver.getTokenUsage()?.inputTokens ?? 0;\n const driverSessionId = this.driver.runtimeSessionId ?? null;\n const driverModel = this.driver.getModel() ?? null;\n const driverProvider = this.driver.driverInfo?.id ?? null;\n const coversFromSeq = this.lastCompactionSeq ?? 0;\n // Phase 3: capture the registry signature once at the start of the call\n // so all attempt-event branches (failed/validation-failed/success) share\n // the same value.\n const capabilitySignatureAtCompaction = this.opts.getCurrentCapabilitySignature?.() ?? null;\n\n this.opts.onCompactionStart?.(trigger);\n this.opts.onLog?.(`[compaction] Starting (trigger=${trigger}, tokens=${tokensBefore})`);\n\n const prompt = buildCompactionPrompt({\n agentPrompt: this.opts.agentCompactionPrompt,\n skillDirectives: this.opts.skillDirectives,\n mcpDirectives: this.opts.mcpDirectives,\n focus,\n });\n\n let summaryText = \"\";\n // The driver emits raw bridge-level events (message_update, message_start,\n // message_end) that are NOT in the AgentEvent union — those are normalized\n // by EventNormalizer in serve.ts. Since the compaction handler attaches\n // directly to the driver, we type the parameter loosely.\n const captureHandler = (raw: unknown) => {\n const event = raw as { type: string; [k: string]: unknown };\n // Normalized events (from EventNormalizer or other drivers)\n if (event.type === \"text\") {\n summaryText += (event.content as string) ?? \"\";\n return;\n }\n // Raw SDK driver events — message_update carries _textDelta, bypassing\n // the EventNormalizer which isn't in the compaction capture path.\n if (event.type === \"message_update\") {\n const delta = event._textDelta as string | undefined;\n if (delta) summaryText += delta;\n return;\n }\n // Fallback: non-streaming drivers may emit message_start/message_end\n // with the full text in the message content blocks.\n if (event.type === \"message_start\" || event.type === \"message_end\") {\n const msg = event.message as { content?: { type: string; text?: string }[] } | undefined;\n if (!msg?.content) return;\n const blocks = Array.isArray(msg.content) ? msg.content : [];\n for (const b of blocks) {\n if (b.type === \"text\" && b.text) summaryText += b.text;\n }\n }\n };\n\n let promptError: unknown = null;\n try {\n this.driver.on(\"agent-event\", captureHandler);\n await this.driver.prompt(prompt);\n } catch (err) {\n promptError = err;\n } finally {\n this.driver.removeListener(\"agent-event\", captureHandler);\n }\n\n // ── Failure path: prompt() threw ──────────────────────────────────────\n if (promptError !== null) {\n const classified = classifyClaudeSdkError(\n promptError instanceof Error ? promptError.message : String(promptError),\n );\n // Map classifier categories to our error codes per spec.\n // `auth` covers both real credential failures AND payment-blocked OAuth\n // subscriptions that Anthropic mislabels as auth errors (see\n // bridge/error-classifier.ts docstring) — owners investigate further.\n const errorCode =\n classified.category === \"rate_limit\"\n ? \"rate_limit\"\n : classified.category === \"auth\"\n ? \"auth\"\n : classified.category === \"network\"\n ? \"timeout\"\n : classified.category === \"validation\"\n ? \"parse_error\"\n : classified.category;\n\n this.opts.onLog?.(`[compaction] Failed: ${classified.message} (${errorCode})`);\n this.opts.onCompactionAttempt?.({\n type: \"compaction_attempt\",\n status: \"failed\",\n errorCode,\n trigger,\n summary: \"\",\n model: driverModel,\n provider: driverProvider,\n inputTokens: tokensBefore,\n outputTokens: 0,\n coversFromSeq,\n coversToSeq: this.currentSeq,\n driverSessionIdAtCompaction: driverSessionId,\n modelAtCompaction: driverModel,\n capabilitySignatureAtCompaction,\n validatedAt: null,\n });\n this.opts.onCompactionEnd?.();\n return null;\n }\n\n // ── Validation path: prompt succeeded but output may be malformed ────\n // Use actual output token count from the driver; fall back to heuristic.\n const actualUsage = this.driver.getTokenUsage();\n const tokensAfter = actualUsage?.outputTokens ?? Math.ceil(summaryText.length / 4);\n\n const validation = validateCompactionOutput(summaryText, tokensBefore, tokensAfter);\n if (!validation.ok) {\n this.opts.onLog?.(\n `[compaction] Output failed validation (${validation.errorCode}); recording failed attempt`,\n );\n this.opts.onCompactionAttempt?.({\n type: \"compaction_attempt\",\n status: \"failed\",\n errorCode: validation.errorCode,\n trigger,\n summary: \"\",\n model: driverModel,\n provider: driverProvider,\n inputTokens: tokensBefore,\n outputTokens: tokensAfter,\n coversFromSeq,\n coversToSeq: this.currentSeq,\n driverSessionIdAtCompaction: driverSessionId,\n modelAtCompaction: driverModel,\n capabilitySignatureAtCompaction,\n validatedAt: null,\n });\n this.opts.onCompactionEnd?.();\n return null;\n }\n\n // ── Success path ──────────────────────────────────────────────────────\n const validatedAt = new Date().toISOString();\n\n const snapshot: SnapshotEvent = {\n type: \"snapshot\",\n summary: summaryText,\n trigger,\n coversFromSeq,\n coversToSeq: this.currentSeq,\n tokensBefore,\n tokensAfter,\n };\n\n // 1. Emit the new attempt event AND the legacy snapshot event.\n // Both ride alongside each other through Phase 4 (back-compat).\n this.opts.onCompactionAttempt?.({\n type: \"compaction_attempt\",\n status: \"success\",\n errorCode: null,\n trigger,\n summary: summaryText,\n model: driverModel,\n provider: driverProvider,\n inputTokens: tokensBefore,\n outputTokens: tokensAfter,\n coversFromSeq,\n coversToSeq: this.currentSeq,\n driverSessionIdAtCompaction: driverSessionId,\n modelAtCompaction: driverModel,\n capabilitySignatureAtCompaction,\n validatedAt,\n });\n this.opts.onSnapshot?.(snapshot);\n\n // 2. Update internal state\n this.lastCompactionSeq = this.currentSeq + 1;\n this.lastCompactionTime = Date.now();\n this.messagesSinceCompaction = 0;\n\n // 3. Clear compacting flag so the injection turn's events flow normally\n this.opts.onCompactionEnd?.();\n\n // 4. Reset driver and inject snapshot (skip for hibernate -- container shuts down)\n if (trigger !== \"hibernate\") {\n this.opts.onLog?.(\"[compaction] Resetting driver session\");\n await this.driver.resetSession();\n await this.driver.prompt(\n `<session_snapshot>\\n${summaryText}\\n</session_snapshot>\\n\\nThe conversation has been compacted. The above snapshot contains the full context of our work so far. Continue from where we left off.`,\n );\n }\n\n // 5. Log completion\n this.opts.onLog?.(\n `[compaction] Complete (${tokensBefore} -> ${tokensAfter} tokens, ratio=${((tokensAfter / Math.max(tokensBefore, 1)) * 100).toFixed(1)}%)`,\n );\n return snapshot;\n }\n\n initFromSnapshot(lastSnapshotSeq: number, lastSnapshotTime: number): void {\n this.lastCompactionSeq = lastSnapshotSeq;\n this.lastCompactionTime = lastSnapshotTime;\n this.messagesSinceCompaction = 0;\n }\n}\n","/**\n * Rewrite file_changed event paths to mounts-relative form.\n *\n * The bridge normalizer forwards tool filePaths verbatim — for Claude SDK\n * Write/Edit they are cwd-relative (e.g. \"workspace/foo/bar.py\" when cwd\n * is /skaile and the file lives at /skaile/workspace/foo/bar.py). The\n * frontend's file-change listener treats the path as relative to the\n * currently-selected mount, which double-prefixes when the workspace\n * mount sits under cwd.\n *\n * This helper resolves the path against cwd, locates the mount it falls\n * inside, and re-expresses the path relative to that mount with the\n * matching mountId attached.\n *\n * Events that already carry a mountId (watcher-originated) and events\n * whose path resolves outside every mount are passed through unchanged.\n */\n\nimport { relative, resolve } from \"node:path\";\nimport type { AgentEvent } from \"@skaile/workspaces/types\";\n\n/**\n * Describes a filesystem mount point for path rewriting.\n *\n * @docLink packages/runner/dev-guide#flow-execution-turn-based-model\n */\nexport interface MountPoint {\n id: string;\n /** Absolute mount path on the agent's filesystem. */\n mountPath: string;\n}\n\n/**\n * Rewrite a single file_changed event. Non-file_changed events and events\n * already tagged with a mountId are returned unchanged.\n * @docLink packages/runner/dev-guide#flow-execution-turn-based-model\n */\nexport function rewriteFileChangedPath(\n event: AgentEvent,\n cwd: string,\n mounts: readonly MountPoint[],\n): AgentEvent {\n if (event.type !== \"file_changed\") return event;\n if ((event as { mountId?: string }).mountId) return event;\n const rawPath = event.path;\n if (!rawPath) return event;\n\n const absPath = resolve(cwd, rawPath);\n for (const mount of mounts) {\n const rel = relative(mount.mountPath, absPath);\n // rel starts with \"..\" → outside the mount\n // rel === \"\" → the mount itself (not a child)\n // rel is absolute (starts with \"/\") → different filesystem root\n if (rel === \"\" || rel.startsWith(\"..\") || rel.startsWith(\"/\")) continue;\n return { ...event, path: rel, mountId: mount.id };\n }\n return event;\n}\n","/**\n * Refresh-flag dispatcher — wake-mid-401 hardening for Tier-2 git connectors.\n *\n * The Tier-2 git credential-helper script (rendered by\n * `connectors/credential-helper-script.ts`) touches a workspace-level\n * refresh-flag file when it detects a stale credentials file. The runner\n * watches that flag via `fs.watch` and on `change` invokes the dispatcher\n * here, which:\n *\n * 1. Lists git connectors whose `exposeAccessToken === true` AND\n * `auth === 'backend'` (Tier-2 backend-mediated only — PAT connectors\n * can't be refreshed runtime-side).\n * 2. For each eligible connector, calls the GitConnector's\n * `refreshExposedCredential(connectorId, handle)` — which mediates a\n * fresh access token via the runner-supplied `tokenMediator` and\n * rewrites the credentials file via `atomicReplaceCredential`.\n *\n * Extracted into its own module so the watcher logic can be unit-tested\n * without spinning up the full WebSocket server.\n *\n * Spec: `_devlog/specs/2026-05-07-unified-credential-mediation.md` Step 9a.\n */\n\nimport type { Logger } from \"@skaile/workspaces/types\";\n\n/**\n * Minimal connector-manager surface the dispatcher needs. Matches the public\n * interface of `ConnectorManager` (`listGitConnectors`, `get`) but stays\n * structural so tests can pass mocks without importing the full class.\n */\nexport interface DispatchConnectorManager {\n listGitConnectors(): Array<{\n id: string;\n source: string;\n exposeAccessToken: boolean;\n auth?: string;\n }>;\n get(id: string): {\n connector: {\n refreshExposedCredential?: (connectorId: string, handle: unknown) => Promise<void>;\n };\n handle: unknown;\n };\n}\n\n/**\n * Iterate every currently connected git connector and refresh the credential\n * for those eligible (Tier-2 backend-mediated). Failures on one connector do\n * not abort the rest.\n *\n * @param manager - The active connector manager. Pass `null` to short-circuit\n * (used during the brief window between session boot and provisioning).\n * @param log - Logger. The dispatcher emits `info` on success and `warn` on\n * per-connector failure.\n */\nexport async function dispatchRefreshToExposedGitMounts(\n manager: DispatchConnectorManager | null,\n log: Logger,\n): Promise<void> {\n if (!manager) return;\n\n let gitConnectors: ReturnType<DispatchConnectorManager[\"listGitConnectors\"]>;\n try {\n gitConnectors = manager.listGitConnectors();\n } catch (err) {\n log.warn(\"listGitConnectors failed during refresh-flag dispatch\", {\n error: err instanceof Error ? err.message : String(err),\n });\n return;\n }\n\n const eligible = gitConnectors.filter(\n (m) => m.exposeAccessToken === true && m.auth === \"backend\",\n );\n if (eligible.length === 0) {\n log.debug(\"refresh-flag fired but no eligible git connectors (Tier-2 backend) found\");\n return;\n }\n\n log.info(\"refresh-flag fired -- dispatching backend mediation\", {\n connectorIds: eligible.map((m) => m.id),\n });\n\n await Promise.all(\n eligible.map(async (m) => {\n try {\n const entry = manager.get(m.id);\n if (typeof entry.connector.refreshExposedCredential !== \"function\") {\n log.debug(\"connector lacks refreshExposedCredential -- skipping\", {\n connectorId: m.id,\n });\n return;\n }\n await entry.connector.refreshExposedCredential(m.id, entry.handle);\n } catch (err) {\n log.warn(\"refresh-flag dispatch failed for connector\", {\n connectorId: m.id,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }),\n );\n}\n","/**\n * Runner-side capabilities (Protocol v3). Replaces the deleted v2\n * `AgentCommand` types `add_resource` / `remove_resource` /\n * `set_log_level` / `state_action` / lifecycle by exposing them as named\n * capabilities the platform invokes through the bidirectional\n * capability registry — the same wire pattern as agent->platform calls,\n * just in reverse.\n *\n * All seven caps are `audience: ['runtime']` so they never leak to the\n * LLM tool list or to the user-facing command palette (cmdK). They run\n * with `side: 'agent'` (handler lives in the agent runtime) and\n * `origin: { kind: 'framework' }` — `CapabilityOrigin` (as of\n * `@skaile/workspaces/types@4.0.0`) does not include a `runner` kind, and\n * per the v3 spec \"origin tag stays separate (origin.kind); audience\n * determines visibility\". The `runner.<verb>` naming convention lives\n * in the capability `name`, not in the origin tag.\n *\n * The factory takes a {@link RunnerCapabilityHandlers} bag so the\n * caller (typically `serve.ts`) wires each cap to its own state-\n * mutation helpers without this file having to import `serve.ts` —\n * keeping the dependency direction acyclic.\n *\n * @category Runtime\n * @since 3.0.0\n */\nimport * as z from \"zod\";\nimport type { CredentialMint, LogLevel } from \"@skaile/workspaces/types\";\nimport { getLogStore } from \"@skaile/workspaces/core/logging\";\nimport { defineCapability, type DefinedCapability } from \"./define-capability.js\";\n\n/**\n * Per-session handlers that runner-side capabilities delegate into. The\n * caller (typically `serve.ts`) wires these to its own state-mutation\n * helpers. Each method is optional; capabilities whose handler is\n * undefined return a structured `not_implemented` error.\n *\n * @category Runtime\n * @since 3.0.0\n */\nexport interface RunnerCapabilityHandlers {\n /**\n * Add a mount to the live session. Implementations typically delegate\n * to `VolumeManager.mount()` after staging the `preMintedToken` into\n * the secrets provider chain.\n */\n addMount?: (input: {\n declaration: unknown;\n preMintedToken?: { token: string; expiresAt?: string | null };\n }) => Promise<{ ok: true; id: string } | { ok: false; code: string; message: string }>;\n\n /**\n * Add a connector to the live session. Implementations typically\n * delegate to `ConnectorManager.connect()` after staging the\n * `preMintedToken`.\n */\n addConnector?: (input: {\n declaration: unknown;\n preMintedToken?: { token: string; expiresAt?: string | null };\n }) => Promise<{ ok: true; id: string } | { ok: false; code: string; message: string }>;\n\n /**\n * Remove a mount or connector by id. The id namespace is shared — the\n * handler resolves whichever manager owns it.\n */\n removeResource?: (input: {\n id: string;\n }) => Promise<{ ok: true } | { ok: false; code: string; message: string }>;\n\n /**\n * Replace the pre-minted credential on an existing mount or\n * connector. Used for proactive rotation before TTL expiry, so the\n * resource can keep running without a reconnect.\n */\n updateCredential?: (input: {\n kind: \"mount\" | \"connector\";\n id: string;\n mint: CredentialMint;\n }) => Promise<{ ok: true } | { ok: false; code: string; message: string }>;\n\n /**\n * Set the in-container LogStore minimum level. When omitted, the\n * cap falls back to calling `getLogStore()?.setLevel(level)` itself\n * (the default behaviour matches the legacy `set_log_level` command).\n */\n setLogLevel?: (input: { level: string }) => Promise<{ ok: true }>;\n\n /**\n * Write into the shared state store. Shape matches the legacy\n * `state_action` v2 command body so existing platform-side senders\n * can be migrated mechanically.\n */\n setState?: (input: { store: string; key: string; value: unknown }) => Promise<{ ok: true }>;\n\n /** Trigger a session lifecycle transition. */\n lifecycle?: (input: { action: \"hibernate\" | \"close\" | \"shutdown\" }) => Promise<{ ok: true }>;\n}\n\n/** Common origin tag used by all runner-side caps. */\nconst RUNNER_CAP_ORIGIN = { kind: \"framework\" } as const;\n\n/**\n * Build the standard `not_implemented` reply for a cap whose handler\n * was not wired by the caller. The shape mirrors the success/error\n * union the wired handlers return, so callers consuming the result\n * uniformly only need one discriminator (`ok`).\n */\nfunction notImplemented(name: string): { ok: false; code: \"not_implemented\"; message: string } {\n return {\n ok: false,\n code: \"not_implemented\",\n message: `${name} handler not configured`,\n };\n}\n\n// Input schemas. `declaration` and `value` use `z.unknown()` with an\n// explicit `.refine(() => true)` so the inferred type is `unknown`\n// (required) rather than `unknown | undefined` (optional) — Zod's\n// default treatment of `z.unknown()` is optional even at the top of\n// an object, which would break the handler-input contract.\nconst requiredUnknown = z.unknown().refine(() => true);\n\nconst preMintedTokenSchema = z\n .object({\n token: z.string(),\n expiresAt: z.string().nullable().optional(),\n })\n .optional();\n\nconst mountDeclarationInput = z.strictObject({\n declaration: requiredUnknown,\n preMintedToken: preMintedTokenSchema,\n});\n\nconst connectorDeclarationInput = z.strictObject({\n declaration: requiredUnknown,\n preMintedToken: preMintedTokenSchema,\n});\n\nconst removeResourceInput = z.strictObject({\n id: z.string(),\n});\n\nconst updateCredentialInput = z.strictObject({\n kind: z.enum([\"mount\", \"connector\"]),\n id: z.string(),\n // `CredentialMint` is a discriminated union from `@skaile/workspaces/types`.\n // We accept it as `z.unknown()` here because Zod can't easily mirror\n // a discriminated TypeScript union without duplicating the schema —\n // the platform side has already validated the shape before sending.\n mint: requiredUnknown,\n});\n\nconst setLogLevelInput = z.strictObject({\n level: z.enum([\"silent\", \"error\", \"warn\", \"info\", \"debug\", \"trace\"]),\n});\n\nconst setStateInput = z.strictObject({\n store: z.string(),\n key: z.string(),\n value: requiredUnknown,\n});\n\nconst lifecycleInput = z.strictObject({\n action: z.enum([\"hibernate\", \"close\", \"shutdown\"]),\n});\n\n/** Levels accepted by the underlying `LogStore.setLevel`. */\nconst VALID_LOG_STORE_LEVELS = new Set<LogLevel>([\"debug\", \"info\", \"warn\", \"error\"]);\n\n/**\n * Build the seven `runner.*` capabilities. Caller registers each with\n * `capabilityRegistry.register(cap, \"agent\")`.\n *\n * The returned capabilities are independent — the caller can also\n * register a subset, e.g. for a stub runner used in tests.\n *\n * @category Runtime\n * @since 3.0.0\n */\nexport function buildRunnerCapabilities(handlers: RunnerCapabilityHandlers): DefinedCapability[] {\n return [\n defineCapability({\n name: \"runner.add_mount\",\n displayName: \"Add mount\",\n description:\n \"Mount a volume into the live session. Used by the platform to attach data sources mid-session.\",\n side: \"agent\",\n origin: RUNNER_CAP_ORIGIN,\n audience: [\"runtime\"],\n kind: \"effect\",\n input: mountDeclarationInput,\n handler: async (input) => {\n if (!handlers.addMount) return notImplemented(\"runner.add_mount\");\n return handlers.addMount({\n declaration: input.declaration,\n preMintedToken: input.preMintedToken,\n });\n },\n }),\n defineCapability({\n name: \"runner.add_connector\",\n displayName: \"Add connector\",\n description:\n \"Connect a tool-providing connector into the live session. Used by the platform to attach databases, APIs, etc. mid-session.\",\n side: \"agent\",\n origin: RUNNER_CAP_ORIGIN,\n audience: [\"runtime\"],\n kind: \"effect\",\n input: connectorDeclarationInput,\n handler: async (input) => {\n if (!handlers.addConnector) return notImplemented(\"runner.add_connector\");\n return handlers.addConnector({\n declaration: input.declaration,\n preMintedToken: input.preMintedToken,\n });\n },\n }),\n defineCapability({\n name: \"runner.remove_resource\",\n displayName: \"Remove resource\",\n description:\n \"Detach a mount or connector by id. The id namespace is shared across both kinds.\",\n side: \"agent\",\n origin: RUNNER_CAP_ORIGIN,\n audience: [\"runtime\"],\n kind: \"effect\",\n input: removeResourceInput,\n handler: async (input) => {\n if (!handlers.removeResource) return notImplemented(\"runner.remove_resource\");\n return handlers.removeResource(input);\n },\n }),\n defineCapability({\n name: \"runner.update_credential\",\n displayName: \"Update credential\",\n description:\n \"Replace the pre-minted credential on an existing mount or connector. Used for proactive rotation before TTL expiry.\",\n side: \"agent\",\n origin: RUNNER_CAP_ORIGIN,\n audience: [\"runtime\"],\n kind: \"effect\",\n input: updateCredentialInput,\n handler: async (input) => {\n if (!handlers.updateCredential) return notImplemented(\"runner.update_credential\");\n return handlers.updateCredential({\n kind: input.kind,\n id: input.id,\n mint: input.mint as CredentialMint,\n });\n },\n }),\n defineCapability({\n name: \"runner.set_log_level\",\n displayName: \"Set log level\",\n description:\n \"Live-update the in-container LogStore minimum level without restarting the session.\",\n side: \"agent\",\n origin: RUNNER_CAP_ORIGIN,\n audience: [\"runtime\"],\n kind: \"effect\",\n input: setLogLevelInput,\n handler: async (input) => {\n if (handlers.setLogLevel) {\n return handlers.setLogLevel(input);\n }\n // Default behaviour matches the legacy `set_log_level` command:\n // adjust the process-singleton LogStore directly. The cap input\n // accepts 6 levels per the v3 spec for forward-compatibility with\n // `silent` / `trace`, but `LogStore.setLevel` only knows the four\n // canonical ones — drop unknown values silently.\n const candidate = input.level as LogLevel;\n if (VALID_LOG_STORE_LEVELS.has(candidate)) {\n getLogStore()?.setLevel(candidate);\n }\n return { ok: true };\n },\n }),\n defineCapability({\n name: \"runner.set_state\",\n displayName: \"Set state\",\n description:\n \"Write into the session shared state store. Shape matches the legacy state_action command body.\",\n side: \"agent\",\n origin: RUNNER_CAP_ORIGIN,\n audience: [\"runtime\"],\n kind: \"effect\",\n input: setStateInput,\n handler: async (input) => {\n if (!handlers.setState) {\n // Honour the protocol contract by returning a structured\n // not_implemented error; callers can detect the gap without\n // a thrown exception. Cast through unknown because the cap's\n // declared output is `{ ok: true }` per the legacy shape.\n return notImplemented(\"runner.set_state\") as unknown as { ok: true };\n }\n return handlers.setState({\n store: input.store,\n key: input.key,\n value: input.value,\n });\n },\n }),\n defineCapability({\n name: \"runner.lifecycle\",\n displayName: \"Session lifecycle\",\n description:\n \"Transition the session lifecycle: hibernate to disk, close the active flow, or shut down the runner.\",\n side: \"agent\",\n origin: RUNNER_CAP_ORIGIN,\n audience: [\"runtime\"],\n kind: \"effect\",\n input: lifecycleInput,\n handler: async (input) => {\n if (!handlers.lifecycle) {\n return notImplemented(\"runner.lifecycle\") as unknown as { ok: true };\n }\n return handlers.lifecycle(input);\n },\n }),\n ];\n}\n","/**\n * Credentials-file helpers used by `serve.ts` for Claude Code subscription\n * credentials. Extracted so other modules (e.g. AI 401 mediation) can reuse\n * the atomic rewrite without importing from the much larger `serve.ts`.\n *\n * @category Credentials\n * @since 3.3.0\n */\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { mkdir, rename, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\n/**\n * Well-known platform key for the Claude Code OAuth credentials JSON blob\n * forwarded by `provision_secrets`. The runner writes it to\n * `<home>/.claude/.credentials.json` instead of the secret provider since\n * the SDK reads it as a file.\n *\n * @docLink packages/runner/dev-guide#environment-variables\n */\nexport const CLAUDE_CODE_CREDENTIALS_KEY = \"CLAUDE_CODE_CREDENTIALS_JSON\";\n\n/**\n * Writes the Claude Code credentials JSON blob to the Claude user config dir\n * at the current canonical Linux path, `~/.claude/.credentials.json`, with\n * mode `0600`. Creates the parent directory with mode `0700` if needed.\n *\n * Atomic via tmp-file + rename within the same directory.\n *\n * Exported for unit tests + the AI 401 mediation helper.\n *\n * @docLink packages/runner/dev-guide#environment-variables\n */\nexport async function writeClaudeCodeCredentialsFile(home: string, json: string): Promise<string> {\n const claudeDir = join(home, \".claude\");\n await mkdir(claudeDir, { recursive: true, mode: 0o700 });\n const finalPath = join(claudeDir, \".credentials.json\");\n const tmpPath = `${finalPath}.tmp.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}`;\n await writeFile(tmpPath, json, { mode: 0o600 });\n await rename(tmpPath, finalPath); // POSIX atomic on same fs\n return finalPath;\n}\n\n/**\n * Atomically merge a fresh `accessToken` into the credentials JSON at\n * `<home>/.claude/.credentials.json`, preserving any other top-level fields\n * and the nested `claudeAiOauth` shape the platform writes at provision time.\n *\n * Read-modify-write under {@link writeClaudeCodeCredentialsFile}'s atomic-\n * rename semantics. Used by the runner's `onAuthError` callback (in\n * `serve.ts`) when the bridge driver asks for a credential refresh after\n * a 401 from the underlying agent.\n *\n * @param home - The home directory under which `.claude/.credentials.json`\n * lives.\n * @param accessToken - The fresh access token to persist.\n * @param expiresAt - Optional ISO timestamp for the rotated token.\n * @returns The path to the rewritten credentials file.\n *\n * Spec: `_devlog/specs/2026-05-07-unified-credential-mediation.md`\n * § \"Runner-side handling on 401\" (now bridge-side).\n */\nexport async function mergeAndRewriteCredentialsFile(\n home: string,\n accessToken: string,\n expiresAt?: string | null,\n): Promise<string> {\n const credPath = join(home, \".claude\", \".credentials.json\");\n let merged: Record<string, unknown> = {};\n if (existsSync(credPath)) {\n try {\n merged = JSON.parse(readFileSync(credPath, \"utf-8\")) as Record<string, unknown>;\n } catch {\n merged = {};\n }\n }\n const oauthBlock = ((merged as { claudeAiOauth?: Record<string, unknown> }).claudeAiOauth ??\n {}) as Record<string, unknown>;\n oauthBlock.accessToken = accessToken;\n if (expiresAt) oauthBlock.expiresAt = expiresAt;\n (merged as { claudeAiOauth?: Record<string, unknown> }).claudeAiOauth = oauthBlock;\n // Top-level accessToken too, for SDK builds that read the flat shape.\n (merged as { accessToken?: string }).accessToken = accessToken;\n return writeClaudeCodeCredentialsFile(home, JSON.stringify(merged));\n}\n\n/**\n * Extract the access-token expiry from a raw Claude Code credentials JSON\n * blob. Supports both the nested `claudeAiOauth.expiresAt` shape the\n * platform writes at provision time and an optional top-level `expiresAt`\n * field used by some SDK builds.\n *\n * Returns `null` when the field is missing, empty, or not a parseable\n * date — callers treat `null` as \"static token, don't schedule a\n * proactive refresh\". Tolerates both ISO-8601 strings and millisecond\n * epochs (some Claude Code builds emit the epoch; normalise to ISO so\n * downstream code has one format to reason about).\n *\n * Used by the runner's proactive AI-credential refresh scheduler in\n * `serve.ts` to compute the next refresh fire time after a fresh\n * credential lands (initial provision OR `host.refresh_credential`\n * response). The runner never mutates the credentials blob; this is a\n * pure read.\n *\n * @docLink packages/runner/dev-guide#ai-credential-mediation\n */\nexport function extractClaudeAiOauthExpiresAt(json: string): string | null {\n let parsed: unknown;\n try {\n parsed = JSON.parse(json);\n } catch {\n return null;\n }\n if (!parsed || typeof parsed !== \"object\") return null;\n const obj = parsed as Record<string, unknown>;\n const oauth = obj.claudeAiOauth as Record<string, unknown> | undefined;\n const raw = oauth?.expiresAt ?? obj.expiresAt;\n if (raw == null) return null;\n if (typeof raw === \"string\") {\n const t = Date.parse(raw);\n return Number.isFinite(t) ? new Date(t).toISOString() : null;\n }\n if (typeof raw === \"number\" && Number.isFinite(raw)) {\n // Epoch milliseconds (Claude Code subscription tokens encode it this way).\n return new Date(raw).toISOString();\n }\n return null;\n}\n","/**\n * Session stimulus bus — generic trailing-edge coalescing turn driver.\n *\n * Connectors that observe state changes (FlowAdapter, future alert/inbox/\n * file-watch connectors) call `bus.signal(connectorId, { promptFragment, meta })`\n * to request that the agent be woken with a fresh turn. Multiple signals from\n * the same connector arriving within `coalesceMs` are folded into one turn,\n * with their `promptFragment`s concatenated by `\\n\\n` and their `meta` objects\n * collected into an array.\n *\n * Per-`connectorId` queues — concurrent connectors NEVER coalesce together;\n * each runs its own pending timer and turn pipeline.\n *\n * If `signal()` is called for a connector whose driveTurn is already in flight,\n * the new signal queues for the next cycle (a fresh timer starts only after\n * the in-flight turn settles).\n *\n * Distinct from `refresh-flag-dispatcher.ts`'s leading-edge debounce: that one\n * fires immediately and drops within a 2 s window. The stimulus bus is trailing-\n * edge collapse with a returned promise, so callers can `await` completion of\n * the turn that drained their signal.\n *\n * @docLink runner#session-stimulus-bus\n * @since 2.2.0\n */\n\nimport type { Logger } from \"@skaile/workspaces/types\";\n\n/**\n * One stimulus from a connector. The bus collapses contiguous signals from the\n * same connector into a single turn whose prompt is built by joining the\n * `promptFragment`s with `\\n\\n`.\n */\nexport interface StimulusSignal {\n /** Fragment the connector wants prepended to the next turn prompt. */\n promptFragment: string;\n /** Optional event metadata for tracing. Connector-defined. */\n meta?: Record<string, unknown>;\n /**\n * Trailing-edge coalesce window — multiple signals from the same connector\n * arriving within this many ms are folded into one turn with their\n * fragments concatenated. Default: 50 ms (a tick to let near-simultaneous\n * signals settle without perceptible delay).\n */\n coalesceMs?: number;\n}\n\n/**\n * Public surface returned by `createSessionStimulusBus`. Connectors hold a\n * reference to this and call `signal(...)` whenever they want to wake the\n * agent.\n */\nexport interface SessionStimulusBus {\n /**\n * Request a turn kick for `connectorId`. Resolves once the resulting turn\n * has drained (the supplied `driveTurn` resolved). Multiple parallel calls\n * within `coalesceMs` collapse into one turn and share a single resolution.\n */\n signal(connectorId: string, sig: StimulusSignal): Promise<void>;\n}\n\n/**\n * Drives one agent turn given a concatenated prompt fragment. The runner\n * supplies this when constructing the bus — typically wraps `driver.prompt`\n * + waits for `agent_end`. The bus calls it with all coalesced fragments\n * joined by newline.\n */\nexport type TurnDriver = (\n promptFragment: string,\n batchedMeta: Array<Record<string, unknown>>,\n) => Promise<void>;\n\nexport interface CreateStimulusBusOptions {\n driveTurn: TurnDriver;\n /** Default coalesce window when a signal omits its own. */\n defaultCoalesceMs?: number;\n log?: Logger;\n}\n\n/** Default coalesce window — kept consistent with the spec's stated default. */\nexport const DEFAULT_COALESCE_MS = 50;\n\ninterface PendingEntry {\n signal: StimulusSignal;\n resolve: () => void;\n reject: (err: unknown) => void;\n}\n\ninterface ConnectorQueue {\n /** Buffered entries waiting for the current timer to fire. */\n pending: PendingEntry[];\n /** The timer that will fire `flushQueue`. `null` when no timer is active. */\n timer: ReturnType<typeof setTimeout> | null;\n /**\n * `true` when `driveTurn` is currently running for this connector. New\n * signals arriving while this is set queue up but do NOT start their timer\n * until the in-flight turn settles.\n */\n inFlight: boolean;\n}\n\n/**\n * Construct a fresh stimulus bus. The caller (typically `serve.ts` or\n * `run-flow.ts`) provides `driveTurn`, which kicks one agent turn given a\n * joined prompt + batched meta, and resolves once the turn drains.\n */\nexport function createSessionStimulusBus(opts: CreateStimulusBusOptions): SessionStimulusBus {\n const { driveTurn, defaultCoalesceMs = DEFAULT_COALESCE_MS, log } = opts;\n const queues = new Map<string, ConnectorQueue>();\n\n function getQueue(connectorId: string): ConnectorQueue {\n let q = queues.get(connectorId);\n if (!q) {\n q = { pending: [], timer: null, inFlight: false };\n queues.set(connectorId, q);\n }\n return q;\n }\n\n function startTimerIfNeeded(connectorId: string, q: ConnectorQueue, coalesceMs: number) {\n if (q.timer != null) return;\n if (q.inFlight) return; // wait until the in-flight turn settles\n q.timer = setTimeout(() => {\n q.timer = null;\n void flushQueue(connectorId, q);\n }, coalesceMs);\n }\n\n async function flushQueue(connectorId: string, q: ConnectorQueue): Promise<void> {\n if (q.pending.length === 0) return;\n const batch = q.pending;\n q.pending = [];\n q.inFlight = true;\n\n const fragments = batch.map((e) => e.signal.promptFragment);\n const metas = batch\n .map((e) => e.signal.meta)\n .filter((m): m is Record<string, unknown> => m !== undefined);\n const joined = fragments.join(\"\\n\\n\");\n\n log?.debug(\"turn driving\", {\n connectorId,\n count: batch.length,\n fragmentLength: joined.length,\n });\n\n try {\n await driveTurn(joined, metas);\n log?.debug(\"turn drained\", {\n connectorId,\n count: batch.length,\n fragmentLength: joined.length,\n });\n for (const entry of batch) entry.resolve();\n } catch (err) {\n log?.debug(\"turn failed\", {\n connectorId,\n count: batch.length,\n fragmentLength: joined.length,\n error: err instanceof Error ? err.message : String(err),\n });\n for (const entry of batch) entry.reject(err);\n } finally {\n q.inFlight = false;\n // If signals arrived while the turn was in flight, kick a fresh timer\n // for the next cycle so the next batch drains.\n if (q.pending.length > 0) {\n // Use the most recent signal's coalesceMs as the next window — it's\n // the simplest predictable choice when callers may have heterogeneous\n // windows.\n const nextWindow = q.pending[q.pending.length - 1]?.signal.coalesceMs ?? defaultCoalesceMs;\n startTimerIfNeeded(connectorId, q, nextWindow);\n }\n }\n }\n\n return {\n signal(connectorId: string, sig: StimulusSignal): Promise<void> {\n const coalesceMs = sig.coalesceMs ?? defaultCoalesceMs;\n log?.debug(\"stimulus signaled\", {\n connectorId,\n fragmentLength: sig.promptFragment.length,\n });\n return new Promise<void>((resolve, reject) => {\n const q = getQueue(connectorId);\n q.pending.push({ signal: sig, resolve, reject });\n startTimerIfNeeded(connectorId, q, coalesceMs);\n });\n },\n };\n}\n","/**\n * serve.ts — WebSocket agent server.\n *\n * Exposes the agent runtime over a pluggable transport. Accepts AgentCommand\n * messages and streams AgentEvent responses. Uses WebSocketServerTransport for\n * the default transport (pass opts.transport to override for testing/stdio).\n *\n * Usage:\n * skaile serve --project-dir /project --port 8080\n *\n * The platform's session manager connects via AgentClient + WebSocketClientTransport\n * to drive agent execution inside a local subprocess or Docker container.\n *\n * ─── Session Startup Pattern ───────────────────────────────────────────────────\n *\n * All three runner modes (REPL, flow, serve) follow the same 5-step setup:\n * 1. resolveSettings() → driver, model, provider, API key\n * 2. loadAgentManifest() → manifest (model/maxTurns/tools); optionally systemPrompt\n * 3. buildAgentResources() → ConnectorManager, resourcePromptSection, mcpServers\n * 4. createDriver() → AgentDriver with assembled systemPrompt\n * 5. driver.start() → subprocess spawn / SDK import\n *\n * Differences between modes:\n * REPL — identity native (agentDir/agentName); systemPrompt = resource docs only; eager start\n * Flow — identity injected (full SOUL+RULES+knowledge); no transport; single orchestrator prompt\n * Serve — identity injected + external (SKAILE_SYSTEM_PROMPT_FILE); lazy start (first prompt cmd);\n * adds EventNormalizer, resource watch callbacks, lifecycle command handling\n *\n * The shared `createAgentSession(opts)` helper in session-builder.ts extracts the\n * common setup sequence. serve.ts retains: EventNormalizer, lazy start (driverStarted flag),\n * transport setup, and lifecycle command handling.\n */\n\nimport {\n existsSync,\n type FSWatcher,\n watch as fsWatch,\n mkdirSync,\n readFileSync,\n writeFileSync,\n} from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\nimport {\n deployCatalogEntry,\n undeployCatalogEntry,\n} from \"@skaile/workspaces/asset-manager/catalog-deployer\";\nimport type { FlowDefinition } from \"@skaile/workspaces/base-assets/connectors/flow/engine\";\nimport {\n buildOrchestratorPrompt,\n renderStimulusPrompt,\n type TurnStimulus,\n} from \"@skaile/workspaces/base-assets/connectors/flow/prompt-fragments\";\nimport { type AgentEvent as BridgeAgentEvent, EventNormalizer } from \"@skaile/workspaces/bridge\";\nimport {\n buildSdkConnectorTools,\n type ConnectorHandle,\n ConnectorManager,\n type FlowAdapter,\n InMemorySecretProvider,\n PreMintedSecretProvider,\n registerBuiltinConnectors,\n} from \"@skaile/workspaces/connectors\";\nimport {\n type CatalogEntry,\n parseAssetRef,\n providerEnvKey,\n resolveAgentDir,\n resolveSkWorkspaceConfig,\n} from \"@skaile/workspaces/core\";\nimport { createLogger, WsLogSink } from \"@skaile/workspaces/core/logging\";\nimport { WebSocketServerTransport } from \"@skaile/workspaces/transport\";\nimport type {\n AgentCommand,\n AgentEvent,\n ConnectorInfo,\n FlowExecution,\n MountInfo,\n ServerTransport,\n} from \"@skaile/workspaces/types\";\nimport { PROTOCOL_VERSION } from \"@skaile/workspaces/types\";\n// Static import so bun --compile bundles zod into the binary. Without this,\n// dynamic import(\"zod\") fails at runtime inside the /$bunfs/ virtual filesystem.\nimport { z as _z } from \"zod\";\nimport { createAiCredentialRefreshScheduler } from \"./ai-credential-refresh.js\";\nimport { bootstrapCapabilityRegistry } from \"./builtin-capabilities.js\";\nimport { CapabilityRegistry, computeCapabilitySignature } from \"./capability-registry.js\";\nimport {\n buildClientCapabilityHandler as buildClientCapabilityRoundtripHandler,\n DEFAULT_CAPABILITY_CALL_TIMEOUT_MS,\n type PendingCallEntry,\n rejectCapabilityOnApprovalDeny,\n resolveCapabilityCallTimeoutMs,\n resolveCapabilityResult,\n} from \"./capability-roundtrip.js\";\nimport { CompactionOrchestrator } from \"./compaction/index.js\";\nimport { registerCompositionCapabilities } from \"./composition/bootstrap.js\";\nimport { type MountPoint, rewriteFileChangedPath } from \"./file-changed-rewriter.js\";\nimport { bootstrapRunnerLogStore } from \"./logging-bootstrap.js\";\nimport { buildCapabilitiesPromptSection } from \"./prompt-assembly.js\";\nimport { dispatchRefreshToExposedGitMounts } from \"./refresh-flag-dispatcher.js\";\nimport { handleMountResourceRequest, handleResourceRequest } from \"./resource-handler.js\";\nimport { buildRunnerCapabilities } from \"./runner-capabilities.js\";\nimport {\n CLAUDE_CODE_CREDENTIALS_KEY,\n extractClaudeAiOauthExpiresAt,\n mergeAndRewriteCredentialsFile,\n writeClaudeCodeCredentialsFile,\n} from \"./serve-credentials.js\";\nimport {\n type AgentSession,\n type AgentSessionConfig,\n createAgentSession,\n} from \"./session-builder.js\";\nimport { createSessionStimulusBus, type SessionStimulusBus } from \"./session-stimulus.js\";\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Pull catalog entries from the active session's runtime assets, with a safe\n * fallback to empty when the session was not yet created or the resolver\n * failed. The session-builder caches the same `RuntimeAssetsResult` across\n * the session lifetime so live-update paths see a stable view.\n */\nfunction getSessionCatalogEntries(session: AgentSession | undefined): CatalogEntry[] {\n return session?.runtimeAssets?.catalogEntries ?? [];\n}\n\n/**\n * Emit a `system_prompt_composed` event carrying the labeled section\n * breakdown from the freshly-built {@link AgentSession}. Called from every\n * `createAgentSession` consumer in serve.ts (initial bootstrap, configure\n * re-runs, add_resource flow-connector path, aiResources skill changes,\n * session_init provisioned path) so the platform's debug panel always sees\n * the prompt the agent is actually receiving.\n *\n * Keeping the emission centralised in serve.ts (rather than inside\n * session-builder.ts) preserves the builder's transport-agnostic contract —\n * forge apps and the CLI consume the same builder without a transport.\n *\n * Spec: `docs/superpowers/specs/2026-05-13-platform-agent-prompt-design.md`\n * § 3.3.2 Re-emission requirement.\n * @since 2026-05\n */\nexport function emitSystemPromptComposed(\n agentSession: AgentSession,\n sendEvent: (e: AgentEvent) => void,\n): void {\n sendEvent({\n type: \"system_prompt_composed\",\n sections: agentSession.systemPromptSections,\n composedAt: new Date().toISOString(),\n });\n}\n\n/** Collect installed @skaile/* package versions. Cached per process. */\nconst FRAMEWORK_PACKAGES = [\n \"@skaile/workspaces/runner\",\n \"@skaile/workspaces/bridge\",\n \"@skaile/workspaces/core\",\n \"@skaile/workspaces/types\",\n \"@skaile/workspaces/base-assets\",\n \"@skaile/workspaces/connectors\",\n \"@skaile/workspaces/resolver\",\n \"@skaile/workspaces/transport\",\n \"@skaile/workspaces/workspace-plugin\",\n] as const;\n\nlet _frameworkVersions: Record<string, string> | null = null;\nfunction getFrameworkVersions(): Record<string, string> {\n if (_frameworkVersions) return _frameworkVersions;\n const versions: Record<string, string> = {};\n for (const pkg of FRAMEWORK_PACKAGES) {\n try {\n const pjPath = require.resolve(`${pkg}/package.json`);\n const pj = JSON.parse(readFileSync(pjPath, \"utf-8\"));\n versions[pkg.replace(\"@skaile/\", \"\")] = pj.version;\n } catch {\n // not installed\n }\n }\n _frameworkVersions = versions;\n return versions;\n}\n\n// ---------------------------------------------------------------------------\n// Resource lifecycle helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Split a unified `ConnectorManager`'s connectors into the wire-shape\n * `mounts` / `connectors` arrays the `resources_available` event expects.\n *\n * Filesystem-face connectors (those with a `mountPath`) are reported as\n * mounts; the rest are reported as connectors. The unified manager owns both,\n * so this is purely a wire-format projection.\n */\nfunction splitConnectorsForWire(manager: ConnectorManager | null): {\n mounts: MountInfo[];\n connectors: ConnectorInfo[];\n} {\n const mounts: MountInfo[] = [];\n const connectors: ConnectorInfo[] = [];\n if (!manager) return { mounts, connectors };\n for (const c of manager.listConnectors()) {\n if (typeof c.mountPath === \"string\") {\n let source = \"\";\n try {\n source = manager.get(c.id).declaration.mount?.source ?? \"\";\n } catch {\n /* connector vanished between list and get — best-effort */\n }\n mounts.push({\n id: c.id,\n driver: c.driver,\n access: c.access,\n mountPath: c.mountPath,\n mounted: true,\n source,\n });\n } else {\n connectors.push({\n id: c.id,\n driver: c.driver,\n access: c.access,\n operations: manager.getOperations(c.id).map((op) => op.name),\n });\n }\n }\n return { mounts, connectors };\n}\n\n/** Walk upward from a directory looking for an ai-assets/ folder. */\nfunction findAiAssetsRoot(startDir: string): string | null {\n let dir = startDir;\n for (let i = 0; i < 6; i++) {\n const candidate = join(dir, \"ai-assets\");\n if (existsSync(candidate)) return candidate;\n dir = join(dir, \"..\");\n }\n return null;\n}\n\n/**\n * Phase 4.8 — Claude Code subscription credentials provisioning.\n *\n * The constant + the atomic rewrite helper now live in `./serve-credentials.ts`\n * so the AI 401 mediation helper can reuse them without importing from this\n * (large) module. Re-exported here for back-compat with existing test\n * imports of `serve.js`.\n *\n * @docLink packages/runner/dev-guide#environment-variables\n */\nexport {\n CLAUDE_CODE_CREDENTIALS_KEY,\n extractClaudeAiOauthExpiresAt,\n writeClaudeCodeCredentialsFile,\n};\n\n/**\n * Idempotently ensure `~/.gitconfig` includes the runner-managed gitconfig\n * via `[include] path = <managedGitconfigPath>`. Fallback path for shells\n * that strip `GIT_CONFIG_GLOBAL`. The function is idempotent — running it\n * twice produces the same file content.\n *\n * Exported for unit tests.\n * @docLink packages/runner/capabilities#ensure-git-config-include\n */\nexport function ensureGitConfigInclude(managedGitconfigPath: string): void {\n const home = process.env.HOME ?? homedir();\n if (!home) return;\n const gitconfigPath = join(home, \".gitconfig\");\n let existing = \"\";\n try {\n existing = readFileSync(gitconfigPath, \"utf-8\");\n } catch {\n // file doesn't exist — fall through and create\n }\n // Bail if any include block already references our managed file. Walk the\n // gitconfig line-by-line tracking the current section header so a stray\n // `path = …` key inside an unrelated section (e.g. `[some-other] path = …`)\n // does not trigger a false-positive match. Git only honours `path` keys\n // under `[include]` and `[includeIf \"<cond>\"]`; mirror that contract here.\n const sectionRe = /^\\s*\\[([^\\]\\s]+)(?:\\s+\"[^\"]*\")?\\]\\s*$/;\n const pathKeyRe = /^\\s*path\\s*=\\s*(.+?)\\s*$/;\n let currentSection: string | null = null;\n for (const line of existing.split(/\\r?\\n/)) {\n const sectionMatch = line.match(sectionRe);\n if (sectionMatch) {\n currentSection = sectionMatch[1]?.toLowerCase() ?? null;\n continue;\n }\n if (currentSection !== \"include\" && currentSection !== \"includeif\") continue;\n const pathMatch = line.match(pathKeyRe);\n if (pathMatch?.[1] === managedGitconfigPath) return;\n }\n if (!existsSync(dirname(gitconfigPath))) {\n mkdirSync(dirname(gitconfigPath), { recursive: true });\n }\n const block =\n `${existing.trimEnd()}\\n` +\n `# skaile-runner: managed-gitconfig include\\n` +\n `[include]\\n\\tpath = ${managedGitconfigPath}\\n`;\n writeFileSync(gitconfigPath, block, { mode: 0o644 });\n}\n\n// v3 protocol — handleRemountMount removed alongside the RemountMountCommand\n// wire type. Hot remounting is now reachable through the runner.add_mount\n// capability (the platform's invokeRunnerCapability dispatch path), which\n// handles the disconnect+connect semantics via the ConnectorManager surface.\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/**\n * Configuration for {@link startAgentServer}.\n * @docLink packages/runner/dev-guide#flow-execution-turn-based-model\n */\nexport interface ServeOptions {\n /**\n * WebSocket server port. Defaults to `8080`.\n * Ignored when a custom {@link transport} is provided.\n */\n port?: number;\n /** Absolute path to the project working directory. */\n projectDir: string;\n /**\n * GitAgent definition directory (`agent.yaml`, `SOUL.md`, `RULES.md`,\n * `knowledge/`). When omitted, resolved from `skaile.yaml` via\n * `resolveAgentDir`. If unresolvable, no agent definition is loaded and the\n * agent starts without an identity prompt.\n */\n agentDir?: string;\n /** Agent driver backend override (e.g. `\"omp\"`, `\"claude-sdk\"`). */\n driver?: string;\n /** LLM model name override. */\n model?: string;\n /** LLM provider override (e.g. `\"anthropic\"`, `\"openrouter\"`). */\n provider?: string;\n /** Directory of deployed prompt/command files appended to the system prompt. */\n promptsDir?: string;\n /** Stable session ID for conversation continuity across agent turns. */\n sessionId?: string;\n /**\n * OMP driver session ID to resume. When set, OMP is spawned with\n * `--session <id>` to restore its native conversation context without\n * needing `<conversation_history>` injection. For OMP driver only.\n */\n resumeSessionId?: string;\n /** Called for each diagnostic log line. Defaults to `console.log`. */\n onLog?: (line: string) => void;\n /**\n * Pre-built transport to use instead of the default\n * `WebSocketServerTransport`. Useful for testing (in-process transport,\n * stdio transport) or embedding the server in another process.\n */\n transport?: ServerTransport;\n /**\n * Bearer token the default WebSocket server requires from connecting clients.\n * Falls back to `SKAILE_WS_AUTH_TOKEN`. When neither is set the server accepts\n * unauthenticated connections (back-compatible default). Ignored when a custom\n * {@link transport} is provided.\n */\n authToken?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Server\n// ---------------------------------------------------------------------------\n\n/**\n * Start a WebSocket agent server that the Skaile platform connects to for\n * host-driven agent execution inside a local subprocess or Docker container.\n *\n * The server accepts {@link AgentCommand} messages over a\n * {@link ServerTransport} (default: `WebSocketServerTransport` on `opts.port`)\n * and streams {@link AgentEvent} responses back to the connected client.\n *\n * Handled commands:\n * - `provision_secrets` — injects API keys and Claude Code credentials; in\n * `provisioned` secrets mode, triggers deferred session creation.\n * - `configure` — registers shared state stores and applies mid-session skill\n * catalog changes. Phase 4 of the flow-connector extraction (Protocol 2.2)\n * removed the implicit `activeFlows` rehydration; hosts now issue an\n * explicit `connector_mutate { id: \"flow\", op: \"hydrate\" }` per flow.\n * - `prompt` — routes free-chat messages through the SessionStimulusBus when\n * a flow is active, otherwise forwards directly to the driver; **driver is\n * lazily started on the first `prompt` command**.\n * - `connector_mutate` / `connector_query` — generic connector dispatch.\n * Replaces the 6 typed flow commands removed in Protocol 2.2 (`start_flow`,\n * `approve_flow_node`, `provide_flow_input`, `cancel_flow`,\n * `set_flow_autonomous_mode`, `retry_flow_node`); see\n * `MIGRATION-flow-connector.md` for the per-op mapping table.\n * - `add_resource` / `remove_resource` — mount/unmount mounts or\n * connect/disconnect connectors mid-session. When the added connector's\n * driver is `flow`, the runner injects the per-session stimulus bus into\n * the connect options.\n *\n * The function resolves after the transport starts listening. It does not\n * resolve until the process exits — shutdown is driven by SIGINT/SIGTERM or\n * a `shutdown` command from the connected client.\n *\n * @param opts - Server configuration.\n * @docLink packages/runner/dev-guide#flow-execution-turn-based-model\n */\nexport async function startAgentServer(opts: ServeOptions): Promise<void> {\n const port = opts.port ?? 8080;\n const sessionId = opts.sessionId ?? process.env.SKAILE_SESSION_ID ?? \"session-unknown\";\n const resumeSessionId = opts.resumeSessionId ?? process.env.SKAILE_RESUME_SESSION_ID;\n\n // Read platform maxTurns from workspace config (before createAgentSession)\n const wsConfig = resolveSkWorkspaceConfig(opts.projectDir);\n\n // Bootstrap structured logging — registers a process-singleton LogStore.\n // OnLogBridgeSink mirrors entries to opts.onLog when caller provides it,\n // preserving back-compat with hosts that consume plain text lines.\n const { store: logStore, dispose: disposeLogStore } = bootstrapRunnerLogStore({\n sessionId,\n projectDir: opts.projectDir,\n yamlBlock: (wsConfig as { logging?: unknown }).logging,\n onLog: opts.onLog,\n });\n const serverLog = createLogger({\n kind: \"runner\",\n subkind: \"session\",\n instance: sessionId,\n });\n // Back-compat: keep `log()` as a string alias so existing call sites continue\n // to work; new diagnostics should call serverLog.{info,warn,error,debug} directly.\n const log = (line: string) => serverLog.info(line);\n const profile = wsConfig.agent_config?.default;\n const maxTurns =\n wsConfig.agent?.permissions?.max_turns ??\n ((profile as Record<string, unknown> | undefined)?.max_turns as number | undefined);\n\n // ---------------------------------------------------------------------------\n // Tier-2 managed-gitconfig env propagation (git credential tiers, Step 1A)\n // ---------------------------------------------------------------------------\n //\n // The runner owns one path — `<projectDir>/.skaile/managed-gitconfig` — and\n // exposes it to every spawned agent shell via `GIT_CONFIG_GLOBAL`. The git\n // mount driver writes per-mount tagged blocks into this file when (and only\n // when) `exposeAccessToken: true` is set on the mount declaration. Bridge\n // drivers inherit the runner's env when spawning agent processes, so no\n // change is required on their side.\n //\n // Belt-and-suspenders: also write `[include] path = …` into `~/.gitconfig`\n // so shells that strip `GIT_CONFIG_GLOBAL` still pick the file up. The\n // include is idempotent — a second run will not append a duplicate line.\n //\n // Spec: `_devlog/specs/2026-05-05-git-credential-tiers.md`.\n const managedGitconfigPath = join(opts.projectDir, \".skaile\", \"managed-gitconfig\");\n process.env.GIT_CONFIG_GLOBAL = managedGitconfigPath;\n try {\n ensureGitConfigInclude(managedGitconfigPath);\n } catch (err) {\n serverLog.warn(\"failed to write ~/.gitconfig include — relying on env only\", {\n error: err instanceof Error ? err.message : String(err),\n });\n }\n\n // Resolve the agent definition directory. CLI flag wins; otherwise fall back\n // to skaile.yaml `agent.definition` via resolveAgentDir. Without this, the\n // agent identity (SOUL+RULES+knowledge) is rendered at install time, not loaded at runtime.\n const agentDir = opts.agentDir ?? resolveAgentDir(opts.projectDir);\n if (agentDir) {\n serverLog.info(\"agent dir resolved\", { agentDir });\n } else {\n serverLog.warn(\"no agent definition found in skaile.yaml\");\n }\n\n // ---------------------------------------------------------------------------\n // Transport setup (must be before resource init — sync callbacks use sendEvent)\n // ---------------------------------------------------------------------------\n\n const authToken = opts.authToken ?? process.env.SKAILE_WS_AUTH_TOKEN;\n const transport: ServerTransport =\n opts.transport ??\n new WebSocketServerTransport({ port, onLog: log, ...(authToken ? { authToken } : {}) });\n\n // Wire structured log forwarding: every LogEntry recorded by the in-container\n // LogStore is emitted as a `log_entry` AgentEvent over the same transport\n // the gateway already subscribes to. The transport drops sends when no client\n // is connected, so no buffering is needed here.\n logStore.addSink(\n new WsLogSink({\n send: (event) => {\n if (transport.connected) transport.send(event);\n },\n }),\n );\n\n // Forward agent events to the connected client\n function sendEvent(event: AgentEvent) {\n if (transport.connected) {\n transport.send(event);\n }\n }\n\n // ---------------------------------------------------------------------------\n // Capability registry (Protocol v2)\n // ---------------------------------------------------------------------------\n //\n // Single per-session registry. Built-in `__capabilities.list/search/describe`\n // are registered at boot. Client-side capabilities arrive via\n // ConfigureCommandV2.capabilities in the v2 configure handler below.\n //\n // The registry is constructed eagerly (before session creation) so the\n // bridge can pull tool definitions through `BridgeCapabilityHooks` on its\n // first turn. Built-ins are registered immediately; downstream registrations\n // (skills/connectors/mounts/client) happen at their own lifecycles.\n\n const capabilityRegistry = new CapabilityRegistry(\n createLogger({\n kind: \"runner\",\n subkind: \"capability-registry\",\n instance: sessionId,\n }),\n );\n bootstrapCapabilityRegistry(capabilityRegistry);\n\n // ---------------------------------------------------------------------------\n // Client-side capability round-trip (Protocol v2)\n // ---------------------------------------------------------------------------\n //\n // When the LLM invokes a `side: 'client'` capability, the bridge calls the\n // registry's invoke() which delegates to the per-capability handler. For\n // client-side caps the handler emits a `capability_invoked` event over the\n // transport, registers a pending promise keyed by `callId`, and waits for\n // a `capability_result` command from the platform. `fireAndForget` caps\n // bypass the pending map (the bridge also short-circuits in\n // `dispatchCapability`, so this is defence-in-depth).\n const pendingCapabilityCalls = new Map<string, PendingCallEntry>();\n\n // ---------------------------------------------------------------------------\n // Outbound capability invocation (Protocol v3)\n // ---------------------------------------------------------------------------\n //\n // The runner invokes `host.*` capabilities on the platform through the same\n // `capability_invoked` / `capability_result` round-trip already used for\n // client-side capabilities — just in the opposite direction. The pending\n // map is shared (`pendingCapabilityCalls`) since the wire shape is identical.\n //\n // Spec: `_devlog/specs/2026-05-10-deterministic-session-bootstrap.md`\n // § \"Bidirectional capability registry as RPC backbone\".\n const remoteCapabilityInvoker = (name: string, input: unknown): Promise<unknown> => {\n const callId =\n typeof crypto?.randomUUID === \"function\"\n ? crypto.randomUUID()\n : `rcap-${Date.now()}-${Math.floor(Math.random() * 1e9)}`;\n return new Promise<unknown>((resolve, reject) => {\n if (!transport.connected) {\n reject(new Error(`Transport disconnected; cannot invoke remote capability ${name}`));\n return;\n }\n const timer = setTimeout(() => {\n pendingCapabilityCalls.delete(callId);\n reject(new Error(`Remote capability ${name} (callId=${callId}) timed out`));\n }, DEFAULT_CAPABILITY_CALL_TIMEOUT_MS);\n pendingCapabilityCalls.set(callId, { resolve, reject, timer });\n transport.send({\n type: \"capability_invoked\",\n callId,\n name,\n input,\n invokedBy: \"agent\",\n });\n });\n };\n\n /**\n * Per-session AI provider config id, threaded in via `ConfigureCommandV2.config.aiProviderConfigId`.\n * Read by the auth-error retry handler to fill `request_access_token { kind: 'ai-credentials', configId }`.\n * Standalone runners (CLI / forge / Claude plugin) never see a configure\n * command with this field, so it stays `undefined` and the auth-error\n * handler falls back to surfacing the error.\n *\n * Spec: `_devlog/specs/2026-05-07-unified-credential-mediation.md`\n * § \"Wire `aiProviderConfigId` end-to-end\".\n */\n let aiProviderConfigId: string | undefined;\n\n /**\n * Inner credential-mediation helper shared by the reactive\n * `onAuthError` callback and the proactive refresh timer. Acquires a\n * fresh access token through `host.refresh_credential`, rewrites\n * `<home>/.claude/.credentials.json`, and returns the typed mint.\n * Successful mints re-arm the proactive scheduler against the freshly\n * issued token's expiry.\n *\n * Declared before `aiCredentialRefreshScheduler` even though the\n * scheduler's `refresh` callback references this — keeps the textual\n * order matching the call graph (mint → schedule re-arm) instead of\n * relying on hoisting semantics that would break under a future\n * arrow-function refactor.\n */\n async function mintAndPersistAiCredential(args: {\n configId?: string;\n reason: \"refresh\" | \"retry-401\";\n }): Promise<import(\"@skaile/workspaces/types\").CredentialMint> {\n if (!transport.connected || aiProviderConfigId === undefined) {\n return {\n ok: false,\n code: \"not-configured\",\n message: \"no transport or aiProviderConfigId; standalone runner cannot mediate refresh\",\n };\n }\n const targetConfigId = args.configId || aiProviderConfigId;\n try {\n const result = (await capabilityRegistry.invokeRemote(\"host.refresh_credential\", {\n kind: \"ai-credentials\",\n id: targetConfigId,\n reason: args.reason,\n })) as import(\"@skaile/workspaces/types\").CredentialMint;\n if (!result?.ok) {\n return result ?? { ok: false, code: \"backend-error\", message: \"no result from host\" };\n }\n const home = process.env.HOME ?? homedir();\n if (!home) {\n return {\n ok: false,\n code: \"backend-error\",\n message: \"HOME env var unset; cannot rewrite credentials file\",\n };\n }\n await mergeAndRewriteCredentialsFile(home, result.token, result.expiresAt ?? null);\n // Re-arm proactive timer for the freshly issued token. The reactive\n // (retry-401) path calls into here too, so retry success also chains\n // the next proactive fire.\n aiCredentialRefreshScheduler.schedule(result.expiresAt ?? null);\n return result;\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n return { ok: false, code: \"backend-error\", message: errMsg };\n }\n }\n\n /**\n * Proactive AI-credential refresh scheduler. Holds a single timer that\n * fires `PROACTIVE_AI_REFRESH_MARGIN_MS` before the current token\n * expires, calls `host.refresh_credential { reason: 'refresh' }`, and\n * re-arms against the new expiry. Pairs with the bridge-side\n * `failTurn` deferral that suppresses downstream auth-error events\n * when a self-heal is about to run: this timer is the primary\n * prevention of in-container 401s, the reactive 401 path is the\n * safety net.\n *\n * Schedule is re-armed on every fresh credential (initial provision,\n * a reactive retry-401 success, or a previous proactive fire). Tokens\n * with `expiresAt === null` (static PATs) do not schedule.\n *\n * Spec: `_devlog/specs/2026-05-07-unified-credential-mediation.md`\n * § \"Proactive refresh\" (added 2026-05-20).\n */\n const aiCredentialRefreshScheduler = createAiCredentialRefreshScheduler({\n refresh: async () => {\n const result = await mintAndPersistAiCredential({ reason: \"refresh\" });\n if (!result.ok) {\n log(\n `[serve] proactive AI refresh failed (code=${result.code}); leaving reactive path as fallback`,\n );\n return undefined;\n }\n return result.expiresAt ?? null;\n },\n log,\n });\n\n /**\n * Auth-refresh callback handed to the bridge driver via\n * `AgentConfig.onAuthError`. The bridge invokes this when its underlying\n * agent surfaces an `authentication_error`. We ask the platform for a\n * fresh access token, atomically rewrite `~/.claude/.credentials.json`,\n * and resolve `true` so the driver retries the in-flight prompt once.\n *\n * Centralising auth retry inside the driver removes the per-call-site\n * wrapping that previously lived around `driver.prompt(...)`. Compaction,\n * flow turns, the serve handler, and any future call site all benefit\n * automatically.\n *\n * Standalone CLI / forge sessions never set `aiProviderConfigId`, so\n * this returns `false` and the driver surfaces the original `AuthError`\n * to the caller — preserving the legacy behaviour.\n *\n * Spec: `_devlog/specs/2026-05-07-unified-credential-mediation.md`\n * § \"Runner-side handling on 401\" (now bridge-side).\n */\n /**\n * Auth-refresh callback handed to the bridge driver via\n * `AgentConfig.onAuthError`. Invoked when the underlying agent surfaces\n * an `authentication_error`. In v3, the runner mediates the fresh\n * credential through `host.refresh_credential` (a `runtime`-audience\n * capability the platform registered at session_init) and returns the\n * typed `CredentialMint` to the driver so it can branch on the\n * discriminator.\n *\n * Standalone CLI / forge sessions never register `host.refresh_credential`\n * (no platform peer), so the invocation fails synchronously and we\n * surface a structured `not_available` mint — preserving the legacy\n * \"no mediator -> surface AuthError\" behaviour.\n *\n * Spec: `_devlog/specs/2026-05-10-deterministic-session-bootstrap.md`\n * § \"Refresh-on-401 routes through host.refresh_credential\".\n */\n const onAuthError = async (args: {\n configId: string;\n }): Promise<import(\"@skaile/workspaces/types\").CredentialMint> => {\n log(\"[serve] auth error: invoking host.refresh_credential capability\");\n const result = await mintAndPersistAiCredential({\n configId: args.configId,\n reason: \"retry-401\",\n });\n if (!result.ok) {\n log(`[serve] auth error: mint failed (code=${result.code}); surfacing`);\n } else {\n log(\"[serve] auth error: rewrote .credentials.json with mediated accessToken\");\n }\n return result;\n };\n\n /**\n * Approval-required client caps (Protocol v2.1) park on the platform until\n * a human responds. Human approvals routinely take minutes, so the default\n * 60-second timeout would cause the runner to abandon the pending call\n * while the platform later still dispatches the side effect. Use a long\n * (15-minute) timeout for `requiresApproval: true` capabilities so the\n * platform's parked-approval lifetime stays inside the runner's window.\n */\n const APPROVAL_REQUIRED_CAPABILITY_TIMEOUT_MS = 15 * 60 * 1000;\n\n function buildClientCapabilityHandler(\n wire: import(\"@skaile/workspaces/types\").Capability,\n ): (input: unknown) => Promise<unknown> {\n // Precedence: an explicit per-capability `callTimeoutMs` wins (e.g.\n // `platform.ask_session` blocks for minutes); otherwise approval-required\n // caps get the long 15-minute window; everything else uses the default.\n const timeoutMs = resolveCapabilityCallTimeoutMs(wire, APPROVAL_REQUIRED_CAPABILITY_TIMEOUT_MS);\n return buildClientCapabilityRoundtripHandler({\n wire,\n pending: pendingCapabilityCalls,\n emit: (event) => sendEvent(event),\n timeoutMs,\n });\n }\n\n /**\n * Build the bridge-facing capability hooks. Drivers consume this through\n * `AgentConfig.capabilities`. The runner owns:\n * - tool list composition (registry.composeLLMTools)\n * - per-handler logging + Zod validation (registry.invoke)\n * - render-event forwarding to the WebSocket client\n * - text fallback emission for clients without a render layer\n */\n function buildCapabilityHooks(): import(\"@skaile/workspaces/bridge\").BridgeCapabilityHooks {\n return {\n sessionId,\n composeTools: () => capabilityRegistry.composeLLMTools(),\n resolve: (name) => {\n const cap = capabilityRegistry.resolve(name);\n if (!cap) return null;\n // Strip runtime-only fields by going through the wire-format `list`.\n return capabilityRegistry.list().find((c) => c.name === name) ?? null;\n },\n invoke: (name, input) => capabilityRegistry.invoke(name, input, { sessionId }),\n emitRender: (event) => sendEvent(event),\n emitText: (text) =>\n sendEvent({\n type: \"text\",\n content: text,\n }),\n };\n }\n\n // ---------------------------------------------------------------------------\n // Composition → capability registration helper\n // ---------------------------------------------------------------------------\n\n /**\n * Register discoverable composition entries from a freshly created session\n * into the capability registry. Inline blocks are already injected into the\n * system prompt by session-builder; this handles only the tool-list entries.\n */\n function registerSessionComposition(session: AgentSession): void {\n if (session.composition?.discoverableEntries.length) {\n registerCompositionCapabilities(capabilityRegistry, session.composition.discoverableEntries);\n log(\n `[serve] registered ${session.composition.discoverableEntries.length} composition capabilities`,\n );\n }\n }\n\n // ---------------------------------------------------------------------------\n // Secret provisioning mode\n // ---------------------------------------------------------------------------\n\n const secretsMode = wsConfig.secrets?.provider ?? \"env\";\n const secretsTimeoutMs = wsConfig.secrets?.timeoutMs ?? 30_000;\n\n // Build the session config factory (secretProvider injected after provisioning)\n function buildSessionConfig(secretProvider?: unknown, apiKey?: string): AgentSessionConfig {\n return {\n projectDir: opts.projectDir,\n agentDir,\n driver: opts.driver,\n model: opts.model,\n provider: opts.provider,\n promptsDir: opts.promptsDir,\n sessionId,\n resumeSessionId,\n maxTurns,\n wsConfig,\n externalPromptFile: process.env.SKAILE_SYSTEM_PROMPT_FILE,\n secretProvider,\n onAuthError,\n ...(apiKey ? { apiKey } : {}),\n // Protocol v2 `<CAPABILITIES>` block — joins each registered capability's\n // `promptFragment` (framework first, then client, then agent-side\n // surfaces). Built lazily inside `buildSessionConfig` so newly registered\n // capabilities (e.g. via mid-session `capability_register` commands) are\n // reflected on the next session rebuild.\n additionalPromptSections: (() => {\n const sections: string[] = [];\n const capSection = buildCapabilitiesPromptSection(capabilityRegistry);\n if (capSection) sections.push(capSection);\n return sections.length > 0 ? sections : undefined;\n })(),\n watch: {\n onSyncStatus: (mountId, status) => {\n sendEvent({\n type: \"sync_status\",\n mountId,\n ...status,\n phase: status.phase as\n | \"enumerating\"\n | \"stubs_ready\"\n | \"downloading\"\n | \"initial_sync_complete\"\n | \"error\",\n });\n if (status.phase === \"stubs_ready\") {\n log(\n `[serve] ${mountId}: file tree ready (${status.totalFiles} files, ${status.stubFiles} stubs)`,\n );\n } else if (status.phase === \"initial_sync_complete\") {\n log(\n `[serve] ${mountId}: sync complete (${status.downloadedFiles}/${status.totalFiles} downloaded)`,\n );\n }\n },\n onFileChanged: (connectorId, event) => {\n sendEvent({\n type: \"file_changed\",\n path: event.path,\n action: event.action,\n mountId: connectorId,\n });\n },\n },\n onLog: (line) => log(`[serve] ${line}`),\n capabilities: buildCapabilityHooks(),\n // v3: pre-minted credentials replace the tokenMediator for initial mints.\n // Refresh routes through `host.refresh_credential` (invoked from the\n // bridge driver's onAuthError callback). The legacy `tokenMediator`\n // wire is gone.\n ...(preMintedSecrets ? { preMintedSecrets } : {}),\n ...(aiProviderConfigId ? { aiProviderConfigId } : {}),\n };\n }\n\n // Session-readiness gate — other command handlers await this promise before\n // accessing agentSession, driver, resourceManager, etc. In env mode it\n // resolves synchronously; in provisioned mode it resolves after\n // createAgentSession completes (which may involve slow mount operations).\n let resolveSessionReady!: () => void;\n let rejectSessionReady!: (err: Error) => void;\n const sessionReady = new Promise<void>((resolve, reject) => {\n resolveSessionReady = resolve;\n rejectSessionReady = reject;\n });\n\n // In provisioned mode we defer session creation until secrets arrive.\n // In env mode we create the session immediately (existing behavior).\n let sessionConfig: AgentSessionConfig;\n let agentSession: AgentSession;\n let secretProvider: unknown;\n\n // v3 protocol — populated by the `session_init` handler. Used for the\n // identity-mismatch shutdown on successive inits and for capability\n // handlers that resolve project-scoped state.\n let runtimeIdentity:\n | import(\"@skaile/workspaces/types\").SessionInitCommand[\"identity\"]\n | undefined;\n\n // v3 protocol — pre-minted credentials delivered with `session_init`.\n // Wired into ConnectorManager via the `preMintedSecrets` option so the\n // initial mint of `auth: backend` connectors is satisfied in-process.\n let preMintedSecrets: PreMintedSecretProvider | undefined;\n\n if (secretsMode === \"provisioned\") {\n log(\"[serve] secrets mode: provisioned — waiting for provision_secrets command\");\n } else {\n sessionConfig = buildSessionConfig();\n agentSession = await createAgentSession(sessionConfig);\n emitSystemPromptComposed(agentSession, sendEvent);\n\n registerSessionComposition(agentSession);\n resolveSessionReady();\n }\n\n // Mutable references — updated after provisioning in provisioned mode\n let resourceManager: any | null = secretsMode === \"env\" ? agentSession!.resourceManager : null;\n\n if (secretsMode === \"env\") {\n if (!agentSession!.provider) {\n log(\n `[serve] WARNING: no API key found for ${agentSession!.provider ?? \"anthropic\"} — agent calls will fail`,\n );\n log(`[serve] Pass via env var (e.g. ANTHROPIC_API_KEY) or .skaile/settings.json`);\n }\n\n if (resourceManager) {\n const watched: string[] = resourceManager.watchedResources ?? [];\n if (watched.length > 0) {\n log(`[serve] watching ${watched.length} resource(s): ${watched.join(\", \")}`);\n }\n }\n }\n\n // Surface runtime-asset resolution warnings (missing drivers, unavailable\n // repositories) as validation_warning events so the platform frontend can\n // show actionable hints. Same event shape as the legacy skill validator.\n // Skip in provisioned mode — the session does not exist yet at this point;\n // warnings will be emitted after createAgentSession runs in the\n // provision_secrets handler.\n if (secretsMode === \"env\" && agentSession!.runtimeAssets) {\n for (const w of agentSession!.runtimeAssets.warnings) {\n const asset =\n w.code === \"missing_driver\" && w.declarationId\n ? `${w.declarationId} → ${w.name ?? \"unknown\"}`\n : (w.name ?? w.code);\n log(`[serve] validation_warning: ${w.code}: ${w.message}`);\n sendEvent({\n type: \"validation_warning\",\n asset,\n reason: w.code,\n suggestion: w.message,\n });\n }\n }\n\n // Validate top-level skaile.yaml dependencies against deployed skills\n // (graceful degradation). The legacy ai_resources[] block is gone — deps are\n // a flat top-level list of canonical refs now.\n try {\n const wsConfig = resolveSkWorkspaceConfig(opts.projectDir);\n for (const dep of wsConfig.dependencies ?? []) {\n let ref: string | undefined;\n try {\n const parsed = parseAssetRef(dep);\n if (parsed.kind !== \"skill\") continue;\n ref = parsed.name;\n } catch {\n continue;\n }\n const skillDir = join(opts.projectDir, \".claude\", \"skills\", ref);\n if (!existsSync(skillDir)) {\n log(`[serve] validation_warning: dependency \"${dep}\" not found — continuing without it`);\n sendEvent({\n type: \"validation_warning\",\n asset: dep,\n reason: \"not_found\",\n suggestion: \"Sync the catalog and re-add this asset\",\n });\n }\n }\n } catch {\n // Non-fatal — validation failure should never crash the container\n }\n\n // EventNormalizer deduplicates and normalizes events from the driver (e.g. subagent detection).\n // Only applied in serve mode — REPL and flow modes receive raw events.\n // TODO: candidate to move into createAgentSession() if REPL/flow are found to need normalisation.\n const normalizer = new EventNormalizer();\n\n /**\n * Forward a normalized agent event, rewriting file_changed paths so they\n * are mounts-relative and tagged with their mountId.\n *\n * See file-changed-rewriter.ts for the reasoning — the short version is\n * that Claude SDK Write/Edit tool results carry cwd-relative filePaths,\n * and the frontend's file-change listener assumes they are mounts-relative.\n */\n // Protocol v2 — `[CUSTOM:type:json]`, `[REACT:emoji]`, `[PASS]` text-marker\n // parsing and the AAP raw-JSON-events-as-text robustness path are removed.\n // The agent now invokes `platform.react`, `platform.pass`, and\n // `platform.custom_message` capability tools instead.\n\n function forwardNormalizedEvent(event: AgentEvent): void {\n // Suppress event forwarding during compaction turns -- the orchestrator's\n // captureHandler captures text independently and the host should not see\n // the compaction turn's intermediate events.\n if (compacting) return;\n\n // Track durable events for compaction seq counter\n const isTransient =\n event.type === \"status\" ||\n event.type === \"sync_status\" ||\n event.type === \"resources_available\" ||\n event.type === \"resource_response\" ||\n event.type === \"commands_available\";\n if (!isTransient) {\n eventSeq++;\n compactionOrchestrator?.trackMessage(eventSeq);\n }\n\n if (event.type === \"finished\") {\n // Check auto-compaction after turn completes (skip if already compacting)\n if (!compacting && compactionOrchestrator?.shouldCompact()) {\n compactionOrchestrator.compact(\"threshold\").catch((err: unknown) => {\n log(\n `[serve] auto-compaction failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n });\n }\n }\n\n if (!resourceManager) {\n sendEvent(event);\n return;\n }\n // Filesystem-face connectors expose a `mountPath`; tool-only connectors do not.\n const mounts: MountPoint[] = (\n resourceManager.listConnectors() as Array<{ id: string; mountPath?: string }>\n )\n .filter((info) => typeof info.mountPath === \"string\")\n .map((info) => ({\n id: info.id,\n mountPath: info.mountPath as string,\n }));\n sendEvent(rewriteFileChangedPath(event, opts.projectDir, mounts));\n }\n let driverStarted = false; // Lazy start — driver initializes on first prompt command\n let driver = secretsMode === \"env\" ? agentSession!.driver : (undefined as any);\n let secretsProvisioned = secretsMode === \"env\"; // env mode starts ready\n\n // ---------------------------------------------------------------------------\n // Compaction orchestrator\n // ---------------------------------------------------------------------------\n\n /** Local seq counter for durable events. */\n let eventSeq = 0;\n /** True while a compaction turn is in progress -- suppresses event forwarding. */\n let compacting = false;\n let compactionOrchestrator: CompactionOrchestrator | null = null;\n\n const compactionConfig = wsConfig.compaction;\n\n /** Build (or rebuild) the compaction orchestrator for the current driver. */\n function rebuildCompactionOrchestrator(): void {\n if (!driver) return;\n compactionOrchestrator = new CompactionOrchestrator({\n driver,\n config: compactionConfig,\n onCompactionStart: (trigger) => {\n compacting = true;\n sendEvent({ type: \"status\", phase: \"compacting\" } as AgentEvent);\n log(`[serve] compaction started (trigger=${trigger})`);\n },\n onSnapshot: (snapshot) => {\n sendEvent(snapshot as AgentEvent);\n },\n onCompactionAttempt: (event) => {\n sendEvent(event as AgentEvent);\n },\n onCompactionEnd: () => {\n compacting = false;\n sendEvent({ type: \"status\", phase: \"idle\" } as AgentEvent);\n },\n onLog: (line) => log(`[serve] ${line}`),\n // Phase 3: stamp every CompactionAttemptEvent with the registry's\n // current signature so wake-time tier-1 selection has the input it\n // needs. The registry exists for the entire serve lifetime, so this\n // closure is safe across orchestrator rebuilds.\n getCurrentCapabilitySignature: () => computeCapabilitySignature(capabilityRegistry.list()),\n });\n }\n\n if (secretsMode === \"env\" && driver) {\n rebuildCompactionOrchestrator();\n }\n\n // ---------------------------------------------------------------------------\n // Active flow executions (Phase 4 of the flow-connector extraction)\n // ---------------------------------------------------------------------------\n //\n // MVP allows one active flow per session (decision F14). Each entry holds\n // the FlowAdapter handle + the connectorId used as the bus's queue key.\n // Phase 4 dropped the FlowOrchestrator: SessionStimulusBus is the sole\n // turn driver now, with FlowAdapter signalling on every mutation through\n // its `useBusForStimulus: true` wiring (see `base-assets/connectors/flow/\n // adapter.ts`).\n\n interface ActiveFlow {\n runId: string;\n flowDef: FlowDefinition;\n adapter: FlowAdapter;\n handle: ConnectorHandle;\n /** Bus queue key — matches `connectorId` passed to `flowAdapter.connect`. */\n connectorId: string;\n }\n\n const activeFlows = new Map<string, ActiveFlow>();\n\n /**\n * Per-session stimulus bus — built lazily on the first flow start so the\n * driver is guaranteed to exist by the time we wire `driveTurn`. The\n * adapter calls `bus.signal(connectorId, ...)` on every mutation; the\n * bus coalesces and invokes `driveTurn` to run one agent turn.\n */\n let stimulusBus: SessionStimulusBus | null = null;\n /** Runner-side default per-flow turn timeout (4 hours). */\n const FLOW_TURN_TIMEOUT_MS = 4 * 60 * 60 * 1000;\n\n /** Shorthand for the single MVP active flow. Returns null if none. */\n function getOnlyActiveFlow(): ActiveFlow | null {\n const iter = activeFlows.values().next();\n return iter.done ? null : iter.value;\n }\n\n /**\n * Build (or rebuild) the per-session SessionStimulusBus. The bus's\n * `driveTurn` callback wraps the active driver's `prompt(...)` and waits\n * for `agent_end`. It also rebuilds the full orchestrator prompt around\n * the bus-emitted stimulus fragment so the agent sees the same five-\n * section flow context the legacy orchestrator produced.\n *\n * The bus is created on first use and reused across flows in the same\n * session. When the driver is recreated (mid-session skill deploy or\n * resume), the bus's closure over `driver` updates because we mutate the\n * `driver` binding in place — hence the late-binding `driver` access\n * below rather than capturing the current reference.\n */\n function getOrCreateStimulusBus(): SessionStimulusBus {\n if (stimulusBus) return stimulusBus;\n stimulusBus = createSessionStimulusBus({\n driveTurn: async (promptFragment: string, metas: Array<Record<string, unknown>>) => {\n // Locate the targeted flow from the metas so we can rebuild the\n // full prompt with the correct flow definition + state. The bus\n // queue is keyed by connectorId, so all metas in one batch share\n // the same flow.\n const lastMeta = metas[metas.length - 1] ?? {};\n const runId = typeof lastMeta.runId === \"string\" ? lastMeta.runId : null;\n const entry = runId ? activeFlows.get(runId) : getOnlyActiveFlow();\n if (!entry) {\n serverLog.warn(\"driveTurn fired with no active flow\", { runId });\n return;\n }\n\n // Reconstruct the typed stimulus from the meta. The adapter sets\n // `meta.kind` to a `TurnStimulus[\"kind\"]`; we promote it back to\n // the structured form for `buildOrchestratorPrompt`. Fall back to\n // `state_changed` for unknown / batched kinds.\n const lastKind = lastMeta.kind;\n let stimulus: TurnStimulus;\n if (lastKind === \"flow_started\") {\n stimulus = { kind: \"flow_started\" };\n } else if (lastKind === \"user_message\" && typeof lastMeta.text === \"string\") {\n stimulus = {\n kind: \"user_message\",\n text: String(lastMeta.text),\n senderId: String(lastMeta.senderId ?? \"user\"),\n };\n } else {\n stimulus = { kind: \"state_changed\" };\n }\n // The fragment passed in is the adapter's `renderStimulusPrompt(stim)`.\n // We discard it and rebuild the full orchestrator prompt below; the\n // structured stimulus already encodes everything the fragment did.\n void promptFragment;\n\n const fullPrompt = buildOrchestratorPrompt(\n entry.flowDef,\n entry.adapter.getExecution(entry.handle),\n stimulus,\n );\n\n if (!driverStarted) {\n await driver.start();\n driverStarted = true;\n driver.on(\"agent-event\", (event: unknown) => {\n const normalized = normalizer.normalize(event as never);\n for (const e of normalized) forwardNormalizedEvent(e);\n });\n driver.on(\"error\", (err: Error) => {\n log(`[serve] driver error: ${err.message}`);\n sendEvent({ type: \"error\", message: err.message, fatal: true });\n });\n }\n\n await awaitFlowAgentEnd(fullPrompt, FLOW_TURN_TIMEOUT_MS);\n },\n log: serverLog,\n });\n return stimulusBus;\n }\n\n /**\n * Send a prompt to the active driver and resolve when the agent emits\n * `agent_end` (or reject on `error`). Used by the stimulus bus's\n * `driveTurn` callback. Mirrors the legacy orchestrator's wait helper\n * but uses a scoped per-turn listener so the persistent forwarding\n * listener installed at driver-start time is left intact.\n */\n function awaitFlowAgentEnd(prompt: string, timeoutMs: number): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n let settled = false;\n const onEvent = (event: BridgeAgentEvent) => {\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 const done = (err?: Error) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n // EventEmitter.removeListener / .off — bridge drivers extend\n // node:events EventEmitter so this is always available.\n (driver as { off?: (e: string, h: (...a: unknown[]) => void) => void }).off?.(\n \"agent-event\",\n onEvent as unknown as (...a: unknown[]) => void,\n ) ??\n (\n driver as {\n removeListener: (e: string, h: (...a: unknown[]) => void) => void;\n }\n ).removeListener(\"agent-event\", onEvent as unknown as (...a: unknown[]) => void);\n if (err) reject(err);\n else resolve();\n };\n const timer = setTimeout(\n () => done(new Error(`Flow turn timed out after ${timeoutMs / 1000}s`)),\n timeoutMs,\n );\n driver.on(\"agent-event\", onEvent);\n driver.prompt(prompt).catch(done);\n });\n }\n\n /**\n * Instantiate a FlowAdapter for a flow definition and register it as the\n * active flow. Wires the adapter's onChange to emit state_changed via\n * `sendEvent`, and connects it to the per-session stimulus bus so every\n * mutation kicks an agent turn (Phase 4 of the flow-connector extraction).\n */\n async function createActiveFlow(\n flowDef: FlowDefinition,\n seedOrExecution:\n | { seed: { runId: string; startedBy: string; autonomousMode?: boolean } }\n | { execution: FlowExecution },\n ): Promise<ActiveFlow> {\n if (!resourceManager) {\n // Lazy-create a ConnectorManager if one does not exist yet — the\n // session may have no connectors in skaile.yaml, but we still\n // need a home for the FlowAdapter instance.\n registerBuiltinConnectors();\n resourceManager = new ConnectorManager(opts.projectDir, {\n catalogEntries: getSessionCatalogEntries(agentSession),\n });\n log(\"[serve] created ConnectorManager for flow execution (no other connectors declared)\");\n }\n\n const bus = getOrCreateStimulusBus();\n const baseOptions = {\n stimulusBus: bus,\n useBusForStimulus: true,\n };\n const options =\n \"execution\" in seedOrExecution\n ? { flow: flowDef, execution: seedOrExecution.execution, ...baseOptions }\n : { flow: flowDef, seed: seedOrExecution.seed, ...baseOptions };\n const seedRunId =\n \"execution\" in seedOrExecution ? seedOrExecution.execution.runId : seedOrExecution.seed.runId;\n const connectorId = `flow:${seedRunId}`;\n\n // Connect via ConnectorManager so the FlowAdapter's tools become\n // visible to buildSdkConnectorTools below. Direct `new FlowAdapter()`\n // would leave the adapter outside the manager's connectors map and\n // the SDK driver would never see the flow tools.\n const handle = await resourceManager.connect({\n id: connectorId,\n driver: \"flow\",\n access: \"read-write\" as const,\n options,\n });\n const adapter = resourceManager.get(connectorId).connector as unknown as FlowAdapter;\n\n const runId = adapter.getExecution(handle).runId;\n\n // Wire the adapter's onChange so the host's flow-state mirror stays in sync.\n adapter.onStateChange(handle, (state) => {\n sendEvent({\n type: \"state_changed\",\n store: `flow:${state.runId}`,\n state: state as unknown as Record<string, unknown>,\n });\n });\n\n // Rebuild the SDK MCP server tools so the agent can call the new flow\n // connector's tools. If the driver has already started (e.g. the user\n // chatted before clicking Start), restart it via the same dispose +\n // recreate-with-resumeSessionId dance the mid-session skill deploy\n // path uses (see the `aiResources` configure handler) so the agent\n // sees the updated tool list with conversation history preserved.\n if (agentSession?.driverType === \"claude-sdk\") {\n try {\n const server = await buildSdkConnectorTools(resourceManager, { z: _z });\n if (server) {\n if (driverStarted) {\n const prevSessionId = driver.runtimeSessionId;\n log(\n `[serve] restarting driver to register flow connector tools (resume=${prevSessionId ?? \"none\"})`,\n );\n await agentSession.dispose();\n agentSession = await createAgentSession({\n ...sessionConfig,\n resumeSessionId: prevSessionId,\n });\n emitSystemPromptComposed(agentSession, sendEvent);\n driver = agentSession.driver;\n normalizer.reset();\n driverStarted = false;\n rebuildCompactionOrchestrator();\n }\n (driver as any).config.mcpServers = { \"skaile-connectors\": server };\n log(`[serve] rebuilt MCP connector tools for flow ${connectorId}`);\n } else {\n log(`[serve] buildSdkConnectorTools returned null for flow ${connectorId}`);\n }\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n log(`[serve] failed to rebuild MCP tools for flow: ${errMsg}`);\n }\n }\n\n const entry: ActiveFlow = { runId, flowDef, adapter, handle, connectorId };\n activeFlows.set(runId, entry);\n return entry;\n }\n\n // Phase 4: `destroyActiveFlow` was the legacy `cancel_flow` typed handler's\n // tear-down helper. With Protocol 2.2, hosts cancel via\n // `connector_mutate { id: \"flow\", op: \"cancel\" }` which transitions the\n // adapter's state to `cancelled` without disconnecting the connector. The\n // connector is reusable across runs (the adapter's `start` op replaces the\n // execution in-place); the host issues `remove_resource` if and when the\n // connector should go away.\n\n // ---------------------------------------------------------------------------\n // Refresh-flag watcher (Step 9a — wake-mid-401 hardening)\n // ---------------------------------------------------------------------------\n //\n // The Tier-2 git credential-helper script touches\n // `<projectDir>/.skaile/refresh-request` when it detects a stale credentials\n // file (mtime > triggerAgeSec). The runner watches that path via `fs.watch`\n // and dispatches `request_access_token { reason: 'retry-401' }` for every\n // git mount with `exposeAccessToken: true` AND `auth: 'backend'`. The mount\n // driver's `refreshExposedCredential` method does the actual mediation +\n // file rewrite via `atomicReplaceCredential`, mirroring the proactive 5-min\n // pre-expiry refresh timer.\n //\n // Pre-create the flag file: `fs.watch` on a non-existent path throws on\n // Linux (ENOENT) and silently misses events on macOS until the file is\n // created. Mode 0660 — owner+group rw so the helper script (running as\n // the agent uid in the skaile group) can `: > \"$FLAG_FILE\"` it.\n //\n // Spec: `_devlog/specs/2026-05-07-unified-credential-mediation.md` Step 9a.\n\n const refreshFlagPath = join(opts.projectDir, \".skaile\", \"refresh-request\");\n try {\n mkdirSync(join(opts.projectDir, \".skaile\"), { recursive: true });\n if (!existsSync(refreshFlagPath)) {\n writeFileSync(refreshFlagPath, \"\", { mode: 0o660, flag: \"a\" });\n }\n } catch (err) {\n serverLog.warn(\"failed to pre-create refresh-flag — wake-mid-401 disabled\", {\n error: err instanceof Error ? err.message : String(err),\n });\n }\n\n let lastRefreshAt = 0;\n const REFRESH_DEBOUNCE_MS = 2_000;\n\n let refreshFlagWatcher: FSWatcher | null = null;\n try {\n refreshFlagWatcher = fsWatch(refreshFlagPath, (event) => {\n if (event !== \"change\") return;\n const now = Date.now();\n if (now - lastRefreshAt < REFRESH_DEBOUNCE_MS) return;\n lastRefreshAt = now;\n // Dispatch is extracted into `refresh-flag-dispatcher.ts` so the logic\n // can be unit-tested without spinning up the full WebSocket server.\n void dispatchRefreshToExposedGitMounts(resourceManager, serverLog);\n });\n } catch (err) {\n serverLog.warn(\"fs.watch on refresh-flag failed — wake-mid-401 disabled\", {\n error: err instanceof Error ? err.message : String(err),\n });\n }\n\n // ---------------------------------------------------------------------------\n // Cleanup\n // ---------------------------------------------------------------------------\n\n async function cleanup() {\n // Bound the wait on sessionReady — in provisioned mode the session may\n // never be built (no platform has connected yet), and in env mode it has\n // already resolved. Either way we must not block shutdown on it.\n try {\n await Promise.race([\n sessionReady,\n new Promise<void>((resolve) => {\n const t = setTimeout(resolve, 2000);\n t.unref?.();\n }),\n ]);\n } catch {\n /* session may have failed to build */\n }\n try {\n driver?.kill();\n } catch {}\n aiCredentialRefreshScheduler.cancel();\n // Reject any pending capability round-trips so the bridge surfaces tool\n // errors instead of hanging forever after the session shuts down.\n for (const [callId, pending] of pendingCapabilityCalls) {\n clearTimeout(pending.timer);\n pending.reject(new Error(`Session terminated before capability_result (callId=${callId})`));\n }\n pendingCapabilityCalls.clear();\n try {\n refreshFlagWatcher?.close();\n } catch {\n /* best-effort — watcher may already be closed */\n }\n refreshFlagWatcher = null;\n if (agentSession) {\n try {\n await agentSession.dispose();\n } catch {\n /* best-effort — mount unmount/connector disconnect can fail */\n }\n }\n }\n\n // ---------------------------------------------------------------------------\n // Command handling\n // ---------------------------------------------------------------------------\n\n async function handleCommand(\n cmd: AgentCommand | import(\"@skaile/workspaces/types\").SessionInitCommand,\n ) {\n // v3: the access_token_response ingress is removed — refresh-on-401\n // rides on the host.refresh_credential capability invocation now.\n // SessionInitCommand is delivered alongside AgentCommand on the same\n // transport — type the parameter as the envelope union so the switch\n // can handle both.\n switch (cmd.type) {\n case \"session_init\": {\n // Protocol v3 deterministic boot envelope. Replaces the v2\n // configure + provision_secrets + initial request_access_token round\n // trips with one upfront message carrying identity, resolved config,\n // pre-minted credentials, secrets, capabilities, shared state,\n // active flows, resume hints, and logging config.\n //\n // Spec: _devlog/specs/2026-05-10-deterministic-session-bootstrap.md.\n\n // 1. Protocol major-equality\n if (cmd.protocolVersion.major !== PROTOCOL_VERSION.major) {\n log(\n `[serve] incompatible protocol: agent=${PROTOCOL_VERSION.major} platform=${cmd.protocolVersion.major}`,\n );\n sendEvent({\n type: \"incompatible_protocol\",\n agentVersion: PROTOCOL_VERSION,\n platformVersion: cmd.protocolVersion,\n });\n await cleanup();\n disposeLogStore();\n return;\n }\n\n // 2. Identity. Future successive session_init calls must match this\n // containerId; mismatch shuts the runner down.\n if (runtimeIdentity && runtimeIdentity.containerId !== cmd.identity.containerId) {\n log(\n `[serve] session_init_mismatch: expected=${runtimeIdentity.containerId} received=${cmd.identity.containerId}`,\n );\n sendEvent({\n type: \"session_init_mismatch\",\n expectedContainerId: runtimeIdentity.containerId,\n receivedContainerId: cmd.identity.containerId,\n });\n await cleanup();\n disposeLogStore();\n return;\n }\n runtimeIdentity = cmd.identity;\n\n // 3. Register client-side capabilities from the envelope.\n const incoming = cmd.capabilities ?? [];\n for (const wire of incoming) {\n // Audience-scoped runtime caps (host.*) are not registered as\n // client capabilities — they are invoked outbound via\n // capabilityRegistry.invokeRemote(). Filter them out here so the\n // registry doesn't store them as LLM-callable stubs.\n if (wire.audience && !wire.audience.includes(\"llm\") && !wire.audience.includes(\"user\")) {\n // Pure runtime audience — keep around in a separate map for\n // outbound invocation (handled by registry.setRemoteInvoker\n // wiring, not by `register`).\n continue;\n }\n const stub = {\n ...wire,\n inputZod: { parse: (v: unknown) => v } as unknown as import(\"zod\").ZodTypeAny,\n outputZod: undefined,\n handler: buildClientCapabilityHandler(wire),\n };\n capabilityRegistry.register(stub, \"client\");\n }\n sendEvent({ type: \"protocol_info\", version: PROTOCOL_VERSION });\n\n // 4. Pre-minted credentials → in-process PreMintedSecretProvider.\n preMintedSecrets = new PreMintedSecretProvider(cmd.credentials);\n\n // 5. Long-lived secrets → in-memory secret provider (replaces\n // provision_secrets). The Claude Code credentials JSON is handled\n // separately — it goes to disk, not the secret provider.\n let initialAiCredentialExpiresAt: string | null = null;\n if (cmd.secrets) {\n const ccdValue = cmd.secrets[CLAUDE_CODE_CREDENTIALS_KEY];\n if (ccdValue) {\n const home = process.env.HOME ?? homedir();\n if (home) {\n try {\n await writeClaudeCodeCredentialsFile(home, ccdValue);\n log(\n `[serve] wrote Claude Code credentials file to ${home}/.claude/.credentials.json (mode 0600)`,\n );\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n log(`[serve] failed to write Claude Code credentials file: ${errMsg}`);\n }\n }\n // Parse the expiry so the proactive refresh timer can prevent\n // the next 401 instead of relying on the reactive retry path.\n // Scheduling happens once aiProviderConfigId is stashed below.\n initialAiCredentialExpiresAt = extractClaudeAiOauthExpiresAt(ccdValue);\n }\n const otherSecrets = Object.fromEntries(\n Object.entries(cmd.secrets).filter(([k]) => k !== CLAUDE_CODE_CREDENTIALS_KEY),\n );\n const provider = new InMemorySecretProvider();\n provider.provision(otherSecrets);\n secretProvider = provider;\n secretsProvisioned = true;\n }\n\n // 6. Build session using the resolved config. Replaces the v2\n // provision_secrets + configure handshake.\n try {\n const effectiveProvider = opts.provider ?? \"anthropic\";\n const envKey = providerEnvKey(effectiveProvider);\n const apiKeyFromSecrets = cmd.secrets?.[envKey];\n sessionConfig = buildSessionConfig(secretProvider, apiKeyFromSecrets);\n if (!agentSession) {\n agentSession = await createAgentSession(sessionConfig);\n emitSystemPromptComposed(agentSession, sendEvent);\n resourceManager = agentSession.resourceManager;\n driver = agentSession.driver;\n rebuildCompactionOrchestrator();\n registerSessionComposition(agentSession);\n sendEvent({\n type: \"resources_available\",\n ...splitConnectorsForWire(resourceManager),\n });\n agentSession.startWatching();\n\n // 6a. Wire the outbound capability invoker so handlers can call\n // `capabilityRegistry.invokeRemote('host.*', ...)` against the\n // platform peer. Done after the transport is connected (which\n // happens before session_init is processed) so the round-trip\n // map is ready to park calls.\n capabilityRegistry.setRemoteInvoker(remoteCapabilityInvoker);\n\n // 6b. Register the seven runner.* capabilities (audience: runtime)\n // so the platform can dispatch lifecycle / resource / log-level\n // mutations through invokeRunnerCapability. Handlers that are\n // not yet wired return a structured `not_implemented` error\n // and will be filled in as Phase B platform reroutes land.\n const runnerCaps = buildRunnerCapabilities({\n // setLogLevel is left undefined — the cap's built-in fallback\n // calls `getLogStore()?.setLevel(...)` directly, which matches\n // the legacy `set_log_level` AgentCommand body 1:1.\n // Other handlers (addMount / addConnector / removeResource /\n // updateCredential / setState / lifecycle) remain stubs;\n // wiring is tracked under AF-PV3 / F-RUNNER-CAPS.\n });\n for (const cap of runnerCaps) {\n capabilityRegistry.register(cap, \"agent\");\n }\n\n resolveSessionReady();\n log(\"[serve] session built from session_init envelope\");\n }\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n log(`[serve] session_init failed to build session: ${errMsg}`);\n sendEvent({ type: \"error\", message: errMsg, fatal: true });\n rejectSessionReady(err instanceof Error ? err : new Error(errMsg));\n }\n\n // 7. Stash aiProviderConfigId for the auth-error retry handler.\n if (cmd.resolvedConfig.aiProviderConfigId) {\n aiProviderConfigId = cmd.resolvedConfig.aiProviderConfigId;\n log(`[serve] stashed aiProviderConfigId=${aiProviderConfigId}`);\n }\n\n // 7a. Arm the proactive AI-credential refresh timer. Needs\n // aiProviderConfigId in scope (set above) AND an `expiresAt`\n // parsed from the initial credentials blob (step 5). Static PATs\n // and standalone sessions short-circuit to no-op inside the\n // scheduler.\n if (aiProviderConfigId && initialAiCredentialExpiresAt) {\n aiCredentialRefreshScheduler.schedule(initialAiCredentialExpiresAt);\n }\n\n // 8. Adapt the rest of the configure logic onto envelope fields.\n const cfg = {\n aiResources: cmd.resolvedConfig.aiResources,\n subagents: cmd.resolvedConfig.subagents,\n sharedState: cmd.sharedState,\n resumeSessionId: cmd.resume?.sessionId,\n expectedCapabilitySignature: cmd.resume?.expectedCapabilitySignature,\n aiProviderConfigId: cmd.resolvedConfig.aiProviderConfigId,\n };\n log(\n `[serve] configure cfg keys=${Object.keys(cfg).join(\",\")} sharedState=${cfg.sharedState ? cfg.sharedState.length : \"undefined\"} resourceManager=${resourceManager ? \"set\" : \"null\"}`,\n );\n\n // `aiProviderConfigId` was already stashed in step 7 above. The legacy\n // configure-handler block re-stashed `cfg.aiProviderConfigId` here for\n // the standalone configure path; on session_init the field is sourced\n // from the same `cmd.resolvedConfig.aiProviderConfigId` so the second\n // assignment was redundant and has been removed.\n //\n // Spec: `_devlog/specs/2026-05-07-unified-credential-mediation.md`\n // § \"Wire `aiProviderConfigId` end-to-end\".\n\n // ── Tier-1 native SDK resume (Phase 3 of the resume cascade) ──────\n //\n // The platform sets `cfg.resumeSessionId` (and optionally\n // `cfg.expectedCapabilitySignature`) when wake-time tier selection\n // chose tier 1. We:\n // 1. Compute the current registry signature post-cap-registration.\n // 2. If a signature was supplied and it doesn't match — drop the\n // resume hint and emit `resume_failed { signature_mismatch }`.\n // 3. Otherwise, dispose + recreate the driver with the supplied\n // session id so the first prompt resumes the SDK conversation.\n //\n // Spec: `_devlog/specs/2026-05-05-session-resume-restart-design.md`\n // The resume hint is staged here and merged into any subsequent\n // driver recreate within this configure call. Without staging, a\n // later branch (e.g. `cfg.subagents`) would clobber the resume by\n // recreating the driver from `sessionConfig` without the hint.\n let pendingResumeSessionId: string | undefined;\n const cfgResumeSessionId = cfg.resumeSessionId;\n const cfgExpectedSig = cfg.expectedCapabilitySignature;\n if (cfgResumeSessionId) {\n const currentSig = computeCapabilitySignature(capabilityRegistry.list());\n if (cfgExpectedSig && cfgExpectedSig !== currentSig) {\n log(\n `[serve] tier-1 resume rejected: signature mismatch (expected=${cfgExpectedSig.slice(0, 12)} current=${currentSig.slice(0, 12)})`,\n );\n sendEvent({\n type: \"resume_failed\",\n resumeSessionId: cfgResumeSessionId,\n reason: \"signature_mismatch\",\n });\n } else {\n log(`[serve] tier-1 resume attempted: resumeSessionId=${cfgResumeSessionId}`);\n sendEvent({\n type: \"resume_attempted\",\n resumeSessionId: cfgResumeSessionId,\n capabilitySignature: currentSig,\n });\n pendingResumeSessionId = cfgResumeSessionId;\n }\n }\n\n // Apply tier-1 resume + any subagents recreate in a single dispose\n // + recreate. Either branch alone, both together, or neither. When\n // both are set, the subagents `cfg.subagents` is already in\n // `sessionConfig.wsConfig` via `buildSessionConfig`, so `cfg.subagents`\n // here is informational only — we still need to recreate so the\n // driver picks up the new config. Threading\n // `pendingResumeSessionId` into the same recreate prevents the\n // tier-1 hint from being clobbered.\n if (pendingResumeSessionId || cfg.subagents) {\n await agentSession.dispose();\n agentSession = await createAgentSession({\n ...sessionConfig,\n ...(aiProviderConfigId ? { aiProviderConfigId } : {}),\n ...(pendingResumeSessionId ? { resumeSessionId: pendingResumeSessionId } : {}),\n });\n emitSystemPromptComposed(agentSession, sendEvent);\n driver = agentSession.driver;\n normalizer.reset();\n driverStarted = false;\n rebuildCompactionOrchestrator();\n }\n if (cfg.sharedState) {\n // Lazy-create a ConnectorManager if one doesn't exist yet (the\n // session may have no connectors in skaile.yaml, but the platform\n // still needs to register shared state stores).\n if (!resourceManager) {\n try {\n registerBuiltinConnectors();\n resourceManager = new ConnectorManager(opts.projectDir, {\n catalogEntries: getSessionCatalogEntries(agentSession),\n });\n log(\"[serve] created ConnectorManager for sharedState (no connectors were declared)\");\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n log(`[serve] failed to create ConnectorManager: ${errMsg}`);\n sendEvent({ type: \"configured\" });\n break;\n }\n }\n // Register each shared state store as a hot-plug connector and wire\n // its change callback to forward state_changed events to the client.\n let storesRegistered = 0;\n for (const stateConfig of cfg.sharedState) {\n try {\n if (resourceManager.has(stateConfig.id)) {\n // Store already exists (e.g. backend reconnected after restart).\n // Re-emit current state so the backend's stateCache is repopulated.\n try {\n const snapshot = await resourceManager.executeOp(stateConfig.id, \"get\", {});\n const state = snapshot ? JSON.parse(snapshot) : {};\n sendEvent({\n type: \"state_changed\",\n store: stateConfig.id,\n state,\n });\n log(\n `[serve] sharedState ${stateConfig.id} already registered — re-emitted current state`,\n );\n } catch {\n log(\n `[serve] sharedState ${stateConfig.id} already registered — skipping (could not read state)`,\n );\n }\n continue;\n }\n const handle = await resourceManager.connect({\n id: stateConfig.id,\n driver: stateConfig.adapter,\n access: \"read-write\" as const,\n options: {\n ...((stateConfig.definition as Record<string, unknown> | undefined) ?? {}),\n initial: stateConfig.initialState ?? {},\n },\n });\n // Wire onStoreChange (xstate-store specific) to emit state_changed events\n const entry = resourceManager.get(stateConfig.id);\n if (typeof entry.connector.onStoreChange === \"function\") {\n entry.connector.onStoreChange(handle, (snapshot: Record<string, unknown>) => {\n sendEvent({\n type: \"state_changed\",\n store: stateConfig.id,\n state: snapshot,\n });\n });\n }\n log(`[serve] sharedState registered: ${stateConfig.id} (${stateConfig.adapter})`);\n storesRegistered++;\n // Emit initial state immediately so subscribers don't have to wait for the first mutation.\n sendEvent({\n type: \"state_changed\",\n store: stateConfig.id,\n state: stateConfig.initialState ?? {},\n });\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n log(`[serve] sharedState registration failed for ${stateConfig.id}: ${errMsg}`);\n sendEvent({\n type: \"error\",\n message: `sharedState ${stateConfig.id}: ${errMsg}`,\n fatal: false,\n });\n }\n }\n\n // Rebuild MCP connector tools so the agent can access the new stores.\n // This must happen before the driver starts (lazy start on first prompt).\n if (storesRegistered > 0 && !driverStarted && agentSession?.driverType === \"claude-sdk\") {\n try {\n const server = await buildSdkConnectorTools(resourceManager, { z: _z });\n if (server) {\n (driver as any).config.mcpServers = { \"skaile-connectors\": server };\n log(`[serve] rebuilt MCP connector tools (${storesRegistered} new store(s))`);\n } else {\n log(`[serve] buildSdkConnectorTools returned null`);\n }\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n log(`[serve] failed to rebuild MCP tools: ${errMsg}`);\n }\n }\n }\n\n // Phase 4 of flow-connector extraction (Protocol 2.2): the implicit\n // `configure.activeFlows` rehydration was removed. Hosts now issue an\n // explicit `connector_mutate { id: \"flow\", op: \"hydrate\" }` per flow\n // after `configure` completes. See `MIGRATION-flow-connector.md`.\n\n // Handle aiResources (mid-session skill changes via catalog)\n if (cfg.aiResources) {\n const catalogActions = cfg.aiResources.filter((a) => a.action);\n if (catalogActions.length > 0) {\n log(`[serve] aiResources catalog actions: ${catalogActions.length}`);\n try {\n const skillsDir = join(\n sessionConfig.projectDir ?? process.cwd(),\n \".claude\",\n \"skills\",\n );\n\n // Resolve ai-assets root from runner's own environment\n const assetsRoot =\n process.env.SKAILE_ASSETS_ROOT ??\n findAiAssetsRoot(sessionConfig.projectDir ?? process.cwd()) ??\n \"/app/ai-assets\";\n\n for (const res of catalogActions) {\n if (res.action === \"add\" && res.entry) {\n const entry = res.entry as Record<string, unknown>;\n const result = deployCatalogEntry(entry as any, {\n assetsRoot,\n skillsDir,\n context: res.context,\n });\n if (result.success) {\n log(`[serve] deployed skill: ${(entry.name as string) ?? res.name}`);\n } else {\n log(\n `[serve] failed to deploy skill ${(entry.name as string) ?? res.name}: ${result.error}`,\n );\n }\n } else if (res.action === \"remove\") {\n const removed = undeployCatalogEntry(res.name, skillsDir);\n log(`[serve] ${removed ? \"removed\" : \"not found\"} skill: ${res.name}`);\n }\n }\n\n // Restart the driver so the SDK re-discovers skills from .claude/skills/.\n // Capture the current session ID so we can resume with conversation history.\n if (driverStarted) {\n const prevSessionId = driver.runtimeSessionId;\n log(\n `[serve] restarting driver to pick up skill changes (resume=${prevSessionId ?? \"none\"})`,\n );\n await agentSession.dispose();\n agentSession = await createAgentSession({\n ...sessionConfig,\n resumeSessionId: prevSessionId,\n });\n emitSystemPromptComposed(agentSession, sendEvent);\n driver = agentSession.driver;\n normalizer.reset();\n driverStarted = false;\n rebuildCompactionOrchestrator();\n\n sendEvent({\n type: \"skills_changed\",\n skills: catalogActions.map((a) => ({\n name: ((a.entry as Record<string, unknown>)?.name as string) ?? a.name,\n action: a.action ?? \"add\",\n })),\n });\n } else {\n log(\n \"[serve] aiResources applied before driver start — skills discovered on first prompt\",\n );\n }\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n log(`[serve] aiResources handling failed: ${errMsg}`);\n sendEvent({\n type: \"error\",\n message: `aiResources: ${errMsg}`,\n fatal: false,\n });\n }\n }\n }\n // ACK — let the platform know the envelope has been processed so it\n // can release the session lock. Includes the post-init capability\n // signature so tier-1 resume can be validated.\n sendEvent({\n type: \"session_init_ack\",\n capabilitySignature: computeCapabilitySignature(capabilityRegistry.list()),\n });\n break;\n }\n\n case \"prompt\": {\n try {\n await sessionReady;\n } catch (err) {\n sendEvent({\n type: \"error\",\n message: `Session not available: ${(err as Error).message}`,\n fatal: true,\n });\n break;\n }\n if (!secretsProvisioned) {\n log(\"[serve] prompt received before secrets provisioned — rejecting\");\n sendEvent({\n type: \"error\",\n message: \"Secrets not yet provisioned — send provision_secrets first\",\n fatal: false,\n });\n break;\n }\n log(`[serve] prompt: ${cmd.prompt.slice(0, 80)}...`);\n\n // Route free-chat user messages through the SessionStimulusBus\n // when a flow is active — every turn then includes the flow\n // context, and the agent decides whether to advance the flow\n // or just answer the user. The original prompt path below\n // runs only when no flow is active. Sender attribution comes\n // from the envelope layer in hosts that track it; the bare\n // prompt command carries none today so we use a placeholder.\n const activeFlow = getOnlyActiveFlow();\n if (activeFlow) {\n sendEvent({ type: \"status\", phase: \"thinking\" });\n try {\n const bus = getOrCreateStimulusBus();\n const userStimulus: TurnStimulus = {\n kind: \"user_message\",\n text: cmd.prompt,\n senderId: \"user\",\n };\n await bus.signal(activeFlow.connectorId, {\n promptFragment: renderStimulusPrompt(userStimulus),\n meta: {\n kind: \"user_message\",\n runId: activeFlow.runId,\n text: cmd.prompt,\n senderId: \"user\",\n },\n });\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n log(`[serve] flow user-message turn failed: ${errMsg}`);\n sendEvent({ type: \"error\", message: `Flow turn failed: ${errMsg}`, fatal: false });\n }\n break;\n }\n\n if (!driverStarted) {\n try {\n await driver.start();\n driverStarted = true;\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n log(`[serve] driver start failed: ${errMsg}`);\n sendEvent({ type: \"error\", message: `Driver start failed: ${errMsg}`, fatal: true });\n break;\n }\n\n // Wire event forwarding through normalizer\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n driver.on(\"agent-event\", (event: any) => {\n const normalized = normalizer.normalize(event);\n for (const e of normalized) {\n forwardNormalizedEvent(e);\n }\n });\n\n driver.on(\"error\", (err: Error) => {\n log(`[serve] driver error: ${err.message}`);\n sendEvent({ type: \"error\", message: err.message, fatal: true });\n });\n }\n\n sendEvent({ type: \"status\", phase: \"thinking\" });\n\n try {\n await driver.prompt(cmd.prompt);\n } catch (err) {\n const errMsg = err instanceof Error ? err.message : String(err);\n log(`[serve] prompt failed: ${errMsg}`);\n sendEvent({ type: \"error\", message: `Prompt failed: ${errMsg}`, fatal: true });\n }\n break;\n }\n\n case \"reply\": {\n try {\n await sessionReady;\n } catch (err) {\n sendEvent({\n type: \"error\",\n message: `Session not available: ${(err as Error).message}`,\n fatal: true,\n });\n break;\n }\n log(`[serve] reply: ${cmd.answer.slice(0, 80)}...`);\n try {\n await driver.prompt(cmd.answer);\n } catch (err) {\n sendEvent({\n type: \"error\",\n message: `Reply failed: ${err instanceof Error ? err.message : String(err)}`,\n fatal: false,\n });\n }\n break;\n }\n\n case \"cancel\": {\n try {\n await sessionReady;\n } catch (err) {\n sendEvent({\n type: \"error\",\n message: `Session not available: ${(err as Error).message}`,\n fatal: true,\n });\n break;\n }\n log(\"[serve] cancel\");\n try {\n await driver.abort();\n } catch (err) {\n log(`[serve] cancel failed: ${err}`);\n }\n break;\n }\n\n // v3: compact + lifecycle removed — reachable via runner.lifecycle capability\n // (the v3 `runner.lifecycle` cap takes `{ phase: 'hibernate' | 'close' | 'compact' }`).\n\n case \"resource_request\": {\n try {\n await sessionReady;\n } catch (err) {\n sendEvent({\n type: \"error\",\n message: `Session not available: ${(err as Error).message}`,\n fatal: true,\n });\n break;\n }\n // Route to mounts handler if the ID matches a mounted mount\n if (resourceManager?.has(cmd.connectorId)) {\n handleMountResourceRequest(cmd, resourceManager, sendEvent);\n break;\n }\n if (!resourceManager) {\n sendEvent({\n type: \"resource_response\",\n requestId: cmd.requestId,\n resourceId: cmd.connectorId,\n operation: cmd.operation,\n error: \"No resources available — no mounts or connectors configured\",\n });\n break;\n }\n void handleResourceRequest(cmd, resourceManager, sendEvent);\n break;\n }\n\n // v3: state_action removed — reachable via the runner.set_state capability.\n\n // ── Generic connector dispatch (Protocol 2.2) ──────────────────────\n // The 6 typed flow commands (`start_flow`, `approve_flow_node`,\n // `provide_flow_input`, `cancel_flow`, `set_flow_autonomous_mode`,\n // `retry_flow_node`) were removed in Phase 4 of the flow-connector\n // extraction. Hosts now drive flow execution exclusively through\n // `connector_mutate` against the `flow` connector. See\n // `MIGRATION-flow-connector.md` for the per-op mapping table.\n case \"connector_mutate\": {\n try {\n if (!resourceManager) throw new Error(\"connector_mutate before resources ready\");\n // Phase 4: when the host issues `start` against the `flow` connector,\n // route through `createActiveFlow` so the activeFlows map and bus\n // wiring stay in sync with the adapter's new run. The path also\n // ensures the SDK driver's MCP tool surface picks up the flow tools\n // (legacy parity with the removed `start_flow` typed handler).\n //\n // For all other ops we fall through to the generic dispatch — the\n // adapter's mutate() pipeline emits state_changed via onChange and\n // wakes the next turn through the stimulus bus.\n //\n // Hosts address the flow connector by its bare driver id (\"flow\")\n // per MIGRATION-flow-connector.md. createActiveFlow registers the\n // per-run connector at id `flow:${runId}`, so we (a) treat a bare\n // \"flow\" id with no existing entry as a request to create one\n // (start path, below) and (b) rewrite a bare \"flow\" id to the\n // singleton active run's connectorId for non-start ops so the\n // ConnectorManager lookup succeeds.\n const targetEntry = resourceManager.has?.(cmd.id) ? resourceManager.get(cmd.id) : null;\n const isExistingFlow =\n (targetEntry?.connector as { name?: string } | undefined)?.name === \"flow\";\n const isBareFlowId = cmd.id === \"flow\";\n if (cmd.op === \"start\") {\n if (isExistingFlow || isBareFlowId) {\n const payload = (cmd.payload ?? {}) as Record<string, unknown>;\n const flowDef = payload.flow as FlowDefinition | undefined;\n const seed = payload.seed as\n | { runId: string; startedBy: string; autonomousMode?: boolean }\n | undefined;\n if (flowDef?.id && seed?.runId && seed?.startedBy) {\n if (activeFlows.size > 0) {\n serverLog.warn(\"connector_mutate flow.start: another flow already active\", {\n activeRunIds: Array.from(activeFlows.keys()),\n });\n break;\n }\n const entry = await createActiveFlow(flowDef, { seed });\n serverLog.info(\"connector_mutate flow.start\", {\n runId: entry.runId,\n flowId: flowDef.id,\n });\n break;\n }\n }\n }\n // Non-start ops: rewrite bare \"flow\" id to the active run's\n // connectorId. The runner enforces a singleton active flow at\n // `start` time, so picking the only entry is safe.\n let dispatchId = cmd.id;\n if (!targetEntry && isBareFlowId) {\n const onlyActive = getOnlyActiveFlow();\n if (onlyActive) {\n dispatchId = onlyActive.connectorId;\n }\n }\n await resourceManager.executeOp(dispatchId, cmd.op, cmd.payload ?? {});\n } catch (err) {\n serverLog.warn(\"connector_mutate failed\", {\n id: cmd.id,\n op: cmd.op,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n break;\n }\n\n case \"connector_query\": {\n let ok = true;\n let result: string | undefined;\n let error: string | undefined;\n try {\n if (!resourceManager) throw new Error(\"connector_query before resources ready\");\n // Same bare-\"flow\"-id rewrite as connector_mutate so hosts can\n // address the flow connector by its driver id without knowing\n // the per-run connectorId format.\n let dispatchId = cmd.id;\n if (!resourceManager.has?.(cmd.id) && cmd.id === \"flow\") {\n const onlyActive = getOnlyActiveFlow();\n if (onlyActive) {\n dispatchId = onlyActive.connectorId;\n }\n }\n result = await resourceManager.executeOp(dispatchId, cmd.op, cmd.payload ?? {});\n } catch (err) {\n ok = false;\n error = err instanceof Error ? err.message : String(err);\n }\n sendEvent({\n type: \"connector_query_response\",\n requestId: cmd.requestId,\n ok,\n ...(result !== undefined ? { result } : {}),\n ...(error !== undefined ? { error } : {}),\n });\n break;\n }\n\n case \"debug\": {\n try {\n await sessionReady;\n } catch (err) {\n sendEvent({\n type: \"error\",\n message: `Session not available: ${(err as Error).message}`,\n fatal: true,\n });\n break;\n }\n log(`[serve] debug query=${cmd.query}`);\n let result: unknown;\n try {\n switch (cmd.query) {\n case \"tools\": {\n const mcpServers = Object.keys((driver as any)?.config?.mcpServers ?? {});\n const allowedTools = (driver as any)?.config?.allowedTools ?? null;\n result = { mcpServers, allowedTools, driverStarted };\n break;\n }\n case \"connectors\": {\n result = resourceManager?.listConnectors?.() ?? [];\n break;\n }\n case \"mcp\": {\n const servers = Object.entries((driver as any)?.config?.mcpServers ?? {}).map(\n ([name]) => ({ name }),\n );\n result = { servers };\n break;\n }\n case \"config\": {\n // Read model from the live driver so changes via\n // reconfigure_agent are reflected in the debug panel.\n const liveModel = driver?.getModel() ?? agentSession?.model;\n result = {\n driver: agentSession?.driverType,\n model: liveModel,\n provider: agentSession?.provider,\n maxTurns,\n secretsMode,\n driverStarted,\n projectDir: opts.projectDir,\n versions: getFrameworkVersions(),\n };\n break;\n }\n case \"state\": {\n const storeId = cmd.args?.store as string | undefined;\n if (storeId) {\n try {\n const snapshot = await resourceManager?.executeOp(storeId, \"get\", {});\n result = snapshot ? JSON.parse(snapshot) : null;\n } catch (err) {\n result = { error: err instanceof Error ? err.message : String(err) };\n }\n } else {\n const all = resourceManager?.listConnectors?.() ?? [];\n result = { stores: all.map((c: { id: string }) => c.id) };\n }\n break;\n }\n case \"commands\": {\n const commands = driver?.getSlashCommands?.() ?? [];\n result = { commands, driverType: agentSession?.driverType };\n break;\n }\n default:\n result = { error: `Unknown debug query: ${(cmd as any).query}` };\n }\n } catch (err) {\n result = { error: err instanceof Error ? err.message : String(err) };\n }\n sendEvent({ type: \"debug_result\", query: cmd.query, data: result });\n break;\n }\n\n // -----------------------------------------------------------------------\n // -----------------------------------------------------------------------\n\n // v3: add_resource, remove_resource, remount_mount, set_log_level,\n // reconfigure_agent removed from AgentCommand union.\n // Reachable now via the `runner.set_log_level` and `runner.reconfigure`\n // capability invocations (audience: ['runtime']) — the platform calls\n // them through invokeRunnerCapability on the gateway. Handler bodies\n // live in the runner.* capability registrations.\n\n case \"shutdown\": {\n log(\"[serve] shutdown requested\");\n await cleanup();\n if (transport instanceof WebSocketServerTransport) {\n await transport.close();\n }\n disposeLogStore();\n process.exit(0);\n break;\n }\n\n // Protocol v2 — capability round-trip results from the platform.\n case \"capability_result\": {\n const matched = resolveCapabilityResult(pendingCapabilityCalls, cmd);\n if (!matched) {\n log(\n `[serve] capability_result for unknown callId=${cmd.callId} (timed out or already resolved); dropping`,\n );\n }\n break;\n }\n\n // Protocol v2 — additional capability lifecycle commands. The platform\n // can register / deregister capabilities mid-session (e.g. when a user\n // installs an extension after `configure`). Approval routing is reserved\n // for a later phase; we accept the command shape for forward\n // compatibility and log it.\n case \"capability_register\": {\n for (const raw of cmd.capabilities) {\n const wire = raw;\n capabilityRegistry.register(\n {\n ...wire,\n inputZod: { parse: (v: unknown) => v } as unknown as import(\"zod\").ZodTypeAny,\n outputZod: undefined,\n handler: buildClientCapabilityHandler(wire),\n },\n \"client\",\n );\n }\n break;\n }\n case \"capability_deregister\": {\n for (const name of cmd.names) {\n capabilityRegistry.deregister(name);\n }\n break;\n }\n case \"capability_approve\": {\n // Protocol v2.1 — the platform forwards the user's decision for any\n // capability declared `requiresApproval: true`. The platform itself\n // gates dispatch (it parks the `capability_invoked` until the user\n // responds), so:\n //\n // - `approved`: the platform proceeds to dispatch and replies with\n // `capability_result` through the normal path. We only audit-log\n // here; rejecting/resolving the pending call would race the\n // subsequent result.\n // - `rejected`: the platform did NOT dispatch. Reject the pending\n // call so the LLM sees a tool error explaining the user denied\n // the action.\n if (cmd.decision === \"rejected\") {\n const matched = rejectCapabilityOnApprovalDeny(\n pendingCapabilityCalls,\n cmd.callId,\n cmd.feedback,\n );\n if (!matched) {\n log(\n `[serve] capability_approve(rejected) for unknown callId=${cmd.callId} (already resolved or timed out); dropping`,\n );\n } else {\n log(\n `[serve] capability_approve(rejected) callId=${cmd.callId} decidedBy=${cmd.decidedBy}${cmd.feedback ? ` feedback=${JSON.stringify(cmd.feedback)}` : \"\"}`,\n );\n }\n } else {\n log(\n `[serve] capability_approve(approved) callId=${cmd.callId} decidedBy=${cmd.decidedBy} (awaiting capability_result)`,\n );\n }\n break;\n }\n }\n }\n\n // Wire transport commands to handler\n transport.onCommand((cmd) => {\n void handleCommand(cmd);\n });\n\n // Start listening\n if (transport instanceof WebSocketServerTransport) {\n await transport.listen();\n }\n\n // Start filesystem/connector watchers AFTER the transport is listening.\n // Watching can be slow on large directory trees (e.g. node_modules over\n // Docker bind mounts) and must not block the WebSocket readiness check.\n if (secretsMode === \"env\" && agentSession!) {\n agentSession!.startWatching();\n }\n\n // Emit available resources on each client connect (not just once after listen,\n // because the platform connects after the server starts listening)\n if (transport instanceof WebSocketServerTransport) {\n transport.onConnect(() => {\n if (resourceManager) {\n const wire = splitConnectorsForWire(resourceManager);\n log(\n `[serve] emitting resources_available: ${wire.mounts.length} mount(s), ${wire.connectors.length} connector(s)`,\n );\n sendEvent({ type: \"resources_available\", ...wire });\n }\n // Re-emit cached slash commands if the driver has already discovered them\n const commands = driver?.getSlashCommands?.() ?? [];\n if (commands.length > 0) {\n log(`[serve] emitting commands_available: ${commands.length} command(s)`);\n sendEvent({ type: \"commands_available\", commands });\n }\n });\n }\n\n if (secretsMode === \"env\") {\n log(\n `[serve] driver=${agentSession!.driverType} model=${agentSession!.model ?? \"(default)\"} provider=${agentSession!.provider ?? \"(default)\"} maxTurns=${maxTurns ?? \"(default)\"}`,\n );\n } else {\n log(`[serve] secrets=provisioned — session will initialize after provision_secrets`);\n }\n log(`[serve] project=${opts.projectDir}`);\n\n // Last-resort safety net: a single bad watcher event or stray async error\n // should never take the session down. Log and keep serving.\n process.on(\"uncaughtException\", (err) => {\n log(\n `[serve] uncaughtException (non-fatal): ${err instanceof Error ? (err.stack ?? err.message) : String(err)}`,\n );\n });\n process.on(\"unhandledRejection\", (reason) => {\n log(\n `[serve] unhandledRejection (non-fatal): ${reason instanceof Error ? (reason.stack ?? reason.message) : String(reason)}`,\n );\n });\n\n // Signal handlers for graceful shutdown.\n //\n // Must be safe against:\n // - Shutdown while session is still initializing (cleanup bounds its own wait).\n // - Hanging mount unmount / connector disconnect / driver kill (deadline timer force-exits).\n // - User impatience (second SIGINT/SIGTERM force-exits immediately).\n const GRACEFUL_SHUTDOWN_TIMEOUT_MS = 5000;\n let shuttingDown = false;\n\n async function initiateShutdown(signal: \"SIGINT\" | \"SIGTERM\"): Promise<void> {\n if (shuttingDown) {\n log(`[serve] ${signal} received again — forcing exit`);\n process.exit(130);\n }\n shuttingDown = true;\n log(`[serve] ${signal} received — shutting down (press Ctrl-C again to force)`);\n\n const forceExitTimer = setTimeout(() => {\n log(`[serve] graceful shutdown exceeded ${GRACEFUL_SHUTDOWN_TIMEOUT_MS}ms — forcing exit`);\n process.exit(130);\n }, GRACEFUL_SHUTDOWN_TIMEOUT_MS);\n forceExitTimer.unref?.();\n\n try {\n await cleanup();\n } catch (err) {\n log(`[serve] cleanup error: ${(err as Error).message}`);\n }\n try {\n if (transport instanceof WebSocketServerTransport) {\n await transport.close();\n }\n } catch (err) {\n log(`[serve] transport close error: ${(err as Error).message}`);\n }\n\n clearTimeout(forceExitTimer);\n log(\"[serve] shutdown complete\");\n disposeLogStore();\n process.exit(0);\n }\n\n process.on(\"SIGTERM\", () => {\n void initiateShutdown(\"SIGTERM\");\n });\n process.on(\"SIGINT\", () => {\n void initiateShutdown(\"SIGINT\");\n });\n}\n","import { randomUUID } from \"node:crypto\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\n\nconst SESSION_DIR = \".skaile\";\nconst SESSIONS_SUBDIR = \"sessions\";\nconst CURRENT_FILE = \"current\";\nconst LEGACY_FILE = \"session.json\";\n\n/**\n * Runner session metadata.\n *\n * Holds only what the runner needs to resume the agent driver across\n * process restarts — notably `driverSessionId` for SDK session resume.\n *\n * Flow execution state (per-node status, approvals, outputs) moved out\n * of the session file in Phase 2 of the flow-execution plan. It now\n * lives in the FlowAdapter's in-memory snapshot and, for hosts that\n * persist it, in whatever durable store they provide (the Skaile\n * platform uses the `FlowExecution` Prisma table). The runner does\n * not read or write flow state from disk.\n * @docLink packages/runner/session#session-state\n */\nexport interface SessionState {\n /** Unique identifier for this session run (UUID). */\n runId: string;\n /** ID of the flow definition being executed. */\n flowId: string;\n /** Absolute path to the project directory. */\n projectDir: string;\n /**\n * Absolute path to the agent definition directory (`agent.yaml`,\n * `SOUL.md`, `RULES.md`, `knowledge/`). Resolved from `skaile.yaml`\n * via `resolveAgentDir` when absent at session creation time.\n */\n agentDir?: string;\n /** Agent driver backend used for this session (e.g. `\"omp\"`, `\"claude-sdk\"`). */\n driver: string;\n /** LLM provider (if set), e.g. `\"anthropic\"` or `\"openrouter\"`. */\n provider?: string;\n /** Model name (if set), e.g. `\"claude-opus-4-5\"`. */\n model?: string;\n /** Provider-native session/thread identifier for resume support. */\n driverSessionId?: string;\n /** ISO 8601 timestamp when the session was created. */\n startedAt: string;\n /** ISO 8601 timestamp of the last state change. */\n updatedAt: string;\n /** Optional human-readable label for the session */\n label?: string;\n /** Session lifecycle status. */\n status?: \"running\" | \"complete\" | \"failed\" | \"paused\";\n}\n\n// ---------------------------------------------------------------------------\n// Path helpers\n// ---------------------------------------------------------------------------\n\nfunction sessionsDir(projectDir: string): string {\n return path.join(projectDir, SESSION_DIR, SESSIONS_SUBDIR);\n}\n\nfunction sessionFilePath(projectDir: string, runId: string): string {\n return path.join(sessionsDir(projectDir), `${runId}.json`);\n}\n\nfunction currentPointerPath(projectDir: string): string {\n return path.join(projectDir, SESSION_DIR, CURRENT_FILE);\n}\n\nfunction legacySessionPath(projectDir: string): string {\n return path.join(projectDir, SESSION_DIR, LEGACY_FILE);\n}\n\n// ---------------------------------------------------------------------------\n// Migration\n// ---------------------------------------------------------------------------\n\n/**\n * Migrate legacy session.json to sessions/<runId>.json if it exists.\n * Safe to call multiple times — no-op if already migrated.\n */\nasync function migrateLegacySession(projectDir: string): Promise<void> {\n const legacyPath = legacySessionPath(projectDir);\n try {\n const raw = await fs.readFile(legacyPath, \"utf-8\");\n const state = JSON.parse(raw) as SessionState;\n // Write to new location\n await fs.mkdir(sessionsDir(projectDir), { recursive: true });\n await fs.writeFile(\n sessionFilePath(projectDir, state.runId),\n JSON.stringify(state, null, 2),\n \"utf-8\",\n );\n // Write current pointer\n await fs.writeFile(currentPointerPath(projectDir), state.runId, \"utf-8\");\n // Remove legacy file\n await fs.rm(legacyPath);\n } catch {\n // No legacy file or already migrated — ignore\n }\n}\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Load the current (most recently active) session for a project.\n *\n * Reads the `<projectDir>/.skaile/current` pointer file and loads the\n * corresponding session. Auto-migrates the legacy flat `session.json`\n * format to the per-run `sessions/<runId>.json` layout on first call.\n *\n * @param projectDir - Absolute path to the project directory.\n * @returns The current session or `null` if no session exists.\n * @docLink packages/runner/session#load-session\n */\nexport async function loadSession(projectDir: string): Promise<SessionState | null> {\n await migrateLegacySession(projectDir);\n try {\n const runId = (await fs.readFile(currentPointerPath(projectDir), \"utf-8\")).trim();\n if (!runId) return null;\n return await loadSessionById(projectDir, runId);\n } catch {\n return null;\n }\n}\n\n/**\n * Load a specific session by its run ID.\n *\n * @param projectDir - Absolute path to the project directory.\n * @param runId - The UUID of the session to load.\n * @returns The session state or `null` if not found.\n * @docLink packages/runner/session#load-session-by-id\n */\nexport async function loadSessionById(\n projectDir: string,\n runId: string,\n): Promise<SessionState | null> {\n try {\n const raw = await fs.readFile(sessionFilePath(projectDir, runId), \"utf-8\");\n return JSON.parse(raw) as SessionState;\n } catch {\n return null;\n }\n}\n\n/**\n * List all sessions for a project.\n *\n * Auto-migrates the legacy flat `session.json` format on first call.\n * Corrupt or unreadable session files are silently skipped.\n *\n * @param projectDir - Absolute path to the project directory.\n * @returns All sessions sorted by `updatedAt` descending (newest first).\n * @docLink packages/runner/session#list-sessions\n */\nexport async function listSessions(projectDir: string): Promise<SessionState[]> {\n await migrateLegacySession(projectDir);\n const dir = sessionsDir(projectDir);\n try {\n const files = await fs.readdir(dir);\n const sessions: SessionState[] = [];\n for (const file of files) {\n if (!file.endsWith(\".json\")) continue;\n try {\n const raw = await fs.readFile(path.join(dir, file), \"utf-8\");\n sessions.push(JSON.parse(raw) as SessionState);\n } catch {\n /* skip corrupt files */\n }\n }\n return sessions.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));\n } catch {\n return [];\n }\n}\n\n/**\n * Persist a session to `<projectDir>/.skaile/sessions/<runId>.json`.\n *\n * @param projectDir - Absolute path to the project directory.\n * @param state - Session state to write.\n * @param setCurrent - When `true` (default), updates the `current` pointer\n * file so subsequent {@link loadSession} calls return this session.\n * @docLink packages/runner/session#save-session\n */\nexport async function saveSession(\n projectDir: string,\n state: SessionState,\n setCurrent = true,\n): Promise<void> {\n await fs.mkdir(sessionsDir(projectDir), { recursive: true });\n await fs.writeFile(\n sessionFilePath(projectDir, state.runId),\n JSON.stringify(state, null, 2),\n \"utf-8\",\n );\n if (setCurrent) {\n await fs.writeFile(currentPointerPath(projectDir), state.runId, \"utf-8\");\n }\n}\n\n/**\n * Set the current session pointer to an existing session.\n *\n * @param projectDir - Absolute path to the project directory.\n * @param runId - The UUID of the session to make current.\n * @throws {Error} When no session with the given `runId` exists.\n * @docLink packages/runner/session#set-current-session\n */\nexport async function setCurrentSession(projectDir: string, runId: string): Promise<void> {\n const exists = await loadSessionById(projectDir, runId);\n if (!exists) throw new Error(`Session not found: ${runId}`);\n await fs.mkdir(path.join(projectDir, SESSION_DIR), { recursive: true });\n await fs.writeFile(currentPointerPath(projectDir), runId, \"utf-8\");\n}\n\n/**\n * Delete a session file by run ID.\n *\n * If the deleted session was the current session, the `current` pointer\n * file is also removed. Missing session files are silently ignored.\n *\n * @param projectDir - Absolute path to the project directory.\n * @param runId - The UUID of the session to delete.\n * @docLink packages/runner/session#delete-session\n */\nexport async function deleteSession(projectDir: string, runId: string): Promise<void> {\n try {\n await fs.rm(sessionFilePath(projectDir, runId));\n } catch {\n /* ignore missing */\n }\n // Clear current pointer if it pointed to this session\n try {\n const current = (await fs.readFile(currentPointerPath(projectDir), \"utf-8\")).trim();\n if (current === runId) {\n await fs.rm(currentPointerPath(projectDir));\n }\n } catch {\n /* ignore */\n }\n}\n\n/**\n * Unset the current session pointer without deleting the session file.\n *\n * After calling this, {@link loadSession} returns `null` until a new\n * session is saved or {@link setCurrentSession} is called.\n *\n * @param projectDir - Absolute path to the project directory.\n * @docLink packages/runner/session#clear-session\n */\nexport async function clearSession(projectDir: string): Promise<void> {\n try {\n await fs.rm(currentPointerPath(projectDir));\n } catch {\n /* ignore missing */\n }\n}\n\n/**\n * Create a new {@link SessionState} with a fresh UUID and current timestamps.\n *\n * The returned session has `status: \"running\"` and both `startedAt` and\n * `updatedAt` set to the current ISO 8601 time. Caller is responsible for\n * persisting it via {@link saveSession}.\n *\n * @param opts - All session fields except `runId`, `startedAt`, `updatedAt`,\n * and `status` (which are generated automatically).\n * @returns A fully initialized session state ready to be saved.\n * @docLink packages/runner/session#new-session\n */\nexport function newSession(\n opts: Omit<SessionState, \"runId\" | \"startedAt\" | \"updatedAt\" | \"status\">,\n): SessionState {\n const now = new Date().toISOString();\n return { ...opts, runId: randomUUID(), startedAt: now, updatedAt: now, status: \"running\" };\n}\n\n/**\n * Update a session's `updatedAt` timestamp without changing any other field.\n * Used by callers that persist a session mid-run to refresh the staleness clock.\n *\n * @param state - Current session state\n * @returns New session state with updated timestamp\n * @docLink packages/runner/session#touch-session\n */\nexport function touchSession(state: SessionState): SessionState {\n return { ...state, updatedAt: new Date().toISOString() };\n}\n"]}