@skaile/workspaces 3.15.0 → 3.16.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 (175) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/dist/{asset-feeds-XSUE5LE6.js → asset-feeds-6UC7CUTI.js} +11 -11
  3. package/dist/{asset-feeds-XSUE5LE6.js.map → asset-feeds-6UC7CUTI.js.map} +1 -1
  4. package/dist/asset-manager/catalog-deployer.js +7 -7
  5. package/dist/asset-manager/index.js +10 -10
  6. package/dist/asset-manager/installer.js +7 -7
  7. package/dist/bridge/drivers/claude-sdk.js +8 -8
  8. package/dist/bridge/drivers/codex.js +3 -3
  9. package/dist/bridge/drivers/continue.js +4 -4
  10. package/dist/bridge/drivers/echo.js +3 -3
  11. package/dist/bridge/drivers/gemini.js +5 -5
  12. package/dist/bridge/drivers/goose.js +4 -4
  13. package/dist/bridge/drivers/omp.js +3 -3
  14. package/dist/bridge/drivers/opencode.js +4 -4
  15. package/dist/bridge/drivers/qwen.js +5 -5
  16. package/dist/bridge/index.js +9 -9
  17. package/dist/{chunk-RUFTB7QN.js → chunk-3NCGSSCU.js} +3 -3
  18. package/dist/{chunk-RUFTB7QN.js.map → chunk-3NCGSSCU.js.map} +1 -1
  19. package/dist/{chunk-4VTBZ2MF.js → chunk-3XXQPHGL.js} +4 -4
  20. package/dist/{chunk-4VTBZ2MF.js.map → chunk-3XXQPHGL.js.map} +1 -1
  21. package/dist/{chunk-3UU3D2Q3.js → chunk-5KSIVLOX.js} +5 -5
  22. package/dist/{chunk-3UU3D2Q3.js.map → chunk-5KSIVLOX.js.map} +1 -1
  23. package/dist/{chunk-CWTL2QWL.js → chunk-6HTQNNOX.js} +7 -7
  24. package/dist/{chunk-CWTL2QWL.js.map → chunk-6HTQNNOX.js.map} +1 -1
  25. package/dist/{chunk-FYLIY6TO.js → chunk-6KPCHQP5.js} +3 -3
  26. package/dist/{chunk-FYLIY6TO.js.map → chunk-6KPCHQP5.js.map} +1 -1
  27. package/dist/{chunk-GHWJHOYX.js → chunk-7BUZQVRR.js} +4 -4
  28. package/dist/{chunk-GHWJHOYX.js.map → chunk-7BUZQVRR.js.map} +1 -1
  29. package/dist/{chunk-JAHHMZWG.js → chunk-7IRJ4K4F.js} +3 -3
  30. package/dist/{chunk-JAHHMZWG.js.map → chunk-7IRJ4K4F.js.map} +1 -1
  31. package/dist/{chunk-QZ6XXD3A.js → chunk-BQMRUH7J.js} +3 -3
  32. package/dist/{chunk-QZ6XXD3A.js.map → chunk-BQMRUH7J.js.map} +1 -1
  33. package/dist/{chunk-O52DU5KU.js → chunk-BUKPS4YL.js} +3 -3
  34. package/dist/{chunk-O52DU5KU.js.map → chunk-BUKPS4YL.js.map} +1 -1
  35. package/dist/{chunk-Q7KWJO4J.js → chunk-C4AP3XZB.js} +5 -5
  36. package/dist/{chunk-Q7KWJO4J.js.map → chunk-C4AP3XZB.js.map} +1 -1
  37. package/dist/{chunk-F2WTSHZS.js → chunk-CIPK5JMJ.js} +4 -4
  38. package/dist/{chunk-F2WTSHZS.js.map → chunk-CIPK5JMJ.js.map} +1 -1
  39. package/dist/{chunk-MTCLDJPR.js → chunk-CL4TYERP.js} +9 -9
  40. package/dist/{chunk-MTCLDJPR.js.map → chunk-CL4TYERP.js.map} +1 -1
  41. package/dist/{chunk-PPKK5EV6.js → chunk-DZ4UZOFB.js} +3 -3
  42. package/dist/{chunk-PPKK5EV6.js.map → chunk-DZ4UZOFB.js.map} +1 -1
  43. package/dist/{chunk-LVZ5NGME.js → chunk-ER4UOIUS.js} +3 -3
  44. package/dist/{chunk-LVZ5NGME.js.map → chunk-ER4UOIUS.js.map} +1 -1
  45. package/dist/{chunk-G2CXWUO5.js → chunk-FAI2SMFE.js} +4 -4
  46. package/dist/{chunk-G2CXWUO5.js.map → chunk-FAI2SMFE.js.map} +1 -1
  47. package/dist/{chunk-5Q7HA4JP.js → chunk-FTG7CRFD.js} +3 -3
  48. package/dist/{chunk-5Q7HA4JP.js.map → chunk-FTG7CRFD.js.map} +1 -1
  49. package/dist/{chunk-TMAGWRKY.js → chunk-GWQZ2ECO.js} +6 -6
  50. package/dist/{chunk-TMAGWRKY.js.map → chunk-GWQZ2ECO.js.map} +1 -1
  51. package/dist/{chunk-5WMFU575.js → chunk-IVWJHELM.js} +116 -29
  52. package/dist/chunk-IVWJHELM.js.map +1 -0
  53. package/dist/{chunk-DTSKPMP3.js → chunk-JNCORFRK.js} +3 -3
  54. package/dist/{chunk-DTSKPMP3.js.map → chunk-JNCORFRK.js.map} +1 -1
  55. package/dist/{chunk-DWO2N72K.js → chunk-KLDWNSDN.js} +4 -4
  56. package/dist/{chunk-DWO2N72K.js.map → chunk-KLDWNSDN.js.map} +1 -1
  57. package/dist/{chunk-FI4QNNMD.js → chunk-MFWIWPJP.js} +8 -8
  58. package/dist/{chunk-FI4QNNMD.js.map → chunk-MFWIWPJP.js.map} +1 -1
  59. package/dist/{chunk-VQ4P7UYE.js → chunk-MKZOK4JU.js} +3 -3
  60. package/dist/{chunk-VQ4P7UYE.js.map → chunk-MKZOK4JU.js.map} +1 -1
  61. package/dist/{chunk-Z5ED4E57.js → chunk-NIUG3MIH.js} +3 -3
  62. package/dist/{chunk-Z5ED4E57.js.map → chunk-NIUG3MIH.js.map} +1 -1
  63. package/dist/{chunk-4OQ2HQCQ.js → chunk-OGTS7QJX.js} +4 -4
  64. package/dist/{chunk-4OQ2HQCQ.js.map → chunk-OGTS7QJX.js.map} +1 -1
  65. package/dist/{chunk-SH572OBN.js → chunk-OIDFK7SG.js} +4 -4
  66. package/dist/{chunk-SH572OBN.js.map → chunk-OIDFK7SG.js.map} +1 -1
  67. package/dist/{chunk-IP3GXHOB.js → chunk-OZ7UNMTK.js} +3 -3
  68. package/dist/{chunk-IP3GXHOB.js.map → chunk-OZ7UNMTK.js.map} +1 -1
  69. package/dist/{chunk-6YDXCJGK.js → chunk-PMYZRX6M.js} +3 -3
  70. package/dist/{chunk-6YDXCJGK.js.map → chunk-PMYZRX6M.js.map} +1 -1
  71. package/dist/{chunk-X5EYJEEQ.js → chunk-S4UA244H.js} +4 -4
  72. package/dist/{chunk-X5EYJEEQ.js.map → chunk-S4UA244H.js.map} +1 -1
  73. package/dist/{chunk-WE7ONZNB.js → chunk-SUPIVTLX.js} +3 -3
  74. package/dist/{chunk-WE7ONZNB.js.map → chunk-SUPIVTLX.js.map} +1 -1
  75. package/dist/{chunk-VFPFW67T.js → chunk-SZ7VJQK3.js} +10 -10
  76. package/dist/{chunk-VFPFW67T.js.map → chunk-SZ7VJQK3.js.map} +1 -1
  77. package/dist/{chunk-3A5IKBHQ.js → chunk-W4IPN3DD.js} +61 -8
  78. package/dist/chunk-W4IPN3DD.js.map +1 -0
  79. package/dist/{chunk-LAOS2TZU.js → chunk-X2665LP2.js} +8 -8
  80. package/dist/{chunk-LAOS2TZU.js.map → chunk-X2665LP2.js.map} +1 -1
  81. package/dist/{chunk-M5D2QNTY.js → chunk-ZNCZ7RUO.js} +3 -3
  82. package/dist/{chunk-M5D2QNTY.js.map → chunk-ZNCZ7RUO.js.map} +1 -1
  83. package/dist/cli/index.js +56 -52
  84. package/dist/cli/index.js.map +1 -1
  85. package/dist/cli/src/commands/serve.d.ts.map +1 -1
  86. package/dist/connectors/config.js +7 -7
  87. package/dist/connectors/index.js +12 -12
  88. package/dist/core/index.js +6 -6
  89. package/dist/core/logging.js +2 -2
  90. package/dist/core/manifest.js +2 -2
  91. package/dist/core/runtime-assets.js +4 -4
  92. package/dist/core/src/logging/index.d.ts +2 -0
  93. package/dist/core/src/logging/index.d.ts.map +1 -1
  94. package/dist/core/src/logging/log-store.d.ts.map +1 -1
  95. package/dist/core/src/logging/sinks/stdout-sink.d.ts +6 -1
  96. package/dist/core/src/logging/sinks/stdout-sink.d.ts.map +1 -1
  97. package/dist/core/src/logging/stream-health.d.ts +46 -0
  98. package/dist/core/src/logging/stream-health.d.ts.map +1 -0
  99. package/dist/core/workspace-config.js +3 -3
  100. package/dist/deploy/index.js +8 -7
  101. package/dist/deploy/index.js.map +1 -1
  102. package/dist/deploy/src/targets/process-handle.d.ts.map +1 -1
  103. package/dist/discovery/index.js +3 -3
  104. package/dist/{ensure-sources-SFQT5GXY.js → ensure-sources-VJZUHSFZ.js} +13 -13
  105. package/dist/{ensure-sources-SFQT5GXY.js.map → ensure-sources-VJZUHSFZ.js.map} +1 -1
  106. package/dist/factory-assets/connectors/box.js +12 -12
  107. package/dist/factory-assets/connectors/deploy.js +12 -12
  108. package/dist/factory-assets/connectors/devserver.js +12 -12
  109. package/dist/factory-assets/connectors/flow/adapter.js +12 -12
  110. package/dist/factory-assets/connectors/flow/engine.js +7 -7
  111. package/dist/factory-assets/connectors/flow/run-flow.js +14 -14
  112. package/dist/factory-assets/connectors/flow.js +12 -12
  113. package/dist/factory-assets/connectors/git.js +12 -12
  114. package/dist/factory-assets/connectors/gmail.js +12 -12
  115. package/dist/factory-assets/connectors/googledrive.js +12 -12
  116. package/dist/factory-assets/connectors/local.js +12 -12
  117. package/dist/factory-assets/connectors/mattermost.js +12 -12
  118. package/dist/factory-assets/connectors/memory.js +12 -12
  119. package/dist/factory-assets/connectors/minio.js +12 -12
  120. package/dist/factory-assets/connectors/postgres.js +12 -12
  121. package/dist/factory-assets/connectors/s3.js +12 -12
  122. package/dist/factory-assets/connectors/sharepoint.js +12 -12
  123. package/dist/factory-assets/connectors/sqlite.js +12 -12
  124. package/dist/factory-assets/connectors/static-server.js +12 -12
  125. package/dist/factory-assets/connectors/tunnel.js +12 -12
  126. package/dist/factory-assets/connectors/webdav.js +12 -12
  127. package/dist/factory-assets/connectors/xstate-store.js +12 -12
  128. package/dist/factory-assets/connectors/xstate.js +12 -12
  129. package/dist/flows-2SUFOVVO.js +20 -0
  130. package/dist/{flows-Z3DM5BHF.js.map → flows-2SUFOVVO.js.map} +1 -1
  131. package/dist/{helpers-VRQXNHFR.js → helpers-EEYMGGLO.js} +13 -13
  132. package/dist/{helpers-VRQXNHFR.js.map → helpers-EEYMGGLO.js.map} +1 -1
  133. package/dist/library/index.js +8 -8
  134. package/dist/library/install.js +6 -6
  135. package/dist/{library-publish-DV3B2ITY.js → library-publish-37UBVMC3.js} +17 -17
  136. package/dist/{library-publish-DV3B2ITY.js.map → library-publish-37UBVMC3.js.map} +1 -1
  137. package/dist/{open-library-2BXBAC6Q.js → open-library-JYVUN4CY.js} +15 -15
  138. package/dist/{open-library-2BXBAC6Q.js.map → open-library-JYVUN4CY.js.map} +1 -1
  139. package/dist/paths-4APA2PKT.js +16 -0
  140. package/dist/{paths-AI7MDPNA.js.map → paths-4APA2PKT.js.map} +1 -1
  141. package/dist/{plugin-store-OO5EZBYP.js → plugin-store-JQAIKR3R.js} +8 -8
  142. package/dist/{plugin-store-OO5EZBYP.js.map → plugin-store-JQAIKR3R.js.map} +1 -1
  143. package/dist/{project-2TYDMEZB.js → project-DKQACM3N.js} +14 -14
  144. package/dist/{project-2TYDMEZB.js.map → project-DKQACM3N.js.map} +1 -1
  145. package/dist/resolver/index.js +7 -7
  146. package/dist/runner/index.js +17 -17
  147. package/dist/runner/src/process-safety-net.d.ts +61 -0
  148. package/dist/runner/src/process-safety-net.d.ts.map +1 -0
  149. package/dist/runner/src/serve.d.ts +10 -0
  150. package/dist/runner/src/serve.d.ts.map +1 -1
  151. package/dist/sdk/asset-manager.js +10 -10
  152. package/dist/sdk/bridge.js +9 -9
  153. package/dist/sdk/core.js +6 -6
  154. package/dist/sdk/flow.js +7 -7
  155. package/dist/sdk/index.js +17 -17
  156. package/dist/sdk/resolver.js +7 -7
  157. package/dist/sdk/runner.js +17 -17
  158. package/dist/{setup-EH4TZFMN.js → setup-7FJNMKFA.js} +11 -11
  159. package/dist/{setup-EH4TZFMN.js.map → setup-7FJNMKFA.js.map} +1 -1
  160. package/dist/skills-Q7PJVB3W.js +20 -0
  161. package/dist/{skills-XZOG6ZPX.js.map → skills-Q7PJVB3W.js.map} +1 -1
  162. package/dist/{source-PVTUMNAO.js → source-CT6RH3CJ.js} +16 -16
  163. package/dist/{source-PVTUMNAO.js.map → source-CT6RH3CJ.js.map} +1 -1
  164. package/dist/{source-manifest-publish-3XYTUVQQ.js → source-manifest-publish-VBENANBT.js} +18 -18
  165. package/dist/{source-manifest-publish-3XYTUVQQ.js.map → source-manifest-publish-VBENANBT.js.map} +1 -1
  166. package/dist/tui/index.js +17 -17
  167. package/dist/workspace-plugin/adapters/mcp.js +11 -11
  168. package/dist/workspace-plugin/adapters/omp.js +7 -7
  169. package/dist/workspace-plugin/index.js +3 -3
  170. package/package.json +1 -1
  171. package/dist/chunk-3A5IKBHQ.js.map +0 -1
  172. package/dist/chunk-5WMFU575.js.map +0 -1
  173. package/dist/flows-Z3DM5BHF.js +0 -20
  174. package/dist/paths-AI7MDPNA.js +0 -16
  175. package/dist/skills-XZOG6ZPX.js +0 -20
@@ -1 +1 @@
1
- {"version":3,"sources":["../bridge/src/cloud.ts","../bridge/src/drivers/scrub-transcript.ts","../bridge/src/drivers/resume-probe.ts"],"names":["join"],"mappings":";;;;;;;;AAsBO,IAAM,mBAAmB,CAAC,SAAA,EAAW,SAAA,EAAW,QAAA,EAAU,SAAS,SAAS;AAuC5E,IAAM,qBAAA,GAAgF;AAAA,EAC3F,OAAA,EAAS;AAAA,IACP,mBAAA;AAAA,IACA,uBAAA;AAAA,IACA,mBAAA;AAAA,IACA;AAAA,GACF;AAAA,EACA,MAAA,EAAQ,CAAC,qCAAqC,CAAA;AAAA,EAC9C,KAAA,EAAO,CAAC,2BAA2B,CAAA;AAAA,EACnC,OAAA,EAAS,CAAC,sBAAA,EAAwB,mBAAmB;AACvD;AAaA,IAAM,iBAAA,GAAoB,CAAC,mBAAA,EAAqB,sBAAA,EAAwB,oBAAoB,CAAA;AAuBrF,SAAS,oBAAoB,IAAA,EAQT;AACzB,EAAA,MAAM,EAAE,KAAA,EAAO,WAAA,EAAa,cAAc,OAAA,EAAS,SAAA,EAAW,gBAAe,GAAI,IAAA;AACjF,EAAA,MAAM,MAA8B,EAAE,GAAG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AA,CAAkB,UAAU,OAAO,CAAA,CAAA,EAAI,MAAM,MAAA,CAAO,OAAO,CAAA,EAAG,MAAA,EAAW,SAAS,CAAA;AACxF,IAAA,OAAO,MAAA;AAAA,EACT;AAEA,EAAA,MAAA,CAAO,OAAA,GAAU,IAAA;AACjB,EAAA,GAAA,EAAK,KAAK,gDAAA,EAAkD;AAAA,IAC1D,QAAA;AAAA,IACA,WAAW,MAAA,CAAO,SAAA;AAAA,IAClB,SAAS,MAAA,CAAO,OAAA;AAAA,IAChB,eAAe,MAAA,CAAO;AAAA,GACvB,CAAA;AACD,EAAA,OAAO,MAAA;AACT;ACtcA,IAAM,uBAAA,GAA0B,GAAA;AAwBzB,SAAS,uBAAuB,GAAA,EAAkD;AACvF,EAAA,OAAO,GAAA,EAAK,qBAAqB,OAAA,CAAQ,GAAA,CAAI,qBAAqBA,IAAAA,CAAK,OAAA,IAAW,SAAS,CAAA;AAC7F;AAgBA,eAAsB,qBAAA,CACpB,WACA,IAAA,EAKyC;AACzC,EAAA,MAAM,SAAA,GAAY,sBAAA,CAAuB,IAAA,EAAM,GAAG,CAAA;AAClD,EAAA,MAAM,SAAA,GAAY,MAAM,SAAA,IAAa,uBAAA;AACrC,EAAA,MAAM,MAAA,GAAS,MAAM,MAAA,IAAU,oBAAA;AAC/B,EAAA,IAAI;AAIF,IAAA,MAAM,WAAW,MAAM,cAAA;AAAA,MACrB,gBAAgB,SAAS,CAAA,CAAA;AAAA,MACzB,MAAM,MAAA,CAAO,SAAA,EAAW,SAAS,CAAA;AAAA,MACjC;AAAA,KACF;AACA,IAAA,OAAO,WAAW,kBAAA,GAAqB,YAAA;AAAA,EACzC,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,MAAA;AAAA,EACT;AACF","file":"chunk-RUFTB7QN.js","sourcesContent":["/**\n * AI cloud-provider transport dimension for the `claude-sdk` driver.\n *\n * `cloud` is a config axis orthogonal to `provider` (model vendor) and\n * `driver` (agent runtime). Under `driver: claude-sdk` each non-default value\n * maps to one of the Claude Agent SDK's native env-var transports:\n * Amazon Bedrock, Google Vertex AI, Azure AI Foundry, or a generic\n * `ANTHROPIC_BASE_URL` gateway (LiteLLM / corporate proxy).\n *\n * Cross-repo contract: env key names and semantics here are load-bearing —\n * the platform resolves credential bundles against the same key set.\n */\n\n/**\n * Canonical list of supported cloud transports. `\"default\"` (or an absent\n * `cloud` field) means the provider's native API — today's behavior, unchanged.\n *\n * The codec in `core/workspace-config.ts` keeps a local copy (`KNOWN_CLOUDS`)\n * to avoid an import cycle; a drift test asserts parity.\n *\n * @since 1.3.0\n */\nexport const SUPPORTED_CLOUDS = [\"default\", \"bedrock\", \"vertex\", \"azure\", \"gateway\"] as const;\n\n/** One of the supported cloud transport identifiers. */\nexport type CloudId = (typeof SUPPORTED_CLOUDS)[number];\n\n/**\n * Non-secret transport settings for a cloud. Sourced from skaile.yaml\n * `cloud_config` (snake_case on the wire, camelCase in-process — converted\n * exactly once at the settings/serve boundary).\n *\n * Must stay field-identical with core's `CloudTransportConfig` and the inline\n * `AgentSessionConfig.cloudConfig` shape (kept separate to avoid a core↔bridge\n * import cycle) — a field added here must be added there too.\n *\n * @since 1.3.0\n */\nexport interface CloudConfig {\n /** bedrock: AWS region (`AWS_REGION`); vertex: `CLOUD_ML_REGION`. */\n region?: string;\n /** vertex only: GCP project (`ANTHROPIC_VERTEX_PROJECT_ID`). */\n projectId?: string;\n /** azure only: Foundry resource name (`ANTHROPIC_FOUNDRY_RESOURCE`). */\n resource?: string;\n /** azure (alternative to `resource`) / gateway (required): endpoint base URL. */\n baseUrl?: string;\n}\n\n/**\n * Secret env keys that make up the credential bundle for each non-default\n * cloud. The platform delivers these env-keyed in the `session_init` secrets\n * map; the runner picks them out via `resolveCloudSecretBundle`.\n *\n * Vertex note: `GOOGLE_APPLICATION_CREDENTIALS_JSON` is our convention for the\n * raw service-account JSON blob. The runner materializes it to a 0600 file and\n * hands the driver `GOOGLE_APPLICATION_CREDENTIALS` (a path) instead — the\n * driver never sees the raw JSON.\n *\n * @since 1.3.0\n */\nexport const CLOUD_SECRET_ENV_KEYS: Record<Exclude<CloudId, \"default\">, readonly string[]> = {\n bedrock: [\n \"AWS_ACCESS_KEY_ID\",\n \"AWS_SECRET_ACCESS_KEY\",\n \"AWS_SESSION_TOKEN\",\n \"AWS_BEARER_TOKEN_BEDROCK\",\n ],\n vertex: [\"GOOGLE_APPLICATION_CREDENTIALS_JSON\"],\n azure: [\"ANTHROPIC_FOUNDRY_API_KEY\"],\n gateway: [\"ANTHROPIC_AUTH_TOKEN\", \"ANTHROPIC_API_KEY\"],\n};\n\n/**\n * Env vars scrubbed from the inherited environment before a non-default cloud\n * transport is assembled. Ambient first-party credentials or a stale\n * `CLAUDE_CODE_USE_*` flag must never leak into a Bedrock/Vertex/Foundry/\n * gateway session (the gateway branch re-adds its own carriers explicitly).\n *\n * Deliberately NOT exhaustive across clouds: ambient cloud-specific vars\n * (AWS_*, GOOGLE_*, ANTHROPIC_VERTEX_PROJECT_ID, ANTHROPIC_FOUNDRY_*) survive\n * so a standalone CLI inherits its own cloud's environment; the SDK ignores\n * vars whose transport flag is unset.\n */\nconst SCRUBBED_ENV_KEYS = [\"ANTHROPIC_API_KEY\", \"ANTHROPIC_AUTH_TOKEN\", \"ANTHROPIC_BASE_URL\"];\n\n/**\n * Assemble the Claude Agent SDK child env for a non-default cloud transport.\n *\n * Pure function (no external state touched; the returned `env` is a fresh\n * object — inputs are never mutated): starts from `baseEnv` (caller passes a\n * copy of `process.env` with undefined stripped) merged with `configEnv`,\n * scrubs inherited Anthropic\n * credential/routing vars and every `CLAUDE_CODE_USE_*` flag, then sets exactly\n * one `CLAUDE_CODE_USE_*` flag (none for gateway) plus the cloud's credential\n * bundle and derived non-secret vars. AWS_* / GOOGLE_* ambient values are NOT\n * scrubbed, so a standalone CLI inherits ambient cloud credentials when no\n * explicit `cloudSecrets` bundle is provided. Gateway is the mirror case: its\n * carriers ARE the scrubbed Anthropic vars, so the gateway branch restores\n * them from `cloudSecrets` → `fallbackApiKey` (resolved `apiKeys.anthropic`)\n * → the pre-scrub config/ambient value — otherwise a standalone gateway\n * session would have no reachable auth carrier at all.\n *\n * Never returns `undefined` values; absent settings are simply omitted.\n *\n * @since 1.3.0\n */\nexport function buildClaudeCloudEnv(args: {\n cloud: Exclude<CloudId, \"default\">;\n cloudConfig?: CloudConfig;\n cloudSecrets?: Record<string, string>;\n baseEnv: Record<string, string>;\n configEnv?: Record<string, string>;\n /** Resolved API key (e.g. `apiKeys.anthropic`) — gateway auth fallback only. */\n fallbackApiKey?: string;\n}): Record<string, string> {\n const { cloud, cloudConfig, cloudSecrets, baseEnv, configEnv, fallbackApiKey } = args;\n const env: Record<string, string> = { ...baseEnv, ...(configEnv ?? {}) };\n\n // Captured before the scrub — gateway falls back to these carriers.\n const ambient = {\n authToken: env.ANTHROPIC_AUTH_TOKEN,\n apiKey: env.ANTHROPIC_API_KEY,\n baseUrl: env.ANTHROPIC_BASE_URL,\n };\n\n for (const key of Object.keys(env)) {\n if (SCRUBBED_ENV_KEYS.includes(key) || key.startsWith(\"CLAUDE_CODE_USE_\")) {\n delete env[key];\n }\n }\n\n const set = (key: string, value: string | undefined) => {\n // Falsy check is deliberate: an empty-string credential/setting is never\n // valid env — dropping it beats shipping a key the SDK treats as set.\n if (value) env[key] = value;\n };\n\n switch (cloud) {\n case \"bedrock\": {\n env.CLAUDE_CODE_USE_BEDROCK = \"1\";\n // Explicit bundle values override ambient AWS_* (which survive the scrub\n // so a standalone CLI keeps its ambient credentials).\n for (const key of CLOUD_SECRET_ENV_KEYS.bedrock) set(key, cloudSecrets?.[key]);\n set(\"AWS_REGION\", cloudConfig?.region);\n break;\n }\n case \"vertex\": {\n env.CLAUDE_CODE_USE_VERTEX = \"1\";\n // Runner-materialized SA file path; ambient GOOGLE_APPLICATION_CREDENTIALS\n // is kept when no bundle value is provided.\n set(\"GOOGLE_APPLICATION_CREDENTIALS\", cloudSecrets?.GOOGLE_APPLICATION_CREDENTIALS);\n set(\"ANTHROPIC_VERTEX_PROJECT_ID\", cloudConfig?.projectId);\n set(\"CLOUD_ML_REGION\", cloudConfig?.region);\n break;\n }\n case \"azure\": {\n env.CLAUDE_CODE_USE_FOUNDRY = \"1\";\n set(\"ANTHROPIC_FOUNDRY_API_KEY\", cloudSecrets?.ANTHROPIC_FOUNDRY_API_KEY);\n // Resource wins over base_url when both are configured.\n if (cloudConfig?.resource) {\n env.ANTHROPIC_FOUNDRY_RESOURCE = cloudConfig.resource;\n } else {\n set(\"ANTHROPIC_FOUNDRY_BASE_URL\", cloudConfig?.baseUrl);\n }\n break;\n }\n case \"gateway\": {\n // No CLAUDE_CODE_USE_* flag — the gateway is addressed purely via\n // ANTHROPIC_BASE_URL plus an auth carrier. Explicit bundle wins;\n // standalone sessions fall back to the resolved key / ambient carriers.\n set(\"ANTHROPIC_BASE_URL\", cloudConfig?.baseUrl ?? ambient.baseUrl);\n const authToken = cloudSecrets?.ANTHROPIC_AUTH_TOKEN ?? ambient.authToken;\n if (authToken) {\n env.ANTHROPIC_AUTH_TOKEN = authToken;\n } else {\n set(\n \"ANTHROPIC_API_KEY\",\n cloudSecrets?.ANTHROPIC_API_KEY ?? fallbackApiKey ?? ambient.apiKey,\n );\n }\n break;\n }\n }\n\n return env;\n}\n","/**\n * Poisoned-transcript repair for the Claude Agent SDK driver.\n *\n * The Anthropic Messages API can permanently reject a conversation once its\n * persisted history contains a malformed content block. Because the bad block\n * lives in the SDK's on-disk JSONL transcript, every replayed turn fails with\n * the same `400 invalid_request_error` and the session is bricked with no\n * in-band recovery.\n *\n * This module repairs the transcript in place, covering three known poison\n * classes:\n *\n * 1. **Image `media_type` mismatch / omission.** An image block whose declared\n * `media_type` does not match — or is missing for — the actual bytes:\n * `... The image was specified using the image/png media type, but the\n * image appears to be a image/jpeg image`. Produced by the Claude Code\n * `Read` tool's format fallback (anthropics/claude-code#55338, #30124,\n * #33179). Repaired by sniffing the base64 magic bytes and correcting\n * `media_type`.\n * 2. **Oversized image.** An image whose decoded payload exceeds the API's\n * 5 MB per-image limit (anthropics/claude-code#34566). Replaced with a\n * text stub — the byte budget cannot be recovered any other way.\n * 3. **`cache_control` on an empty text block.** A text block carrying a\n * `cache_control` marker with empty/whitespace `text`\n * (anthropics/claude-code#59626). The `cache_control` field is stripped.\n *\n * Genuinely unidentifiable image blocks are also replaced with a text stub.\n *\n * Recovering by content scan (rather than parsing the API's `messages.N`\n * index) is deliberate: the index addresses the assembled API request, not a\n * JSONL line, and reproducing the SDK's message-assembly is fragile. A full\n * scan is index-free and repairs every poisoned block in one pass.\n *\n * **Async and line-streaming since #454.** A Claude Code transcript is routinely\n * multi-megabyte (base64 images inline in `tool_result` blocks), and this runs on\n * a failed turn *and before every resume* — inside the single-threaded `skaile\n * serve` loop. The previous `readFileSync` + `writeFileSync` + `renameSync` held\n * the loop for the whole file and materialised it twice over as one string. Both\n * passes now stream line by line off a `createReadStream`, so the loop is yielded\n * between lines and peak memory is one JSONL line rather than the whole file, and\n * every I/O phase is deadline-bounded.\n *\n * Streaming was chosen over a worker thread: the work is I/O-bound rather than\n * CPU-bound (per-line `JSON.parse` on a yielded loop is not what stalls a turn),\n * and a worker would add a structured-clone of the same multi-MB payload plus a\n * thread lifecycle to a path that must never block a turn.\n *\n * @module\n */\n\nimport { createReadStream, createWriteStream } from \"node:fs\";\nimport { readdir, rename, stat, unlink } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { pipeline } from \"node:stream/promises\";\nimport { fsDeadlineMs, tryWithFsDeadline, withFsDeadline } from \"@skaile/workspaces/core\";\n\n/**\n * Minimal logger shape accepted by {@link scrubPoisonedTranscript}. Compatible\n * with the bridge `Logger`, but narrowed so the helper stays unit-testable\n * without a real logger instance.\n *\n * @category Transcript repair\n */\nexport interface ScrubLogger {\n info(message: string, data?: Record<string, unknown>): void;\n warn(message: string, data?: Record<string, unknown>): void;\n}\n\n/**\n * Options for {@link scrubPoisonedTranscript}.\n *\n * @category Transcript repair\n */\nexport interface ScrubTranscriptOptions {\n /**\n * Claude Code config directory — the parent of `projects/`. Resolve from\n * `CLAUDE_CONFIG_DIR`, falling back to `~/.claude`.\n */\n configDir: string;\n /** SDK session id whose transcript JSONL should be repaired. */\n sessionId: string;\n /** Optional logger for diagnostics. */\n log?: ScrubLogger;\n}\n\n/**\n * Outcome of a {@link scrubPoisonedTranscript} pass.\n *\n * @category Transcript repair\n */\nexport interface ScrubTranscriptResult {\n /** The located JSONL transcript path, or `null` when not found. */\n filePath: string | null;\n /** Image blocks whose `media_type` was corrected (or filled in) to match the bytes. */\n corrected: number;\n /**\n * Image blocks replaced with a text stub — either unidentifiable bytes or a\n * payload over the API's 5 MB per-image limit.\n */\n stubbed: number;\n /** Empty text blocks from which a rejected `cache_control` marker was stripped. */\n cacheStripped: number;\n /**\n * `true` when the transcript was located, contained at least one poisoned\n * block, and was rewritten. `false` means nothing needed repair (or the\n * file was not found) — the caller should not retry the resume.\n */\n changed: boolean;\n}\n\n/** Text inserted in place of an image block whose format cannot be identified. */\nconst STUB_TEXT = \"[image removed: unprocessable image data]\";\n\n/** Text inserted in place of an image block that exceeds the API size limit. */\nconst STUB_TEXT_OVERSIZED = \"[image removed: image too large]\";\n\n/**\n * The Anthropic Messages API rejects any single image whose decoded payload\n * exceeds 5 MB. An image at or under this is left alone; a larger one is\n * stubbed (its byte budget cannot be recovered).\n */\nconst MAX_IMAGE_BYTES = 5 * 1024 * 1024;\n\n/**\n * Identify an image's media type from the leading bytes of its base64 payload.\n *\n * Recognises the four formats the Anthropic API accepts. Returns `null` when\n * the magic bytes match no known format — the caller treats that as a\n * genuinely corrupt block and stubs it.\n *\n * @param base64 - Base64-encoded image data (only the prefix is inspected).\n * @returns An `image/*` media type, or `null` when unrecognised.\n * @category Transcript repair\n */\nexport function sniffImageMediaType(base64: string): string | null {\n let buf: Buffer;\n try {\n // 32 base64 chars decode to 24 bytes — enough for the WebP check at 12.\n buf = Buffer.from(base64.slice(0, 32), \"base64\");\n } catch {\n return null;\n }\n if (buf.length < 4) {\n return null;\n }\n // JPEG — SOI marker `FF D8`. Third byte varies (and may be corrupt), so a\n // two-byte check is intentional: it still matches malformed JPEGs, which is\n // exactly the poison case the API flags as \"appears to be image/jpeg\".\n if (buf[0] === 0xff && buf[1] === 0xd8) {\n return \"image/jpeg\";\n }\n // PNG — `89 50 4E 47`.\n if (buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47) {\n return \"image/png\";\n }\n // GIF — `47 49 46 38` (\"GIF8\").\n if (buf[0] === 0x47 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x38) {\n return \"image/gif\";\n }\n // WebP — `RIFF` at 0..3 and `WEBP` at 8..11.\n if (\n buf.length >= 12 &&\n buf[0] === 0x52 &&\n buf[1] === 0x49 &&\n buf[2] === 0x46 &&\n buf[3] === 0x46 &&\n buf[8] === 0x57 &&\n buf[9] === 0x45 &&\n buf[10] === 0x42 &&\n buf[11] === 0x50\n ) {\n return \"image/webp\";\n }\n return null;\n}\n\n/** A base64 image source on a content block (shape is SDK-defined). */\ninterface Base64ImageSource {\n type?: string;\n media_type?: string;\n data?: string;\n}\n\n/** Loosely-typed content block from a transcript message. */\ninterface ContentBlockLike {\n type?: string;\n source?: Base64ImageSource;\n content?: unknown;\n [k: string]: unknown;\n}\n\n/** Mutable counters threaded through one scrub pass. */\ninterface ScrubCounters {\n corrected: number;\n stubbed: number;\n cacheStripped: number;\n}\n\n/** Total repairs recorded in a counter set — used to detect per-line changes. */\nfunction totalChanges(c: ScrubCounters): number {\n return c.corrected + c.stubbed + c.cacheStripped;\n}\n\n/**\n * Repair a single content block. Returns the (possibly replaced) block.\n *\n * - A `tool_result` block recurses into its `content` array.\n * - A text block carrying a `cache_control` marker whose `text` is empty or\n * whitespace has the marker stripped (the API rejects `cache_control` on\n * empty text blocks).\n * - An image block whose decoded payload exceeds the API's 5 MB limit is\n * replaced with a text stub.\n * - An image block whose bytes match no known format is replaced with a text\n * stub (an image cannot simply be dropped — a `tool_result` must keep at\n * least one content entry, and a bare `image` block is replaced 1:1).\n * - An image block whose declared `media_type` mismatches (or is missing for)\n * the sniffed type is corrected in place.\n * - Every other block is returned untouched.\n */\nfunction scrubBlock(block: ContentBlockLike, counters: ScrubCounters): ContentBlockLike {\n if (block.type === \"tool_result\" && Array.isArray(block.content)) {\n return {\n ...block,\n content: (block.content as ContentBlockLike[]).map((inner) => scrubBlock(inner, counters)),\n };\n }\n\n // A `cache_control` marker on a text block whose text is empty or whitespace\n // is rejected by the API (\"cache_control cannot be set for empty text\n // blocks\"). Strip the marker — the empty block itself is harmless.\n if (block.type === \"text\" && block.cache_control != null) {\n const text = typeof block.text === \"string\" ? block.text : \"\";\n if (text.trim() === \"\") {\n counters.cacheStripped++;\n const clone = { ...block };\n delete clone.cache_control;\n return clone;\n }\n }\n\n if (\n block.type === \"image\" &&\n block.source?.type === \"base64\" &&\n typeof block.source.data === \"string\"\n ) {\n const data = block.source.data;\n // The API rejects any image whose decoded payload exceeds 5 MB. The byte\n // budget cannot be salvaged, so the whole block becomes a text stub.\n // base64 encodes 3 bytes per 4 chars, so decoded length ≈ len * 3 / 4.\n if (Math.floor((data.length * 3) / 4) > MAX_IMAGE_BYTES) {\n counters.stubbed++;\n return { type: \"text\", text: STUB_TEXT_OVERSIZED };\n }\n const sniffed = sniffImageMediaType(data);\n if (sniffed === null) {\n counters.stubbed++;\n return { type: \"text\", text: STUB_TEXT };\n }\n if (sniffed !== block.source.media_type) {\n counters.corrected++;\n return { ...block, source: { ...block.source, media_type: sniffed } };\n }\n }\n\n return block;\n}\n\n/**\n * Locate the JSONL transcript for `sessionId` under `<configDir>/projects/`.\n *\n * Claude Code encodes the project directory into the `projects/` subfolder\n * name; rather than reproduce that encoding, this scans every subfolder for\n * `<sessionId>.jsonl` (the session id is a UUID — globally unique).\n *\n * Async and deadline-bounded since #454. The `existsSync(projectsDir)` probe is\n * gone: `readdir` already fails on a missing directory, so the probe was a\n * second stat on the same path for no information.\n *\n * `timeoutMs` defaults to {@link fsDeadlineMs} so callers that only need the\n * path (the resume probe) can omit it.\n *\n * @category Transcript repair\n */\nexport async function locateTranscriptPath(\n configDir: string,\n sessionId: string,\n timeoutMs: number = fsDeadlineMs(),\n): Promise<string | null> {\n const projectsDir = join(configDir, \"projects\");\n const entries = await tryWithFsDeadline(\n `readdir ${projectsDir}`,\n () => readdir(projectsDir),\n null,\n timeoutMs,\n );\n if (!entries) return null;\n for (const entry of entries) {\n const candidate = join(projectsDir, entry, `${sessionId}.jsonl`);\n const found = await tryWithFsDeadline(\n `stat ${candidate}`,\n async () => (await stat(candidate)).isFile(),\n false,\n timeoutMs,\n );\n if (found) return candidate;\n }\n return null;\n}\n\n/**\n * Yield a file's contents line by line, reproducing `readFileSync(...).split(\"\\n\")`\n * exactly — including the final (possibly empty) segment, so a trailing newline\n * survives a rewrite byte for byte.\n *\n * Splits on `\\n` alone, so a line out of a CRLF transcript arrives with its\n * `\\r` still attached. That carrier byte is part of the line here, and\n * {@link repairLine} re-attaches it to a line it rewrites — the file keeps the\n * terminator style it arrived with. Deliberately not `node:readline`:\n * `crlfDelay` strips the `\\r` outright (rewriting a CRLF transcript to LF) and\n * the interface swallows the trailing-newline distinction, either of which\n * would make the \"clean transcript is left byte-for-byte untouched\" guarantee\n * false. Only one line is held in memory at a time, so a multi-MB transcript\n * never materialises as a single string.\n */\nasync function* streamLines(filePath: string): AsyncGenerator<string> {\n const stream = createReadStream(filePath, { encoding: \"utf8\" });\n let pending = \"\";\n try {\n for await (const chunk of stream) {\n pending += chunk as string;\n let idx = pending.indexOf(\"\\n\");\n while (idx !== -1) {\n yield pending.slice(0, idx);\n pending = pending.slice(idx + 1);\n idx = pending.indexOf(\"\\n\");\n }\n }\n yield pending;\n } finally {\n stream.destroy();\n }\n}\n\n/**\n * Repair one JSONL line, returning the (possibly rewritten) line and mutating\n * `counters`. A non-JSON, blank, or content-less line is returned untouched.\n *\n * The reader splits on `\\n` only, so a line from a CRLF transcript still carries\n * its trailing `\\r`. An untouched line is returned verbatim and keeps it; a\n * rewritten one is rebuilt by `JSON.stringify`, which would drop it — leaving a\n * repaired CRLF transcript with mixed line endings. So the terminator is split\n * off before the parse and re-appended to the rewritten line.\n */\nfunction repairLine(line: string, counters: ScrubCounters): string {\n if (line.trim() === \"\") return line;\n const eol = line.endsWith(\"\\r\") ? \"\\r\" : \"\";\n const body = eol === \"\" ? line : line.slice(0, -1);\n let entry: { message?: { content?: unknown } };\n try {\n entry = JSON.parse(body);\n } catch {\n return line; // Not JSON — leave untouched.\n }\n const content = entry.message?.content;\n if (!Array.isArray(content)) return line;\n const before = totalChanges(counters);\n const scrubbed = (content as ContentBlockLike[]).map((block) => scrubBlock(block, counters));\n if (totalChanges(counters) === before) return line; // Nothing changed on this line.\n return `${JSON.stringify({ ...entry, message: { ...entry.message, content: scrubbed } })}${eol}`;\n}\n\n/**\n * Scan a Claude Code SDK transcript for image content blocks whose declared\n * `media_type` does not match the actual bytes, repair them, and atomically\n * rewrite the file.\n *\n * Safe to call after a turn has failed: the SDK query is dead at that point,\n * and the next resume re-reads the transcript from disk.\n *\n * **Async since #454.** Two streaming passes rather than one whole-file read:\n * pass 1 counts repairs without writing anything, and pass 2 runs only when\n * pass 1 found something. The common case — the preventive scrub of a clean\n * transcript before every resume — is therefore one streaming read and zero\n * writes, and a clean transcript is still left byte-for-byte untouched.\n *\n * @param opts - Config directory, session id, and an optional logger.\n * @returns A {@link ScrubTranscriptResult}. When `changed` is `true` the\n * caller may retry the resume with the same session id.\n * @category Transcript repair\n */\nexport async function scrubPoisonedTranscript(\n opts: ScrubTranscriptOptions,\n): Promise<ScrubTranscriptResult> {\n const { configDir, sessionId, log } = opts;\n const timeoutMs = fsDeadlineMs();\n const result: ScrubTranscriptResult = {\n filePath: null,\n corrected: 0,\n stubbed: 0,\n cacheStripped: 0,\n changed: false,\n };\n\n const filePath = await locateTranscriptPath(configDir, sessionId, timeoutMs);\n if (!filePath) {\n log?.warn(\"scrub-transcript: no transcript found\", { configDir, sessionId });\n return result;\n }\n result.filePath = filePath;\n\n // ── Pass 1: detect. Streams the transcript, counting repairs, writing nothing.\n const counters: ScrubCounters = { corrected: 0, stubbed: 0, cacheStripped: 0 };\n try {\n await withFsDeadline(\n `scan transcript ${filePath}`,\n async () => {\n for await (const line of streamLines(filePath)) repairLine(line, counters);\n },\n timeoutMs,\n );\n } catch (err) {\n log?.warn(\"scrub-transcript: failed to read transcript\", {\n filePath,\n error: err instanceof Error ? err.message : String(err),\n });\n return result;\n }\n\n result.corrected = counters.corrected;\n result.stubbed = counters.stubbed;\n result.cacheStripped = counters.cacheStripped;\n\n if (totalChanges(counters) === 0) {\n return result;\n }\n\n // ── Pass 2: rewrite. Atomic: stream a sibling temp file, then rename over the\n // original. Line separators are re-emitted exactly as pass 1 split them, so a\n // trailing newline and any blank lines survive verbatim.\n const tmpPath = `${filePath}.scrub-tmp`;\n try {\n await withFsDeadline(\n `rewrite transcript ${filePath}`,\n async () => {\n const discard: ScrubCounters = { corrected: 0, stubbed: 0, cacheStripped: 0 };\n await pipeline(\n (async function* () {\n let first = true;\n for await (const line of streamLines(filePath)) {\n yield first ? repairLine(line, discard) : `\\n${repairLine(line, discard)}`;\n first = false;\n }\n })(),\n createWriteStream(tmpPath, { encoding: \"utf8\" }),\n );\n await rename(tmpPath, filePath);\n },\n timeoutMs,\n );\n } catch (err) {\n log?.warn(\"scrub-transcript: failed to rewrite transcript\", {\n filePath,\n error: err instanceof Error ? err.message : String(err),\n });\n // Never leave a half-written sibling behind — the next scrub would rewrite\n // it anyway, but a stray `.scrub-tmp` in the SDK's projects dir is noise.\n await tryWithFsDeadline(`unlink ${tmpPath}`, () => unlink(tmpPath), undefined, timeoutMs);\n return result;\n }\n\n result.changed = true;\n log?.info(\"scrub-transcript: repaired poisoned transcript\", {\n filePath,\n corrected: result.corrected,\n stubbed: result.stubbed,\n cacheStripped: result.cacheStripped,\n });\n return result;\n}\n","/**\n * Pre-first-turn resume probe for the Claude Agent SDK driver.\n *\n * A tier-1 native resume only hands its session id to the SDK inside the first\n * real turn, so the `jsonl_lost` outcome (\"No conversation found\") is invisible\n * until a turn is consumed. The runner shares the container filesystem with the\n * SDK, so a cheap `stat` of the on-disk JSONL transcript is an authoritative,\n * side-effect-free signal of whether the resume will find its history — no\n * probe query, no spurious model turn.\n *\n * @module\n */\n\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { withFsDeadline } from \"@skaile/workspaces/core\";\nimport { locateTranscriptPath } from \"./scrub-transcript.js\";\n\n/**\n * Overall wall-clock budget for the probe. Deliberately a small fraction of the\n * platform's `session_init_ack` timeout (`DEFAULT_INIT_ACK_TIMEOUT_MS`, 15s):\n * the probe runs synchronously on the pre-ack path, so a wedged\n * `CLAUDE_CONFIG_DIR` mount must never push the ack past its deadline.\n */\nconst RESUME_PROBE_TIMEOUT_MS = 2_000;\n\n/**\n * Outcome of {@link probeResumeTranscript}: whether the SDK transcript for a\n * requested tier-1 resume exists on disk.\n *\n * @category Resume probe\n */\nexport type ResumeProbeOutcome = \"transcript_found\" | \"jsonl_lost\";\n\n/**\n * Resolve the Claude Code config directory — the parent of `projects/` — from\n * an explicit env map, the process environment, or the `~/.claude` default.\n *\n * The runner's probe and the claude-sdk driver share this one resolver, so they\n * agree as long as they see the same `CLAUDE_CONFIG_DIR`. Today they do:\n * `CLAUDE_CONFIG_DIR` is container-scoped and neither side threads a per-session\n * override through `config.env`, so both fall through to `process.env`. If a\n * future change ever set the driver's `config.env.CLAUDE_CONFIG_DIR` to a\n * divergent path, the reactive `resume_failed { jsonl_lost }` turn remains the\n * safety net.\n *\n * @category Resume probe\n */\nexport function resolveClaudeConfigDir(env?: Record<string, string | undefined>): string {\n return env?.CLAUDE_CONFIG_DIR || process.env.CLAUDE_CONFIG_DIR || join(homedir(), \".claude\");\n}\n\n/**\n * Probe whether the SDK JSONL transcript for `sessionId` exists on disk.\n *\n * Non-null locator result → `transcript_found`; null → `jsonl_lost`;\n * `undefined` → outcome unknown (the probe exceeded its budget or errored). The\n * caller leaves the ack field ABSENT on `undefined` so the reactive\n * `resume_failed { jsonl_lost }` turn stays the safety net — a timed-out probe\n * must never masquerade as a genuine `jsonl_lost` and force a needless downgrade.\n *\n * `opts.timeoutMs` overrides {@link RESUME_PROBE_TIMEOUT_MS}; `opts.locate`\n * overrides the transcript locator (used by tests / alternate stores).\n *\n * @category Resume probe\n */\nexport async function probeResumeTranscript(\n sessionId: string,\n opts?: {\n env?: Record<string, string | undefined>;\n timeoutMs?: number;\n locate?: (configDir: string, sessionId: string) => Promise<string | null>;\n },\n): Promise<ResumeProbeOutcome | undefined> {\n const configDir = resolveClaudeConfigDir(opts?.env);\n const timeoutMs = opts?.timeoutMs ?? RESUME_PROBE_TIMEOUT_MS;\n const locate = opts?.locate ?? locateTranscriptPath;\n try {\n // Bound the whole probe on wall-clock and THROW on expiry: the inner per-op\n // deadline swallows a timeout into a null path (a false `jsonl_lost`), so a\n // wedged mount must yield \"unknown\" here rather than a spurious downgrade.\n const filePath = await withFsDeadline(\n `resume-probe ${sessionId}`,\n () => locate(configDir, sessionId),\n timeoutMs,\n );\n return filePath ? \"transcript_found\" : \"jsonl_lost\";\n } catch {\n return undefined;\n }\n}\n"]}
1
+ {"version":3,"sources":["../bridge/src/cloud.ts","../bridge/src/drivers/scrub-transcript.ts","../bridge/src/drivers/resume-probe.ts"],"names":["join"],"mappings":";;;;;;;;AAsBO,IAAM,mBAAmB,CAAC,SAAA,EAAW,SAAA,EAAW,QAAA,EAAU,SAAS,SAAS;AAuC5E,IAAM,qBAAA,GAAgF;AAAA,EAC3F,OAAA,EAAS;AAAA,IACP,mBAAA;AAAA,IACA,uBAAA;AAAA,IACA,mBAAA;AAAA,IACA;AAAA,GACF;AAAA,EACA,MAAA,EAAQ,CAAC,qCAAqC,CAAA;AAAA,EAC9C,KAAA,EAAO,CAAC,2BAA2B,CAAA;AAAA,EACnC,OAAA,EAAS,CAAC,sBAAA,EAAwB,mBAAmB;AACvD;AAaA,IAAM,iBAAA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qB,YAAA;AAAA,EACzC,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,MAAA;AAAA,EACT;AACF","file":"chunk-3NCGSSCU.js","sourcesContent":["/**\n * AI cloud-provider transport dimension for the `claude-sdk` driver.\n *\n * `cloud` is a config axis orthogonal to `provider` (model vendor) and\n * `driver` (agent runtime). Under `driver: claude-sdk` each non-default value\n * maps to one of the Claude Agent SDK's native env-var transports:\n * Amazon Bedrock, Google Vertex AI, Azure AI Foundry, or a generic\n * `ANTHROPIC_BASE_URL` gateway (LiteLLM / corporate proxy).\n *\n * Cross-repo contract: env key names and semantics here are load-bearing —\n * the platform resolves credential bundles against the same key set.\n */\n\n/**\n * Canonical list of supported cloud transports. `\"default\"` (or an absent\n * `cloud` field) means the provider's native API — today's behavior, unchanged.\n *\n * The codec in `core/workspace-config.ts` keeps a local copy (`KNOWN_CLOUDS`)\n * to avoid an import cycle; a drift test asserts parity.\n *\n * @since 1.3.0\n */\nexport const SUPPORTED_CLOUDS = [\"default\", \"bedrock\", \"vertex\", \"azure\", \"gateway\"] as const;\n\n/** One of the supported cloud transport identifiers. */\nexport type CloudId = (typeof SUPPORTED_CLOUDS)[number];\n\n/**\n * Non-secret transport settings for a cloud. Sourced from skaile.yaml\n * `cloud_config` (snake_case on the wire, camelCase in-process — converted\n * exactly once at the settings/serve boundary).\n *\n * Must stay field-identical with core's `CloudTransportConfig` and the inline\n * `AgentSessionConfig.cloudConfig` shape (kept separate to avoid a core↔bridge\n * import cycle) — a field added here must be added there too.\n *\n * @since 1.3.0\n */\nexport interface CloudConfig {\n /** bedrock: AWS region (`AWS_REGION`); vertex: `CLOUD_ML_REGION`. */\n region?: string;\n /** vertex only: GCP project (`ANTHROPIC_VERTEX_PROJECT_ID`). */\n projectId?: string;\n /** azure only: Foundry resource name (`ANTHROPIC_FOUNDRY_RESOURCE`). */\n resource?: string;\n /** azure (alternative to `resource`) / gateway (required): endpoint base URL. */\n baseUrl?: string;\n}\n\n/**\n * Secret env keys that make up the credential bundle for each non-default\n * cloud. The platform delivers these env-keyed in the `session_init` secrets\n * map; the runner picks them out via `resolveCloudSecretBundle`.\n *\n * Vertex note: `GOOGLE_APPLICATION_CREDENTIALS_JSON` is our convention for the\n * raw service-account JSON blob. The runner materializes it to a 0600 file and\n * hands the driver `GOOGLE_APPLICATION_CREDENTIALS` (a path) instead — the\n * driver never sees the raw JSON.\n *\n * @since 1.3.0\n */\nexport const CLOUD_SECRET_ENV_KEYS: Record<Exclude<CloudId, \"default\">, readonly string[]> = {\n bedrock: [\n \"AWS_ACCESS_KEY_ID\",\n \"AWS_SECRET_ACCESS_KEY\",\n \"AWS_SESSION_TOKEN\",\n \"AWS_BEARER_TOKEN_BEDROCK\",\n ],\n vertex: [\"GOOGLE_APPLICATION_CREDENTIALS_JSON\"],\n azure: [\"ANTHROPIC_FOUNDRY_API_KEY\"],\n gateway: [\"ANTHROPIC_AUTH_TOKEN\", \"ANTHROPIC_API_KEY\"],\n};\n\n/**\n * Env vars scrubbed from the inherited environment before a non-default cloud\n * transport is assembled. Ambient first-party credentials or a stale\n * `CLAUDE_CODE_USE_*` flag must never leak into a Bedrock/Vertex/Foundry/\n * gateway session (the gateway branch re-adds its own carriers explicitly).\n *\n * Deliberately NOT exhaustive across clouds: ambient cloud-specific vars\n * (AWS_*, GOOGLE_*, ANTHROPIC_VERTEX_PROJECT_ID, ANTHROPIC_FOUNDRY_*) survive\n * so a standalone CLI inherits its own cloud's environment; the SDK ignores\n * vars whose transport flag is unset.\n */\nconst SCRUBBED_ENV_KEYS = [\"ANTHROPIC_API_KEY\", \"ANTHROPIC_AUTH_TOKEN\", \"ANTHROPIC_BASE_URL\"];\n\n/**\n * Assemble the Claude Agent SDK child env for a non-default cloud transport.\n *\n * Pure function (no external state touched; the returned `env` is a fresh\n * object — inputs are never mutated): starts from `baseEnv` (caller passes a\n * copy of `process.env` with undefined stripped) merged with `configEnv`,\n * scrubs inherited Anthropic\n * credential/routing vars and every `CLAUDE_CODE_USE_*` flag, then sets exactly\n * one `CLAUDE_CODE_USE_*` flag (none for gateway) plus the cloud's credential\n * bundle and derived non-secret vars. AWS_* / GOOGLE_* ambient values are NOT\n * scrubbed, so a standalone CLI inherits ambient cloud credentials when no\n * explicit `cloudSecrets` bundle is provided. Gateway is the mirror case: its\n * carriers ARE the scrubbed Anthropic vars, so the gateway branch restores\n * them from `cloudSecrets` → `fallbackApiKey` (resolved `apiKeys.anthropic`)\n * → the pre-scrub config/ambient value — otherwise a standalone gateway\n * session would have no reachable auth carrier at all.\n *\n * Never returns `undefined` values; absent settings are simply omitted.\n *\n * @since 1.3.0\n */\nexport function buildClaudeCloudEnv(args: {\n cloud: Exclude<CloudId, \"default\">;\n cloudConfig?: CloudConfig;\n cloudSecrets?: Record<string, string>;\n baseEnv: Record<string, string>;\n configEnv?: Record<string, string>;\n /** Resolved API key (e.g. `apiKeys.anthropic`) — gateway auth fallback only. */\n fallbackApiKey?: string;\n}): Record<string, string> {\n const { cloud, cloudConfig, cloudSecrets, baseEnv, configEnv, fallbackApiKey } = args;\n const env: Record<string, string> = { ...baseEnv, ...(configEnv ?? {}) };\n\n // Captured before the scrub — gateway falls back to these carriers.\n const ambient = {\n authToken: env.ANTHROPIC_AUTH_TOKEN,\n apiKey: env.ANTHROPIC_API_KEY,\n baseUrl: env.ANTHROPIC_BASE_URL,\n };\n\n for (const key of Object.keys(env)) {\n if (SCRUBBED_ENV_KEYS.includes(key) || key.startsWith(\"CLAUDE_CODE_USE_\")) {\n delete env[key];\n }\n }\n\n const set = (key: string, value: string | undefined) => {\n // Falsy check is deliberate: an empty-string credential/setting is never\n // valid env — dropping it beats shipping a key the SDK treats as set.\n if (value) env[key] = value;\n };\n\n switch (cloud) {\n case \"bedrock\": {\n env.CLAUDE_CODE_USE_BEDROCK = \"1\";\n // Explicit bundle values override ambient AWS_* (which survive the scrub\n // so a standalone CLI keeps its ambient credentials).\n for (const key of CLOUD_SECRET_ENV_KEYS.bedrock) set(key, cloudSecrets?.[key]);\n set(\"AWS_REGION\", cloudConfig?.region);\n break;\n }\n case \"vertex\": {\n env.CLAUDE_CODE_USE_VERTEX = \"1\";\n // Runner-materialized SA file path; ambient GOOGLE_APPLICATION_CREDENTIALS\n // is kept when no bundle value is provided.\n set(\"GOOGLE_APPLICATION_CREDENTIALS\", cloudSecrets?.GOOGLE_APPLICATION_CREDENTIALS);\n set(\"ANTHROPIC_VERTEX_PROJECT_ID\", cloudConfig?.projectId);\n set(\"CLOUD_ML_REGION\", cloudConfig?.region);\n break;\n }\n case \"azure\": {\n env.CLAUDE_CODE_USE_FOUNDRY = \"1\";\n set(\"ANTHROPIC_FOUNDRY_API_KEY\", cloudSecrets?.ANTHROPIC_FOUNDRY_API_KEY);\n // Resource wins over base_url when both are configured.\n if (cloudConfig?.resource) {\n env.ANTHROPIC_FOUNDRY_RESOURCE = cloudConfig.resource;\n } else {\n set(\"ANTHROPIC_FOUNDRY_BASE_URL\", cloudConfig?.baseUrl);\n }\n break;\n }\n case \"gateway\": {\n // No CLAUDE_CODE_USE_* flag — the gateway is addressed purely via\n // ANTHROPIC_BASE_URL plus an auth carrier. Explicit bundle wins;\n // standalone sessions fall back to the resolved key / ambient carriers.\n set(\"ANTHROPIC_BASE_URL\", cloudConfig?.baseUrl ?? ambient.baseUrl);\n const authToken = cloudSecrets?.ANTHROPIC_AUTH_TOKEN ?? ambient.authToken;\n if (authToken) {\n env.ANTHROPIC_AUTH_TOKEN = authToken;\n } else {\n set(\n \"ANTHROPIC_API_KEY\",\n cloudSecrets?.ANTHROPIC_API_KEY ?? fallbackApiKey ?? ambient.apiKey,\n );\n }\n break;\n }\n }\n\n return env;\n}\n","/**\n * Poisoned-transcript repair for the Claude Agent SDK driver.\n *\n * The Anthropic Messages API can permanently reject a conversation once its\n * persisted history contains a malformed content block. Because the bad block\n * lives in the SDK's on-disk JSONL transcript, every replayed turn fails with\n * the same `400 invalid_request_error` and the session is bricked with no\n * in-band recovery.\n *\n * This module repairs the transcript in place, covering three known poison\n * classes:\n *\n * 1. **Image `media_type` mismatch / omission.** An image block whose declared\n * `media_type` does not match — or is missing for — the actual bytes:\n * `... The image was specified using the image/png media type, but the\n * image appears to be a image/jpeg image`. Produced by the Claude Code\n * `Read` tool's format fallback (anthropics/claude-code#55338, #30124,\n * #33179). Repaired by sniffing the base64 magic bytes and correcting\n * `media_type`.\n * 2. **Oversized image.** An image whose decoded payload exceeds the API's\n * 5 MB per-image limit (anthropics/claude-code#34566). Replaced with a\n * text stub — the byte budget cannot be recovered any other way.\n * 3. **`cache_control` on an empty text block.** A text block carrying a\n * `cache_control` marker with empty/whitespace `text`\n * (anthropics/claude-code#59626). The `cache_control` field is stripped.\n *\n * Genuinely unidentifiable image blocks are also replaced with a text stub.\n *\n * Recovering by content scan (rather than parsing the API's `messages.N`\n * index) is deliberate: the index addresses the assembled API request, not a\n * JSONL line, and reproducing the SDK's message-assembly is fragile. A full\n * scan is index-free and repairs every poisoned block in one pass.\n *\n * **Async and line-streaming since #454.** A Claude Code transcript is routinely\n * multi-megabyte (base64 images inline in `tool_result` blocks), and this runs on\n * a failed turn *and before every resume* — inside the single-threaded `skaile\n * serve` loop. The previous `readFileSync` + `writeFileSync` + `renameSync` held\n * the loop for the whole file and materialised it twice over as one string. Both\n * passes now stream line by line off a `createReadStream`, so the loop is yielded\n * between lines and peak memory is one JSONL line rather than the whole file, and\n * every I/O phase is deadline-bounded.\n *\n * Streaming was chosen over a worker thread: the work is I/O-bound rather than\n * CPU-bound (per-line `JSON.parse` on a yielded loop is not what stalls a turn),\n * and a worker would add a structured-clone of the same multi-MB payload plus a\n * thread lifecycle to a path that must never block a turn.\n *\n * @module\n */\n\nimport { createReadStream, createWriteStream } from \"node:fs\";\nimport { readdir, rename, stat, unlink } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { pipeline } from \"node:stream/promises\";\nimport { fsDeadlineMs, tryWithFsDeadline, withFsDeadline } from \"@skaile/workspaces/core\";\n\n/**\n * Minimal logger shape accepted by {@link scrubPoisonedTranscript}. Compatible\n * with the bridge `Logger`, but narrowed so the helper stays unit-testable\n * without a real logger instance.\n *\n * @category Transcript repair\n */\nexport interface ScrubLogger {\n info(message: string, data?: Record<string, unknown>): void;\n warn(message: string, data?: Record<string, unknown>): void;\n}\n\n/**\n * Options for {@link scrubPoisonedTranscript}.\n *\n * @category Transcript repair\n */\nexport interface ScrubTranscriptOptions {\n /**\n * Claude Code config directory — the parent of `projects/`. Resolve from\n * `CLAUDE_CONFIG_DIR`, falling back to `~/.claude`.\n */\n configDir: string;\n /** SDK session id whose transcript JSONL should be repaired. */\n sessionId: string;\n /** Optional logger for diagnostics. */\n log?: ScrubLogger;\n}\n\n/**\n * Outcome of a {@link scrubPoisonedTranscript} pass.\n *\n * @category Transcript repair\n */\nexport interface ScrubTranscriptResult {\n /** The located JSONL transcript path, or `null` when not found. */\n filePath: string | null;\n /** Image blocks whose `media_type` was corrected (or filled in) to match the bytes. */\n corrected: number;\n /**\n * Image blocks replaced with a text stub — either unidentifiable bytes or a\n * payload over the API's 5 MB per-image limit.\n */\n stubbed: number;\n /** Empty text blocks from which a rejected `cache_control` marker was stripped. */\n cacheStripped: number;\n /**\n * `true` when the transcript was located, contained at least one poisoned\n * block, and was rewritten. `false` means nothing needed repair (or the\n * file was not found) — the caller should not retry the resume.\n */\n changed: boolean;\n}\n\n/** Text inserted in place of an image block whose format cannot be identified. */\nconst STUB_TEXT = \"[image removed: unprocessable image data]\";\n\n/** Text inserted in place of an image block that exceeds the API size limit. */\nconst STUB_TEXT_OVERSIZED = \"[image removed: image too large]\";\n\n/**\n * The Anthropic Messages API rejects any single image whose decoded payload\n * exceeds 5 MB. An image at or under this is left alone; a larger one is\n * stubbed (its byte budget cannot be recovered).\n */\nconst MAX_IMAGE_BYTES = 5 * 1024 * 1024;\n\n/**\n * Identify an image's media type from the leading bytes of its base64 payload.\n *\n * Recognises the four formats the Anthropic API accepts. Returns `null` when\n * the magic bytes match no known format — the caller treats that as a\n * genuinely corrupt block and stubs it.\n *\n * @param base64 - Base64-encoded image data (only the prefix is inspected).\n * @returns An `image/*` media type, or `null` when unrecognised.\n * @category Transcript repair\n */\nexport function sniffImageMediaType(base64: string): string | null {\n let buf: Buffer;\n try {\n // 32 base64 chars decode to 24 bytes — enough for the WebP check at 12.\n buf = Buffer.from(base64.slice(0, 32), \"base64\");\n } catch {\n return null;\n }\n if (buf.length < 4) {\n return null;\n }\n // JPEG — SOI marker `FF D8`. Third byte varies (and may be corrupt), so a\n // two-byte check is intentional: it still matches malformed JPEGs, which is\n // exactly the poison case the API flags as \"appears to be image/jpeg\".\n if (buf[0] === 0xff && buf[1] === 0xd8) {\n return \"image/jpeg\";\n }\n // PNG — `89 50 4E 47`.\n if (buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47) {\n return \"image/png\";\n }\n // GIF — `47 49 46 38` (\"GIF8\").\n if (buf[0] === 0x47 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x38) {\n return \"image/gif\";\n }\n // WebP — `RIFF` at 0..3 and `WEBP` at 8..11.\n if (\n buf.length >= 12 &&\n buf[0] === 0x52 &&\n buf[1] === 0x49 &&\n buf[2] === 0x46 &&\n buf[3] === 0x46 &&\n buf[8] === 0x57 &&\n buf[9] === 0x45 &&\n buf[10] === 0x42 &&\n buf[11] === 0x50\n ) {\n return \"image/webp\";\n }\n return null;\n}\n\n/** A base64 image source on a content block (shape is SDK-defined). */\ninterface Base64ImageSource {\n type?: string;\n media_type?: string;\n data?: string;\n}\n\n/** Loosely-typed content block from a transcript message. */\ninterface ContentBlockLike {\n type?: string;\n source?: Base64ImageSource;\n content?: unknown;\n [k: string]: unknown;\n}\n\n/** Mutable counters threaded through one scrub pass. */\ninterface ScrubCounters {\n corrected: number;\n stubbed: number;\n cacheStripped: number;\n}\n\n/** Total repairs recorded in a counter set — used to detect per-line changes. */\nfunction totalChanges(c: ScrubCounters): number {\n return c.corrected + c.stubbed + c.cacheStripped;\n}\n\n/**\n * Repair a single content block. Returns the (possibly replaced) block.\n *\n * - A `tool_result` block recurses into its `content` array.\n * - A text block carrying a `cache_control` marker whose `text` is empty or\n * whitespace has the marker stripped (the API rejects `cache_control` on\n * empty text blocks).\n * - An image block whose decoded payload exceeds the API's 5 MB limit is\n * replaced with a text stub.\n * - An image block whose bytes match no known format is replaced with a text\n * stub (an image cannot simply be dropped — a `tool_result` must keep at\n * least one content entry, and a bare `image` block is replaced 1:1).\n * - An image block whose declared `media_type` mismatches (or is missing for)\n * the sniffed type is corrected in place.\n * - Every other block is returned untouched.\n */\nfunction scrubBlock(block: ContentBlockLike, counters: ScrubCounters): ContentBlockLike {\n if (block.type === \"tool_result\" && Array.isArray(block.content)) {\n return {\n ...block,\n content: (block.content as ContentBlockLike[]).map((inner) => scrubBlock(inner, counters)),\n };\n }\n\n // A `cache_control` marker on a text block whose text is empty or whitespace\n // is rejected by the API (\"cache_control cannot be set for empty text\n // blocks\"). Strip the marker — the empty block itself is harmless.\n if (block.type === \"text\" && block.cache_control != null) {\n const text = typeof block.text === \"string\" ? block.text : \"\";\n if (text.trim() === \"\") {\n counters.cacheStripped++;\n const clone = { ...block };\n delete clone.cache_control;\n return clone;\n }\n }\n\n if (\n block.type === \"image\" &&\n block.source?.type === \"base64\" &&\n typeof block.source.data === \"string\"\n ) {\n const data = block.source.data;\n // The API rejects any image whose decoded payload exceeds 5 MB. The byte\n // budget cannot be salvaged, so the whole block becomes a text stub.\n // base64 encodes 3 bytes per 4 chars, so decoded length ≈ len * 3 / 4.\n if (Math.floor((data.length * 3) / 4) > MAX_IMAGE_BYTES) {\n counters.stubbed++;\n return { type: \"text\", text: STUB_TEXT_OVERSIZED };\n }\n const sniffed = sniffImageMediaType(data);\n if (sniffed === null) {\n counters.stubbed++;\n return { type: \"text\", text: STUB_TEXT };\n }\n if (sniffed !== block.source.media_type) {\n counters.corrected++;\n return { ...block, source: { ...block.source, media_type: sniffed } };\n }\n }\n\n return block;\n}\n\n/**\n * Locate the JSONL transcript for `sessionId` under `<configDir>/projects/`.\n *\n * Claude Code encodes the project directory into the `projects/` subfolder\n * name; rather than reproduce that encoding, this scans every subfolder for\n * `<sessionId>.jsonl` (the session id is a UUID — globally unique).\n *\n * Async and deadline-bounded since #454. The `existsSync(projectsDir)` probe is\n * gone: `readdir` already fails on a missing directory, so the probe was a\n * second stat on the same path for no information.\n *\n * `timeoutMs` defaults to {@link fsDeadlineMs} so callers that only need the\n * path (the resume probe) can omit it.\n *\n * @category Transcript repair\n */\nexport async function locateTranscriptPath(\n configDir: string,\n sessionId: string,\n timeoutMs: number = fsDeadlineMs(),\n): Promise<string | null> {\n const projectsDir = join(configDir, \"projects\");\n const entries = await tryWithFsDeadline(\n `readdir ${projectsDir}`,\n () => readdir(projectsDir),\n null,\n timeoutMs,\n );\n if (!entries) return null;\n for (const entry of entries) {\n const candidate = join(projectsDir, entry, `${sessionId}.jsonl`);\n const found = await tryWithFsDeadline(\n `stat ${candidate}`,\n async () => (await stat(candidate)).isFile(),\n false,\n timeoutMs,\n );\n if (found) return candidate;\n }\n return null;\n}\n\n/**\n * Yield a file's contents line by line, reproducing `readFileSync(...).split(\"\\n\")`\n * exactly — including the final (possibly empty) segment, so a trailing newline\n * survives a rewrite byte for byte.\n *\n * Splits on `\\n` alone, so a line out of a CRLF transcript arrives with its\n * `\\r` still attached. That carrier byte is part of the line here, and\n * {@link repairLine} re-attaches it to a line it rewrites — the file keeps the\n * terminator style it arrived with. Deliberately not `node:readline`:\n * `crlfDelay` strips the `\\r` outright (rewriting a CRLF transcript to LF) and\n * the interface swallows the trailing-newline distinction, either of which\n * would make the \"clean transcript is left byte-for-byte untouched\" guarantee\n * false. Only one line is held in memory at a time, so a multi-MB transcript\n * never materialises as a single string.\n */\nasync function* streamLines(filePath: string): AsyncGenerator<string> {\n const stream = createReadStream(filePath, { encoding: \"utf8\" });\n let pending = \"\";\n try {\n for await (const chunk of stream) {\n pending += chunk as string;\n let idx = pending.indexOf(\"\\n\");\n while (idx !== -1) {\n yield pending.slice(0, idx);\n pending = pending.slice(idx + 1);\n idx = pending.indexOf(\"\\n\");\n }\n }\n yield pending;\n } finally {\n stream.destroy();\n }\n}\n\n/**\n * Repair one JSONL line, returning the (possibly rewritten) line and mutating\n * `counters`. A non-JSON, blank, or content-less line is returned untouched.\n *\n * The reader splits on `\\n` only, so a line from a CRLF transcript still carries\n * its trailing `\\r`. An untouched line is returned verbatim and keeps it; a\n * rewritten one is rebuilt by `JSON.stringify`, which would drop it — leaving a\n * repaired CRLF transcript with mixed line endings. So the terminator is split\n * off before the parse and re-appended to the rewritten line.\n */\nfunction repairLine(line: string, counters: ScrubCounters): string {\n if (line.trim() === \"\") return line;\n const eol = line.endsWith(\"\\r\") ? \"\\r\" : \"\";\n const body = eol === \"\" ? line : line.slice(0, -1);\n let entry: { message?: { content?: unknown } };\n try {\n entry = JSON.parse(body);\n } catch {\n return line; // Not JSON — leave untouched.\n }\n const content = entry.message?.content;\n if (!Array.isArray(content)) return line;\n const before = totalChanges(counters);\n const scrubbed = (content as ContentBlockLike[]).map((block) => scrubBlock(block, counters));\n if (totalChanges(counters) === before) return line; // Nothing changed on this line.\n return `${JSON.stringify({ ...entry, message: { ...entry.message, content: scrubbed } })}${eol}`;\n}\n\n/**\n * Scan a Claude Code SDK transcript for image content blocks whose declared\n * `media_type` does not match the actual bytes, repair them, and atomically\n * rewrite the file.\n *\n * Safe to call after a turn has failed: the SDK query is dead at that point,\n * and the next resume re-reads the transcript from disk.\n *\n * **Async since #454.** Two streaming passes rather than one whole-file read:\n * pass 1 counts repairs without writing anything, and pass 2 runs only when\n * pass 1 found something. The common case — the preventive scrub of a clean\n * transcript before every resume — is therefore one streaming read and zero\n * writes, and a clean transcript is still left byte-for-byte untouched.\n *\n * @param opts - Config directory, session id, and an optional logger.\n * @returns A {@link ScrubTranscriptResult}. When `changed` is `true` the\n * caller may retry the resume with the same session id.\n * @category Transcript repair\n */\nexport async function scrubPoisonedTranscript(\n opts: ScrubTranscriptOptions,\n): Promise<ScrubTranscriptResult> {\n const { configDir, sessionId, log } = opts;\n const timeoutMs = fsDeadlineMs();\n const result: ScrubTranscriptResult = {\n filePath: null,\n corrected: 0,\n stubbed: 0,\n cacheStripped: 0,\n changed: false,\n };\n\n const filePath = await locateTranscriptPath(configDir, sessionId, timeoutMs);\n if (!filePath) {\n log?.warn(\"scrub-transcript: no transcript found\", { configDir, sessionId });\n return result;\n }\n result.filePath = filePath;\n\n // ── Pass 1: detect. Streams the transcript, counting repairs, writing nothing.\n const counters: ScrubCounters = { corrected: 0, stubbed: 0, cacheStripped: 0 };\n try {\n await withFsDeadline(\n `scan transcript ${filePath}`,\n async () => {\n for await (const line of streamLines(filePath)) repairLine(line, counters);\n },\n timeoutMs,\n );\n } catch (err) {\n log?.warn(\"scrub-transcript: failed to read transcript\", {\n filePath,\n error: err instanceof Error ? err.message : String(err),\n });\n return result;\n }\n\n result.corrected = counters.corrected;\n result.stubbed = counters.stubbed;\n result.cacheStripped = counters.cacheStripped;\n\n if (totalChanges(counters) === 0) {\n return result;\n }\n\n // ── Pass 2: rewrite. Atomic: stream a sibling temp file, then rename over the\n // original. Line separators are re-emitted exactly as pass 1 split them, so a\n // trailing newline and any blank lines survive verbatim.\n const tmpPath = `${filePath}.scrub-tmp`;\n try {\n await withFsDeadline(\n `rewrite transcript ${filePath}`,\n async () => {\n const discard: ScrubCounters = { corrected: 0, stubbed: 0, cacheStripped: 0 };\n await pipeline(\n (async function* () {\n let first = true;\n for await (const line of streamLines(filePath)) {\n yield first ? repairLine(line, discard) : `\\n${repairLine(line, discard)}`;\n first = false;\n }\n })(),\n createWriteStream(tmpPath, { encoding: \"utf8\" }),\n );\n await rename(tmpPath, filePath);\n },\n timeoutMs,\n );\n } catch (err) {\n log?.warn(\"scrub-transcript: failed to rewrite transcript\", {\n filePath,\n error: err instanceof Error ? err.message : String(err),\n });\n // Never leave a half-written sibling behind — the next scrub would rewrite\n // it anyway, but a stray `.scrub-tmp` in the SDK's projects dir is noise.\n await tryWithFsDeadline(`unlink ${tmpPath}`, () => unlink(tmpPath), undefined, timeoutMs);\n return result;\n }\n\n result.changed = true;\n log?.info(\"scrub-transcript: repaired poisoned transcript\", {\n filePath,\n corrected: result.corrected,\n stubbed: result.stubbed,\n cacheStripped: result.cacheStripped,\n });\n return result;\n}\n","/**\n * Pre-first-turn resume probe for the Claude Agent SDK driver.\n *\n * A tier-1 native resume only hands its session id to the SDK inside the first\n * real turn, so the `jsonl_lost` outcome (\"No conversation found\") is invisible\n * until a turn is consumed. The runner shares the container filesystem with the\n * SDK, so a cheap `stat` of the on-disk JSONL transcript is an authoritative,\n * side-effect-free signal of whether the resume will find its history — no\n * probe query, no spurious model turn.\n *\n * @module\n */\n\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\nimport { withFsDeadline } from \"@skaile/workspaces/core\";\nimport { locateTranscriptPath } from \"./scrub-transcript.js\";\n\n/**\n * Overall wall-clock budget for the probe. Deliberately a small fraction of the\n * platform's `session_init_ack` timeout (`DEFAULT_INIT_ACK_TIMEOUT_MS`, 15s):\n * the probe runs synchronously on the pre-ack path, so a wedged\n * `CLAUDE_CONFIG_DIR` mount must never push the ack past its deadline.\n */\nconst RESUME_PROBE_TIMEOUT_MS = 2_000;\n\n/**\n * Outcome of {@link probeResumeTranscript}: whether the SDK transcript for a\n * requested tier-1 resume exists on disk.\n *\n * @category Resume probe\n */\nexport type ResumeProbeOutcome = \"transcript_found\" | \"jsonl_lost\";\n\n/**\n * Resolve the Claude Code config directory — the parent of `projects/` — from\n * an explicit env map, the process environment, or the `~/.claude` default.\n *\n * The runner's probe and the claude-sdk driver share this one resolver, so they\n * agree as long as they see the same `CLAUDE_CONFIG_DIR`. Today they do:\n * `CLAUDE_CONFIG_DIR` is container-scoped and neither side threads a per-session\n * override through `config.env`, so both fall through to `process.env`. If a\n * future change ever set the driver's `config.env.CLAUDE_CONFIG_DIR` to a\n * divergent path, the reactive `resume_failed { jsonl_lost }` turn remains the\n * safety net.\n *\n * @category Resume probe\n */\nexport function resolveClaudeConfigDir(env?: Record<string, string | undefined>): string {\n return env?.CLAUDE_CONFIG_DIR || process.env.CLAUDE_CONFIG_DIR || join(homedir(), \".claude\");\n}\n\n/**\n * Probe whether the SDK JSONL transcript for `sessionId` exists on disk.\n *\n * Non-null locator result → `transcript_found`; null → `jsonl_lost`;\n * `undefined` → outcome unknown (the probe exceeded its budget or errored). The\n * caller leaves the ack field ABSENT on `undefined` so the reactive\n * `resume_failed { jsonl_lost }` turn stays the safety net — a timed-out probe\n * must never masquerade as a genuine `jsonl_lost` and force a needless downgrade.\n *\n * `opts.timeoutMs` overrides {@link RESUME_PROBE_TIMEOUT_MS}; `opts.locate`\n * overrides the transcript locator (used by tests / alternate stores).\n *\n * @category Resume probe\n */\nexport async function probeResumeTranscript(\n sessionId: string,\n opts?: {\n env?: Record<string, string | undefined>;\n timeoutMs?: number;\n locate?: (configDir: string, sessionId: string) => Promise<string | null>;\n },\n): Promise<ResumeProbeOutcome | undefined> {\n const configDir = resolveClaudeConfigDir(opts?.env);\n const timeoutMs = opts?.timeoutMs ?? RESUME_PROBE_TIMEOUT_MS;\n const locate = opts?.locate ?? locateTranscriptPath;\n try {\n // Bound the whole probe on wall-clock and THROW on expiry: the inner per-op\n // deadline swallows a timeout into a null path (a false `jsonl_lost`), so a\n // wedged mount must yield \"unknown\" here rather than a spurious downgrade.\n const filePath = await withFsDeadline(\n `resume-probe ${sessionId}`,\n () => locate(configDir, sessionId),\n timeoutMs,\n );\n return filePath ? \"transcript_found\" : \"jsonl_lost\";\n } catch {\n return undefined;\n }\n}\n"]}
@@ -1,5 +1,5 @@
1
- import { withFsDeadline, tryWithFsDeadline, walkDir } from './chunk-VQ4P7UYE.js';
2
- import { createLogger } from './chunk-3A5IKBHQ.js';
1
+ import { withFsDeadline, tryWithFsDeadline, walkDir } from './chunk-MKZOK4JU.js';
2
+ import { createLogger } from './chunk-W4IPN3DD.js';
3
3
  import { parse } from 'yaml';
4
4
  import { readFile, stat } from 'fs/promises';
5
5
  import path from 'path';
@@ -329,5 +329,5 @@ function validateFlowVersions(nodes, skillVersions) {
329
329
  }
330
330
 
331
331
  export { buildRequiresPreamble, parseCompactionDirectives, parseSkillFrontmatter, parseSkillRequirements, validateConnectorRequirements, validateFlowVersions, validateRequirements };
332
- //# sourceMappingURL=chunk-4VTBZ2MF.js.map
333
- //# sourceMappingURL=chunk-4VTBZ2MF.js.map
332
+ //# sourceMappingURL=chunk-3XXQPHGL.js.map
333
+ //# sourceMappingURL=chunk-3XXQPHGL.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../resolver/src/parser.ts","../resolver/src/preamble.ts","../resolver/src/validator.ts","../resolver/src/version.ts"],"names":["parseYaml"],"mappings":";;;;;;;AAeO,SAAS,sBAAsB,OAAA,EAAsC;AAC1E,EAAA,MAAM,KAAA,GAAQ,OAAA,CAAQ,KAAA,CAAM,uBAAuB,CAAA;AACnD,EAAA,IAAI,CAAC,KAAA,EAAO,OAAO,EAAC;AACpB,EAAA,IAAI;AACF,IAAA,OAAOA,KAAA,CAAU,KAAA,CAAM,CAAC,CAAE,KAAK,EAAC;AAAA,EAClC,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,EAAC;AAAA,EACV;AACF;AAmBO,SAAS,uBAAuB,OAAA,EAAoC;AACzE,EAAA,MAAM,EAAA,GAAK,sBAAsB,OAAO,CAAA;AACxC,EAAA,MAAM,IAAA,GAAO,EAAA,CAAG,QAAA,IAAY,EAAC;AAC7B,EAAA,MAAM,aAAA,GAAgB,IAAA,CAAK,aAAA,IAAiB,EAAC;AAE7C,EAAA,MAAM,KAAA,GAA2B;AAAA,IAC/B,OAAO,EAAC;AAAA,IACR,iBAAiB,EAAC;AAAA,IAClB,iBAAiB,EAAC;AAAA,IAClB,OAAO,EAAC;AAAA,IACR,UAAU,EAAC;AAAA,IACX,WAAW,EAAC;AAAA,IACZ,YAAY;AAAC,GACf;AAGA,EAAA,IACE,aAAA,CAAc,KAAA,IACd,aAAA,CAAc,eAAA,IAC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U,QAAQ,OAAA,EAAS;AAAA,IAC1C,UAAA,EAAY,CAAC,IAAA,KAAS;AACpB,MAAA,UAAA,KAAe,IAAA;AAAA,IACjB;AAAA,GACD,CAAA,EAAG;AACF,IAAA,KAAA,EAAA;AAGA,IAAA,IAAI,KAAA,IAAS,KAAA,EAAO,OAAO,EAAE,KAAA,EAAM;AAAA,EACrC;AACA,EAAA,OAAO,EAAE,OAAO,UAAA,EAAW;AAC7B;AChPO,SAAS,oBAAA,CACd,OACA,aAAA,EACgB;AAChB,EAAA,MAAM,SAAyB,EAAC;AAEhC,EAAA,KAAA,MAAW,QAAQ,KAAA,EAAO;AACxB,IAAA,IAAI,CAAC,KAAK,gBAAA,EAAkB;AAE5B,IAAA,MAAM,MAAA,GAAS,aAAA,CAAc,GAAA,CAAI,IAAA,CAAK,OAAO,CAAA,IAAK,EAAA;AAClD,IAAA,MAAM,YAAY,IAAA,CAAK,gBAAA;AAGvB,IAAA,MAAM,UAAA,GAAa,UAAA,CAAW,SAAS,CAAA,KAAM,IAAA;AAC7C,IAAA,MAAM,WAAA,GAAc,MAAA,KAAW,EAAA,IAAM,KAAA,CAAM,MAAM,CAAA,KAAM,IAAA;AACvD,IAAA,MAAM,WAAA,GAAc,UAAA,IAAc,WAAA,IAAe,SAAA,CAAU,QAAQ,SAAS,CAAA;AAE5E,IAAA,MAAA,CAAO,IAAA,CAAK;AAAA,MACV,QAAQ,IAAA,CAAK,MAAA;AAAA,MACb,SAAS,IAAA,CAAK,OAAA;AAAA,MACd,SAAA;AAAA,MACA,MAAA;AAAA,MACA,SAAA,EAAW;AAAA,KACZ,CAAA;AAAA,EACH;AAEA,EAAA,OAAO,MAAA;AACT","file":"chunk-4VTBZ2MF.js","sourcesContent":["import { parse as parseYaml } from \"yaml\";\nimport type { ConnectorRequirement, InputField, SkillRequirements } from \"./types.js\";\n\n/**\n * Extract YAML frontmatter from a SKILL.md string.\n *\n * Frontmatter is delimited by leading `---` fences. Returns the parsed object,\n * or an empty object `{}` if no frontmatter block is found or if the YAML is malformed.\n * Errors are silently swallowed — callers should treat an empty result as \"no requirements\".\n *\n * @param content - Raw SKILL.md file content (full string, including `---` fences)\n * @returns Parsed frontmatter object, or `{}` on absence or parse failure\n *\n * @docLink packages/resolver/api-reference#parseskill-frontmatter\n */\nexport function parseSkillFrontmatter(content: string): Record<string, any> {\n const match = content.match(/^---\\n([\\s\\S]*?)\\n---/);\n if (!match) return {};\n try {\n return parseYaml(match[1]!) ?? {};\n } catch {\n return {};\n }\n}\n\n/**\n * Parse skill requirements from raw SKILL.md content into a `SkillRequirements` object.\n *\n * Supports two frontmatter formats:\n * 1. **New format** — `metadata.prerequisites` with explicit\n * `files`, `inputs_required`, `inputs_optional`, `reads`, `produces`, and `resources` arrays.\n * 2. **Legacy format** — `metadata.user_inputs.dialog[]` array, automatically promoted to\n * `inputs_required` / `inputs_optional` based on each entry's `required` flag.\n *\n * Returns empty requirements `{ files: [], inputs_required: [], inputs_optional: [], reads: [], produces: [], resources: [] }`\n * when no recognisable prerequisites section is found.\n *\n * @param content - Raw SKILL.md file content (full string, including `---` fences)\n * @returns Structured `SkillRequirements` (never throws)\n *\n * @docLink packages/resolver/api-reference#parseskill-requirements\n */\nexport function parseSkillRequirements(content: string): SkillRequirements {\n const fm = parseSkillFrontmatter(content);\n const meta = fm.metadata ?? {};\n const prerequisites = meta.prerequisites ?? {};\n\n const empty: SkillRequirements = {\n files: [],\n inputs_required: [],\n inputs_optional: [],\n reads: [],\n produces: [],\n resources: [],\n connectors: [],\n };\n\n // New format: metadata.prerequisites\n if (\n prerequisites.files ||\n prerequisites.inputs_required ||\n prerequisites.inputs_optional ||\n prerequisites.reads ||\n prerequisites.produces ||\n prerequisites.resources ||\n prerequisites.connectors\n ) {\n return {\n files: (prerequisites.files ?? []).map((f: any) => ({\n path: f.path,\n gate: f.gate ?? \"hard\",\n description: f.description ?? \"\",\n ...(f.min_entries != null ? { min_entries: f.min_entries } : {}),\n })),\n inputs_required: (prerequisites.inputs_required ?? []).map(normalizeInputField(true)),\n inputs_optional: (prerequisites.inputs_optional ?? []).map(normalizeInputField(false)),\n reads: (prerequisites.reads ?? []).map((r: any) => ({\n path: r.path,\n description: r.description ?? \"\",\n })),\n produces: (prerequisites.produces ?? []).map((p: any) => ({\n path: p.path,\n description: p.description ?? \"\",\n })),\n resources: (prerequisites.resources ?? []).map((r: any) => ({\n id: r.id,\n ...(r.operations ? { operations: r.operations } : {}),\n optional: r.optional ?? false,\n ...(r.description ? { description: r.description } : {}),\n })),\n connectors: parseConnectorRequirements(prerequisites.connectors),\n };\n }\n\n // Legacy format: metadata.user_inputs.dialog[]\n const dialog = meta.user_inputs?.dialog;\n if (Array.isArray(dialog)) {\n const required: InputField[] = [];\n const optional: InputField[] = [];\n for (const d of dialog) {\n const field = normalizeInputField(d.required ?? false)(d);\n if (d.required) required.push(field);\n else optional.push(field);\n }\n return { ...empty, inputs_required: required, inputs_optional: optional, resources: [] };\n }\n\n return empty;\n}\n\n/**\n * Extract compaction directives from a SKILL.md markdown body.\n *\n * Scans the markdown body (not frontmatter) for a `## Compaction Directives` section\n * and returns each bullet point as a trimmed string. Compaction directives are hints\n * the agent uses to summarise context when the conversation history grows long.\n * Returns an empty array when the section is absent.\n *\n * @param content - Raw SKILL.md file content (full string including frontmatter and body)\n * @returns Array of directive strings extracted from the bullet list, or `[]` if none found\n *\n * @docLink packages/resolver/api-reference#parse-compaction-directives\n */\nexport function parseCompactionDirectives(content: string): string[] {\n const headerIdx = content.search(/^## Compaction Directives/m);\n if (headerIdx === -1) return [];\n\n // Header on the last line (no trailing newline) → no body to scan.\n const newlineIdx = content.indexOf(\"\\n\", headerIdx);\n if (newlineIdx === -1) return [];\n const bodyStart = newlineIdx + 1;\n const rest = content.slice(bodyStart);\n const nextSection = rest.search(/^##\\s/m);\n const sectionBody = nextSection === -1 ? rest : rest.slice(0, nextSection);\n\n const bullets: string[] = [];\n for (const line of sectionBody.split(\"\\n\")) {\n const match = line.match(/^\\s*[-*]\\s+(.+)/);\n if (match) bullets.push(match[1].trim());\n }\n return bullets;\n}\n\nfunction normalizeInputField(defaultRequired: boolean) {\n return (d: any): InputField => ({\n // UserInputSchema permits `key` or `id`; `prompt` is the legacy label alias.\n id: d.id ?? d.key,\n label: d.label ?? d.prompt ?? d.id ?? d.key,\n type: d.type ?? \"text\",\n required: d.required ?? defaultRequired,\n ...(d.options ? { options: d.options } : {}),\n ...(d.default != null ? { default: d.default } : {}),\n ...(d.hint ? { hint: d.hint } : {}),\n ...(d.schema ? { schema: d.schema } : {}),\n });\n}\n\nfunction parseConnectorRequirements(raw: unknown): ConnectorRequirement[] {\n if (!Array.isArray(raw)) return [];\n return raw\n .filter((c): c is Record<string, unknown> => typeof c === \"object\" && c !== null)\n .map((c) => ({\n driver: String(c.driver ?? \"\"),\n ...(c.access === \"read-write\"\n ? { access: \"read-write\" as const }\n : { access: \"read-only\" as const }),\n }))\n .filter((c) => c.driver.length > 0);\n}\n","import type { SkillRequirements } from \"./types.js\";\n\n/**\n * Generate a DSL-format preamble from skill requirements.\n *\n * The preamble is prepended to the skill prompt when the skill runs standalone\n * (without an orchestrator), giving the agent an explicit checklist of what to\n * verify before starting work. Each section maps to a requirement category:\n *\n * - `REQUIRES` — file/directory gates (`hard:` or `soft:` prefix)\n * - `INPUT` — user input fields, with a pointer to `input.json` if `skillId` is provided\n * - `READS` — informational read sources (not gated)\n * - `WRITES` — files the skill will produce\n * - `RESOURCE` — runtime resource dependencies\n *\n * Sections with no entries are omitted. Returns an empty string when all\n * requirement arrays are empty.\n *\n * @param requirements - Parsed requirements (output of `parseSkillRequirements`)\n * @param skillId - Optional skill identifier; when provided, the INPUT section includes\n * the canonical `input.json` path so the agent knows where to read collected values\n * @returns Multi-section DSL string, or `\"\"` if there are no requirements to list\n *\n * @example\n * ```ts\n * const preamble = buildRequiresPreamble(requirements, \"cf_overview\");\n * const fullPrompt = preamble ? `${preamble}\\n\\n${skillBody}` : skillBody;\n * ```\n *\n * @docLink packages/resolver/api-reference#build-requires-preamble\n */\nexport function buildRequiresPreamble(requirements: SkillRequirements, skillId?: string): string {\n const sections: string[] = [];\n\n pushSection(sections, buildRequiresSection(requirements));\n pushSection(sections, buildInputSection(requirements, skillId));\n pushSection(sections, buildReadsSection(requirements));\n pushSection(sections, buildWritesSection(requirements));\n pushSection(sections, buildResourceSection(requirements));\n\n return sections.join(\"\\n\\n\");\n}\n\n/** Append a section to the list when it produced output. */\nfunction pushSection(sections: string[], section: string | null): void {\n if (section !== null) sections.push(section);\n}\n\n/** REQUIRES section (file gates). Returns `null` when there are no file gates. */\nfunction buildRequiresSection(requirements: SkillRequirements): string | null {\n if (requirements.files.length === 0) return null;\n const lines = [\"REQUIRES\"];\n for (const f of requirements.files) {\n const prefix = f.gate === \"hard\" ? \"hard\" : \"soft\";\n lines.push(` ${prefix}: ${f.path} — ${f.description}`);\n }\n return lines.join(\"\\n\");\n}\n\n/** INPUT section (user inputs). Returns `null` when there are no inputs. */\nfunction buildInputSection(requirements: SkillRequirements, skillId?: string): string | null {\n const allInputs = [...requirements.inputs_required, ...requirements.inputs_optional];\n if (allInputs.length === 0) return null;\n const lines = [\"INPUT\"];\n if (skillId) {\n lines.push(` Read from: _concept/_grounding/${skillId}/input.json`);\n lines.push(\n ` If input.json is missing, ask the user for the following values and write the file:`,\n );\n }\n for (const input of allInputs) {\n const req = input.required ? \"(required)\" : \"(optional)\";\n const opts = input.options ? ` [${input.options.join(\" | \")}]` : \"\";\n const def = input.default != null ? ` default: ${input.default}` : \"\";\n lines.push(` - ${input.id}: ${input.label} ${req}${opts}${def}`);\n if (input.hint) lines.push(` hint: ${input.hint}`);\n }\n return lines.join(\"\\n\");\n}\n\n/** READS section. Returns `null` when there are no read sources. */\nfunction buildReadsSection(requirements: SkillRequirements): string | null {\n if (requirements.reads.length === 0) return null;\n const lines = [\"READS\"];\n for (const r of requirements.reads) {\n lines.push(` ? ${r.path} — ${r.description}`);\n }\n return lines.join(\"\\n\");\n}\n\n/** WRITES section (produces). Returns `null` when there is nothing produced. */\nfunction buildWritesSection(requirements: SkillRequirements): string | null {\n if (requirements.produces.length === 0) return null;\n const lines = [\"WRITES\"];\n for (const p of requirements.produces) {\n lines.push(` ${p.path} — ${p.description}`);\n }\n return lines.join(\"\\n\");\n}\n\n/** RESOURCE section. Returns `null` when there are no resources. */\nfunction buildResourceSection(requirements: SkillRequirements): string | null {\n if (!requirements.resources || requirements.resources.length === 0) return null;\n const lines = [\"RESOURCE\"];\n for (const r of requirements.resources) {\n const req = r.optional ? \"(optional)\" : \"(required)\";\n const ops = r.operations ? ` ops: [${r.operations.join(\", \")}]` : \"\";\n lines.push(` ${r.id} ${req}${ops}`);\n if (r.description) lines.push(` — ${r.description}`);\n }\n return lines.join(\"\\n\");\n}\n","import { readFile, stat } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport {\n tryWithFsDeadline,\n walkDir,\n type WalkTruncation,\n withFsDeadline,\n} from \"@skaile/workspaces/core\";\nimport { createLogger } from \"@skaile/workspaces/core/logging\";\nimport type {\n ConnectorRequirement,\n FileCheck,\n InputCheck,\n NodeOverrides,\n ReadCheck,\n RequirementsReport,\n ResourceCheck,\n SkillInputFile,\n SkillRequirements,\n} from \"./types.js\";\n\nlet validatorLogger: ReturnType<typeof createLogger> | undefined;\n\nfunction log(): ReturnType<typeof createLogger> {\n validatorLogger ??= createLogger({ kind: \"runner\", subkind: \"skill-requirements\" });\n return validatorLogger;\n}\n\n/** Best-effort existence probe. A missing path, an unreadable one, and an\n * unresponsive mount are all \"not usable here\" for a requirement check. */\nasync function pathExists(target: string): Promise<boolean> {\n return tryWithFsDeadline(\n `stat ${target}`,\n async () => {\n await stat(target);\n return true;\n },\n false,\n );\n}\n\n/**\n * Validate skill requirements against the filesystem and collected inputs.\n *\n * File checks resolve paths relative to `projectDir`. Hard-gate files that are absent\n * set `satisfied: false` on the returned report; soft-gate misses are recorded but do not block.\n * Input checks read `_concept/_grounding/{skillId}/input.json`; missing files are treated as\n * no inputs collected. Resource checks are always recorded as `available: true` — actual\n * availability must be confirmed by the runner's `ResourceManager`.\n *\n * **Async and bounded since #454.** `projectDir` reaches this function straight\n * from the agent — `workspace_check_skill_requirements` takes `target_dir` as a\n * tool argument — so it can be `/skaile/workspace`, the rclone FUSE mount. Every\n * probe is now awaited and deadline-bounded, and the `min_entries` count walks\n * through the bounded {@link walkDir}, so a wedged mount or a symlink cycle\n * costs one failed tool call instead of the whole `skaile serve` event loop.\n *\n * @param skillId - Canonical skill identifier, used to locate `input.json`\n * @param requirements - Parsed requirements from SKILL.md (`parseSkillRequirements` output)\n * @param projectDir - Absolute path to the project root directory\n * @param overrides - Optional flow-level overrides; paths in `skip_checks` are treated as present\n * @param producesIndex - Maps file paths to the skill ID that produces them, enabling \"produced by\" hints in the report\n * @returns `RequirementsReport` with per-check results and an overall `satisfied` flag\n *\n * @docLink packages/resolver/api-reference#validate-requirements\n */\nexport async function validateRequirements(\n skillId: string,\n requirements: SkillRequirements,\n projectDir: string,\n overrides?: NodeOverrides,\n producesIndex?: Map<string, string>,\n): Promise<RequirementsReport> {\n const skipSet = new Set(overrides?.skip_checks ?? []);\n\n // Check files. Serial on purpose: `projectDir` may be one network mount, and\n // fanning every probe out concurrently multiplies the queue depth on exactly\n // the resource that is already the bottleneck.\n const files: FileCheck[] = [];\n for (const req of requirements.files) {\n if (skipSet.has(req.path)) {\n files.push({ path: req.path, gate: req.gate, exists: true, description: req.description });\n continue;\n }\n\n const fullPath = path.join(projectDir, req.path);\n const check: FileCheck = {\n path: req.path,\n gate: req.gate,\n exists: false,\n description: req.description,\n producedBy: producesIndex?.get(req.path),\n };\n\n if (req.min_entries != null) {\n const counted = await checkDirectoryMinEntries(fullPath, req.min_entries);\n check.exists = counted.satisfied;\n if (counted.truncated) check.truncated = true;\n } else {\n check.exists = await pathExists(fullPath);\n }\n\n files.push(check);\n }\n\n // Check inputs — look for _concept/_grounding/{skillId}/input.json\n const inputFile = path.join(projectDir, \"_concept\", \"_grounding\", skillId, \"input.json\");\n let collectedValues: Record<string, any> = {};\n try {\n const raw = await withFsDeadline(`readFile ${inputFile}`, () => readFile(inputFile, \"utf-8\"));\n const parsed = JSON.parse(raw) as SkillInputFile;\n collectedValues = parsed.values ?? {};\n } catch {\n // No input file — all inputs are missing\n }\n\n const allInputs = [\n ...requirements.inputs_required.map((f) => ({ field: f, required: true })),\n ...requirements.inputs_optional.map((f) => ({ field: f, required: false })),\n ];\n\n const inputs: InputCheck[] = allInputs.map(({ field, required }) => ({\n id: field.id,\n required,\n present: field.id in collectedValues,\n field,\n }));\n\n // Check reads (informational only)\n const reads: ReadCheck[] = [];\n for (const r of requirements.reads) {\n reads.push({\n path: r.path,\n exists: await pathExists(path.join(projectDir, r.path)),\n description: r.description,\n });\n }\n\n // Check resources (validated at a higher level if a ResourceManager is available;\n // here we just record them in the report with unknown status)\n const resources: ResourceCheck[] = (requirements.resources ?? []).map((r) => ({\n id: r.id,\n available: true, // Actual availability checked by runner with ResourceManager\n missingOps: [],\n optional: r.optional ?? false,\n }));\n\n // Satisfaction: all hard file gates pass AND all required inputs present\n const hardFilesSatisfied = files.filter((f) => f.gate === \"hard\").every((f) => f.exists);\n\n const requiredInputsSatisfied = inputs.filter((i) => i.required).every((i) => i.present);\n\n const requiredResourcesSatisfied = resources.filter((r) => !r.optional).every((r) => r.available);\n\n return {\n skillId,\n satisfied: hardFilesSatisfied && requiredInputsSatisfied && requiredResourcesSatisfied,\n files,\n inputs,\n reads,\n resources,\n };\n}\n\n/**\n * A warning produced by `validateConnectorRequirements` when a skill's declared\n * connector requirement is not satisfied by the connectors in skaile.yaml.\n * Each warning covers either a missing driver or an insufficient access level.\n *\n * @docLink packages/resolver/api-reference#connector-validation-warning\n */\nexport interface ConnectorValidationWarning {\n /** Driver name that triggered the warning. */\n driver: string;\n /** Human-readable explanation of the gap, including a remediation command where applicable. */\n message: string;\n}\n\n/** Minimal structural type accepted by validateConnectorRequirements. Compatible with both\n * ConnectorDeclaration shapes in @skaile/workspaces/core and @skaile/workspaces/connectors. */\ninterface AvailableConnector {\n driver: string;\n access?: \"read-only\" | \"read-write\";\n}\n\n/**\n * Check that all connector requirements declared in a skill's SKILL.md are\n * satisfied by the connectors declared in skaile.yaml.\n *\n * Returns one warning per gap — either a missing driver or an insufficient\n * access level. This is a pre-flight advisory; no runtime enforcement is done.\n *\n * @param requirements - Connector requirements from `parseSkillRequirements().connectors`\n * @param available - Connector declarations from `skaile.yaml` (via `loadConnectorDeclarations`)\n * @returns Array of warnings — one per gap. Empty array when all requirements are satisfied.\n *\n * @docLink packages/resolver/api-reference#validate-connector-requirements\n */\nexport function validateConnectorRequirements(\n requirements: ConnectorRequirement[],\n available: AvailableConnector[],\n): ConnectorValidationWarning[] {\n const warnings: ConnectorValidationWarning[] = [];\n\n for (const req of requirements) {\n const matches = available.filter((a) => a.driver === req.driver);\n\n if (matches.length === 0) {\n warnings.push({\n driver: req.driver,\n message:\n `Skill requires connector driver \"${req.driver}\" but none is declared in skaile.yaml. ` +\n `Run: skaile connector add ${req.driver}`,\n });\n continue;\n }\n\n if (req.access === \"read-write\") {\n const hasReadWrite = matches.some((m) => (m.access ?? \"read-only\") === \"read-write\");\n if (!hasReadWrite) {\n warnings.push({\n driver: req.driver,\n message:\n `Skill requires \"${req.driver}\" with read-write access, but all declared instances ` +\n `are read-only. Update access in skaile.yaml.`,\n });\n }\n }\n }\n\n return warnings;\n}\n\n/**\n * Does `dirPath` hold at least `minEntries` files, counted recursively?\n *\n * `truncated` is set when a walk bound was hit *and* the count still fell\n * short: the number is then a floor, not the truth, so `satisfied: false` is\n * \"we could not prove it\" rather than \"there are not enough files\". Reaching\n * `minEntries` short-circuits the walk, so the common case never pays for the\n * whole tree and a bound hit after that point is irrelevant.\n */\nasync function checkDirectoryMinEntries(\n dirPath: string,\n minEntries: number,\n): Promise<{ satisfied: boolean; truncated: boolean }> {\n const st = await tryWithFsDeadline(`stat ${dirPath}`, () => stat(dirPath), null);\n if (!st?.isDirectory()) return { satisfied: false, truncated: false };\n\n const { count, truncation } = await countFilesRecursive(dirPath, minEntries);\n const satisfied = count >= minEntries;\n if (!satisfied && truncation) {\n log().warn(\"min_entries count truncated — result is a lower bound, not the file count\", {\n dirPath,\n minEntries,\n count,\n ...truncation,\n });\n }\n return { satisfied, truncated: !satisfied && truncation !== undefined };\n}\n\n/**\n * Count files under `dirPath`, stopping at `limit`.\n *\n * Delegates to core's {@link walkDir} rather than recursing here: `dirPath` is\n * agent-supplied and can be a network mount, so the walk needs the deadline per\n * `opendir`, the depth / entry / wall-clock bounds, and the visited-inode cycle\n * guard that walker already owns. The pre-#454 `readdirSync` recursion had none\n * of them and recursed forever on `a/link -> a`.\n *\n * Inheriting `walkDir` also inherits its skip list: `.git` and `node_modules`\n * no longer count toward `min_entries`, which is what a prerequisite like\n * \"at least 3 feature files\" meant in the first place.\n */\nasync function countFilesRecursive(\n dirPath: string,\n limit: number,\n): Promise<{ count: number; truncation?: WalkTruncation }> {\n let count = 0;\n let truncation: WalkTruncation | undefined;\n for await (const _entry of walkDir(dirPath, {\n onTruncate: (info) => {\n truncation ??= info;\n },\n })) {\n count++;\n // Enough is enough — no reason to keep walking a large tree (or a wedged\n // mount) once the requirement is already met.\n if (count >= limit) return { count };\n }\n return { count, truncation };\n}\n","import { satisfies, valid, validRange } from \"semver\";\n\n/**\n * Result of a single flow-node version pin check.\n * Returned in the array produced by `validateFlowVersions()` for every\n * node that declares a `requestedVersion`.\n *\n * @docLink packages/resolver/api-reference#version-check\n */\nexport interface VersionCheck {\n /** Flow node identifier. */\n nodeId: string;\n /** Canonical skill identifier. */\n skillId: string;\n /** Semver range from the flow node (e.g. \"^1.0.0\") */\n requested: string;\n /** Version from the skill's frontmatter */\n actual: string;\n /** Whether `actual` satisfies the `requested` semver range. */\n satisfied: boolean;\n}\n\n/**\n * Minimal descriptor for a flow node that optionally pins a skill version.\n * Passed as input to `validateFlowVersions()`. Nodes without `requestedVersion`\n * are skipped during version checking.\n *\n * @docLink packages/resolver/api-reference#flow-version-node\n */\nexport interface FlowVersionNode {\n /** Flow node identifier. */\n nodeId: string;\n /** Canonical skill identifier referenced by this node. */\n skillId: string;\n /** Optional semver range the node requires (e.g. `\"^1.2.0\"`). Omit to skip version checking. */\n requestedVersion?: string;\n}\n\n/**\n * Validate flow node version pins against discovered skill versions.\n *\n * Only checks nodes that declare a `requestedVersion`. Nodes without a\n * version pin are skipped entirely (no entry is produced for those nodes).\n * A check is marked `satisfied: false` when the range is invalid, the actual\n * version string is not valid semver, or the version does not satisfy the range.\n *\n * @param nodes - Flow nodes to check; only those with `requestedVersion` are evaluated\n * @param skillVersions - Map from skill ID to the semver version string in its frontmatter\n * @returns Array of `VersionCheck` results, one per node that declared a version pin\n *\n * @docLink packages/resolver/api-reference#validate-flow-versions\n */\nexport function validateFlowVersions(\n nodes: FlowVersionNode[],\n skillVersions: Map<string, string>,\n): VersionCheck[] {\n const checks: VersionCheck[] = [];\n\n for (const node of nodes) {\n if (!node.requestedVersion) continue;\n\n const actual = skillVersions.get(node.skillId) ?? \"\";\n const requested = node.requestedVersion;\n\n // Invalid range or missing/invalid actual version → not satisfied\n const rangeValid = validRange(requested) !== null;\n const actualValid = actual !== \"\" && valid(actual) !== null;\n const isSatisfied = rangeValid && actualValid && satisfies(actual, requested);\n\n checks.push({\n nodeId: node.nodeId,\n skillId: node.skillId,\n requested,\n actual,\n satisfied: isSatisfied,\n });\n }\n\n return checks;\n}\n"]}
1
+ {"version":3,"sources":["../resolver/src/parser.ts","../resolver/src/preamble.ts","../resolver/src/validator.ts","../resolver/src/version.ts"],"names":["parseYaml"],"mappings":";;;;;;;AAeO,SAAS,sBAAsB,OAAA,EAAsC;AAC1E,EAAA,MAAM,KAAA,GAAQ,OAAA,CAAQ,KAAA,CAAM,uBAAuB,CAAA;AACnD,EAAA,IAAI,CAAC,KAAA,EAAO,OAAO,EAAC;AACpB,EAAA,IAAI;AACF,IAAA,OAAOA,KAAA,CAAU,KAAA,CAAM,CAAC,CAAE,KAAK,EAAC;AAAA,EAClC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M,KAAA,CAAM,MAAM,CAAA,KAAM,IAAA;AACvD,IAAA,MAAM,WAAA,GAAc,UAAA,IAAc,WAAA,IAAe,SAAA,CAAU,QAAQ,SAAS,CAAA;AAE5E,IAAA,MAAA,CAAO,IAAA,CAAK;AAAA,MACV,QAAQ,IAAA,CAAK,MAAA;AAAA,MACb,SAAS,IAAA,CAAK,OAAA;AAAA,MACd,SAAA;AAAA,MACA,MAAA;AAAA,MACA,SAAA,EAAW;AAAA,KACZ,CAAA;AAAA,EACH;AAEA,EAAA,OAAO,MAAA;AACT","file":"chunk-3XXQPHGL.js","sourcesContent":["import { parse as parseYaml } from \"yaml\";\nimport type { ConnectorRequirement, InputField, SkillRequirements } from \"./types.js\";\n\n/**\n * Extract YAML frontmatter from a SKILL.md string.\n *\n * Frontmatter is delimited by leading `---` fences. Returns the parsed object,\n * or an empty object `{}` if no frontmatter block is found or if the YAML is malformed.\n * Errors are silently swallowed — callers should treat an empty result as \"no requirements\".\n *\n * @param content - Raw SKILL.md file content (full string, including `---` fences)\n * @returns Parsed frontmatter object, or `{}` on absence or parse failure\n *\n * @docLink packages/resolver/api-reference#parseskill-frontmatter\n */\nexport function parseSkillFrontmatter(content: string): Record<string, any> {\n const match = content.match(/^---\\n([\\s\\S]*?)\\n---/);\n if (!match) return {};\n try {\n return parseYaml(match[1]!) ?? {};\n } catch {\n return {};\n }\n}\n\n/**\n * Parse skill requirements from raw SKILL.md content into a `SkillRequirements` object.\n *\n * Supports two frontmatter formats:\n * 1. **New format** — `metadata.prerequisites` with explicit\n * `files`, `inputs_required`, `inputs_optional`, `reads`, `produces`, and `resources` arrays.\n * 2. **Legacy format** — `metadata.user_inputs.dialog[]` array, automatically promoted to\n * `inputs_required` / `inputs_optional` based on each entry's `required` flag.\n *\n * Returns empty requirements `{ files: [], inputs_required: [], inputs_optional: [], reads: [], produces: [], resources: [] }`\n * when no recognisable prerequisites section is found.\n *\n * @param content - Raw SKILL.md file content (full string, including `---` fences)\n * @returns Structured `SkillRequirements` (never throws)\n *\n * @docLink packages/resolver/api-reference#parseskill-requirements\n */\nexport function parseSkillRequirements(content: string): SkillRequirements {\n const fm = parseSkillFrontmatter(content);\n const meta = fm.metadata ?? {};\n const prerequisites = meta.prerequisites ?? {};\n\n const empty: SkillRequirements = {\n files: [],\n inputs_required: [],\n inputs_optional: [],\n reads: [],\n produces: [],\n resources: [],\n connectors: [],\n };\n\n // New format: metadata.prerequisites\n if (\n prerequisites.files ||\n prerequisites.inputs_required ||\n prerequisites.inputs_optional ||\n prerequisites.reads ||\n prerequisites.produces ||\n prerequisites.resources ||\n prerequisites.connectors\n ) {\n return {\n files: (prerequisites.files ?? []).map((f: any) => ({\n path: f.path,\n gate: f.gate ?? \"hard\",\n description: f.description ?? \"\",\n ...(f.min_entries != null ? { min_entries: f.min_entries } : {}),\n })),\n inputs_required: (prerequisites.inputs_required ?? []).map(normalizeInputField(true)),\n inputs_optional: (prerequisites.inputs_optional ?? []).map(normalizeInputField(false)),\n reads: (prerequisites.reads ?? []).map((r: any) => ({\n path: r.path,\n description: r.description ?? \"\",\n })),\n produces: (prerequisites.produces ?? []).map((p: any) => ({\n path: p.path,\n description: p.description ?? \"\",\n })),\n resources: (prerequisites.resources ?? []).map((r: any) => ({\n id: r.id,\n ...(r.operations ? { operations: r.operations } : {}),\n optional: r.optional ?? false,\n ...(r.description ? { description: r.description } : {}),\n })),\n connectors: parseConnectorRequirements(prerequisites.connectors),\n };\n }\n\n // Legacy format: metadata.user_inputs.dialog[]\n const dialog = meta.user_inputs?.dialog;\n if (Array.isArray(dialog)) {\n const required: InputField[] = [];\n const optional: InputField[] = [];\n for (const d of dialog) {\n const field = normalizeInputField(d.required ?? false)(d);\n if (d.required) required.push(field);\n else optional.push(field);\n }\n return { ...empty, inputs_required: required, inputs_optional: optional, resources: [] };\n }\n\n return empty;\n}\n\n/**\n * Extract compaction directives from a SKILL.md markdown body.\n *\n * Scans the markdown body (not frontmatter) for a `## Compaction Directives` section\n * and returns each bullet point as a trimmed string. Compaction directives are hints\n * the agent uses to summarise context when the conversation history grows long.\n * Returns an empty array when the section is absent.\n *\n * @param content - Raw SKILL.md file content (full string including frontmatter and body)\n * @returns Array of directive strings extracted from the bullet list, or `[]` if none found\n *\n * @docLink packages/resolver/api-reference#parse-compaction-directives\n */\nexport function parseCompactionDirectives(content: string): string[] {\n const headerIdx = content.search(/^## Compaction Directives/m);\n if (headerIdx === -1) return [];\n\n // Header on the last line (no trailing newline) → no body to scan.\n const newlineIdx = content.indexOf(\"\\n\", headerIdx);\n if (newlineIdx === -1) return [];\n const bodyStart = newlineIdx + 1;\n const rest = content.slice(bodyStart);\n const nextSection = rest.search(/^##\\s/m);\n const sectionBody = nextSection === -1 ? rest : rest.slice(0, nextSection);\n\n const bullets: string[] = [];\n for (const line of sectionBody.split(\"\\n\")) {\n const match = line.match(/^\\s*[-*]\\s+(.+)/);\n if (match) bullets.push(match[1].trim());\n }\n return bullets;\n}\n\nfunction normalizeInputField(defaultRequired: boolean) {\n return (d: any): InputField => ({\n // UserInputSchema permits `key` or `id`; `prompt` is the legacy label alias.\n id: d.id ?? d.key,\n label: d.label ?? d.prompt ?? d.id ?? d.key,\n type: d.type ?? \"text\",\n required: d.required ?? defaultRequired,\n ...(d.options ? { options: d.options } : {}),\n ...(d.default != null ? { default: d.default } : {}),\n ...(d.hint ? { hint: d.hint } : {}),\n ...(d.schema ? { schema: d.schema } : {}),\n });\n}\n\nfunction parseConnectorRequirements(raw: unknown): ConnectorRequirement[] {\n if (!Array.isArray(raw)) return [];\n return raw\n .filter((c): c is Record<string, unknown> => typeof c === \"object\" && c !== null)\n .map((c) => ({\n driver: String(c.driver ?? \"\"),\n ...(c.access === \"read-write\"\n ? { access: \"read-write\" as const }\n : { access: \"read-only\" as const }),\n }))\n .filter((c) => c.driver.length > 0);\n}\n","import type { SkillRequirements } from \"./types.js\";\n\n/**\n * Generate a DSL-format preamble from skill requirements.\n *\n * The preamble is prepended to the skill prompt when the skill runs standalone\n * (without an orchestrator), giving the agent an explicit checklist of what to\n * verify before starting work. Each section maps to a requirement category:\n *\n * - `REQUIRES` — file/directory gates (`hard:` or `soft:` prefix)\n * - `INPUT` — user input fields, with a pointer to `input.json` if `skillId` is provided\n * - `READS` — informational read sources (not gated)\n * - `WRITES` — files the skill will produce\n * - `RESOURCE` — runtime resource dependencies\n *\n * Sections with no entries are omitted. Returns an empty string when all\n * requirement arrays are empty.\n *\n * @param requirements - Parsed requirements (output of `parseSkillRequirements`)\n * @param skillId - Optional skill identifier; when provided, the INPUT section includes\n * the canonical `input.json` path so the agent knows where to read collected values\n * @returns Multi-section DSL string, or `\"\"` if there are no requirements to list\n *\n * @example\n * ```ts\n * const preamble = buildRequiresPreamble(requirements, \"cf_overview\");\n * const fullPrompt = preamble ? `${preamble}\\n\\n${skillBody}` : skillBody;\n * ```\n *\n * @docLink packages/resolver/api-reference#build-requires-preamble\n */\nexport function buildRequiresPreamble(requirements: SkillRequirements, skillId?: string): string {\n const sections: string[] = [];\n\n pushSection(sections, buildRequiresSection(requirements));\n pushSection(sections, buildInputSection(requirements, skillId));\n pushSection(sections, buildReadsSection(requirements));\n pushSection(sections, buildWritesSection(requirements));\n pushSection(sections, buildResourceSection(requirements));\n\n return sections.join(\"\\n\\n\");\n}\n\n/** Append a section to the list when it produced output. */\nfunction pushSection(sections: string[], section: string | null): void {\n if (section !== null) sections.push(section);\n}\n\n/** REQUIRES section (file gates). Returns `null` when there are no file gates. */\nfunction buildRequiresSection(requirements: SkillRequirements): string | null {\n if (requirements.files.length === 0) return null;\n const lines = [\"REQUIRES\"];\n for (const f of requirements.files) {\n const prefix = f.gate === \"hard\" ? \"hard\" : \"soft\";\n lines.push(` ${prefix}: ${f.path} — ${f.description}`);\n }\n return lines.join(\"\\n\");\n}\n\n/** INPUT section (user inputs). Returns `null` when there are no inputs. */\nfunction buildInputSection(requirements: SkillRequirements, skillId?: string): string | null {\n const allInputs = [...requirements.inputs_required, ...requirements.inputs_optional];\n if (allInputs.length === 0) return null;\n const lines = [\"INPUT\"];\n if (skillId) {\n lines.push(` Read from: _concept/_grounding/${skillId}/input.json`);\n lines.push(\n ` If input.json is missing, ask the user for the following values and write the file:`,\n );\n }\n for (const input of allInputs) {\n const req = input.required ? \"(required)\" : \"(optional)\";\n const opts = input.options ? ` [${input.options.join(\" | \")}]` : \"\";\n const def = input.default != null ? ` default: ${input.default}` : \"\";\n lines.push(` - ${input.id}: ${input.label} ${req}${opts}${def}`);\n if (input.hint) lines.push(` hint: ${input.hint}`);\n }\n return lines.join(\"\\n\");\n}\n\n/** READS section. Returns `null` when there are no read sources. */\nfunction buildReadsSection(requirements: SkillRequirements): string | null {\n if (requirements.reads.length === 0) return null;\n const lines = [\"READS\"];\n for (const r of requirements.reads) {\n lines.push(` ? ${r.path} — ${r.description}`);\n }\n return lines.join(\"\\n\");\n}\n\n/** WRITES section (produces). Returns `null` when there is nothing produced. */\nfunction buildWritesSection(requirements: SkillRequirements): string | null {\n if (requirements.produces.length === 0) return null;\n const lines = [\"WRITES\"];\n for (const p of requirements.produces) {\n lines.push(` ${p.path} — ${p.description}`);\n }\n return lines.join(\"\\n\");\n}\n\n/** RESOURCE section. Returns `null` when there are no resources. */\nfunction buildResourceSection(requirements: SkillRequirements): string | null {\n if (!requirements.resources || requirements.resources.length === 0) return null;\n const lines = [\"RESOURCE\"];\n for (const r of requirements.resources) {\n const req = r.optional ? \"(optional)\" : \"(required)\";\n const ops = r.operations ? ` ops: [${r.operations.join(\", \")}]` : \"\";\n lines.push(` ${r.id} ${req}${ops}`);\n if (r.description) lines.push(` — ${r.description}`);\n }\n return lines.join(\"\\n\");\n}\n","import { readFile, stat } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport {\n tryWithFsDeadline,\n walkDir,\n type WalkTruncation,\n withFsDeadline,\n} from \"@skaile/workspaces/core\";\nimport { createLogger } from \"@skaile/workspaces/core/logging\";\nimport type {\n ConnectorRequirement,\n FileCheck,\n InputCheck,\n NodeOverrides,\n ReadCheck,\n RequirementsReport,\n ResourceCheck,\n SkillInputFile,\n SkillRequirements,\n} from \"./types.js\";\n\nlet validatorLogger: ReturnType<typeof createLogger> | undefined;\n\nfunction log(): ReturnType<typeof createLogger> {\n validatorLogger ??= createLogger({ kind: \"runner\", subkind: \"skill-requirements\" });\n return validatorLogger;\n}\n\n/** Best-effort existence probe. A missing path, an unreadable one, and an\n * unresponsive mount are all \"not usable here\" for a requirement check. */\nasync function pathExists(target: string): Promise<boolean> {\n return tryWithFsDeadline(\n `stat ${target}`,\n async () => {\n await stat(target);\n return true;\n },\n false,\n );\n}\n\n/**\n * Validate skill requirements against the filesystem and collected inputs.\n *\n * File checks resolve paths relative to `projectDir`. Hard-gate files that are absent\n * set `satisfied: false` on the returned report; soft-gate misses are recorded but do not block.\n * Input checks read `_concept/_grounding/{skillId}/input.json`; missing files are treated as\n * no inputs collected. Resource checks are always recorded as `available: true` — actual\n * availability must be confirmed by the runner's `ResourceManager`.\n *\n * **Async and bounded since #454.** `projectDir` reaches this function straight\n * from the agent — `workspace_check_skill_requirements` takes `target_dir` as a\n * tool argument — so it can be `/skaile/workspace`, the rclone FUSE mount. Every\n * probe is now awaited and deadline-bounded, and the `min_entries` count walks\n * through the bounded {@link walkDir}, so a wedged mount or a symlink cycle\n * costs one failed tool call instead of the whole `skaile serve` event loop.\n *\n * @param skillId - Canonical skill identifier, used to locate `input.json`\n * @param requirements - Parsed requirements from SKILL.md (`parseSkillRequirements` output)\n * @param projectDir - Absolute path to the project root directory\n * @param overrides - Optional flow-level overrides; paths in `skip_checks` are treated as present\n * @param producesIndex - Maps file paths to the skill ID that produces them, enabling \"produced by\" hints in the report\n * @returns `RequirementsReport` with per-check results and an overall `satisfied` flag\n *\n * @docLink packages/resolver/api-reference#validate-requirements\n */\nexport async function validateRequirements(\n skillId: string,\n requirements: SkillRequirements,\n projectDir: string,\n overrides?: NodeOverrides,\n producesIndex?: Map<string, string>,\n): Promise<RequirementsReport> {\n const skipSet = new Set(overrides?.skip_checks ?? []);\n\n // Check files. Serial on purpose: `projectDir` may be one network mount, and\n // fanning every probe out concurrently multiplies the queue depth on exactly\n // the resource that is already the bottleneck.\n const files: FileCheck[] = [];\n for (const req of requirements.files) {\n if (skipSet.has(req.path)) {\n files.push({ path: req.path, gate: req.gate, exists: true, description: req.description });\n continue;\n }\n\n const fullPath = path.join(projectDir, req.path);\n const check: FileCheck = {\n path: req.path,\n gate: req.gate,\n exists: false,\n description: req.description,\n producedBy: producesIndex?.get(req.path),\n };\n\n if (req.min_entries != null) {\n const counted = await checkDirectoryMinEntries(fullPath, req.min_entries);\n check.exists = counted.satisfied;\n if (counted.truncated) check.truncated = true;\n } else {\n check.exists = await pathExists(fullPath);\n }\n\n files.push(check);\n }\n\n // Check inputs — look for _concept/_grounding/{skillId}/input.json\n const inputFile = path.join(projectDir, \"_concept\", \"_grounding\", skillId, \"input.json\");\n let collectedValues: Record<string, any> = {};\n try {\n const raw = await withFsDeadline(`readFile ${inputFile}`, () => readFile(inputFile, \"utf-8\"));\n const parsed = JSON.parse(raw) as SkillInputFile;\n collectedValues = parsed.values ?? {};\n } catch {\n // No input file — all inputs are missing\n }\n\n const allInputs = [\n ...requirements.inputs_required.map((f) => ({ field: f, required: true })),\n ...requirements.inputs_optional.map((f) => ({ field: f, required: false })),\n ];\n\n const inputs: InputCheck[] = allInputs.map(({ field, required }) => ({\n id: field.id,\n required,\n present: field.id in collectedValues,\n field,\n }));\n\n // Check reads (informational only)\n const reads: ReadCheck[] = [];\n for (const r of requirements.reads) {\n reads.push({\n path: r.path,\n exists: await pathExists(path.join(projectDir, r.path)),\n description: r.description,\n });\n }\n\n // Check resources (validated at a higher level if a ResourceManager is available;\n // here we just record them in the report with unknown status)\n const resources: ResourceCheck[] = (requirements.resources ?? []).map((r) => ({\n id: r.id,\n available: true, // Actual availability checked by runner with ResourceManager\n missingOps: [],\n optional: r.optional ?? false,\n }));\n\n // Satisfaction: all hard file gates pass AND all required inputs present\n const hardFilesSatisfied = files.filter((f) => f.gate === \"hard\").every((f) => f.exists);\n\n const requiredInputsSatisfied = inputs.filter((i) => i.required).every((i) => i.present);\n\n const requiredResourcesSatisfied = resources.filter((r) => !r.optional).every((r) => r.available);\n\n return {\n skillId,\n satisfied: hardFilesSatisfied && requiredInputsSatisfied && requiredResourcesSatisfied,\n files,\n inputs,\n reads,\n resources,\n };\n}\n\n/**\n * A warning produced by `validateConnectorRequirements` when a skill's declared\n * connector requirement is not satisfied by the connectors in skaile.yaml.\n * Each warning covers either a missing driver or an insufficient access level.\n *\n * @docLink packages/resolver/api-reference#connector-validation-warning\n */\nexport interface ConnectorValidationWarning {\n /** Driver name that triggered the warning. */\n driver: string;\n /** Human-readable explanation of the gap, including a remediation command where applicable. */\n message: string;\n}\n\n/** Minimal structural type accepted by validateConnectorRequirements. Compatible with both\n * ConnectorDeclaration shapes in @skaile/workspaces/core and @skaile/workspaces/connectors. */\ninterface AvailableConnector {\n driver: string;\n access?: \"read-only\" | \"read-write\";\n}\n\n/**\n * Check that all connector requirements declared in a skill's SKILL.md are\n * satisfied by the connectors declared in skaile.yaml.\n *\n * Returns one warning per gap — either a missing driver or an insufficient\n * access level. This is a pre-flight advisory; no runtime enforcement is done.\n *\n * @param requirements - Connector requirements from `parseSkillRequirements().connectors`\n * @param available - Connector declarations from `skaile.yaml` (via `loadConnectorDeclarations`)\n * @returns Array of warnings — one per gap. Empty array when all requirements are satisfied.\n *\n * @docLink packages/resolver/api-reference#validate-connector-requirements\n */\nexport function validateConnectorRequirements(\n requirements: ConnectorRequirement[],\n available: AvailableConnector[],\n): ConnectorValidationWarning[] {\n const warnings: ConnectorValidationWarning[] = [];\n\n for (const req of requirements) {\n const matches = available.filter((a) => a.driver === req.driver);\n\n if (matches.length === 0) {\n warnings.push({\n driver: req.driver,\n message:\n `Skill requires connector driver \"${req.driver}\" but none is declared in skaile.yaml. ` +\n `Run: skaile connector add ${req.driver}`,\n });\n continue;\n }\n\n if (req.access === \"read-write\") {\n const hasReadWrite = matches.some((m) => (m.access ?? \"read-only\") === \"read-write\");\n if (!hasReadWrite) {\n warnings.push({\n driver: req.driver,\n message:\n `Skill requires \"${req.driver}\" with read-write access, but all declared instances ` +\n `are read-only. Update access in skaile.yaml.`,\n });\n }\n }\n }\n\n return warnings;\n}\n\n/**\n * Does `dirPath` hold at least `minEntries` files, counted recursively?\n *\n * `truncated` is set when a walk bound was hit *and* the count still fell\n * short: the number is then a floor, not the truth, so `satisfied: false` is\n * \"we could not prove it\" rather than \"there are not enough files\". Reaching\n * `minEntries` short-circuits the walk, so the common case never pays for the\n * whole tree and a bound hit after that point is irrelevant.\n */\nasync function checkDirectoryMinEntries(\n dirPath: string,\n minEntries: number,\n): Promise<{ satisfied: boolean; truncated: boolean }> {\n const st = await tryWithFsDeadline(`stat ${dirPath}`, () => stat(dirPath), null);\n if (!st?.isDirectory()) return { satisfied: false, truncated: false };\n\n const { count, truncation } = await countFilesRecursive(dirPath, minEntries);\n const satisfied = count >= minEntries;\n if (!satisfied && truncation) {\n log().warn(\"min_entries count truncated — result is a lower bound, not the file count\", {\n dirPath,\n minEntries,\n count,\n ...truncation,\n });\n }\n return { satisfied, truncated: !satisfied && truncation !== undefined };\n}\n\n/**\n * Count files under `dirPath`, stopping at `limit`.\n *\n * Delegates to core's {@link walkDir} rather than recursing here: `dirPath` is\n * agent-supplied and can be a network mount, so the walk needs the deadline per\n * `opendir`, the depth / entry / wall-clock bounds, and the visited-inode cycle\n * guard that walker already owns. The pre-#454 `readdirSync` recursion had none\n * of them and recursed forever on `a/link -> a`.\n *\n * Inheriting `walkDir` also inherits its skip list: `.git` and `node_modules`\n * no longer count toward `min_entries`, which is what a prerequisite like\n * \"at least 3 feature files\" meant in the first place.\n */\nasync function countFilesRecursive(\n dirPath: string,\n limit: number,\n): Promise<{ count: number; truncation?: WalkTruncation }> {\n let count = 0;\n let truncation: WalkTruncation | undefined;\n for await (const _entry of walkDir(dirPath, {\n onTruncate: (info) => {\n truncation ??= info;\n },\n })) {\n count++;\n // Enough is enough — no reason to keep walking a large tree (or a wedged\n // mount) once the requirement is already met.\n if (count >= limit) return { count };\n }\n return { count, truncation };\n}\n","import { satisfies, valid, validRange } from \"semver\";\n\n/**\n * Result of a single flow-node version pin check.\n * Returned in the array produced by `validateFlowVersions()` for every\n * node that declares a `requestedVersion`.\n *\n * @docLink packages/resolver/api-reference#version-check\n */\nexport interface VersionCheck {\n /** Flow node identifier. */\n nodeId: string;\n /** Canonical skill identifier. */\n skillId: string;\n /** Semver range from the flow node (e.g. \"^1.0.0\") */\n requested: string;\n /** Version from the skill's frontmatter */\n actual: string;\n /** Whether `actual` satisfies the `requested` semver range. */\n satisfied: boolean;\n}\n\n/**\n * Minimal descriptor for a flow node that optionally pins a skill version.\n * Passed as input to `validateFlowVersions()`. Nodes without `requestedVersion`\n * are skipped during version checking.\n *\n * @docLink packages/resolver/api-reference#flow-version-node\n */\nexport interface FlowVersionNode {\n /** Flow node identifier. */\n nodeId: string;\n /** Canonical skill identifier referenced by this node. */\n skillId: string;\n /** Optional semver range the node requires (e.g. `\"^1.2.0\"`). Omit to skip version checking. */\n requestedVersion?: string;\n}\n\n/**\n * Validate flow node version pins against discovered skill versions.\n *\n * Only checks nodes that declare a `requestedVersion`. Nodes without a\n * version pin are skipped entirely (no entry is produced for those nodes).\n * A check is marked `satisfied: false` when the range is invalid, the actual\n * version string is not valid semver, or the version does not satisfy the range.\n *\n * @param nodes - Flow nodes to check; only those with `requestedVersion` are evaluated\n * @param skillVersions - Map from skill ID to the semver version string in its frontmatter\n * @returns Array of `VersionCheck` results, one per node that declared a version pin\n *\n * @docLink packages/resolver/api-reference#validate-flow-versions\n */\nexport function validateFlowVersions(\n nodes: FlowVersionNode[],\n skillVersions: Map<string, string>,\n): VersionCheck[] {\n const checks: VersionCheck[] = [];\n\n for (const node of nodes) {\n if (!node.requestedVersion) continue;\n\n const actual = skillVersions.get(node.skillId) ?? \"\";\n const requested = node.requestedVersion;\n\n // Invalid range or missing/invalid actual version → not satisfied\n const rangeValid = validRange(requested) !== null;\n const actualValid = actual !== \"\" && valid(actual) !== null;\n const isSatisfied = rangeValid && actualValid && satisfies(actual, requested);\n\n checks.push({\n nodeId: node.nodeId,\n skillId: node.skillId,\n requested,\n actual,\n satisfied: isSatisfied,\n });\n }\n\n return checks;\n}\n"]}
@@ -1,6 +1,6 @@
1
- import { resolveSkWorkspaceConfig } from './chunk-IP3GXHOB.js';
2
- import { parseFrontmatter } from './chunk-VQ4P7UYE.js';
3
- import { createLogger } from './chunk-3A5IKBHQ.js';
1
+ import { resolveSkWorkspaceConfig } from './chunk-OZ7UNMTK.js';
2
+ import { parseFrontmatter } from './chunk-MKZOK4JU.js';
3
+ import { createLogger } from './chunk-W4IPN3DD.js';
4
4
  import { readFileSync, existsSync, readdirSync, statSync } from 'fs';
5
5
  import { join } from 'path';
6
6
 
@@ -446,5 +446,5 @@ function resolveAuthRef(auth, mountId) {
446
446
  }
447
447
 
448
448
  export { EnvSecretProvider, ForgeSecretProvider, InMemorySecretProvider, LegacyAuthGrammarError, LockedSecretProvider, OAuthRequiredError, PreMintedSecretProvider, SecretProviderChain, createCliSecretProviderChain, createForgeSecretProviderChain, deriveSingleMaterializedConnectorDeclaration, fromMaterializedConnectorMd, isKnownSecretRef, loadConnectorDeclarations, loadMaterializedConnectorDeclarations, resolveAuthRef, resolveBackendAuthFor, resolvedConfigToDeclarations };
449
- //# sourceMappingURL=chunk-3UU3D2Q3.js.map
450
- //# sourceMappingURL=chunk-3UU3D2Q3.js.map
449
+ //# sourceMappingURL=chunk-5KSIVLOX.js.map
450
+ //# sourceMappingURL=chunk-5KSIVLOX.js.map