@skaile/workspaces 3.14.1 → 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 (207) hide show
  1. package/CHANGELOG.md +183 -0
  2. package/dist/{asset-feeds-STHKKTW3.js → asset-feeds-6UC7CUTI.js} +12 -12
  3. package/dist/{asset-feeds-STHKKTW3.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 +12 -12
  6. package/dist/asset-manager/installer.js +9 -9
  7. package/dist/asset-manager/renderers.js +2 -2
  8. package/dist/bridge/drivers/claude-sdk.js +15 -12
  9. package/dist/bridge/drivers/claude-sdk.js.map +1 -1
  10. package/dist/bridge/drivers/codex.js +4 -4
  11. package/dist/bridge/drivers/continue.js +4 -4
  12. package/dist/bridge/drivers/echo.js +3 -3
  13. package/dist/bridge/drivers/gemini.js +6 -6
  14. package/dist/bridge/drivers/goose.js +4 -4
  15. package/dist/bridge/drivers/omp.js +147 -8
  16. package/dist/bridge/drivers/omp.js.map +1 -1
  17. package/dist/bridge/drivers/opencode.js +4 -4
  18. package/dist/bridge/drivers/qwen.js +6 -6
  19. package/dist/bridge/index.js +10 -10
  20. package/dist/bridge/src/drivers/claude-sdk.d.ts.map +1 -1
  21. package/dist/bridge/src/drivers/omp.d.ts +62 -0
  22. package/dist/bridge/src/drivers/omp.d.ts.map +1 -1
  23. package/dist/bridge/src/index.d.ts +1 -0
  24. package/dist/bridge/src/index.d.ts.map +1 -1
  25. package/dist/bridge/src/models.d.ts +27 -2
  26. package/dist/bridge/src/models.d.ts.map +1 -1
  27. package/dist/bridge/src/provider-endpoints.d.ts +39 -0
  28. package/dist/bridge/src/provider-endpoints.d.ts.map +1 -1
  29. package/dist/bridge/src/validation.d.ts +6 -1
  30. package/dist/bridge/src/validation.d.ts.map +1 -1
  31. package/dist/{chunk-RUFTB7QN.js → chunk-3NCGSSCU.js} +3 -3
  32. package/dist/{chunk-RUFTB7QN.js.map → chunk-3NCGSSCU.js.map} +1 -1
  33. package/dist/{chunk-4VTBZ2MF.js → chunk-3XXQPHGL.js} +4 -4
  34. package/dist/{chunk-4VTBZ2MF.js.map → chunk-3XXQPHGL.js.map} +1 -1
  35. package/dist/{chunk-3UU3D2Q3.js → chunk-5KSIVLOX.js} +5 -5
  36. package/dist/{chunk-3UU3D2Q3.js.map → chunk-5KSIVLOX.js.map} +1 -1
  37. package/dist/{chunk-HYFJPR7W.js → chunk-6HTQNNOX.js} +7 -7
  38. package/dist/{chunk-HYFJPR7W.js.map → chunk-6HTQNNOX.js.map} +1 -1
  39. package/dist/{chunk-PGUTER7Z.js → chunk-6KPCHQP5.js} +3 -3
  40. package/dist/{chunk-PGUTER7Z.js.map → chunk-6KPCHQP5.js.map} +1 -1
  41. package/dist/{chunk-GHWJHOYX.js → chunk-7BUZQVRR.js} +4 -4
  42. package/dist/{chunk-GHWJHOYX.js.map → chunk-7BUZQVRR.js.map} +1 -1
  43. package/dist/{chunk-JAHHMZWG.js → chunk-7IRJ4K4F.js} +3 -3
  44. package/dist/{chunk-JAHHMZWG.js.map → chunk-7IRJ4K4F.js.map} +1 -1
  45. package/dist/{chunk-IRORTHGA.js → chunk-AN6NAFRT.js} +21 -7
  46. package/dist/chunk-AN6NAFRT.js.map +1 -0
  47. package/dist/{chunk-OYZIURPH.js → chunk-BQMRUH7J.js} +3 -3
  48. package/dist/{chunk-OYZIURPH.js.map → chunk-BQMRUH7J.js.map} +1 -1
  49. package/dist/{chunk-GRMQBBN4.js → chunk-BUKPS4YL.js} +3 -3
  50. package/dist/{chunk-GRMQBBN4.js.map → chunk-BUKPS4YL.js.map} +1 -1
  51. package/dist/{chunk-OCLCDB7G.js → chunk-C4AP3XZB.js} +6 -6
  52. package/dist/{chunk-OCLCDB7G.js.map → chunk-C4AP3XZB.js.map} +1 -1
  53. package/dist/{chunk-AZPXCHDK.js → chunk-CIPK5JMJ.js} +5 -6
  54. package/dist/chunk-CIPK5JMJ.js.map +1 -0
  55. package/dist/{chunk-KKMRT6GU.js → chunk-CL4TYERP.js} +10 -10
  56. package/dist/{chunk-KKMRT6GU.js.map → chunk-CL4TYERP.js.map} +1 -1
  57. package/dist/{chunk-IEX5YV4R.js → chunk-DVSASEGO.js} +3 -3
  58. package/dist/{chunk-IEX5YV4R.js.map → chunk-DVSASEGO.js.map} +1 -1
  59. package/dist/{chunk-PW4SJE3X.js → chunk-DZ4UZOFB.js} +4 -4
  60. package/dist/{chunk-PW4SJE3X.js.map → chunk-DZ4UZOFB.js.map} +1 -1
  61. package/dist/{chunk-5F33LGZL.js → chunk-ER4UOIUS.js} +3 -3
  62. package/dist/{chunk-5F33LGZL.js.map → chunk-ER4UOIUS.js.map} +1 -1
  63. package/dist/{chunk-G2CXWUO5.js → chunk-FAI2SMFE.js} +4 -4
  64. package/dist/{chunk-G2CXWUO5.js.map → chunk-FAI2SMFE.js.map} +1 -1
  65. package/dist/{chunk-5Q7HA4JP.js → chunk-FTG7CRFD.js} +3 -3
  66. package/dist/{chunk-5Q7HA4JP.js.map → chunk-FTG7CRFD.js.map} +1 -1
  67. package/dist/{chunk-V34ZEXSE.js → chunk-GURXUF2J.js} +32 -7
  68. package/dist/chunk-GURXUF2J.js.map +1 -0
  69. package/dist/{chunk-Z7W4B7P2.js → chunk-GWQZ2ECO.js} +6 -6
  70. package/dist/{chunk-Z7W4B7P2.js.map → chunk-GWQZ2ECO.js.map} +1 -1
  71. package/dist/{chunk-ZPCHTTD7.js → chunk-IVWJHELM.js} +116 -29
  72. package/dist/chunk-IVWJHELM.js.map +1 -0
  73. package/dist/{chunk-2A7BV6WT.js → chunk-JNCORFRK.js} +9 -6
  74. package/dist/chunk-JNCORFRK.js.map +1 -0
  75. package/dist/{chunk-XICDQVOG.js → chunk-KLDWNSDN.js} +4 -4
  76. package/dist/{chunk-XICDQVOG.js.map → chunk-KLDWNSDN.js.map} +1 -1
  77. package/dist/{chunk-URB2QZ4W.js → chunk-MFWIWPJP.js} +8 -8
  78. package/dist/{chunk-URB2QZ4W.js.map → chunk-MFWIWPJP.js.map} +1 -1
  79. package/dist/{chunk-VQ4P7UYE.js → chunk-MKZOK4JU.js} +3 -3
  80. package/dist/{chunk-VQ4P7UYE.js.map → chunk-MKZOK4JU.js.map} +1 -1
  81. package/dist/{chunk-AONVXRAE.js → chunk-NIUG3MIH.js} +3 -3
  82. package/dist/{chunk-AONVXRAE.js.map → chunk-NIUG3MIH.js.map} +1 -1
  83. package/dist/{chunk-ZSZSDBBW.js → chunk-OGTS7QJX.js} +5 -5
  84. package/dist/{chunk-ZSZSDBBW.js.map → chunk-OGTS7QJX.js.map} +1 -1
  85. package/dist/{chunk-SH572OBN.js → chunk-OIDFK7SG.js} +4 -4
  86. package/dist/{chunk-SH572OBN.js.map → chunk-OIDFK7SG.js.map} +1 -1
  87. package/dist/{chunk-IP3GXHOB.js → chunk-OZ7UNMTK.js} +3 -3
  88. package/dist/{chunk-IP3GXHOB.js.map → chunk-OZ7UNMTK.js.map} +1 -1
  89. package/dist/{chunk-UTW6YKAC.js → chunk-PMYZRX6M.js} +3 -3
  90. package/dist/{chunk-UTW6YKAC.js.map → chunk-PMYZRX6M.js.map} +1 -1
  91. package/dist/{chunk-O7WKKINT.js → chunk-S4UA244H.js} +5 -5
  92. package/dist/{chunk-O7WKKINT.js.map → chunk-S4UA244H.js.map} +1 -1
  93. package/dist/{chunk-WAFHQDLK.js → chunk-SUPIVTLX.js} +3 -3
  94. package/dist/{chunk-WAFHQDLK.js.map → chunk-SUPIVTLX.js.map} +1 -1
  95. package/dist/{chunk-Y6JJHOLR.js → chunk-SZ7VJQK3.js} +10 -10
  96. package/dist/{chunk-Y6JJHOLR.js.map → chunk-SZ7VJQK3.js.map} +1 -1
  97. package/dist/{chunk-3A5IKBHQ.js → chunk-W4IPN3DD.js} +61 -8
  98. package/dist/chunk-W4IPN3DD.js.map +1 -0
  99. package/dist/{chunk-VW6RUT7X.js → chunk-X2665LP2.js} +8 -8
  100. package/dist/{chunk-VW6RUT7X.js.map → chunk-X2665LP2.js.map} +1 -1
  101. package/dist/{chunk-M5D2QNTY.js → chunk-ZNCZ7RUO.js} +3 -3
  102. package/dist/{chunk-M5D2QNTY.js.map → chunk-ZNCZ7RUO.js.map} +1 -1
  103. package/dist/cli/index.js +60 -56
  104. package/dist/cli/index.js.map +1 -1
  105. package/dist/cli/src/commands/serve.d.ts.map +1 -1
  106. package/dist/connectors/config.js +7 -7
  107. package/dist/connectors/index.js +13 -13
  108. package/dist/core/index.js +6 -6
  109. package/dist/core/logging.js +2 -2
  110. package/dist/core/manifest.js +2 -2
  111. package/dist/core/runtime-assets.js +4 -4
  112. package/dist/core/src/logging/index.d.ts +2 -0
  113. package/dist/core/src/logging/index.d.ts.map +1 -1
  114. package/dist/core/src/logging/log-store.d.ts.map +1 -1
  115. package/dist/core/src/logging/sinks/stdout-sink.d.ts +6 -1
  116. package/dist/core/src/logging/sinks/stdout-sink.d.ts.map +1 -1
  117. package/dist/core/src/logging/stream-health.d.ts +46 -0
  118. package/dist/core/src/logging/stream-health.d.ts.map +1 -0
  119. package/dist/core/src/settings.d.ts +12 -1
  120. package/dist/core/src/settings.d.ts.map +1 -1
  121. package/dist/core/workspace-config.js +3 -3
  122. package/dist/deploy/index.js +8 -7
  123. package/dist/deploy/index.js.map +1 -1
  124. package/dist/deploy/src/targets/process-handle.d.ts.map +1 -1
  125. package/dist/discovery/index.js +4 -4
  126. package/dist/{ensure-sources-BFVKV773.js → ensure-sources-VJZUHSFZ.js} +15 -15
  127. package/dist/{ensure-sources-BFVKV773.js.map → ensure-sources-VJZUHSFZ.js.map} +1 -1
  128. package/dist/factory-assets/connectors/box.js +13 -13
  129. package/dist/factory-assets/connectors/deploy.js +13 -13
  130. package/dist/factory-assets/connectors/devserver.js +13 -13
  131. package/dist/factory-assets/connectors/flow/adapter.js +13 -13
  132. package/dist/factory-assets/connectors/flow/engine.js +7 -7
  133. package/dist/factory-assets/connectors/flow/run-flow.js +15 -15
  134. package/dist/factory-assets/connectors/flow.js +13 -13
  135. package/dist/factory-assets/connectors/git.js +13 -13
  136. package/dist/factory-assets/connectors/gmail.js +13 -13
  137. package/dist/factory-assets/connectors/googledrive.js +13 -13
  138. package/dist/factory-assets/connectors/local.js +13 -13
  139. package/dist/factory-assets/connectors/mattermost.js +13 -13
  140. package/dist/factory-assets/connectors/memory.js +13 -13
  141. package/dist/factory-assets/connectors/minio.js +13 -13
  142. package/dist/factory-assets/connectors/postgres.js +13 -13
  143. package/dist/factory-assets/connectors/s3.js +13 -13
  144. package/dist/factory-assets/connectors/sharepoint.js +13 -13
  145. package/dist/factory-assets/connectors/sqlite.js +13 -13
  146. package/dist/factory-assets/connectors/static-server.js +13 -13
  147. package/dist/factory-assets/connectors/tunnel.js +13 -13
  148. package/dist/factory-assets/connectors/webdav.js +13 -13
  149. package/dist/factory-assets/connectors/xstate-store.js +13 -13
  150. package/dist/factory-assets/connectors/xstate.js +13 -13
  151. package/dist/flows-2SUFOVVO.js +20 -0
  152. package/dist/{flows-4R4VJ5VM.js.map → flows-2SUFOVVO.js.map} +1 -1
  153. package/dist/{helpers-CQV2V2SL.js → helpers-EEYMGGLO.js} +15 -15
  154. package/dist/{helpers-CQV2V2SL.js.map → helpers-EEYMGGLO.js.map} +1 -1
  155. package/dist/library/index.js +9 -9
  156. package/dist/library/install.js +6 -6
  157. package/dist/{library-publish-6FZCXPYU.js → library-publish-37UBVMC3.js} +19 -19
  158. package/dist/{library-publish-6FZCXPYU.js.map → library-publish-37UBVMC3.js.map} +1 -1
  159. package/dist/open-library-JYVUN4CY.js +32 -0
  160. package/dist/{open-library-4EOFZ4QD.js.map → open-library-JYVUN4CY.js.map} +1 -1
  161. package/dist/paths-4APA2PKT.js +16 -0
  162. package/dist/{paths-S7UESJKT.js.map → paths-4APA2PKT.js.map} +1 -1
  163. package/dist/{plugin-store-5SJX2PRR.js → plugin-store-JQAIKR3R.js} +8 -8
  164. package/dist/{plugin-store-5SJX2PRR.js.map → plugin-store-JQAIKR3R.js.map} +1 -1
  165. package/dist/{project-J7RSKBAU.js → project-DKQACM3N.js} +16 -16
  166. package/dist/{project-J7RSKBAU.js.map → project-DKQACM3N.js.map} +1 -1
  167. package/dist/resolver/index.js +7 -7
  168. package/dist/runner/index.js +18 -18
  169. package/dist/runner/src/process-safety-net.d.ts +61 -0
  170. package/dist/runner/src/process-safety-net.d.ts.map +1 -0
  171. package/dist/runner/src/serve.d.ts +10 -0
  172. package/dist/runner/src/serve.d.ts.map +1 -1
  173. package/dist/sdk/asset-manager.js +12 -12
  174. package/dist/sdk/bridge.js +10 -10
  175. package/dist/sdk/core.js +6 -6
  176. package/dist/sdk/flow.js +7 -7
  177. package/dist/sdk/index.js +18 -18
  178. package/dist/sdk/resolver.js +7 -7
  179. package/dist/sdk/runner.js +18 -18
  180. package/dist/{setup-OQT5YK2Q.js → setup-7FJNMKFA.js} +12 -12
  181. package/dist/{setup-OQT5YK2Q.js.map → setup-7FJNMKFA.js.map} +1 -1
  182. package/dist/skills-Q7PJVB3W.js +20 -0
  183. package/dist/{skills-OBJX3VYG.js.map → skills-Q7PJVB3W.js.map} +1 -1
  184. package/dist/{source-AJ27AS6D.js → source-CT6RH3CJ.js} +18 -18
  185. package/dist/{source-AJ27AS6D.js.map → source-CT6RH3CJ.js.map} +1 -1
  186. package/dist/{source-manifest-publish-UCA2O5UA.js → source-manifest-publish-VBENANBT.js} +20 -20
  187. package/dist/{source-manifest-publish-UCA2O5UA.js.map → source-manifest-publish-VBENANBT.js.map} +1 -1
  188. package/dist/tui/index.js +18 -18
  189. package/dist/types/manifests.js +1 -1
  190. package/dist/types/src/manifests/agent.d.ts +47 -7
  191. package/dist/types/src/manifests/agent.d.ts.map +1 -1
  192. package/dist/types/src/manifests/index.d.ts +2 -2
  193. package/dist/types/src/manifests/index.d.ts.map +1 -1
  194. package/dist/workspace-plugin/adapters/mcp.js +11 -11
  195. package/dist/workspace-plugin/adapters/omp.js +7 -7
  196. package/dist/workspace-plugin/index.js +3 -3
  197. package/package.json +2 -1
  198. package/dist/chunk-2A7BV6WT.js.map +0 -1
  199. package/dist/chunk-3A5IKBHQ.js.map +0 -1
  200. package/dist/chunk-AZPXCHDK.js.map +0 -1
  201. package/dist/chunk-IRORTHGA.js.map +0 -1
  202. package/dist/chunk-V34ZEXSE.js.map +0 -1
  203. package/dist/chunk-ZPCHTTD7.js.map +0 -1
  204. package/dist/flows-4R4VJ5VM.js +0 -20
  205. package/dist/open-library-4EOFZ4QD.js +0 -32
  206. package/dist/paths-S7UESJKT.js +0 -16
  207. package/dist/skills-OBJX3VYG.js +0 -20
@@ -1,6 +1,68 @@
1
1
  import type { DriverTarget } from "@skaile/workspaces/plugin-registry";
2
2
  import type { ModelEntry } from "../models.js";
3
3
  import { type AgentConfig, AgentDriver, type DriverInfo } from "../types.js";
4
+ /**
5
+ * Credential and routing env vars forwarded to the omp child process.
6
+ *
7
+ * omp is model-agnostic — it selects a provider from whichever of these it
8
+ * finds. Forwarding only `ANTHROPIC_API_KEY`, as this allowlist used to,
9
+ * silently reduced every non-Anthropic workspace to a fallback: the child had
10
+ * no credential for the provider it was configured for and no way to say so.
11
+ * It also omitted `ANTHROPIC_BASE_URL`, so an Anthropic-compatible gateway was
12
+ * bypassed and traffic went to Anthropic's own API instead.
13
+ *
14
+ * The list mirrors the "Environment Variables" section of `omp --help`, which
15
+ * is the authoritative statement of what the child actually reads. Widening it
16
+ * is deliberate: these names *are* the provider credentials, so a host that
17
+ * sets one in the runner's environment is asking for the agent to use it. Vars
18
+ * outside this list — anything a platform provisions under its own naming —
19
+ * still do not reach the child.
20
+ *
21
+ * @docLink packages/bridge/concepts#omp-env-whitelist
22
+ */
23
+ export declare const OMP_PROVIDER_ENV_KEYS: readonly ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_OAUTH_TOKEN", "ANTHROPIC_BASE_URL", "ANTHROPIC_CUSTOM_HEADERS", "ANTHROPIC_FOUNDRY_API_KEY", "FOUNDRY_BASE_URL", "CLAUDE_CODE_USE_FOUNDRY", "CLAUDE_CODE_CLIENT_CERT", "CLAUDE_CODE_CLIENT_KEY", "NODE_EXTRA_CA_CERTS", "OPENAI_API_KEY", "OPENAI_BASE_URL", "GEMINI_API_KEY", "COPILOT_GITHUB_TOKEN", "AZURE_OPENAI_API_KEY", "GROQ_API_KEY", "CEREBRAS_API_KEY", "XAI_API_KEY", "MISTRAL_API_KEY", "ZAI_API_KEY", "MINIMAX_API_KEY", "DEEPSEEK_API_KEY", "OPENROUTER_API_KEY", "KILO_API_KEY", "AI_GATEWAY_API_KEY", "OPENCODE_API_KEY", "CURSOR_ACCESS_TOKEN", "CLINE_API_KEY", "WAFER_SERVERLESS_API_KEY", "YOLO_AUTO_API_KEY", "ABLITERATION_API_KEY", "UMANS_AI_CODING_PLAN_API_KEY", "UMANS_WEBSEARCH_PROVIDER", "AWS_PROFILE", "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN", "AWS_REGION", "AWS_DEFAULT_REGION", "GOOGLE_CLOUD_PROJECT", "GOOGLE_CLOUD_LOCATION", "GOOGLE_APPLICATION_CREDENTIALS", "EXA_API_KEY", "BRAVE_API_KEY", "PERPLEXITY_API_KEY", "PERPLEXITY_COOKIES", "TAVILY_API_KEY", "TINYFISH_API_KEY", "FIRECRAWL_API_KEY", "ANTHROPIC_SEARCH_API_KEY", "ANTHROPIC_SEARCH_BASE_URL", "OMP_PROFILE"];
24
+ /**
25
+ * Build the explicit env allowlist forwarded to the omp child process.
26
+ *
27
+ * The runner's full environment is never inherited — only
28
+ * {@link OMP_BASE_ENV_KEYS} (process essentials),
29
+ * {@link OMP_PROVIDER_ENV_KEYS} (provider credentials and routing), and the
30
+ * `PI_*` prefix (omp's own app config the host operator may have set).
31
+ *
32
+ * Test seams (`OMP_BRIDGE_*`, `FAKE_OMP_*`) are passed through so the
33
+ * subprocess harness in `tests/omp-driver.test.ts` can drive a fake-omp
34
+ * script via env-driven mode flags.
35
+ *
36
+ * @docLink packages/bridge/concepts#omp-env-whitelist
37
+ */
38
+ export declare function buildOmpChildEnv(parent: NodeJS.ProcessEnv): Record<string, string>;
39
+ /**
40
+ * omp's built-in tools, as reported by `omp --help` ("Available Tools").
41
+ *
42
+ * `computer` is the one entry omp does not enable by default; everything else
43
+ * is on unless `--tools` narrows the set. Used to turn a manifest *deny* list
44
+ * into the *allow* list omp's CLI actually accepts.
45
+ */
46
+ export declare const OMP_BUILTIN_TOOLS: readonly ["read", "bash", "edit", "write", "grep", "glob", "lsp", "python", "notebook", "browser", "computer", "task", "todo", "web_search", "ask"];
47
+ /** omp's default-enabled toolset — every built-in except `computer`. */
48
+ export declare const OMP_DEFAULT_TOOLS: readonly string[];
49
+ /**
50
+ * Resolve `AgentConfig.tools` into the omp CLI flags that enforce it.
51
+ *
52
+ * omp expresses tool restriction as a positive `--tools a,b,c` list (or
53
+ * `--no-tools`) — there is no deny flag — so a manifest deny list is applied by
54
+ * subtracting from {@link OMP_DEFAULT_TOOLS}.
55
+ *
56
+ * Returns `[]` when the manifest declares no restriction, which leaves omp on
57
+ * its full default toolset exactly as before. That default toolset is the bulk
58
+ * of every request's fixed token prefix, so this is the lever an agent
59
+ * definition needs in order to shrink it.
60
+ *
61
+ * Pure — exported for direct testing.
62
+ *
63
+ * @since 1.5.0
64
+ */
65
+ export declare function buildOmpToolArgs(tools: AgentConfig["tools"]): string[];
4
66
  /**
5
67
  * Agent driver for the oh-my-pi (omp) coding agent.
6
68
  *
@@ -1 +1 @@
1
- {"version":3,"file":"omp.d.ts","sourceRoot":"","sources":["../../../../bridge/src/drivers/omp.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,oCAAoC,CAAC;AAKvE,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAE/C,OAAO,EAAE,KAAK,WAAW,EAAE,WAAW,EAAmB,KAAK,UAAU,EAAE,MAA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eSdkResultErrorInput, cla
4
4
  export * from "./logger.js";
5
5
  export * from "./models.js";
6
6
  export * from "./normalizer.js";
7
+ export * from "./provider-endpoints.js";
7
8
  export * from "./registry.js";
8
9
  export { probeResumeTranscript, type ResumeProbeOutcome, resolveClaudeConfigDir, } from "./drivers/resume-probe.js";
9
10
  export * from "./runtime.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../bridge/src/index.ts"],"names":[],"mappings":"AAAA,cAAc,0BAA0B,CAAC;AACzC,cAAc,YAAY,CAAC;AAC3B,OAAO,EACL,uBAAuB,EACvB,SAAS,EACT,KAAK,yBAAyB,EAC9B,sBAAsB,EACtB,kCAAkC,GACnC,MAAM,uBAAuB,CAAC;AAC/B,cAAc,aAAa,CAAC;AAC5B,cAAc,aAAa,CAAC;AAC5B,cAAc,iBAAiB,CAAC;AAChC,cAAc,eAAe,CAAC;AAC9B,OAAO,EACL,qBAAqB,EACrB,KAAK,kBAAkB,EACvB,sBAAsB,GACvB,MAAM,2BAA2B,CAAC;AACnC,cAAc,cAAc,CAAC;AAC7B,cAAc,YAAY,CAAC;AAC3B,cAAc,iBAAiB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../bridge/src/index.ts"],"names":[],"mappings":"AAAA,cAAc,0BAA0B,CAAC;AACzC,cAAc,YAAY,CAAC;AAC3B,OAAO,EACL,uBAAuB,EACvB,SAAS,EACT,KAAK,yBAAyB,EAC9B,sBAAsB,EACtB,kCAAkC,GACnC,MAAM,uBAAuB,CAAC;AAC/B,cAAc,aAAa,CAAC;AAC5B,cAAc,aAAa,CAAC;AAC5B,cAAc,iBAAiB,CAAC;AAChC,cAAc,yBAAyB,CAAC;AACxC,cAAc,eAAe,CAAC;AAC9B,OAAO,EACL,qBAAqB,EACrB,KAAK,kBAAkB,EACvB,sBAAsB,GACvB,MAAM,2BAA2B,CAAC;AACnC,cAAc,cAAc,CAAC;AAC7B,cAAc,YAAY,CAAC;AAC3B,cAAc,iBAAiB,CAAC"}
@@ -38,6 +38,25 @@ export interface FetchModelsResult {
38
38
  /** Whether the result came from a live API call or the static fallback. */
39
39
  source: "api" | "static";
40
40
  }
41
+ /**
42
+ * Options controlling where a model-list fetch is addressed.
43
+ *
44
+ * @since 1.5.0
45
+ */
46
+ export interface FetchModelsOptions {
47
+ /**
48
+ * Base URL to resolve the provider's models endpoint against — e.g. the
49
+ * gateway a session already routes completions through. Overrides the
50
+ * provider's `baseUrlEnv` value.
51
+ */
52
+ baseUrl?: string;
53
+ /**
54
+ * Environment consulted for the provider's base-URL env var
55
+ * (`ANTHROPIC_BASE_URL` for `anthropic`). Defaults to `process.env`; pass an
56
+ * explicit record to keep a call hermetic.
57
+ */
58
+ env?: Record<string, string | undefined>;
59
+ }
41
60
  /**
42
61
  * Fetch the model list from a provider's REST API.
43
62
  *
@@ -45,13 +64,18 @@ export interface FetchModelsResult {
45
64
  * `{ ok: false, models: [], error }` on any HTTP or network failure — the
46
65
  * caller should fall back to {@link getStaticModels} in that case.
47
66
  *
67
+ * When the provider is reachable through a gateway, the request targets the
68
+ * configured base URL rather than the provider's public API — see
69
+ * {@link resolveProviderModelsUrl}. Without one, behaviour is unchanged.
70
+ *
48
71
  * @param provider - Provider name matching a key in the shared `PROVIDER_ENDPOINTS` map
49
72
  * (e.g. `"anthropic"`, `"openai"`, `"google"`).
50
73
  * @param apiKey - API key forwarded in the request header or query parameter.
74
+ * @param options - Optional base-URL / environment overrides.
51
75
  * @returns Resolved model list with source attribution.
52
76
  * @docLink packages/bridge/api-reference#models
53
77
  */
54
- export declare function fetchProviderModels(provider: string, apiKey: string): Promise<FetchModelsResult>;
78
+ export declare function fetchProviderModels(provider: string, apiKey: string, options?: FetchModelsOptions): Promise<FetchModelsResult>;
55
79
  /**
56
80
  * Get models for a provider, trying the live API first and falling back to the static catalog.
57
81
  *
@@ -61,10 +85,11 @@ export declare function fetchProviderModels(provider: string, apiKey: string): P
61
85
  *
62
86
  * @param provider - Provider name (e.g. `"anthropic"`, `"openai"`, `"google"`).
63
87
  * @param apiKey - Optional API key; omit to skip the live fetch and use the static catalog.
88
+ * @param options - Optional base-URL / environment overrides (see {@link FetchModelsOptions}).
64
89
  * @returns Resolved model list with source attribution.
65
90
  * @docLink packages/bridge/api-reference#models
66
91
  */
67
- export declare function getModels(provider: string, apiKey?: string): Promise<FetchModelsResult>;
92
+ export declare function getModels(provider: string, apiKey?: string, options?: FetchModelsOptions): Promise<FetchModelsResult>;
68
93
  /**
69
94
  * Offline model catalog keyed by provider name.
70
95
  *
@@ -1 +1 @@
1
- {"version":3,"file":"models.d.ts","sourceRoot":"","sources":["../../../bridge/src/models.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAIH;;;;;;;GAOG;AACH,MAAM,WAAW,UAAU;IACzB,yFAAyF;IACzF,EAAE,EAAE,MAAM,CAAC;IACX,iFAAiF;IACjF,IAAI,EAAE,MAAM,CAAC;CACd;AA6GD;;;;;;;;GAQG;AACH,MAAM,WAAW,iBAAiB;IAChC,iEAAiE;IACjE,EAAE,EAAE,OAAO,CAAC;IACZ,4CAA4C;IAC5C,MAAM,EAAE,UAAU,EAAE,CAAC;IACrB,6DAA6D;IAC7D,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,2EAA2E;IAC3E,MAAM,EAAE,KAAK,GAAG,QAAQ,CAAC;CAC1B;AAED;;;;;;;;;;;;GAYG;AACH,wBAAsB,mBAAmB,CACvC,QAAQ,EAAE,MAAM,EAChB,MAAM,EAAE,MAAM,GACb,OAAO,CAAC,iBAAiB,CAAC,CA+C5B;AAED;;;;;;;;;;;GAWG;AACH,wBAAsB,SAAS,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAkB7F;AAMD;;;;;;;;;GASG;AACH,eAAO,MAAM,aAAa,EAAE,MAAM,CAAC,MAAM,EAAE,UAAU,EAAE,CAgEtD,CAAC;AAEF;;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;IAE/C,QAAQ,CAAC,IAAI,EAAE,OAAO,GAAG,MAAM;IAC/B,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS;gBAD5B,IAAI,EAAE,OAAO,GAAG,MAAM,EACtB,QAAQ,EAAE,MAAM,GAAG,SAAS;CAQxC;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,gBAAgB,CAC9B,IAAI,EAAE,OAAO,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,EAC9C,YAAY,EAAE,MAAM,GAAG,SAAS,EAChC,OAAO,GAAE;IAAE,QAAQ,CAAC,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,kBAAkB,CAAA;CAAO,GAClF,MAAM,GAAG,SAAS,CAWpB"}
@@ -8,9 +8,48 @@
8
8
  */
9
9
  /** REST endpoint descriptor for a provider's models listing. */
10
10
  export interface ProviderEndpoint {
11
+ /** Full models-list URL against the provider's own public API. */
11
12
  url: string;
13
+ /**
14
+ * Path appended to a caller- or env-supplied base URL. Present only for
15
+ * providers that can legitimately be addressed through a gateway/proxy that
16
+ * emulates their wire protocol.
17
+ */
18
+ path?: string;
19
+ /**
20
+ * Env var carrying a base-URL override for this provider, using the same
21
+ * name the provider's own SDK reads. Consulted by
22
+ * {@link resolveProviderModelsUrl} when no explicit base URL is passed.
23
+ */
24
+ baseUrlEnv?: string;
12
25
  headers: (key: string) => Record<string, string>;
13
26
  queryParam?: string;
14
27
  }
15
28
  export declare const PROVIDER_ENDPOINTS: Record<string, ProviderEndpoint>;
29
+ /**
30
+ * Resolve the models-list URL for a provider, honouring a configured base URL.
31
+ *
32
+ * Behind a gateway (LiteLLM, a corporate proxy, an Anthropic-compatible
33
+ * router) the credential in play is the *gateway's*, not the provider's. Firing
34
+ * discovery at the provider's own public API therefore 401s and yields an empty
35
+ * catalog — which a caller that reads "empty" as "unknown" then degrades into
36
+ * "accept anything". Resolving against the same base URL the runtime already
37
+ * routes completions through keeps discovery and dispatch pointed at one place.
38
+ *
39
+ * Precedence: explicit `baseUrl` argument → the endpoint's `baseUrlEnv` value
40
+ * in `env` → the provider's own `url`. A provider with no `path` has no
41
+ * gateway form and always returns `url`.
42
+ *
43
+ * The base URL is joined tolerantly: a trailing slash is stripped, and a base
44
+ * that already ends in the path's leading version segment (`…/v1` for a
45
+ * `/v1/models` path) is not doubled up. Both spellings are common in the wild.
46
+ *
47
+ * Pure: reads only the `env` record it is handed.
48
+ *
49
+ * @since 1.5.0
50
+ */
51
+ export declare function resolveProviderModelsUrl(provider: string, options?: {
52
+ baseUrl?: string;
53
+ env?: Record<string, string | undefined>;
54
+ }): string | undefined;
16
55
  //# sourceMappingURL=provider-endpoints.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"provider-endpoints.d.ts","sourceRoot":"","sources":["../../../bridge/src/provider-endpoints.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,gEAAgE;AAChE,MAAM,WAAW,gBAAgB;IAC/B,GAAG,EAAE,MAAM,CAAC;IACZ,OAAO,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjD,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,eAAO,MAAM,kBAAkB,EAAE,MAAM,CAAC,MAAM,EAAE,gBAAgB,CA0C/D,CAAC"}
1
+ {"version":3,"file":"provider-endpoints.d.ts","sourceRoot":"","sources":["../../../bridge/src/provider-endpoints.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,gEAAgE;AAChE,MAAM,WAAW,gBAAgB;IAC/B,kEAAkE;IAClE,GAAG,EAAE,MAAM,CAAC;IACZ;;;;OAIG;IACH,IAAI,CAAC,EAAE,MAAM,CAAC;IACd;;;;OAIG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,OAAO,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACjD,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,eAAO,MAAM,kBAAkB,EAAE,MAAM,CAAC,MAAM,EAAE,gBAAgB,CA8C/D,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,wBAAwB,CACtC,QAAQ,EAAE,MAAM,EAChB,OAAO,GAAE;IAAE,OAAO,CAAC,EAAE,MAAM,CAAC;IAAC,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAA;CAAO,GAC3E,MAAM,GAAG,SAAS,CAUpB"}
@@ -20,8 +20,13 @@ export interface ValidationResult {
20
20
  * @param provider - Provider name matching a key in the shared `PROVIDER_ENDPOINTS` map
21
21
  * (e.g. `"anthropic"`, `"openai"`, `"google"`).
22
22
  * @param key - API key to validate.
23
+ * @param options - Optional base-URL / environment overrides; defaults to the
24
+ * provider's own API, or its `baseUrlEnv` value when one is set.
23
25
  * @returns Validation result with optional error description.
24
26
  * @docLink packages/bridge/api-reference#validation
25
27
  */
26
- export declare function validateApiKey(provider: string, key: string): Promise<ValidationResult>;
28
+ export declare function validateApiKey(provider: string, key: string, options?: {
29
+ baseUrl?: string;
30
+ env?: Record<string, string | undefined>;
31
+ }): Promise<ValidationResult>;
27
32
  //# sourceMappingURL=validation.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"validation.d.ts","sourceRoot":"","sources":["../../../bridge/src/validation.ts"],"names":[],"mappings":"AAAA,kGAAkG;AAIlG;;;;GAIG;AACH,MAAM,WAAW,gBAAgB;IAC/B,8EAA8E;IAC9E,EAAE,EAAE,OAAO,CAAC;IACZ,6DAA6D;IAC7D,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED;;;;;;;;;;;;GAYG;AACH,wBAAsB,cAAc,CAAC,QAAQ,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,CAAC,CA8B7F"}
1
+ {"version":3,"file":"validation.d.ts","sourceRoot":"","sources":["../../../bridge/src/validation.ts"],"names":[],"mappings":"AAAA,kGAAkG;AAIlG;;;;GAIG;AACH,MAAM,WAAW,gBAAgB;IAC/B,8EAA8E;IAC9E,EAAE,EAAE,OAAO,CAAC;IACZ,6DAA6D;IAC7D,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,cAAc,CAClC,QAAQ,EAAE,MAAM,EAChB,GAAG,EAAE,MAAM,EACX,OAAO,GAAE;IAAE,OAAO,CAAC,EAAE,MAAM,CAAC;IAAC,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAA;CAAO,GAC3E,OAAO,CAAC,gBAAgB,CAAC,CAoC3B"}
@@ -1,4 +1,4 @@
1
- import { fsDeadlineMs, withFsDeadline, tryWithFsDeadline } from './chunk-VQ4P7UYE.js';
1
+ import { fsDeadlineMs, withFsDeadline, tryWithFsDeadline } from './chunk-MKZOK4JU.js';
2
2
  import { createReadStream, createWriteStream } from 'fs';
3
3
  import { readdir, stat, rename, unlink } from 'fs/promises';
4
4
  import { join } from 'path';
@@ -292,5 +292,5 @@ async function probeResumeTranscript(sessionId, opts) {
292
292
  }
293
293
 
294
294
  export { CLOUD_SECRET_ENV_KEYS, SUPPORTED_CLOUDS, buildClaudeCloudEnv, probeResumeTranscript, resolveClaudeConfigDir, scrubPoisonedTranscript };
295
- //# sourceMappingURL=chunk-RUFTB7QN.js.map
296
- //# sourceMappingURL=chunk-RUFTB7QN.js.map
295
+ //# sourceMappingURL=chunk-3NCGSSCU.js.map
296
+ //# sourceMappingURL=chunk-3NCGSSCU.js.map
@@ -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,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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,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,SAAS,GAAI,SAAA,IAAa,EAAC,EAAG;AAGvE,EAAA,MAAM,OAAA,GAAU;AAAA,IACd,WAAW,GAAA,CAAI,oBAAA;AAAA,IACf,QAAQ,GAAA,CAAI,iBAAA;AAAA,IACZ,SAAS,GAAA,CAAI;AAAA,GACf;AAEA,EAAA,KAAA,MAAW,GAAA,IAAO,MAAA,CAAO,IAAA,CAAK,GAAG,CAAA,EAAG;AAClC,IAAA,IAAI,kBAAkB,QAAA,CAAS,GAAG,KAAK,GAAA,CAAI,UAAA,CAAW,kBAAkB,CAAA,EAAG;AACzE,MAAA,OAAO,IAAI,GAAG,CAAA;AAAA,IAChB;AAAA,EACF;AAEA,EAAA,MAAM,GAAA,G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AuB,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-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