@skaile/workspaces 6.8.1 → 6.9.1
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.
- package/CHANGELOG.md +54 -0
- package/dist/ai-sdk.js +5 -5
- package/dist/{asset-feeds-R75MH2WW.js → asset-feeds-PANNQPEE.js} +19 -19
- package/dist/{asset-feeds-R75MH2WW.js.map → asset-feeds-PANNQPEE.js.map} +1 -1
- package/dist/asset-manager/catalog-deployer.js +4 -4
- package/dist/asset-manager/history.js +19 -1
- package/dist/asset-manager/index.js +11 -11
- package/dist/asset-manager/installer.js +7 -7
- package/dist/asset-manager/renderers.js +6 -6
- package/dist/asset-manager/src/history.d.ts.map +1 -1
- package/dist/asset-manager/src/index.d.ts +65 -3
- package/dist/asset-manager/src/index.d.ts.map +1 -1
- package/dist/bridge/harnesses/claude-sdk.js +9 -9
- package/dist/bridge/harnesses/codex.js +29 -12
- package/dist/bridge/harnesses/codex.js.map +1 -1
- package/dist/bridge/harnesses/continue.js +8 -8
- package/dist/bridge/harnesses/echo.js +3 -3
- package/dist/bridge/harnesses/gemini.js +8 -8
- package/dist/bridge/harnesses/goose.js +8 -8
- package/dist/bridge/harnesses/omp.js +191 -24
- package/dist/bridge/harnesses/omp.js.map +1 -1
- package/dist/bridge/harnesses/opencode.js +8 -8
- package/dist/bridge/harnesses/qwen.js +8 -8
- package/dist/bridge/index.js +14 -14
- package/dist/bridge/src/codex/friendly-error.d.ts +7 -1
- package/dist/bridge/src/codex/friendly-error.d.ts.map +1 -1
- package/dist/bridge/src/codex/login-fallback.d.ts +5 -0
- package/dist/bridge/src/codex/login-fallback.d.ts.map +1 -1
- package/dist/bridge/src/harnesses/codex.d.ts +2 -0
- package/dist/bridge/src/harnesses/codex.d.ts.map +1 -1
- package/dist/bridge/src/harnesses/omp.d.ts +28 -0
- package/dist/bridge/src/harnesses/omp.d.ts.map +1 -1
- package/dist/{chunk-PKC2AHOB.js → chunk-2UKNI2HJ.js} +2 -2
- package/dist/{chunk-PKC2AHOB.js.map → chunk-2UKNI2HJ.js.map} +1 -1
- package/dist/{chunk-SBNUXJ6E.js → chunk-3AIEJSQR.js} +3 -3
- package/dist/{chunk-SBNUXJ6E.js.map → chunk-3AIEJSQR.js.map} +1 -1
- package/dist/{chunk-TMJBEGS4.js → chunk-4KPQ6ILH.js} +5 -34
- package/dist/chunk-4KPQ6ILH.js.map +1 -0
- package/dist/{chunk-G7NMF5WQ.js → chunk-4ROXSQEG.js} +3 -3
- package/dist/{chunk-G7NMF5WQ.js.map → chunk-4ROXSQEG.js.map} +1 -1
- package/dist/{chunk-WFK4MUBL.js → chunk-5J6JWGY4.js} +3 -3
- package/dist/{chunk-WFK4MUBL.js.map → chunk-5J6JWGY4.js.map} +1 -1
- package/dist/{chunk-ORXV3UB6.js → chunk-5J6N6LHL.js} +3 -3
- package/dist/{chunk-ORXV3UB6.js.map → chunk-5J6N6LHL.js.map} +1 -1
- package/dist/{chunk-O5Y7VMVQ.js → chunk-5KWQMCH7.js} +3 -3
- package/dist/{chunk-O5Y7VMVQ.js.map → chunk-5KWQMCH7.js.map} +1 -1
- package/dist/{chunk-KTBKW2FI.js → chunk-7QYBKUAS.js} +4 -3
- package/dist/chunk-7QYBKUAS.js.map +1 -0
- package/dist/{chunk-SILFO5RY.js → chunk-7TF5MNFK.js} +2 -2
- package/dist/{chunk-SILFO5RY.js.map → chunk-7TF5MNFK.js.map} +1 -1
- package/dist/{chunk-XIIIGLSL.js → chunk-7UCPGQCW.js} +9 -9
- package/dist/{chunk-XIIIGLSL.js.map → chunk-7UCPGQCW.js.map} +1 -1
- package/dist/{chunk-NAEXYRHR.js → chunk-AQTAULXT.js} +10 -10
- package/dist/{chunk-NAEXYRHR.js.map → chunk-AQTAULXT.js.map} +1 -1
- package/dist/{chunk-LL5GMUQG.js → chunk-BDAXHJC5.js} +7 -7
- package/dist/{chunk-LL5GMUQG.js.map → chunk-BDAXHJC5.js.map} +1 -1
- package/dist/{chunk-DXBHGNSI.js → chunk-BLBXOG5Q.js} +6 -6
- package/dist/{chunk-DXBHGNSI.js.map → chunk-BLBXOG5Q.js.map} +1 -1
- package/dist/{chunk-Y6LC5PEZ.js → chunk-C324IAXI.js} +14 -5
- package/dist/chunk-C324IAXI.js.map +1 -0
- package/dist/{chunk-NW7Y5SNK.js → chunk-CPMLMNI5.js} +4 -4
- package/dist/{chunk-NW7Y5SNK.js.map → chunk-CPMLMNI5.js.map} +1 -1
- package/dist/{chunk-DFP476EU.js → chunk-DJSGQW2Q.js} +89 -4
- package/dist/chunk-DJSGQW2Q.js.map +1 -0
- package/dist/{chunk-QCR5AE5E.js → chunk-E675QKFG.js} +5 -5
- package/dist/{chunk-QCR5AE5E.js.map → chunk-E675QKFG.js.map} +1 -1
- package/dist/{chunk-7RBFYW24.js → chunk-EMSU6L7K.js} +5 -5
- package/dist/{chunk-7RBFYW24.js.map → chunk-EMSU6L7K.js.map} +1 -1
- package/dist/{chunk-O7ADRMCR.js → chunk-FZO64PLQ.js} +45 -16
- package/dist/chunk-FZO64PLQ.js.map +1 -0
- package/dist/{chunk-I4DI5DAX.js → chunk-FZTHL6SK.js} +18 -18
- package/dist/chunk-FZTHL6SK.js.map +1 -0
- package/dist/{chunk-CMXDFTA2.js → chunk-GYPPVANR.js} +3 -3
- package/dist/{chunk-CMXDFTA2.js.map → chunk-GYPPVANR.js.map} +1 -1
- package/dist/{chunk-G44FFUMA.js → chunk-GZL6RN4Z.js} +92 -14
- package/dist/chunk-GZL6RN4Z.js.map +1 -0
- package/dist/{chunk-N65H7YYI.js → chunk-IISEBVMA.js} +5 -5
- package/dist/{chunk-N65H7YYI.js.map → chunk-IISEBVMA.js.map} +1 -1
- package/dist/{chunk-BGATDUYX.js → chunk-J45JCYS4.js} +4 -4
- package/dist/{chunk-BGATDUYX.js.map → chunk-J45JCYS4.js.map} +1 -1
- package/dist/{chunk-6ZM5X2XW.js → chunk-KVTV4LT2.js} +3 -3
- package/dist/{chunk-6ZM5X2XW.js.map → chunk-KVTV4LT2.js.map} +1 -1
- package/dist/{chunk-SAL72A7T.js → chunk-LMADWO4Q.js} +9 -6
- package/dist/chunk-LMADWO4Q.js.map +1 -0
- package/dist/{chunk-3HSLJAMJ.js → chunk-LYVLDGML.js} +3 -3
- package/dist/{chunk-3HSLJAMJ.js.map → chunk-LYVLDGML.js.map} +1 -1
- package/dist/{chunk-SGI5MRKP.js → chunk-MDCI4RSG.js} +40 -5
- package/dist/chunk-MDCI4RSG.js.map +1 -0
- package/dist/{chunk-QGA2OBUJ.js → chunk-MPO5CQUZ.js} +3 -3
- package/dist/{chunk-QGA2OBUJ.js.map → chunk-MPO5CQUZ.js.map} +1 -1
- package/dist/{chunk-KO3VSZQP.js → chunk-NDBHEOIA.js} +6 -6
- package/dist/{chunk-KO3VSZQP.js.map → chunk-NDBHEOIA.js.map} +1 -1
- package/dist/{chunk-OLZE4IHX.js → chunk-PBEDRYHP.js} +4093 -3886
- package/dist/chunk-PBEDRYHP.js.map +1 -0
- package/dist/{chunk-YMO4ZDLC.js → chunk-PLVM6OIV.js} +45 -13
- package/dist/chunk-PLVM6OIV.js.map +1 -0
- package/dist/{chunk-LZ3E6TML.js → chunk-Q5SSRVD5.js} +18 -9
- package/dist/chunk-Q5SSRVD5.js.map +1 -0
- package/dist/{chunk-4CD2R4MJ.js → chunk-QBUJTVMY.js} +4 -4
- package/dist/{chunk-4CD2R4MJ.js.map → chunk-QBUJTVMY.js.map} +1 -1
- package/dist/{chunk-REAF7ZFA.js → chunk-QIV7H3GJ.js} +398 -36
- package/dist/chunk-QIV7H3GJ.js.map +1 -0
- package/dist/{chunk-I6XH46Q6.js → chunk-RP3ML3QD.js} +3 -3
- package/dist/{chunk-I6XH46Q6.js.map → chunk-RP3ML3QD.js.map} +1 -1
- package/dist/{chunk-SVMIUCTT.js → chunk-RZRJTCP2.js} +4 -4
- package/dist/{chunk-SVMIUCTT.js.map → chunk-RZRJTCP2.js.map} +1 -1
- package/dist/{chunk-N2W7OJC6.js → chunk-S47KU4YB.js} +3 -3
- package/dist/{chunk-N2W7OJC6.js.map → chunk-S47KU4YB.js.map} +1 -1
- package/dist/{chunk-EDKTS44C.js → chunk-SME3PK4L.js} +6 -6
- package/dist/{chunk-EDKTS44C.js.map → chunk-SME3PK4L.js.map} +1 -1
- package/dist/{chunk-QW5B3TEO.js → chunk-TMQFOJ6F.js} +3 -3
- package/dist/{chunk-QW5B3TEO.js.map → chunk-TMQFOJ6F.js.map} +1 -1
- package/dist/{chunk-BB5EJLKZ.js → chunk-TUOHA6BM.js} +2 -2
- package/dist/{chunk-BB5EJLKZ.js.map → chunk-TUOHA6BM.js.map} +1 -1
- package/dist/{chunk-HLAEYFUN.js → chunk-U3FI4DVT.js} +3 -3
- package/dist/{chunk-HLAEYFUN.js.map → chunk-U3FI4DVT.js.map} +1 -1
- package/dist/{chunk-237BMOZW.js → chunk-UWD7YBDR.js} +4 -4
- package/dist/{chunk-237BMOZW.js.map → chunk-UWD7YBDR.js.map} +1 -1
- package/dist/{chunk-56PIAGD6.js → chunk-VEIWFS7Z.js} +331 -59
- package/dist/chunk-VEIWFS7Z.js.map +1 -0
- package/dist/{chunk-7O2CR5SZ.js → chunk-WEPTGUR4.js} +41 -35
- package/dist/chunk-WEPTGUR4.js.map +1 -0
- package/dist/{chunk-VT6G5AJV.js → chunk-WS3BOCAT.js} +4 -3
- package/dist/chunk-WS3BOCAT.js.map +1 -0
- package/dist/{chunk-JAGBPHXB.js → chunk-X5SGUBUV.js} +3 -3
- package/dist/{chunk-JAGBPHXB.js.map → chunk-X5SGUBUV.js.map} +1 -1
- package/dist/{chunk-62NNP7LU.js → chunk-XB4XHGIE.js} +3 -3
- package/dist/{chunk-62NNP7LU.js.map → chunk-XB4XHGIE.js.map} +1 -1
- package/dist/{chunk-VQFA5DR7.js → chunk-YPTDPN2B.js} +3 -3
- package/dist/{chunk-VQFA5DR7.js.map → chunk-YPTDPN2B.js.map} +1 -1
- package/dist/{chunk-Z5EPCIB6.js → chunk-ZUROGXJM.js} +93 -14
- package/dist/chunk-ZUROGXJM.js.map +1 -0
- package/dist/{claude-code-DS26HI3K.js → claude-code-ILZ46SLO.js} +5 -5
- package/dist/{claude-code-DS26HI3K.js.map → claude-code-ILZ46SLO.js.map} +1 -1
- package/dist/cli/index.js +277 -143
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/src/agent-pins.d.ts +8 -0
- package/dist/cli/src/agent-pins.d.ts.map +1 -1
- package/dist/cli/src/commands/asset-cmd.d.ts.map +1 -1
- package/dist/cli/src/commands/catalog.d.ts +4 -4
- package/dist/cli/src/commands/catalog.d.ts.map +1 -1
- package/dist/cli/src/commands/connector.d.ts.map +1 -1
- package/dist/cli/src/commands/deploy.d.ts.map +1 -1
- package/dist/cli/src/commands/flow.d.ts.map +1 -1
- package/dist/cli/src/commands/harness.d.ts.map +1 -1
- package/dist/cli/src/commands/integration.d.ts.map +1 -1
- package/dist/cli/src/commands/library-cmd.d.ts.map +1 -1
- package/dist/cli/src/commands/library-index.d.ts +42 -0
- package/dist/cli/src/commands/library-index.d.ts.map +1 -1
- package/dist/cli/src/commands/library-publish.d.ts.map +1 -1
- package/dist/cli/src/commands/npx.d.ts.map +1 -1
- package/dist/cli/src/commands/patch.d.ts.map +1 -1
- package/dist/cli/src/commands/plugin-registry-cmd.d.ts.map +1 -1
- package/dist/cli/src/commands/project.d.ts.map +1 -1
- package/dist/cli/src/commands/run.d.ts.map +1 -1
- package/dist/cli/src/commands/serve-preflight.d.ts +10 -0
- package/dist/cli/src/commands/serve-preflight.d.ts.map +1 -1
- package/dist/cli/src/commands/serve.d.ts +5 -3
- package/dist/cli/src/commands/serve.d.ts.map +1 -1
- package/dist/cli/src/commands/session.d.ts.map +1 -1
- package/dist/cli/src/commands/source.d.ts.map +1 -1
- package/dist/cli/src/commands/store.d.ts.map +1 -1
- package/dist/cli/src/commands/validate.d.ts.map +1 -1
- package/dist/cli/src/config-checks.d.ts +13 -0
- package/dist/cli/src/config-checks.d.ts.map +1 -1
- package/dist/cli/src/group-help.d.ts +11 -0
- package/dist/cli/src/group-help.d.ts.map +1 -0
- package/dist/connectors/config.js +2 -2
- package/dist/connectors/index.js +17 -17
- package/dist/connectors/src/config.d.ts.map +1 -1
- package/dist/{connectors-3ST6PGWP.js → connectors-KTRUUKWG.js} +20 -20
- package/dist/{connectors-3ST6PGWP.js.map → connectors-KTRUUKWG.js.map} +1 -1
- package/dist/core/index.js +4 -4
- package/dist/core/logging.js +1 -1
- package/dist/core/runtime-assets.js +2 -2
- package/dist/core/src/index.d.ts +1 -1
- package/dist/core/src/index.d.ts.map +1 -1
- package/dist/core/src/logging/config.d.ts.map +1 -1
- package/dist/core/src/repo-manager.d.ts +6 -0
- package/dist/core/src/repo-manager.d.ts.map +1 -1
- package/dist/core/src/run-state-ignore.d.ts +6 -4
- package/dist/core/src/run-state-ignore.d.ts.map +1 -1
- package/dist/core/src/walker.d.ts.map +1 -1
- package/dist/core/src/workspace-config.d.ts +6 -0
- package/dist/core/src/workspace-config.d.ts.map +1 -1
- package/dist/core/workspace-config.js +1 -1
- package/dist/deploy/index.js +4 -4
- package/dist/discovery/index.js +2 -2
- package/dist/{ensure-sources-VELKRM6X.js → ensure-sources-5QWKUIUD.js} +23 -23
- package/dist/{ensure-sources-VELKRM6X.js.map → ensure-sources-5QWKUIUD.js.map} +1 -1
- package/dist/factory-assets/connectors/box.js +17 -17
- package/dist/factory-assets/connectors/deploy.js +17 -17
- package/dist/factory-assets/connectors/devserver.js +17 -17
- package/dist/factory-assets/connectors/flow/adapter.js +17 -17
- package/dist/factory-assets/connectors/flow/engine.js +5 -5
- package/dist/factory-assets/connectors/flow/run-flow.js +18 -18
- package/dist/factory-assets/connectors/flow.js +17 -17
- package/dist/factory-assets/connectors/git.js +17 -17
- package/dist/factory-assets/connectors/gmail.js +17 -17
- package/dist/factory-assets/connectors/googledrive.js +17 -17
- package/dist/factory-assets/connectors/local.js +17 -17
- package/dist/factory-assets/connectors/mattermost.js +17 -17
- package/dist/factory-assets/connectors/memory.js +17 -17
- package/dist/factory-assets/connectors/minio.js +17 -17
- package/dist/factory-assets/connectors/postgres.js +17 -17
- package/dist/factory-assets/connectors/s3.js +17 -17
- package/dist/factory-assets/connectors/sharepoint.js +17 -17
- package/dist/factory-assets/connectors/sqlite.js +17 -17
- package/dist/factory-assets/connectors/static-server.js +17 -17
- package/dist/factory-assets/connectors/tunnel.js +17 -17
- package/dist/factory-assets/connectors/webdav.js +17 -17
- package/dist/factory-assets/connectors/xstate-store.js +17 -17
- package/dist/factory-assets/connectors/xstate.js +17 -17
- package/dist/factory-assets/skills/authoring-skaile-assets/SKILL.md +4 -4
- package/dist/factory-assets/skills/authoring-skaile-manifests/SKILL.md +10 -10
- package/dist/factory-assets/skills/authoring-skaile-manifests/references/dependency-standard.md +15 -15
- package/dist/factory-assets/skills/manifest-compliance/SKILL.md +1 -1
- package/dist/{flows-I6ODIPZZ.js → flows-UCP6ZUYS.js} +7 -7
- package/dist/{flows-I6ODIPZZ.js.map → flows-UCP6ZUYS.js.map} +1 -1
- package/dist/{helpers-LWNKX56Y.js → helpers-INS4B7OQ.js} +23 -23
- package/dist/{helpers-LWNKX56Y.js.map → helpers-INS4B7OQ.js.map} +1 -1
- package/dist/library/index.js +7 -7
- package/dist/library/src/index.d.ts +1 -1
- package/dist/library/src/index.d.ts.map +1 -1
- package/dist/library/src/remote/index.d.ts +1 -1
- package/dist/library/src/remote/index.d.ts.map +1 -1
- package/dist/library/src/remote/remote-catalog-source.d.ts +33 -2
- package/dist/library/src/remote/remote-catalog-source.d.ts.map +1 -1
- package/dist/{library-publish-WJVCT2IK.js → library-publish-AZTYRASL.js} +61 -47
- package/dist/library-publish-AZTYRASL.js.map +1 -0
- package/dist/model-endpoint/index.js +7 -7
- package/dist/model-endpoint/src/index.d.ts +1 -1
- package/dist/model-endpoint/src/index.d.ts.map +1 -1
- package/dist/model-endpoint/src/openai-agent.d.ts +60 -0
- package/dist/model-endpoint/src/openai-agent.d.ts.map +1 -0
- package/dist/model-endpoint/src/resolve.d.ts +12 -3
- package/dist/model-endpoint/src/resolve.d.ts.map +1 -1
- package/dist/model-endpoint/src/server.d.ts.map +1 -1
- package/dist/model-endpoint/src/types.d.ts +33 -0
- package/dist/model-endpoint/src/types.d.ts.map +1 -1
- package/dist/model-endpoint/src/upstream-models.d.ts +20 -0
- package/dist/model-endpoint/src/upstream-models.d.ts.map +1 -0
- package/dist/{open-library-Q7QZJY5D.js → open-library-3HMXYGUF.js} +26 -26
- package/dist/{open-library-Q7QZJY5D.js.map → open-library-3HMXYGUF.js.map} +1 -1
- package/dist/{open-registry-RZW2AFD6.js → open-registry-BHBHQMBA.js} +11 -11
- package/dist/{open-registry-RZW2AFD6.js.map → open-registry-BHBHQMBA.js.map} +1 -1
- package/dist/{paths-RPK5PNZQ.js → paths-77PXOXZY.js} +7 -7
- package/dist/{paths-RPK5PNZQ.js.map → paths-77PXOXZY.js.map} +1 -1
- package/dist/{plugin-store-OJTERUEZ.js → plugin-store-XQP2CRYH.js} +7 -7
- package/dist/{plugin-store-OJTERUEZ.js.map → plugin-store-XQP2CRYH.js.map} +1 -1
- package/dist/{project-WVPRL7CP.js → project-HVNPK2ZF.js} +39 -40
- package/dist/{project-WVPRL7CP.js.map → project-HVNPK2ZF.js.map} +1 -1
- package/dist/resolver/index.js +4 -4
- package/dist/runner/index.js +28 -28
- package/dist/runner/src/agent-loop.d.ts +42 -0
- package/dist/runner/src/agent-loop.d.ts.map +1 -0
- package/dist/runner/src/agents/in-process-host.d.ts +9 -6
- package/dist/runner/src/agents/in-process-host.d.ts.map +1 -1
- package/dist/runner/src/model-endpoint-discovery.d.ts +3 -0
- package/dist/runner/src/model-endpoint-discovery.d.ts.map +1 -1
- package/dist/runner/src/serve.d.ts.map +1 -1
- package/dist/runner/src/session-builder.d.ts +6 -4
- package/dist/runner/src/session-builder.d.ts.map +1 -1
- package/dist/runner/src/turn-end-contract.d.ts.map +1 -1
- package/dist/runner/src/turn-scheduler.d.ts +37 -2
- package/dist/runner/src/turn-scheduler.d.ts.map +1 -1
- package/dist/sdk/asset-manager.js +11 -11
- package/dist/sdk/bridge.js +14 -14
- package/dist/sdk/core.js +4 -4
- package/dist/sdk/flow.js +5 -5
- package/dist/sdk/index.js +28 -28
- package/dist/sdk/resolver.js +4 -4
- package/dist/sdk/runner.js +28 -28
- package/dist/sdk/transport/ws/server.js +5 -5
- package/dist/sdk/transport/ws.js +5 -5
- package/dist/sdk/transport.js +5 -5
- package/dist/{serve-preflight-24YWWYUG.js → serve-preflight-NHZOKHIC.js} +27 -26
- package/dist/{serve-preflight-24YWWYUG.js.map → serve-preflight-NHZOKHIC.js.map} +1 -1
- package/dist/{setup-F5JX64UP.js → setup-EX7Z7XRN.js} +24 -24
- package/dist/{setup-F5JX64UP.js.map → setup-EX7Z7XRN.js.map} +1 -1
- package/dist/{skills-KHHW3RZ3.js → skills-DE2BDQ6G.js} +6 -6
- package/dist/{skills-KHHW3RZ3.js.map → skills-DE2BDQ6G.js.map} +1 -1
- package/dist/{source-DG5IAAGZ.js → source-URRPRGMZ.js} +39 -39
- package/dist/{source-DG5IAAGZ.js.map → source-URRPRGMZ.js.map} +1 -1
- package/dist/{source-manifest-publish-76S2JD3O.js → source-manifest-publish-ZWRYRJ2U.js} +41 -41
- package/dist/{source-manifest-publish-76S2JD3O.js.map → source-manifest-publish-ZWRYRJ2U.js.map} +1 -1
- package/dist/transport/index.js +5 -5
- package/dist/transport/ws/server.js +5 -5
- package/dist/transport/ws.js +5 -5
- package/dist/tui/index.js +29 -29
- package/dist/tui/index.js.map +1 -1
- package/dist/tui/src/repl.d.ts.map +1 -1
- package/dist/types/manifests.js +1 -1
- package/dist/types/src/manifests/scaffold-body.d.ts +1 -1
- package/dist/types/src/manifests/scaffold-body.d.ts.map +1 -1
- package/dist/workspace-plugin/adapters/mcp.js +20 -20
- package/dist/workspace-plugin/adapters/omp.js +14 -14
- package/dist/workspace-plugin/index.js +2 -2
- package/package.json +1 -1
- package/dist/chunk-56PIAGD6.js.map +0 -1
- package/dist/chunk-7O2CR5SZ.js.map +0 -1
- package/dist/chunk-DFP476EU.js.map +0 -1
- package/dist/chunk-E5AZA2FL.js +0 -83
- package/dist/chunk-E5AZA2FL.js.map +0 -1
- package/dist/chunk-G44FFUMA.js.map +0 -1
- package/dist/chunk-I4DI5DAX.js.map +0 -1
- package/dist/chunk-KTBKW2FI.js.map +0 -1
- package/dist/chunk-LZ3E6TML.js.map +0 -1
- package/dist/chunk-O7ADRMCR.js.map +0 -1
- package/dist/chunk-OLZE4IHX.js.map +0 -1
- package/dist/chunk-REAF7ZFA.js.map +0 -1
- package/dist/chunk-SAL72A7T.js.map +0 -1
- package/dist/chunk-SGI5MRKP.js.map +0 -1
- package/dist/chunk-TMJBEGS4.js.map +0 -1
- package/dist/chunk-VT6G5AJV.js.map +0 -1
- package/dist/chunk-Y6LC5PEZ.js.map +0 -1
- package/dist/chunk-YMO4ZDLC.js.map +0 -1
- package/dist/chunk-Z5EPCIB6.js.map +0 -1
- package/dist/library-publish-WJVCT2IK.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../bridge/src/approval-card.ts","../bridge/src/cloud.ts","../bridge/src/harnesses/scrub-transcript.ts","../bridge/src/harnesses/resume-probe.ts","../bridge/src/agent-transcript.ts","../bridge/src/claude-sdk-surface.ts"],"names":["join"],"mappings":";;;;;;;;;;;;AAUO,IAAM,YAAA,GAAe;AAErB,IAAM,IAAA,GAAO;AAab,SAAS,eAAe,KAAA,EAA6C;AAC1E,EAAA,IAAI,KAAA,CAAM,IAAA,KAAS,eAAA,IAAmB,CAAC,KAAA,CAAM,QAAQ,KAAA,CAAM,OAAA,CAAQ,OAAO,CAAA,EAAG,OAAO,MAAA;AACpF,EAAA,KAAA,MAAW,KAAA,IAAS,KAAA,CAAM,OAAA,CAAQ,OAAA,EAAS;AACzC,IAAA,IAAI,KAAA,CAAM,IAAA,KAAS,UAAA,IAAc,KAAA,CAAM,SAAS,iBAAA,EAA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A,UAAA,EAAa,UAAU,CAAA,YAAA,EAAe,OAAO,kEAAkE,SAAA,CAAU,IAAA,CAAK,IAAI,CAAC,CAAA,CAAA,CAAA;AAC5I;AAOO,SAAS,oBAAA,CACd,UACA,QAAA,EACoB;AACpB,EAAA,MAAM,KAAA,GAAQ,UAAU,IAAA,EAAK;AAC7B,EAAA,IAAI,CAAC,OAAO,OAAO,MAAA;AACnB,EAAA,MAAM,OAAA,GAAU,gBAAgB,QAAQ,CAAA;AAGxC,EAAA,MAAM,MAAA,GAAS,OAAA,CAAQ,IAAA,CAAK,CAAC,CAAC,EAAE,CAAA,KAAM,EAAA,KAAO,KAAK,CAAA,GAAI,MAAA,GAAY,aAAA,CAAc,OAAO,QAAQ,CAAA;AAC/F,EAAA,IAAI,MAAA,EAAQ,UAAU,OAAO,MAAA;AAC7B,EAAA,MAAM,UAAA,GAAa,OAAA,CAAQ,IAAA,CAAK,CAAC,CAAC,EAAE,CAAA,KAAM,EAAA,KAAO,KAAK,CAAA,GAAI,KAAA,GAAQ,MAAA,EAAQ,UAAA;AAC1E,EAAA,MAAM,KAAA,GAAQ,OAAA,CAAQ,IAAA,CAAK,CAAC,CAAC,EAAE,CAAA,KAAM,EAAA,KAAO,UAAU,CAAA,GAAI,CAAC,CAAA;AAC3D,EAAA,OAAO,UAAA,IAAc,KAAA,GAAQ,wBAAA,CAAyB,UAAA,EAAY,KAAK,CAAA,GAAI,MAAA;AAC7E","file":"chunk-6ZM5X2XW.js","sourcesContent":["/**\n * The tool-approval card a harness raises for `permissionMode: \"interactive\"`: a `message_start`\n * carrying an `AskUserQuestion` tool call whose input has an `approval` description. The\n * normalizer turns it into a `question` event with `approval`; a host that reads the harness's\n * events directly (the REPL, a single-shot run) recognises it with {@link approvalCardOf} and\n * answers with {@link APPROVE_ONCE} or {@link DENY} through `harness.answerQuestion`.\n */\nimport type { AgentEvent } from \"./types.js\";\n\n/** The one positive answer of an approval card. */\nexport const APPROVE_ONCE = \"Approve once\";\n/** The negative answer of an approval card. */\nexport const DENY = \"Deny\";\n\n/** What a host needs to ask and answer one approval card. */\nexport interface ApprovalCard {\n /** The question text; the key `answerQuestion` takes. */\n question: string;\n requestId?: string;\n kind: \"command\" | \"file\" | \"permissions\" | \"mcp\";\n /** Bounded plain text of what the tool call is about to do. */\n details: string[];\n}\n\n/** The approval card an event carries, else `undefined`. */\nexport function approvalCardOf(event: AgentEvent): ApprovalCard | undefined {\n if (event.type !== \"message_start\" || !Array.isArray(event.message.content)) return undefined;\n for (const block of event.message.content) {\n if (block.type !== \"tool_use\" || block.name !== \"AskUserQuestion\") continue;\n const input = block.input as Record<string, unknown> | undefined;\n const approval = input?.approval as { kind?: unknown; details?: unknown } | undefined;\n const questions = input?.questions;\n const first = Array.isArray(questions) ? (questions[0] as { question?: unknown }) : undefined;\n if (\n !approval ||\n typeof first?.question !== \"string\" ||\n !Array.isArray(approval.details) ||\n !approval.details.every((d) => typeof d === \"string\")\n ) {\n continue;\n }\n return {\n question: first.question,\n ...(typeof input?.requestId === \"string\" ? { requestId: input.requestId } : {}),\n kind: approval.kind as ApprovalCard[\"kind\"],\n details: approval.details as string[],\n };\n }\n return undefined;\n}\n","/**\n * AI endpoint transport for the `claude-sdk` harness — the Claude Agent SDK's\n * child-process environment.\n *\n * {@link buildClaudeEndpointEnv} takes an **AI provider registry entry** and\n * is what the harness calls, on every transport. It is plan §2.3's\n * `buildEndpointEnv` for the claude-sdk row (named for the harness 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 harness'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 harness.\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 * The last valid `cost-state` entry of this session, read during the same\n * pass. The CLI restores its run totals from it on `--resume`, so it is the\n * baseline of the resumed spawn's first `total_cost_usd` and `modelUsage`.\n * `null` when the transcript holds none (the CLI then starts from zero) or\n * could not be read.\n */\n costState: TranscriptCostState | null;\n}\n\n/**\n * The run totals the Claude Code CLI saves into a transcript as a\n * `{\"type\":\"cost-state\"}` entry and restores on `--resume`.\n *\n * @category Transcript repair\n */\nexport interface TranscriptCostState {\n /** The CLI's run-cumulative `total_cost_usd` at the time of the save. */\n totalCostUSD: number;\n /** The CLI's run-cumulative per-model usage, keyed by model id, in SDK field names. */\n modelUsage: Record<string, Record<string, number>>;\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 * Per-model counters the CLI's `cost-state` schema requires (checked against\n * `@anthropic-ai/claude-agent-sdk` 0.3.289; `thinkingTokens` is optional there).\n */\nconst COST_STATE_MODEL_FIELDS = [\n \"inputTokens\",\n \"outputTokens\",\n \"cacheReadInputTokens\",\n \"cacheCreationInputTokens\",\n \"webSearchRequests\",\n \"costUSD\",\n] as const;\n\nfunction isCount(value: unknown): value is number {\n return typeof value === \"number\" && Number.isFinite(value) && value >= 0;\n}\n\n/**\n * Read a `cost-state` entry of `sessionId` off one JSONL line, or `null` when\n * the line is anything else. Mirrors the CLI, which skips an entry that fails\n * its schema and keeps the last valid one, so an entry with a bad total or a\n * per-model counter that is not a non-negative number is not a restorable\n * state. Leading NUL bytes (a torn append) are stripped, as the CLI does.\n */\nfunction readCostState(line: string, sessionId: string): TranscriptCostState | null {\n if (!line.includes('\"cost-state\"')) return null;\n let entry: { type?: unknown; sessionId?: unknown; totalCostUSD?: unknown; modelUsage?: unknown };\n try {\n entry = JSON.parse(line.replace(/^\\0+/, \"\"));\n } catch {\n return null;\n }\n if (entry.type !== \"cost-state\" || entry.sessionId !== sessionId) return null;\n const total = entry.totalCostUSD;\n if (!isCount(total)) return null;\n const usage = entry.modelUsage;\n if (!usage || typeof usage !== \"object\" || Array.isArray(usage)) return null;\n for (const model of Object.values(usage)) {\n if (!model || typeof model !== \"object\") return null;\n const counters = model as Record<string, unknown>;\n if (!COST_STATE_MODEL_FIELDS.every((field) => isCount(counters[field]))) return null;\n }\n return {\n totalCostUSD: total,\n modelUsage: usage as Record<string, Record<string, number>>,\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 costState: null,\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 let costState: TranscriptCostState | null = null;\n try {\n await withFsDeadline(\n `scan transcript ${filePath}`,\n async () => {\n for await (const line of streamLines(store.read(filePath))) {\n repairLine(line, counters);\n costState = readCostState(line, sessionId) ?? costState;\n }\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 result.costState = costState;\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","/**\n * Pre-first-turn resume probe for the Claude Agent SDK harness.\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 harness 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 harness'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","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 \"./harnesses/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","import {\n type AIProviderEntry,\n type AIProviderRegistry,\n type MergedAIProviderRegistry,\n parseModelRef,\n registryEntries,\n} from \"@skaile/workspaces/core/provider-registry\";\nimport { BUILTIN_HARNESS_CATALOG } from \"./registry.js\";\n\n/**\n * The line for a selected provider entry whose surface the Claude Agent SDK cannot speak, or\n * `undefined` when there is none. `skaile run` and `skaile repl` print it as one `!` line (runner\n * `credential-notice.ts`), so the harness logs the same text at `info`, which reaches the log\n * database but not the terminal (p1475).\n *\n * @param providerId - The entry the run selected.\n * @param entry - That registry entry.\n */\nexport function unsupportedSurfaceNotice(\n providerId: string,\n entry: AIProviderEntry,\n): string | undefined {\n const supported = BUILTIN_HARNESS_CATALOG[\"claude-sdk\"].surfaces;\n const surface = \"surface\" in entry ? entry.surface : undefined;\n if (!surface || !supported || supported.includes(surface)) return undefined;\n return `provider '${providerId}' uses the '${surface}' surface, which the Claude Agent SDK cannot speak (it speaks: ${supported.join(\", \")})`;\n}\n\n/**\n * {@link unsupportedSurfaceNotice} for a session: the entry its model selector names (an entry id,\n * or the head of `<providerId>/<modelId>`). `undefined` with no selector, an id no entry lists\n * (it selects no provider), or an entry it speaks.\n */\nexport function sessionSurfaceNotice(\n registry: AIProviderRegistry | MergedAIProviderRegistry,\n modelRef: string | undefined,\n): string | undefined {\n const named = modelRef?.trim();\n if (!named) return undefined;\n const entries = registryEntries(registry);\n // An id no entry lists (`sonnet`, `claude-sonnet-4-5`) selects no provider: the harness takes\n // it as typed on the endpoint it would use with no selector.\n const parsed = entries.some(([id]) => id === named) ? undefined : parseModelRef(named, registry);\n if (parsed?.fallback) return undefined;\n const providerId = entries.some(([id]) => id === named) ? named : parsed?.providerId;\n const entry = entries.find(([id]) => id === providerId)?.[1];\n return providerId && entry ? unsupportedSurfaceNotice(providerId, entry) : undefined;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../bridge/src/approval-card.ts","../bridge/src/cloud.ts","../bridge/src/harnesses/scrub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A,KAAO,UAAU,CAAA,GAAI,CAAC,CAAA;AAC3D,EAAA,OAAO,UAAA,IAAc,KAAA,GAAQ,wBAAA,CAAyB,UAAA,EAAY,KAAK,CAAA,GAAI,MAAA;AAC7E","file":"chunk-KVTV4LT2.js","sourcesContent":["/**\n * The tool-approval card a harness raises for `permissionMode: \"interactive\"`: a `message_start`\n * carrying an `AskUserQuestion` tool call whose input has an `approval` description. The\n * normalizer turns it into a `question` event with `approval`; a host that reads the harness's\n * events directly (the REPL, a single-shot run) recognises it with {@link approvalCardOf} and\n * answers with {@link APPROVE_ONCE} or {@link DENY} through `harness.answerQuestion`.\n */\nimport type { AgentEvent } from \"./types.js\";\n\n/** The one positive answer of an approval card. */\nexport const APPROVE_ONCE = \"Approve once\";\n/** The negative answer of an approval card. */\nexport const DENY = \"Deny\";\n\n/** What a host needs to ask and answer one approval card. */\nexport interface ApprovalCard {\n /** The question text; the key `answerQuestion` takes. */\n question: string;\n requestId?: string;\n kind: \"command\" | \"file\" | \"permissions\" | \"mcp\";\n /** Bounded plain text of what the tool call is about to do. */\n details: string[];\n}\n\n/** The approval card an event carries, else `undefined`. */\nexport function approvalCardOf(event: AgentEvent): ApprovalCard | undefined {\n if (event.type !== \"message_start\" || !Array.isArray(event.message.content)) return undefined;\n for (const block of event.message.content) {\n if (block.type !== \"tool_use\" || block.name !== \"AskUserQuestion\") continue;\n const input = block.input as Record<string, unknown> | undefined;\n const approval = input?.approval as { kind?: unknown; details?: unknown } | undefined;\n const questions = input?.questions;\n const first = Array.isArray(questions) ? (questions[0] as { question?: unknown }) : undefined;\n if (\n !approval ||\n typeof first?.question !== \"string\" ||\n !Array.isArray(approval.details) ||\n !approval.details.every((d) => typeof d === \"string\")\n ) {\n continue;\n }\n return {\n question: first.question,\n ...(typeof input?.requestId === \"string\" ? { requestId: input.requestId } : {}),\n kind: approval.kind as ApprovalCard[\"kind\"],\n details: approval.details as string[],\n };\n }\n return undefined;\n}\n","/**\n * AI endpoint transport for the `claude-sdk` harness — the Claude Agent SDK's\n * child-process environment.\n *\n * {@link buildClaudeEndpointEnv} takes an **AI provider registry entry** and\n * is what the harness calls, on every transport. It is plan §2.3's\n * `buildEndpointEnv` for the claude-sdk row (named for the harness 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 harness'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 harness.\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 * The last valid `cost-state` entry of this session, read during the same\n * pass. The CLI restores its run totals from it on `--resume`, so it is the\n * baseline of the resumed spawn's first `total_cost_usd` and `modelUsage`.\n * `null` when the transcript holds none (the CLI then starts from zero) or\n * could not be read.\n */\n costState: TranscriptCostState | null;\n}\n\n/**\n * The run totals the Claude Code CLI saves into a transcript as a\n * `{\"type\":\"cost-state\"}` entry and restores on `--resume`.\n *\n * @category Transcript repair\n */\nexport interface TranscriptCostState {\n /** The CLI's run-cumulative `total_cost_usd` at the time of the save. */\n totalCostUSD: number;\n /** The CLI's run-cumulative per-model usage, keyed by model id, in SDK field names. */\n modelUsage: Record<string, Record<string, number>>;\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 * Per-model counters the CLI's `cost-state` schema requires (checked against\n * `@anthropic-ai/claude-agent-sdk` 0.3.289; `thinkingTokens` is optional there).\n */\nconst COST_STATE_MODEL_FIELDS = [\n \"inputTokens\",\n \"outputTokens\",\n \"cacheReadInputTokens\",\n \"cacheCreationInputTokens\",\n \"webSearchRequests\",\n \"costUSD\",\n] as const;\n\nfunction isCount(value: unknown): value is number {\n return typeof value === \"number\" && Number.isFinite(value) && value >= 0;\n}\n\n/**\n * Read a `cost-state` entry of `sessionId` off one JSONL line, or `null` when\n * the line is anything else. Mirrors the CLI, which skips an entry that fails\n * its schema and keeps the last valid one, so an entry with a bad total or a\n * per-model counter that is not a non-negative number is not a restorable\n * state. Leading NUL bytes (a torn append) are stripped, as the CLI does.\n */\nfunction readCostState(line: string, sessionId: string): TranscriptCostState | null {\n if (!line.includes('\"cost-state\"')) return null;\n let entry: { type?: unknown; sessionId?: unknown; totalCostUSD?: unknown; modelUsage?: unknown };\n try {\n entry = JSON.parse(line.replace(/^\\0+/, \"\"));\n } catch {\n return null;\n }\n if (entry.type !== \"cost-state\" || entry.sessionId !== sessionId) return null;\n const total = entry.totalCostUSD;\n if (!isCount(total)) return null;\n const usage = entry.modelUsage;\n if (!usage || typeof usage !== \"object\" || Array.isArray(usage)) return null;\n for (const model of Object.values(usage)) {\n if (!model || typeof model !== \"object\") return null;\n const counters = model as Record<string, unknown>;\n if (!COST_STATE_MODEL_FIELDS.every((field) => isCount(counters[field]))) return null;\n }\n return {\n totalCostUSD: total,\n modelUsage: usage as Record<string, Record<string, number>>,\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 costState: null,\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 let costState: TranscriptCostState | null = null;\n try {\n await withFsDeadline(\n `scan transcript ${filePath}`,\n async () => {\n for await (const line of streamLines(store.read(filePath))) {\n repairLine(line, counters);\n costState = readCostState(line, sessionId) ?? costState;\n }\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 result.costState = costState;\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","/**\n * Pre-first-turn resume probe for the Claude Agent SDK harness.\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 harness 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 harness'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","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 \"./harnesses/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","import {\n type AIProviderEntry,\n type AIProviderRegistry,\n type MergedAIProviderRegistry,\n parseModelRef,\n registryEntries,\n} from \"@skaile/workspaces/core/provider-registry\";\nimport { BUILTIN_HARNESS_CATALOG } from \"./registry.js\";\n\n/**\n * The line for a selected provider entry whose surface the Claude Agent SDK cannot speak, or\n * `undefined` when there is none. `skaile run` and `skaile repl` print it as one `!` line (runner\n * `credential-notice.ts`), so the harness logs the same text at `info`, which reaches the log\n * database but not the terminal (p1475).\n *\n * @param providerId - The entry the run selected.\n * @param entry - That registry entry.\n */\nexport function unsupportedSurfaceNotice(\n providerId: string,\n entry: AIProviderEntry,\n): string | undefined {\n const supported = BUILTIN_HARNESS_CATALOG[\"claude-sdk\"].surfaces;\n const surface = \"surface\" in entry ? entry.surface : undefined;\n if (!surface || !supported || supported.includes(surface)) return undefined;\n return `provider '${providerId}' uses the '${surface}' surface, which the Claude Agent SDK cannot speak (it speaks: ${supported.join(\", \")})`;\n}\n\n/**\n * {@link unsupportedSurfaceNotice} for a session: the entry its model selector names (an entry id,\n * or the head of `<providerId>/<modelId>`). `undefined` with no selector, an id no entry lists\n * (it selects no provider), or an entry it speaks.\n */\nexport function sessionSurfaceNotice(\n registry: AIProviderRegistry | MergedAIProviderRegistry,\n modelRef: string | undefined,\n): string | undefined {\n const named = modelRef?.trim();\n if (!named) return undefined;\n const entries = registryEntries(registry);\n // An id no entry lists (`sonnet`, `claude-sonnet-4-5`) selects no provider: the harness takes\n // it as typed on the endpoint it would use with no selector.\n const parsed = entries.some(([id]) => id === named) ? undefined : parseModelRef(named, registry);\n if (parsed?.fallback) return undefined;\n const providerId = entries.some(([id]) => id === named) ? named : parsed?.providerId;\n const entry = entries.find(([id]) => id === providerId)?.[1];\n return providerId && entry ? unsupportedSurfaceNotice(providerId, entry) : undefined;\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { resolveSkWorkspaceConfig, localConnectorMountDir } from './chunk-
|
|
1
|
+
import { resolveSkWorkspaceConfig, localConnectorMountDir } from './chunk-FZO64PLQ.js';
|
|
2
2
|
import { parseFrontmatter } from './chunk-GNUA7XT2.js';
|
|
3
3
|
import { createLogger } from './chunk-BOFL7GIF.js';
|
|
4
4
|
import { readFileSync, existsSync, readdirSync, statSync } from 'fs';
|
|
@@ -377,11 +377,14 @@ function withMaterializedConnectorDeclarations(base, projectDir) {
|
|
|
377
377
|
}
|
|
378
378
|
return [...byId.values()];
|
|
379
379
|
}
|
|
380
|
+
function accessOf(access) {
|
|
381
|
+
return access === "read-write" ? "read-write" : "read-only";
|
|
382
|
+
}
|
|
380
383
|
function workspaceConnectorToDeclaration(c, projectDir) {
|
|
381
384
|
const decl = {
|
|
382
385
|
id: c.id,
|
|
383
386
|
driver: c.driver,
|
|
384
|
-
access: c.access
|
|
387
|
+
access: accessOf(c.access),
|
|
385
388
|
auth: c.auth,
|
|
386
389
|
options: c.options
|
|
387
390
|
};
|
|
@@ -424,7 +427,7 @@ function resolvedConfigToDeclarations(resolved) {
|
|
|
424
427
|
const decl = {
|
|
425
428
|
id: m.id,
|
|
426
429
|
driver: m.driver,
|
|
427
|
-
access: m.access
|
|
430
|
+
access: accessOf(m.access),
|
|
428
431
|
...m.access == null ? { accessDefaulted: true } : {},
|
|
429
432
|
auth: m.auth,
|
|
430
433
|
options: m.options,
|
|
@@ -449,7 +452,7 @@ function resolvedConfigToDeclarations(resolved) {
|
|
|
449
452
|
const decl = {
|
|
450
453
|
id: c.id,
|
|
451
454
|
driver: c.driver,
|
|
452
|
-
access: c.access
|
|
455
|
+
access: accessOf(c.access),
|
|
453
456
|
...c.access == null ? { accessDefaulted: true } : {},
|
|
454
457
|
auth: c.auth,
|
|
455
458
|
options: c.options
|
|
@@ -499,5 +502,5 @@ function resolveAuthRef(auth, mountId) {
|
|
|
499
502
|
}
|
|
500
503
|
|
|
501
504
|
export { ConnectorFieldMissingError, ConnectorStartupError, EnvSecretProvider, ForgeSecretProvider, InMemorySecretProvider, LegacyAuthGrammarError, LockedSecretProvider, OAuthRequiredError, PreMintedSecretProvider, SecretProviderChain, createCliSecretProviderChain, createForgeSecretProviderChain, deriveSingleMaterializedConnectorDeclaration, fromMaterializedConnectorMd, isKnownSecretRef, loadConnectorDeclarations, loadMaterializedConnectorDeclarations, loadYamlConnectorDeclarations, readUnavailableMarker, resolveAuthRef, resolveBackendAuthFor, resolvedConfigToDeclarations, withMaterializedConnectorDeclarations };
|
|
502
|
-
//# sourceMappingURL=chunk-
|
|
503
|
-
//# sourceMappingURL=chunk-
|
|
505
|
+
//# sourceMappingURL=chunk-LMADWO4Q.js.map
|
|
506
|
+
//# sourceMappingURL=chunk-LMADWO4Q.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../connectors/src/connector-types.ts","../connectors/src/materialized-connectors.ts","../connectors/src/secrets.ts","../connectors/src/config.ts"],"names":[],"mappings":";;;;;;;AAqHO,SAAS,sBAAsB,KAAA,EAA+C;AACnF,EAAA,IAAI,UAAU,MAAA,IAAa,KAAA,KAAU,IAAA,IAAQ,KAAA,KAAU,OAAO,OAAO,MAAA;AACrE,EAAA,IAAI,OAAO,KAAA,KAAU,QAAA,IA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EAC0B;AAC1B,EAAA,IAAI,CAAC,MAAM,OAAO,MAAA;AAElB,EAAA,IAAI,SAAS,SAAA,EAAW;AACtB,IAAA,OAAO,EAAE,IAAA,EAAM,SAAA,EAAW,KAAA,EAAO,EAAA,EAAI,KAAK,IAAA,EAAK;AAAA,EACjD;AACA,EAAA,IAAI,IAAA,CAAK,UAAA,CAAW,MAAM,CAAA,EAAG;AAC3B,IAAA,OAAO,EAAE,IAAA,EAAM,KAAA,EAAO,KAAA,EAAO,IAAA,CAAK,MAAM,MAAA,CAAO,MAAM,CAAA,EAAG,GAAA,EAAK,IAAA,EAAK;AAAA,EACpE;AAIA,EAAA,MAAM,IAAI,sBAAA,CAAuB,IAAA,EAAM,OAAO,CAAA;AAChD","file":"chunk-LMADWO4Q.js","sourcesContent":["/**\n * Connector adapter infrastructure types.\n *\n * Connectors are external backends (databases, KV stores, object stores,\n * in-process state, git repos, etc.). A connector exposes up to two faces: a\n * `ToolFace` (agents access it through injected tools) and/or a\n * `FilesystemFace` (the connector projects content into a mounted directory).\n *\n * @docLink packages/connectors/concepts#connector-types\n */\n\nimport type {\n ConnectorContent,\n ConnectorEntry,\n ListOptions,\n OperationDescriptor,\n SearchOptions,\n SearchResult,\n SyncOptions,\n SyncResult,\n WatchHandle,\n WatchOptions,\n} from \"./shared-types.js\";\n\nexport type { OperationDescriptor } from \"./shared-types.js\";\n\nimport type { ConnectorPushState, Logger } from \"@skaile/workspaces/types\";\nimport type { SecretProvider } from \"./secrets.js\";\n\n// ── Connector declaration (runtime config, resolved from skaile.yaml) ────────\n\n/**\n * Parsed connector configuration from `skaile.yaml`, passed to `ConnectorAdapter.connect()` and held by `ConnectorManager`.\n * @docLink packages/connectors/concepts#connector-declaration\n */\nexport interface ConnectorDeclaration {\n /** Unique identifier for this connector instance. */\n id: string;\n /** Driver type: \"postgres\", \"redis\", \"memory\", \"xstate\", \"yjs\", etc. */\n driver: string;\n /**\n * Human-readable connection name, projected from the materialized CONNECTOR.md\n * frontmatter `label`. The platform resource-explorer tab renders this over the\n * driver name when present; absent for connectors with no configured name.\n */\n label?: string;\n /** Access level enforced by the manager. */\n access: \"read-only\" | \"read-write\";\n /**\n * True when the source set no `access` and the parser filled in the\n * `read-only` default. The git driver's read-only mode (discard edits, never\n * push) runs only on an explicit `read-only`, so an undeclared mount keeps\n * its earlier behaviour.\n */\n accessDefaulted?: true;\n /** Credential reference: \"env:VAR_NAME\" or inline value. */\n auth?: string;\n /**\n * Backend provider link id for `auth: \"backend\"` connectors. The runner's\n * token-refresh mediator passes this as the `host.refresh_credential` `id` so\n * the platform resolves the credential against the right provider link.\n */\n providerLinkId?: string;\n /**\n * Operating mode for connectors that manage a working copy. Orthogonal to\n * faces. `agent` = the agent drives the source natively (e.g. native git) and\n * the connector only provisions short-lived credentials. `sync` = the\n * connector owns the working copy (clone + watch + auto-commit/pull). Absent =\n * the driver's legacy `options.{session,sync,lifecycle}` blocks decide.\n */\n mode?: \"agent\" | \"sync\";\n /** Driver-specific configuration. */\n options?: Record<string, unknown>;\n /**\n * Owner-authored instruction text projected from the materialized\n * CONNECTOR.md body (preset custom instructions). Injected eagerly into the\n * agent system prompt. Absent when the body is empty.\n */\n instructions?: string;\n /** Filesystem-face config — only meaningful for mountable connectors. */\n mount?: {\n /** Source URL or path (repo URL, bucket name, host path). */\n source: string;\n /** Override mount target directory (default: `.mounts/<id>/`). */\n target?: string;\n /** Watch flag: omitted → watch read-write, skip read-only. */\n watch?: boolean;\n /** Expert-only: expose the resolved credential to the agent CLI. */\n exposeAccessToken?: boolean;\n /** Optional access-token TTL override (seconds). */\n accessTokenTTL?: number;\n };\n /**\n * Set by the host when it has already decided this connector cannot be\n * attached (e.g. a cloud mount whose host-side build failed). The manager\n * never calls the driver for it and reports it as failed with this reason.\n */\n unavailable?: UnavailableMarker;\n}\n\n/**\n * Why the host declared a connector without making it available. `reason` is\n * a short machine-readable token chosen by the host; `detail` is its prose.\n * @docLink packages/connectors/concepts#connector-declaration\n */\nexport interface UnavailableMarker {\n reason: string;\n detail?: string;\n}\n\n/**\n * Read an `unavailable:` value from an untyped declaration. Absent, `null` and\n * `false` mean \"not marked\". Any other value marks the connector unavailable —\n * a host that wrote the key meant it. A plain string is taken as the reason;\n * anything else that is not a `{ reason, detail? }` object gets a generic one.\n * @docLink packages/connectors/concepts#connector-declaration\n */\nexport function readUnavailableMarker(value: unknown): UnavailableMarker | undefined {\n if (value === undefined || value === null || value === false) return undefined;\n if (typeof value === \"string\" && value.trim() !== \"\") return { reason: value };\n if (typeof value !== \"object\") return { reason: \"unavailable\" };\n const { reason, detail } = value as { reason?: unknown; detail?: unknown };\n const marker: UnavailableMarker = {\n reason: typeof reason === \"string\" && reason.trim() !== \"\" ? reason : \"unavailable\",\n };\n if (typeof detail === \"string\" && detail.trim() !== \"\") marker.detail = detail;\n return marker;\n}\n\n// ── Connector handle (returned by adapter.connect) ───────────────────────────\n\n/**\n * Live state of a connected backend, returned by `Connector.connect()` (or the\n * legacy `ConnectorAdapter.connect()`) and held by `ConnectorManager`.\n * @docLink packages/connectors/concepts#connector-handle\n */\nexport interface ConnectorHandle {\n /** Connector declaration ID. */\n readonly id: string;\n /** Driver name. */\n readonly driver: string;\n /** Effective access level. */\n readonly access: \"read-only\" | \"read-write\";\n /** Lifecycle status. Set by every `Connector`. */\n status: \"connecting\" | \"connected\" | \"error\" | \"disconnected\";\n /** Present iff the connector has a filesystem face and is mounted. */\n mountPath?: string;\n /** Adapter-specific state (connection pool, client, etc.). Opaque to callers. */\n state: unknown;\n}\n\n/** Optional capability a filesystem-face connector attaches to its handle state\n * when reads need an authoritative remote byte size rather than trusting local\n * filesystem metadata.\n */\nexport interface AuthoritativeSizeProvider {\n authoritativeSize(relPath: string): Promise<number | null>;\n}\n\n// ── Connector change event ────────────────────────────────────────────────────\n\n/**\n * Change event emitted by a connector adapter's `watch()` implementation.\n * @docLink packages/connectors/concepts#connector-change-event\n */\nexport interface ConnectorChangeEvent {\n /** Relative path, key, table name, node ID, etc. */\n path: string;\n /** What happened. */\n action: \"create\" | \"edit\" | \"delete\" | \"conflict\";\n /** What caused the change. */\n source: \"filesystem\" | \"operation\" | \"remote\" | \"sync\";\n}\n\n// ── ConnectorManager info ────────────────────────────────────────────────────\n\n/**\n * Summary of a connected connector returned by `ConnectorManager.listConnectors()`.\n * @docLink packages/connectors/concepts#connector-info\n */\nexport interface ConnectorInfo {\n id: string;\n driver: string;\n /** Human-readable connection name; the resource-explorer tab renders this over `id`/`driver` when present. */\n label?: string;\n access: \"read-only\" | \"read-write\";\n /** Operation names this connector exposes as agent tools (via describeOperations). */\n operations: string[];\n}\n\n/**\n * Bulk connect/disconnect result returned by `ConnectorManager.connectAll()` and `disconnectAll()`.\n * @docLink packages/connectors/concepts#connector-report\n */\nexport interface ConnectorReport {\n results: Array<{ id: string; connected: boolean; error?: string }>;\n}\n\n// ── Field spec (connector credential/config declarations) ────────────────────\n\n/**\n * Input types for `ConnectorFieldSpec`. Controls validation rules and the Forge UI affordance.\n * @docLink packages/connectors/concepts#field-type\n */\nexport type FieldType =\n | \"text\" // plain string\n | \"password\" // sensitive; always stored via SecretProvider\n | \"api-key\" // alias for password with specific UI affordance\n | \"url\" // validated URL string\n | \"oauth\" // triggers OAuth flow; oauthService required\n | \"select\" // enum; choices required and non-empty\n | \"boolean\" // default must be \"true\" or \"false\" if provided\n | \"number\"; // default must be a parseable numeric string if provided\n\n/**\n * Declares one credential or configuration field that a connector adapter requires.\n * Used by `ConnectorManager.resolveFields()` and the Forge settings UI.\n * @docLink packages/connectors/concepts#connector-field-spec\n */\nexport interface ConnectorFieldSpec {\n /** Machine name used as the options key in skaile.yaml. */\n key: string;\n /** Human-readable label for the forge settings UI. */\n label: string;\n /** Tooltip / help text. */\n description?: string;\n /** Input type. Controls validation rules and UI affordance in the forge settings panel. */\n type: FieldType;\n /** Whether the adapter refuses to connect when this field is missing. */\n required: boolean;\n /** String fallback used when not provided and not required. */\n default?: string;\n /** Forge UI masks the value; value is never logged. */\n sensitive: boolean;\n /** UI grouping: \"Authentication\", \"Connection\", \"Options\". */\n group?: string;\n /**\n * Required when type === \"select\"; must be non-empty.\n */\n choices?: string[];\n /**\n * Required when type === \"oauth\".\n * Identifies the OAuth service, e.g. \"google\".\n * Used to call OAuthSecretProvider.initiateFlow(oauthService, account).\n * oauth fields must be declared AFTER any field they reference (e.g., \"account\").\n */\n oauthService?: string;\n /** Example value shown as placeholder text in the forge settings UI. */\n example?: string;\n}\n\n/**\n * Thrown by `ConnectorManager.connectAll()` and `resolveFields()` when a required\n * adapter field cannot be resolved through the `SecretProviderChain`. Carries the\n * connector ID, the missing field spec, the ref that was tried, and the available\n * providers for actionable error messages.\n * @docLink packages/connectors/concepts#connector-field-missing-error\n */\nexport class ConnectorFieldMissingError extends Error {\n readonly connectorId: string;\n readonly field: ConnectorFieldSpec;\n readonly triedRef: string;\n readonly availableProviders: string[];\n\n constructor(opts: {\n connectorId: string;\n field: ConnectorFieldSpec;\n triedRef: string;\n availableProviders: string[];\n }) {\n super(\n `Connector \"${opts.connectorId}\" is missing required field \"${opts.field.key}\" ` +\n `(tried: ${opts.triedRef || \"(none)\"}). ` +\n `Available providers: ${opts.availableProviders.join(\", \") || \"(none)\"}`,\n );\n this.name = \"ConnectorFieldMissingError\";\n this.connectorId = opts.connectorId;\n this.field = opts.field;\n this.triedRef = opts.triedRef;\n this.availableProviders = opts.availableProviders;\n }\n}\n\n// ── Runtime skill descriptor ──────────────────────────────────────────────────\n\n/**\n * Instance-specific skill descriptor returned by `ConnectorAdapter.describeSkill()`.\n * Returned by `ConnectorManager.listSkills()` to surface connector capabilities to the agent.\n * @docLink packages/connectors/concepts#runtime-skill-descriptor\n */\nexport interface RuntimeSkillDescriptor {\n /** Connector instance id, e.g. \"gmail-work\". */\n id: string;\n /** Short label: \"Gmail — work@company.com\". */\n name: string;\n /** Instance-specific description: \"Read and write email for work@company.com\". */\n description: string;\n /** Category for grouping in the forge UI. */\n category: string;\n access: \"read-only\" | \"read-write\";\n /** Operation names (without loading full defs) for agent planning. */\n toolNames: string[];\n}\n\n// ── Token mediator (Tier-2 credential mediation) ─────────────────────────────\n\n/**\n * Result of a single `TokenMediator` call. Mirrors\n * `AccessTokenResponseEvent.result` from `@skaile/workspaces/types` so the runner\n * can pass it straight through.\n *\n * @docLink packages/connectors/api-reference#token-mediator\n */\nexport type TokenMediatorResult =\n | {\n ok: true;\n /** Access token to use for the next git operation. */\n token: string;\n /**\n * ISO-8601 expiry, or `null` for indefinite tokens (static PATs). Drives\n * whether the driver schedules a refresh tick.\n */\n expiresAt: string | null;\n /** Optional scope/permissions list, surfaced in audit logs. */\n scope?: string[];\n }\n | {\n ok: false;\n code: \"not-configured\" | \"revoked\" | \"provider-error\" | \"backend-error\" | \"timeout\";\n /** Human-readable detail, never carries secrets. */\n message: string;\n };\n\n/**\n * Function signature mountable connectors use to acquire a fresh access token\n * from the runner-owned backend mediator. Implemented by the runner: emits a\n * `request_access_token` command over the transport and resolves with the\n * matching `access_token_response` payload.\n *\n * Connectors MUST treat this as the only token source when the parsed\n * `MountAuthRef.kind === 'backend'`. Local minting (PAT, OAuth, GitHub App)\n * has been removed from the runner — provider dispatch lives on the platform.\n *\n * @docLink packages/connectors/api-reference#token-mediator\n */\nexport type TokenMediator = (input: {\n connectorId: string;\n reason: \"initial\" | \"refresh\" | \"retry-401\";\n /**\n * Connector driver, used by the runner mediator to pick the platform refresh\n * `kind`; absent on `initial` and for legacy callers.\n */\n driver?: string;\n /**\n * Backend provider link id — the `id` the platform `host.refresh_credential`\n * capability resolves the credential against. Absent on `initial` and for\n * legacy callers.\n */\n providerLinkId?: string;\n /**\n * The connector's declaration id, bound from the declaration like `driver`\n * and `providerLinkId`. The runner sends it next to the link id on a git\n * refresh, so a read-only reference sharing its link with a read-write\n * mount is refreshed read-only. Absent on `initial` and for legacy callers.\n */\n declarationId?: string;\n}) => Promise<TokenMediatorResult>;\n\n// ── S3 presigner (backend-signed S3 reads) ───────────────────────────────────\n\n/**\n * Request to the platform's runtime capability `host.s3_presign`. `mountId` is\n * the connector id of an `auth: backend` S3 mount in this session; bucket,\n * prefix and endpoint come from the platform's copy of that declaration.\n */\nexport type S3PresignRequest =\n | { mountId: string; op: \"list\"; continuationToken?: string }\n | { mountId: string; op: \"get\"; keys: string[] };\n\n/**\n * Answer from `host.s3_presign`. `list` carries one ListObjectsV2 URL, `get`\n * one GetObject URL per key; folder markers (keys ending in `/`) are listed in\n * `skipped` instead. Every URL expires at `expiresAt` (ten minutes today).\n */\nexport type S3PresignResult =\n | { ok: true; op: \"list\"; url: string; expiresAt: string }\n | {\n ok: true;\n op: \"get\";\n urls: { key: string; url: string }[];\n skipped: { key: string; reason: string }[];\n expiresAt: string;\n }\n | { ok: false; code: string; message: string };\n\n/**\n * Presign client for `auth: backend` S3 mounts, implemented by the runner over\n * the same remote-capability channel as {@link TokenMediator}. The S3 keys stay\n * in the backend; the container only ever sees short-lived read URLs.\n * Never throws: transport failures resolve as `{ ok: false, code: \"backend-error\" }`.\n */\nexport type S3Presigner = (request: S3PresignRequest) => Promise<S3PresignResult>;\n\n// ── Unified connector types ───────────────────────────────────────────────────\n\n/**\n * Context passed to `Connector.connect()` by `ConnectorManager`.\n * @docLink packages/connectors/concepts#connect-context\n */\nexport interface ConnectContext {\n /**\n * Absolute project directory the owning `ConnectorManager` runs for (always set by the manager). A connector that needs\n * an optional npm peer looks in this project's `node_modules` first.\n */\n projectDir?: string;\n /** Secret provider for resolving credential references. */\n secrets?: SecretProvider;\n /**\n * Backend token mediator — present for `auth: backend` connectors of either\n * face (filesystem or tool), so mount refresh and tool-face OAuth flows share\n * one path.\n */\n tokenMediator?: TokenMediator;\n /**\n * Backend S3 presigner — the read path for `auth: backend` S3 mounts. Absent\n * outside a platform-connected runner.\n */\n s3Presigner?: S3Presigner;\n /**\n * Absolute directory the manager allocated for the filesystem face.\n * Present iff `connector.filesystem != null`. The connector projects its\n * content here during `connect()` and sets `handle.mountPath`.\n */\n mountTarget?: string;\n /** Resolved credential/config fields (from `describeFields()`). */\n resolvedFields?: Record<string, string>;\n /**\n * Aborted when the owning `ConnectorManager` is disposed. Long-running\n * `connect()` implementations — notably background (deferred) filesystem\n * mounts — should observe this and bail out promptly so session cleanup\n * does not wait on a wedged remote.\n */\n abortSignal?: AbortSignal;\n}\n\n/**\n * Filesystem face — present ⇒ the connector is \"mountable\".\n * @docLink packages/connectors/concepts#filesystem-face\n */\nexport interface FilesystemFace {\n /** Pull latest remote state into the mounted directory. */\n sync(handle: ConnectorHandle, options?: SyncOptions): Promise<SyncResult>;\n}\n\n/**\n * Tool face — present ⇒ the connector exposes agent tools.\n * @docLink packages/connectors/concepts#tool-face\n */\nexport interface ToolFace {\n read?(handle: ConnectorHandle, path: string): Promise<ConnectorContent | null>;\n write?(handle: ConnectorHandle, path: string, content: ConnectorContent): Promise<void>;\n delete?(handle: ConnectorHandle, path: string): Promise<boolean>;\n list?(handle: ConnectorHandle, path?: string, options?: ListOptions): Promise<ConnectorEntry[]>;\n search?(handle: ConnectorHandle, query: string, options?: SearchOptions): Promise<SearchResult[]>;\n describeOperations(handle: ConnectorHandle): OperationDescriptor[];\n executeOp(\n handle: ConnectorHandle,\n operation: string,\n args: Record<string, unknown>,\n ): Promise<string>;\n describeSkill?(\n handle: ConnectorHandle,\n declaration: ConnectorDeclaration,\n ): RuntimeSkillDescriptor;\n}\n\n/**\n * The unified connector contract. A connector should expose at least one face\n * (`filesystem` and/or `tools`); `ConnectorManager` rejects a faceless\n * connector at connect time.\n * @docLink packages/connectors/concepts#connector\n */\nexport interface Connector {\n readonly name: string;\n /**\n * True when `connect()` for this declaration can only get its credential from\n * `ctx.tokenMediator`. A manager with neither a mediator nor a pre-mint then\n * fails the connect without calling the driver, whose failure path may write\n * shared state (the git driver's credential helper) the live session uses.\n */\n requiresTokenMediator?(declaration: ConnectorDeclaration): boolean;\n connect(declaration: ConnectorDeclaration, ctx: ConnectContext): Promise<ConnectorHandle>;\n disconnect(handle: ConnectorHandle): Promise<void>;\n readonly filesystem?: FilesystemFace;\n readonly tools?: ToolFace;\n describeFields?(): ConnectorFieldSpec[];\n setLogger?(logger: Logger): void;\n watch?(\n handle: ConnectorHandle,\n callback: (e: ConnectorChangeEvent) => void,\n options?: WatchOptions,\n ): WatchHandle;\n onHibernate?(handle: ConnectorHandle): Promise<ConnectorHookOutcome>;\n onSessionClose?(handle: ConnectorHandle): Promise<ConnectorHookOutcome>;\n}\n\n/**\n * Structured return of a lifecycle hook (`onHibernate` / `onSessionClose`).\n * `detail` is the same human-readable line a hook can return as a plain string;\n * `pushState` is what the connector can prove about its working copy, copied\n * onto the hook's `LifecycleResult`.\n */\nexport interface ConnectorHookReport {\n detail?: string;\n pushState?: ConnectorPushState;\n}\n\n/** What a lifecycle hook may return: a detail line, a structured report, or nothing. */\nexport type ConnectorHookOutcome = string | ConnectorHookReport | undefined;\n\n/**\n * Factory used by the connector registry.\n * @docLink packages/connectors/api-reference#connector-factory\n */\nexport type ConnectorFactory = () => Connector;\n\n/**\n * Per-connector bulk-connect result returned by `ConnectorManager.connectAll()`.\n * @docLink packages/connectors/concepts#connector-startup-report\n */\nexport interface ConnectorStartupReport {\n results: Array<{\n id: string;\n connected: boolean;\n /**\n * A fleet mount whose readiness check missed its deadline: registered with\n * `connected: false`, retried in the background, and not a failure.\n * `error` says why it is not live yet.\n */\n connecting?: boolean;\n mountPath?: string;\n error?: string;\n access?: \"read-only\" | \"read-write\";\n }>;\n}\n\n/**\n * A connector that failed to connect, as returned by\n * `ConnectorManager.listFailedConnectors()`.\n *\n * A failed connector never enters the manager's active map, so it is absent\n * from `listConnectors()` and `get()` by design — those describe what the agent\n * can actually use. This record is the second list that keeps the failure\n * itself visible.\n *\n * @docLink packages/connectors/concepts#connector-manager\n */\nexport interface FailedConnectorInfo {\n id: string;\n driver: string;\n access: \"read-only\" | \"read-write\";\n label?: string;\n /** `mount.source` when declared. */\n source?: string;\n /** Resolved absolute mount target, when the declaration has a mount. */\n mountPath?: string;\n /** True when the failure is fail-fast material: read-write AND mount-bearing. */\n required: boolean;\n /** The connect error message. */\n error: string;\n /** Present when the host declared the connector unavailable; no connect was attempted. */\n unavailable?: UnavailableMarker;\n}\n\n/**\n * Thrown by `connectAll` when a read-write mountable connector fails and\n * `failOnReadWriteError` was set.\n * @docLink packages/connectors/concepts#connector-startup-error\n */\nexport class ConnectorStartupError extends Error {\n readonly report: ConnectorStartupReport;\n readonly failedReadWrite: ReadonlyArray<{ id: string; error: string }>;\n constructor(\n message: string,\n report: ConnectorStartupReport,\n failedReadWrite: ReadonlyArray<{ id: string; error: string }>,\n ) {\n super(message);\n this.name = \"ConnectorStartupError\";\n this.report = report;\n this.failedReadWrite = failedReadWrite;\n }\n}\n","/**\n * Derive runtime connector declarations from the platform-materialized\n * `.skaile/assets/connector/<name>/CONNECTOR.md` projection.\n *\n * Connector mirror of MCP's `loadMaterializedMcpDeclarations` /\n * `deriveSingleMaterializedMcpDeclaration`. The generated `CONNECTOR.md` carries\n * a RUNTIME declaration (driver/access/auth/mode/options/mount) — distinct from\n * the catalog `CONNECTOR.md` parsed by `core/manifest.ts:fromConnectorMd`\n * (entry/fields). Driver is referenced by name (first-party; resolved via the\n * connector registry — no code-loading).\n */\nimport { existsSync, readFileSync, readdirSync, statSync } from \"node:fs\";\nimport { join } from \"node:path\";\n// Narrow module, not the `core` barrel: the barrel's chunks carry `import.meta`,\n// which breaks consumers that transpile this entry to CommonJS.\nimport { parseFrontmatter } from \"../../core/src/manifest.js\";\nimport type { ConnectorDeclaration } from \"./connector-types.js\";\n\n/** Parse a generated CONNECTOR.md (runtime projection) into a ConnectorDeclaration. */\nexport function fromMaterializedConnectorMd(filePath: string, name: string): ConnectorDeclaration {\n const { data: meta, body } = parseFrontmatter(readFileSync(filePath, \"utf8\"));\n const id = String(meta.name ?? name);\n const decl: ConnectorDeclaration = {\n id,\n driver: String(meta.driver ?? \"\"),\n access: meta.access === \"read-write\" ? \"read-write\" : \"read-only\",\n };\n if (meta.access !== \"read-write\" && meta.access !== \"read-only\") decl.accessDefaulted = true;\n if (typeof meta.label === \"string\" && meta.label) decl.label = meta.label;\n if (typeof meta.auth === \"string\") decl.auth = meta.auth;\n if (typeof meta.providerLinkId === \"string\" && meta.providerLinkId) {\n decl.providerLinkId = meta.providerLinkId;\n }\n if (meta.mode === \"agent\" || meta.mode === \"sync\") decl.mode = meta.mode;\n if (meta.options && typeof meta.options === \"object\" && !Array.isArray(meta.options)) {\n decl.options = meta.options as Record<string, unknown>;\n }\n if (meta.mount && typeof meta.mount === \"object\" && !Array.isArray(meta.mount)) {\n const m = meta.mount as Record<string, unknown>;\n decl.mount = {\n source: String(m.source ?? \"\"),\n ...(m.target !== undefined ? { target: String(m.target) } : {}),\n ...(typeof m.watch === \"boolean\" ? { watch: m.watch } : {}),\n ...(typeof m.exposeAccessToken === \"boolean\"\n ? { exposeAccessToken: m.exposeAccessToken }\n : {}),\n ...(typeof m.accessTokenTTL === \"number\" ? { accessTokenTTL: m.accessTokenTTL } : {}),\n };\n }\n const trimmedBody = body.trim();\n if (trimmedBody.length > 0) decl.instructions = trimmedBody;\n return decl;\n}\n\n/** Provide `.instance.json` config entries as defaults under the declaration's options (the CONNECTOR.md declaration wins on key collision). */\nfunction foldInstanceConfig(decl: ConnectorDeclaration, instancePath: string): void {\n if (!existsSync(instancePath)) return;\n let parsed: { config?: Record<string, unknown> };\n try {\n parsed = JSON.parse(readFileSync(instancePath, \"utf8\"));\n } catch {\n return;\n }\n const config = parsed.config;\n if (!config || typeof config !== \"object\" || Array.isArray(config)) return;\n decl.options = { ...(config as Record<string, unknown>), ...(decl.options ?? {}) };\n}\n\n/** Derive a single materialized connector declaration; null when no CONNECTOR.md. */\nexport function deriveSingleMaterializedConnectorDeclaration(\n connectorAssetsDir: string,\n name: string,\n): ConnectorDeclaration | null {\n const sub = join(connectorAssetsDir, name);\n const md = join(sub, \"CONNECTOR.md\");\n if (!existsSync(md)) return null;\n const decl = fromMaterializedConnectorMd(md, name);\n foldInstanceConfig(decl, join(sub, \".instance.json\"));\n return decl;\n}\n\n/** Scan `<projectDir>/.skaile/assets/connector/*` for materialized connectors. */\nexport function loadMaterializedConnectorDeclarations(projectDir: string): ConnectorDeclaration[] {\n const root = join(projectDir, \".skaile/assets/connector\");\n if (!existsSync(root)) return [];\n const out: ConnectorDeclaration[] = [];\n for (const name of readdirSync(root)) {\n try {\n const sub = join(root, name);\n if (!statSync(sub).isDirectory()) continue;\n const decl = deriveSingleMaterializedConnectorDeclaration(root, name);\n if (decl) out.push(decl);\n } catch {\n // Per-directory failure is isolated — one bad asset never aborts the scan.\n }\n }\n return out;\n}\n","/**\n * Secret provider abstraction.\n *\n * Decouples credential resolution from process.env so secrets can be\n * provisioned over the transport bridge instead of living in the\n * container's environment.\n */\n\n// Narrow module, not the `core/logging` barrel: it re-exports the SQLite sink,\n// whose `import.meta` breaks consumers that transpile this entry to CommonJS.\nimport { createLogger } from \"../../core/src/logging/create-logger.js\";\n\nconst log = createLogger({ kind: \"connector\", subkind: \"secrets\" });\n\n// ── Interfaces ──────────────────────────────────────────────────────────────\n\n/**\n * Read-only secret resolution. Adapters receive this interface.\n * @docLink packages/connectors/api-reference#secret-provider\n */\nexport interface SecretProvider {\n /**\n * Resolve a credential reference.\n *\n * @param ref - Credential reference such as \"env:GIT_TOKEN\",\n * \"oauth:google:user@example.com\", or an inline literal.\n * @returns The resolved secret value or undefined if not found.\n */\n resolve(ref: string): string | undefined;\n /**\n * Check whether a reference can be resolved.\n *\n * @param ref - Reference to check.\n * @returns True if resolve(ref) would return a non-undefined value.\n */\n has(ref: string): boolean;\n /**\n * Return all ref strings this provider can currently resolve.\n *\n * @returns All resolvable refs (used by forge UI and ConnectorFieldMissingError).\n */\n capabilities(): string[];\n}\n\n/**\n * Extends `SecretProvider` with the ability to load secrets at runtime via `provision()`.\n * @docLink packages/connectors/api-reference#provisionable-secret-provider\n */\nexport interface ProvisionableSecretProvider extends SecretProvider {\n /** Store a batch of key-value secrets. Keys are bare names (no prefix). */\n provision(secrets: Record<string, string>): void;\n}\n\n// ── Implementations ─────────────────────────────────────────────────────────\n\n/**\n * In-memory secret store. Secrets are provisioned over the transport bridge\n * and stored in a private Map — never touching the filesystem or process.env.\n *\n * Supports ref prefixes:\n * `\"env:KEY\"` — looks up KEY in the store\n * `\"vault:KEY\"` — looks up KEY in the store (future vault compat)\n * (no prefix) — returned as an inline value (backwards compat for non-chain usages)\n * @docLink packages/connectors/api-reference#in-memory-secret-provider\n */\nexport class InMemorySecretProvider implements ProvisionableSecretProvider {\n private readonly store = new Map<string, string>();\n\n /**\n * Store a batch of key-value secrets.\n *\n * @param secrets - Key-value map of secret names to values. Keys are bare names (no prefix).\n */\n provision(secrets: Record<string, string>): void {\n for (const [key, value] of Object.entries(secrets)) {\n this.store.set(key, value);\n }\n }\n\n resolve(ref: string): string | undefined {\n if (!ref) return undefined;\n if (ref.startsWith(\"env:\")) return this.store.get(ref.slice(4));\n if (ref.startsWith(\"vault:\")) return this.store.get(ref.slice(6));\n // Bare key: check store first, then fall back to inline literal\n const stored = this.store.get(ref);\n if (stored !== undefined) return stored;\n return ref;\n }\n\n has(ref: string): boolean {\n return this.resolve(ref) !== undefined;\n }\n\n capabilities(): string[] {\n return [...this.store.keys()].map((k) => `env:${k}`);\n }\n}\n\n/**\n * Delegates to `process.env`. Used in CLI/standalone mode.\n * Does NOT pass through inline literals — returns `undefined` for any ref\n * that does not start with `\"env:\"`. Use `InMemorySecretProvider` for inline\n * literals in non-chain contexts.\n * @docLink packages/connectors/api-reference#env-secret-provider\n */\nexport class EnvSecretProvider implements SecretProvider {\n resolve(ref: string): string | undefined {\n if (!ref) return undefined;\n if (ref.startsWith(\"env:\")) return process.env[ref.slice(4)];\n return undefined; // no inline passthrough\n }\n\n has(ref: string): boolean {\n return this.resolve(ref) !== undefined;\n }\n\n capabilities(): string[] {\n return Object.keys(process.env).map((k) => `env:${k}`);\n }\n}\n\n/**\n * Pre-minted credential entry. Mirrors the discriminated `CredentialMint`\n * shape from `@skaile/workspaces/types` but redeclared here to keep this package\n * free of cross-package type dependencies.\n *\n * The failure branch carries the platform-side `code` + `message` so the\n * `ConnectorManager`'s wrapped mediator can surface the real reason instead of\n * a generic \"no pre-mint\" placeholder when a mint comes back as `ok: false`.\n */\nexport type PreMintedCredential =\n | { ok: true; token: string; expiresAt: string | null; mintedAt?: string }\n | {\n ok: false;\n code?: \"not-configured\" | \"revoked\" | \"provider-error\" | \"backend-error\";\n message?: string;\n };\n\n/**\n * Pre-minted credential store. Holds short-lived tokens delivered upfront in\n * the v3 `session_init` envelope so the runner never has to call back to the\n * platform during mount setup.\n *\n * Resolves refs of the form `mount:<id>`, `connector:<id>`, and `mcp:<id>`.\n * Returns `undefined` for any other ref so the chain falls through to the\n * next provider (`EnvSecretProvider` for `pat:env:NAME`, etc.).\n *\n * Tokens can be added/removed at runtime via {@link set} / {@link unset} so\n * `runner.add_mount` / `runner.add_connector` / `runner.add_mcp` capabilities\n * stay strictly in-process — no round trip to the platform to mint while\n * the resource is hot-attached.\n *\n * For callers that need the full mint metadata (expiry timestamp, mintedAt\n * audit fields), use {@link mintFor} instead of the bare `resolve`. The\n * `ConnectorManager` consults this for the `auth: backend` initial-mint path so\n * the driver retains the original expiry semantics.\n *\n * Spec: `_devlog/specs/2026-05-10-deterministic-session-bootstrap.md`.\n *\n * @docLink packages/connectors/api-reference#pre-minted-secret-provider\n */\nexport class PreMintedSecretProvider implements SecretProvider {\n private readonly mints = new Map<string, PreMintedCredential>();\n\n /**\n * Seed pre-minted credentials from the v3 `session_init.credentials` map.\n *\n * Failed mints (`ok: false`) are stored too so callers can distinguish\n * \"not pre-minted\" from \"pre-minted but failed\"; {@link resolve} treats\n * both as `undefined`.\n *\n * @param credentials Optional initial `{ mounts, connectors, mcp }` map.\n */\n constructor(credentials?: {\n mounts?: Record<string, PreMintedCredential>;\n connectors?: Record<string, PreMintedCredential>;\n mcp?: Record<string, PreMintedCredential>;\n }) {\n if (!credentials) return;\n for (const [id, mint] of Object.entries(credentials.mounts ?? {})) {\n this.mints.set(`mount:${id}`, mint);\n }\n for (const [id, mint] of Object.entries(credentials.connectors ?? {})) {\n this.mints.set(`connector:${id}`, mint);\n }\n for (const [id, mint] of Object.entries(credentials.mcp ?? {})) {\n this.mints.set(`mcp:${id}`, mint);\n }\n }\n\n /**\n * Insert (or replace) a pre-minted credential. Used by\n * `runner.add_mount` / `runner.add_connector` / `runner.add_mcp` capability\n * handlers when the platform delivers new credentials mid-session.\n */\n set(kind: \"mount\" | \"connector\" | \"mcp\", id: string, mint: PreMintedCredential): void {\n this.mints.set(`${kind}:${id}`, mint);\n }\n\n /**\n * Remove a stored pre-minted credential. Used by the\n * `runner.remove_resource` capability handler.\n */\n unset(kind: \"mount\" | \"connector\" | \"mcp\", id: string): boolean {\n return this.mints.delete(`${kind}:${id}`);\n }\n\n /**\n * Look up the full {@link PreMintedCredential} for a `mount:` /\n * `connector:` / `mcp:` keyed entry. Callers that only need the token use\n * {@link resolve} via the chain; callers that need expiry / audit\n * metadata (e.g. ConnectorManager) use this entry point.\n */\n mintFor(kind: \"mount\" | \"connector\" | \"mcp\", id: string): PreMintedCredential | undefined {\n return this.mints.get(`${kind}:${id}`);\n }\n\n resolve(ref: string): string | undefined {\n if (!ref) return undefined;\n if (!(ref.startsWith(\"mount:\") || ref.startsWith(\"connector:\") || ref.startsWith(\"mcp:\")))\n return undefined;\n const mint = this.mints.get(ref);\n return mint?.ok ? mint.token : undefined;\n }\n\n has(ref: string): boolean {\n return this.resolve(ref) !== undefined;\n }\n\n capabilities(): string[] {\n return [...this.mints.entries()].filter(([, m]) => m.ok).map(([k]) => k);\n }\n}\n\n/**\n * Forge session secret provider. Secrets are provisioned from the Forge settings\n * panel over the transport bridge. Only handles `\"forge:\"` prefixed refs — returns\n * `undefined` for all others.\n * @docLink packages/connectors/api-reference#forge-secret-provider\n */\nexport class ForgeSecretProvider implements ProvisionableSecretProvider {\n private readonly store = new Map<string, string>();\n\n provision(secrets: Record<string, string>): void {\n for (const [key, value] of Object.entries(secrets)) {\n this.store.set(key, value);\n }\n }\n\n resolve(ref: string): string | undefined {\n if (!ref) return undefined;\n if (ref.startsWith(\"forge:\")) return this.store.get(ref.slice(6));\n return undefined;\n }\n\n has(ref: string): boolean {\n return this.resolve(ref) !== undefined;\n }\n\n capabilities(): string[] {\n return [...this.store.keys()].map((k) => `forge:${k}`);\n }\n}\n\n/**\n * Thrown when an OAuth-secured connector field requires user authorization before\n * it can be resolved. Contains the redirect URL to open in the user's browser.\n * @docLink packages/connectors/api-reference#o-auth-required-error\n */\nexport class OAuthRequiredError extends Error {\n readonly oauthRef: string;\n readonly authUrl: string;\n readonly state: string;\n\n /**\n * @param oauthRef - The 'oauth:<service>:<account>' ref that triggered the error\n * @param authUrl - Browser URL to open for OAuth authorization\n * @param state - OAuth state token for CSRF protection and callback correlation\n */\n constructor(oauthRef: string, authUrl: string, state: string) {\n super(`OAuth authorization required for ${oauthRef}`);\n this.name = \"OAuthRequiredError\";\n this.oauthRef = oauthRef;\n this.authUrl = authUrl;\n this.state = state;\n }\n}\n\n/**\n * Shape of an OAuth token bundle stored by `OAuthSecretProvider`.\n * @docLink packages/connectors/api-reference#o-auth-token-bundle\n */\nexport interface OAuthTokenBundle {\n accessToken: string;\n refreshToken?: string;\n /** Unix timestamp in ms */\n expiry?: number;\n}\n\n/**\n * Return value of `OAuthSecretProvider.initiateFlow()`. Contains the URL and CSRF state token.\n * @docLink packages/connectors/api-reference#o-auth-flow-request\n */\nexport interface OAuthFlowRequest {\n authUrl: string;\n state: string;\n}\n\n/**\n * OAuth token provider. Handles `\"oauth:<service>:<account>\"` refs.\n * Callers must call `chain.prepareRef()` before `chain.resolve()` for `oauth:` refs.\n * @docLink packages/connectors/api-reference#o-auth-secret-provider\n */\nexport interface OAuthSecretProvider extends SecretProvider {\n /**\n * Ensure the token for this ref is fresh.\n * Refreshes if expired.\n * Throws OAuthRequiredError if no token exists and user authorization is needed.\n */\n ensureFresh(ref: string): Promise<void>;\n\n /** Initiate the OAuth authorization flow. Returns URL to open in the user's browser. */\n initiateFlow(oauthService: string, account: string): Promise<OAuthFlowRequest>;\n\n /** Exchange authorization code for tokens and store the bundle. */\n completeFlow(state: string, code: string): Promise<void>;\n}\n\n/**\n * Abstract base for vault-backed secret providers (1Password, KeePass). Subclasses\n * implement `prefix` and `loadKeys()`. Locked until `unlock(credential)` is called.\n * @docLink packages/connectors/api-reference#locked-secret-provider\n */\nexport abstract class LockedSecretProvider implements SecretProvider {\n locked = true;\n protected readonly store = new Map<string, string>();\n abstract readonly prefix: string;\n\n async unlock(credential: string): Promise<void> {\n await this.loadKeys(credential);\n this.locked = false;\n }\n\n protected abstract loadKeys(credential: string): Promise<void>;\n\n resolve(ref: string): string | undefined {\n if (this.locked) return undefined;\n if (!ref.startsWith(this.prefix)) return undefined;\n return this.store.get(ref.slice(this.prefix.length));\n }\n\n has(ref: string): boolean {\n return this.resolve(ref) !== undefined;\n }\n\n capabilities(): string[] {\n if (this.locked) return [];\n return [...this.store.keys()].map((k) => `${this.prefix}${k}`);\n }\n}\n\n// ── Known provider prefixes ──────────────────────────────────────────────────\n\nconst KNOWN_PREFIXES = [\n \"env:\",\n \"vault:\",\n \"forge:\",\n \"op:\",\n \"kp:\",\n \"oauth:\",\n \"mount:\",\n \"connector:\",\n \"mcp:\",\n] as const;\n\nfunction getPrefix(ref: string): string | undefined {\n return KNOWN_PREFIXES.find((p) => ref.startsWith(p));\n}\n\n/**\n * True when `value` starts with a known secret-ref prefix (`env:`, `oauth:`,\n * `mcp:`, ...). Lets callers distinguish an intended-but-unresolved ref from a\n * plain literal — e.g. the runner refuses to forward an unresolved ref into\n * MCP transport headers/env, where the literal would otherwise leak onto the\n * wire and produce a misleading upstream error.\n */\nexport function isKnownSecretRef(value: string): boolean {\n return getPrefix(value) !== undefined;\n}\n\n/**\n * Chains multiple `SecretProvider` instances into a single resolver.\n * - Prefixed refs (`env:`, `forge:`, `op:`, `kp:`, `oauth:`) are routed to the first provider that can resolve them.\n * - Bare refs waterfall through all providers in order.\n * - Plain literals in `skaile.yaml` options are NOT passed to the chain; `ConnectorManager` handles them before calling `resolve()`.\n * @docLink packages/connectors/api-reference#secret-provider-chain\n */\nexport class SecretProviderChain implements SecretProvider {\n /**\n * @param providers - Ordered list of providers. For prefixed refs, the first\n * provider that can resolve wins. For bare refs, waterfall through all in order.\n */\n constructor(private readonly providers: SecretProvider[]) {}\n\n resolve(ref: string): string | undefined {\n if (!ref) return undefined;\n const prefix = getPrefix(ref);\n log.debug(\"resolve secret\", { ref, prefix: prefix ?? \"(bare)\" });\n if (prefix) {\n for (const p of this.providers) {\n const val = p.resolve(ref);\n if (val !== undefined) return val;\n }\n log.warn(\"secret not resolvable\", { ref });\n return undefined;\n }\n // Waterfall for bare refs\n for (const p of this.providers) {\n const val = p.resolve(ref);\n if (val !== undefined) return val;\n }\n log.warn(\"secret not resolvable\", { ref });\n return undefined;\n }\n\n has(ref: string): boolean {\n return this.resolve(ref) !== undefined;\n }\n\n capabilities(): string[] {\n const all = this.providers.flatMap((p) => p.capabilities());\n return [...new Set(all)];\n }\n\n /** Returns the first provider that can resolve this ref. */\n providerFor(ref: string): SecretProvider | undefined {\n for (const p of this.providers) {\n if (p.resolve(ref) !== undefined) return p;\n }\n return undefined;\n }\n\n /**\n * Calls ensureFresh(ref) on the owning provider if it implements OAuthSecretProvider.\n * No-op for providers that don't have ensureFresh().\n *\n * @param ref - Must be an \"oauth:\" prefixed ref for this to have any effect.\n * Calls ensureFresh() on the owning OAuthSecretProvider.\n */\n async prepareRef(ref: string): Promise<void> {\n const owner = this.providerFor(ref);\n if (\n owner &&\n \"ensureFresh\" in owner &&\n typeof (owner as OAuthSecretProvider).ensureFresh === \"function\"\n ) {\n try {\n await (owner as OAuthSecretProvider).ensureFresh(ref);\n } catch (err) {\n log.error(\"secret provider ensureFresh failed\", err, { ref });\n throw err;\n }\n }\n }\n}\n","/**\n * Load connector declarations from skaile.yaml.\n *\n * The top-level `mounts:` key is no longer accepted (hard cut as of Task 11).\n * Filesystem-projected backends must be declared under `connectors:` with a\n * `mount:` sub-block. See `docs/migration-mounts-to-connectors.md`.\n */\n\nimport type { ResolvedSkaileConfig } from \"@skaile/workspaces/types\";\n// Narrow modules, not the `core` barrels: their chunks carry `import.meta`,\n// which breaks consumers that transpile this entry to CommonJS.\nimport { createLogger } from \"../../core/src/logging/create-logger.js\";\nimport {\n localConnectorMountDir,\n resolveSkWorkspaceConfig,\n type ConnectorDeclaration as WorkspaceConnector,\n} from \"../../core/src/workspace-config.js\";\nimport type { ConnectorDeclaration } from \"./connector-types.js\";\nimport { readUnavailableMarker } from \"./connector-types.js\";\nimport { loadMaterializedConnectorDeclarations } from \"./materialized-connectors.js\";\n\nconst configLog = createLogger({ kind: \"connector\", subkind: \"config\" });\n\n/**\n * Read `skaile.yaml` in `projectDir` and return all declared connectors as `ConnectorDeclaration[]`.\n *\n * Throws a migration error when the legacy top-level `mounts:` key is present.\n *\n * @param projectDir - Root of the workspace (directory containing `skaile.yaml`).\n * @returns Merged array of connector declarations from `skaile.yaml` and the materialized\n * `.skaile/assets/connector/*` disk projection (Phase 2.5); empty array if neither source\n * contributes any entries. `skaile.yaml` wins on id collision.\n * @docLink packages/connectors/api-reference#load-connector-declarations\n */\nexport function loadConnectorDeclarations(projectDir: string): ConnectorDeclaration[] {\n return withMaterializedConnectorDeclarations(\n loadYamlConnectorDeclarations(projectDir),\n projectDir,\n );\n}\n\n/**\n * The `skaile.yaml` half of {@link loadConnectorDeclarations}: only the `connectors:` entries,\n * without the materialized projection. The runner needs it on its own because in broker mode the\n * session root keeps materialized connectors across wakes while its yaml declares nothing, and the\n * `session_init` wire set must then stand in for the yaml half, not for both.\n *\n * Throws a migration error when the legacy top-level `mounts:` key is present.\n */\nexport function loadYamlConnectorDeclarations(projectDir: string): ConnectorDeclaration[] {\n const config = resolveSkWorkspaceConfig(projectDir);\n\n // Hard cut: reject legacy top-level `mounts:` key with an actionable message.\n if (config.mounts && config.mounts.length > 0) {\n throw new Error(\n \"'mounts:' is no longer supported — move entries under 'connectors:' with a 'mount:' sub-block. See docs/migration-mounts-to-connectors.md\",\n );\n }\n\n return config.connectors && config.connectors.length > 0\n ? config.connectors.map((c) => workspaceConnectorToDeclaration(c, projectDir))\n : [];\n}\n\n/**\n * Add the materialized `.skaile/assets/connector/*` projection to `base`. Library-assigned\n * connectors reach the runner only through that projection. `base` is explicit config (the\n * skaile.yaml entries, or the `session_init` wire set standing in for them) and wins on id\n * collision; the shadowed materialized connector is logged, not silently dropped.\n */\nexport function withMaterializedConnectorDeclarations(\n base: ConnectorDeclaration[],\n projectDir: string,\n): ConnectorDeclaration[] {\n const byId = new Map<string, ConnectorDeclaration>();\n for (const d of base) byId.set(d.id, d);\n for (const d of loadMaterializedConnectorDeclarations(projectDir)) {\n if (byId.has(d.id)) {\n configLog.warn(`materialized connector '${d.id}' shadowed by an explicit connector`);\n continue;\n }\n byId.set(d.id, d);\n }\n return [...byId.values()];\n}\n\n/**\n * A declared `access` as the manager enforces it: only `read-write` writes. A missing value and an\n * unknown one (`rw`, a typo) read-only, so a wrong spelling never opens a mount for writing.\n */\nfunction accessOf(access: string | undefined): \"read-only\" | \"read-write\" {\n return access === \"read-write\" ? \"read-write\" : \"read-only\";\n}\n\nfunction workspaceConnectorToDeclaration(\n c: WorkspaceConnector,\n projectDir: string,\n): ConnectorDeclaration {\n const decl: ConnectorDeclaration = {\n id: c.id,\n driver: c.driver,\n access: accessOf(c.access),\n auth: c.auth,\n options: c.options,\n };\n if (c.access == null) decl.accessDefaulted = true;\n\n // Backend-auth routing key for live token refresh; dropping it breaks git mount mint.\n if (c.providerLinkId) decl.providerLinkId = c.providerLinkId;\n\n const unavailable = readUnavailableMarker(c.unavailable);\n if (unavailable) decl.unavailable = unavailable;\n\n // Map the optional mount sub-block when present.\n if (c.mount) {\n decl.mount = {\n source: c.mount.source,\n target: c.mount.target,\n watch: c.mount.watch,\n exposeAccessToken: c.mount.exposeAccessToken,\n accessTokenTTL: c.mount.accessTokenTTL,\n };\n } else if (c.driver === \"local\") {\n // `mountPath:` names the host directory. An absolute source with no target makes the manager\n // bind the connector straight to it, so reads and writes land in that directory.\n const source = localConnectorMountDir(c, projectDir);\n if (source) decl.mount = { source };\n }\n\n return decl;\n}\n\n/**\n * Map a Protocol v3 `session_init` `resolvedConfig` to `ConnectorDeclaration[]`.\n *\n * Wire mounts are flat (`source` / `target` / `watch` top-level per\n * `ResolvedSkaileConfig`); declarations carry them in the `mount:` sub-block.\n * Wire `connectors` (tool-face) map without a mount block. Malformed entries\n * (missing `id`, `driver`, or — for mounts — `source`) are logged and dropped,\n * never thrown: one bad wire entry must not kill session boot. Duplicate ids\n * (within or across the two arrays) keep the FIRST occurrence — mounts precede\n * connectors — and the shadowed entry is logged and dropped the same way.\n *\n * Pure function, no I/O. Used by the runner in place of the `skaile.yaml`\n * entries when `skaile.yaml` declares no connectors (broker mode, where the\n * delivered yaml carries no declarations). Materialized connectors are added\n * on top either way.\n *\n * @param resolved - `mounts` / `connectors` arrays from the platform-resolved config.\n * @returns Declarations in wire order — mounts first, then connectors.\n * @docLink packages/connectors/api-reference#resolved-config-to-declarations\n */\nexport function resolvedConfigToDeclarations(\n resolved: Pick<ResolvedSkaileConfig, \"mounts\" | \"connectors\">,\n): ConnectorDeclaration[] {\n // Keyed by id: the wire carries no well-formedness guarantee, and a duplicate\n // id downstream would collide on mount paths / tool namespaces. First wins.\n const byId = new Map<string, ConnectorDeclaration>();\n const pushUnlessDuplicate = (kind: \"mount\" | \"connector\", decl: ConnectorDeclaration): void => {\n if (byId.has(decl.id)) {\n configLog.warn(`dropping duplicate resolvedConfig ${kind} (id already declared)`, {\n id: decl.id,\n });\n return;\n }\n byId.set(decl.id, decl);\n };\n\n for (const m of resolved.mounts ?? []) {\n // A mount without a source cannot connect — drop it with the malformed ones.\n if (\n typeof m?.id !== \"string\" ||\n typeof m?.driver !== \"string\" ||\n typeof m.source !== \"string\"\n ) {\n configLog.warn(\"dropping malformed resolvedConfig mount (missing id/driver/source)\", {\n id: (m as { id?: unknown } | undefined)?.id,\n });\n continue;\n }\n const decl: ConnectorDeclaration = {\n id: m.id,\n driver: m.driver,\n access: accessOf(m.access),\n ...(m.access == null ? { accessDefaulted: true as const } : {}),\n auth: m.auth,\n options: m.options,\n mount: {\n source: m.source,\n target: m.target,\n watch: m.watch,\n exposeAccessToken: m.exposeAccessToken,\n accessTokenTTL: m.accessTokenTTL,\n },\n };\n // Backend-auth routing key for live token refresh; dropping it breaks git mount mint.\n if (m.providerLinkId) decl.providerLinkId = m.providerLinkId;\n pushUnlessDuplicate(\"mount\", decl);\n }\n\n for (const c of resolved.connectors ?? []) {\n if (typeof c?.id !== \"string\" || typeof c?.driver !== \"string\") {\n configLog.warn(\"dropping malformed resolvedConfig connector (missing id/driver)\", {\n id: (c as { id?: unknown } | undefined)?.id,\n });\n continue;\n }\n const decl: ConnectorDeclaration = {\n id: c.id,\n driver: c.driver,\n access: accessOf(c.access),\n ...(c.access == null ? { accessDefaulted: true as const } : {}),\n auth: c.auth,\n options: c.options,\n };\n if (c.providerLinkId) decl.providerLinkId = c.providerLinkId;\n pushUnlessDuplicate(\"connector\", decl);\n }\n\n return [...byId.values()];\n}\n\nimport type { ForgeSecretProvider, SecretProvider } from \"./secrets.js\";\nimport { EnvSecretProvider, InMemorySecretProvider, SecretProviderChain } from \"./secrets.js\";\n\n/**\n * Build a `SecretProviderChain` for Forge session context.\n * `OAuthSecretProvider` is not wired here — it must be provided externally\n * (the Forge session manager constructs it and passes it in).\n * @param forgeProvider - The Forge-provisioned secret store.\n * @param extraProviders - Additional providers prepended to the chain (e.g. an OAuth provider).\n * @returns A chain that routes `forge:` refs to the Forge store and `env:` refs to process.env.\n * @docLink packages/connectors/api-reference#create-forge-secret-provider-chain\n */\nexport function createForgeSecretProviderChain(\n forgeProvider: ForgeSecretProvider,\n extraProviders: SecretProvider[] = [],\n): SecretProviderChain {\n return new SecretProviderChain([...extraProviders, forgeProvider, new EnvSecretProvider()]);\n}\n\n/**\n * Build a `SecretProviderChain` for CLI/standalone context.\n * `EnvSecretProvider` takes priority; `extraSecrets` are loaded into an `InMemorySecretProvider`.\n * @param extraSecrets - Inline secrets injected into memory (e.g. tokens passed via CLI flags).\n * @returns A chain that resolves `env:` refs from process.env plus any inline extras.\n * @docLink packages/connectors/api-reference#create-cli-secret-provider-chain\n */\nexport function createCliSecretProviderChain(\n extraSecrets: Record<string, string> = {},\n): SecretProviderChain {\n const mem = new InMemorySecretProvider();\n if (Object.keys(extraSecrets).length > 0) {\n mem.provision(extraSecrets);\n }\n return new SecretProviderChain([new EnvSecretProvider(), mem]);\n}\n\n// ── Auth grammar (mount-side, Tier 2 credential tiers) ───────────────────────\n\n/**\n * Provider kind for a mount auth ref.\n *\n * Two values are accepted:\n * - `pat` — static personal access token resolved via the secrets chain\n * (standalone CLI / non-platform contexts).\n * - `backend` — token minted by the platform's credential mediator over the\n * transport (`request_access_token` round-trip). Provider\n * dispatch (OAuth, GitHub App, ...) lives backend-side; the\n * runner stays provider-agnostic.\n *\n * @docLink packages/connectors/api-reference#mount-auth-kind\n */\nexport type MountAuthKind = \"pat\" | \"backend\";\n\n/**\n * Parsed mount `auth:` field.\n *\n * - `pat` → `value` is the inner secret ref (e.g. `env:NAME`).\n * - `backend` → `value` is empty (sentinel only); the runner asks the\n * backend for tokens via `request_access_token`.\n *\n * @docLink packages/connectors/api-reference#mount-auth-ref\n */\nexport interface MountAuthRef {\n kind: MountAuthKind;\n /** Prefix-stripped payload — see kind for shape. Empty for `backend`. */\n value: string;\n /** Original auth string from the declaration, kept for diagnostics. */\n raw: string;\n}\n\n/**\n * Thrown when a mount declaration's `auth:` field uses the legacy bare `env:NAME` grammar\n * or any other unrecognized form. Migrate to `pat:env:NAME` (standalone) or `backend`\n * (platform-mediated).\n * @docLink packages/connectors/api-reference#legacy-auth-grammar-error\n */\nexport class LegacyAuthGrammarError extends Error {\n readonly auth: string;\n constructor(auth: string, mountId?: string) {\n const where = mountId ? ` on mount '${mountId}'` : \"\";\n super(\n `Legacy or unrecognized auth grammar${where} ('${auth}'). ` +\n `Replace with one of:\\n` +\n ` - backend (platform-mediated, recommended)\\n` +\n ` - pat:env:NAME (standalone CLI / static token)\\n` +\n `See _devlog/specs/2026-05-06-tier-2-credential-mediation.md.`,\n );\n this.name = \"LegacyAuthGrammarError\";\n this.auth = auth;\n }\n}\n\n/**\n * Resolve the `auth: backend` initial mint for a given mount or connector id\n * by querying the secrets chain with a `${kind}:${id}` ref. Returns the\n * resolved bearer token or `undefined` if no pre-minted credential is\n * available.\n *\n * Used by the runner when wiring `ConnectorManager` to\n * answer initial-mint requests from `PreMintedSecretProvider` without\n * round-tripping to the platform. Drivers continue to receive a\n * `tokenMediator` for refresh + retry-401 paths.\n *\n * @param kind Resource family (`mount` or `connector`).\n * @param id Resource declaration id.\n * @param chain Secrets chain. Pass `undefined` to return `undefined`.\n * @returns The pre-minted token, or `undefined` if not stored on the chain.\n * @docLink packages/connectors/api-reference#resolve-backend-auth-for\n */\nexport function resolveBackendAuthFor(\n kind: \"mount\" | \"connector\",\n id: string,\n chain: import(\"./secrets.js\").SecretProvider | undefined,\n): string | undefined {\n if (!chain) return undefined;\n return chain.resolve(`${kind}:${id}`);\n}\n\n/**\n * Parse a mount-side auth ref into a typed `MountAuthRef`.\n *\n * Accepted forms:\n * - `backend` — platform-mediated mint via `request_access_token`.\n * - `pat:env:NAME` — static PAT resolved from the secrets chain.\n *\n * Rejects bare `env:NAME` (legacy) and provider-prefixed grammars (`oauth:`,\n * `github-app:`) — those moved backend-side as part of Tier-2 mediation.\n * Returns `undefined` when `auth` is absent or empty.\n *\n * @param auth - Raw `auth:` value from the mount declaration.\n * @param mountId - Optional mount id included in error messages.\n * @returns Parsed `MountAuthRef` or `undefined`.\n * @throws {LegacyAuthGrammarError} for any unrecognized grammar.\n * @docLink packages/connectors/api-reference#resolve-auth-ref\n */\nexport function resolveAuthRef(\n auth: string | undefined,\n mountId?: string,\n): MountAuthRef | undefined {\n if (!auth) return undefined;\n\n if (auth === \"backend\") {\n return { kind: \"backend\", value: \"\", raw: auth };\n }\n if (auth.startsWith(\"pat:\")) {\n return { kind: \"pat\", value: auth.slice(\"pat:\".length), raw: auth };\n }\n\n // Legacy bare `env:NAME` and the deprecated provider-prefixed grammars\n // (`oauth:`, `github-app:`) all land here.\n throw new LegacyAuthGrammarError(auth, mountId);\n}\n"]}
|