@skaile/workspaces 4.30.0 → 4.31.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 (183) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/app-sdk/index.js +1 -1
  3. package/dist/{asset-feeds-K7N37CGF.js → asset-feeds-XNL4NQBM.js} +7 -7
  4. package/dist/{asset-feeds-K7N37CGF.js.map → asset-feeds-XNL4NQBM.js.map} +1 -1
  5. package/dist/asset-manager/catalog-deployer.js +3 -3
  6. package/dist/asset-manager/index.js +6 -6
  7. package/dist/asset-manager/installer.js +4 -4
  8. package/dist/bridge/drivers/claude-sdk.js +105 -17
  9. package/dist/bridge/drivers/claude-sdk.js.map +1 -1
  10. package/dist/bridge/drivers/codex.js +7 -7
  11. package/dist/bridge/drivers/continue.js +7 -7
  12. package/dist/bridge/drivers/echo.js +5 -5
  13. package/dist/bridge/drivers/gemini.js +8 -8
  14. package/dist/bridge/drivers/goose.js +7 -7
  15. package/dist/bridge/drivers/omp.js +8 -8
  16. package/dist/bridge/drivers/opencode.js +7 -7
  17. package/dist/bridge/drivers/qwen.js +8 -8
  18. package/dist/bridge/index.js +11 -11
  19. package/dist/bridge/src/drivers/claude-sdk.d.ts +24 -0
  20. package/dist/bridge/src/drivers/claude-sdk.d.ts.map +1 -1
  21. package/dist/bridge/src/error-classifier.d.ts +13 -0
  22. package/dist/bridge/src/error-classifier.d.ts.map +1 -1
  23. package/dist/bridge/src/types.d.ts +15 -0
  24. package/dist/bridge/src/types.d.ts.map +1 -1
  25. package/dist/{chunk-3FVL4TBA.js → chunk-2RIM7HAG.js} +8 -8
  26. package/dist/{chunk-3FVL4TBA.js.map → chunk-2RIM7HAG.js.map} +1 -1
  27. package/dist/{chunk-IJTEDXWQ.js → chunk-3ZE7X5Y6.js} +3 -3
  28. package/dist/{chunk-IJTEDXWQ.js.map → chunk-3ZE7X5Y6.js.map} +1 -1
  29. package/dist/{chunk-MLM5JZAQ.js → chunk-4UGEZIMA.js} +4 -4
  30. package/dist/{chunk-MLM5JZAQ.js.map → chunk-4UGEZIMA.js.map} +1 -1
  31. package/dist/{chunk-UQ3JFN4N.js → chunk-54A5QAIV.js} +2 -2
  32. package/dist/{chunk-UQ3JFN4N.js.map → chunk-54A5QAIV.js.map} +1 -1
  33. package/dist/{chunk-KOVAB6W2.js → chunk-5KJLMR23.js} +5 -5
  34. package/dist/{chunk-KOVAB6W2.js.map → chunk-5KJLMR23.js.map} +1 -1
  35. package/dist/{chunk-TU2UTFVG.js → chunk-7ZXENJLO.js} +4 -4
  36. package/dist/{chunk-TU2UTFVG.js.map → chunk-7ZXENJLO.js.map} +1 -1
  37. package/dist/{chunk-RLIISQHO.js → chunk-A62RPNIZ.js} +4 -4
  38. package/dist/{chunk-RLIISQHO.js.map → chunk-A62RPNIZ.js.map} +1 -1
  39. package/dist/{chunk-HNWYNNIX.js → chunk-ATRQ2PKM.js} +2 -2
  40. package/dist/{chunk-HNWYNNIX.js.map → chunk-ATRQ2PKM.js.map} +1 -1
  41. package/dist/{chunk-K575XNKG.js → chunk-AVXSY4WO.js} +4 -4
  42. package/dist/{chunk-K575XNKG.js.map → chunk-AVXSY4WO.js.map} +1 -1
  43. package/dist/{chunk-UFWADBG6.js → chunk-BR2IXOWX.js} +3 -3
  44. package/dist/{chunk-UFWADBG6.js.map → chunk-BR2IXOWX.js.map} +1 -1
  45. package/dist/{chunk-CFKJQDPA.js → chunk-CMHRZOHQ.js} +5 -5
  46. package/dist/{chunk-CFKJQDPA.js.map → chunk-CMHRZOHQ.js.map} +1 -1
  47. package/dist/{chunk-GHX6XFLY.js → chunk-D6L7RQGP.js} +9 -9
  48. package/dist/{chunk-GHX6XFLY.js.map → chunk-D6L7RQGP.js.map} +1 -1
  49. package/dist/{chunk-TJRNJVGU.js → chunk-EINLFFP6.js} +3 -3
  50. package/dist/{chunk-TJRNJVGU.js.map → chunk-EINLFFP6.js.map} +1 -1
  51. package/dist/{chunk-GHLJV2FY.js → chunk-FF5L6IV3.js} +3 -3
  52. package/dist/{chunk-GHLJV2FY.js.map → chunk-FF5L6IV3.js.map} +1 -1
  53. package/dist/{chunk-LIWDDZO2.js → chunk-GH3BHLBF.js} +6 -6
  54. package/dist/{chunk-LIWDDZO2.js.map → chunk-GH3BHLBF.js.map} +1 -1
  55. package/dist/{chunk-PE3A6FFW.js → chunk-HCYS7GFP.js} +3 -3
  56. package/dist/{chunk-PE3A6FFW.js.map → chunk-HCYS7GFP.js.map} +1 -1
  57. package/dist/{chunk-XFWB3KFV.js → chunk-HL6SZ7Z3.js} +3 -3
  58. package/dist/{chunk-XFWB3KFV.js.map → chunk-HL6SZ7Z3.js.map} +1 -1
  59. package/dist/{chunk-DPLIN2RA.js → chunk-ICSCSM5D.js} +3 -3
  60. package/dist/{chunk-DPLIN2RA.js.map → chunk-ICSCSM5D.js.map} +1 -1
  61. package/dist/{chunk-3W4SDHJP.js → chunk-J3UD57GK.js} +45 -29
  62. package/dist/chunk-J3UD57GK.js.map +1 -0
  63. package/dist/{chunk-YVWUHPQW.js → chunk-JULFGNQN.js} +3 -3
  64. package/dist/{chunk-YVWUHPQW.js.map → chunk-JULFGNQN.js.map} +1 -1
  65. package/dist/{chunk-324NAWHN.js → chunk-JV2YHKOY.js} +7 -7
  66. package/dist/{chunk-324NAWHN.js.map → chunk-JV2YHKOY.js.map} +1 -1
  67. package/dist/{chunk-527MPCTU.js → chunk-JXTW3VCT.js} +4 -4
  68. package/dist/{chunk-527MPCTU.js.map → chunk-JXTW3VCT.js.map} +1 -1
  69. package/dist/{chunk-6S5KL76M.js → chunk-LX3FKVLL.js} +3 -3
  70. package/dist/{chunk-6S5KL76M.js.map → chunk-LX3FKVLL.js.map} +1 -1
  71. package/dist/{chunk-OHON7XSG.js → chunk-M42SMH7V.js} +3 -3
  72. package/dist/{chunk-OHON7XSG.js.map → chunk-M42SMH7V.js.map} +1 -1
  73. package/dist/{chunk-GZZPKAV5.js → chunk-MJHSLODD.js} +20 -3
  74. package/dist/chunk-MJHSLODD.js.map +1 -0
  75. package/dist/{chunk-NQOE57Q7.js → chunk-MX7LCQUQ.js} +4 -4
  76. package/dist/{chunk-NQOE57Q7.js.map → chunk-MX7LCQUQ.js.map} +1 -1
  77. package/dist/{chunk-KKBXGPJE.js → chunk-NHABMUXY.js} +5 -5
  78. package/dist/{chunk-KKBXGPJE.js.map → chunk-NHABMUXY.js.map} +1 -1
  79. package/dist/{chunk-MZQOSE2X.js → chunk-OGPNWRWU.js} +5 -5
  80. package/dist/{chunk-MZQOSE2X.js.map → chunk-OGPNWRWU.js.map} +1 -1
  81. package/dist/{chunk-CYX7TIWL.js → chunk-RTQTWQHW.js} +3 -3
  82. package/dist/{chunk-CYX7TIWL.js.map → chunk-RTQTWQHW.js.map} +1 -1
  83. package/dist/{chunk-C5OSO7HJ.js → chunk-VYNIZDAD.js} +3 -3
  84. package/dist/{chunk-C5OSO7HJ.js.map → chunk-VYNIZDAD.js.map} +1 -1
  85. package/dist/{chunk-RHXRXTBO.js → chunk-WORPEN3X.js} +4 -4
  86. package/dist/{chunk-RHXRXTBO.js.map → chunk-WORPEN3X.js.map} +1 -1
  87. package/dist/{chunk-UWU572Q6.js → chunk-WPISSDEI.js} +3 -3
  88. package/dist/{chunk-UWU572Q6.js.map → chunk-WPISSDEI.js.map} +1 -1
  89. package/dist/{chunk-BGY4KTU6.js → chunk-XBSQ4KMC.js} +10 -3
  90. package/dist/chunk-XBSQ4KMC.js.map +1 -0
  91. package/dist/{chunk-X22NBPTU.js → chunk-XSVWRISC.js} +7 -7
  92. package/dist/{chunk-X22NBPTU.js.map → chunk-XSVWRISC.js.map} +1 -1
  93. package/dist/cli/index.js +65 -56
  94. package/dist/cli/index.js.map +1 -1
  95. package/dist/cli/src/commands/serve.d.ts +5 -0
  96. package/dist/cli/src/commands/serve.d.ts.map +1 -1
  97. package/dist/connectors/index.js +14 -14
  98. package/dist/connectors-shared/index.js +2 -2
  99. package/dist/core/index.js +3 -3
  100. package/dist/core/provider-registry-credentials.js +2 -2
  101. package/dist/core/provider-registry.js +1 -1
  102. package/dist/core/src/index.d.ts +1 -1
  103. package/dist/core/src/index.d.ts.map +1 -1
  104. package/dist/core/src/provider-registry.d.ts +10 -0
  105. package/dist/core/src/provider-registry.d.ts.map +1 -1
  106. package/dist/deploy/index.js +3 -3
  107. package/dist/{ensure-sources-OGAOMNTT.js → ensure-sources-NEZZ6YY7.js} +9 -9
  108. package/dist/{ensure-sources-OGAOMNTT.js.map → ensure-sources-NEZZ6YY7.js.map} +1 -1
  109. package/dist/factory-assets/connectors/box.js +14 -14
  110. package/dist/factory-assets/connectors/deploy.js +14 -14
  111. package/dist/factory-assets/connectors/devserver.js +14 -14
  112. package/dist/factory-assets/connectors/flow/adapter.js +14 -14
  113. package/dist/factory-assets/connectors/flow/engine.js +4 -4
  114. package/dist/factory-assets/connectors/flow/run-flow.js +15 -15
  115. package/dist/factory-assets/connectors/flow.js +14 -14
  116. package/dist/factory-assets/connectors/git.js +14 -14
  117. package/dist/factory-assets/connectors/gmail.js +14 -14
  118. package/dist/factory-assets/connectors/googledrive.js +14 -14
  119. package/dist/factory-assets/connectors/local.js +14 -14
  120. package/dist/factory-assets/connectors/mattermost.js +14 -14
  121. package/dist/factory-assets/connectors/memory.js +14 -14
  122. package/dist/factory-assets/connectors/minio.js +14 -14
  123. package/dist/factory-assets/connectors/postgres.js +14 -14
  124. package/dist/factory-assets/connectors/s3.js +14 -14
  125. package/dist/factory-assets/connectors/sharepoint.js +14 -14
  126. package/dist/factory-assets/connectors/sqlite.js +14 -14
  127. package/dist/factory-assets/connectors/static-server.js +14 -14
  128. package/dist/factory-assets/connectors/tunnel.js +14 -14
  129. package/dist/factory-assets/connectors/webdav.js +14 -14
  130. package/dist/factory-assets/connectors/xstate-store.js +14 -14
  131. package/dist/factory-assets/connectors/xstate.js +14 -14
  132. package/dist/{flows-6WUQ2J4X.js → flows-QTUSWYKY.js} +6 -6
  133. package/dist/{flows-6WUQ2J4X.js.map → flows-QTUSWYKY.js.map} +1 -1
  134. package/dist/{helpers-AS2CN7BJ.js → helpers-XJEFDCMQ.js} +9 -9
  135. package/dist/{helpers-AS2CN7BJ.js.map → helpers-XJEFDCMQ.js.map} +1 -1
  136. package/dist/library/index.js +4 -4
  137. package/dist/{library-publish-SXQAWWPG.js → library-publish-N726WYMF.js} +13 -13
  138. package/dist/{library-publish-SXQAWWPG.js.map → library-publish-N726WYMF.js.map} +1 -1
  139. package/dist/{open-library-UVAFPWK7.js → open-library-D6ACC3TX.js} +11 -11
  140. package/dist/{open-library-UVAFPWK7.js.map → open-library-D6ACC3TX.js.map} +1 -1
  141. package/dist/{paths-6VH76QLZ.js → paths-IOOMNHTC.js} +5 -5
  142. package/dist/{paths-6VH76QLZ.js.map → paths-IOOMNHTC.js.map} +1 -1
  143. package/dist/{plugin-store-4MXOIEHP.js → plugin-store-OIIPB2MQ.js} +5 -5
  144. package/dist/{plugin-store-4MXOIEHP.js.map → plugin-store-OIIPB2MQ.js.map} +1 -1
  145. package/dist/{project-MHUUWPCN.js → project-NRCGUOM4.js} +10 -10
  146. package/dist/{project-MHUUWPCN.js.map → project-NRCGUOM4.js.map} +1 -1
  147. package/dist/resolver/index.js +3 -3
  148. package/dist/runner/index.js +20 -20
  149. package/dist/runner/src/serve.d.ts +6 -0
  150. package/dist/runner/src/serve.d.ts.map +1 -1
  151. package/dist/runner/src/session-builder.d.ts +7 -1
  152. package/dist/runner/src/session-builder.d.ts.map +1 -1
  153. package/dist/sdk/asset-manager.js +6 -6
  154. package/dist/sdk/bridge.js +11 -11
  155. package/dist/sdk/core.js +3 -3
  156. package/dist/sdk/flow.js +4 -4
  157. package/dist/sdk/index.js +20 -20
  158. package/dist/sdk/resolver.js +3 -3
  159. package/dist/sdk/runner.js +20 -20
  160. package/dist/sdk/session.js +2 -2
  161. package/dist/sdk/types.js +1 -1
  162. package/dist/session/index.js +2 -2
  163. package/dist/{setup-NQKJXRK5.js → setup-3GHCXHOO.js} +18 -18
  164. package/dist/{setup-NQKJXRK5.js.map → setup-3GHCXHOO.js.map} +1 -1
  165. package/dist/{skills-FA4VQEO7.js → skills-DH75K326.js} +5 -5
  166. package/dist/{skills-FA4VQEO7.js.map → skills-DH75K326.js.map} +1 -1
  167. package/dist/{source-T7DWNSDN.js → source-OAIEGNQB.js} +12 -12
  168. package/dist/{source-T7DWNSDN.js.map → source-OAIEGNQB.js.map} +1 -1
  169. package/dist/{source-manifest-publish-WBAWFUHX.js → source-manifest-publish-DQTXHT4V.js} +14 -14
  170. package/dist/{source-manifest-publish-WBAWFUHX.js.map → source-manifest-publish-DQTXHT4V.js.map} +1 -1
  171. package/dist/tui/index.js +20 -20
  172. package/dist/types/index.js +1 -1
  173. package/dist/types/src/events.d.ts +8 -0
  174. package/dist/types/src/events.d.ts.map +1 -1
  175. package/dist/types/src/version.d.ts +8 -1
  176. package/dist/types/src/version.d.ts.map +1 -1
  177. package/dist/workspace-plugin/adapters/mcp.js +6 -6
  178. package/dist/workspace-plugin/adapters/omp.js +7 -7
  179. package/dist/workspace-plugin/index.js +1 -1
  180. package/package.json +1 -1
  181. package/dist/chunk-3W4SDHJP.js.map +0 -1
  182. package/dist/chunk-BGY4KTU6.js.map +0 -1
  183. package/dist/chunk-GZZPKAV5.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../bridge/src/cloud.ts","../bridge/src/drivers/scrub-transcript.ts","../bridge/src/agent-transcript.ts","../bridge/src/drivers/resume-probe.ts"],"names":["join"],"mappings":";;;;;;;;;;;AAuCA,IAAM,iBAAA,GAAoB,CAAC,mBAAA,EAAqB,sBAAA,EAAwB,oBAAoB,CAAA;AAQrF,IAAM,0BAAA,GAA6B;AAQ1C,IAAM,iBAAA,GAA0C;AAAA,EAC9C,mBAAA,EAAqB,IAAA;AAAA,EACrB,aAAA,EAAe,IAAA;AAAA,EACf,WAAA,EAAa;AACf,CAAA;AAcO,SAAS,mBAAmB,KAAA,EAA4C;AAC7E,EAAA,MAAM,UAAW,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AA,EACxB,CAAA,SAAE;AACA,IAAA,YAAA,CAAa,KAAK,CAAA;AAAA,EACpB;AACF;AC5LA,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-6S5KL76M.js","sourcesContent":["/**\n * AI endpoint transport for the `claude-sdk` driver — the Claude Agent SDK's\n * child-process environment.\n *\n * {@link buildClaudeEndpointEnv} takes an **AI provider registry entry** and\n * is what the driver calls, on every transport. It is plan §2.3's\n * `buildEndpointEnv` for the claude-sdk row (named for the driver because the\n * vars it emits — `CLAUDE_CODE_USE_*`, `ANTHROPIC_*` — are the Claude Agent\n * SDK's own contract, not a portable one).\n *\n * A registry entry says what the deleted `cloud` axis said — Amazon Bedrock,\n * Google Vertex AI, Azure AI Foundry, a generic gateway — with `surface` +\n * `transport` + `base_url` + `credential`, and says it for the direct\n * endpoint too, which the `cloud` axis could not address at all.\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\nimport {\n type AIProviderEntry,\n type AIProviderLlmEntry,\n entryTransport,\n normalizeAnthropicBaseUrl,\n resolveEntryBaseUrl,\n} from \"@skaile/workspaces/core/provider-registry\";\n\n/**\n * Env vars scrubbed from the inherited environment before an endpoint env is\n * assembled. Ambient first-party credentials or a stale `CLAUDE_CODE_USE_*`\n * flag must never leak into a session whose entry points elsewhere (the\n * ambient carriers are restored explicitly when the entry has none of its\n * own).\n *\n * Deliberately NOT exhaustive: ambient transport-specific vars (AWS_*,\n * GOOGLE_*, ANTHROPIC_VERTEX_PROJECT_ID, ANTHROPIC_FOUNDRY_*) survive so a\n * standalone CLI inherits its own signing chain; the SDK ignores vars whose\n * transport flag is unset.\n */\nconst SCRUBBED_ENV_KEYS = [\"ANTHROPIC_API_KEY\", \"ANTHROPIC_AUTH_TOKEN\", \"ANTHROPIC_BASE_URL\"];\n\n/**\n * The Anthropic first-party endpoint. An entry that resolves to exactly this\n * host needs no `ANTHROPIC_BASE_URL`: the SDK already points there, and an\n * explicit value would make every default session look like a third-party\n * redirect to Claude Code's own telemetry and auth heuristics.\n */\nexport const ANTHROPIC_DEFAULT_BASE_URL = \"https://api.anthropic.com\";\n\n/**\n * Headers the SDK owns and an entry must not restate through\n * `ANTHROPIC_CUSTOM_HEADERS`: the protocol version it was built against, and\n * the two credential carriers (which are `credential.ref`'s job — a literal\n * secret in `headers` is a validation error anyway).\n */\nconst SDK_OWNED_HEADERS: Record<string, true> = {\n \"anthropic-version\": true,\n authorization: true,\n \"x-api-key\": true,\n};\n\n/**\n * Which of the Claude Agent SDK's four native transports an entry addresses.\n *\n * The SDK has no `transport` field: it switches on a `CLAUDE_CODE_USE_*` flag.\n * Bedrock and Vertex are their own wire surfaces, so they are recognized by\n * `surface` as well as by `transport` — a legacy-derived entry that had no\n * region (and therefore no `params`, and therefore no `transport`) is still a\n * Bedrock session, exactly as it was before the registry existed.\n */\nexport type ClaudeEndpointMode = \"anthropic\" | \"bedrock\" | \"vertex\" | \"foundry\";\n\n/** Classify a registry entry into its {@link ClaudeEndpointMode}. */\nexport function claudeEndpointMode(entry: AIProviderEntry): ClaudeEndpointMode {\n const surface = (entry as AIProviderLlmEntry).surface;\n const transport = entryTransport(entry);\n if (surface === \"bedrock-converse-stream\" || transport === \"bedrock\") return \"bedrock\";\n if (surface === \"google-vertex\" || transport === \"vertex\") return \"vertex\";\n if (transport === \"foundry\") return \"foundry\";\n return \"anthropic\";\n}\n\n/** Arguments for {@link buildClaudeEndpointEnv}. */\nexport interface ClaudeEndpointEnvInput {\n /** The selected registry entry — the whole endpoint definition. */\n entry: AIProviderEntry;\n /**\n * The entry's credential, already resolved from its `credential.ref`\n * (`resolveEntryCredential`). Absent for `kind: none`, for an ambient\n * `sigv4` / `google_adc` / `azure_entra` chain, for `oauth` (whose blob the\n * runner writes to the Claude credentials file, never to the env), and for a\n * reference that did not resolve.\n */\n credential?: string;\n /**\n * The driver's base environment — `process.env` with `undefined` dropped.\n * The endpoint vars are layered **on top** of it, never instead of it, so\n * `PATH`, `HOME` and `SKAILE_SESSION_ID` reach the child.\n */\n baseEnv: Record<string, string>;\n /** `AgentConfig.env` plus any credential material the session carried. */\n configEnv?: Record<string, string>;\n}\n\n/**\n * Assemble the Claude Agent SDK child env for one registry entry (plan §2.3).\n *\n * Pure (no external state read, no input mutated). Starts from `baseEnv`\n * merged with `configEnv`, scrubs the inherited Anthropic credential/routing\n * vars and every `CLAUDE_CODE_USE_*` flag, then writes exactly what the entry\n * describes: at most one transport flag, the endpoint, and the credential in\n * the carrier its `kind` names.\n *\n * Credential kinds (§1.4): `api_key_header` → `ANTHROPIC_API_KEY` (the SDK\n * sends it as `x-api-key`); `bearer` → `ANTHROPIC_AUTH_TOKEN` (sent as\n * `Authorization: Bearer`); `sigv4` / `google_adc` / `azure_entra` emit\n * nothing and let the AWS/Google/Azure chain sign — which is why the scrub\n * deliberately spares ambient `AWS_*` / `GOOGLE_*` values; `oauth` and `none`\n * emit nothing, and the pre-scrub ambient carriers are restored so an OAuth or\n * shell-configured session keeps the auth it had.\n *\n * Never returns `undefined` or empty values; absent settings are omitted.\n */\nexport function buildClaudeEndpointEnv(args: ClaudeEndpointEnvInput): Record<string, string> {\n const { entry, credential, baseEnv, configEnv } = args;\n const env: Record<string, string> = { ...baseEnv, ...(configEnv ?? {}) };\n\n // Captured before the scrub — an entry with no credential material of its\n // own falls back to these, the way the gateway branch always has.\n const ambient = { authToken: env.ANTHROPIC_AUTH_TOKEN, apiKey: env.ANTHROPIC_API_KEY };\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 const kind = entry.credential?.kind ?? \"none\";\n const params = (entry as AIProviderLlmEntry).params as Record<string, string> | undefined;\n\n // Static headers ride as ANTHROPIC_CUSTOM_HEADERS (`Name: Value` per line),\n // the only channel the SDK offers. An entry with none leaves an ambient\n // value alone.\n const headers = Object.entries(entry.headers ?? {}).filter(\n ([name]) => !SDK_OWNED_HEADERS[name.toLowerCase()],\n );\n if (headers.length > 0) {\n env.ANTHROPIC_CUSTOM_HEADERS = headers.map(([name, value]) => `${name}: ${value}`).join(\"\\n\");\n }\n\n switch (claudeEndpointMode(entry)) {\n case \"bedrock\": {\n env.CLAUDE_CODE_USE_BEDROCK = \"1\";\n // The AWS credential bundle itself is `configEnv` material (AWS_*), and\n // ambient AWS_* survived the scrub, so a standalone CLI keeps its own.\n set(\"AWS_REGION\", params?.region);\n break;\n }\n case \"vertex\": {\n env.CLAUDE_CODE_USE_VERTEX = \"1\";\n // GOOGLE_APPLICATION_CREDENTIALS is a path the runner materialized; it\n // arrives through `configEnv` or ambient, never from `credential`.\n set(\"ANTHROPIC_VERTEX_PROJECT_ID\", params?.project);\n set(\"CLOUD_ML_REGION\", params?.location);\n break;\n }\n case \"foundry\": {\n env.CLAUDE_CODE_USE_FOUNDRY = \"1\";\n // §1.3: an explicit `base_url` wins over the resource-derived endpoint,\n // and the SDK has a separate var for each form.\n if (entry.base_url) set(\"ANTHROPIC_FOUNDRY_BASE_URL\", entry.base_url);\n else set(\"ANTHROPIC_FOUNDRY_RESOURCE\", params?.resource);\n set(\"ANTHROPIC_FOUNDRY_API_KEY\", credential);\n break;\n }\n case \"anthropic\": {\n const baseUrl = normalizeAnthropicBaseUrl(resolveEntryBaseUrl(entry));\n if (baseUrl && baseUrl.toLowerCase() !== ANTHROPIC_DEFAULT_BASE_URL) {\n env.ANTHROPIC_BASE_URL = baseUrl;\n }\n if (kind === \"bearer\") set(\"ANTHROPIC_AUTH_TOKEN\", credential);\n else if (kind === \"api_key_header\") set(\"ANTHROPIC_API_KEY\", credential);\n if (!credential) {\n // `oauth` / `none` / an unresolved ref: the ambient carriers are the\n // only auth this session has, and the scrub just removed them.\n if (ambient.authToken) env.ANTHROPIC_AUTH_TOKEN = ambient.authToken;\n else set(\"ANTHROPIC_API_KEY\", ambient.apiKey);\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 * Where the transcript is read and written. Defaults to this process's own\n * filesystem access ({@link localTranscriptStore}); with the agent uid split\n * the transcript belongs to the agent uid and must be reached through it.\n */\n store?: TranscriptStore;\n}\n\n/**\n * Filesystem access to Claude Code transcripts. The CLI creates them 0600 in\n * 0700 dirs, so when it runs as a different uid than the runner, only that uid\n * can locate, read or rewrite them (see `agent-transcript.ts`).\n *\n * @category Transcript repair\n */\nexport interface TranscriptStore {\n /** Path of `<sessionId>.jsonl` under `<configDir>/projects/`, or `null` when absent. */\n locate(configDir: string, sessionId: string, timeoutMs?: number): Promise<string | null>;\n /** The file's contents as UTF-8 chunks. */\n read(filePath: string): AsyncIterable<string>;\n /** Atomically replace the file with `chunks` via a `.scrub-tmp` sibling. */\n replace(filePath: string, chunks: AsyncIterable<string>): Promise<void>;\n /** Remove the sibling a failed or abandoned {@link replace} left (best effort). */\n discardTemp(filePath: string): Promise<void>;\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(chunks: AsyncIterable<string>): AsyncGenerator<string> {\n let pending = \"\";\n for await (const chunk of chunks) {\n pending += chunk;\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}\n\n/**\n * The runner's own filesystem access: the default {@link TranscriptStore}.\n *\n * @category Transcript repair\n */\nexport const localTranscriptStore: TranscriptStore = {\n locate: (configDir, sessionId, timeoutMs) =>\n locateTranscriptPath(configDir, sessionId, timeoutMs),\n async *read(filePath) {\n const stream = createReadStream(filePath, { encoding: \"utf8\" });\n try {\n for await (const chunk of stream) yield chunk as string;\n } finally {\n stream.destroy();\n }\n },\n async replace(filePath, chunks) {\n const tmpPath = `${filePath}.scrub-tmp`;\n await pipeline(chunks, createWriteStream(tmpPath, { encoding: \"utf8\" }));\n await rename(tmpPath, filePath);\n },\n async discardTemp(filePath) {\n const tmpPath = `${filePath}.scrub-tmp`;\n await tryWithFsDeadline(`unlink ${tmpPath}`, () => unlink(tmpPath), undefined, fsDeadlineMs());\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 store = opts.store ?? localTranscriptStore;\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 let filePath: string | null;\n try {\n filePath = await store.locate(configDir, sessionId, timeoutMs);\n } catch (err) {\n log?.warn(\"scrub-transcript: failed to locate transcript\", {\n configDir,\n sessionId,\n error: err instanceof Error ? err.message : String(err),\n });\n return result;\n }\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(store.read(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 source = filePath;\n try {\n await withFsDeadline(\n `rewrite transcript ${source}`,\n async () => {\n const discard: ScrubCounters = { corrected: 0, stubbed: 0, cacheStripped: 0 };\n await store.replace(\n source,\n (async function* () {\n let first = true;\n for await (const line of streamLines(store.read(source))) {\n yield first ? repairLine(line, discard) : `\\n${repairLine(line, discard)}`;\n first = false;\n }\n })(),\n );\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 `.scrub-tmp` in the SDK's projects dir, also\n // when the deadline abandoned the replace mid-write.\n await store.discardTemp(source).catch(() => {});\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","import { type ChildProcess, spawn } from \"node:child_process\";\nimport { join } from \"node:path\";\nimport { fsDeadlineMs, withFsDeadline } from \"@skaile/workspaces/core\";\nimport { resolveAgentExec } from \"./agent-exec.js\";\nimport { localTranscriptStore, type TranscriptStore } from \"./drivers/scrub-transcript.js\";\n\n/**\n * Transcripts reached through the agent launch shim.\n *\n * With the uid split on, the Claude CLI runs as the agent uid and creates its\n * transcripts 0600 in 0700 dirs, so the runner can no longer list, read or\n * rewrite them itself. This store runs plain tools (`find`, `cat`, `sh`, `mv`)\n * as the agent uid through the shim instead. The child gets only `PATH` and\n * `LC_ALL`, never the runner's environment, and runs in `/` because the\n * runner's own cwd may not be enterable by the agent uid.\n */\nexport function agentTranscriptStore(shim: string): TranscriptStore {\n // A replace the scrub's deadline abandoned keeps running; discardTemp stops\n // it before removing its temp file.\n const inFlight = new Map<string, ChildProcess>();\n // Paths whose rewrite discardTemp gave up on: their rename must never run.\n const cancelled = new Set<string>();\n const track = (filePath: string, child: ChildProcess) => {\n inFlight.set(filePath, child);\n child.once(\"close\", () => {\n if (inFlight.get(filePath) === child) inFlight.delete(filePath);\n });\n };\n return {\n async locate(configDir, sessionId, timeoutMs = 10_000) {\n // A session id is a UUID; anything glob- or path-shaped is not ours.\n if (!/^[A-Za-z0-9._-]+$/.test(sessionId)) return null;\n const projectsDir = join(configDir, \"projects\");\n // Markers on stdout, not exit codes, carry the answer: a shim or launcher\n // failure has exit codes of its own and must never read as \"not found\".\n const { stdout } = await collect(\n runAsAgent(shim, [\n \"sh\",\n \"-c\",\n '[ -d \"$1\" ] || { echo \"@@no-projects\"; exit 0; }; ' +\n 'find \"$1\" -mindepth 2 -maxdepth 2 -type f -name \"$2\" -print -quit; echo \"@@find:$?\"',\n \"sh\",\n projectsDir,\n `${sessionId}.jsonl`,\n ]),\n timeoutMs,\n );\n const lines = stdout.split(\"\\n\").map((l) => l.trim());\n // A missing projects/ is the same \"not found\" as a failed readdir locally.\n if (lines.includes(\"@@no-projects\")) return null;\n const status = lines.find((l) => l.startsWith(\"@@find:\"));\n if (status === undefined)\n throw new Error(\"locating a transcript as the agent uid failed (no answer from the shim)\");\n // A path find printed counts even if it later hit an unreadable sibling.\n const found = lines.find((l) => l.startsWith(\"/\"));\n if (found) return found;\n if (status !== \"@@find:0\")\n throw new Error(`locating a transcript as the agent uid failed (${status.slice(2)})`);\n return null;\n },\n\n async *read(filePath) {\n const child = runAsAgent(shim, [\"cat\", \"--\", filePath]);\n const exited = exitOf(child);\n exited.catch(() => {}); // awaited below; this only stops an unhandled rejection\n const stderr = drain(child);\n child.stdout?.setEncoding(\"utf8\");\n for await (const chunk of child.stdout as AsyncIterable<string>) yield chunk;\n const code = await exited;\n if (code !== 0)\n throw new Error(`reading ${filePath} as the agent uid failed: ${await stderr}`);\n },\n\n async replace(filePath, chunks) {\n const child = runAsAgent(shim, [\n \"sh\",\n \"-c\",\n // 0600 like the CLI's own files. Only writes the temp file: the rename\n // is a separate step below, run only after the input was fully sent,\n // so a killed or starved writer can never commit a partial transcript.\n 'umask 077; cat > \"$1.scrub-tmp\"',\n \"sh\",\n filePath,\n ]);\n cancelled.delete(filePath);\n track(filePath, child);\n const exited = exitOf(child);\n exited.catch(() => {}); // awaited below; this only stops an unhandled rejection\n const stderr = drain(child);\n const stdin = child.stdin;\n if (!stdin) throw new Error(\"agent shim has no stdin\");\n // A child that dies early surfaces through its exit code, not an EPIPE crash.\n stdin.on(\"error\", () => {});\n const gone = exited.then(\n () => undefined,\n () => undefined,\n );\n // Stop pulling input as soon as the child is gone (killed by discardTemp,\n // or failed), instead of waiting on a producer that may never resume.\n const input = chunks[Symbol.asyncIterator]();\n let drained = false;\n try {\n for (;;) {\n const next = await Promise.race([\n input.next(),\n gone.then(() => ({ dead: true as const })),\n ]);\n if (\"dead\" in next || stdin.destroyed) break;\n if (next.done) {\n drained = true;\n break;\n }\n if (!stdin.write(next.value)) {\n await Promise.race([new Promise((resolve) => stdin.once(\"drain\", resolve)), gone]);\n }\n }\n } finally {\n stdin.end();\n // Close the producer too, so the reader feeding it (a `cat` through\n // the shim) is torn down rather than left blocked on a full pipe.\n if (!drained) void input.return?.()?.catch(() => {});\n }\n const code = await exited;\n if (code !== 0 || !drained)\n throw new Error(`rewriting ${filePath} as the agent uid failed: ${await stderr}`);\n if (cancelled.has(filePath)) throw new Error(`rewrite of ${filePath} was abandoned`);\n const mover = runAsAgent(shim, [\"mv\", \"-f\", \"--\", `${filePath}.scrub-tmp`, filePath]);\n track(filePath, mover);\n const moved = await collect(mover, 10_000);\n if (moved.code !== 0) throw new Error(`renaming the rewritten ${filePath} failed`);\n },\n\n async discardTemp(filePath) {\n // Before anything else, so a writer that is just finishing never renames.\n cancelled.add(filePath);\n const pending = inFlight.get(filePath);\n if (pending && pending.exitCode === null && pending.signalCode === null) {\n // The writer cannot commit (the rename is a separate step), so this only\n // stops it; bounded, since a writer stuck on a hung mount may never die.\n const closed = new Promise((resolve) => pending.once(\"close\", resolve));\n pending.kill(\"SIGKILL\");\n await withFsDeadline(`stop the rewrite of ${filePath}`, () => closed, fsDeadlineMs());\n }\n await collect(runAsAgent(shim, [\"rm\", \"-f\", \"--\", `${filePath}.scrub-tmp`]), 10_000);\n },\n };\n}\n\n/**\n * The transcript store for this runner: through the agent shim when\n * `SKAILE_AGENT_EXEC` is set, the runner's own filesystem otherwise.\n */\nexport function transcriptStoreForRuntime(\n env: Record<string, string | undefined> = process.env,\n): TranscriptStore {\n const shim = resolveAgentExec(env);\n return shim ? agentTranscriptStore(shim) : localTranscriptStore;\n}\n\nfunction runAsAgent(shim: string, argv: string[]): ChildProcess {\n return spawn(shim, [\"--\", ...argv], {\n cwd: \"/\",\n env: { PATH: process.env.PATH ?? \"/usr/bin:/bin\", LC_ALL: \"C\" },\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n });\n}\n\nfunction exitOf(child: ChildProcess): Promise<number> {\n return new Promise((resolve, reject) => {\n child.once(\"error\", reject);\n child.once(\"close\", (code) => resolve(code ?? 1));\n });\n}\n\n/** Keep the last 1 KiB of stderr for the error message, and keep the pipe drained. */\nfunction drain(child: ChildProcess): Promise<string> {\n return new Promise((resolve) => {\n let tail = \"\";\n child.stderr?.setEncoding(\"utf8\");\n child.stderr?.on(\"data\", (c: string) => {\n tail = (tail + c).slice(-1024);\n });\n child.stderr?.once(\"close\", () => resolve(tail.trim()));\n });\n}\n\nasync function collect(\n child: ChildProcess,\n timeoutMs: number,\n): Promise<{ code: number; stdout: string }> {\n let stdout = \"\";\n child.stdout?.setEncoding(\"utf8\");\n child.stdout?.on(\"data\", (c: string) => {\n stdout += c;\n });\n void drain(child);\n child.stdin?.end();\n let timer: NodeJS.Timeout | undefined;\n try {\n const code = await Promise.race([\n exitOf(child),\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n child.kill(\"SIGKILL\");\n reject(new Error(`agent shim did not answer within ${timeoutMs} ms`));\n }, timeoutMs);\n }),\n ]);\n return { code, stdout };\n } finally {\n clearTimeout(timer);\n }\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/agent-transcript.ts","../bridge/src/drivers/resume-probe.ts"],"names":["join"],"mappings":";;;;;;;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AA,EAAG,MAAA,KAAW;AAChC,QAAA,KAAA,GAAQ,WAAW,MAAM;AACvB,UAAA,KAAA,CAAM,KAAK,SAAS,CAAA;AACpB,UAAA,MAAA,CAAO,IAAI,KAAA,CAAM,CAAA,iCAAA,EAAoC,SAAS,KAAK,CAAC,CAAA;AAAA,QACtE,GAAG,SAAS,CAAA;AAAA,MACd,CAAC;AAAA,KACF,CAAA;AACD,IAAA,OAAO,EAAE,MAAM,MAAA,EAAO;AAAA,EACxB,CAAA,SAAE;AACA,IAAA,YAAA,CAAa,KAAK,CAAA;AAAA,EACpB;AACF;AC5LA,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-LX3FKVLL.js","sourcesContent":["/**\n * AI endpoint transport for the `claude-sdk` driver — the Claude Agent SDK's\n * child-process environment.\n *\n * {@link buildClaudeEndpointEnv} takes an **AI provider registry entry** and\n * is what the driver calls, on every transport. It is plan §2.3's\n * `buildEndpointEnv` for the claude-sdk row (named for the driver because the\n * vars it emits — `CLAUDE_CODE_USE_*`, `ANTHROPIC_*` — are the Claude Agent\n * SDK's own contract, not a portable one).\n *\n * A registry entry says what the deleted `cloud` axis said — Amazon Bedrock,\n * Google Vertex AI, Azure AI Foundry, a generic gateway — with `surface` +\n * `transport` + `base_url` + `credential`, and says it for the direct\n * endpoint too, which the `cloud` axis could not address at all.\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\nimport {\n type AIProviderEntry,\n type AIProviderLlmEntry,\n entryTransport,\n normalizeAnthropicBaseUrl,\n resolveEntryBaseUrl,\n} from \"@skaile/workspaces/core/provider-registry\";\n\n/**\n * Env vars scrubbed from the inherited environment before an endpoint env is\n * assembled. Ambient first-party credentials or a stale `CLAUDE_CODE_USE_*`\n * flag must never leak into a session whose entry points elsewhere (the\n * ambient carriers are restored explicitly when the entry has none of its\n * own).\n *\n * Deliberately NOT exhaustive: ambient transport-specific vars (AWS_*,\n * GOOGLE_*, ANTHROPIC_VERTEX_PROJECT_ID, ANTHROPIC_FOUNDRY_*) survive so a\n * standalone CLI inherits its own signing chain; the SDK ignores vars whose\n * transport flag is unset.\n */\nconst SCRUBBED_ENV_KEYS = [\"ANTHROPIC_API_KEY\", \"ANTHROPIC_AUTH_TOKEN\", \"ANTHROPIC_BASE_URL\"];\n\n/**\n * The Anthropic first-party endpoint. An entry that resolves to exactly this\n * host needs no `ANTHROPIC_BASE_URL`: the SDK already points there, and an\n * explicit value would make every default session look like a third-party\n * redirect to Claude Code's own telemetry and auth heuristics.\n */\nexport const ANTHROPIC_DEFAULT_BASE_URL = \"https://api.anthropic.com\";\n\n/**\n * Headers the SDK owns and an entry must not restate through\n * `ANTHROPIC_CUSTOM_HEADERS`: the protocol version it was built against, and\n * the two credential carriers (which are `credential.ref`'s job — a literal\n * secret in `headers` is a validation error anyway).\n */\nconst SDK_OWNED_HEADERS: Record<string, true> = {\n \"anthropic-version\": true,\n authorization: true,\n \"x-api-key\": true,\n};\n\n/**\n * Which of the Claude Agent SDK's four native transports an entry addresses.\n *\n * The SDK has no `transport` field: it switches on a `CLAUDE_CODE_USE_*` flag.\n * Bedrock and Vertex are their own wire surfaces, so they are recognized by\n * `surface` as well as by `transport` — a legacy-derived entry that had no\n * region (and therefore no `params`, and therefore no `transport`) is still a\n * Bedrock session, exactly as it was before the registry existed.\n */\nexport type ClaudeEndpointMode = \"anthropic\" | \"bedrock\" | \"vertex\" | \"foundry\";\n\n/** Classify a registry entry into its {@link ClaudeEndpointMode}. */\nexport function claudeEndpointMode(entry: AIProviderEntry): ClaudeEndpointMode {\n const surface = (entry as AIProviderLlmEntry).surface;\n const transport = entryTransport(entry);\n if (surface === \"bedrock-converse-stream\" || transport === \"bedrock\") return \"bedrock\";\n if (surface === \"google-vertex\" || transport === \"vertex\") return \"vertex\";\n if (transport === \"foundry\") return \"foundry\";\n return \"anthropic\";\n}\n\n/** Arguments for {@link buildClaudeEndpointEnv}. */\nexport interface ClaudeEndpointEnvInput {\n /** The selected registry entry — the whole endpoint definition. */\n entry: AIProviderEntry;\n /**\n * The entry's credential, already resolved from its `credential.ref`\n * (`resolveEntryCredential`). Absent for `kind: none`, for an ambient\n * `sigv4` / `google_adc` / `azure_entra` chain, for `oauth` (whose blob the\n * runner writes to the Claude credentials file, never to the env), and for a\n * reference that did not resolve.\n */\n credential?: string;\n /**\n * The driver's base environment — `process.env` with `undefined` dropped.\n * The endpoint vars are layered **on top** of it, never instead of it, so\n * `PATH`, `HOME` and `SKAILE_SESSION_ID` reach the child.\n */\n baseEnv: Record<string, string>;\n /** `AgentConfig.env` plus any credential material the session carried. */\n configEnv?: Record<string, string>;\n}\n\n/**\n * Assemble the Claude Agent SDK child env for one registry entry (plan §2.3).\n *\n * Pure (no external state read, no input mutated). Starts from `baseEnv`\n * merged with `configEnv`, scrubs the inherited Anthropic credential/routing\n * vars and every `CLAUDE_CODE_USE_*` flag, then writes exactly what the entry\n * describes: at most one transport flag, the endpoint, and the credential in\n * the carrier its `kind` names.\n *\n * Credential kinds (§1.4): `api_key_header` → `ANTHROPIC_API_KEY` (the SDK\n * sends it as `x-api-key`); `bearer` → `ANTHROPIC_AUTH_TOKEN` (sent as\n * `Authorization: Bearer`); `sigv4` / `google_adc` / `azure_entra` emit\n * nothing and let the AWS/Google/Azure chain sign — which is why the scrub\n * deliberately spares ambient `AWS_*` / `GOOGLE_*` values; `oauth` and `none`\n * emit nothing, and the pre-scrub ambient carriers are restored so an OAuth or\n * shell-configured session keeps the auth it had.\n *\n * Never returns `undefined` or empty values; absent settings are omitted.\n */\nexport function buildClaudeEndpointEnv(args: ClaudeEndpointEnvInput): Record<string, string> {\n const { entry, credential, baseEnv, configEnv } = args;\n const env: Record<string, string> = { ...baseEnv, ...(configEnv ?? {}) };\n\n // Captured before the scrub — an entry with no credential material of its\n // own falls back to these, the way the gateway branch always has.\n const ambient = { authToken: env.ANTHROPIC_AUTH_TOKEN, apiKey: env.ANTHROPIC_API_KEY };\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 const kind = entry.credential?.kind ?? \"none\";\n const params = (entry as AIProviderLlmEntry).params as Record<string, string> | undefined;\n\n // Static headers ride as ANTHROPIC_CUSTOM_HEADERS (`Name: Value` per line),\n // the only channel the SDK offers. An entry with none leaves an ambient\n // value alone.\n const headers = Object.entries(entry.headers ?? {}).filter(\n ([name]) => !SDK_OWNED_HEADERS[name.toLowerCase()],\n );\n if (headers.length > 0) {\n env.ANTHROPIC_CUSTOM_HEADERS = headers.map(([name, value]) => `${name}: ${value}`).join(\"\\n\");\n }\n\n switch (claudeEndpointMode(entry)) {\n case \"bedrock\": {\n env.CLAUDE_CODE_USE_BEDROCK = \"1\";\n // The AWS credential bundle itself is `configEnv` material (AWS_*), and\n // ambient AWS_* survived the scrub, so a standalone CLI keeps its own.\n set(\"AWS_REGION\", params?.region);\n break;\n }\n case \"vertex\": {\n env.CLAUDE_CODE_USE_VERTEX = \"1\";\n // GOOGLE_APPLICATION_CREDENTIALS is a path the runner materialized; it\n // arrives through `configEnv` or ambient, never from `credential`.\n set(\"ANTHROPIC_VERTEX_PROJECT_ID\", params?.project);\n set(\"CLOUD_ML_REGION\", params?.location);\n break;\n }\n case \"foundry\": {\n env.CLAUDE_CODE_USE_FOUNDRY = \"1\";\n // §1.3: an explicit `base_url` wins over the resource-derived endpoint,\n // and the SDK has a separate var for each form.\n if (entry.base_url) set(\"ANTHROPIC_FOUNDRY_BASE_URL\", entry.base_url);\n else set(\"ANTHROPIC_FOUNDRY_RESOURCE\", params?.resource);\n set(\"ANTHROPIC_FOUNDRY_API_KEY\", credential);\n break;\n }\n case \"anthropic\": {\n const baseUrl = normalizeAnthropicBaseUrl(resolveEntryBaseUrl(entry));\n if (baseUrl && baseUrl.toLowerCase() !== ANTHROPIC_DEFAULT_BASE_URL) {\n env.ANTHROPIC_BASE_URL = baseUrl;\n }\n if (kind === \"bearer\") set(\"ANTHROPIC_AUTH_TOKEN\", credential);\n else if (kind === \"api_key_header\") set(\"ANTHROPIC_API_KEY\", credential);\n if (!credential) {\n // `oauth` / `none` / an unresolved ref: the ambient carriers are the\n // only auth this session has, and the scrub just removed them.\n if (ambient.authToken) env.ANTHROPIC_AUTH_TOKEN = ambient.authToken;\n else set(\"ANTHROPIC_API_KEY\", ambient.apiKey);\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 * Where the transcript is read and written. Defaults to this process's own\n * filesystem access ({@link localTranscriptStore}); with the agent uid split\n * the transcript belongs to the agent uid and must be reached through it.\n */\n store?: TranscriptStore;\n}\n\n/**\n * Filesystem access to Claude Code transcripts. The CLI creates them 0600 in\n * 0700 dirs, so when it runs as a different uid than the runner, only that uid\n * can locate, read or rewrite them (see `agent-transcript.ts`).\n *\n * @category Transcript repair\n */\nexport interface TranscriptStore {\n /** Path of `<sessionId>.jsonl` under `<configDir>/projects/`, or `null` when absent. */\n locate(configDir: string, sessionId: string, timeoutMs?: number): Promise<string | null>;\n /** The file's contents as UTF-8 chunks. */\n read(filePath: string): AsyncIterable<string>;\n /** Atomically replace the file with `chunks` via a `.scrub-tmp` sibling. */\n replace(filePath: string, chunks: AsyncIterable<string>): Promise<void>;\n /** Remove the sibling a failed or abandoned {@link replace} left (best effort). */\n discardTemp(filePath: string): Promise<void>;\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(chunks: AsyncIterable<string>): AsyncGenerator<string> {\n let pending = \"\";\n for await (const chunk of chunks) {\n pending += chunk;\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}\n\n/**\n * The runner's own filesystem access: the default {@link TranscriptStore}.\n *\n * @category Transcript repair\n */\nexport const localTranscriptStore: TranscriptStore = {\n locate: (configDir, sessionId, timeoutMs) =>\n locateTranscriptPath(configDir, sessionId, timeoutMs),\n async *read(filePath) {\n const stream = createReadStream(filePath, { encoding: \"utf8\" });\n try {\n for await (const chunk of stream) yield chunk as string;\n } finally {\n stream.destroy();\n }\n },\n async replace(filePath, chunks) {\n const tmpPath = `${filePath}.scrub-tmp`;\n await pipeline(chunks, createWriteStream(tmpPath, { encoding: \"utf8\" }));\n await rename(tmpPath, filePath);\n },\n async discardTemp(filePath) {\n const tmpPath = `${filePath}.scrub-tmp`;\n await tryWithFsDeadline(`unlink ${tmpPath}`, () => unlink(tmpPath), undefined, fsDeadlineMs());\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 store = opts.store ?? localTranscriptStore;\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 let filePath: string | null;\n try {\n filePath = await store.locate(configDir, sessionId, timeoutMs);\n } catch (err) {\n log?.warn(\"scrub-transcript: failed to locate transcript\", {\n configDir,\n sessionId,\n error: err instanceof Error ? err.message : String(err),\n });\n return result;\n }\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(store.read(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 source = filePath;\n try {\n await withFsDeadline(\n `rewrite transcript ${source}`,\n async () => {\n const discard: ScrubCounters = { corrected: 0, stubbed: 0, cacheStripped: 0 };\n await store.replace(\n source,\n (async function* () {\n let first = true;\n for await (const line of streamLines(store.read(source))) {\n yield first ? repairLine(line, discard) : `\\n${repairLine(line, discard)}`;\n first = false;\n }\n })(),\n );\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 `.scrub-tmp` in the SDK's projects dir, also\n // when the deadline abandoned the replace mid-write.\n await store.discardTemp(source).catch(() => {});\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","import { type ChildProcess, spawn } from \"node:child_process\";\nimport { join } from \"node:path\";\nimport { fsDeadlineMs, withFsDeadline } from \"@skaile/workspaces/core\";\nimport { resolveAgentExec } from \"./agent-exec.js\";\nimport { localTranscriptStore, type TranscriptStore } from \"./drivers/scrub-transcript.js\";\n\n/**\n * Transcripts reached through the agent launch shim.\n *\n * With the uid split on, the Claude CLI runs as the agent uid and creates its\n * transcripts 0600 in 0700 dirs, so the runner can no longer list, read or\n * rewrite them itself. This store runs plain tools (`find`, `cat`, `sh`, `mv`)\n * as the agent uid through the shim instead. The child gets only `PATH` and\n * `LC_ALL`, never the runner's environment, and runs in `/` because the\n * runner's own cwd may not be enterable by the agent uid.\n */\nexport function agentTranscriptStore(shim: string): TranscriptStore {\n // A replace the scrub's deadline abandoned keeps running; discardTemp stops\n // it before removing its temp file.\n const inFlight = new Map<string, ChildProcess>();\n // Paths whose rewrite discardTemp gave up on: their rename must never run.\n const cancelled = new Set<string>();\n const track = (filePath: string, child: ChildProcess) => {\n inFlight.set(filePath, child);\n child.once(\"close\", () => {\n if (inFlight.get(filePath) === child) inFlight.delete(filePath);\n });\n };\n return {\n async locate(configDir, sessionId, timeoutMs = 10_000) {\n // A session id is a UUID; anything glob- or path-shaped is not ours.\n if (!/^[A-Za-z0-9._-]+$/.test(sessionId)) return null;\n const projectsDir = join(configDir, \"projects\");\n // Markers on stdout, not exit codes, carry the answer: a shim or launcher\n // failure has exit codes of its own and must never read as \"not found\".\n const { stdout } = await collect(\n runAsAgent(shim, [\n \"sh\",\n \"-c\",\n '[ -d \"$1\" ] || { echo \"@@no-projects\"; exit 0; }; ' +\n 'find \"$1\" -mindepth 2 -maxdepth 2 -type f -name \"$2\" -print -quit; echo \"@@find:$?\"',\n \"sh\",\n projectsDir,\n `${sessionId}.jsonl`,\n ]),\n timeoutMs,\n );\n const lines = stdout.split(\"\\n\").map((l) => l.trim());\n // A missing projects/ is the same \"not found\" as a failed readdir locally.\n if (lines.includes(\"@@no-projects\")) return null;\n const status = lines.find((l) => l.startsWith(\"@@find:\"));\n if (status === undefined)\n throw new Error(\"locating a transcript as the agent uid failed (no answer from the shim)\");\n // A path find printed counts even if it later hit an unreadable sibling.\n const found = lines.find((l) => l.startsWith(\"/\"));\n if (found) return found;\n if (status !== \"@@find:0\")\n throw new Error(`locating a transcript as the agent uid failed (${status.slice(2)})`);\n return null;\n },\n\n async *read(filePath) {\n const child = runAsAgent(shim, [\"cat\", \"--\", filePath]);\n const exited = exitOf(child);\n exited.catch(() => {}); // awaited below; this only stops an unhandled rejection\n const stderr = drain(child);\n child.stdout?.setEncoding(\"utf8\");\n for await (const chunk of child.stdout as AsyncIterable<string>) yield chunk;\n const code = await exited;\n if (code !== 0)\n throw new Error(`reading ${filePath} as the agent uid failed: ${await stderr}`);\n },\n\n async replace(filePath, chunks) {\n const child = runAsAgent(shim, [\n \"sh\",\n \"-c\",\n // 0600 like the CLI's own files. Only writes the temp file: the rename\n // is a separate step below, run only after the input was fully sent,\n // so a killed or starved writer can never commit a partial transcript.\n 'umask 077; cat > \"$1.scrub-tmp\"',\n \"sh\",\n filePath,\n ]);\n cancelled.delete(filePath);\n track(filePath, child);\n const exited = exitOf(child);\n exited.catch(() => {}); // awaited below; this only stops an unhandled rejection\n const stderr = drain(child);\n const stdin = child.stdin;\n if (!stdin) throw new Error(\"agent shim has no stdin\");\n // A child that dies early surfaces through its exit code, not an EPIPE crash.\n stdin.on(\"error\", () => {});\n const gone = exited.then(\n () => undefined,\n () => undefined,\n );\n // Stop pulling input as soon as the child is gone (killed by discardTemp,\n // or failed), instead of waiting on a producer that may never resume.\n const input = chunks[Symbol.asyncIterator]();\n let drained = false;\n try {\n for (;;) {\n const next = await Promise.race([\n input.next(),\n gone.then(() => ({ dead: true as const })),\n ]);\n if (\"dead\" in next || stdin.destroyed) break;\n if (next.done) {\n drained = true;\n break;\n }\n if (!stdin.write(next.value)) {\n await Promise.race([new Promise((resolve) => stdin.once(\"drain\", resolve)), gone]);\n }\n }\n } finally {\n stdin.end();\n // Close the producer too, so the reader feeding it (a `cat` through\n // the shim) is torn down rather than left blocked on a full pipe.\n if (!drained) void input.return?.()?.catch(() => {});\n }\n const code = await exited;\n if (code !== 0 || !drained)\n throw new Error(`rewriting ${filePath} as the agent uid failed: ${await stderr}`);\n if (cancelled.has(filePath)) throw new Error(`rewrite of ${filePath} was abandoned`);\n const mover = runAsAgent(shim, [\"mv\", \"-f\", \"--\", `${filePath}.scrub-tmp`, filePath]);\n track(filePath, mover);\n const moved = await collect(mover, 10_000);\n if (moved.code !== 0) throw new Error(`renaming the rewritten ${filePath} failed`);\n },\n\n async discardTemp(filePath) {\n // Before anything else, so a writer that is just finishing never renames.\n cancelled.add(filePath);\n const pending = inFlight.get(filePath);\n if (pending && pending.exitCode === null && pending.signalCode === null) {\n // The writer cannot commit (the rename is a separate step), so this only\n // stops it; bounded, since a writer stuck on a hung mount may never die.\n const closed = new Promise((resolve) => pending.once(\"close\", resolve));\n pending.kill(\"SIGKILL\");\n await withFsDeadline(`stop the rewrite of ${filePath}`, () => closed, fsDeadlineMs());\n }\n await collect(runAsAgent(shim, [\"rm\", \"-f\", \"--\", `${filePath}.scrub-tmp`]), 10_000);\n },\n };\n}\n\n/**\n * The transcript store for this runner: through the agent shim when\n * `SKAILE_AGENT_EXEC` is set, the runner's own filesystem otherwise.\n */\nexport function transcriptStoreForRuntime(\n env: Record<string, string | undefined> = process.env,\n): TranscriptStore {\n const shim = resolveAgentExec(env);\n return shim ? agentTranscriptStore(shim) : localTranscriptStore;\n}\n\nfunction runAsAgent(shim: string, argv: string[]): ChildProcess {\n return spawn(shim, [\"--\", ...argv], {\n cwd: \"/\",\n env: { PATH: process.env.PATH ?? \"/usr/bin:/bin\", LC_ALL: \"C\" },\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n });\n}\n\nfunction exitOf(child: ChildProcess): Promise<number> {\n return new Promise((resolve, reject) => {\n child.once(\"error\", reject);\n child.once(\"close\", (code) => resolve(code ?? 1));\n });\n}\n\n/** Keep the last 1 KiB of stderr for the error message, and keep the pipe drained. */\nfunction drain(child: ChildProcess): Promise<string> {\n return new Promise((resolve) => {\n let tail = \"\";\n child.stderr?.setEncoding(\"utf8\");\n child.stderr?.on(\"data\", (c: string) => {\n tail = (tail + c).slice(-1024);\n });\n child.stderr?.once(\"close\", () => resolve(tail.trim()));\n });\n}\n\nasync function collect(\n child: ChildProcess,\n timeoutMs: number,\n): Promise<{ code: number; stdout: string }> {\n let stdout = \"\";\n child.stdout?.setEncoding(\"utf8\");\n child.stdout?.on(\"data\", (c: string) => {\n stdout += c;\n });\n void drain(child);\n child.stdin?.end();\n let timer: NodeJS.Timeout | undefined;\n try {\n const code = await Promise.race([\n exitOf(child),\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n child.kill(\"SIGKILL\");\n reject(new Error(`agent shim did not answer within ${timeoutMs} ms`));\n }, timeoutMs);\n }),\n ]);\n return { code, stdout };\n } finally {\n clearTimeout(timer);\n }\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,4 +1,4 @@
1
- import { MENTION_GROUPS } from './chunk-NQOE57Q7.js';
1
+ import { MENTION_GROUPS } from './chunk-MX7LCQUQ.js';
2
2
  import { createHash } from 'crypto';
3
3
 
4
4
  // session/src/bounded-subscriber-transport.ts
@@ -930,5 +930,5 @@ function isAgentAddressed(mentions) {
930
930
  }
931
931
 
932
932
  export { BoundedSubscriberTransport, DEFAULT_SUBSCRIBER_BUFFER_LIMITS, SessionDispatcher, SubscriberBufferOverflowError, UNSIZED_EVENT, approxEventSize, isAddressedByKind, isAgentAddressed, isMentioned, parseMentions };
933
- //# sourceMappingURL=chunk-OHON7XSG.js.map
934
- //# sourceMappingURL=chunk-OHON7XSG.js.map
933
+ //# sourceMappingURL=chunk-M42SMH7V.js.map
934
+ //# sourceMappingURL=chunk-M42SMH7V.js.map