@skaile/workspaces 5.15.1 → 5.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +80 -0
- package/dist/app-sdk/index.js +1 -1
- package/dist/{asset-feeds-FVDNQ2FM.js → asset-feeds-MALYFZUM.js} +18 -18
- package/dist/{asset-feeds-FVDNQ2FM.js.map → asset-feeds-MALYFZUM.js.map} +1 -1
- package/dist/asset-manager/catalog-deployer.js +7 -7
- package/dist/asset-manager/index.js +13 -13
- package/dist/asset-manager/installer.js +9 -9
- package/dist/asset-manager/renderers.js +8 -8
- package/dist/asset-manager/src/index.d.ts +105 -6
- package/dist/asset-manager/src/index.d.ts.map +1 -1
- package/dist/asset-manager/src/installer.d.ts +11 -2
- package/dist/asset-manager/src/installer.d.ts.map +1 -1
- package/dist/asset-manager/src/mcp-config.d.ts.map +1 -1
- package/dist/bridge/drivers/claude-sdk.js +425 -111
- package/dist/bridge/drivers/claude-sdk.js.map +1 -1
- package/dist/bridge/drivers/codex.js +15 -128
- package/dist/bridge/drivers/codex.js.map +1 -1
- package/dist/bridge/drivers/continue.js +10 -10
- package/dist/bridge/drivers/echo.js +4 -4
- package/dist/bridge/drivers/gemini.js +7 -7
- package/dist/bridge/drivers/goose.js +10 -10
- package/dist/bridge/drivers/omp.js +64 -8
- package/dist/bridge/drivers/omp.js.map +1 -1
- package/dist/bridge/drivers/opencode.js +10 -10
- package/dist/bridge/drivers/qwen.js +7 -7
- package/dist/bridge/index.js +15 -14
- package/dist/bridge/src/approval-card.d.ts +24 -0
- package/dist/bridge/src/approval-card.d.ts.map +1 -0
- package/dist/bridge/src/driver-model-check.d.ts +21 -0
- package/dist/bridge/src/driver-model-check.d.ts.map +1 -0
- package/dist/bridge/src/drivers/claude-sdk.d.ts +95 -19
- package/dist/bridge/src/drivers/claude-sdk.d.ts.map +1 -1
- package/dist/bridge/src/drivers/claude-self-turns.d.ts +25 -6
- package/dist/bridge/src/drivers/claude-self-turns.d.ts.map +1 -1
- package/dist/bridge/src/drivers/omp-models-yml.d.ts.map +1 -1
- package/dist/bridge/src/drivers/omp.d.ts.map +1 -1
- package/dist/bridge/src/drivers/sanitize-assistant-text.d.ts +10 -0
- package/dist/bridge/src/drivers/sanitize-assistant-text.d.ts.map +1 -1
- package/dist/bridge/src/drivers/scrub-transcript.d.ts +20 -0
- package/dist/bridge/src/drivers/scrub-transcript.d.ts.map +1 -1
- package/dist/bridge/src/index.d.ts +2 -0
- package/dist/bridge/src/index.d.ts.map +1 -1
- package/dist/bridge/src/types.d.ts +23 -0
- package/dist/bridge/src/types.d.ts.map +1 -1
- package/dist/{chunk-YUURCZWY.js → chunk-2SKPPIV7.js} +5 -5
- package/dist/{chunk-YUURCZWY.js.map → chunk-2SKPPIV7.js.map} +1 -1
- package/dist/{chunk-TCWECSEB.js → chunk-3OYOBTY4.js} +70 -6
- package/dist/chunk-3OYOBTY4.js.map +1 -0
- package/dist/{chunk-PK5XQBOC.js → chunk-46IRZJV4.js} +4 -4
- package/dist/{chunk-PK5XQBOC.js.map → chunk-46IRZJV4.js.map} +1 -1
- package/dist/{chunk-54TVXZP3.js → chunk-5DCOG5B5.js} +3 -3
- package/dist/{chunk-54TVXZP3.js.map → chunk-5DCOG5B5.js.map} +1 -1
- package/dist/{chunk-X7DIT65W.js → chunk-5RDZ5JHH.js} +4 -4
- package/dist/{chunk-X7DIT65W.js.map → chunk-5RDZ5JHH.js.map} +1 -1
- package/dist/chunk-5SWED2LW.js +125 -0
- package/dist/chunk-5SWED2LW.js.map +1 -0
- package/dist/{chunk-BV7NLPI6.js → chunk-6GSE63K2.js} +4 -4
- package/dist/{chunk-BV7NLPI6.js.map → chunk-6GSE63K2.js.map} +1 -1
- package/dist/{chunk-PW3TYWOI.js → chunk-AJ7EGIFR.js} +3 -3
- package/dist/{chunk-PW3TYWOI.js.map → chunk-AJ7EGIFR.js.map} +1 -1
- package/dist/{chunk-LEOXPIC6.js → chunk-AP24HESN.js} +3 -3
- package/dist/{chunk-LEOXPIC6.js.map → chunk-AP24HESN.js.map} +1 -1
- package/dist/{chunk-7Y7UYNGL.js → chunk-BBRMS4IC.js} +12 -9
- package/dist/chunk-BBRMS4IC.js.map +1 -0
- package/dist/{chunk-55VKZUQY.js → chunk-BVXXBZWA.js} +70 -34
- package/dist/chunk-BVXXBZWA.js.map +1 -0
- package/dist/{chunk-JUHDED6J.js → chunk-CWAWYXD5.js} +3 -3
- package/dist/{chunk-JUHDED6J.js.map → chunk-CWAWYXD5.js.map} +1 -1
- package/dist/{chunk-OOQ5Q75W.js → chunk-D3PU3C6F.js} +41 -16
- package/dist/chunk-D3PU3C6F.js.map +1 -0
- package/dist/{chunk-WXKNM2JJ.js → chunk-D5REDKVU.js} +3 -3
- package/dist/{chunk-WXKNM2JJ.js.map → chunk-D5REDKVU.js.map} +1 -1
- package/dist/{chunk-B6I7SF2X.js → chunk-DR5ZOEYI.js} +114 -81
- package/dist/chunk-DR5ZOEYI.js.map +1 -0
- package/dist/{chunk-YIDZJHY6.js → chunk-EFLKSMCO.js} +3 -3
- package/dist/{chunk-YIDZJHY6.js.map → chunk-EFLKSMCO.js.map} +1 -1
- package/dist/{chunk-JJLH4TX4.js → chunk-EOKWTN4N.js} +421 -112
- package/dist/chunk-EOKWTN4N.js.map +1 -0
- package/dist/{chunk-NKDSU4Q7.js → chunk-ES6ARJPQ.js} +21 -7
- package/dist/chunk-ES6ARJPQ.js.map +1 -0
- package/dist/{chunk-VQQCA7BD.js → chunk-EYDRONKO.js} +4 -4
- package/dist/{chunk-VQQCA7BD.js.map → chunk-EYDRONKO.js.map} +1 -1
- package/dist/{chunk-U7YMGW7M.js → chunk-FACRITOL.js} +2 -2
- package/dist/{chunk-U7YMGW7M.js.map → chunk-FACRITOL.js.map} +1 -1
- package/dist/{chunk-WWUWMOX2.js → chunk-FSLVMZXR.js} +37 -17
- package/dist/chunk-FSLVMZXR.js.map +1 -0
- package/dist/{chunk-MKTJZLQM.js → chunk-FSSRBWYL.js} +4 -4
- package/dist/{chunk-MKTJZLQM.js.map → chunk-FSSRBWYL.js.map} +1 -1
- package/dist/{chunk-VY6NTFE7.js → chunk-FT4ZHLYR.js} +3 -2
- package/dist/chunk-FT4ZHLYR.js.map +1 -0
- package/dist/{chunk-O673TBWJ.js → chunk-GYZJKZPJ.js} +3 -3
- package/dist/{chunk-O673TBWJ.js.map → chunk-GYZJKZPJ.js.map} +1 -1
- package/dist/{chunk-ANSZULXH.js → chunk-H7R7R5BN.js} +21 -6
- package/dist/chunk-H7R7R5BN.js.map +1 -0
- package/dist/{chunk-RNFHJUK7.js → chunk-HLETG3CX.js} +3 -3
- package/dist/{chunk-RNFHJUK7.js.map → chunk-HLETG3CX.js.map} +1 -1
- package/dist/{plugin-store-BIITCNOZ.js → chunk-HUKUYWBJ.js} +32 -23
- package/dist/chunk-HUKUYWBJ.js.map +1 -0
- package/dist/chunk-KZWZRNIY.js +1016 -0
- package/dist/chunk-KZWZRNIY.js.map +1 -0
- package/dist/{chunk-X5O56UO4.js → chunk-L2AMXONH.js} +3 -3
- package/dist/chunk-L2AMXONH.js.map +1 -0
- package/dist/{chunk-NOF73BUH.js → chunk-L6UMSKDF.js} +10 -2
- package/dist/chunk-L6UMSKDF.js.map +1 -0
- package/dist/{chunk-GQ5OYFVD.js → chunk-LQT2IKYY.js} +47 -47
- package/dist/chunk-LQT2IKYY.js.map +1 -0
- package/dist/{chunk-NHH3MRSC.js → chunk-MMARPEV7.js} +7 -7
- package/dist/{chunk-NHH3MRSC.js.map → chunk-MMARPEV7.js.map} +1 -1
- package/dist/{chunk-GR7TV4XC.js → chunk-OQN7PCI4.js} +4 -4
- package/dist/{chunk-GR7TV4XC.js.map → chunk-OQN7PCI4.js.map} +1 -1
- package/dist/{chunk-NVBN3YOH.js → chunk-OXUCYHL5.js} +46 -67
- package/dist/chunk-OXUCYHL5.js.map +1 -0
- package/dist/{chunk-SZPE55SB.js → chunk-PGZDSDOB.js} +3 -3
- package/dist/{chunk-SZPE55SB.js.map → chunk-PGZDSDOB.js.map} +1 -1
- package/dist/{chunk-4QINFQ27.js → chunk-PIC23DDE.js} +59 -17
- package/dist/chunk-PIC23DDE.js.map +1 -0
- package/dist/{chunk-SAKVAG23.js → chunk-QBY74UBH.js} +7 -7
- package/dist/{chunk-SAKVAG23.js.map → chunk-QBY74UBH.js.map} +1 -1
- package/dist/{chunk-GV3MFKDV.js → chunk-QEX75L77.js} +62 -6
- package/dist/chunk-QEX75L77.js.map +1 -0
- package/dist/{chunk-4AKR4XPQ.js → chunk-QSLXB44M.js} +3 -3
- package/dist/chunk-QSLXB44M.js.map +1 -0
- package/dist/{chunk-PQF5QHVS.js → chunk-QW534EZB.js} +20 -6
- package/dist/chunk-QW534EZB.js.map +1 -0
- package/dist/{chunk-DPCEQOIZ.js → chunk-QXA2W6UB.js} +3 -3
- package/dist/{chunk-DPCEQOIZ.js.map → chunk-QXA2W6UB.js.map} +1 -1
- package/dist/{chunk-N36S36OZ.js → chunk-SPV2CXJ3.js} +3 -3
- package/dist/{chunk-N36S36OZ.js.map → chunk-SPV2CXJ3.js.map} +1 -1
- package/dist/{chunk-KRRHADE7.js → chunk-SXWGLW23.js} +4 -4
- package/dist/{chunk-KRRHADE7.js.map → chunk-SXWGLW23.js.map} +1 -1
- package/dist/{chunk-MUOSKYI2.js → chunk-V5CDPKDA.js} +12 -12
- package/dist/{chunk-MUOSKYI2.js.map → chunk-V5CDPKDA.js.map} +1 -1
- package/dist/{chunk-R37L4BNR.js → chunk-W44KA24A.js} +648 -76
- package/dist/chunk-W44KA24A.js.map +1 -0
- package/dist/{chunk-PV47EEHD.js → chunk-WKEBNB5S.js} +4 -4
- package/dist/{chunk-PV47EEHD.js.map → chunk-WKEBNB5S.js.map} +1 -1
- package/dist/{chunk-ESXZJP4M.js → chunk-WXWQNJCT.js} +3 -3
- package/dist/{chunk-ESXZJP4M.js.map → chunk-WXWQNJCT.js.map} +1 -1
- package/dist/{chunk-354JIEIE.js → chunk-WY22FMZF.js} +5 -5
- package/dist/{chunk-354JIEIE.js.map → chunk-WY22FMZF.js.map} +1 -1
- package/dist/{chunk-D5WTOVLG.js → chunk-Y56YIT6J.js} +2 -2
- package/dist/chunk-Y56YIT6J.js.map +1 -0
- package/dist/{chunk-ZIW34FGO.js → chunk-YIF2IJUA.js} +3 -3
- package/dist/{chunk-ZIW34FGO.js.map → chunk-YIF2IJUA.js.map} +1 -1
- package/dist/{chunk-MGM5EJQQ.js → chunk-YK3XLEQJ.js} +40 -26
- package/dist/chunk-YK3XLEQJ.js.map +1 -0
- package/dist/{chunk-SP5NGNBV.js → chunk-YW2BNDSE.js} +11 -4
- package/dist/chunk-YW2BNDSE.js.map +1 -0
- package/dist/{chunk-GLMKS6V6.js → chunk-ZPCABSSW.js} +4 -4
- package/dist/{chunk-GLMKS6V6.js.map → chunk-ZPCABSSW.js.map} +1 -1
- package/dist/{chunk-J76LDUDS.js → chunk-ZVZTCDUN.js} +26 -10
- package/dist/chunk-ZVZTCDUN.js.map +1 -0
- package/dist/{chunk-RTYDYSUV.js → chunk-ZWUJ22RF.js} +82 -22
- package/dist/chunk-ZWUJ22RF.js.map +1 -0
- package/dist/cli/index.js +902 -1620
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/src/agent-checks.d.ts +22 -10
- package/dist/cli/src/agent-checks.d.ts.map +1 -1
- package/dist/cli/src/commands/catalog.d.ts.map +1 -1
- package/dist/cli/src/commands/config.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 +6 -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/outdated.d.ts.map +1 -1
- package/dist/cli/src/commands/plugin/codex.d.ts +10 -0
- package/dist/cli/src/commands/plugin/codex.d.ts.map +1 -1
- package/dist/cli/src/commands/plugin/types.d.ts +5 -2
- package/dist/cli/src/commands/plugin/types.d.ts.map +1 -1
- package/dist/cli/src/commands/preset-export.d.ts.map +1 -1
- package/dist/cli/src/commands/project.d.ts +6 -0
- package/dist/cli/src/commands/project.d.ts.map +1 -1
- package/dist/cli/src/commands/rebuild.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 +13 -0
- package/dist/cli/src/commands/serve-preflight.d.ts.map +1 -1
- package/dist/cli/src/commands/serve.d.ts.map +1 -1
- package/dist/cli/src/commands/show.d.ts.map +1 -1
- package/dist/cli/src/commands/source.d.ts +2 -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/update.d.ts.map +1 -1
- package/dist/cli/src/commands/validate.d.ts +6 -1
- package/dist/cli/src/commands/validate.d.ts.map +1 -1
- package/dist/cli/src/commands/verify.d.ts.map +1 -1
- package/dist/cli/src/helpers.d.ts +23 -0
- package/dist/cli/src/helpers.d.ts.map +1 -1
- package/dist/cli/src/plugin-store/index.d.ts +8 -0
- package/dist/cli/src/plugin-store/index.d.ts.map +1 -1
- package/dist/cli/src/plugin-store/load.d.ts +1 -0
- package/dist/cli/src/plugin-store/load.d.ts.map +1 -1
- package/dist/cli/src/skill-checks.d.ts +9 -21
- package/dist/cli/src/skill-checks.d.ts.map +1 -1
- package/dist/connectors/config.js +5 -5
- package/dist/connectors/index.js +19 -18
- package/dist/{connectors-TVFFE5H4.js → connectors-CIEIMJY2.js} +22 -21
- package/dist/{connectors-TVFFE5H4.js.map → connectors-CIEIMJY2.js.map} +1 -1
- package/dist/connectors-shared/index.js +2 -2
- package/dist/core/index.js +6 -6
- package/dist/core/manifest.js +2 -2
- package/dist/core/models.js +1 -1
- package/dist/core/publish-manifest.js +3 -3
- package/dist/core/ref.js +1 -1
- package/dist/core/runtime-assets.js +5 -5
- package/dist/core/src/conformance.d.ts.map +1 -1
- package/dist/core/src/driver-sdk.d.ts +12 -2
- package/dist/core/src/driver-sdk.d.ts.map +1 -1
- package/dist/core/src/index.d.ts +4 -4
- package/dist/core/src/index.d.ts.map +1 -1
- package/dist/core/src/lock.d.ts +7 -0
- package/dist/core/src/lock.d.ts.map +1 -1
- package/dist/core/src/manifest.d.ts +9 -0
- package/dist/core/src/manifest.d.ts.map +1 -1
- package/dist/core/src/models.d.ts.map +1 -1
- package/dist/core/src/publish-manifest.d.ts +5 -2
- package/dist/core/src/publish-manifest.d.ts.map +1 -1
- package/dist/core/src/repo-manager.d.ts +14 -0
- package/dist/core/src/repo-manager.d.ts.map +1 -1
- package/dist/core/workspace-config.js +4 -4
- package/dist/deploy/index.js +6 -6
- package/dist/discovery/index.js +5 -5
- package/dist/discovery/src/index.d.ts +2 -2
- package/dist/discovery/src/index.d.ts.map +1 -1
- package/dist/discovery/src/parse-manifest.d.ts +7 -0
- package/dist/discovery/src/parse-manifest.d.ts.map +1 -1
- package/dist/discovery/src/source-config.d.ts +6 -0
- package/dist/discovery/src/source-config.d.ts.map +1 -1
- package/dist/{ensure-sources-N4E5EDGC.js → ensure-sources-I62QMZZP.js} +16 -16
- package/dist/{ensure-sources-N4E5EDGC.js.map → ensure-sources-I62QMZZP.js.map} +1 -1
- package/dist/factory-assets/README.md +1 -1
- package/dist/factory-assets/connectors/box.js +19 -18
- package/dist/factory-assets/connectors/deploy.js +19 -18
- package/dist/factory-assets/connectors/devserver.js +19 -18
- package/dist/factory-assets/connectors/flow/adapter.js +19 -18
- package/dist/factory-assets/connectors/flow/engine.js +7 -7
- package/dist/factory-assets/connectors/flow/run-flow.d.ts.map +1 -1
- package/dist/factory-assets/connectors/flow/run-flow.js +21 -20
- package/dist/factory-assets/connectors/flow.js +19 -18
- package/dist/factory-assets/connectors/git.js +19 -18
- package/dist/factory-assets/connectors/gmail.js +19 -18
- package/dist/factory-assets/connectors/googledrive.js +19 -18
- package/dist/factory-assets/connectors/local.js +19 -18
- package/dist/factory-assets/connectors/mattermost.js +19 -18
- package/dist/factory-assets/connectors/memory.js +19 -18
- package/dist/factory-assets/connectors/minio.js +19 -18
- package/dist/factory-assets/connectors/postgres.js +19 -18
- package/dist/factory-assets/connectors/s3.js +19 -18
- package/dist/factory-assets/connectors/sharepoint.js +19 -18
- package/dist/factory-assets/connectors/sqlite.js +19 -18
- package/dist/factory-assets/connectors/static-server.js +19 -18
- package/dist/factory-assets/connectors/tunnel.js +19 -18
- package/dist/factory-assets/connectors/webdav.js +19 -18
- package/dist/factory-assets/connectors/xstate-store.js +19 -18
- package/dist/factory-assets/connectors/xstate.js +19 -18
- package/dist/factory-assets/skills/authoring-skaile-assets/SKILL.md +12 -11
- package/dist/factory-assets/skills/authoring-skaile-manifests/SKILL.md +11 -7
- package/dist/factory-assets/skills/skailify/SKILL.md +3 -3
- package/dist/{flows-CYJI3URW.js → flows-YKC53LDP.js} +11 -11
- package/dist/{flows-CYJI3URW.js.map → flows-YKC53LDP.js.map} +1 -1
- package/dist/{helpers-PPVGVYIZ.js → helpers-3FOM37BO.js} +16 -16
- package/dist/{helpers-PPVGVYIZ.js.map → helpers-3FOM37BO.js.map} +1 -1
- package/dist/library/index.js +10 -10
- package/dist/library/install.js +4 -4
- package/dist/library/src/index.d.ts +1 -1
- package/dist/library/src/index.d.ts.map +1 -1
- package/dist/library/src/local/store-paths.d.ts +8 -0
- package/dist/library/src/local/store-paths.d.ts.map +1 -1
- package/dist/library/src/manifest-writer.d.ts +5 -1
- package/dist/library/src/manifest-writer.d.ts.map +1 -1
- package/dist/library/src/remote/remote-catalog-source.d.ts +3 -2
- package/dist/library/src/remote/remote-catalog-source.d.ts.map +1 -1
- package/dist/{library-publish-EQFYHJ6G.js → library-publish-EFKITCGE.js} +59 -51
- package/dist/library-publish-EFKITCGE.js.map +1 -0
- package/dist/model-endpoint/index.js +19 -3
- 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/resolve.d.ts +5 -0
- package/dist/model-endpoint/src/resolve.d.ts.map +1 -1
- package/dist/model-endpoint/src/server.d.ts +7 -0
- package/dist/model-endpoint/src/server.d.ts.map +1 -1
- package/dist/model-endpoint/src/types.d.ts +41 -7
- package/dist/model-endpoint/src/types.d.ts.map +1 -1
- package/dist/{open-library-JJGDEYYT.js → open-library-NZUI4XGF.js} +19 -19
- package/dist/{open-library-JJGDEYYT.js.map → open-library-NZUI4XGF.js.map} +1 -1
- package/dist/{open-registry-X6YQVP7V.js → open-registry-YPRQDUMK.js} +14 -14
- package/dist/{open-registry-X6YQVP7V.js.map → open-registry-YPRQDUMK.js.map} +1 -1
- package/dist/{paths-NXWIBZCX.js → paths-P55DTBEK.js} +9 -9
- package/dist/{paths-NXWIBZCX.js.map → paths-P55DTBEK.js.map} +1 -1
- package/dist/plugin-store-IPIBZRBX.js +23 -0
- package/dist/plugin-store-IPIBZRBX.js.map +1 -0
- package/dist/project-2BNFZ2CR.js +83 -0
- package/dist/{project-5HW3XSOE.js.map → project-2BNFZ2CR.js.map} +1 -1
- package/dist/resolver/index.js +7 -7
- package/dist/resolver/src/types.d.ts +1 -0
- package/dist/resolver/src/types.d.ts.map +1 -1
- package/dist/resolver/src/validator.d.ts +1 -1
- package/dist/runner/index.js +35 -34
- package/dist/runner/src/agent.d.ts +9 -1
- package/dist/runner/src/agent.d.ts.map +1 -1
- package/dist/runner/src/agents/in-process-host.d.ts.map +1 -1
- package/dist/runner/src/coalesced-restart.d.ts +41 -0
- package/dist/runner/src/coalesced-restart.d.ts.map +1 -0
- package/dist/runner/src/compaction/prompt.d.ts.map +1 -1
- package/dist/runner/src/composition/content-source.d.ts.map +1 -1
- package/dist/runner/src/composition/index.d.ts +1 -1
- package/dist/runner/src/composition/index.d.ts.map +1 -1
- package/dist/runner/src/composition/resolve-instance.d.ts +20 -0
- package/dist/runner/src/composition/resolve-instance.d.ts.map +1 -1
- package/dist/runner/src/mcp-runtime-handlers.d.ts +27 -0
- package/dist/runner/src/mcp-runtime-handlers.d.ts.map +1 -1
- package/dist/runner/src/model-endpoint-discovery.d.ts.map +1 -1
- package/dist/runner/src/resource-handler.d.ts.map +1 -1
- package/dist/runner/src/runner-capabilities.d.ts +16 -3
- package/dist/runner/src/runner-capabilities.d.ts.map +1 -1
- package/dist/runner/src/serve.d.ts +10 -0
- package/dist/runner/src/serve.d.ts.map +1 -1
- package/dist/runner/src/session-builder.d.ts +20 -1
- package/dist/runner/src/session-builder.d.ts.map +1 -1
- package/dist/runner/src/session-capability-wiring.d.ts +7 -0
- package/dist/runner/src/session-capability-wiring.d.ts.map +1 -1
- package/dist/sdk/asset-manager.js +13 -13
- package/dist/sdk/bridge.js +15 -14
- package/dist/sdk/core.js +6 -6
- package/dist/sdk/flow.js +7 -7
- package/dist/sdk/index.js +35 -34
- package/dist/sdk/index.js.map +1 -1
- package/dist/sdk/resolver.js +7 -7
- package/dist/sdk/runner.js +35 -34
- package/dist/sdk/session.js +2 -2
- package/dist/sdk/transport/ws/server.js +1 -1
- package/dist/sdk/transport/ws.js +1 -1
- package/dist/sdk/transport.js +1 -1
- package/dist/sdk/types.js +1 -1
- package/dist/{serve-preflight-GD7IQFA3.js → serve-preflight-V5GM33T3.js} +15 -9
- package/dist/serve-preflight-V5GM33T3.js.map +1 -0
- package/dist/session/index.js +2 -2
- package/dist/{setup-52NDDR7C.js → setup-ZMAPTKJW.js} +25 -24
- package/dist/setup-ZMAPTKJW.js.map +1 -0
- package/dist/{skills-XVHOXOOH.js → skills-7G6QCDEM.js} +12 -12
- package/dist/{skills-XVHOXOOH.js.map → skills-7G6QCDEM.js.map} +1 -1
- package/dist/{source-WKV4QFGS.js → source-6BZA34F5.js} +45 -44
- package/dist/{source-WKV4QFGS.js.map → source-6BZA34F5.js.map} +1 -1
- package/dist/{source-manifest-publish-3HAX6DPN.js → source-manifest-publish-MJXCSUKT.js} +47 -46
- package/dist/source-manifest-publish-MJXCSUKT.js.map +1 -0
- package/dist/transport/index.js +1 -1
- package/dist/transport/src/ws/server.d.ts +9 -0
- package/dist/transport/src/ws/server.d.ts.map +1 -1
- package/dist/transport/ws/server.js +1 -1
- package/dist/transport/ws.js +1 -1
- package/dist/tui/index.js +110 -44
- package/dist/tui/index.js.map +1 -1
- package/dist/tui/src/repl-session.d.ts +7 -0
- package/dist/tui/src/repl-session.d.ts.map +1 -1
- package/dist/tui/src/repl.d.ts +16 -0
- package/dist/tui/src/repl.d.ts.map +1 -1
- package/dist/types/index.js +1 -1
- package/dist/types/manifests.js +1 -1
- package/dist/types/src/events.d.ts +7 -4
- package/dist/types/src/events.d.ts.map +1 -1
- package/dist/types/src/manifests/index.d.ts +1 -0
- package/dist/types/src/manifests/index.d.ts.map +1 -1
- package/dist/types/src/manifests/scaffold-body.d.ts +8 -0
- package/dist/types/src/manifests/scaffold-body.d.ts.map +1 -0
- package/dist/workspace-plugin/adapters/mcp.js +26 -25
- package/dist/workspace-plugin/adapters/omp.js +14 -14
- package/dist/workspace-plugin/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-4AKR4XPQ.js.map +0 -1
- package/dist/chunk-4QINFQ27.js.map +0 -1
- package/dist/chunk-55VKZUQY.js.map +0 -1
- package/dist/chunk-7Y7UYNGL.js.map +0 -1
- package/dist/chunk-ANSZULXH.js.map +0 -1
- package/dist/chunk-B6I7SF2X.js.map +0 -1
- package/dist/chunk-D5WTOVLG.js.map +0 -1
- package/dist/chunk-GQ5OYFVD.js.map +0 -1
- package/dist/chunk-GV3MFKDV.js.map +0 -1
- package/dist/chunk-J76LDUDS.js.map +0 -1
- package/dist/chunk-JJLH4TX4.js.map +0 -1
- package/dist/chunk-MGM5EJQQ.js.map +0 -1
- package/dist/chunk-NKDSU4Q7.js.map +0 -1
- package/dist/chunk-NOF73BUH.js.map +0 -1
- package/dist/chunk-NVBN3YOH.js.map +0 -1
- package/dist/chunk-OOQ5Q75W.js.map +0 -1
- package/dist/chunk-PQF5QHVS.js.map +0 -1
- package/dist/chunk-R37L4BNR.js.map +0 -1
- package/dist/chunk-RTYDYSUV.js.map +0 -1
- package/dist/chunk-SP5NGNBV.js.map +0 -1
- package/dist/chunk-TCWECSEB.js.map +0 -1
- package/dist/chunk-VY6NTFE7.js.map +0 -1
- package/dist/chunk-WWUWMOX2.js.map +0 -1
- package/dist/chunk-X5O56UO4.js.map +0 -1
- package/dist/library-publish-EQFYHJ6G.js.map +0 -1
- package/dist/plugin-store-BIITCNOZ.js.map +0 -1
- package/dist/project-5HW3XSOE.js +0 -82
- package/dist/serve-preflight-GD7IQFA3.js.map +0 -1
- package/dist/setup-52NDDR7C.js.map +0 -1
- package/dist/source-manifest-publish-3HAX6DPN.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../bridge/src/drivers/omp-models-yml.ts","../../../bridge/src/drivers/omp.ts"],"names":["path","fs"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA4EO,IAAM,cAAA,GAAoC,CAAC,GAAG,oBAAA,EAAsB,mBAAmB,CAAA;AAO9F,IAAM,mBAAA,GAAyC;AAAA,EAC7C,QAAA;AAAA,EACA,WAAA;AAAA,EACA,WAAA;AAAA,EACA,oBAAA;AAAA,EACA,OAAA;AAAA,EACA;AACF,CAAA;AAyBO,IAAM,mBAAA,GAAsB,YAAA;AAG5B,IAAM,mBAAA,GAAsB,YAAA;AAOnC,IAAM,qBAAA,GAA8C;AAAA,EAClD,YAAA,EAAc,IAAA;AAAA,EACd,aAAA,EAAe,IAAA;AAAA,EACf,aAAA,EAAe,IAAA;AAAA,EACf,YAAA,EAAc,IAAA;AAAA,EACd,aAAA,EAAe,IAAA;AAAA,EACf,iBAAA,EAAmB,IAAA;AAAA,EACnB,kBAAA,EAAoB,IAAA;AAAA,EACpB,eAAA,EAAiB;AACnB,CAAA;AAOA,IAAM,mBAAA,GAA4C;AAAA,EAChD,UAAA,EAAY,IAAA;AAAA,EACZ,cAAA,EAAgB,IAAA;AAAA,EAChB,cAAA,EAAgB,IAAA;AAAA,EAChB,WAAA,E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P","file":"omp.js","sourcesContent":["/**\n * The omp adapter: an AI provider registry serialized into omp's own\n * configuration files, inside a session-private agent directory.\n *\n * omp already implements the target schema — `~/.omp/agent/models.yml` is a\n * `providers:` map with `baseUrl`, `api`, `apiKey`, `headers`, `authHeader`,\n * `auth`, `discovery` and `models[]` (`omp://models.md`) — so this module is a\n * *serializer*, not a translator. Our `surface` enum is omp's `api` enum\n * verbatim (§1.2); {@link OMP_API_VALUES} encodes that assertion so a future\n * surface that omp does not know is reported instead of silently written into\n * a file omp will then reject wholesale.\n *\n * Two files are produced:\n *\n * - `models.yml` — one entry per enabled `llm`/`embed` registry entry. `apiKey`\n * holds the **name** of the per-entry environment variable\n * (`SKAILE_AIP_<ID>_KEY`, {@link providerCredentialEnvName}), never a value:\n * omp resolves a `models.yml` `apiKey` as an env-var name first and only\n * falls back to treating it as a literal token. The values travel in the\n * child environment.\n * - `config.yml` — omp's settings file, carrying `modelRoles` rendered from the\n * `skaile.yaml` `roles` table. `models.yml`'s root accepts only `providers:`;\n * unknown root keys fail its schema, so roles cannot live there.\n *\n * `PI_CODING_AGENT_DIR` relocates omp's whole agent base — `config.yml`,\n * `models.yml` **and** the auth store `agent.db` (`omp://settings.md`). Pointing\n * it at a session-private directory is what makes N providers per session\n * possible without ever writing the user's `~/.omp/agent`. The cost is that a\n * standalone developer session would also lose the OAuth logins stored in that\n * auth store, so {@link materializeOmpAgentDir} seeds the session directory\n * with symlinks to everything in the user's agent directory *except* the two\n * files this module owns. Verified against omp 18.2.6: a ChatGPT/Codex OAuth\n * account stored in `~/.omp/agent/agent.db` still resolves (`omp token\n * openai-codex`) from a relocated directory that only symlinks `agent.db*`.\n * Under the platform the user directory does not exist, the seed is a no-op,\n * and the session starts empty — which is the correct behaviour there.\n *\n * @see PROVIDER-CONFIG-PLAN.md §2.3 (omp row), §5, §9\n * @see omp://models.md, omp://settings.md\n */\n\nimport { createHash } from \"node:crypto\";\nimport type { Stats } from \"node:fs\";\nimport fs from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport {\n type AIProviderLlmEntry,\n type AIProviderRegistry,\n AI_PROVIDER_SURFACES,\n isEntryEnabled,\n type MergedAIProviderRegistry,\n normalizeEntryBaseUrl,\n parseModelRef,\n registryEntries,\n resolveEntryBaseUrl,\n} from \"@skaile/workspaces/core/provider-registry\";\nimport { parse, stringify } from \"yaml\";\nimport type { ModelEntry } from \"../models.js\";\nimport {\n entryCredentialValue,\n providerCredentialEnvName,\n type RegistryCredentialEnvOptions,\n unresolvedProviderCredentials,\n} from \"../provider-materialize/credential-env.js\";\nimport { entrySurface } from \"../provider-materialize/env-drivers.js\";\nimport type { AgentConfig, OmpDriverOptions } from \"../types.js\";\n\n/**\n * omp's allowed provider/model `api` values (`omp://models.md`, \"Allowed\n * provider/model `api` values\").\n *\n * Every {@link AI_PROVIDER_SURFACES} member is in this list — that equality is\n * the premise the whole adapter rests on (§1.2). `google-gemini-cli` is omp's\n * one extra value, which the registry has no surface for.\n */\nexport const OMP_API_VALUES: readonly string[] = [...AI_PROVIDER_SURFACES, \"google-gemini-cli\"];\n\n/**\n * `discovery.type` values omp accepts. The registry's own enum is wider on one\n * side (`anthropic-models-list`, `google-models-list`, `none`) and narrower on\n * the other, so a discovery block is emitted only when omp can act on it.\n */\nconst OMP_DISCOVERY_TYPES: readonly string[] = [\n \"ollama\",\n \"llama.cpp\",\n \"lm-studio\",\n \"openai-models-list\",\n \"proxy\",\n \"litellm\",\n];\n\n/** One `providers.<id>` block of `models.yml`. */\ninterface OmpProviderBlock {\n baseUrl?: string;\n api?: string;\n /** The *name* of the env var holding the credential — never a value. */\n apiKey?: string;\n auth?: \"apiKey\" | \"none\" | \"oauth\";\n authHeader?: boolean;\n headers?: Record<string, string>;\n discovery?: { type: string };\n models?: OmpModelBlock[];\n}\n\n/** One entry of a provider's `models[]`. */\ninterface OmpModelBlock {\n id: string;\n name?: string;\n input?: string[];\n contextWindow?: number;\n supportsTools?: boolean;\n}\n\n/** The two files this module owns inside the agent directory. */\nexport const OMP_MODELS_FILENAME = \"models.yml\";\n\n/** omp's settings file; `modelRoles` lives here, not in `models.yml`. */\nexport const OMP_CONFIG_FILENAME = \"config.yml\";\n\n/**\n * Names {@link materializeOmpAgentDir} never links in from the user's agent\n * directory: the two files it writes itself, their alternate spellings, and\n * the legacy `settings.json` omp would migrate into `config.yml`.\n */\nconst OWNED_AGENT_DIR_FILES: Record<string, true> = {\n \"models.yml\": true,\n \"models.yaml\": true,\n \"models.json\": true,\n \"config.yml\": true,\n \"config.yaml\": true,\n \"config.yml.lock\": true,\n \"config.yaml.lock\": true,\n \"settings.json\": true,\n};\n\n/**\n * omp's own runtime state inside its home. An agent directory that an older release used as\n * omp's home still holds these; they are never agent files, so the identity link skips them\n * and the user's own login (`agent.db`) linked in from their agent directory stays in place.\n */\nconst OMP_RUNTIME_ENTRIES: Record<string, true> = {\n \"agent.db\": true,\n \"agent.db-shm\": true,\n \"agent.db-wal\": true,\n \"models.db\": true,\n \"models.db-shm\": true,\n \"models.db-wal\": true,\n \"skill-descriptions.db\": true,\n \"skill-descriptions.db-shm\": true,\n \"skill-descriptions.db-wal\": true,\n \"custom-session-files\": true,\n intercom: true,\n sessions: true,\n};\n\n/**\n * The only entries of the user's own omp agent directory a session's private home links in:\n * omp's credential store, so the login the developer already has keeps working. Sessions,\n * history, `mcp.json`, extensions and blobs stay out: a run must not write into the user's\n * session store or load their MCP servers and extensions. `config.yml` is copied, not linked.\n */\nconst OMP_LOGIN_FILES = [\"agent.db\", \"agent.db-shm\", \"agent.db-wal\"] as const;\n\n/** Options for {@link renderOmpRegistry}. */\nexport interface RenderOmpRegistryOptions extends RegistryCredentialEnvOptions {\n /** `skaile.yaml` `roles`: role name → model selector. Rendered as `modelRoles`. */\n roles?: Record<string, string>;\n /**\n * The session's own selector. When `roles` names no `default`, the resolved\n * model becomes `modelRoles.default` so `@default` (and omp's `*` alias)\n * resolve to the entry the session actually runs on.\n */\n modelRef?: string;\n /**\n * Settings to render underneath `modelRoles` — the user's own `config.yml`\n * when a standalone session seeds one. `modelRoles` is replaced wholesale,\n * not deep-merged: a seeded role pointing at a provider this session does\n * not define would otherwise survive as a dangling selector.\n */\n baseSettings?: Record<string, unknown>;\n}\n\n/** What {@link renderOmpRegistry} produced. */\nexport interface OmpRegistryRender {\n /** `models.yml` contents. */\n modelsYml: string;\n /** `config.yml` contents. */\n configYml: string;\n /**\n * `SKAILE_AIP_<ID>_KEY` → secret, for the child environment. The only place\n * a credential value appears; both rendered files hold names alone.\n */\n credentialEnv: Record<string, string>;\n /** Entry ids written to `models.yml`, in registry order. */\n providerIds: string[];\n /** `modelRoles` as written, role name → `<providerId>/<providerModelId>`. */\n modelRoles: Record<string, string>;\n /** Entries and roles that could not be rendered, and why. */\n warnings: string[];\n}\n\n/** The provider-side model ids an entry declares, keyed by logical id. */\nfunction entryModelIds(entry: AIProviderLlmEntry): Array<[string, string]> {\n const logical = new Set<string>([\n ...Object.keys(entry.model_map ?? {}),\n ...Object.keys(entry.capabilities ?? {}),\n ]);\n const seen = new Set<string>();\n const out: Array<[string, string]> = [];\n for (const id of logical) {\n const providerSide = entry.model_map?.[id] ?? id;\n if (seen.has(providerSide)) continue;\n seen.add(providerSide);\n out.push([id, providerSide]);\n }\n return out;\n}\n\n/**\n * Serialize one entry into an omp provider block, or report why it cannot be.\n *\n * omp requires `baseUrl` on any provider that declares `models[]`, and\n * provider-level `api` whenever `discovery` is set (except `discovery.type:\n * proxy`, where the wire is auto-detected per model). A file that violates its\n * schema is rejected *wholesale* — the registry keeps operating on built-in\n * models and the error only surfaces through `ModelRegistry.getError()` — so an\n * entry that cannot satisfy those rules is dropped here, loudly, rather than\n * taking every other provider down with it.\n */\nfunction renderProvider(\n id: string,\n entry: AIProviderLlmEntry,\n warnings: string[],\n): OmpProviderBlock | undefined {\n // The Anthropic SDK inside omp appends `/v1/messages`: a stored `…/v1` must\n // not reach the file as written. Not `entryBaseUrl`: omp gets no preset\n // literal, so an entry without an endpoint of its own is reported below.\n const baseUrl = normalizeEntryBaseUrl(resolveEntryBaseUrl(entry), entrySurface(entry));\n if (!baseUrl) {\n warnings.push(\n `provider '${id}' has no resolvable base_url (missing transport params?) — omitted from models.yml`,\n );\n return undefined;\n }\n\n // Only the entry's own surface becomes `api`; an inherited one stays omp's\n // to infer, as before. The preset's surface above only picks the URL rule.\n const surface = entry.surface;\n if (surface && !OMP_API_VALUES.includes(surface)) {\n warnings.push(\n `provider '${id}' has surface '${surface}', which omp's api enum does not accept`,\n );\n return undefined;\n }\n\n const block: OmpProviderBlock = { baseUrl };\n if (surface) block.api = surface;\n\n const kind = entry.credential?.kind ?? \"none\";\n if (kind === \"none\") {\n block.auth = \"none\";\n } else if (kind === \"sigv4\" || kind === \"google_adc\" || kind === \"azure_entra\") {\n // Ambient signing chains: the AWS/Google/Azure SDK inside omp signs the\n // request from its own environment. There is no token to hand over, and\n // omp must not treat the provider as unavailable for the lack of one.\n block.auth = \"none\";\n } else {\n block.apiKey = providerCredentialEnvName(id);\n // `bearer` is the only kind that needs the header injected; the Anthropic\n // and Azure surfaces place an `api_key_header` credential themselves.\n if (kind === \"bearer\" || kind === \"oauth\") block.authHeader = true;\n }\n\n const headers = { ...entry.headers };\n if (entry.query_params && Object.keys(entry.query_params).length > 0) {\n if (surface === \"bedrock-converse-stream\") {\n // omp keeps a query string on a Bedrock `baseUrl` and appends it to the\n // final URL (and to SigV4's canonical request) — the documented carrier\n // for gateways that authenticate by query parameter.\n const search = new URLSearchParams(entry.query_params).toString();\n block.baseUrl = `${baseUrl}${baseUrl.includes(\"?\") ? \"&\" : \"?\"}${search}`;\n } else {\n warnings.push(\n `provider '${id}' declares query_params, which omp's models.yml has no slot for on surface ` +\n `'${surface ?? \"unset\"}' — they were dropped`,\n );\n }\n }\n if (Object.keys(headers).length > 0) block.headers = headers;\n\n const discoveryType = entry.discovery?.type;\n if (discoveryType) {\n if (!OMP_DISCOVERY_TYPES.includes(discoveryType)) {\n warnings.push(\n `provider '${id}' declares discovery '${discoveryType}', which omp does not implement — ` +\n `models come from model_map only`,\n );\n } else if (!surface && discoveryType !== \"proxy\") {\n warnings.push(\n `provider '${id}' declares discovery '${discoveryType}' but no surface — omp requires ` +\n `provider-level api for every discovery type but 'proxy'`,\n );\n } else {\n block.discovery = { type: discoveryType };\n }\n }\n\n const models: OmpModelBlock[] = [];\n for (const [logical, providerSide] of entryModelIds(entry)) {\n const model: OmpModelBlock = { id: providerSide };\n if (logical !== providerSide) model.name = logical;\n const caps = entry.capabilities?.[logical];\n if (caps?.context_window !== undefined) model.contextWindow = caps.context_window;\n if (caps?.images !== undefined) model.input = caps.images ? [\"text\", \"image\"] : [\"text\"];\n if (caps?.tools !== undefined) model.supportsTools = caps.tools;\n models.push(model);\n }\n if (models.length > 0) {\n if (!surface) {\n warnings.push(\n `provider '${id}' declares models but no surface — omp requires api at provider or model level`,\n );\n return undefined;\n }\n block.models = models;\n } else if (!block.discovery) {\n warnings.push(\n `provider '${id}' declares neither model_map/capabilities nor a discovery omp implements — ` +\n `it will only override an omp built-in provider of the same id`,\n );\n }\n\n return block;\n}\n\n/**\n * Resolve the `roles` table into omp `modelRoles` selectors.\n *\n * Roles do not chain, so each value is resolved as a plain selector rather than\n * through `@role` expansion. A trailing omp thinking suffix (`:high`) survives\n * untouched: it is not part of any `model_map` key, so it falls through\n * `parseModelRef`'s literal path and is re-emitted on the provider-side id.\n */\nfunction renderModelRoles(\n registry: AIProviderRegistry | MergedAIProviderRegistry,\n roles: Record<string, string> | undefined,\n modelRef: string | undefined,\n warnings: string[],\n): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [role, selector] of Object.entries(roles ?? {})) {\n const trimmed = selector.trim();\n if (!trimmed) continue;\n const ref = parseModelRef(trimmed, registry);\n if (!ref?.providerModelId) {\n warnings.push(\n `role '${role}' ('${selector}') resolves to no model in this registry — dropped`,\n );\n continue;\n }\n out[role] = `${ref.providerId}/${ref.providerModelId}`;\n }\n if (out.default === undefined && modelRef) {\n const ref = parseModelRef(modelRef, registry, roles);\n if (ref?.providerModelId) out.default = `${ref.providerId}/${ref.providerModelId}`;\n }\n return out;\n}\n\n/**\n * Serialize a registry into the two omp files plus the credential environment\n * that carries their secrets.\n *\n * Only enabled `llm`/`embed` entries are rendered: `stt`/`tts` entries have no\n * wire surface and omp has no slot for them. The credential environment is\n * scoped to the same set — the omp child has no use for a Deepgram key, and a\n * secret that reaches a process which cannot spend it is pure exposure.\n *\n * An entry whose credential does not resolve here still gets its\n * `SKAILE_AIP_<ID>_KEY` name written into `models.yml`: a `platform:` ref is\n * resolved by the session boundary, which materializes the value into\n * `AgentConfig.env` under that same programme-standard name.\n */\nexport function renderOmpRegistry(\n registry: AIProviderRegistry | MergedAIProviderRegistry,\n options: RenderOmpRegistryOptions = {},\n): OmpRegistryRender {\n const warnings: string[] = [];\n const providers: Record<string, OmpProviderBlock> = {};\n const providerIds: string[] = [];\n const credentialEnv: Record<string, string> = {};\n\n // An entry whose credential cannot be resolved here is not handed to omp: it\n // would send an empty key (`invalid x-api-key`) and shadow omp's own login for\n // the same provider.\n const unresolved = new Map(\n unresolvedProviderCredentials(registry, options).map((u) => [u.providerId, u.reason]),\n );\n for (const [id, entry] of registryEntries(registry)) {\n if (entry.kind !== \"llm\" && entry.kind !== \"embed\") continue;\n if (!isEntryEnabled(entry)) continue;\n const reason = unresolved.get(id);\n if (reason) {\n warnings.push(`provider '${id}' omitted from models.yml: ${reason}`);\n continue;\n }\n const block = renderProvider(id, entry as AIProviderLlmEntry, warnings);\n if (!block) continue;\n providers[id] = block;\n providerIds.push(id);\n // Only the canonical name, never a vendor-conventional alias: every\n // endpoint omp may address is named in models.yml with its own variable,\n // and a stray `ANTHROPIC_API_KEY` would silently make omp's *built-in*\n // Anthropic provider look authenticated with some gateway entry's key.\n const secret = entryCredentialValue(id, entry, options);\n if (secret) credentialEnv[providerCredentialEnvName(id)] = secret;\n }\n\n const modelRoles = renderModelRoles(registry, options.roles, options.modelRef, warnings);\n\n const settings: Record<string, unknown> = { ...options.baseSettings };\n if (Object.keys(modelRoles).length > 0) settings.modelRoles = modelRoles;\n\n return {\n modelsYml: stringify({ providers }),\n configYml: stringify(settings),\n credentialEnv,\n providerIds,\n modelRoles,\n warnings,\n };\n}\n\n/**\n * The models a registry makes selectable, as the driver-neutral catalog entry.\n *\n * ids are `<providerId>/<providerModelId>` — the exact selector omp's `--model`\n * and `modelRoles` take, and unambiguous when two entries serve the same model\n * id, which is the normal case once a session carries N providers.\n */\nexport function registryModelEntries(\n registry: AIProviderRegistry | MergedAIProviderRegistry | undefined,\n): ModelEntry[] {\n if (!registry) return [];\n const out: ModelEntry[] = [];\n for (const [id, entry] of registryEntries(registry)) {\n if (entry.kind !== \"llm\" && entry.kind !== \"embed\") continue;\n if (!isEntryEnabled(entry)) continue;\n const label = entry.label ?? id;\n for (const [logical, providerSide] of entryModelIds(entry as AIProviderLlmEntry)) {\n out.push({ id: `${id}/${providerSide}`, name: `${label} ${logical}` });\n }\n }\n return out;\n}\n\n/** Options for {@link materializeOmpAgentDir}. */\nexport interface MaterializeOmpAgentDirOptions extends RenderOmpRegistryOptions {\n /**\n * The user's own omp agent directory to seed from — its auth store\n * (`agent.db`) is linked in so a standalone session keeps the login the\n * developer already has, and its `config.yml` is read as base settings.\n * Sessions, history, `mcp.json` and extensions are not linked. Absent (the\n * platform case) seeds nothing. A missing directory is not an error: it is the platform case.\n */\n seedFrom?: string;\n /**\n * GitAgent identity directory (`AgentConfig.agentDir`) whose contents omp\n * reads out of the same base: `agent.yaml`, `SOUL.md`, `RULES.md`,\n * `knowledge/`. Linked in after the seed, so identity wins a name clash.\n */\n identityDir?: string;\n}\n\n/** What {@link materializeOmpAgentDir} wrote. */\nexport interface OmpAgentDirMaterialization extends OmpRegistryRender {\n /** The directory `PI_CODING_AGENT_DIR` must point at. */\n agentDir: string;\n /** The directory is the driver's temporary home: remove it when the run ends. */\n ephemeral?: boolean;\n /** Names linked in from {@link MaterializeOmpAgentDirOptions.seedFrom}. */\n seeded: string[];\n /** Names linked in from {@link MaterializeOmpAgentDirOptions.identityDir}. */\n identity: string[];\n}\n\n/** Inputs {@link planOmpAgentDir} derives the session directory layout from. */\nexport interface OmpAgentDirPlanInput {\n /** Session working directory. Distinguishes two default-named sessions. */\n cwd: string;\n /** Session id — the directory key, so concurrent sessions never collide. */\n sessionId?: string;\n /** `AgentConfig.driverOptions.omp`. */\n options?: OmpDriverOptions;\n /** Home the default seed source resolves against. Defaults to `os.homedir()`. */\n homeDir?: string;\n /** Root the private directory is created under. Defaults to `os.tmpdir()`. */\n tmpDir?: string;\n}\n\n/** Where a session's omp agent directory lives, and what it inherits. */\nexport interface OmpAgentDirPlan {\n /** Session-private directory `PI_CODING_AGENT_DIR` points at. */\n agentDir: string;\n /** User agent directory whose login is linked in, when there is one to inherit. */\n seedFrom?: string;\n /**\n * The directory is the driver's own temporary home, to be removed when the run ends. False\n * when the session named its own `driverOptions.omp.agentHome`, which belongs to the user.\n */\n ephemeral: boolean;\n}\n\n/**\n * Decide the session-private agent directory and whether it inherits the\n * developer's omp state.\n *\n * The directory is deliberately **outside `cwd`**. It holds omp's credential\n * store — a symlink to the developer's `agent.db` on a standalone machine —\n * and `cwd` is the one tree the agent has write access to by design; managed\n * codex draws the same line and rejects a private directory nested in the\n * workspace (`codex/instance-state.ts`). Sessions are keyed by id, falling\n * back to a digest of the workspace path. The temporary directory is `<key>-<random>`, created per\n * call, so no two runs share one (and one run's cleanup never removes another's).\n *\n * Seeding keys on the user directory *existing*, which is exactly the\n * platform/standalone distinction the plan draws: a platform container has no\n * `~/.omp/agent`, so the session correctly starts empty; a developer machine\n * has one, so the session keeps the logins already stored there.\n * `driverOptions.omp.seedUserAgentDir: false` forces the empty case anyway.\n */\nexport async function planOmpAgentDir(input: OmpAgentDirPlanInput): Promise<OmpAgentDirPlan> {\n const options = input.options;\n const key =\n input.sessionId?.trim() ||\n createHash(\"sha256\").update(path.resolve(input.cwd)).digest(\"hex\").slice(0, 16);\n const ephemeral = options?.agentHome === undefined;\n // The temporary home is unique per spawn: callers key sessions loosely (`skaile chat` passes\n // none, `serve` without --session-id uses one shared id, sub-prompt drivers share a hash), and\n // the driver deletes its home when its run ends, which must never reach a sibling's home.\n let agentDir = options?.agentHome ?? \"\";\n if (ephemeral) {\n const root = path.join(input.tmpDir ?? os.tmpdir(), \"skaile-omp-agent\");\n await fs.mkdir(root, { recursive: true });\n agentDir = await fs.mkdtemp(path.join(root, `${key.replace(/[^A-Za-z0-9._-]/g, \"_\")}-`));\n }\n if (options?.seedUserAgentDir === false) return { agentDir, ephemeral };\n\n const seedFrom =\n options?.userAgentDir ?? path.join(input.homeDir ?? os.homedir(), \".omp\", \"agent\");\n if (path.resolve(seedFrom) === path.resolve(agentDir)) return { agentDir, ephemeral };\n try {\n if (!(await fs.stat(seedFrom)).isDirectory()) return { agentDir, ephemeral };\n } catch {\n return { agentDir, ephemeral };\n }\n return { agentDir, seedFrom, ephemeral };\n}\n\n/**\n * Run the steps that fill a planned home; when one throws, remove a temporary home before\n * rethrowing. The driver only learns the home (and deletes it at cleanup) once these steps\n * return, so a failure here would otherwise leave a new directory per spawn behind.\n */\nasync function removeHomeOnThrow<T>(plan: OmpAgentDirPlan, fill: () => Promise<T>): Promise<T> {\n try {\n return await fill();\n } catch (err) {\n if (plan.ephemeral) await fs.rm(plan.agentDir, { recursive: true, force: true });\n throw err;\n }\n}\n\n/** Remove a path whatever it is, without following a symlink into its target. */\nasync function removeEntry(target: string): Promise<void> {\n let stat: Stats;\n try {\n stat = await fs.lstat(target);\n } catch {\n return;\n }\n if (stat.isSymbolicLink() || stat.isFile()) {\n await fs.unlink(target);\n return;\n }\n await fs.rm(target, { recursive: true, force: true });\n}\n\n/** Symlink every entry of `sourceDir` into `dir`, skipping the owned names. */\nasync function linkInto(\n dir: string,\n sourceDir: string,\n skip: Record<string, true>,\n): Promise<string[]> {\n let names: string[];\n try {\n names = await fs.readdir(sourceDir);\n } catch {\n return [];\n }\n const linked: string[] = [];\n for (const name of names) {\n if (skip[name]) continue;\n const target = path.join(dir, name);\n await removeEntry(target);\n await fs.symlink(path.join(sourceDir, name), target);\n linked.push(name);\n }\n return linked;\n}\n\n/**\n * Remove the symlinks into the user's agent directory that an older release (or a home the\n * session named itself) left in `dir`: only the login files may point there (p811).\n */\nasync function dropStaleSeedLinks(dir: string, sourceDir: string): Promise<void> {\n let names: string[];\n try {\n names = await fs.readdir(dir);\n } catch {\n return;\n }\n const root = path.resolve(sourceDir);\n for (const name of names) {\n if ((OMP_LOGIN_FILES as readonly string[]).includes(name)) continue;\n const entry = path.join(dir, name);\n try {\n if (!(await fs.lstat(entry)).isSymbolicLink()) continue;\n const to = path.resolve(dir, await fs.readlink(entry));\n if (to === root || to.startsWith(root + path.sep)) await fs.unlink(entry);\n } catch {\n // Gone or unreadable: nothing to drop.\n }\n }\n}\n\n/** Symlink the login files (see {@link OMP_LOGIN_FILES}) of the user's agent directory into `dir`. */\nasync function linkLoginFiles(dir: string, sourceDir: string): Promise<string[]> {\n await dropStaleSeedLinks(dir, sourceDir);\n const linked: string[] = [];\n for (const name of OMP_LOGIN_FILES) {\n const from = path.join(sourceDir, name);\n try {\n if (!(await fs.stat(from)).isFile()) continue;\n } catch {\n continue;\n }\n const target = path.join(dir, name);\n await removeEntry(target);\n await fs.symlink(from, target);\n linked.push(name);\n }\n return linked;\n}\n\n/** Read a seeded `config.yml` as the base settings, or `{}` when unusable. */\nasync function readSeededSettings(seedFrom: string): Promise<Record<string, unknown>> {\n for (const name of [\"config.yml\", \"config.yaml\"]) {\n let raw: string;\n try {\n raw = await fs.readFile(path.join(seedFrom, name), \"utf-8\");\n } catch {\n continue;\n }\n const parsed = parse(raw) as unknown;\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n return parsed as Record<string, unknown>;\n }\n }\n return {};\n}\n\n/**\n * Build the session-private agent directory and write omp's two files into it.\n *\n * The user's `~/.omp/agent/models.yml` and `config.yml` are never opened for\n * writing: `config.yml` is *copied* into the session (so a token refresh or a\n * settings write inside the session cannot reach back through a symlink),\n * `models.yml` is not seeded at all, and everything else — `agent.db*` above\n * all — is symlinked so the session shares the developer's logins and caches.\n */\nexport async function materializeOmpAgentDir(\n agentDir: string,\n registry: AIProviderRegistry | MergedAIProviderRegistry,\n options: MaterializeOmpAgentDirOptions = {},\n): Promise<OmpAgentDirMaterialization> {\n await fs.mkdir(agentDir, { recursive: true });\n\n const seeded = options.seedFrom ? await linkLoginFiles(agentDir, options.seedFrom) : [];\n const identity = options.identityDir\n ? await linkInto(agentDir, options.identityDir, OWNED_AGENT_DIR_FILES)\n : [];\n\n const baseSettings =\n options.baseSettings ??\n (options.seedFrom ? await readSeededSettings(options.seedFrom) : undefined);\n\n const render = renderOmpRegistry(registry, { ...options, baseSettings });\n\n await fs.writeFile(path.join(agentDir, OMP_MODELS_FILENAME), render.modelsYml, \"utf-8\");\n await fs.writeFile(path.join(agentDir, OMP_CONFIG_FILENAME), render.configYml, \"utf-8\");\n\n return { ...render, agentDir, seeded, identity };\n}\n\n/** What the omp driver gets back from {@link materializeOmpProviders}. */\nexport interface OmpProviderMaterialization extends OmpAgentDirMaterialization {\n /**\n * The `--model` argument for this session: `<providerId>/<providerModelId>`,\n * the one selector form omp treats as unambiguous when several providers\n * carry the same model id. Absent when the session named no model.\n */\n modelArg?: string;\n}\n\n/**\n * The whole omp adapter for one session: decide the private agent directory,\n * inherit the developer's omp state where there is any, write `models.yml` and\n * `config.yml`, and report the credential environment and `--model` selector\n * the child needs.\n *\n * Returns `undefined` when the session carries no registry with a selectable\n * entry — the driver then behaves exactly as it did before the registry\n * existed, which is what keeps this an expand-and-contract change.\n *\n * Also returns `undefined` when no entry can be handed to omp (every\n * credential unresolved) or when the entry the session's model selects was\n * left out: a session-private agent directory would then start omp without the\n * user's own settings, and a model that only the user's own omp login can\n * serve would fail with `No API key found` although native omp answers. The\n * driver then starts omp on the user's agent directory, so \"omp falls back to\n * its own login\" is true.\n *\n * `env:` references resolve against the runner's environment *overlaid with*\n * `config.env`, so a credential the session boundary already resolved (a\n * `platform:` secret it turned into an env var, for instance) is found here\n * under the name the registry entry points at.\n */\nexport async function materializeOmpProviders(\n config: AgentConfig,\n): Promise<OmpProviderMaterialization | undefined> {\n const registry = config.registry;\n if (!registry) return undefined;\n const selectable = registryEntries(registry).some(\n ([, entry]) => (entry.kind === \"llm\" || entry.kind === \"embed\") && isEntryEnabled(entry),\n );\n if (!selectable) return undefined;\n\n const env = { ...process.env, ...config.env };\n const selected = config.modelRef\n ? parseModelRef(config.modelRef, registry, config.roles)\n : undefined;\n const usable = renderOmpRegistry(registry, {\n env,\n ...(config.roles ? { roles: config.roles } : {}),\n ...(config.modelRef ? { modelRef: config.modelRef } : {}),\n }).providerIds;\n if (usable.length === 0) return undefined;\n if (selected && !usable.includes(selected.providerId)) return undefined;\n\n const plan = await planOmpAgentDir({\n cwd: config.cwd,\n ...(config.sessionId ? { sessionId: config.sessionId } : {}),\n ...(config.driverOptions?.omp ? { options: config.driverOptions.omp } : {}),\n });\n\n const rendered = await removeHomeOnThrow(plan, () =>\n materializeOmpAgentDir(plan.agentDir, registry, {\n env,\n ...(plan.seedFrom ? { seedFrom: plan.seedFrom } : {}),\n ...(config.agentDir ? { identityDir: config.agentDir } : {}),\n ...(config.roles ? { roles: config.roles } : {}),\n ...(config.modelRef ? { modelRef: config.modelRef } : {}),\n }),\n );\n\n return {\n ...rendered,\n ephemeral: plan.ephemeral,\n ...(selected?.providerModelId\n ? { modelArg: `${selected.providerId}/${selected.providerModelId}` }\n : {}),\n };\n}\n\n/** What {@link materializeOmpIdentityDir} wrote. */\nexport interface OmpIdentityDirMaterialization {\n /** The directory `PI_CODING_AGENT_DIR` must point at. */\n agentDir: string;\n /** The directory is the driver's temporary home: remove it when the run ends. */\n ephemeral: boolean;\n /** Names linked in from the user's own omp agent directory. */\n seeded: string[];\n /** Names linked in from `AgentConfig.agentDir`. */\n identity: string[];\n}\n\n/**\n * The omp home of a session that has an agent directory but no provider registry.\n *\n * omp keeps its runtime state (`agent.db`, `models.db`, `skill-descriptions.db`, session\n * scratch, `intercom/`) in `PI_CODING_AGENT_DIR`. Pointing that at the agent directory itself\n * put those files beside `SOUL.md` in a pinned, shared source (`.skaile/cache/agents/<name>/`)\n * and made omp name a path inside the cache when it lacks a credential. So the home is a\n * private directory outside `cwd` (see {@link planOmpAgentDir}): the developer's own omp state\n * is linked in (their login keeps working), their `config.yml` / `models.yml` are copied (a\n * settings write cannot reach back), and the agent directory's entries are linked in last,\n * so the agent files stay where they are and omp can still read them.\n *\n * Returns `undefined` when the session has no `agentDir`.\n */\nexport async function materializeOmpIdentityDir(\n config: AgentConfig,\n): Promise<OmpIdentityDirMaterialization | undefined> {\n const identityDir = config.agentDir;\n if (!identityDir) return undefined;\n // Keyed by the agent and the workspace too: two role children of one session, each with\n // its own agent directory, must not link their entries into one home.\n const agentKey = createHash(\"sha256\")\n .update(`${path.resolve(identityDir)}\\0${path.resolve(config.cwd)}`)\n .digest(\"hex\")\n .slice(0, 12);\n const plan = await planOmpAgentDir({\n cwd: config.cwd,\n sessionId: `${config.sessionId?.trim() || \"agent\"}-${agentKey}`,\n ...(config.driverOptions?.omp ? { options: config.driverOptions.omp } : {}),\n });\n return removeHomeOnThrow(plan, async () => {\n await fs.mkdir(plan.agentDir, { recursive: true });\n const seeded = plan.seedFrom ? await linkLoginFiles(plan.agentDir, plan.seedFrom) : [];\n if (plan.seedFrom) {\n for (const name of Object.keys(OWNED_AGENT_DIR_FILES)) {\n const from = path.join(plan.seedFrom, name);\n try {\n if (!(await fs.stat(from)).isFile()) continue;\n } catch {\n continue;\n }\n const to = path.join(plan.agentDir, name);\n await removeEntry(to);\n await fs.copyFile(from, to);\n }\n }\n const identity = await linkInto(plan.agentDir, identityDir, {\n ...OWNED_AGENT_DIR_FILES,\n ...OMP_RUNTIME_ENTRIES,\n });\n return { agentDir: plan.agentDir, ephemeral: plan.ephemeral, seeded, identity };\n });\n}\n","import { type ChildProcess, spawn } from \"node:child_process\";\nimport { randomUUID } from \"node:crypto\";\nimport type { EventEmitter } from \"node:events\";\nimport { rmSync } from \"node:fs\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createInterface, type Interface } from \"node:readline\";\nimport type { DriverTarget } from \"@skaile/workspaces/plugin-registry\";\nimport {\n type DriverContextReport,\n type Logger,\n type TokenUsage,\n withActivityLabelJsonSchema,\n} from \"@skaile/workspaces/types\";\nimport * as z from \"zod\";\nimport { dispatchCapability } from \"../capability-dispatch.js\";\nimport { classifyGenericErrorMessage } from \"../error-classifier.js\";\nimport { getBridgeLogger } from \"../logger.js\";\nimport { checkToolInputSchema } from \"../mcp-tool-schema-filter.js\";\nimport type { ModelEntry } from \"../models.js\";\nimport { registryDriverConfig } from \"../provider-registry-derive.js\";\nimport {\n type ReconfigureApplyResult,\n ReconfigureLedger,\n type ReconfigurePushContext,\n type ReconfigureSnapshot,\n} from \"../reconfigure-ledger.js\";\nimport { BUILTIN_DRIVER_CATALOG } from \"../registry.js\";\nimport { resolveAgentExec, wrapAgentCommand } from \"../agent-exec.js\";\nimport { stripRunnerPrivateEnv } from \"../runner-private-env.js\";\nimport {\n type AgentConfig,\n AgentDriver,\n type AgentError,\n type AgentPromptInput,\n type BridgeCapabilityTool,\n type DriverInfo,\n type ReconfigureApplied,\n type ReconfigureOutcome,\n type ReconfigurePatch,\n type SlashCommandInfo,\n TOOL_ALLOWLIST_UNSUPPORTED,\n} from \"../types.js\";\nimport {\n materializeOmpIdentityDir,\n materializeOmpProviders,\n registryModelEntries,\n} from \"./omp-models-yml.js\";\n\n/**\n * omp's own `No API key found for <provider>` text ends with `or create <home>/agent.db`:\n * the home is the session's private directory, a path nobody logs in at. Say what a user\n * can do instead: add the provider to the registry, or log in once with `omp`.\n * Any other message is returned as it came.\n */\nexport function ompCredentialMessage(msg: string): string {\n const match = /^(?:Error:\\s*)?No API key found for ([A-Za-z0-9._-]+?)\\.?(?:\\s|$)/.exec(msg);\n if (!match) return msg;\n const provider = match[1];\n const envName = `${provider.toUpperCase().replace(/[^A-Z0-9]/g, \"_\")}_API_KEY`;\n return (\n `No API key found for ${provider}. Add the provider with ` +\n `\\`skaile providers add ${provider} --credential env:${envName}\\`, ` +\n \"or log in once with `omp` (type /login).\"\n );\n}\n\n/**\n * Process-level vars omp needs to run at all, independent of any provider.\n */\nconst OMP_BASE_ENV_KEYS = [\"PATH\", \"HOME\", \"USER\", \"HOSTNAME\", \"SKAILE_SESSION_ID\"] as const;\n\n/**\n * Build the explicit env allowlist forwarded to the omp child process.\n *\n * The runner's full environment is never inherited — only\n * {@link OMP_BASE_ENV_KEYS} (process essentials) and the `PI_*` prefix (omp's\n * own app config the host operator may have set).\n *\n * **Credentials are not on this list.** Every endpoint omp may address is a\n * registry entry, serialized into the session's own `models.yml` with its\n * credential named as `SKAILE_AIP_<ID>_KEY` and the value assigned after this\n * allowlist is built (`./omp-models-yml.ts`). An ambient `ANTHROPIC_API_KEY`\n * in the runner's shell is not a session's statement of intent and does not\n * reach the child; `skaile providers add anthropic --preset anthropic\n * --credential env:ANTHROPIC_API_KEY` is.\n *\n * Test seams (`OMP_BRIDGE_*`, `FAKE_OMP_*`) are passed through so the\n * subprocess harness in `tests/omp-driver.test.ts` can drive a fake-omp\n * script via env-driven mode flags.\n *\n * @docLink packages/bridge/concepts#omp-env-whitelist\n */\nexport function buildOmpChildEnv(parent: NodeJS.ProcessEnv): Record<string, string> {\n const out: Record<string, string> = {};\n for (const key of OMP_BASE_ENV_KEYS) {\n const v = parent[key];\n if (typeof v === \"string\") out[key] = v;\n }\n for (const [key, value] of Object.entries(parent)) {\n if (typeof value !== \"string\") continue;\n if (key.startsWith(\"PI_\") || key.startsWith(\"OMP_BRIDGE_\") || key.startsWith(\"FAKE_OMP_\")) {\n out[key] = value;\n }\n }\n return out;\n}\n\n/**\n * omp's built-in tools, as reported by `omp --help` (\"Available Tools\").\n *\n * `computer` is the one entry omp does not enable by default; everything else\n * is on unless `--tools` narrows the set. Used to turn a manifest *deny* list\n * into the *allow* list omp's CLI actually accepts.\n */\nexport const OMP_BUILTIN_TOOLS = [\n \"read\",\n \"bash\",\n \"edit\",\n \"write\",\n \"grep\",\n \"glob\",\n \"lsp\",\n \"python\",\n \"notebook\",\n \"browser\",\n \"computer\",\n \"task\",\n \"todo\",\n \"web_search\",\n \"ask\",\n] as const;\n\n/** omp's default-enabled toolset — every built-in except `computer`. */\nexport const OMP_DEFAULT_TOOLS: readonly string[] = OMP_BUILTIN_TOOLS.filter(\n (t) => t !== \"computer\",\n);\n\n/**\n * Canonical (Claude Code) tool name → omp built-in tool name.\n *\n * Agent manifests are authored once in the canonical vocabulary and run on\n * whichever harness the workspace is configured for, so the driver owns the\n * translation. Names already in omp's own spelling pass through unchanged.\n *\n * Deliberately partial: Claude tools with no omp counterpart (`WebFetch`,\n * `BashOutput`, `KillShell`, `mcp__*` server tools) are absent and get dropped\n * from the omp `--tools` value — omp's `--tools` governs built-ins only, so\n * naming a non-built-in there would be rejected, and silently keeping it would\n * not restrict anything.\n */\nconst CANONICAL_TO_OMP_TOOL: Record<string, string> = {\n read: \"read\",\n write: \"write\",\n edit: \"edit\",\n multiedit: \"edit\",\n notebookedit: \"notebook\",\n bash: \"bash\",\n grep: \"grep\",\n glob: \"glob\",\n ls: \"glob\",\n task: \"task\",\n agent: \"task\",\n todowrite: \"todo\",\n todoread: \"todo\",\n websearch: \"web_search\",\n web_search: \"web_search\",\n notebook: \"notebook\",\n lsp: \"lsp\",\n python: \"python\",\n browser: \"browser\",\n computer: \"computer\",\n todo: \"todo\",\n ask: \"ask\",\n askuserquestion: \"ask\",\n};\n\n/**\n * Translate a manifest tool list into omp built-in tool names.\n *\n * Unknown names are dropped rather than passed through: a manifest is expected\n * to run on more than one harness, so it legitimately names tools this one has\n * never heard of.\n */\nfunction toOmpToolNames(names: readonly string[] | undefined): string[] {\n const out: string[] = [];\n for (const raw of names ?? []) {\n const mapped = CANONICAL_TO_OMP_TOOL[raw.trim().toLowerCase().replace(/[\\s-]/g, \"\")];\n if (mapped && !out.includes(mapped)) out.push(mapped);\n }\n return out;\n}\n\n/**\n * Resolve `AgentConfig.tools` into the omp CLI flags that enforce it.\n *\n * omp expresses tool restriction as a positive `--tools a,b,c` list (or\n * `--no-tools`) — there is no deny flag — so a manifest deny list is applied by\n * subtracting from {@link OMP_DEFAULT_TOOLS}.\n *\n * Returns `[]` when the manifest declares no restriction, which leaves omp on\n * its full default toolset exactly as before. That default toolset is the bulk\n * of every request's fixed token prefix, so this is the lever an agent\n * definition needs in order to shrink it.\n *\n * Pure — exported for direct testing.\n *\n * @since 1.5.0\n */\nexport function buildOmpToolArgs(tools: AgentConfig[\"tools\"]): string[] {\n const allowed = toOmpToolNames(tools?.allowed);\n const denied = new Set(toOmpToolNames(tools?.denied));\n\n const declaredAllow = (tools?.allowed?.length ?? 0) > 0;\n const declaredDeny = (tools?.denied?.length ?? 0) > 0;\n if (!declaredAllow && !declaredDeny) return [];\n\n const base = declaredAllow ? allowed : [...OMP_DEFAULT_TOOLS];\n const effective = base.filter((t) => !denied.has(t));\n\n // An allow list that named only tools omp does not have, or a deny list that\n // removed everything, both mean \"no tools\" — say so explicitly rather than\n // emitting `--tools ` and letting omp fall back to the full default set.\n if (effective.length === 0) return [\"--no-tools\"];\n return [\"--tools\", effective.join(\",\")];\n}\n\n/**\n * Longest host tool name handed to omp. omp forwards host tool names to the\n * provider verbatim; Anthropic allows 128 characters, OpenAI-compatible\n * endpoints 64, so the stricter bound keeps every provider working.\n */\nconst OMP_HOST_TOOL_NAME_MAX = 64;\n\n/** One `set_host_tools` entry (`omp://rpc.md`, \"set_host_tools payload\"). */\nexport interface OmpHostToolDefinition {\n name: string;\n label: string;\n description: string;\n parameters: Record<string, unknown>;\n loadMode: \"essential\";\n}\n\n/** Result of {@link buildOmpHostTools}. */\nexport interface OmpHostToolSet {\n /** Definitions to send in `set_host_tools`. */\n definitions: OmpHostToolDefinition[];\n /** omp host tool name → capability name, for routing `host_tool_call`. */\n capabilityNames: Map<string, string>;\n /** Capabilities left out because the provider would reject their schema. */\n dropped: Array<{ tool: string; reason: string }>;\n}\n\n/**\n * Turn the runner's capability tool list into omp host tool definitions.\n *\n * omp accepts any name in `set_host_tools` but forwards it to the provider\n * as-is, and providers reject anything outside `^[a-zA-Z0-9_-]{1,64}$` with a\n * 400 that fails the whole turn (verified against omp 18.6.0 + Anthropic:\n * `app.editor.open` → `tools.3.custom.name: String should match pattern`).\n * Names are therefore sanitised (`app.editor.open` → `app_editor_open`) and\n * the original kept in `capabilityNames`. Collisions — with another\n * capability or with an omp built-in, which omp refuses — get a numeric\n * suffix.\n *\n * omp also forwards the JSON Schema untouched, so each advertised schema is\n * checked with the same rules the claude-sdk driver applies to raw MCP\n * schemas ({@link checkToolInputSchema}); a failing tool is dropped rather\n * than turning every request into a 400. `loadMode: \"essential\"` keeps every\n * capability in the prompt instead of behind omp's tool discovery, matching\n * claude-sdk where every capability is in the tool list.\n *\n * Pure — exported for direct testing.\n */\nexport function buildOmpHostTools(tools: readonly BridgeCapabilityTool[]): OmpHostToolSet {\n const taken = new Set<string>(OMP_BUILTIN_TOOLS);\n const out: OmpHostToolSet = { definitions: [], capabilityNames: new Map(), dropped: [] };\n for (const tool of tools) {\n // Advertise-only label, as in claude-sdk and codex; `dispatchCapability`\n // strips it before the registry sees the input.\n const parameters = { ...withActivityLabelJsonSchema(tool.parameters), type: \"object\" };\n const reason = checkToolInputSchema(parameters);\n if (reason) {\n out.dropped.push({ tool: tool.name, reason });\n continue;\n }\n const base =\n tool.name.replace(/[^a-zA-Z0-9_-]/g, \"_\").slice(0, OMP_HOST_TOOL_NAME_MAX) || \"capability\";\n let name = base;\n for (let n = 2; taken.has(name); n++) {\n const suffix = `_${n}`;\n name = `${base.slice(0, OMP_HOST_TOOL_NAME_MAX - suffix.length)}${suffix}`;\n }\n taken.add(name);\n out.capabilityNames.set(name, tool.name);\n out.definitions.push({\n name,\n label: tool.name,\n description: tool.description,\n parameters,\n loadMode: \"essential\",\n });\n }\n return out;\n}\n\n/** Thinking levels omp accepts for `--thinking` / `set_thinking_level`. omp drops anything else silently. */\nexport const OMP_THINKING_LEVELS = [\n \"off\",\n \"minimal\",\n \"low\",\n \"medium\",\n \"high\",\n \"xhigh\",\n \"max\",\n \"auto\",\n] as const;\nexport type OmpThinkingLevel = (typeof OMP_THINKING_LEVELS)[number];\n\n/** Largest image attachment omp will be sent (Anthropic's 5 MB per-image limit). */\nconst OMP_MAX_IMAGE_BYTES = 5 * 1024 * 1024;\n\n/**\n * Map `AgentConfig.thinking` / `effort` to an omp thinking level.\n *\n * `disabled` wins over `effort` → `off`. Otherwise an explicit `effort`\n * (low/medium/high/xhigh/max) maps to the same-named level (omp clamps `max` to\n * `xhigh` on models without it). Without effort, `enabled` → `medium` and\n * `adaptive` → `auto`. Returns `undefined` when neither is set (omp keeps its\n * own default) or when the value is outside omp's set — `set_thinking_level`\n * accepts garbage without an error, so validation has to happen here.\n */\nexport function ompThinkingLevel(\n cfg: Pick<AgentConfig, \"thinking\" | \"effort\">,\n): OmpThinkingLevel | undefined {\n const level = (() => {\n if (cfg.thinking === \"disabled\") return \"off\";\n if (cfg.effort) return cfg.effort;\n if (cfg.thinking === \"enabled\") return \"medium\";\n if (cfg.thinking === \"adaptive\") return \"auto\";\n return undefined;\n })();\n return level !== undefined && (OMP_THINKING_LEVELS as readonly string[]).includes(level)\n ? (level as OmpThinkingLevel)\n : undefined;\n}\n\n/**\n * Split a model selector into the `provider` / `modelId` pair `set_model`\n * takes. The registry renders selectors as `<providerId>/<providerModelId>`\n * (the spawn-time `--model` value); provider ids never contain `/` but model\n * ids can, so the split is on the FIRST `/`:\n * `openrouter/anthropic/claude-sonnet-4` → `{ provider: \"openrouter\", modelId: \"anthropic/claude-sonnet-4\" }`.\n * A bare name (no `provider/` prefix) cannot be expressed: omp's `--model`\n * fuzzy matching has no RPC equivalent, so the result is `undefined`.\n */\nexport function splitOmpModel(model: string): { provider: string; modelId: string } | undefined {\n const slash = model.indexOf(\"/\");\n if (slash > 0 && slash < model.length - 1) {\n return { provider: model.slice(0, slash), modelId: model.slice(slash + 1) };\n }\n return undefined;\n}\n\ninterface OmpEvent {\n type: string;\n data?: unknown;\n id?: string;\n success?: boolean;\n error?: string;\n message?: OmpMessage;\n [key: string]: unknown;\n}\n\ninterface OmpMessage {\n role?: string;\n content?: string | OmpContentBlock[];\n /**\n * Why the turn stopped. omp reports a failed request as a normal\n * `message_end` carrying `stopReason: \"error\"` rather than as an `error`\n * event, so this is the only signal that the turn failed.\n */\n stopReason?: string;\n /** Provider/transport error text accompanying `stopReason: \"error\"`. */\n errorMessage?: string;\n /** Final usage of this model call; running partials on `message_start`/updates are ignored. */\n usage?: OmpUsage;\n}\n\n/** Token counters on an assistant `message_end`; every field is optional and unvalidated. */\ninterface OmpUsage {\n input?: unknown;\n output?: unknown;\n cacheRead?: unknown;\n cacheWrite?: unknown;\n reasoningTokens?: unknown;\n totalTokens?: unknown;\n}\n\n/** omp RPC `ImageContent`: raw base64 (no `data:` prefix) plus its MIME type. */\ninterface OmpImageContent {\n type: \"image\";\n data: string;\n mimeType: string;\n}\n\ninterface OmpContentBlock {\n type: string;\n text?: string;\n id?: string;\n name?: string;\n input?: unknown;\n thinking?: string;\n}\n\n/**\n * A question omp is parked on: the `extension_ui_request` the host still owes\n * an `extension_ui_response` for. One request can carry several questions;\n * the response goes out once every one has an answer.\n */\ninterface OmpPendingQuestion {\n /** Id of the `extension_ui_request`; the response must echo it. */\n id: string;\n /** `ask` answers with `answers[]`; the `select` fallback answers with `value`. */\n method: \"ask\" | \"select\";\n questions: Array<{ id: string; question: string; options: string[]; multi: boolean }>;\n /** The user's answer per question, by position; `undefined` while unanswered. */\n answers: Array<string | undefined>;\n}\n\n/** What the running omp process holds, for the reconfigure ledger. */\ninterface OmpApplied extends ReconfigureSnapshot {\n /** The omp thinking level last sent (or spawned with). */\n level?: OmpThinkingLevel;\n}\n\n/**\n * The line of omp's stderr that says why it gave up. omp prints an unrelated\n * warning first (a failed extension load) and the real cause last (`No default\n * model selected. Use /login ...`), so the cause is the last line that reads as\n * an error, else the last line. Escape sequences are stripped.\n */\nexport function ompStartFailureCause(lines: readonly string[]): string {\n const clean = lines\n // biome-ignore lint/suspicious/noControlCharactersInRegex: strips ANSI escapes\n .map((l) => l.replace(/\\u001b\\[[0-9;]*m/g, \"\").trim())\n .filter(Boolean);\n const isCause = (l: string) =>\n /\\b(error|no default model|not (?:found|installed|logged)|invalid|unauthori[sz]ed|cannot|can't|failed)\\b/i.test(\n l,\n ) && !/failed to load extension/i.test(l);\n for (let i = clean.length - 1; i >= 0; i--) {\n if (isCause(clean[i] as string)) return clean[i] as string;\n }\n return clean.at(-1) ?? \"\";\n}\n\n/**\n * Agent driver for the oh-my-pi (omp) coding agent.\n *\n * Spawns `omp --mode rpc-ui --no-ui` as a child process and communicates via newline-delimited\n * JSON-RPC over stdin/stdout. Model-agnostic: supports any LLM provider.\n *\n * @see https://github.com/can1357/oh-my-pi\n *\n * @remarks\n * **Session persistence** — omp writes JSONL session files to `<cwd>/.omp/sessions/`\n * (via `--session-dir`). After each turn (`agent_end`), sends a `get_state` RPC to\n * capture the native session ID and emits a `session_info` event so the forge layer\n * can persist it. On the next spawn, callers pass `resumeSessionId` to restore omp's\n * native context.\n *\n * **stderrBuffer** — collects the last 20 lines of stderr so they can be appended to\n * crash error messages for diagnostics without blocking the stdout readline loop.\n *\n * **systemPrompt injection** — omp does not accept a system prompt string directly.\n * The driver writes `AgentConfig.systemPrompt` to a file of its own under\n * `<cwd>/.skaile/cache/omp-system/`, passes the path via `--append-system-prompt` and deletes\n * the file when the process ends.\n *\n * **agentDir** — omp's home (`PI_CODING_AGENT_DIR`) is a private directory outside `cwd`\n * that links in the entries of the GitAgent directory (agent.yaml, RULES.md, knowledge/), so\n * omp's runtime databases never land beside the pinned agent files. omp reads no SOUL.md:\n * the runner puts the soul into `systemPrompt`.\n *\n * **Capabilities** — `AgentConfig.capabilities` (Protocol v2) is registered with omp\n * as host tools (`set_host_tools`) once the process is ready, and again whenever the\n * registry reports a change. omp calls them back with `host_tool_call`, answered via\n * `dispatchCapability` exactly as claude-sdk's `skaile-capabilities` MCP server does.\n * Names are sanitised for the provider; see {@link buildOmpHostTools}.\n *\n * **Questions** — omp's `ask` tool is enabled as one `extension_ui_request` dialog\n * (`set_ask_dialog`), published as the same `question` events as claude-sdk's\n * `AskUserQuestion` and answered through {@link OmpDriver.answerQuestion}. The turn stays\n * parked in omp until then; abort, kill and process exit release it. Dialogs the host\n * cannot answer (`confirm`, `input`, `editor`) are cancelled immediately.\n *\n * @docLink packages/bridge/drivers#omp-driver\n */\nexport class OmpDriver extends AgentDriver {\n readonly driverInfo: DriverInfo = {\n id: \"omp\",\n name: \"omp (oh-my-pi)\",\n modelAgnostic: true,\n supportsInBandAbort: true,\n capabilities: BUILTIN_DRIVER_CATALOG.omp?.capabilities,\n };\n\n private readonly log: Logger = getBridgeLogger(\"omp\");\n private proc: ChildProcess | null = null;\n private rl: Interface | null = null;\n private reqId = 0;\n private config: AgentConfig;\n private ready = false;\n private startPromise: Promise<void> | null = null;\n private stderrBuffer: string[] = [];\n private prevText = \"\";\n /** OMP session ID captured via `get_state` after each turn. */\n private _ompSessionId?: string;\n /**\n * Usage of the most recent turn, summed over every model call in it (a tool\n * loop is one prompt but many assistant messages). Cleared when a turn\n * starts, like claude-sdk, so it never mixes two turns.\n */\n private _lastTokens: TokenUsage | null = null;\n /**\n * Prompt size of the most recent model call: the real context fill, which\n * `_lastTokens` (turn-cumulative) overstates on a tool loop. omp's own\n * `get_state.contextUsage.tokens` replaces it once that reply lands.\n */\n private _lastContextTokens: number | null = null;\n /** Context window of the active model, from `get_state.contextUsage`. */\n private _contextWindow: number | null = null;\n /** Per-spawn file holding the system prompt omp was started with; removed with the process. */\n private systemPromptFile: string | null = null;\n /** The private omp home of the running process, when it is the driver's own temporary one. */\n private privateHome: string | null = null;\n\n override getTokenUsage(): TokenUsage | null {\n return this._lastTokens;\n }\n\n override getContextTokens(): number | null {\n return this._lastContextTokens;\n }\n\n override getContextWindow(): number | null {\n return this._contextWindow;\n }\n\n /**\n * omp reports only its fill and window (`get_state.contextUsage`), refreshed\n * here so a request between turns is current. A local RPC, so cheap. Unlike\n * `captureState` it throws on a failed reply: a stale fill must never be\n * reported as a fresh measurement.\n */\n override async getContextUsageReport(): Promise<DriverContextReport | null> {\n if (!this.proc) return null;\n const response = await this.request({ type: \"get_state\" }, { quiet: true });\n if (!response.success) {\n throw new Error(`omp get_state failed: ${response.error ?? \"no error given\"}`);\n }\n this.captureContextUsage((response.data as Record<string, unknown> | undefined)?.contextUsage);\n if (this._lastContextTokens === null && this._contextWindow === null) return null;\n return { usedTokens: this._lastContextTokens, contextWindow: this._contextWindow };\n }\n\n /** Per-turn settlement handlers; non-null only while a prompt is in flight. */\n private turnResolve: (() => void) | null = null;\n private turnReject: ((err: Error) => void) | null = null;\n /** omp host tool name → capability name for the last `set_host_tools` sent. */\n private hostToolCapabilities = new Map<string, string>();\n /** In-flight `host_tool_call`s by omp request id; aborted by `host_tool_cancel`. */\n private readonly hostToolCalls = new Map<string, { controller: AbortController; name: string }>();\n /** Requests awaiting a `response`, by request id; failed when the process goes away. */\n private readonly pendingRequests = new Map<string, (err: Error) => void>();\n /** Unsubscribes the capability registry listener; set while a process runs. */\n private unsubscribeToolsChanged: (() => void) | null = null;\n /** Request ids whose failed `response` is logged by the caller, not surfaced as an error event. */\n private readonly quietRequestIds = new Set<string>();\n /** Capability tools already warned about, so a re-send logs each once. */\n private readonly warnedDroppedHostTools = new Set<string>();\n /** The `ask` (or `select` fallback) omp is parked on, until answered, cancelled or the process ends. */\n private pendingQuestion: OmpPendingQuestion | null = null;\n /**\n * Tail of the FIFO of prompts: each `prompt()`/`promptInput()` runs only after\n * the previous one settled, so one turn at a time is ever in flight (omp runs\n * a single agent loop). Never rejects.\n */\n private promptTail: Promise<void> = Promise.resolve();\n /** `true` while `agent_end` is being delivered to listeners. */\n private turnEnded = false;\n\n override get runtimeSessionId(): string | undefined {\n return this._ompSessionId;\n }\n\n /** Slash commands from omp's last `available_commands_update`. */\n private cachedCommands: SlashCommandInfo[] = [];\n\n override getSlashCommands(): SlashCommandInfo[] {\n return this.cachedCommands;\n }\n\n override getModel(): string | undefined {\n return this.config.model;\n }\n\n /**\n * Owns the desired config, drift and ordering of live reconfigures. Its\n * snapshot is what the running omp process was last told: the config values\n * `model`, `modelRef`, `thinking` and `effort` came from (the rollback targets\n * when omp refuses a change) and the omp thinking `level` sent. Set at spawn,\n * updated on each successful `set_*`.\n */\n private readonly reconfig: ReconfigureLedger<OmpApplied>;\n\n /**\n * Apply `model` / `thinking` / `effort`: the {@link ReconfigureLedger} writes\n * the desired config and, when the process is up and idle, pushes it through\n * {@link applyLive} (`set_model` / `set_thinking_level`), answering from omp's\n * reply. A patch that arrives mid-turn or before `ready` is not lost: config is\n * the source of truth, flushed before the next `prompt()` and read by the next\n * spawn. A refusal (omp's, or a model `set_model` cannot express live: no\n * `provider/` prefix) rolls the config back and answers `rejected`. In registry\n * mode the patch also replaces `modelRef`, so a respawn (crash, `resetSession()`)\n * starts the reconfigured model; models.yml already lists every enabled provider.\n */\n override reconfigure(patch: ReconfigurePatch): Promise<ReconfigureOutcome> {\n return this.reconfig.reconfigure(patch);\n }\n\n /** Push drifted model / thinking settings to the running process. Never rejects. */\n private async applyLive(\n delta: ReconfigureApplied,\n applied: OmpApplied,\n { late }: ReconfigurePushContext,\n ): Promise<ReconfigureApplyResult> {\n if (delta.model !== undefined) {\n const target = splitOmpModel(delta.model);\n if (!target) {\n // `set_model` cannot express a bare name, so the running process keeps\n // its model: refuse rather than report one omp is not running.\n const message = `set_model cannot apply \"${delta.model}\" live (no provider/ prefix); model unchanged`;\n this.log.warn(\"model has no provider prefix; set_model cannot apply it live\", {\n model: delta.model,\n });\n if (!late) this.emit(\"agent-event\", { type: \"error\", error: message });\n return { rejected: message };\n }\n const refusal = await this.sendReconfigure({ type: \"set_model\", ...target }, late);\n if (refusal !== null) return { rejected: refusal };\n applied.model = delta.model;\n applied.modelRef = delta.modelRef ?? applied.modelRef;\n }\n\n if (delta.thinking !== undefined || delta.effort !== undefined) {\n const level = ompThinkingLevel(this.config);\n if (level !== undefined && level !== applied.level) {\n const refusal = await this.sendReconfigure({ type: \"set_thinking_level\", level }, late);\n if (refusal !== null) return { rejected: refusal };\n applied.level = level;\n }\n }\n return \"applied\";\n }\n\n /**\n * Send one live-reconfigure request. A failed `response` is emitted as an\n * `error` event by {@link handleEvent}, and a transport failure (timeout,\n * process gone) here, unless `late`: a refusal of a patch already answered\n * `ok` reaches the host as `reconfigure_rejected`, so it gets no `error`\n * event as well. Returns `null` when omp accepted it, else why not.\n */\n private async sendReconfigure(\n msg: { type: string; [key: string]: unknown },\n late: boolean,\n ): Promise<string | null> {\n try {\n const resp = await this.request(msg, { quiet: late });\n if (resp.success) return null;\n this.log.warn(\"omp rejected reconfigure\", { type: msg.type, error: resp.error });\n return typeof resp.error === \"string\" ? resp.error : `omp refused ${msg.type}`;\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n this.log.warn(\"reconfigure request failed\", { type: msg.type, error });\n if (!late) {\n this.emit(\"agent-event\", { type: \"error\", error: `${msg.type} failed: ${error}` });\n }\n return `${msg.type} failed: ${error}`;\n }\n }\n\n /**\n * @param config - Driver configuration. omp-relevant fields:\n * - `cwd` — working directory; omp session files are stored under `<cwd>/.omp/sessions/`.\n * - `model` — forwarded as `--model <selector>`. In registry mode `modelRef` takes precedence at spawn; `reconfigure({ model })` keeps both in step.\n * - `systemPrompt` — written to a per-spawn file under `<cwd>/.skaile/cache/omp-system/` and appended via `--append-system-prompt`.\n * - `agentDir` — its entries are linked into omp's private home (`PI_CODING_AGENT_DIR`); the directory itself is never omp's home.\n * - `sshKeyPath` — injected as `GIT_SSH_COMMAND` for authenticated git operations.\n * - `resumeSessionId` — omp session UUID to restore via `--session <id>`.\n */\n constructor(config: AgentConfig) {\n super();\n this.config = config;\n this.reconfig = new ReconfigureLedger<OmpApplied>({\n config: () => this.config,\n isLive: () => this.proc !== null && this.ready,\n isIdle: () => !this.turnResolve,\n applyLive: (delta, applied, context) => this.applyLive(delta, applied, context),\n onLateRejection: (rollback) => this.emit(\"reconfigure-rollback\", rollback),\n log: this.log,\n });\n }\n\n public async start(): Promise<void> {\n // In-flight start first: `proc` is set before `ready` and before the host\n // tools are registered, and callers must not prompt ahead of either.\n if (this.startPromise) return this.startPromise;\n if (this.proc) return;\n // A start that fails before omp is running (home or env setup, a spawn error) must not\n // leave the per-spawn system prompt file behind.\n this.startPromise = this._start().catch((err: unknown) => {\n this.removeSystemPromptFile();\n this.removePrivateHome();\n throw err;\n });\n return this.startPromise;\n }\n\n private async _start(): Promise<void> {\n // `rpc-ui` keeps omp's tool UI (the `ask` dialog) on the wire; `--no-ui`\n // keeps its extensions headless, so no widget/notify frames or approval dialogs.\n const args = [\"--mode\", \"rpc-ui\", \"--no-ui\"];\n\n // ── Session persistence ───────────────────────────────────────────────────\n // Store OMP session files in <cwd>/.omp/sessions/ so they survive process\n // restarts. The caller passes resumeSessionId to restore a prior session.\n const sessionDir = path.join(this.config.cwd, \".omp\", \"sessions\");\n await fs.mkdir(sessionDir, { recursive: true });\n args.push(\"--session-dir\", sessionDir);\n\n if (this.config.resumeSessionId) {\n this.log.info(\"resuming OMP session\", { sessionId: this.config.resumeSessionId });\n args.push(\"--session\", this.config.resumeSessionId);\n }\n\n // ── Provider registry → session-private omp agent directory ───────────────\n // Every enabled registry entry is serialized into omp's own `models.yml`\n // inside a directory `PI_CODING_AGENT_DIR` points at, so an omp session\n // sees N selectable providers and resolves `@role` across them. Returns\n // undefined for a session that carries no registry, which keeps the\n // legacy `provider`/`model`/env path byte-identical.\n const providers = await materializeOmpProviders(this.config);\n if (providers) {\n // Known to cleanup() from here on, so a later start step that throws cannot leave it behind.\n this.privateHome = providers.ephemeral ? providers.agentDir : null;\n for (const warning of providers.warnings) this.log.warn(\"registry\", { warning });\n this.log.info(\"rendered omp models.yml\", {\n agentDir: providers.agentDir,\n providers: providers.providerIds,\n modelRoles: providers.modelRoles,\n seeded: providers.seeded.length,\n });\n } else if (this.config.registry) {\n // No usable entry, or the selected model's entry was left out: omp runs\n // on the user's own agent directory and login.\n this.log.info(\"registry gives omp no usable provider; omp uses its own login\");\n }\n\n const modelArg = providers?.modelArg ?? this.config.model;\n if (modelArg) args.push(\"--model\", modelArg);\n\n // Thinking level: `--thinking <level>` (omp's default is `high`). The\n // spawn-time snapshot lets `reconfigure()` send only what has drifted.\n const thinkingLevel = ompThinkingLevel(this.config);\n if (thinkingLevel) args.push(\"--thinking\", thinkingLevel);\n this.reconfig.setSnapshot({\n model: this.config.model,\n modelRef: this.config.modelRef,\n thinking: this.config.thinking,\n effort: this.config.effort,\n level: thinkingLevel,\n });\n\n // ── Tool restrictions ─────────────────────────────────────────────────────\n // agent.yaml `tools:` reaches the driver as AgentConfig.tools. The\n // claude-sdk driver has always honoured it; omp did not, so a restricted\n // agent definition silently ran with omp's full default toolset — which\n // dominates the fixed token prefix of every request.\n const toolArgs = buildOmpToolArgs(this.config.tools);\n if (toolArgs.length > 0) {\n this.log.info(\"applying tool restrictions\", { args: toolArgs });\n args.push(...toolArgs);\n }\n\n // ── System prompt injection ───────────────────────────────────────────────\n // omp does not accept a system prompt string directly; it reads from a file.\n // The file is private to this spawn and goes away with the process: a fixed\n // `<cwd>/.omp/system.md` is loaded by every native omp session and sub-agent that\n // runs in the same project afterwards, and the nested `agent.run` child of one run\n // overwrote the parent's (last writer wins). The path is passed via\n // --append-system-prompt.\n //\n // In flow mode (factory-assets/connectors/flow/run-flow.ts conductFlow), systemPrompt carries the full agent\n // identity (SOUL + RULES + knowledge + connector docs) because no agentDir is set.\n // In REPL mode (agent.ts buildDriver), systemPrompt carries the runner's agent sections\n // (the soul included: omp reads no SOUL.md) and the connector docs.\n this.removeSystemPromptFile();\n if (this.config.systemPrompt) {\n const promptDir = path.join(this.config.cwd, \".skaile\", \"cache\", \"omp-system\");\n await fs.mkdir(promptDir, { recursive: true });\n const systemFile = path.join(promptDir, `${randomUUID()}.md`);\n await fs.writeFile(systemFile, this.config.systemPrompt);\n this.systemPromptFile = systemFile;\n args.push(\"--append-system-prompt\", systemFile);\n }\n\n // Explicit env whitelist for the omp child process. Avoids leaking the\n // runner's full environment (which may carry user secrets provisioned by\n // the platform) into the spawned subprocess. `this.config.env`, when\n // supplied, fully overrides the whitelist (used by tests + advanced\n // callers).\n const env: Record<string, string> = this.config.env\n ? { ...(this.config.env as Record<string, string>) }\n : buildOmpChildEnv(process.env);\n // ── Main-agent handoff ────────────────────────────────────────────────────\n // PI_CODING_AGENT_DIR is omp's home: its runtime databases, credential store and\n // settings live there. It is never the agent directory itself: that holds the pinned\n // agent files (`.skaile/cache/agents/<name>/`) and omp's databases do not belong\n // beside them. omp reads `RULES.md` (not `SOUL.md`) from its home, so the agent's\n // entries are linked into a private home directory (see `materializeOmpIdentityDir`).\n // A rendered registry owns that home: it already contains the agent's files\n // (linked in from `agentDir`) plus the session's `models.yml` / `config.yml`.\n if (providers) {\n env.PI_CODING_AGENT_DIR = providers.agentDir;\n // The only place a credential *value* exists in this adapter. Registry\n // credentials override the ambient allowlist unconditionally: the\n // session's registry is the statement of intent, not whatever the host\n // happened to export.\n Object.assign(env, providers.credentialEnv);\n } else if (this.config.agentDir) {\n const home = await materializeOmpIdentityDir(this.config);\n if (home) {\n this.log.info(\"omp home for the agent\", { agentDir: home.agentDir });\n env.PI_CODING_AGENT_DIR = home.agentDir;\n this.privateHome = home.ephemeral ? home.agentDir : null;\n }\n }\n if (this.config.sshKeyPath) {\n env.GIT_SSH_COMMAND = `ssh -i \"${this.config.sshKeyPath}\" -o StrictHostKeyChecking=accept-new`;\n }\n stripRunnerPrivateEnv(env);\n\n // test-only: `OMP_BRIDGE_BIN` overrides the binary name and `OMP_BRIDGE_PREARGS`\n // (space-delimited) supplies any leading args (e.g. a JS script path when the\n // override binary is `node` or `bun`). Used by the subprocess harness tests in\n // `tests/omp-driver.test.ts` to point spawn at a fake-omp script without\n // monkey-patching `node:child_process`. Both are ignored in production.\n const overrideBin = process.env.OMP_BRIDGE_BIN;\n const overridePreArgs = process.env.OMP_BRIDGE_PREARGS\n ? process.env.OMP_BRIDGE_PREARGS.split(/\\s+/).filter(Boolean)\n : [];\n const spawnBin = overrideBin || \"omp\";\n const spawnArgs = overrideBin ? [...overridePreArgs, ...args] : args;\n\n const spawned = await new Promise<ChildProcess>((resolve, reject) => {\n const startStderr: string[] = [];\n this.log.info(\"spawning omp\", {\n bin: spawnBin,\n args: spawnArgs,\n cwd: this.config.cwd,\n });\n if (env.PI_CODING_AGENT_DIR)\n this.log.debug(\"env: PI_CODING_AGENT_DIR set\", { value: env.PI_CODING_AGENT_DIR });\n if (env.GIT_SSH_COMMAND) this.log.debug(\"env: GIT_SSH_COMMAND set\");\n\n // Cast to ChildProcess: spawn infers ChildProcessWithoutNullStreams for\n // pipe stdio, but bun-types doesn't expose EventEmitter.on on that subtype.\n // With the uid split on, omp runs as the agent uid through the launch shim.\n const target = wrapAgentCommand(spawnBin, spawnArgs, resolveAgentExec());\n const proc = spawn(target.command, target.args, {\n cwd: this.config.cwd,\n env,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n }) as ChildProcess;\n this.proc = proc;\n // bun-types 1.3.11 omits EventEmitter.on from ChildProcess; cast to subscribe.\n const procEmitter = proc as unknown as EventEmitter;\n\n procEmitter.on(\"error\", (err: Error) => {\n // A process replaced (or killed) by kill()/resetSession() no longer\n // owns the turn, the ready state or the error channel.\n if (this.proc !== proc) {\n clearTimeout(readyTimeout);\n reject(err);\n return;\n }\n const detail = this.classifyProcessError(err as NodeJS.ErrnoException);\n this.log.error(\"process error\", err, { detail });\n this.emit(\"agent-event\", { type: \"error\", error: detail.message, detail });\n if (!this.ready) reject(err);\n // Settle any in-flight turn so a process-level error cannot hang prompt().\n this.rejectTurn(Object.assign(new Error(detail.message), { detail }));\n });\n\n procEmitter.on(\"exit\", (code: number | null, signal: NodeJS.Signals | null) => {\n this.log.info(\"process exited\", { code, signal });\n if (this.proc !== proc) {\n // Killed or replaced by kill()/resetSession(): the kill settled its own\n // turn and cleaned up, and a late exit must neither reject the turn of\n // the process that succeeded it nor tear down that process's state.\n // A start still waiting for `ready` on this process is over.\n clearTimeout(readyTimeout);\n reject(new Error(\"omp process killed before it was ready\"));\n // Only a plain kill() is announced; a live successor is not exiting.\n if (this.proc === null) this.emit(\"exit\", { code, signal });\n return;\n }\n const lastStderr = this.stderrBuffer.slice(-10).join(\"\\n\");\n const crashed = code !== null && code !== 0;\n if (crashed) {\n const detail: AgentError = {\n message: `omp process crashed (exit code ${code})${lastStderr ? `: ${lastStderr}` : \"\"}`,\n category: \"process\",\n retryable: true,\n hint:\n lastStderr || \"The agent process exited unexpectedly. Try sending your prompt again.\",\n };\n this.emit(\"agent-event\", { type: \"error\", error: detail.message, detail });\n }\n // An exit before `ready` ends the start: without this the start promise never\n // settles (the ready timeout skips a gone process), and a caller awaiting it\n // hangs, or the process ends on a pending top-level await. Rejected on `close`\n // so omp's last stderr lines (the reason it gave up) are read first.\n if (!this.ready) {\n clearTimeout(readyTimeout);\n // Settles once: on `close` (stdio drained), or after 1 s if `close` never fires.\n // Not unref'd, so the pending start keeps the process alive until it rejects.\n const rejectStart = () => {\n clearTimeout(fallback);\n reject(\n new Error(\n `omp exited before it was ready (${code !== null ? `exit code ${code}` : `signal ${signal}`})${startStderr.length > 0 ? `: ${ompCredentialMessage(ompStartFailureCause(startStderr))}` : \"\"}`,\n ),\n );\n };\n const fallback = setTimeout(rejectStart, 1000);\n procEmitter.once(\"close\", rejectStart);\n }\n this.cleanup();\n // Settle any in-flight turn: an exit before `agent_end` means the turn\n // can never complete normally, so reject rather than leak a pending promise.\n this.rejectTurn(\n new Error(\n crashed\n ? `omp process crashed (exit code ${code})`\n : `omp process exited before the turn completed${signal ? ` (signal ${signal})` : \"\"}`,\n ),\n );\n this.emit(\"exit\", { code, signal });\n });\n\n if (proc.stdout) {\n const rl = createInterface({ input: proc.stdout });\n this.rl = rl;\n // bun-types 1.3.11 omits EventEmitter.on from readline.Interface; cast to subscribe.\n (rl as unknown as EventEmitter).on(\"line\", (line: string) => {\n if (!line.trim()) return;\n try {\n const event: OmpEvent = JSON.parse(line);\n this.handleEvent(event);\n } catch {\n this.log.debug(\"stdout\", { line });\n }\n });\n }\n\n if (proc.stderr) {\n const stderrRl = createInterface({ input: proc.stderr });\n (stderrRl as unknown as EventEmitter).on(\"line\", (line: string) => {\n this.log.warn(`stderr: ${line}`);\n this.stderrBuffer.push(line);\n if (this.stderrBuffer.length > 20) this.stderrBuffer.shift();\n startStderr.push(line);\n if (startStderr.length > 20) startStderr.shift();\n });\n }\n\n const startTime = Date.now();\n const readyTimeout = setTimeout(() => {\n // Not for a process that was replaced or has gone: it must not mark the\n // driver (now owned by a successor, or stopped) as ready.\n if (!this.ready && this.proc === proc) {\n this.log.warn(\"ready timeout, proceeding\", { timeoutMs: 5000 });\n this.ready = true;\n resolve(proc);\n }\n }, 5000);\n\n this.once(\"ready\", () => {\n clearTimeout(readyTimeout);\n if (!this.ready && this.proc === proc) {\n this.log.info(\"process ready\", { elapsedMs: Date.now() - startTime });\n this.ready = true;\n resolve(proc);\n }\n });\n });\n\n // Every await below can span a kill()/resetSession(): the successor owns the\n // driver state then, so a start for this process must not touch it.\n const assertCurrent = (): void => {\n if (this.proc !== spawned) throw new Error(\"omp process was killed during start\");\n };\n\n assertCurrent();\n // Subscribed before the requests so a registry change that lands while they\n // are in flight is not missed. There is no await between the check and the\n // subscription, so a later kill()'s cleanup() always unsubscribes it.\n const hooks = this.config.capabilities;\n if (hooks) {\n this.unsubscribeToolsChanged =\n hooks.onToolsChanged?.(() => {\n void this.syncHostTools();\n }) ?? null;\n }\n\n // Independent of each other, so concurrent: a misbehaving omp blocks start\n // for one request timeout, not two. Both are best-effort and never throw.\n // Before start() resolves, so the first `ask` already arrives as one dialog\n // and the first prompt already sees the tools.\n await Promise.all([this.enableAskDialog(), hooks ? this.syncHostTools() : undefined]);\n assertCurrent();\n\n // Context fill is known before the first prompt (system prompt + tools);\n // best-effort and not awaited, so a slow `get_state` never delays start().\n void this.captureState({ announceSession: false });\n }\n\n /**\n * Register the runner's capabilities with omp as host tools.\n *\n * Sends the full set every time: `set_host_tools` replaces omp's previous\n * host-owned set, so a registry change that removes a capability takes\n * effect too. Best-effort — a failure is logged and the session runs\n * without host tools rather than failing to start.\n */\n private async syncHostTools(): Promise<void> {\n const hooks = this.config.capabilities;\n if (!hooks || !this.proc) return;\n const set = buildOmpHostTools(hooks.composeTools());\n for (const { tool, reason } of set.dropped) {\n const key = `${tool}\\u0000${reason}`;\n if (this.warnedDroppedHostTools.has(key)) continue;\n this.warnedDroppedHostTools.add(key);\n this.log.warn(\"host tool dropped: invalid input schema\", { tool, reason });\n }\n // Swapped before sending so a call racing the response already routes.\n this.hostToolCapabilities = set.capabilityNames;\n try {\n const response = await this.request(\n { type: \"set_host_tools\", tools: set.definitions },\n { quiet: true },\n );\n if (response.success) {\n const data = response.data as { toolNames?: unknown } | undefined;\n this.log.info(\"registered omp host tools\", { toolNames: data?.toolNames });\n } else {\n this.log.error(\"omp rejected host tools\", new Error(response.error ?? \"unknown error\"), {\n tools: set.definitions.map((t) => t.name),\n });\n }\n } catch (err) {\n this.log.error(\"registering omp host tools failed\", err as Error);\n }\n }\n\n /**\n * Execute a capability omp asked the host to run (`host_tool_call`) and\n * answer with `host_tool_result`. Goes through {@link dispatchCapability}\n * so validation, fire-and-forget and render semantics match claude-sdk.\n *\n * Emits `tool_call` / `tool_execution_end` around the dispatch: the\n * normalizer does not read omp's own tool frames, so without these the\n * call — and its `activity_label` — would never reach the chat.\n */\n private handleHostToolCall(event: OmpEvent): void {\n const id = event.id;\n if (typeof id !== \"string\") return;\n const hostName = typeof event.toolName === \"string\" ? event.toolName : \"\";\n const name = this.hostToolCapabilities.get(hostName) ?? hostName;\n const callId = typeof event.toolCallId === \"string\" ? event.toolCallId : id;\n const input = event.arguments ?? {};\n const hooks = this.config.capabilities;\n const controller = new AbortController();\n const call = { controller, name };\n this.hostToolCalls.set(id, call);\n this.emit(\"agent-event\", {\n type: \"tool_call\",\n name,\n tool: { name },\n toolCallId: callId,\n input,\n });\n\n void (async () => {\n let text: string;\n let isError = false;\n try {\n if (!hooks) throw new Error(`no capability host for ${name}`);\n const dispatch = await dispatchCapability(\n hooks,\n name,\n input,\n (_err, dispatchCallId) =>\n this.log.warn(\"background capability handler failed\", {\n name,\n toolCallId: callId,\n callId: dispatchCallId,\n // Nothing from the error: its message can quote the call's content.\n }),\n controller.signal,\n );\n text =\n typeof dispatch.result === \"string\"\n ? dispatch.result\n : JSON.stringify(dispatch.result ?? {});\n } catch (err) {\n isError = true;\n text = `Error: ${(err as Error)?.message ?? String(err)}`;\n }\n // Cancelled by omp or the process went away: nobody awaits a result.\n if (this.hostToolCalls.get(id) !== call) return;\n this.hostToolCalls.delete(id);\n this.emit(\"agent-event\", { type: \"tool_execution_end\", toolName: name });\n try {\n this.send({\n type: \"host_tool_result\",\n id,\n result: { content: [{ type: \"text\", text }] },\n ...(isError ? { isError: true } : {}),\n });\n } catch (err) {\n this.log.warn(\"host tool result undeliverable\", { name, callId, error: String(err) });\n }\n })();\n }\n\n /**\n * `host_tool_cancel`: omp aborted the call, so abort the capability handler\n * and close the call's chat activity (the handler's later settlement is\n * ignored, so this is the only `tool_execution_end` the call gets).\n */\n private handleHostToolCancel(event: OmpEvent): void {\n const targetId = event.targetId;\n if (typeof targetId !== \"string\") return;\n this.abortHostToolCall(targetId);\n }\n\n /** Abort one in-flight host tool call and end its activity; no-op if already settled. */\n private abortHostToolCall(id: string): void {\n const call = this.hostToolCalls.get(id);\n if (!call) return;\n this.hostToolCalls.delete(id);\n call.controller.abort();\n this.emit(\"agent-event\", { type: \"tool_execution_end\", toolName: call.name });\n }\n\n // ── Interactive questions (`ask`) ──────────────────────────────────────────\n\n /**\n * `extension_ui_request`: omp asks the host something. Only `ask` (and the\n * `select` omp falls back to when `set_ask_dialog` is unavailable) can carry\n * a user question; both park until {@link answerQuestion}. Presentation\n * frames expect no reply. Every other kind is a dialog nobody here can\n * answer, so it is cancelled at once — an unanswered dialog would leave the\n * tool call, and the turn, waiting forever.\n */\n private handleExtensionUiRequest(event: OmpEvent): void {\n const method = event.method;\n if (method === \"cancel\") {\n // omp closed a dialog itself (timeout, abort): nothing is owed any more.\n if (typeof event.targetId === \"string\" && this.pendingQuestion?.id === event.targetId) {\n this.pendingQuestion = null;\n }\n return;\n }\n if (\n method === \"notify\" ||\n method === \"setStatus\" ||\n method === \"setWidget\" ||\n method === \"setTitle\" ||\n method === \"set_editor_text\" ||\n method === \"open_url\"\n ) {\n return;\n }\n const id = event.id;\n if (typeof id !== \"string\") return;\n let parsed: OmpPendingQuestion | null = null;\n if (method === \"ask\") parsed = this.parseAskRequest(id, event);\n else if (method === \"select\") parsed = this.parseSelectRequest(id, event);\n if (!parsed) {\n this.log.debug(\"cancelling unsupported omp dialog\", { method: String(method) });\n this.sendUiResponse({ id, cancelled: true });\n return;\n }\n // omp parks on one dialog at a time; a second request means the first is dead.\n this.cancelPendingQuestion();\n this.pendingQuestion = parsed;\n this.announceQuestion(parsed, event);\n }\n\n private parseAskRequest(id: string, event: OmpEvent): OmpPendingQuestion | null {\n if (!Array.isArray(event.questions) || event.questions.length === 0) return null;\n const questions: OmpPendingQuestion[\"questions\"] = [];\n for (const raw of event.questions as unknown[]) {\n const q = raw as { id?: unknown; question?: unknown; options?: unknown; multi?: unknown };\n // The response needs one `{ id }` entry per question; without either field\n // the ask cannot be answered correctly, so refuse it rather than guess.\n if (!q || typeof q.id !== \"string\" || typeof q.question !== \"string\" || !q.question) {\n return null;\n }\n const options = (Array.isArray(q.options) ? (q.options as unknown[]) : []).flatMap((o) => {\n let label: unknown = o;\n if (o && typeof o === \"object\" && \"label\" in o) label = o.label;\n return typeof label === \"string\" ? [label] : [];\n });\n questions.push({ id: q.id, question: q.question, options, multi: q.multi === true });\n }\n return { id, method: \"ask\", questions, answers: questions.map(() => undefined) };\n }\n\n private parseSelectRequest(id: string, event: OmpEvent): OmpPendingQuestion | null {\n if (typeof event.title !== \"string\" || !event.title || !Array.isArray(event.options)) {\n return null;\n }\n const options = (event.options as unknown[]).filter((o): o is string => typeof o === \"string\");\n if (options.length === 0) return null;\n return {\n id,\n method: \"select\",\n questions: [{ id, question: event.title, options, multi: false }],\n answers: [undefined],\n };\n }\n\n /**\n * Publish the parked question the way claude-sdk does for `AskUserQuestion`:\n * an assistant `tool_use` block the normalizer turns into one `question`\n * event per question, plus the matching `tool_call`. Option descriptions and\n * `header`s survive in the tool input for consumers that render them.\n */\n private announceQuestion(pending: OmpPendingQuestion, event: OmpEvent): void {\n const rawQuestions = Array.isArray(event.questions) ? (event.questions as unknown[]) : [];\n const input = {\n requestId: pending.id,\n questions: pending.questions.map((q, i) => {\n const raw = rawQuestions[i] as\n | { header?: unknown; options?: Array<{ label?: unknown; description?: unknown }> }\n | undefined;\n return {\n question: q.question,\n ...(typeof raw?.header === \"string\" ? { header: raw.header } : {}),\n multiSelect: q.multi,\n options: q.options.map((label, j) => {\n const description = raw?.options?.[j]?.description;\n return { label, ...(typeof description === \"string\" ? { description } : {}) };\n }),\n };\n }),\n };\n const toolCallId = `omp-ask:${pending.id}`;\n this.emit(\"agent-event\", {\n type: \"message_start\",\n message: {\n role: \"assistant\",\n content: [{ type: \"tool_use\", name: \"AskUserQuestion\", id: toolCallId, input }],\n },\n });\n this.emit(\"agent-event\", {\n type: \"tool_call\",\n name: \"AskUserQuestion\",\n tool: { name: \"AskUserQuestion\" },\n toolCallId,\n input,\n });\n this.log.debug(\"paused on omp ask\", { questions: pending.questions.length });\n }\n\n override supersedePendingQuestion(): void {\n this.cancelPendingQuestion();\n }\n\n override hasPendingQuestion(): boolean {\n return this.pendingQuestion !== null;\n }\n\n /**\n * While omp is parked on a question a reply that is not an answer must not\n * become a prompt: the turn is still running, and a second prompt would\n * collide with it.\n */\n override get acceptsReplyAsPrompt(): boolean {\n return this.pendingQuestion === null;\n }\n\n override answerQuestion(answer: string, question?: string, requestId?: string): boolean {\n const pending = this.pendingQuestion;\n if (!pending || typeof answer !== \"string\") return false;\n if (requestId !== undefined && requestId !== pending.id) return false;\n\n // A named answer binds to its own question; an unnamed one fills the next\n // unanswered slot. Same rule as claude-sdk.\n let index =\n question !== undefined ? pending.questions.findIndex((q) => q.question === question) : -1;\n if (index === -1) index = pending.answers.indexOf(undefined);\n if (index === -1) return false;\n pending.answers[index] = answer;\n if (pending.answers.some((a) => a === undefined)) return true;\n\n this.pendingQuestion = null;\n this.sendUiResponse(this.buildQuestionResponse(pending));\n this.log.debug(\"answered omp ask\", { questions: pending.questions.length });\n return true;\n }\n\n /** Shape the collected answers as the `extension_ui_response` payload for the request's method. */\n private buildQuestionResponse(pending: OmpPendingQuestion): Record<string, unknown> {\n const find = (options: string[], text: string): string | undefined =>\n options.find((o) => o === text) ??\n options.find((o) => o.toLowerCase() === text.toLowerCase());\n\n if (pending.method === \"select\") {\n const match = find(pending.questions[0]!.options, (pending.answers[0] ?? \"\").trim());\n if (match !== undefined) return { id: pending.id, value: match };\n // A `select` only takes one of its options; free text has nowhere to go.\n this.log.warn(\"select answer matches no option; cancelling it\");\n return { id: pending.id, cancelled: true };\n }\n\n const answers = pending.questions.map((q, i) => {\n const text = (pending.answers[i] ?? \"\").trim();\n const whole = find(q.options, text);\n if (whole !== undefined) return { id: q.id, selectedOptions: [whole] };\n if (q.multi) {\n // The UI hands a multi-select back as one string; take a comma-separated\n // list of labels apart, but only if every piece is a real option.\n const parts = text\n .split(\",\")\n .map((p) => p.trim())\n .filter(Boolean);\n const matched = parts.map((p) => find(q.options, p));\n if (parts.length > 0 && matched.every((m) => m !== undefined)) {\n return { id: q.id, selectedOptions: [...new Set(matched as string[])] };\n }\n }\n // Anything else is the user's own words (omp always offers free text).\n return { id: q.id, selectedOptions: [], ...(text ? { customInput: text } : {}) };\n });\n return { id: pending.id, answers };\n }\n\n /** Write an `extension_ui_response`; undeliverable (process gone) is logged, not thrown. */\n private sendUiResponse(payload: Record<string, unknown>): void {\n try {\n this.send({ type: \"extension_ui_response\", ...payload });\n } catch (err) {\n this.log.warn(\"extension ui response undeliverable\", { error: String(err) });\n }\n }\n\n /** Drop the pending question and tell omp it was cancelled, so its tool call unwinds. */\n private cancelPendingQuestion(): void {\n const pending = this.pendingQuestion;\n if (!pending) return;\n this.pendingQuestion = null;\n this.sendUiResponse({ id: pending.id, cancelled: true });\n }\n\n /**\n * Opt in to omp's single `ask` dialog request (off by default per process).\n * Best-effort: a build without the command answers with a failed response and\n * its `ask` keeps degrading to one `select` per question, which\n * {@link handleExtensionUiRequest} still surfaces as a question.\n */\n private async enableAskDialog(): Promise<void> {\n try {\n const response = await this.request(\n { type: \"set_ask_dialog\", enabled: true },\n { quiet: true },\n );\n if (!response.success) {\n this.log.warn(\"omp rejected set_ask_dialog; ask falls back to select\", {\n error: response.error,\n });\n }\n } catch (err) {\n this.log.warn(\"set_ask_dialog failed\", { error: String(err) });\n }\n }\n\n private extractMessageText(msg: OmpMessage): string {\n if (!msg) return \"\";\n const c = msg.content;\n if (typeof c === \"string\") return c;\n if (Array.isArray(c))\n return c\n .filter((b) => b.type === \"text\" && b.text)\n .map((b) => b.text)\n .join(\"\");\n return \"\";\n }\n\n /**\n * `available_commands_update`: replace the cached slash-command list and\n * publish it. Names carry no leading slash (omp's already don't), matching\n * claude-sdk's `commands_available`. Entries without a name are skipped.\n */\n private handleCommandsUpdate(event: OmpEvent): void {\n const raw = Array.isArray(event.commands) ? (event.commands as unknown[]) : [];\n const commands: SlashCommandInfo[] = [];\n for (const entry of raw) {\n if (!entry || typeof entry !== \"object\") continue;\n const c = entry as { name?: unknown; description?: unknown; input?: { hint?: unknown } };\n if (typeof c.name !== \"string\" || !c.name) continue;\n const hint = c.input && typeof c.input === \"object\" ? c.input.hint : undefined;\n commands.push({\n name: c.name,\n description: typeof c.description === \"string\" ? c.description : \"\",\n argumentHint: typeof hint === \"string\" && hint ? hint : undefined,\n });\n }\n this.cachedCommands = commands;\n this.emit(\"agent-event\", { type: \"commands_available\", commands });\n this.log.debug(\"discovered slash commands\", { count: commands.length });\n }\n\n private handleEvent(event: OmpEvent) {\n if (event.type === \"ready\") {\n this.emit(\"ready\");\n return;\n }\n if (event.type === \"response\") {\n const quiet = typeof event.id === \"string\" && this.quietRequestIds.delete(event.id);\n if (!event.success && event.error && !quiet) {\n const detail = this.classifyErrorMessage(event.error);\n this.emit(\"agent-event\", { type: \"error\", error: detail.message, detail });\n }\n this.emit(`response:${event.id}`, event);\n return;\n }\n // Host tool requests are answered here, not forwarded: they are a\n // host↔omp exchange, surfaced to consumers as `tool_call` events.\n if (event.type === \"host_tool_call\") {\n this.handleHostToolCall(event);\n return;\n }\n if (event.type === \"host_tool_cancel\") {\n this.handleHostToolCancel(event);\n return;\n }\n // UI dialogs (`ask`, …) are a host↔omp exchange: published as `question`\n // events and answered via `answerQuestion`, never forwarded raw.\n if (event.type === \"extension_ui_request\") {\n this.handleExtensionUiRequest(event);\n return;\n }\n // Slash-command list pushed by omp after `ready` and on change: published\n // as `commands_available` (like claude-sdk), never forwarded raw.\n if (event.type === \"available_commands_update\") {\n this.handleCommandsUpdate(event);\n return;\n }\n if (event.type === \"error\" && event.error) {\n const detail = this.classifyErrorMessage(event.error);\n this.emit(\"agent-event\", { ...event, error: detail.message, detail });\n return;\n }\n // Compute text delta for message_update events\n if (event.type === \"message_update\" && event.message) {\n const text = this.extractMessageText(event.message);\n let delta = \"\";\n if (text.startsWith(this.prevText)) {\n delta = text.slice(this.prevText.length);\n } else {\n // Text blocks restructured — emit full text as delta\n delta = text;\n }\n this.prevText = text;\n // Thinking never enters `_textDelta` (extractMessageText sees text blocks\n // only). It travels beside it as `_thinkingDelta`, taken straight from\n // omp's `thinking_delta` sub-event so it cannot duplicate or reorder.\n const sub = event.assistantMessageEvent;\n const thinking =\n sub && typeof sub === \"object\" && \"type\" in sub && sub.type === \"thinking_delta\"\n ? \"delta\" in sub && typeof sub.delta === \"string\"\n ? sub.delta\n : \"\"\n : \"\";\n this.emit(\"agent-event\", {\n ...event,\n _textDelta: delta,\n ...(thinking ? { _thinkingDelta: thinking } : {}),\n });\n return;\n }\n // Reset delta tracking on message boundaries. `message_start` may already\n // carry content (omp emits a partially-populated message when resuming or\n // when the first chunk lands with the start frame); seeding prevText from\n // it rather than clearing keeps the next message_update from re-emitting\n // that text as a delta.\n if (event.type === \"message_start\") {\n this.prevText = event.message ? this.extractMessageText(event.message) : \"\";\n }\n if (event.type === \"message_end\" || event.type === \"agent_end\") {\n this.prevText = \"\";\n }\n\n if (event.type === \"message_end\") this.recordMessageUsage(event.message);\n\n // A failed omp request arrives as `message_end` with `stopReason: \"error\"`,\n // not as an `error` event. Without this branch the turn ended silently: the\n // caller saw a normal completion with no assistant text and no failure,\n // which reads as a hung or empty agent. Surface it on the same channel as\n // every other driver error so callers can classify and retry.\n if (\n event.type === \"message_end\" &&\n event.message?.role === \"assistant\" &&\n event.message.stopReason === \"error\"\n ) {\n const error = event.message.errorMessage || \"omp request failed\";\n const detail = this.classifyErrorMessage(error);\n this.log.error(\"omp request failed\", new Error(error), { detail });\n this.emit(\"agent-event\", { type: \"error\", error: detail.message, detail });\n }\n\n // After each turn ends, capture the OMP session ID so callers can persist it\n // and pass it as resumeSessionId on the next spawn.\n if (event.type === \"agent_end\") {\n void this.captureState();\n }\n // A listener that kills the driver while it handles `agent_end` (the\n // one-shot `skaile run` does) ends a turn that already finished: `kill()`\n // must settle it as done, not as \"omp process killed\".\n const turnEnded = event.type === \"agent_end\";\n this.turnEnded = turnEnded;\n try {\n this.emit(\"agent-event\", event);\n } finally {\n this.turnEnded = false;\n }\n // Resolve AFTER emitting so listeners observing the turn see `agent_end`\n // before the caller's `prompt()` await unblocks.\n if (turnEnded) {\n this.resolveTurn();\n }\n }\n\n /**\n * Resolve the in-flight prompt turn (on `agent_end`). Idempotent — a turn\n * settles at most once, so a stray second `agent_end` is harmless.\n */\n private resolveTurn(): void {\n const resolve = this.turnResolve;\n this.turnResolve = null;\n this.turnReject = null;\n resolve?.();\n }\n\n /**\n * Reject the in-flight prompt turn (process crash/error). Settling here keeps\n * `prompt()` from hanging forever when the child dies before `agent_end`.\n */\n private rejectTurn(err: Error): void {\n const reject = this.turnReject;\n this.turnResolve = null;\n this.turnReject = null;\n reject?.(err);\n }\n\n /**\n * Query OMP's current state via the `get_state` RPC.\n *\n * Always refreshes the context fill from `contextUsage`. With\n * `announceSession` (the default, used after each turn) it also records the\n * native session ID and emits a `session_info` event so the forge layer can\n * persist it. Failures are silently swallowed — both are best-effort.\n */\n private async captureState(options: { announceSession?: boolean } = {}): Promise<void> {\n const announceSession = options.announceSession ?? true;\n try {\n const response = await this.request({ type: \"get_state\" }, { quiet: !announceSession });\n\n if (response.success && response.data) {\n const data = response.data as Record<string, unknown>;\n this.captureContextUsage(data.contextUsage);\n const sessionId = data.sessionId as string | undefined;\n const sessionFile = data.sessionFile as string | undefined;\n if (announceSession && sessionId) {\n this._ompSessionId = sessionId;\n this.log.debug(\"omp session id assigned\", { sessionId });\n this.emit(\"agent-event\", {\n type: \"session_info\",\n driverSessionId: sessionId,\n ...(sessionFile ? { sessionFile } : {}),\n });\n }\n }\n } catch {\n // get_state is best-effort — OMP may not support it yet or the process\n // may have exited. The short-term history injection fallback still works.\n }\n }\n\n /** `get_state.contextUsage` → context fill + window; absent or malformed values are ignored. */\n private captureContextUsage(raw: unknown): void {\n if (!raw || typeof raw !== \"object\") return;\n const tokens = \"tokens\" in raw ? raw.tokens : undefined;\n const contextWindow = \"contextWindow\" in raw ? raw.contextWindow : undefined;\n if (typeof tokens === \"number\" && Number.isFinite(tokens) && tokens >= 0) {\n this._lastContextTokens = tokens;\n }\n if (typeof contextWindow === \"number\" && Number.isFinite(contextWindow) && contextWindow > 0) {\n this._contextWindow = contextWindow;\n }\n }\n\n /** Forget the previous turn's usage; called as a new turn begins. */\n private beginUsageTurn(): void {\n this._lastTokens = null;\n this._lastContextTokens = null;\n }\n\n /**\n * Fold one finished assistant message into the turn's usage. Only the\n * `message_end` value is final (`message_start` and partials carry running\n * zeros). A message without usage, or an errored one reporting all zeros,\n * bills nothing and must neither create a reading nor wipe a good one.\n */\n private recordMessageUsage(message: OmpMessage | undefined): void {\n if (message?.role !== \"assistant\" || !message.usage) return;\n const count = (value: unknown): number | undefined =>\n typeof value === \"number\" && Number.isFinite(value) && value >= 0 ? value : undefined;\n const input = count(message.usage.input);\n const output = count(message.usage.output);\n const cacheRead = count(message.usage.cacheRead);\n const cacheWrite = count(message.usage.cacheWrite);\n const reasoning = count(message.usage.reasoningTokens);\n const total = count(message.usage.totalTokens);\n const callContext = (input ?? 0) + (cacheRead ?? 0) + (cacheWrite ?? 0);\n if (callContext + (output ?? 0) + (total ?? 0) === 0) return;\n\n const turn: TokenUsage = { ...this._lastTokens };\n const add = (key: keyof TokenUsage, value: number | undefined) => {\n if (value !== undefined) turn[key] = (turn[key] ?? 0) + value;\n };\n add(\"inputTokens\", input);\n add(\"outputTokens\", output);\n add(\"cacheReadTokens\", cacheRead);\n add(\"cacheCreationTokens\", cacheWrite);\n add(\"reasoningTokens\", reasoning);\n add(\"totalTokens\", total);\n this._lastTokens = turn;\n // Provisional until `get_state` reports omp's own figure: that reply lands\n // after `agent_end`, and a compaction check can run before it.\n if (callContext > 0) this._lastContextTokens = callContext;\n }\n\n private nextId(): string {\n return `req-${++this.reqId}`;\n }\n\n /**\n * Send a command and await its `response` frame.\n *\n * @param options.quiet - Leave a failed response to the caller instead of\n * surfacing it as an `error` agent event.\n * @throws When the process is not running or no response arrives within\n * `options.timeoutMs` (default 5 s).\n */\n private request(\n msg: { type: string; [key: string]: unknown },\n options: { quiet?: boolean; timeoutMs?: number } = {},\n ): Promise<OmpEvent> {\n const id = this.nextId();\n const event = `response:${id}`;\n // Not `Promise.withResolvers`: the provider/connector packages that\n // typecheck this file target a lib older than es2024.\n let resolve!: (resp: OmpEvent) => void;\n let reject!: (err: Error) => void;\n const promise = new Promise<OmpEvent>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n const onResponse = (resp: OmpEvent) => {\n clearTimeout(timer);\n this.pendingRequests.delete(id);\n resolve(resp);\n };\n // A timed-out quiet request keeps its id: omp may still answer late (with a\n // failure), and that answer must stay as quiet as an in-time one. The id is\n // dropped when the response is handled or the process ends (`cleanup()`).\n const fail = (err: Error, keepQuiet = false) => {\n clearTimeout(timer);\n this.pendingRequests.delete(id);\n this.removeListener(event, onResponse);\n if (!keepQuiet) this.quietRequestIds.delete(id);\n reject(err);\n };\n const timer = setTimeout(\n () => fail(new Error(`${msg.type} timeout`), true),\n options.timeoutMs ?? 5000,\n );\n this.once(event, onResponse);\n this.pendingRequests.set(id, fail);\n if (options.quiet) this.quietRequestIds.add(id);\n try {\n this.send({ id, ...msg });\n } catch (err) {\n fail(err as Error);\n }\n return promise;\n }\n\n private send(msg: object): void {\n if (!this.proc?.stdin?.writable) {\n const detail: AgentError = {\n message: \"omp process not running\",\n category: \"process\",\n retryable: true,\n hint: \"The agent process is not available. It will restart automatically on the next prompt.\",\n };\n const err = Object.assign(new Error(detail.message), { detail });\n throw err;\n }\n this.proc.stdin.write(`${JSON.stringify(msg)}\\n`);\n }\n\n /**\n * Sends a prompt to the omp process via JSON-RPC and resolves when the turn\n * completes (after the `agent_end` event), honoring the `AgentDriver.prompt`\n * contract so driver-agnostic callers can await turn completion uniformly.\n *\n * The driver emits `agent-event` payloads as omp streams responses on stdout.\n * If the child process errors or exits before `agent_end`, the returned promise\n * rejects rather than hanging.\n *\n * @param message - Plain-text user prompt.\n * @throws {Error} When the omp process is not running, its stdin is closed, or\n * the child crashes/exits before the turn completes.\n */\n public prompt(message: string): Promise<void> {\n return this.enqueuePrompt(() => this.runPrompt({ message }));\n }\n\n /**\n * Run one prompt after every earlier one settled. A question omp is parked on\n * is cancelled first, synchronously and ahead of the queue: the parked turn\n * can only finish once its `ask` is released, so the new prompt (the user\n * typing instead of answering) must not wait behind it. The runner queues chat\n * prompts too; this queue still covers callers that drive the driver directly.\n */\n private enqueuePrompt(run: () => Promise<void>): Promise<void> {\n this.cancelPendingQuestion();\n const queued = this.promptTail.then(run);\n this.promptTail = queued.then(\n () => undefined,\n () => undefined,\n );\n return queued;\n }\n\n /**\n * Structured prompt: text plus image/file/skill attachments. Images travel as\n * omp `ImageContent` (`prompt.images`, base64 + mimeType); file and skill\n * attachments are named in a text preamble, because omp reads files itself.\n * Turn settlement is shared with {@link prompt}.\n */\n public override promptInput(input: AgentPromptInput): Promise<void> {\n if (input.toolAllowlist !== undefined)\n return Promise.reject(new Error(TOOL_ALLOWLIST_UNSUPPORTED));\n return this.enqueuePrompt(async () => this.runPrompt(await this.buildPromptPayload(input)));\n }\n\n /** Resolve attachments into the `message` + `images` fields of an omp `prompt` frame. */\n private async buildPromptPayload(\n input: AgentPromptInput,\n ): Promise<{ message: string; images?: OmpImageContent[] }> {\n const attachments = input.attachments ?? [];\n if (attachments.length === 0) return { message: input.text };\n const mimeByExt: Record<string, string> = {\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".gif\": \"image/gif\",\n \".webp\": \"image/webp\",\n };\n const images: OmpImageContent[] = [];\n const preamble: string[] = [];\n let root: string | undefined;\n for (const attachment of attachments) {\n if (attachment.type !== \"image\") {\n preamble.push(`[Attached ${attachment.type}: ${attachment.name} (${attachment.path})]`);\n continue;\n }\n // Image bytes are read here, so the path must stay inside the workspace.\n root ??= await fs.realpath(this.config.cwd);\n const resolved = await fs.realpath(path.resolve(root, attachment.path));\n const rel = path.relative(root, resolved);\n const escapes = rel === \"..\" || rel.startsWith(`..${path.sep}`);\n if (rel === \"\" || escapes || path.isAbsolute(rel)) {\n throw new Error(`Image attachment is outside the workspace: ${attachment.path}`);\n }\n const mimeType = mimeByExt[path.extname(resolved).toLowerCase()];\n if (!mimeType) {\n throw new Error(`Unsupported image type for attachment: ${attachment.path}`);\n }\n // Anthropic rejects images over 5 MB; fail before reading the bytes.\n const { size } = await fs.stat(resolved);\n if (size > OMP_MAX_IMAGE_BYTES) {\n throw new Error(`Image attachment too large (${size} bytes > 5 MB): ${attachment.path}`);\n }\n images.push({\n type: \"image\",\n data: (await fs.readFile(resolved)).toString(\"base64\"),\n mimeType,\n });\n }\n const message = preamble.length ? `${preamble.join(\"\\n\")}\\n\\n${input.text}` : input.text;\n return { message, ...(images.length ? { images } : {}) };\n }\n\n /**\n * Send one `prompt` frame and resolve when the turn completes (`agent_end`).\n * Rejects if the child dies first.\n */\n private async runPrompt(payload: { message: string; images?: OmpImageContent[] }): Promise<void> {\n await this.start();\n // A reconfigure that landed mid-turn or before `ready` applies now.\n await this.reconfig.flushBeforeTurn();\n const id = this.nextId();\n\n // Install the per-turn resolver BEFORE sending: omp can stream a fast\n // `agent_end` on the next readline tick, and if the resolver isn't wired\n // yet that event would be missed and prompt() would hang forever.\n const turnPromise = new Promise<void>((resolve, reject) => {\n this.turnResolve = resolve;\n this.turnReject = reject;\n });\n\n this.beginUsageTurn();\n try {\n this.send({ id, type: \"prompt\", ...payload });\n } catch (err) {\n this.turnResolve = null;\n this.turnReject = null;\n throw err;\n }\n\n await turnPromise;\n }\n\n /**\n * Sends an in-band abort RPC to the omp process, requesting it to stop the\n * current turn without terminating the child process.\n *\n * @remarks This is a best-effort signal — omp may not honour the abort\n * immediately. The process remains alive after `abort()`.\n */\n public async abort(): Promise<void> {\n if (!this.proc) return;\n const id = this.nextId();\n this.send({ id, type: \"abort\" });\n // The dialog's tool call is aborted with the turn; release what it owed.\n this.cancelPendingQuestion();\n }\n\n /** `true` when the omp child process is alive and has not been killed. */\n public get isRunning(): boolean {\n return this.proc !== null && !this.proc.killed;\n }\n\n /**\n * Sends SIGTERM to the omp child process and performs cleanup.\n *\n * The driver instance must not be reused after `kill()`. Create a new\n * `OmpDriver` to start a fresh session.\n */\n kill(): void {\n const proc = this.proc;\n if (!proc) return;\n // Settle this process's in-flight turn here: its late `exit` is ignored (the\n // process is superseded by then) and must not reach a successor's turn.\n if (this.turnEnded) this.resolveTurn();\n else this.rejectTurn(new Error(\"omp process killed\"));\n proc.kill(\"SIGTERM\");\n this.cleanup();\n }\n\n async resetSession(): Promise<void> {\n this.kill();\n // Otherwise the respawn passes `--session` and reopens the pre-reset session.\n this.config = { ...this.config, resumeSessionId: undefined };\n this._lastTokens = null;\n this._lastContextTokens = null;\n this._contextWindow = null;\n await this.start();\n }\n\n private classifyProcessError(err: NodeJS.ErrnoException): AgentError {\n if (err.code === \"ENOENT\") {\n return {\n message: \"omp command not found\",\n category: \"config\",\n retryable: false,\n hint: \"The omp agent is not installed or not on your PATH. Install it and try again.\",\n };\n }\n if (err.code === \"EACCES\") {\n return {\n message: \"Permission denied running omp\",\n category: \"config\",\n retryable: false,\n hint: \"Check file permissions for the omp binary.\",\n };\n }\n return {\n message: err.message,\n category: \"process\",\n retryable: true,\n hint: \"An unexpected process error occurred. Try sending your prompt again.\",\n };\n }\n\n private classifyErrorMessage(rawMsg: string): AgentError {\n const msg = ompCredentialMessage(rawMsg);\n // Shared keyword buckets live in error-classifier.ts; only the hint copy is omp-specific.\n const generic = classifyGenericErrorMessage(msg);\n if (!generic) return { message: msg, category: \"unknown\", retryable: true };\n\n const lower = msg.toLowerCase();\n const hint =\n generic.category === \"auth\"\n ? \"Check your API key configuration in Settings.\"\n : generic.category === \"rate_limit\"\n ? \"You have hit the provider rate limit. Wait a moment and try again.\"\n : generic.category === \"network\"\n ? \"A network error occurred. Check your connection and try again.\"\n : // model: distinguish unavailable-model from over-long-context.\n lower.includes(\"model\")\n ? \"The selected model is not available. Change the model in settings.\"\n : \"The conversation is too long. Start a new session or choose a model with a larger context window.\";\n return { message: msg, category: generic.category, retryable: generic.retryable, hint };\n }\n\n /**\n * The models this session can select.\n *\n * Answered entirely from the registry: the ids are exactly the\n * `<providerId>/<modelId>` selectors rendered into `models.yml`, so a\n * picker offers every enabled endpoint instead of whichever one the\n * ambient binary happens to be authenticated for. A registry whose\n * entries name no models yields no entries here — that gap is closed by\n * giving the entry a `discovery:` block (`PROVIDER-CONFIG-PLAN.md` §1.1),\n * not by asking the omp binary what it happens to know. omp's own catalog\n * (`omp models --json`) answers a different question — every model omp\n * knows across every provider, regardless of what this session's registry\n * enables or has credentials for — and shelling out to an ambient binary\n * from this code path is itself a liability: it can block indefinitely\n * reading a prompt from stdin when run inside another interactive session.\n */\n override async listModels(): Promise<ModelEntry[]> {\n return registryModelEntries(this.config.registry);\n }\n\n /** Delete the system prompt file of the process that is gone (or about to be replaced). */\n private removeSystemPromptFile(): void {\n const file = this.systemPromptFile;\n this.systemPromptFile = null;\n if (file) rmSync(file, { force: true });\n }\n\n /**\n * Delete the private omp home of the process that is gone: it holds symlinks to the login\n * and the agent files and omp's runtime databases, and nothing reads it afterwards (p811).\n */\n private removePrivateHome(): void {\n const home = this.privateHome;\n this.privateHome = null;\n if (home) rmSync(home, { recursive: true, force: true });\n }\n\n private cleanup(): void {\n this.removeSystemPromptFile();\n this.removePrivateHome();\n this.rl?.close();\n this.rl = null;\n this.proc = null;\n this.ready = false;\n this.reconfig.setSnapshot(null);\n this.startPromise = null;\n this.stderrBuffer = [];\n // A respawn re-subscribes and re-registers the host tools from scratch.\n this.unsubscribeToolsChanged?.();\n this.unsubscribeToolsChanged = null;\n this.hostToolCapabilities = new Map();\n // Nothing can receive these results any more; stop the handlers and close\n // their chat activity (the handlers' later settlement is ignored).\n for (const id of [...this.hostToolCalls.keys()]) this.abortHostToolCall(id);\n // No response can arrive any more: fail the waiters now instead of at their timeout.\n for (const fail of [...this.pendingRequests.values()]) fail(new Error(\"omp process ended\"));\n this.pendingRequests.clear();\n this.quietRequestIds.clear();\n // The process that asked is gone; there is nobody to answer to.\n this.pendingQuestion = null;\n }\n}\n\n/**\n * `DriverTarget` wrapper for the omp driver. Registered into the plugin\n * registry by `registerBuiltinDrivers()`.\n */\nexport const ompDriverTarget: DriverTarget<AgentConfig> = {\n id: \"omp\",\n displayName: BUILTIN_DRIVER_CATALOG.omp?.name ?? \"omp (oh-my-pi)\",\n apiVersion: 1,\n // Drivers take AgentConfig; passthrough — full schema validation is out of scope.\n configSchema: z.custom<AgentConfig>(() => true),\n create: async (config, _ctx) => new OmpDriver(config),\n listModels: async (registry, options) =>\n new OmpDriver({\n cwd: process.cwd(),\n sessionId: \"model-list\",\n ...registryDriverConfig(registry, options),\n }).listModels(),\n};\n"]}
|
|
1
|
+
{"version":3,"sources":["../../../bridge/src/drivers/omp-models-yml.ts","../../../bridge/src/drivers/omp.ts"],"names":["path","fs"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA4EO,IAAM,cAAA,GAAoC,CAAC,GAAG,oBAAA,EAAsB,mBAAmB,CAAA;AAO9F,IAAM,mBAAA,GAAyC;AAAA,EAC7C,QAAA;AAAA,EACA,WAAA;AAAA,EACA,WAAA;AAAA,EACA,oBAAA;AAAA,EACA,OAAA;AAAA,EACA;AACF,CAAA;AAyBO,IAAM,mBAAA,GAAsB,YAAA;AAG5B,IAAM,mBAAA,GAAsB,YAAA;AAOnC,IAAM,qBAAA,GAA8C;AAAA,EAClD,YAAA,EAAc,IAAA;AAAA,EACd,aAAA,EAAe,IAAA;AAAA,EACf,aAAA,EAAe,IAAA;AAAA,EACf,YAAA,EAAc,IAAA;AAAA,EACd,aAAA,EAAe,IAAA;AAAA,EACf,iBAAA,EAAmB,IAAA;AAAA,EACnB,kBAAA,EAAoB,IAAA;AAAA,EACpB,eAAA,EAAiB;AACnB,CAAA;AAOA,IAAM,mBAAA,GAA4C;AAAA,EAChD,UAAA,EAAY,IAAA;AAAA,EACZ,cAAA,EAAgB,IAAA;AAAA,EAChB,cAAA,EAAgB,IAAA;AAAA,EAChB,WAAA,EAAa,IAAA;AAAA,EACb,eAAA,EAAiB,IAAA;AAAA,EACjB,eAAA,EAAiB,IAAA;AAAA,EACjB,uBAAA,EAAyB,IAAA;AAAA,EACzB,2BAAA,EAA6B,IAAA;AAAA,EAC7B,2BAAA,EAA6B,IAAA;AAAA,EAC7B,sBAAA,EAAwB,IAAA;AAAA,EACxB,QAAA,EAAU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B,EAAE,CAAA;AAE1E,IAAA,KAAA,MAAW,IAAA,IAAQ,CAAC,GAAG,IAAA,CAAK,eAAA,CAAgB,MAAA,EAAQ,CAAA,EAAG,IAAA,CAAK,IAAI,KAAA,CAAM,mBAAmB,CAAC,CAAA;AAC1F,IAAA,IAAA,CAAK,gBAAgB,KAAA,EAAM;AAC3B,IAAA,IAAA,CAAK,gBAAgB,KAAA,EAAM;AAE3B,IAAA,IAAA,CAAK,eAAA,GAAkB,IAAA;AAAA,EACzB;AACF;AAMO,IAAM,eAAA,GAA6C;AAAA,EACxD,EAAA,EAAI,KAAA;AAAA,EACJ,WAAA,EAAa,sBAAA,CAAuB,GAAA,EAAK,IAAA,IAAQ,gBAAA;AAAA,EACjD,UAAA,EAAY,CAAA;AAAA;AAAA,EAEZ,YAAA,EAAgB,CAAA,CAAA,MAAA,CAAoB,MAAM,IAAI,CAAA;AAAA,EAC9C,QAAQ,OAAO,MAAA,EAAQ,IAAA,KAAS,IAAI,UAAU,MAAM,CAAA;AAAA,EACpD,UAAA,EAAY,OAAO,QAAA,EAAU,OAAA,KAC3B,IAAI,SAAA,CAAU;AAAA,IACZ,GAAA,EAAK,QAAQ,GAAA,EAAI;AAAA,IACjB,SAAA,EAAW,YAAA;AAAA,IACX,GAAG,oBAAA,CAAqB,QAAA,EAAU,OAAO;AAAA,GAC1C,EAAE,UAAA;AACP","file":"omp.js","sourcesContent":["/**\n * The omp adapter: an AI provider registry serialized into omp's own\n * configuration files, inside a session-private agent directory.\n *\n * omp already implements the target schema — `~/.omp/agent/models.yml` is a\n * `providers:` map with `baseUrl`, `api`, `apiKey`, `headers`, `authHeader`,\n * `auth`, `discovery` and `models[]` (`omp://models.md`) — so this module is a\n * *serializer*, not a translator. Our `surface` enum is omp's `api` enum\n * verbatim (§1.2); {@link OMP_API_VALUES} encodes that assertion so a future\n * surface that omp does not know is reported instead of silently written into\n * a file omp will then reject wholesale.\n *\n * Two files are produced:\n *\n * - `models.yml` — one entry per enabled `llm`/`embed` registry entry. `apiKey`\n * holds the **name** of the per-entry environment variable\n * (`SKAILE_AIP_<ID>_KEY`, {@link providerCredentialEnvName}), never a value:\n * omp resolves a `models.yml` `apiKey` as an env-var name first and only\n * falls back to treating it as a literal token. The values travel in the\n * child environment.\n * - `config.yml` — omp's settings file, carrying `modelRoles` rendered from the\n * `skaile.yaml` `roles` table. `models.yml`'s root accepts only `providers:`;\n * unknown root keys fail its schema, so roles cannot live there.\n *\n * `PI_CODING_AGENT_DIR` relocates omp's whole agent base — `config.yml`,\n * `models.yml` **and** the auth store `agent.db` (`omp://settings.md`). Pointing\n * it at a session-private directory is what makes N providers per session\n * possible without ever writing the user's `~/.omp/agent`. The cost is that a\n * standalone developer session would also lose the OAuth logins stored in that\n * auth store, so {@link materializeOmpAgentDir} seeds the session directory\n * with symlinks to everything in the user's agent directory *except* the two\n * files this module owns. Verified against omp 18.2.6: a ChatGPT/Codex OAuth\n * account stored in `~/.omp/agent/agent.db` still resolves (`omp token\n * openai-codex`) from a relocated directory that only symlinks `agent.db*`.\n * Under the platform the user directory does not exist, the seed is a no-op,\n * and the session starts empty — which is the correct behaviour there.\n *\n * @see PROVIDER-CONFIG-PLAN.md §2.3 (omp row), §5, §9\n * @see omp://models.md, omp://settings.md\n */\n\nimport { createHash } from \"node:crypto\";\nimport type { Stats } from \"node:fs\";\nimport fs from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport {\n type AIProviderLlmEntry,\n type AIProviderRegistry,\n AI_PROVIDER_SURFACES,\n isEntryEnabled,\n type MergedAIProviderRegistry,\n normalizeEntryBaseUrl,\n parseModelRef,\n registryEntries,\n resolveEntryBaseUrl,\n} from \"@skaile/workspaces/core/provider-registry\";\nimport { parse, stringify } from \"yaml\";\nimport type { ModelEntry } from \"../models.js\";\nimport {\n entryCredentialValue,\n providerCredentialEnvName,\n type RegistryCredentialEnvOptions,\n unresolvedProviderCredentials,\n} from \"../provider-materialize/credential-env.js\";\nimport { entrySurface } from \"../provider-materialize/env-drivers.js\";\nimport type { AgentConfig, OmpDriverOptions } from \"../types.js\";\n\n/**\n * omp's allowed provider/model `api` values (`omp://models.md`, \"Allowed\n * provider/model `api` values\").\n *\n * Every {@link AI_PROVIDER_SURFACES} member is in this list — that equality is\n * the premise the whole adapter rests on (§1.2). `google-gemini-cli` is omp's\n * one extra value, which the registry has no surface for.\n */\nexport const OMP_API_VALUES: readonly string[] = [...AI_PROVIDER_SURFACES, \"google-gemini-cli\"];\n\n/**\n * `discovery.type` values omp accepts. The registry's own enum is wider on one\n * side (`anthropic-models-list`, `google-models-list`, `none`) and narrower on\n * the other, so a discovery block is emitted only when omp can act on it.\n */\nconst OMP_DISCOVERY_TYPES: readonly string[] = [\n \"ollama\",\n \"llama.cpp\",\n \"lm-studio\",\n \"openai-models-list\",\n \"proxy\",\n \"litellm\",\n];\n\n/** One `providers.<id>` block of `models.yml`. */\ninterface OmpProviderBlock {\n baseUrl?: string;\n api?: string;\n /** The *name* of the env var holding the credential — never a value. */\n apiKey?: string;\n auth?: \"apiKey\" | \"none\" | \"oauth\";\n authHeader?: boolean;\n headers?: Record<string, string>;\n discovery?: { type: string };\n models?: OmpModelBlock[];\n}\n\n/** One entry of a provider's `models[]`. */\ninterface OmpModelBlock {\n id: string;\n name?: string;\n input?: string[];\n contextWindow?: number;\n supportsTools?: boolean;\n}\n\n/** The two files this module owns inside the agent directory. */\nexport const OMP_MODELS_FILENAME = \"models.yml\";\n\n/** omp's settings file; `modelRoles` lives here, not in `models.yml`. */\nexport const OMP_CONFIG_FILENAME = \"config.yml\";\n\n/**\n * Names {@link materializeOmpAgentDir} never links in from the user's agent\n * directory: the two files it writes itself, their alternate spellings, and\n * the legacy `settings.json` omp would migrate into `config.yml`.\n */\nconst OWNED_AGENT_DIR_FILES: Record<string, true> = {\n \"models.yml\": true,\n \"models.yaml\": true,\n \"models.json\": true,\n \"config.yml\": true,\n \"config.yaml\": true,\n \"config.yml.lock\": true,\n \"config.yaml.lock\": true,\n \"settings.json\": true,\n};\n\n/**\n * omp's own runtime state inside its home. An agent directory that an older release used as\n * omp's home still holds these; they are never agent files, so the identity link skips them\n * and the user's own login (`agent.db`) linked in from their agent directory stays in place.\n */\nconst OMP_RUNTIME_ENTRIES: Record<string, true> = {\n \"agent.db\": true,\n \"agent.db-shm\": true,\n \"agent.db-wal\": true,\n \"models.db\": true,\n \"models.db-shm\": true,\n \"models.db-wal\": true,\n \"skill-descriptions.db\": true,\n \"skill-descriptions.db-shm\": true,\n \"skill-descriptions.db-wal\": true,\n \"custom-session-files\": true,\n intercom: true,\n sessions: true,\n};\n\n/**\n * The only entries of the user's own omp agent directory a session's private home links in:\n * omp's credential store, so the login the developer already has keeps working. Sessions,\n * history, `mcp.json`, extensions and blobs stay out: a run must not write into the user's\n * session store or load their MCP servers and extensions. `config.yml` is copied, not linked.\n */\nconst OMP_LOGIN_FILES = [\"agent.db\", \"agent.db-shm\", \"agent.db-wal\"] as const;\n\n/** Options for {@link renderOmpRegistry}. */\nexport interface RenderOmpRegistryOptions extends RegistryCredentialEnvOptions {\n /** `skaile.yaml` `roles`: role name → model selector. Rendered as `modelRoles`. */\n roles?: Record<string, string>;\n /**\n * The session's own selector. When `roles` names no `default`, the resolved\n * model becomes `modelRoles.default` so `@default` (and omp's `*` alias)\n * resolve to the entry the session actually runs on.\n */\n modelRef?: string;\n /**\n * Settings to render underneath `modelRoles` — the user's own `config.yml`\n * when a standalone session seeds one. `modelRoles` is replaced wholesale,\n * not deep-merged: a seeded role pointing at a provider this session does\n * not define would otherwise survive as a dangling selector.\n */\n baseSettings?: Record<string, unknown>;\n}\n\n/** What {@link renderOmpRegistry} produced. */\nexport interface OmpRegistryRender {\n /** `models.yml` contents. */\n modelsYml: string;\n /** `config.yml` contents. */\n configYml: string;\n /**\n * `SKAILE_AIP_<ID>_KEY` → secret, for the child environment. The only place\n * a credential value appears; both rendered files hold names alone.\n */\n credentialEnv: Record<string, string>;\n /** Entry ids written to `models.yml`, in registry order. */\n providerIds: string[];\n /** `modelRoles` as written, role name → `<providerId>/<providerModelId>`. */\n modelRoles: Record<string, string>;\n /** Entries and roles that could not be rendered, and why. */\n warnings: string[];\n}\n\n/** The provider-side model ids an entry declares, keyed by logical id. */\nfunction entryModelIds(entry: AIProviderLlmEntry): Array<[string, string]> {\n const logical = new Set<string>([\n ...Object.keys(entry.model_map ?? {}),\n ...Object.keys(entry.capabilities ?? {}),\n ]);\n const seen = new Set<string>();\n const out: Array<[string, string]> = [];\n for (const id of logical) {\n const providerSide = entry.model_map?.[id] ?? id;\n if (seen.has(providerSide)) continue;\n seen.add(providerSide);\n out.push([id, providerSide]);\n }\n return out;\n}\n\n/**\n * Serialize one entry into an omp provider block, or report why it cannot be.\n *\n * omp requires `baseUrl` on any provider that declares `models[]`, and\n * provider-level `api` whenever `discovery` is set (except `discovery.type:\n * proxy`, where the wire is auto-detected per model). A file that violates its\n * schema is rejected *wholesale* — the registry keeps operating on built-in\n * models and the error only surfaces through `ModelRegistry.getError()` — so an\n * entry that cannot satisfy those rules is dropped here, loudly, rather than\n * taking every other provider down with it.\n */\nfunction renderProvider(\n id: string,\n entry: AIProviderLlmEntry,\n warnings: string[],\n): OmpProviderBlock | undefined {\n // The Anthropic SDK inside omp appends `/v1/messages`: a stored `…/v1` must\n // not reach the file as written. Not `entryBaseUrl`: omp gets no preset\n // literal, so an entry without an endpoint of its own is reported below.\n const baseUrl = normalizeEntryBaseUrl(resolveEntryBaseUrl(entry), entrySurface(entry));\n if (!baseUrl) {\n warnings.push(\n `provider '${id}' has no resolvable base_url (missing transport params?) — omitted from models.yml`,\n );\n return undefined;\n }\n\n // Only the entry's own surface becomes `api`; an inherited one stays omp's\n // to infer, as before. The preset's surface above only picks the URL rule.\n const surface = entry.surface;\n if (surface && !OMP_API_VALUES.includes(surface)) {\n warnings.push(\n `provider '${id}' has surface '${surface}', which omp's api enum does not accept`,\n );\n return undefined;\n }\n\n const block: OmpProviderBlock = { baseUrl };\n if (surface) block.api = surface;\n\n const kind = entry.credential?.kind ?? \"none\";\n if (kind === \"none\") {\n block.auth = \"none\";\n } else if (kind === \"sigv4\" || kind === \"google_adc\" || kind === \"azure_entra\") {\n // Ambient signing chains: the AWS/Google/Azure SDK inside omp signs the\n // request from its own environment. There is no token to hand over, and\n // omp must not treat the provider as unavailable for the lack of one.\n block.auth = \"none\";\n } else {\n block.apiKey = providerCredentialEnvName(id);\n // `bearer` is the only kind that needs the header injected; the Anthropic\n // and Azure surfaces place an `api_key_header` credential themselves.\n if (kind === \"bearer\" || kind === \"oauth\") block.authHeader = true;\n }\n\n const headers = { ...entry.headers };\n if (entry.query_params && Object.keys(entry.query_params).length > 0) {\n if (surface === \"bedrock-converse-stream\") {\n // omp keeps a query string on a Bedrock `baseUrl` and appends it to the\n // final URL (and to SigV4's canonical request) — the documented carrier\n // for gateways that authenticate by query parameter.\n const search = new URLSearchParams(entry.query_params).toString();\n block.baseUrl = `${baseUrl}${baseUrl.includes(\"?\") ? \"&\" : \"?\"}${search}`;\n } else {\n warnings.push(\n `provider '${id}' declares query_params, which omp's models.yml has no slot for on surface ` +\n `'${surface ?? \"unset\"}' — they were dropped`,\n );\n }\n }\n if (Object.keys(headers).length > 0) block.headers = headers;\n\n const discoveryType = entry.discovery?.type;\n if (discoveryType) {\n if (!OMP_DISCOVERY_TYPES.includes(discoveryType)) {\n warnings.push(\n `provider '${id}' declares discovery '${discoveryType}', which omp does not implement — ` +\n `models come from model_map only`,\n );\n } else if (!surface && discoveryType !== \"proxy\") {\n warnings.push(\n `provider '${id}' declares discovery '${discoveryType}' but no surface — omp requires ` +\n `provider-level api for every discovery type but 'proxy'`,\n );\n } else {\n block.discovery = { type: discoveryType };\n }\n }\n\n const models: OmpModelBlock[] = [];\n for (const [logical, providerSide] of entryModelIds(entry)) {\n const model: OmpModelBlock = { id: providerSide };\n if (logical !== providerSide) model.name = logical;\n const caps = entry.capabilities?.[logical];\n if (caps?.context_window !== undefined) model.contextWindow = caps.context_window;\n if (caps?.images !== undefined) model.input = caps.images ? [\"text\", \"image\"] : [\"text\"];\n if (caps?.tools !== undefined) model.supportsTools = caps.tools;\n models.push(model);\n }\n if (models.length > 0) {\n if (!surface) {\n warnings.push(\n `provider '${id}' declares models but no surface — omp requires api at provider or model level`,\n );\n return undefined;\n }\n block.models = models;\n } else if (!block.discovery) {\n warnings.push(\n `provider '${id}' declares neither model_map/capabilities nor a discovery omp implements — ` +\n `it will only override an omp built-in provider of the same id`,\n );\n }\n\n return block;\n}\n\n/**\n * Resolve the `roles` table into omp `modelRoles` selectors.\n *\n * Roles do not chain, so each value is resolved as a plain selector rather than\n * through `@role` expansion. A trailing omp thinking suffix (`:high`) survives\n * untouched: it is not part of any `model_map` key, so it falls through\n * `parseModelRef`'s literal path and is re-emitted on the provider-side id.\n */\nfunction renderModelRoles(\n registry: AIProviderRegistry | MergedAIProviderRegistry,\n roles: Record<string, string> | undefined,\n modelRef: string | undefined,\n warnings: string[],\n): Record<string, string> {\n const out: Record<string, string> = {};\n for (const [role, selector] of Object.entries(roles ?? {})) {\n const trimmed = selector.trim();\n if (!trimmed) continue;\n const ref = parseModelRef(trimmed, registry);\n if (!ref?.providerModelId) {\n warnings.push(\n `role '${role}' ('${selector}') resolves to no model in this registry — dropped`,\n );\n continue;\n }\n out[role] = `${ref.providerId}/${ref.providerModelId}`;\n }\n if (out.default === undefined && modelRef) {\n const ref = parseModelRef(modelRef, registry, roles);\n if (ref?.providerModelId) out.default = `${ref.providerId}/${ref.providerModelId}`;\n }\n return out;\n}\n\n/**\n * Serialize a registry into the two omp files plus the credential environment\n * that carries their secrets.\n *\n * Only enabled `llm`/`embed` entries are rendered: `stt`/`tts` entries have no\n * wire surface and omp has no slot for them. The credential environment is\n * scoped to the same set — the omp child has no use for a Deepgram key, and a\n * secret that reaches a process which cannot spend it is pure exposure.\n *\n * An entry whose credential does not resolve here still gets its\n * `SKAILE_AIP_<ID>_KEY` name written into `models.yml`: a `platform:` ref is\n * resolved by the session boundary, which materializes the value into\n * `AgentConfig.env` under that same programme-standard name.\n */\nexport function renderOmpRegistry(\n registry: AIProviderRegistry | MergedAIProviderRegistry,\n options: RenderOmpRegistryOptions = {},\n): OmpRegistryRender {\n const warnings: string[] = [];\n const providers: Record<string, OmpProviderBlock> = {};\n const providerIds: string[] = [];\n const credentialEnv: Record<string, string> = {};\n\n // An entry whose credential cannot be resolved here is not handed to omp: it\n // would send an empty key (`invalid x-api-key`) and shadow omp's own login for\n // the same provider.\n const unresolved = new Map(\n unresolvedProviderCredentials(registry, options).map((u) => [u.providerId, u.reason]),\n );\n for (const [id, entry] of registryEntries(registry)) {\n if (entry.kind !== \"llm\" && entry.kind !== \"embed\") continue;\n if (!isEntryEnabled(entry)) continue;\n const reason = unresolved.get(id);\n if (reason) {\n warnings.push(`provider '${id}' omitted from models.yml: ${reason}`);\n continue;\n }\n const block = renderProvider(id, entry as AIProviderLlmEntry, warnings);\n if (!block) continue;\n providers[id] = block;\n providerIds.push(id);\n // Only the canonical name, never a vendor-conventional alias: every\n // endpoint omp may address is named in models.yml with its own variable,\n // and a stray `ANTHROPIC_API_KEY` would silently make omp's *built-in*\n // Anthropic provider look authenticated with some gateway entry's key.\n const secret = entryCredentialValue(id, entry, options);\n if (secret) credentialEnv[providerCredentialEnvName(id)] = secret;\n }\n\n const modelRoles = renderModelRoles(registry, options.roles, options.modelRef, warnings);\n\n const settings: Record<string, unknown> = { ...options.baseSettings };\n if (Object.keys(modelRoles).length > 0) settings.modelRoles = modelRoles;\n\n return {\n modelsYml: stringify({ providers }),\n configYml: stringify(settings),\n credentialEnv,\n providerIds,\n modelRoles,\n warnings,\n };\n}\n\n/**\n * The models a registry makes selectable, as the driver-neutral catalog entry.\n *\n * ids are `<providerId>/<providerModelId>` — the exact selector omp's `--model`\n * and `modelRoles` take, and unambiguous when two entries serve the same model\n * id, which is the normal case once a session carries N providers.\n */\nexport function registryModelEntries(\n registry: AIProviderRegistry | MergedAIProviderRegistry | undefined,\n): ModelEntry[] {\n if (!registry) return [];\n const out: ModelEntry[] = [];\n for (const [id, entry] of registryEntries(registry)) {\n if (entry.kind !== \"llm\" && entry.kind !== \"embed\") continue;\n if (!isEntryEnabled(entry)) continue;\n const label = entry.label ?? id;\n for (const [logical, providerSide] of entryModelIds(entry as AIProviderLlmEntry)) {\n out.push({ id: `${id}/${providerSide}`, name: `${label} ${logical}` });\n }\n }\n return out;\n}\n\n/** Options for {@link materializeOmpAgentDir}. */\nexport interface MaterializeOmpAgentDirOptions extends RenderOmpRegistryOptions {\n /**\n * The user's own omp agent directory to seed from — its auth store\n * (`agent.db`) is linked in so a standalone session keeps the login the\n * developer already has, and its `config.yml` is read as base settings.\n * Sessions, history, `mcp.json` and extensions are not linked. Absent (the\n * platform case) seeds nothing. A missing directory is not an error: it is the platform case.\n */\n seedFrom?: string;\n /**\n * GitAgent identity directory (`AgentConfig.agentDir`) whose contents omp\n * reads out of the same base: `agent.yaml`, `SOUL.md`, `RULES.md`,\n * `knowledge/`. Linked in after the seed, so identity wins a name clash.\n */\n identityDir?: string;\n}\n\n/** What {@link materializeOmpAgentDir} wrote. */\nexport interface OmpAgentDirMaterialization extends OmpRegistryRender {\n /** The directory `PI_CODING_AGENT_DIR` must point at. */\n agentDir: string;\n /** The directory is the driver's temporary home: remove it when the run ends. */\n ephemeral?: boolean;\n /** Names linked in from {@link MaterializeOmpAgentDirOptions.seedFrom}. */\n seeded: string[];\n /** Names linked in from {@link MaterializeOmpAgentDirOptions.identityDir}. */\n identity: string[];\n}\n\n/** Inputs {@link planOmpAgentDir} derives the session directory layout from. */\nexport interface OmpAgentDirPlanInput {\n /** Session working directory. Distinguishes two default-named sessions. */\n cwd: string;\n /** Session id — the directory key, so concurrent sessions never collide. */\n sessionId?: string;\n /** `AgentConfig.driverOptions.omp`. */\n options?: OmpDriverOptions;\n /** Home the default seed source resolves against. Defaults to `os.homedir()`. */\n homeDir?: string;\n /** Root the private directory is created under. Defaults to `os.tmpdir()`. */\n tmpDir?: string;\n}\n\n/** Where a session's omp agent directory lives, and what it inherits. */\nexport interface OmpAgentDirPlan {\n /** Session-private directory `PI_CODING_AGENT_DIR` points at. */\n agentDir: string;\n /** User agent directory whose login is linked in, when there is one to inherit. */\n seedFrom?: string;\n /**\n * The directory is the driver's own temporary home, to be removed when the run ends. False\n * when the session named its own `driverOptions.omp.agentHome`, which belongs to the user.\n */\n ephemeral: boolean;\n}\n\n/**\n * Decide the session-private agent directory and whether it inherits the\n * developer's omp state.\n *\n * The directory is deliberately **outside `cwd`**. It holds omp's credential\n * store — a symlink to the developer's `agent.db` on a standalone machine —\n * and `cwd` is the one tree the agent has write access to by design; managed\n * codex draws the same line and rejects a private directory nested in the\n * workspace (`codex/instance-state.ts`). Sessions are keyed by id, falling\n * back to a digest of the workspace path. The temporary directory is `<key>-<random>`, created per\n * call, so no two runs share one (and one run's cleanup never removes another's).\n *\n * Seeding keys on the user directory *existing*, which is exactly the\n * platform/standalone distinction the plan draws: a platform container has no\n * `~/.omp/agent`, so the session correctly starts empty; a developer machine\n * has one, so the session keeps the logins already stored there.\n * `driverOptions.omp.seedUserAgentDir: false` forces the empty case anyway.\n */\nexport async function planOmpAgentDir(input: OmpAgentDirPlanInput): Promise<OmpAgentDirPlan> {\n const options = input.options;\n const key =\n input.sessionId?.trim() ||\n createHash(\"sha256\").update(path.resolve(input.cwd)).digest(\"hex\").slice(0, 16);\n const ephemeral = options?.agentHome === undefined;\n // The temporary home is unique per spawn: callers key sessions loosely (`skaile chat` passes\n // none, `serve` without --session-id uses one shared id, sub-prompt drivers share a hash), and\n // the driver deletes its home when its run ends, which must never reach a sibling's home.\n let agentDir = options?.agentHome ?? \"\";\n if (ephemeral) {\n const root = path.join(input.tmpDir ?? os.tmpdir(), \"skaile-omp-agent\");\n await fs.mkdir(root, { recursive: true });\n await sweepStaleOmpHomes(root);\n agentDir = await fs.mkdtemp(path.join(root, `${key.replace(/[^A-Za-z0-9._-]/g, \"_\")}-`));\n await fs.writeFile(path.join(agentDir, OWNER_FILE), String(process.pid));\n }\n if (options?.seedUserAgentDir === false) return { agentDir, ephemeral };\n\n const seedFrom =\n options?.userAgentDir ?? path.join(input.homeDir ?? os.homedir(), \".omp\", \"agent\");\n if (path.resolve(seedFrom) === path.resolve(agentDir)) return { agentDir, ephemeral };\n try {\n if (!(await fs.stat(seedFrom)).isDirectory()) return { agentDir, ephemeral };\n } catch {\n return { agentDir, ephemeral };\n }\n return { agentDir, seedFrom, ephemeral };\n}\n\n/** Names the process that created a temporary home; the sweep keeps a home whose owner lives. */\nconst OWNER_FILE = \".skaile-owner-pid\";\n/** A temporary home older than this whose owner is gone is removed at the next start. */\nconst STALE_HOME_MS = 24 * 60 * 60 * 1000;\n\nconst SKAILE_HOME_NAME = /^[A-Za-z0-9._-]+-[A-Za-z0-9]{6}$/;\n\nfunction processAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (err) {\n return (err as NodeJS.ErrnoException).code === \"EPERM\";\n }\n}\n\n/**\n * Remove temporary homes older than a day whose creating process is gone: a run that was killed\n * never reached the driver's own cleanup, and every one leaves symlinks and databases behind\n * (p811). A home of a live process is kept whatever its age. Best effort: a failure is ignored.\n */\nasync function sweepStaleOmpHomes(root: string, now = Date.now()): Promise<void> {\n let names: string[];\n try {\n names = await fs.readdir(root);\n } catch {\n return;\n }\n await Promise.all(\n names.map(async (name) => {\n const home = path.join(root, name);\n try {\n const stat = await fs.lstat(home);\n if (!stat.isDirectory() || now - stat.mtimeMs < STALE_HOME_MS) return;\n const owner = Number.parseInt(\n await fs.readFile(path.join(home, OWNER_FILE), \"utf8\").catch(() => \"\"),\n 10,\n );\n if (Number.isInteger(owner) && processAlive(owner)) return;\n // A home with no owner file is one an older version made: remove it only when its\n // name has the `<key>-<six random characters>` shape `mkdtemp` gives (never a folder\n // somebody else put in this directory).\n if (!Number.isInteger(owner) && !SKAILE_HOME_NAME.test(name)) return;\n await fs.rm(home, { recursive: true, force: true });\n } catch {\n /* another process may be sweeping the same home */\n }\n }),\n );\n}\n\n/**\n * Run the steps that fill a planned home; when one throws, remove a temporary home before\n * rethrowing. The driver only learns the home (and deletes it at cleanup) once these steps\n * return, so a failure here would otherwise leave a new directory per spawn behind.\n */\nasync function removeHomeOnThrow<T>(plan: OmpAgentDirPlan, fill: () => Promise<T>): Promise<T> {\n try {\n return await fill();\n } catch (err) {\n if (plan.ephemeral) await fs.rm(plan.agentDir, { recursive: true, force: true });\n throw err;\n }\n}\n\n/** Remove a path whatever it is, without following a symlink into its target. */\nasync function removeEntry(target: string): Promise<void> {\n let stat: Stats;\n try {\n stat = await fs.lstat(target);\n } catch {\n return;\n }\n if (stat.isSymbolicLink() || stat.isFile()) {\n await fs.unlink(target);\n return;\n }\n await fs.rm(target, { recursive: true, force: true });\n}\n\n/** Symlink every entry of `sourceDir` into `dir`, skipping the owned names. */\nasync function linkInto(\n dir: string,\n sourceDir: string,\n skip: Record<string, true>,\n): Promise<string[]> {\n let names: string[];\n try {\n names = await fs.readdir(sourceDir);\n } catch {\n return [];\n }\n const linked: string[] = [];\n for (const name of names) {\n if (skip[name]) continue;\n const target = path.join(dir, name);\n await removeEntry(target);\n await fs.symlink(path.join(sourceDir, name), target);\n linked.push(name);\n }\n return linked;\n}\n\n/**\n * Remove the symlinks into the user's agent directory that an older release (or a home the\n * session named itself) left in `dir`: only the login files may point there (p811).\n */\nasync function dropStaleSeedLinks(dir: string, sourceDir: string): Promise<void> {\n let names: string[];\n try {\n names = await fs.readdir(dir);\n } catch {\n return;\n }\n const root = path.resolve(sourceDir);\n for (const name of names) {\n if ((OMP_LOGIN_FILES as readonly string[]).includes(name)) continue;\n const entry = path.join(dir, name);\n try {\n if (!(await fs.lstat(entry)).isSymbolicLink()) continue;\n const to = path.resolve(dir, await fs.readlink(entry));\n if (to === root || to.startsWith(root + path.sep)) await fs.unlink(entry);\n } catch {\n // Gone or unreadable: nothing to drop.\n }\n }\n}\n\n/** Symlink the login files (see {@link OMP_LOGIN_FILES}) of the user's agent directory into `dir`. */\nasync function linkLoginFiles(dir: string, sourceDir: string): Promise<string[]> {\n await dropStaleSeedLinks(dir, sourceDir);\n const linked: string[] = [];\n for (const name of OMP_LOGIN_FILES) {\n const from = path.join(sourceDir, name);\n try {\n if (!(await fs.stat(from)).isFile()) continue;\n } catch {\n continue;\n }\n const target = path.join(dir, name);\n await removeEntry(target);\n await fs.symlink(from, target);\n linked.push(name);\n }\n return linked;\n}\n\n/** Read a seeded `config.yml` as the base settings, or `{}` when unusable. */\nasync function readSeededSettings(seedFrom: string): Promise<Record<string, unknown>> {\n for (const name of [\"config.yml\", \"config.yaml\"]) {\n let raw: string;\n try {\n raw = await fs.readFile(path.join(seedFrom, name), \"utf-8\");\n } catch {\n continue;\n }\n const parsed = parse(raw) as unknown;\n if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n return parsed as Record<string, unknown>;\n }\n }\n return {};\n}\n\n/**\n * Build the session-private agent directory and write omp's two files into it.\n *\n * The user's `~/.omp/agent/models.yml` and `config.yml` are never opened for\n * writing: `config.yml` is *copied* into the session (so a token refresh or a\n * settings write inside the session cannot reach back through a symlink),\n * `models.yml` is not seeded at all, and everything else — `agent.db*` above\n * all — is symlinked so the session shares the developer's logins and caches.\n */\nexport async function materializeOmpAgentDir(\n agentDir: string,\n registry: AIProviderRegistry | MergedAIProviderRegistry,\n options: MaterializeOmpAgentDirOptions = {},\n): Promise<OmpAgentDirMaterialization> {\n await fs.mkdir(agentDir, { recursive: true });\n\n const seeded = options.seedFrom ? await linkLoginFiles(agentDir, options.seedFrom) : [];\n const identity = options.identityDir\n ? await linkInto(agentDir, options.identityDir, OWNED_AGENT_DIR_FILES)\n : [];\n\n const baseSettings =\n options.baseSettings ??\n (options.seedFrom ? await readSeededSettings(options.seedFrom) : undefined);\n\n const render = renderOmpRegistry(registry, { ...options, baseSettings });\n\n await fs.writeFile(path.join(agentDir, OMP_MODELS_FILENAME), render.modelsYml, \"utf-8\");\n await fs.writeFile(path.join(agentDir, OMP_CONFIG_FILENAME), render.configYml, \"utf-8\");\n\n return { ...render, agentDir, seeded, identity };\n}\n\n/** What the omp driver gets back from {@link materializeOmpProviders}. */\nexport interface OmpProviderMaterialization extends OmpAgentDirMaterialization {\n /**\n * The `--model` argument for this session: `<providerId>/<providerModelId>`,\n * the one selector form omp treats as unambiguous when several providers\n * carry the same model id. Absent when the session named no model.\n */\n modelArg?: string;\n}\n\n/**\n * The whole omp adapter for one session: decide the private agent directory,\n * inherit the developer's omp state where there is any, write `models.yml` and\n * `config.yml`, and report the credential environment and `--model` selector\n * the child needs.\n *\n * Returns `undefined` when the session carries no registry with a selectable\n * entry — the driver then behaves exactly as it did before the registry\n * existed, which is what keeps this an expand-and-contract change.\n *\n * Also returns `undefined` when no entry can be handed to omp (every\n * credential unresolved) or when the entry the session's model selects was\n * left out: a session-private agent directory would then start omp without the\n * user's own settings, and a model that only the user's own omp login can\n * serve would fail with `No API key found` although native omp answers. The\n * driver then starts omp on the user's agent directory, so \"omp falls back to\n * its own login\" is true.\n *\n * `env:` references resolve against the runner's environment *overlaid with*\n * `config.env`, so a credential the session boundary already resolved (a\n * `platform:` secret it turned into an env var, for instance) is found here\n * under the name the registry entry points at.\n */\nexport async function materializeOmpProviders(\n config: AgentConfig,\n): Promise<OmpProviderMaterialization | undefined> {\n const registry = config.registry;\n if (!registry) return undefined;\n const selectable = registryEntries(registry).some(\n ([, entry]) => (entry.kind === \"llm\" || entry.kind === \"embed\") && isEntryEnabled(entry),\n );\n if (!selectable) return undefined;\n\n const env = { ...process.env, ...config.env };\n const selected = config.modelRef\n ? parseModelRef(config.modelRef, registry, config.roles)\n : undefined;\n const usable = renderOmpRegistry(registry, {\n env,\n ...(config.roles ? { roles: config.roles } : {}),\n ...(config.modelRef ? { modelRef: config.modelRef } : {}),\n }).providerIds;\n if (usable.length === 0) return undefined;\n if (selected && !usable.includes(selected.providerId)) return undefined;\n\n const plan = await planOmpAgentDir({\n cwd: config.cwd,\n ...(config.sessionId ? { sessionId: config.sessionId } : {}),\n ...(config.driverOptions?.omp ? { options: config.driverOptions.omp } : {}),\n });\n\n const rendered = await removeHomeOnThrow(plan, () =>\n materializeOmpAgentDir(plan.agentDir, registry, {\n env,\n ...(plan.seedFrom ? { seedFrom: plan.seedFrom } : {}),\n ...(config.agentDir ? { identityDir: config.agentDir } : {}),\n ...(config.roles ? { roles: config.roles } : {}),\n ...(config.modelRef ? { modelRef: config.modelRef } : {}),\n }),\n );\n\n return {\n ...rendered,\n ephemeral: plan.ephemeral,\n ...(selected?.providerModelId\n ? { modelArg: `${selected.providerId}/${selected.providerModelId}` }\n : {}),\n };\n}\n\n/** What {@link materializeOmpIdentityDir} wrote. */\nexport interface OmpIdentityDirMaterialization {\n /** The directory `PI_CODING_AGENT_DIR` must point at. */\n agentDir: string;\n /** The directory is the driver's temporary home: remove it when the run ends. */\n ephemeral: boolean;\n /** Names linked in from the user's own omp agent directory. */\n seeded: string[];\n /** Names linked in from `AgentConfig.agentDir`. */\n identity: string[];\n}\n\n/**\n * The omp home of a session that has an agent directory but no provider registry.\n *\n * omp keeps its runtime state (`agent.db`, `models.db`, `skill-descriptions.db`, session\n * scratch, `intercom/`) in `PI_CODING_AGENT_DIR`. Pointing that at the agent directory itself\n * put those files beside `SOUL.md` in a pinned, shared source (`.skaile/cache/agents/<name>/`)\n * and made omp name a path inside the cache when it lacks a credential. So the home is a\n * private directory outside `cwd` (see {@link planOmpAgentDir}): the developer's own omp state\n * is linked in (their login keeps working), their `config.yml` / `models.yml` are copied (a\n * settings write cannot reach back), and the agent directory's entries are linked in last,\n * so the agent files stay where they are and omp can still read them.\n *\n * Returns `undefined` when the session has no `agentDir`.\n */\nexport async function materializeOmpIdentityDir(\n config: AgentConfig,\n): Promise<OmpIdentityDirMaterialization | undefined> {\n const identityDir = config.agentDir;\n if (!identityDir) return undefined;\n // Keyed by the agent and the workspace too: two role children of one session, each with\n // its own agent directory, must not link their entries into one home.\n const agentKey = createHash(\"sha256\")\n .update(`${path.resolve(identityDir)}\\0${path.resolve(config.cwd)}`)\n .digest(\"hex\")\n .slice(0, 12);\n const plan = await planOmpAgentDir({\n cwd: config.cwd,\n sessionId: `${config.sessionId?.trim() || \"agent\"}-${agentKey}`,\n ...(config.driverOptions?.omp ? { options: config.driverOptions.omp } : {}),\n });\n return removeHomeOnThrow(plan, async () => {\n await fs.mkdir(plan.agentDir, { recursive: true });\n const seeded = plan.seedFrom ? await linkLoginFiles(plan.agentDir, plan.seedFrom) : [];\n if (plan.seedFrom) {\n for (const name of Object.keys(OWNED_AGENT_DIR_FILES)) {\n const from = path.join(plan.seedFrom, name);\n try {\n if (!(await fs.stat(from)).isFile()) continue;\n } catch {\n continue;\n }\n const to = path.join(plan.agentDir, name);\n await removeEntry(to);\n await fs.copyFile(from, to);\n }\n }\n const identity = await linkInto(plan.agentDir, identityDir, {\n ...OWNED_AGENT_DIR_FILES,\n ...OMP_RUNTIME_ENTRIES,\n });\n return { agentDir: plan.agentDir, ephemeral: plan.ephemeral, seeded, identity };\n });\n}\n","import { type ChildProcess, spawn } from \"node:child_process\";\nimport { randomUUID } from \"node:crypto\";\nimport type { EventEmitter } from \"node:events\";\nimport { rmSync } from \"node:fs\";\nimport fs from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { createInterface, type Interface } from \"node:readline\";\nimport type { DriverTarget } from \"@skaile/workspaces/plugin-registry\";\nimport {\n type DriverContextReport,\n type Logger,\n type TokenUsage,\n withActivityLabelJsonSchema,\n} from \"@skaile/workspaces/types\";\nimport * as z from \"zod\";\nimport { dispatchCapability } from \"../capability-dispatch.js\";\nimport { classifyGenericErrorMessage } from \"../error-classifier.js\";\nimport { getBridgeLogger } from \"../logger.js\";\nimport { checkToolInputSchema } from \"../mcp-tool-schema-filter.js\";\nimport type { ModelEntry } from \"../models.js\";\nimport { registryDriverConfig } from \"../provider-registry-derive.js\";\nimport {\n type ReconfigureApplyResult,\n ReconfigureLedger,\n type ReconfigurePushContext,\n type ReconfigureSnapshot,\n} from \"../reconfigure-ledger.js\";\nimport { BUILTIN_DRIVER_CATALOG } from \"../registry.js\";\nimport { resolveAgentExec, wrapAgentCommand } from \"../agent-exec.js\";\nimport { stripRunnerPrivateEnv } from \"../runner-private-env.js\";\nimport {\n type AgentConfig,\n AgentDriver,\n type AgentError,\n type AgentPromptInput,\n type BridgeCapabilityTool,\n type DriverInfo,\n type ReconfigureApplied,\n type ReconfigureOutcome,\n type ReconfigurePatch,\n type SlashCommandInfo,\n TOOL_ALLOWLIST_UNSUPPORTED,\n} from \"../types.js\";\nimport {\n materializeOmpIdentityDir,\n materializeOmpProviders,\n registryModelEntries,\n} from \"./omp-models-yml.js\";\n\n/**\n * omp's own `No API key found for <provider>` text ends with `or create <home>/agent.db`:\n * the home is the session's private directory, a path nobody logs in at. Say what a user\n * can do instead: add the provider to the registry, or log in once with `omp`.\n * Any other message is returned as it came.\n */\nexport function ompCredentialMessage(msg: string): string {\n const match = /^(?:Error:\\s*)?No API key found for ([A-Za-z0-9._-]+?)\\.?(?:\\s|$)/.exec(msg);\n if (!match) return msg;\n const provider = match[1];\n const envName = `${provider.toUpperCase().replace(/[^A-Z0-9]/g, \"_\")}_API_KEY`;\n return (\n `No API key found for ${provider}. Add the provider with ` +\n `\\`skaile providers add ${provider} --credential env:${envName}\\`, ` +\n \"or log in once with `omp` (type /login).\"\n );\n}\n\n/**\n * Process-level vars omp needs to run at all, independent of any provider.\n */\nconst OMP_BASE_ENV_KEYS = [\"PATH\", \"HOME\", \"USER\", \"HOSTNAME\", \"SKAILE_SESSION_ID\"] as const;\n\n/**\n * Build the explicit env allowlist forwarded to the omp child process.\n *\n * The runner's full environment is never inherited — only\n * {@link OMP_BASE_ENV_KEYS} (process essentials) and the `PI_*` prefix (omp's\n * own app config the host operator may have set).\n *\n * **Credentials are not on this list.** Every endpoint omp may address is a\n * registry entry, serialized into the session's own `models.yml` with its\n * credential named as `SKAILE_AIP_<ID>_KEY` and the value assigned after this\n * allowlist is built (`./omp-models-yml.ts`). An ambient `ANTHROPIC_API_KEY`\n * in the runner's shell is not a session's statement of intent and does not\n * reach the child; `skaile providers add anthropic --preset anthropic\n * --credential env:ANTHROPIC_API_KEY` is.\n *\n * Test seams (`OMP_BRIDGE_*`, `FAKE_OMP_*`) are passed through so the\n * subprocess harness in `tests/omp-driver.test.ts` can drive a fake-omp\n * script via env-driven mode flags.\n *\n * @docLink packages/bridge/concepts#omp-env-whitelist\n */\nexport function buildOmpChildEnv(parent: NodeJS.ProcessEnv): Record<string, string> {\n const out: Record<string, string> = {};\n for (const key of OMP_BASE_ENV_KEYS) {\n const v = parent[key];\n if (typeof v === \"string\") out[key] = v;\n }\n for (const [key, value] of Object.entries(parent)) {\n if (typeof value !== \"string\") continue;\n if (key.startsWith(\"PI_\") || key.startsWith(\"OMP_BRIDGE_\") || key.startsWith(\"FAKE_OMP_\")) {\n out[key] = value;\n }\n }\n return out;\n}\n\n/**\n * omp's built-in tools, as reported by `omp --help` (\"Available Tools\").\n *\n * `computer` is the one entry omp does not enable by default; everything else\n * is on unless `--tools` narrows the set. Used to turn a manifest *deny* list\n * into the *allow* list omp's CLI actually accepts.\n */\nexport const OMP_BUILTIN_TOOLS = [\n \"read\",\n \"bash\",\n \"edit\",\n \"write\",\n \"grep\",\n \"glob\",\n \"lsp\",\n \"python\",\n \"notebook\",\n \"browser\",\n \"computer\",\n \"task\",\n \"todo\",\n \"web_search\",\n \"ask\",\n] as const;\n\n/** omp's default-enabled toolset — every built-in except `computer`. */\nexport const OMP_DEFAULT_TOOLS: readonly string[] = OMP_BUILTIN_TOOLS.filter(\n (t) => t !== \"computer\",\n);\n\n/**\n * Canonical (Claude Code) tool name → omp built-in tool name.\n *\n * Agent manifests are authored once in the canonical vocabulary and run on\n * whichever harness the workspace is configured for, so the driver owns the\n * translation. Names already in omp's own spelling pass through unchanged.\n *\n * Deliberately partial: Claude tools with no omp counterpart (`WebFetch`,\n * `BashOutput`, `KillShell`, `mcp__*` server tools) are absent and get dropped\n * from the omp `--tools` value — omp's `--tools` governs built-ins only, so\n * naming a non-built-in there would be rejected, and silently keeping it would\n * not restrict anything.\n */\nconst CANONICAL_TO_OMP_TOOL: Record<string, string> = {\n read: \"read\",\n write: \"write\",\n edit: \"edit\",\n multiedit: \"edit\",\n notebookedit: \"notebook\",\n bash: \"bash\",\n grep: \"grep\",\n glob: \"glob\",\n ls: \"glob\",\n task: \"task\",\n agent: \"task\",\n todowrite: \"todo\",\n todoread: \"todo\",\n websearch: \"web_search\",\n web_search: \"web_search\",\n notebook: \"notebook\",\n lsp: \"lsp\",\n python: \"python\",\n browser: \"browser\",\n computer: \"computer\",\n todo: \"todo\",\n ask: \"ask\",\n askuserquestion: \"ask\",\n};\n\n/**\n * Translate a manifest tool list into omp built-in tool names.\n *\n * Unknown names are dropped rather than passed through: a manifest is expected\n * to run on more than one harness, so it legitimately names tools this one has\n * never heard of.\n */\nfunction toOmpToolNames(names: readonly string[] | undefined): string[] {\n const out: string[] = [];\n for (const raw of names ?? []) {\n const mapped = CANONICAL_TO_OMP_TOOL[raw.trim().toLowerCase().replace(/[\\s-]/g, \"\")];\n if (mapped && !out.includes(mapped)) out.push(mapped);\n }\n return out;\n}\n\n/**\n * Resolve `AgentConfig.tools` into the omp CLI flags that enforce it.\n *\n * omp expresses tool restriction as a positive `--tools a,b,c` list (or\n * `--no-tools`) — there is no deny flag — so a manifest deny list is applied by\n * subtracting from {@link OMP_DEFAULT_TOOLS}.\n *\n * Returns `[]` when the manifest declares no restriction, which leaves omp on\n * its full default toolset exactly as before. That default toolset is the bulk\n * of every request's fixed token prefix, so this is the lever an agent\n * definition needs in order to shrink it.\n *\n * Pure — exported for direct testing.\n *\n * @since 1.5.0\n */\nexport function buildOmpToolArgs(tools: AgentConfig[\"tools\"]): string[] {\n const allowed = toOmpToolNames(tools?.allowed);\n const denied = new Set(toOmpToolNames(tools?.denied));\n\n const declaredAllow = (tools?.allowed?.length ?? 0) > 0;\n const declaredDeny = (tools?.denied?.length ?? 0) > 0;\n if (!declaredAllow && !declaredDeny) return [];\n\n const base = declaredAllow ? allowed : [...OMP_DEFAULT_TOOLS];\n const effective = base.filter((t) => !denied.has(t));\n\n // An allow list that named only tools omp does not have, or a deny list that\n // removed everything, both mean \"no tools\" — say so explicitly rather than\n // emitting `--tools ` and letting omp fall back to the full default set.\n if (effective.length === 0) return [\"--no-tools\"];\n return [\"--tools\", effective.join(\",\")];\n}\n\n/**\n * Longest host tool name handed to omp. omp forwards host tool names to the\n * provider verbatim; Anthropic allows 128 characters, OpenAI-compatible\n * endpoints 64, so the stricter bound keeps every provider working.\n */\nconst OMP_HOST_TOOL_NAME_MAX = 64;\n\n/** One `set_host_tools` entry (`omp://rpc.md`, \"set_host_tools payload\"). */\nexport interface OmpHostToolDefinition {\n name: string;\n label: string;\n description: string;\n parameters: Record<string, unknown>;\n loadMode: \"essential\";\n}\n\n/** Result of {@link buildOmpHostTools}. */\nexport interface OmpHostToolSet {\n /** Definitions to send in `set_host_tools`. */\n definitions: OmpHostToolDefinition[];\n /** omp host tool name → capability name, for routing `host_tool_call`. */\n capabilityNames: Map<string, string>;\n /** Capabilities left out because the provider would reject their schema. */\n dropped: Array<{ tool: string; reason: string }>;\n}\n\n/**\n * Turn the runner's capability tool list into omp host tool definitions.\n *\n * omp accepts any name in `set_host_tools` but forwards it to the provider\n * as-is, and providers reject anything outside `^[a-zA-Z0-9_-]{1,64}$` with a\n * 400 that fails the whole turn (verified against omp 18.6.0 + Anthropic:\n * `app.editor.open` → `tools.3.custom.name: String should match pattern`).\n * Names are therefore sanitised (`app.editor.open` → `app_editor_open`) and\n * the original kept in `capabilityNames`. Collisions — with another\n * capability or with an omp built-in, which omp refuses — get a numeric\n * suffix.\n *\n * omp also forwards the JSON Schema untouched, so each advertised schema is\n * checked with the same rules the claude-sdk driver applies to raw MCP\n * schemas ({@link checkToolInputSchema}); a failing tool is dropped rather\n * than turning every request into a 400. `loadMode: \"essential\"` keeps every\n * capability in the prompt instead of behind omp's tool discovery, matching\n * claude-sdk where every capability is in the tool list.\n *\n * Pure — exported for direct testing.\n */\nexport function buildOmpHostTools(tools: readonly BridgeCapabilityTool[]): OmpHostToolSet {\n const taken = new Set<string>(OMP_BUILTIN_TOOLS);\n const out: OmpHostToolSet = { definitions: [], capabilityNames: new Map(), dropped: [] };\n for (const tool of tools) {\n // Advertise-only label, as in claude-sdk and codex; `dispatchCapability`\n // strips it before the registry sees the input.\n const parameters = { ...withActivityLabelJsonSchema(tool.parameters), type: \"object\" };\n const reason = checkToolInputSchema(parameters);\n if (reason) {\n out.dropped.push({ tool: tool.name, reason });\n continue;\n }\n const base =\n tool.name.replace(/[^a-zA-Z0-9_-]/g, \"_\").slice(0, OMP_HOST_TOOL_NAME_MAX) || \"capability\";\n let name = base;\n for (let n = 2; taken.has(name); n++) {\n const suffix = `_${n}`;\n name = `${base.slice(0, OMP_HOST_TOOL_NAME_MAX - suffix.length)}${suffix}`;\n }\n taken.add(name);\n out.capabilityNames.set(name, tool.name);\n out.definitions.push({\n name,\n label: tool.name,\n description: tool.description,\n parameters,\n loadMode: \"essential\",\n });\n }\n return out;\n}\n\n/** Thinking levels omp accepts for `--thinking` / `set_thinking_level`. omp drops anything else silently. */\nexport const OMP_THINKING_LEVELS = [\n \"off\",\n \"minimal\",\n \"low\",\n \"medium\",\n \"high\",\n \"xhigh\",\n \"max\",\n \"auto\",\n] as const;\nexport type OmpThinkingLevel = (typeof OMP_THINKING_LEVELS)[number];\n\n/** Largest image attachment omp will be sent (Anthropic's 5 MB per-image limit). */\nconst OMP_MAX_IMAGE_BYTES = 5 * 1024 * 1024;\n\n/**\n * Map `AgentConfig.thinking` / `effort` to an omp thinking level.\n *\n * `disabled` wins over `effort` → `off`. Otherwise an explicit `effort`\n * (low/medium/high/xhigh/max) maps to the same-named level (omp clamps `max` to\n * `xhigh` on models without it). Without effort, `enabled` → `medium` and\n * `adaptive` → `auto`. Returns `undefined` when neither is set (omp keeps its\n * own default) or when the value is outside omp's set — `set_thinking_level`\n * accepts garbage without an error, so validation has to happen here.\n */\nexport function ompThinkingLevel(\n cfg: Pick<AgentConfig, \"thinking\" | \"effort\">,\n): OmpThinkingLevel | undefined {\n const level = (() => {\n if (cfg.thinking === \"disabled\") return \"off\";\n if (cfg.effort) return cfg.effort;\n if (cfg.thinking === \"enabled\") return \"medium\";\n if (cfg.thinking === \"adaptive\") return \"auto\";\n return undefined;\n })();\n return level !== undefined && (OMP_THINKING_LEVELS as readonly string[]).includes(level)\n ? (level as OmpThinkingLevel)\n : undefined;\n}\n\n/**\n * Split a model selector into the `provider` / `modelId` pair `set_model`\n * takes. The registry renders selectors as `<providerId>/<providerModelId>`\n * (the spawn-time `--model` value); provider ids never contain `/` but model\n * ids can, so the split is on the FIRST `/`:\n * `openrouter/anthropic/claude-sonnet-4` → `{ provider: \"openrouter\", modelId: \"anthropic/claude-sonnet-4\" }`.\n * A bare name (no `provider/` prefix) cannot be expressed: omp's `--model`\n * fuzzy matching has no RPC equivalent, so the result is `undefined`.\n */\nexport function splitOmpModel(model: string): { provider: string; modelId: string } | undefined {\n const slash = model.indexOf(\"/\");\n if (slash > 0 && slash < model.length - 1) {\n return { provider: model.slice(0, slash), modelId: model.slice(slash + 1) };\n }\n return undefined;\n}\n\ninterface OmpEvent {\n type: string;\n data?: unknown;\n id?: string;\n success?: boolean;\n error?: string;\n message?: OmpMessage;\n [key: string]: unknown;\n}\n\ninterface OmpMessage {\n role?: string;\n content?: string | OmpContentBlock[];\n /**\n * Why the turn stopped. omp reports a failed request as a normal\n * `message_end` carrying `stopReason: \"error\"` rather than as an `error`\n * event, so this is the only signal that the turn failed.\n */\n stopReason?: string;\n /** Provider/transport error text accompanying `stopReason: \"error\"`. */\n errorMessage?: string;\n /** Final usage of this model call; running partials on `message_start`/updates are ignored. */\n usage?: OmpUsage;\n}\n\n/** Token counters on an assistant `message_end`; every field is optional and unvalidated. */\ninterface OmpUsage {\n input?: unknown;\n output?: unknown;\n cacheRead?: unknown;\n cacheWrite?: unknown;\n reasoningTokens?: unknown;\n totalTokens?: unknown;\n}\n\n/** omp RPC `ImageContent`: raw base64 (no `data:` prefix) plus its MIME type. */\ninterface OmpImageContent {\n type: \"image\";\n data: string;\n mimeType: string;\n}\n\ninterface OmpContentBlock {\n type: string;\n text?: string;\n id?: string;\n name?: string;\n input?: unknown;\n thinking?: string;\n}\n\n/**\n * A question omp is parked on: the `extension_ui_request` the host still owes\n * an `extension_ui_response` for. One request can carry several questions;\n * the response goes out once every one has an answer.\n */\ninterface OmpPendingQuestion {\n /** Id of the `extension_ui_request`; the response must echo it. */\n id: string;\n /** `ask` answers with `answers[]`; the `select` fallback answers with `value`. */\n method: \"ask\" | \"select\";\n questions: Array<{ id: string; question: string; options: string[]; multi: boolean }>;\n /** The user's answer per question, by position; `undefined` while unanswered. */\n answers: Array<string | undefined>;\n}\n\n/** What the running omp process holds, for the reconfigure ledger. */\ninterface OmpApplied extends ReconfigureSnapshot {\n /** The omp thinking level last sent (or spawned with). */\n level?: OmpThinkingLevel;\n}\n\n/**\n * The line of omp's stderr that says why it gave up. omp prints an unrelated\n * warning first (a failed extension load) and the real cause last (`No default\n * model selected. Use /login ...`), so the cause is the last line that reads as\n * an error, else the last line. Escape sequences are stripped.\n */\nexport function ompStartFailureCause(lines: readonly string[]): string {\n const clean = lines\n // biome-ignore lint/suspicious/noControlCharactersInRegex: strips ANSI escapes\n .map((l) => l.replace(/\\u001b\\[[0-9;]*m/g, \"\").trim())\n .filter(Boolean);\n const isCause = (l: string) =>\n /\\b(error|no default model|not (?:found|installed|logged)|invalid|unauthori[sz]ed|cannot|can't|failed)\\b/i.test(\n l,\n ) && !/failed to load extension/i.test(l);\n for (let i = clean.length - 1; i >= 0; i--) {\n if (isCause(clean[i] as string)) return clean[i] as string;\n }\n return clean.at(-1) ?? \"\";\n}\n\n/**\n * Agent driver for the oh-my-pi (omp) coding agent.\n *\n * Spawns `omp --mode rpc-ui --no-ui` as a child process and communicates via newline-delimited\n * JSON-RPC over stdin/stdout. Model-agnostic: supports any LLM provider.\n *\n * @see https://github.com/can1357/oh-my-pi\n *\n * @remarks\n * **Session persistence** — omp writes JSONL session files to `<cwd>/.omp/sessions/`\n * (via `--session-dir`). After each turn (`agent_end`), sends a `get_state` RPC to\n * capture the native session ID and emits a `session_info` event so the forge layer\n * can persist it. On the next spawn, callers pass `resumeSessionId` to restore omp's\n * native context.\n *\n * **stderrBuffer** — collects the last 20 lines of stderr so they can be appended to\n * crash error messages for diagnostics without blocking the stdout readline loop.\n *\n * **systemPrompt injection** — omp does not accept a system prompt string directly.\n * The driver writes `AgentConfig.systemPrompt` to a file of its own under\n * `<cwd>/.skaile/cache/omp-system/`, passes the path via `--append-system-prompt` and deletes\n * the file when the process ends.\n *\n * **agentDir** — omp's home (`PI_CODING_AGENT_DIR`) is a private directory outside `cwd`\n * that links in the entries of the GitAgent directory (agent.yaml, RULES.md, knowledge/), so\n * omp's runtime databases never land beside the pinned agent files. omp reads no SOUL.md:\n * the runner puts the soul into `systemPrompt`.\n *\n * **Capabilities** — `AgentConfig.capabilities` (Protocol v2) is registered with omp\n * as host tools (`set_host_tools`) once the process is ready, and again whenever the\n * registry reports a change. omp calls them back with `host_tool_call`, answered via\n * `dispatchCapability` exactly as claude-sdk's `skaile-capabilities` MCP server does.\n * Names are sanitised for the provider; see {@link buildOmpHostTools}.\n *\n * **Questions** — omp's `ask` tool is enabled as one `extension_ui_request` dialog\n * (`set_ask_dialog`), published as the same `question` events as claude-sdk's\n * `AskUserQuestion` and answered through {@link OmpDriver.answerQuestion}. The turn stays\n * parked in omp until then; abort, kill and process exit release it. Dialogs the host\n * cannot answer (`confirm`, `input`, `editor`) are cancelled immediately.\n *\n * @docLink packages/bridge/drivers#omp-driver\n */\nexport class OmpDriver extends AgentDriver {\n readonly driverInfo: DriverInfo = {\n id: \"omp\",\n name: \"omp (oh-my-pi)\",\n modelAgnostic: true,\n supportsInBandAbort: true,\n capabilities: BUILTIN_DRIVER_CATALOG.omp?.capabilities,\n };\n\n private readonly log: Logger = getBridgeLogger(\"omp\");\n private proc: ChildProcess | null = null;\n private rl: Interface | null = null;\n private reqId = 0;\n private config: AgentConfig;\n private ready = false;\n private startPromise: Promise<void> | null = null;\n private stderrBuffer: string[] = [];\n private prevText = \"\";\n /** OMP session ID captured via `get_state` after each turn. */\n private _ompSessionId?: string;\n /**\n * Usage of the most recent turn, summed over every model call in it (a tool\n * loop is one prompt but many assistant messages). Cleared when a turn\n * starts, like claude-sdk, so it never mixes two turns.\n */\n private _lastTokens: TokenUsage | null = null;\n /**\n * Prompt size of the most recent model call: the real context fill, which\n * `_lastTokens` (turn-cumulative) overstates on a tool loop. omp's own\n * `get_state.contextUsage.tokens` replaces it once that reply lands.\n */\n private _lastContextTokens: number | null = null;\n /** Context window of the active model, from `get_state.contextUsage`. */\n private _contextWindow: number | null = null;\n /** Per-spawn file holding the system prompt omp was started with; removed with the process. */\n private systemPromptFile: string | null = null;\n /** The private omp home of the running process, when it is the driver's own temporary one. */\n private privateHome: string | null = null;\n\n override getTokenUsage(): TokenUsage | null {\n return this._lastTokens;\n }\n\n override getContextTokens(): number | null {\n return this._lastContextTokens;\n }\n\n override getContextWindow(): number | null {\n return this._contextWindow;\n }\n\n /**\n * omp reports only its fill and window (`get_state.contextUsage`), refreshed\n * here so a request between turns is current. A local RPC, so cheap. Unlike\n * `captureState` it throws on a failed reply: a stale fill must never be\n * reported as a fresh measurement.\n */\n override async getContextUsageReport(): Promise<DriverContextReport | null> {\n if (!this.proc) return null;\n const response = await this.request({ type: \"get_state\" }, { quiet: true });\n if (!response.success) {\n throw new Error(`omp get_state failed: ${response.error ?? \"no error given\"}`);\n }\n this.captureContextUsage((response.data as Record<string, unknown> | undefined)?.contextUsage);\n if (this._lastContextTokens === null && this._contextWindow === null) return null;\n return { usedTokens: this._lastContextTokens, contextWindow: this._contextWindow };\n }\n\n /** Per-turn settlement handlers; non-null only while a prompt is in flight. */\n private turnResolve: (() => void) | null = null;\n private turnReject: ((err: Error) => void) | null = null;\n /** omp host tool name → capability name for the last `set_host_tools` sent. */\n private hostToolCapabilities = new Map<string, string>();\n /** In-flight `host_tool_call`s by omp request id; aborted by `host_tool_cancel`. */\n private readonly hostToolCalls = new Map<string, { controller: AbortController; name: string }>();\n /** Requests awaiting a `response`, by request id; failed when the process goes away. */\n private readonly pendingRequests = new Map<string, (err: Error) => void>();\n /** Unsubscribes the capability registry listener; set while a process runs. */\n private unsubscribeToolsChanged: (() => void) | null = null;\n /** Request ids whose failed `response` is logged by the caller, not surfaced as an error event. */\n private readonly quietRequestIds = new Set<string>();\n /** Capability tools already warned about, so a re-send logs each once. */\n private readonly warnedDroppedHostTools = new Set<string>();\n /** The `ask` (or `select` fallback) omp is parked on, until answered, cancelled or the process ends. */\n private pendingQuestion: OmpPendingQuestion | null = null;\n /**\n * Tail of the FIFO of prompts: each `prompt()`/`promptInput()` runs only after\n * the previous one settled, so one turn at a time is ever in flight (omp runs\n * a single agent loop). Never rejects.\n */\n private promptTail: Promise<void> = Promise.resolve();\n /** `true` while `agent_end` is being delivered to listeners. */\n private turnEnded = false;\n\n override get runtimeSessionId(): string | undefined {\n return this._ompSessionId;\n }\n\n /** Slash commands from omp's last `available_commands_update`. */\n private cachedCommands: SlashCommandInfo[] = [];\n\n override getSlashCommands(): SlashCommandInfo[] {\n return this.cachedCommands;\n }\n\n override getModel(): string | undefined {\n return this.config.model;\n }\n\n /**\n * Owns the desired config, drift and ordering of live reconfigures. Its\n * snapshot is what the running omp process was last told: the config values\n * `model`, `modelRef`, `thinking` and `effort` came from (the rollback targets\n * when omp refuses a change) and the omp thinking `level` sent. Set at spawn,\n * updated on each successful `set_*`.\n */\n private readonly reconfig: ReconfigureLedger<OmpApplied>;\n\n /**\n * Apply `model` / `thinking` / `effort`: the {@link ReconfigureLedger} writes\n * the desired config and, when the process is up and idle, pushes it through\n * {@link applyLive} (`set_model` / `set_thinking_level`), answering from omp's\n * reply. A patch that arrives mid-turn or before `ready` is not lost: config is\n * the source of truth, flushed before the next `prompt()` and read by the next\n * spawn. A refusal (omp's, or a model `set_model` cannot express live: no\n * `provider/` prefix) rolls the config back and answers `rejected`. In registry\n * mode the patch also replaces `modelRef`, so a respawn (crash, `resetSession()`)\n * starts the reconfigured model; models.yml already lists every enabled provider.\n */\n override reconfigure(patch: ReconfigurePatch): Promise<ReconfigureOutcome> {\n return this.reconfig.reconfigure(patch);\n }\n\n /** Push drifted model / thinking settings to the running process. Never rejects. */\n private async applyLive(\n delta: ReconfigureApplied,\n applied: OmpApplied,\n { late }: ReconfigurePushContext,\n ): Promise<ReconfigureApplyResult> {\n if (delta.model !== undefined) {\n const target = splitOmpModel(delta.model);\n if (!target) {\n // `set_model` cannot express a bare name, so the running process keeps\n // its model: refuse rather than report one omp is not running.\n const message = `set_model cannot apply \"${delta.model}\" live (no provider/ prefix); model unchanged`;\n this.log.warn(\"model has no provider prefix; set_model cannot apply it live\", {\n model: delta.model,\n });\n if (!late) this.emit(\"agent-event\", { type: \"error\", error: message });\n return { rejected: message };\n }\n const refusal = await this.sendReconfigure({ type: \"set_model\", ...target }, late);\n if (refusal !== null) return { rejected: refusal };\n applied.model = delta.model;\n applied.modelRef = delta.modelRef ?? applied.modelRef;\n }\n\n if (delta.thinking !== undefined || delta.effort !== undefined) {\n const level = ompThinkingLevel(this.config);\n if (level !== undefined && level !== applied.level) {\n const refusal = await this.sendReconfigure({ type: \"set_thinking_level\", level }, late);\n if (refusal !== null) return { rejected: refusal };\n applied.level = level;\n }\n }\n return \"applied\";\n }\n\n /**\n * Send one live-reconfigure request. A failed `response` is emitted as an\n * `error` event by {@link handleEvent}, and a transport failure (timeout,\n * process gone) here, unless `late`: a refusal of a patch already answered\n * `ok` reaches the host as `reconfigure_rejected`, so it gets no `error`\n * event as well. Returns `null` when omp accepted it, else why not.\n */\n private async sendReconfigure(\n msg: { type: string; [key: string]: unknown },\n late: boolean,\n ): Promise<string | null> {\n try {\n const resp = await this.request(msg, { quiet: late });\n if (resp.success) return null;\n this.log.warn(\"omp rejected reconfigure\", { type: msg.type, error: resp.error });\n return typeof resp.error === \"string\" ? resp.error : `omp refused ${msg.type}`;\n } catch (err) {\n const error = err instanceof Error ? err.message : String(err);\n this.log.warn(\"reconfigure request failed\", { type: msg.type, error });\n if (!late) {\n this.emit(\"agent-event\", { type: \"error\", error: `${msg.type} failed: ${error}` });\n }\n return `${msg.type} failed: ${error}`;\n }\n }\n\n /**\n * @param config - Driver configuration. omp-relevant fields:\n * - `cwd` — working directory; omp session files are stored under `<cwd>/.omp/sessions/`.\n * - `model` — forwarded as `--model <selector>`. In registry mode `modelRef` takes precedence at spawn; `reconfigure({ model })` keeps both in step.\n * - `systemPrompt` — written to a per-spawn file under `<cwd>/.skaile/cache/omp-system/` and appended via `--append-system-prompt`.\n * - `agentDir` — its entries are linked into omp's private home (`PI_CODING_AGENT_DIR`); the directory itself is never omp's home.\n * - `sshKeyPath` — injected as `GIT_SSH_COMMAND` for authenticated git operations.\n * - `resumeSessionId` — omp session UUID to restore via `--session <id>`.\n */\n constructor(config: AgentConfig) {\n super();\n this.config = config;\n this.reconfig = new ReconfigureLedger<OmpApplied>({\n config: () => this.config,\n isLive: () => this.proc !== null && this.ready,\n isIdle: () => !this.turnResolve,\n applyLive: (delta, applied, context) => this.applyLive(delta, applied, context),\n onLateRejection: (rollback) => this.emit(\"reconfigure-rollback\", rollback),\n log: this.log,\n });\n }\n\n public async start(): Promise<void> {\n // In-flight start first: `proc` is set before `ready` and before the host\n // tools are registered, and callers must not prompt ahead of either.\n if (this.startPromise) return this.startPromise;\n if (this.proc) return;\n // A start that fails before omp is running (home or env setup, a spawn error) must not\n // leave the per-spawn system prompt file behind.\n this.startPromise = this._start().catch((err: unknown) => {\n this.removeSystemPromptFile();\n this.removePrivateHome();\n throw err;\n });\n return this.startPromise;\n }\n\n private async _start(): Promise<void> {\n // `rpc-ui` keeps omp's tool UI (the `ask` dialog) on the wire; `--no-ui`\n // keeps its extensions headless, so no widget/notify frames or approval dialogs.\n const args = [\"--mode\", \"rpc-ui\", \"--no-ui\"];\n\n // ── Session persistence ───────────────────────────────────────────────────\n // Store OMP session files in <cwd>/.omp/sessions/ so they survive process\n // restarts. The caller passes resumeSessionId to restore a prior session.\n const sessionDir = path.join(this.config.cwd, \".omp\", \"sessions\");\n await fs.mkdir(sessionDir, { recursive: true });\n args.push(\"--session-dir\", sessionDir);\n\n if (this.config.resumeSessionId) {\n this.log.info(\"resuming OMP session\", { sessionId: this.config.resumeSessionId });\n args.push(\"--session\", this.config.resumeSessionId);\n }\n\n // ── Provider registry → session-private omp agent directory ───────────────\n // Every enabled registry entry is serialized into omp's own `models.yml`\n // inside a directory `PI_CODING_AGENT_DIR` points at, so an omp session\n // sees N selectable providers and resolves `@role` across them. Returns\n // undefined for a session that carries no registry, which keeps the\n // legacy `provider`/`model`/env path byte-identical.\n const providers = await materializeOmpProviders(this.config);\n if (providers) {\n // Known to cleanup() from here on, so a later start step that throws cannot leave it behind.\n this.privateHome = providers.ephemeral ? providers.agentDir : null;\n for (const warning of providers.warnings) this.log.warn(\"registry\", { warning });\n this.log.info(\"rendered omp models.yml\", {\n agentDir: providers.agentDir,\n providers: providers.providerIds,\n modelRoles: providers.modelRoles,\n seeded: providers.seeded.length,\n });\n } else if (this.config.registry) {\n // No usable entry, or the selected model's entry was left out: omp runs\n // on the user's own agent directory and login.\n this.log.info(\"registry gives omp no usable provider; omp uses its own login\");\n }\n\n const modelArg = providers?.modelArg ?? this.config.model;\n if (modelArg) args.push(\"--model\", modelArg);\n\n // Thinking level: `--thinking <level>` (omp's default is `high`). The\n // spawn-time snapshot lets `reconfigure()` send only what has drifted.\n const thinkingLevel = ompThinkingLevel(this.config);\n if (thinkingLevel) args.push(\"--thinking\", thinkingLevel);\n this.reconfig.setSnapshot({\n model: this.config.model,\n modelRef: this.config.modelRef,\n thinking: this.config.thinking,\n effort: this.config.effort,\n level: thinkingLevel,\n });\n\n // ── Tool restrictions ─────────────────────────────────────────────────────\n // agent.yaml `tools:` reaches the driver as AgentConfig.tools. The\n // claude-sdk driver has always honoured it; omp did not, so a restricted\n // agent definition silently ran with omp's full default toolset — which\n // dominates the fixed token prefix of every request.\n const toolArgs = buildOmpToolArgs(this.config.tools);\n if (toolArgs.length > 0) {\n this.log.info(\"applying tool restrictions\", { args: toolArgs });\n args.push(...toolArgs);\n }\n\n // ── System prompt injection ───────────────────────────────────────────────\n // omp does not accept a system prompt string directly; it reads from a file.\n // The file is private to this spawn and goes away with the process: a fixed\n // `<cwd>/.omp/system.md` is loaded by every native omp session and sub-agent that\n // runs in the same project afterwards, and the nested `agent.run` child of one run\n // overwrote the parent's (last writer wins). The path is passed via\n // --append-system-prompt.\n //\n // In flow mode (factory-assets/connectors/flow/run-flow.ts conductFlow), systemPrompt carries the full agent\n // identity (SOUL + RULES + knowledge + connector docs) because no agentDir is set.\n // In REPL mode (agent.ts buildDriver), systemPrompt carries the runner's agent sections\n // (the soul included: omp reads no SOUL.md) and the connector docs.\n this.removeSystemPromptFile();\n if (this.config.systemPrompt) {\n const promptDir = path.join(this.config.cwd, \".skaile\", \"cache\", \"omp-system\");\n await fs.mkdir(promptDir, { recursive: true });\n const systemFile = path.join(promptDir, `${randomUUID()}.md`);\n await fs.writeFile(systemFile, this.config.systemPrompt);\n this.systemPromptFile = systemFile;\n args.push(\"--append-system-prompt\", systemFile);\n }\n\n // Explicit env whitelist for the omp child process. Avoids leaking the\n // runner's full environment (which may carry user secrets provisioned by\n // the platform) into the spawned subprocess. `this.config.env`, when\n // supplied, is merged over the whitelist (the caller wins per key), never\n // used in its place: a replaced env drops PATH and the spawn fails with\n // ENOENT (the model endpoint hands the driver only its endpoint variables).\n const env: Record<string, string> = {\n ...buildOmpChildEnv(process.env),\n ...(this.config.env as Record<string, string> | undefined),\n };\n // ── Main-agent handoff ────────────────────────────────────────────────────\n // PI_CODING_AGENT_DIR is omp's home: its runtime databases, credential store and\n // settings live there. It is never the agent directory itself: that holds the pinned\n // agent files (`.skaile/cache/agents/<name>/`) and omp's databases do not belong\n // beside them. omp reads `RULES.md` (not `SOUL.md`) from its home, so the agent's\n // entries are linked into a private home directory (see `materializeOmpIdentityDir`).\n // A rendered registry owns that home: it already contains the agent's files\n // (linked in from `agentDir`) plus the session's `models.yml` / `config.yml`.\n if (providers) {\n env.PI_CODING_AGENT_DIR = providers.agentDir;\n // The only place a credential *value* exists in this adapter. Registry\n // credentials override the ambient allowlist unconditionally: the\n // session's registry is the statement of intent, not whatever the host\n // happened to export.\n Object.assign(env, providers.credentialEnv);\n } else if (this.config.agentDir) {\n const home = await materializeOmpIdentityDir(this.config);\n if (home) {\n this.log.info(\"omp home for the agent\", { agentDir: home.agentDir });\n env.PI_CODING_AGENT_DIR = home.agentDir;\n this.privateHome = home.ephemeral ? home.agentDir : null;\n }\n }\n if (this.config.sshKeyPath) {\n env.GIT_SSH_COMMAND = `ssh -i \"${this.config.sshKeyPath}\" -o StrictHostKeyChecking=accept-new`;\n }\n stripRunnerPrivateEnv(env);\n\n // test-only: `OMP_BRIDGE_BIN` overrides the binary name and `OMP_BRIDGE_PREARGS`\n // (space-delimited) supplies any leading args (e.g. a JS script path when the\n // override binary is `node` or `bun`). Used by the subprocess harness tests in\n // `tests/omp-driver.test.ts` to point spawn at a fake-omp script without\n // monkey-patching `node:child_process`. Both are ignored in production.\n const overrideBin = process.env.OMP_BRIDGE_BIN;\n const overridePreArgs = process.env.OMP_BRIDGE_PREARGS\n ? process.env.OMP_BRIDGE_PREARGS.split(/\\s+/).filter(Boolean)\n : [];\n const spawnBin = overrideBin || \"omp\";\n const spawnArgs = overrideBin ? [...overridePreArgs, ...args] : args;\n\n const spawned = await new Promise<ChildProcess>((resolve, reject) => {\n const startStderr: string[] = [];\n this.log.info(\"spawning omp\", {\n bin: spawnBin,\n args: spawnArgs,\n cwd: this.config.cwd,\n });\n if (env.PI_CODING_AGENT_DIR)\n this.log.debug(\"env: PI_CODING_AGENT_DIR set\", { value: env.PI_CODING_AGENT_DIR });\n if (env.GIT_SSH_COMMAND) this.log.debug(\"env: GIT_SSH_COMMAND set\");\n\n // Cast to ChildProcess: spawn infers ChildProcessWithoutNullStreams for\n // pipe stdio, but bun-types doesn't expose EventEmitter.on on that subtype.\n // With the uid split on, omp runs as the agent uid through the launch shim.\n const target = wrapAgentCommand(spawnBin, spawnArgs, resolveAgentExec());\n const proc = spawn(target.command, target.args, {\n cwd: this.config.cwd,\n env,\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n }) as ChildProcess;\n this.proc = proc;\n // bun-types 1.3.11 omits EventEmitter.on from ChildProcess; cast to subscribe.\n const procEmitter = proc as unknown as EventEmitter;\n\n procEmitter.on(\"error\", (err: Error) => {\n // A process replaced (or killed) by kill()/resetSession() no longer\n // owns the turn, the ready state or the error channel.\n if (this.proc !== proc) {\n clearTimeout(readyTimeout);\n reject(err);\n return;\n }\n const detail = this.classifyProcessError(err as NodeJS.ErrnoException);\n this.log.error(\"process error\", err, { detail });\n this.emit(\"agent-event\", { type: \"error\", error: detail.message, detail });\n if (!this.ready) reject(err);\n // Settle any in-flight turn so a process-level error cannot hang prompt().\n this.rejectTurn(Object.assign(new Error(detail.message), { detail }));\n });\n\n procEmitter.on(\"exit\", (code: number | null, signal: NodeJS.Signals | null) => {\n this.log.info(\"process exited\", { code, signal });\n if (this.proc !== proc) {\n // Killed or replaced by kill()/resetSession(): the kill settled its own\n // turn and cleaned up, and a late exit must neither reject the turn of\n // the process that succeeded it nor tear down that process's state.\n // A start still waiting for `ready` on this process is over.\n clearTimeout(readyTimeout);\n reject(new Error(\"omp process killed before it was ready\"));\n // Only a plain kill() is announced; a live successor is not exiting.\n if (this.proc === null) this.emit(\"exit\", { code, signal });\n return;\n }\n const lastStderr = this.stderrBuffer.slice(-10).join(\"\\n\");\n const crashed = code !== null && code !== 0;\n if (crashed) {\n const detail: AgentError = {\n message: `omp process crashed (exit code ${code})${lastStderr ? `: ${lastStderr}` : \"\"}`,\n category: \"process\",\n retryable: true,\n hint:\n lastStderr || \"The agent process exited unexpectedly. Try sending your prompt again.\",\n };\n this.emit(\"agent-event\", { type: \"error\", error: detail.message, detail });\n }\n // An exit before `ready` ends the start: without this the start promise never\n // settles (the ready timeout skips a gone process), and a caller awaiting it\n // hangs, or the process ends on a pending top-level await. Rejected on `close`\n // so omp's last stderr lines (the reason it gave up) are read first.\n if (!this.ready) {\n clearTimeout(readyTimeout);\n // Settles once: on `close` (stdio drained), or after 1 s if `close` never fires.\n // Not unref'd, so the pending start keeps the process alive until it rejects.\n const rejectStart = () => {\n clearTimeout(fallback);\n reject(\n new Error(\n `omp exited before it was ready (${code !== null ? `exit code ${code}` : `signal ${signal}`})${startStderr.length > 0 ? `: ${ompCredentialMessage(ompStartFailureCause(startStderr))}` : \"\"}`,\n ),\n );\n };\n const fallback = setTimeout(rejectStart, 1000);\n procEmitter.once(\"close\", rejectStart);\n }\n this.cleanup();\n // Settle any in-flight turn: an exit before `agent_end` means the turn\n // can never complete normally, so reject rather than leak a pending promise.\n this.rejectTurn(\n new Error(\n crashed\n ? `omp process crashed (exit code ${code})`\n : `omp process exited before the turn completed${signal ? ` (signal ${signal})` : \"\"}`,\n ),\n );\n this.emit(\"exit\", { code, signal });\n });\n\n if (proc.stdout) {\n const rl = createInterface({ input: proc.stdout });\n this.rl = rl;\n // bun-types 1.3.11 omits EventEmitter.on from readline.Interface; cast to subscribe.\n (rl as unknown as EventEmitter).on(\"line\", (line: string) => {\n if (!line.trim()) return;\n try {\n const event: OmpEvent = JSON.parse(line);\n this.handleEvent(event);\n } catch {\n this.log.debug(\"stdout\", { line });\n }\n });\n }\n\n if (proc.stderr) {\n const stderrRl = createInterface({ input: proc.stderr });\n (stderrRl as unknown as EventEmitter).on(\"line\", (line: string) => {\n this.log.warn(`stderr: ${line}`);\n this.stderrBuffer.push(line);\n if (this.stderrBuffer.length > 20) this.stderrBuffer.shift();\n startStderr.push(line);\n if (startStderr.length > 20) startStderr.shift();\n });\n }\n\n const startTime = Date.now();\n const readyTimeout = setTimeout(() => {\n // Not for a process that was replaced or has gone: it must not mark the\n // driver (now owned by a successor, or stopped) as ready.\n if (!this.ready && this.proc === proc) {\n this.log.warn(\"ready timeout, proceeding\", { timeoutMs: 5000 });\n this.ready = true;\n resolve(proc);\n }\n }, 5000);\n\n this.once(\"ready\", () => {\n clearTimeout(readyTimeout);\n if (!this.ready && this.proc === proc) {\n this.log.info(\"process ready\", { elapsedMs: Date.now() - startTime });\n this.ready = true;\n resolve(proc);\n }\n });\n });\n\n // Every await below can span a kill()/resetSession(): the successor owns the\n // driver state then, so a start for this process must not touch it.\n const assertCurrent = (): void => {\n if (this.proc !== spawned) throw new Error(\"omp process was killed during start\");\n };\n\n assertCurrent();\n // Subscribed before the requests so a registry change that lands while they\n // are in flight is not missed. There is no await between the check and the\n // subscription, so a later kill()'s cleanup() always unsubscribes it.\n const hooks = this.config.capabilities;\n if (hooks) {\n this.unsubscribeToolsChanged =\n hooks.onToolsChanged?.(() => {\n void this.syncHostTools();\n }) ?? null;\n }\n\n // Independent of each other, so concurrent: a misbehaving omp blocks start\n // for one request timeout, not two. Both are best-effort and never throw.\n // Before start() resolves, so the first `ask` already arrives as one dialog\n // and the first prompt already sees the tools.\n await Promise.all([this.enableAskDialog(), hooks ? this.syncHostTools() : undefined]);\n assertCurrent();\n\n // Context fill is known before the first prompt (system prompt + tools);\n // best-effort and not awaited, so a slow `get_state` never delays start().\n void this.captureState({ announceSession: false });\n }\n\n /**\n * Register the runner's capabilities with omp as host tools.\n *\n * Sends the full set every time: `set_host_tools` replaces omp's previous\n * host-owned set, so a registry change that removes a capability takes\n * effect too. Best-effort — a failure is logged and the session runs\n * without host tools rather than failing to start.\n */\n private async syncHostTools(): Promise<void> {\n const hooks = this.config.capabilities;\n if (!hooks || !this.proc) return;\n const set = buildOmpHostTools(hooks.composeTools());\n for (const { tool, reason } of set.dropped) {\n const key = `${tool}\\u0000${reason}`;\n if (this.warnedDroppedHostTools.has(key)) continue;\n this.warnedDroppedHostTools.add(key);\n this.log.warn(\"host tool dropped: invalid input schema\", { tool, reason });\n }\n // Swapped before sending so a call racing the response already routes.\n this.hostToolCapabilities = set.capabilityNames;\n try {\n const response = await this.request(\n { type: \"set_host_tools\", tools: set.definitions },\n { quiet: true },\n );\n if (response.success) {\n const data = response.data as { toolNames?: unknown } | undefined;\n this.log.info(\"registered omp host tools\", { toolNames: data?.toolNames });\n } else {\n this.log.error(\"omp rejected host tools\", new Error(response.error ?? \"unknown error\"), {\n tools: set.definitions.map((t) => t.name),\n });\n }\n } catch (err) {\n this.log.error(\"registering omp host tools failed\", err as Error);\n }\n }\n\n /**\n * Execute a capability omp asked the host to run (`host_tool_call`) and\n * answer with `host_tool_result`. Goes through {@link dispatchCapability}\n * so validation, fire-and-forget and render semantics match claude-sdk.\n *\n * Emits `tool_call` / `tool_execution_end` around the dispatch: the\n * normalizer does not read omp's own tool frames, so without these the\n * call — and its `activity_label` — would never reach the chat.\n */\n private handleHostToolCall(event: OmpEvent): void {\n const id = event.id;\n if (typeof id !== \"string\") return;\n const hostName = typeof event.toolName === \"string\" ? event.toolName : \"\";\n const name = this.hostToolCapabilities.get(hostName) ?? hostName;\n const callId = typeof event.toolCallId === \"string\" ? event.toolCallId : id;\n const input = event.arguments ?? {};\n const hooks = this.config.capabilities;\n const controller = new AbortController();\n const call = { controller, name };\n this.hostToolCalls.set(id, call);\n this.emit(\"agent-event\", {\n type: \"tool_call\",\n name,\n tool: { name },\n toolCallId: callId,\n input,\n });\n\n void (async () => {\n let text: string;\n let isError = false;\n try {\n if (!hooks) throw new Error(`no capability host for ${name}`);\n const dispatch = await dispatchCapability(\n hooks,\n name,\n input,\n (_err, dispatchCallId) =>\n this.log.warn(\"background capability handler failed\", {\n name,\n toolCallId: callId,\n callId: dispatchCallId,\n // Nothing from the error: its message can quote the call's content.\n }),\n controller.signal,\n );\n text =\n typeof dispatch.result === \"string\"\n ? dispatch.result\n : JSON.stringify(dispatch.result ?? {});\n } catch (err) {\n isError = true;\n text = `Error: ${(err as Error)?.message ?? String(err)}`;\n }\n // Cancelled by omp or the process went away: nobody awaits a result.\n if (this.hostToolCalls.get(id) !== call) return;\n this.hostToolCalls.delete(id);\n this.emit(\"agent-event\", { type: \"tool_execution_end\", toolName: name });\n try {\n this.send({\n type: \"host_tool_result\",\n id,\n result: { content: [{ type: \"text\", text }] },\n ...(isError ? { isError: true } : {}),\n });\n } catch (err) {\n this.log.warn(\"host tool result undeliverable\", { name, callId, error: String(err) });\n }\n })();\n }\n\n /**\n * `host_tool_cancel`: omp aborted the call, so abort the capability handler\n * and close the call's chat activity (the handler's later settlement is\n * ignored, so this is the only `tool_execution_end` the call gets).\n */\n private handleHostToolCancel(event: OmpEvent): void {\n const targetId = event.targetId;\n if (typeof targetId !== \"string\") return;\n this.abortHostToolCall(targetId);\n }\n\n /** Abort one in-flight host tool call and end its activity; no-op if already settled. */\n private abortHostToolCall(id: string): void {\n const call = this.hostToolCalls.get(id);\n if (!call) return;\n this.hostToolCalls.delete(id);\n call.controller.abort();\n this.emit(\"agent-event\", { type: \"tool_execution_end\", toolName: call.name });\n }\n\n // ── Interactive questions (`ask`) ──────────────────────────────────────────\n\n /**\n * `extension_ui_request`: omp asks the host something. Only `ask` (and the\n * `select` omp falls back to when `set_ask_dialog` is unavailable) can carry\n * a user question; both park until {@link answerQuestion}. Presentation\n * frames expect no reply. Every other kind is a dialog nobody here can\n * answer, so it is cancelled at once — an unanswered dialog would leave the\n * tool call, and the turn, waiting forever.\n */\n private handleExtensionUiRequest(event: OmpEvent): void {\n const method = event.method;\n if (method === \"cancel\") {\n // omp closed a dialog itself (timeout, abort): nothing is owed any more.\n if (typeof event.targetId === \"string\" && this.pendingQuestion?.id === event.targetId) {\n this.pendingQuestion = null;\n }\n return;\n }\n if (\n method === \"notify\" ||\n method === \"setStatus\" ||\n method === \"setWidget\" ||\n method === \"setTitle\" ||\n method === \"set_editor_text\" ||\n method === \"open_url\"\n ) {\n return;\n }\n const id = event.id;\n if (typeof id !== \"string\") return;\n let parsed: OmpPendingQuestion | null = null;\n if (method === \"ask\") parsed = this.parseAskRequest(id, event);\n else if (method === \"select\") parsed = this.parseSelectRequest(id, event);\n if (!parsed) {\n this.log.debug(\"cancelling unsupported omp dialog\", { method: String(method) });\n this.sendUiResponse({ id, cancelled: true });\n return;\n }\n // omp parks on one dialog at a time; a second request means the first is dead.\n this.cancelPendingQuestion();\n this.pendingQuestion = parsed;\n this.announceQuestion(parsed, event);\n }\n\n private parseAskRequest(id: string, event: OmpEvent): OmpPendingQuestion | null {\n if (!Array.isArray(event.questions) || event.questions.length === 0) return null;\n const questions: OmpPendingQuestion[\"questions\"] = [];\n for (const raw of event.questions as unknown[]) {\n const q = raw as { id?: unknown; question?: unknown; options?: unknown; multi?: unknown };\n // The response needs one `{ id }` entry per question; without either field\n // the ask cannot be answered correctly, so refuse it rather than guess.\n if (!q || typeof q.id !== \"string\" || typeof q.question !== \"string\" || !q.question) {\n return null;\n }\n const options = (Array.isArray(q.options) ? (q.options as unknown[]) : []).flatMap((o) => {\n let label: unknown = o;\n if (o && typeof o === \"object\" && \"label\" in o) label = o.label;\n return typeof label === \"string\" ? [label] : [];\n });\n questions.push({ id: q.id, question: q.question, options, multi: q.multi === true });\n }\n return { id, method: \"ask\", questions, answers: questions.map(() => undefined) };\n }\n\n private parseSelectRequest(id: string, event: OmpEvent): OmpPendingQuestion | null {\n if (typeof event.title !== \"string\" || !event.title || !Array.isArray(event.options)) {\n return null;\n }\n const options = (event.options as unknown[]).filter((o): o is string => typeof o === \"string\");\n if (options.length === 0) return null;\n return {\n id,\n method: \"select\",\n questions: [{ id, question: event.title, options, multi: false }],\n answers: [undefined],\n };\n }\n\n /**\n * Publish the parked question the way claude-sdk does for `AskUserQuestion`:\n * an assistant `tool_use` block the normalizer turns into one `question`\n * event per question, plus the matching `tool_call`. Option descriptions and\n * `header`s survive in the tool input for consumers that render them.\n */\n private announceQuestion(pending: OmpPendingQuestion, event: OmpEvent): void {\n const rawQuestions = Array.isArray(event.questions) ? (event.questions as unknown[]) : [];\n const input = {\n requestId: pending.id,\n questions: pending.questions.map((q, i) => {\n const raw = rawQuestions[i] as\n | { header?: unknown; options?: Array<{ label?: unknown; description?: unknown }> }\n | undefined;\n return {\n question: q.question,\n ...(typeof raw?.header === \"string\" ? { header: raw.header } : {}),\n multiSelect: q.multi,\n options: q.options.map((label, j) => {\n const description = raw?.options?.[j]?.description;\n return { label, ...(typeof description === \"string\" ? { description } : {}) };\n }),\n };\n }),\n };\n const toolCallId = `omp-ask:${pending.id}`;\n this.emit(\"agent-event\", {\n type: \"message_start\",\n message: {\n role: \"assistant\",\n content: [{ type: \"tool_use\", name: \"AskUserQuestion\", id: toolCallId, input }],\n },\n });\n this.emit(\"agent-event\", {\n type: \"tool_call\",\n name: \"AskUserQuestion\",\n tool: { name: \"AskUserQuestion\" },\n toolCallId,\n input,\n });\n this.log.debug(\"paused on omp ask\", { questions: pending.questions.length });\n }\n\n override supersedePendingQuestion(): void {\n this.cancelPendingQuestion();\n }\n\n override hasPendingQuestion(): boolean {\n return this.pendingQuestion !== null;\n }\n\n /**\n * While omp is parked on a question a reply that is not an answer must not\n * become a prompt: the turn is still running, and a second prompt would\n * collide with it.\n */\n override get acceptsReplyAsPrompt(): boolean {\n return this.pendingQuestion === null;\n }\n\n override answerQuestion(answer: string, question?: string, requestId?: string): boolean {\n const pending = this.pendingQuestion;\n if (!pending || typeof answer !== \"string\") return false;\n if (requestId !== undefined && requestId !== pending.id) return false;\n\n // A named answer binds to its own question; an unnamed one fills the next\n // unanswered slot. Same rule as claude-sdk.\n let index =\n question !== undefined ? pending.questions.findIndex((q) => q.question === question) : -1;\n if (index === -1) index = pending.answers.indexOf(undefined);\n if (index === -1) return false;\n pending.answers[index] = answer;\n if (pending.answers.some((a) => a === undefined)) return true;\n\n this.pendingQuestion = null;\n this.sendUiResponse(this.buildQuestionResponse(pending));\n this.log.debug(\"answered omp ask\", { questions: pending.questions.length });\n return true;\n }\n\n /** Shape the collected answers as the `extension_ui_response` payload for the request's method. */\n private buildQuestionResponse(pending: OmpPendingQuestion): Record<string, unknown> {\n const find = (options: string[], text: string): string | undefined =>\n options.find((o) => o === text) ??\n options.find((o) => o.toLowerCase() === text.toLowerCase());\n\n if (pending.method === \"select\") {\n const match = find(pending.questions[0]!.options, (pending.answers[0] ?? \"\").trim());\n if (match !== undefined) return { id: pending.id, value: match };\n // A `select` only takes one of its options; free text has nowhere to go.\n this.log.warn(\"select answer matches no option; cancelling it\");\n return { id: pending.id, cancelled: true };\n }\n\n const answers = pending.questions.map((q, i) => {\n const text = (pending.answers[i] ?? \"\").trim();\n const whole = find(q.options, text);\n if (whole !== undefined) return { id: q.id, selectedOptions: [whole] };\n if (q.multi) {\n // The UI hands a multi-select back as one string; take a comma-separated\n // list of labels apart, but only if every piece is a real option.\n const parts = text\n .split(\",\")\n .map((p) => p.trim())\n .filter(Boolean);\n const matched = parts.map((p) => find(q.options, p));\n if (parts.length > 0 && matched.every((m) => m !== undefined)) {\n return { id: q.id, selectedOptions: [...new Set(matched as string[])] };\n }\n }\n // Anything else is the user's own words (omp always offers free text).\n return { id: q.id, selectedOptions: [], ...(text ? { customInput: text } : {}) };\n });\n return { id: pending.id, answers };\n }\n\n /** Write an `extension_ui_response`; undeliverable (process gone) is logged, not thrown. */\n private sendUiResponse(payload: Record<string, unknown>): void {\n try {\n this.send({ type: \"extension_ui_response\", ...payload });\n } catch (err) {\n this.log.warn(\"extension ui response undeliverable\", { error: String(err) });\n }\n }\n\n /** Drop the pending question and tell omp it was cancelled, so its tool call unwinds. */\n private cancelPendingQuestion(): void {\n const pending = this.pendingQuestion;\n if (!pending) return;\n this.pendingQuestion = null;\n this.sendUiResponse({ id: pending.id, cancelled: true });\n }\n\n /**\n * Opt in to omp's single `ask` dialog request (off by default per process).\n * Best-effort: a build without the command answers with a failed response and\n * its `ask` keeps degrading to one `select` per question, which\n * {@link handleExtensionUiRequest} still surfaces as a question.\n */\n private async enableAskDialog(): Promise<void> {\n try {\n const response = await this.request(\n { type: \"set_ask_dialog\", enabled: true },\n { quiet: true },\n );\n if (!response.success) {\n this.log.warn(\"omp rejected set_ask_dialog; ask falls back to select\", {\n error: response.error,\n });\n }\n } catch (err) {\n this.log.warn(\"set_ask_dialog failed\", { error: String(err) });\n }\n }\n\n private extractMessageText(msg: OmpMessage): string {\n if (!msg) return \"\";\n const c = msg.content;\n if (typeof c === \"string\") return c;\n if (Array.isArray(c))\n return c\n .filter((b) => b.type === \"text\" && b.text)\n .map((b) => b.text)\n .join(\"\");\n return \"\";\n }\n\n /**\n * `available_commands_update`: replace the cached slash-command list and\n * publish it. Names carry no leading slash (omp's already don't), matching\n * claude-sdk's `commands_available`. Entries without a name are skipped.\n */\n private handleCommandsUpdate(event: OmpEvent): void {\n const raw = Array.isArray(event.commands) ? (event.commands as unknown[]) : [];\n const commands: SlashCommandInfo[] = [];\n for (const entry of raw) {\n if (!entry || typeof entry !== \"object\") continue;\n const c = entry as { name?: unknown; description?: unknown; input?: { hint?: unknown } };\n if (typeof c.name !== \"string\" || !c.name) continue;\n const hint = c.input && typeof c.input === \"object\" ? c.input.hint : undefined;\n commands.push({\n name: c.name,\n description: typeof c.description === \"string\" ? c.description : \"\",\n argumentHint: typeof hint === \"string\" && hint ? hint : undefined,\n });\n }\n this.cachedCommands = commands;\n this.emit(\"agent-event\", { type: \"commands_available\", commands });\n this.log.debug(\"discovered slash commands\", { count: commands.length });\n }\n\n private handleEvent(event: OmpEvent) {\n if (event.type === \"ready\") {\n this.emit(\"ready\");\n return;\n }\n if (event.type === \"response\") {\n const quiet = typeof event.id === \"string\" && this.quietRequestIds.delete(event.id);\n if (!event.success && event.error && !quiet) {\n const detail = this.classifyErrorMessage(event.error);\n this.emit(\"agent-event\", { type: \"error\", error: detail.message, detail });\n }\n this.emit(`response:${event.id}`, event);\n return;\n }\n // Host tool requests are answered here, not forwarded: they are a\n // host↔omp exchange, surfaced to consumers as `tool_call` events.\n if (event.type === \"host_tool_call\") {\n this.handleHostToolCall(event);\n return;\n }\n if (event.type === \"host_tool_cancel\") {\n this.handleHostToolCancel(event);\n return;\n }\n // UI dialogs (`ask`, …) are a host↔omp exchange: published as `question`\n // events and answered via `answerQuestion`, never forwarded raw.\n if (event.type === \"extension_ui_request\") {\n this.handleExtensionUiRequest(event);\n return;\n }\n // Slash-command list pushed by omp after `ready` and on change: published\n // as `commands_available` (like claude-sdk), never forwarded raw.\n if (event.type === \"available_commands_update\") {\n this.handleCommandsUpdate(event);\n return;\n }\n if (event.type === \"error\" && event.error) {\n const detail = this.classifyErrorMessage(event.error);\n this.emit(\"agent-event\", { ...event, error: detail.message, detail });\n return;\n }\n // Compute text delta for message_update events\n if (event.type === \"message_update\" && event.message) {\n const text = this.extractMessageText(event.message);\n let delta = \"\";\n if (text.startsWith(this.prevText)) {\n delta = text.slice(this.prevText.length);\n } else {\n // Text blocks restructured — emit full text as delta\n delta = text;\n }\n this.prevText = text;\n // Thinking never enters `_textDelta` (extractMessageText sees text blocks\n // only). It travels beside it as `_thinkingDelta`, taken straight from\n // omp's `thinking_delta` sub-event so it cannot duplicate or reorder.\n const sub = event.assistantMessageEvent;\n const thinking =\n sub && typeof sub === \"object\" && \"type\" in sub && sub.type === \"thinking_delta\"\n ? \"delta\" in sub && typeof sub.delta === \"string\"\n ? sub.delta\n : \"\"\n : \"\";\n this.emit(\"agent-event\", {\n ...event,\n _textDelta: delta,\n ...(thinking ? { _thinkingDelta: thinking } : {}),\n });\n return;\n }\n // Reset delta tracking on message boundaries. `message_start` may already\n // carry content (omp 18.x puts the whole reply, or its first chunk, into the\n // start frame). That text must reach a delta consumer: seeding `prevText`\n // from it alone dropped it (the one-shot `skaile run` printed only what the\n // later updates added), and clearing it made the normalizer count it twice.\n // So the assistant's start text leaves the start frame and travels as the\n // first `_textDelta`, in a `message_update` right after it.\n if (event.type === \"message_start\") {\n const startText =\n event.message?.role === \"assistant\" ? this.extractMessageText(event.message) : \"\";\n this.prevText = startText;\n if (startText && event.message) {\n const content = event.message.content;\n const message = {\n ...event.message,\n content: Array.isArray(content) ? content.filter((b) => b.type !== \"text\") : \"\",\n };\n this.emit(\"agent-event\", { ...event, message });\n this.emit(\"agent-event\", {\n type: \"message_update\",\n message: event.message,\n _textDelta: startText,\n });\n return;\n }\n }\n if (event.type === \"message_end\" || event.type === \"agent_end\") {\n this.prevText = \"\";\n }\n\n if (event.type === \"message_end\") this.recordMessageUsage(event.message);\n\n // A failed omp request arrives as `message_end` with `stopReason: \"error\"`,\n // not as an `error` event. Without this branch the turn ended silently: the\n // caller saw a normal completion with no assistant text and no failure,\n // which reads as a hung or empty agent. Surface it on the same channel as\n // every other driver error so callers can classify and retry.\n if (\n event.type === \"message_end\" &&\n event.message?.role === \"assistant\" &&\n event.message.stopReason === \"error\"\n ) {\n const error = event.message.errorMessage || \"omp request failed\";\n const detail = this.classifyErrorMessage(error);\n this.log.error(\"omp request failed\", new Error(error), { detail });\n this.emit(\"agent-event\", { type: \"error\", error: detail.message, detail });\n }\n\n // After each turn ends, capture the OMP session ID so callers can persist it\n // and pass it as resumeSessionId on the next spawn.\n if (event.type === \"agent_end\") {\n void this.captureState();\n }\n // A listener that kills the driver while it handles `agent_end` (the\n // one-shot `skaile run` does) ends a turn that already finished: `kill()`\n // must settle it as done, not as \"omp process killed\".\n const turnEnded = event.type === \"agent_end\";\n this.turnEnded = turnEnded;\n try {\n this.emit(\"agent-event\", event);\n } finally {\n this.turnEnded = false;\n }\n // Resolve AFTER emitting so listeners observing the turn see `agent_end`\n // before the caller's `prompt()` await unblocks.\n if (turnEnded) {\n this.resolveTurn();\n }\n }\n\n /**\n * Resolve the in-flight prompt turn (on `agent_end`). Idempotent — a turn\n * settles at most once, so a stray second `agent_end` is harmless.\n */\n private resolveTurn(): void {\n const resolve = this.turnResolve;\n this.turnResolve = null;\n this.turnReject = null;\n resolve?.();\n }\n\n /**\n * Reject the in-flight prompt turn (process crash/error). Settling here keeps\n * `prompt()` from hanging forever when the child dies before `agent_end`.\n */\n private rejectTurn(err: Error): void {\n const reject = this.turnReject;\n this.turnResolve = null;\n this.turnReject = null;\n reject?.(err);\n }\n\n /**\n * Query OMP's current state via the `get_state` RPC.\n *\n * Always refreshes the context fill from `contextUsage`. With\n * `announceSession` (the default, used after each turn) it also records the\n * native session ID and emits a `session_info` event so the forge layer can\n * persist it. Failures are silently swallowed — both are best-effort.\n */\n private async captureState(options: { announceSession?: boolean } = {}): Promise<void> {\n const announceSession = options.announceSession ?? true;\n try {\n const response = await this.request({ type: \"get_state\" }, { quiet: !announceSession });\n\n if (response.success && response.data) {\n const data = response.data as Record<string, unknown>;\n this.captureContextUsage(data.contextUsage);\n const sessionId = data.sessionId as string | undefined;\n const sessionFile = data.sessionFile as string | undefined;\n if (announceSession && sessionId) {\n this._ompSessionId = sessionId;\n this.log.debug(\"omp session id assigned\", { sessionId });\n this.emit(\"agent-event\", {\n type: \"session_info\",\n driverSessionId: sessionId,\n ...(sessionFile ? { sessionFile } : {}),\n });\n }\n }\n } catch {\n // get_state is best-effort — OMP may not support it yet or the process\n // may have exited. The short-term history injection fallback still works.\n }\n }\n\n /** `get_state.contextUsage` → context fill + window; absent or malformed values are ignored. */\n private captureContextUsage(raw: unknown): void {\n if (!raw || typeof raw !== \"object\") return;\n const tokens = \"tokens\" in raw ? raw.tokens : undefined;\n const contextWindow = \"contextWindow\" in raw ? raw.contextWindow : undefined;\n if (typeof tokens === \"number\" && Number.isFinite(tokens) && tokens >= 0) {\n this._lastContextTokens = tokens;\n }\n if (typeof contextWindow === \"number\" && Number.isFinite(contextWindow) && contextWindow > 0) {\n this._contextWindow = contextWindow;\n }\n }\n\n /** Forget the previous turn's usage; called as a new turn begins. */\n private beginUsageTurn(): void {\n this._lastTokens = null;\n this._lastContextTokens = null;\n }\n\n /**\n * Fold one finished assistant message into the turn's usage. Only the\n * `message_end` value is final (`message_start` and partials carry running\n * zeros). A message without usage, or an errored one reporting all zeros,\n * bills nothing and must neither create a reading nor wipe a good one.\n */\n private recordMessageUsage(message: OmpMessage | undefined): void {\n if (message?.role !== \"assistant\" || !message.usage) return;\n const count = (value: unknown): number | undefined =>\n typeof value === \"number\" && Number.isFinite(value) && value >= 0 ? value : undefined;\n const input = count(message.usage.input);\n const output = count(message.usage.output);\n const cacheRead = count(message.usage.cacheRead);\n const cacheWrite = count(message.usage.cacheWrite);\n const reasoning = count(message.usage.reasoningTokens);\n const total = count(message.usage.totalTokens);\n const callContext = (input ?? 0) + (cacheRead ?? 0) + (cacheWrite ?? 0);\n if (callContext + (output ?? 0) + (total ?? 0) === 0) return;\n\n const turn: TokenUsage = { ...this._lastTokens };\n const add = (key: keyof TokenUsage, value: number | undefined) => {\n if (value !== undefined) turn[key] = (turn[key] ?? 0) + value;\n };\n add(\"inputTokens\", input);\n add(\"outputTokens\", output);\n add(\"cacheReadTokens\", cacheRead);\n add(\"cacheCreationTokens\", cacheWrite);\n add(\"reasoningTokens\", reasoning);\n add(\"totalTokens\", total);\n this._lastTokens = turn;\n // Provisional until `get_state` reports omp's own figure: that reply lands\n // after `agent_end`, and a compaction check can run before it.\n if (callContext > 0) this._lastContextTokens = callContext;\n }\n\n private nextId(): string {\n return `req-${++this.reqId}`;\n }\n\n /**\n * Send a command and await its `response` frame.\n *\n * @param options.quiet - Leave a failed response to the caller instead of\n * surfacing it as an `error` agent event.\n * @throws When the process is not running or no response arrives within\n * `options.timeoutMs` (default 5 s).\n */\n private request(\n msg: { type: string; [key: string]: unknown },\n options: { quiet?: boolean; timeoutMs?: number } = {},\n ): Promise<OmpEvent> {\n const id = this.nextId();\n const event = `response:${id}`;\n // Not `Promise.withResolvers`: the provider/connector packages that\n // typecheck this file target a lib older than es2024.\n let resolve!: (resp: OmpEvent) => void;\n let reject!: (err: Error) => void;\n const promise = new Promise<OmpEvent>((res, rej) => {\n resolve = res;\n reject = rej;\n });\n const onResponse = (resp: OmpEvent) => {\n clearTimeout(timer);\n this.pendingRequests.delete(id);\n resolve(resp);\n };\n // A timed-out quiet request keeps its id: omp may still answer late (with a\n // failure), and that answer must stay as quiet as an in-time one. The id is\n // dropped when the response is handled or the process ends (`cleanup()`).\n const fail = (err: Error, keepQuiet = false) => {\n clearTimeout(timer);\n this.pendingRequests.delete(id);\n this.removeListener(event, onResponse);\n if (!keepQuiet) this.quietRequestIds.delete(id);\n reject(err);\n };\n const timer = setTimeout(\n () => fail(new Error(`${msg.type} timeout`), true),\n options.timeoutMs ?? 5000,\n );\n this.once(event, onResponse);\n this.pendingRequests.set(id, fail);\n if (options.quiet) this.quietRequestIds.add(id);\n try {\n this.send({ id, ...msg });\n } catch (err) {\n fail(err as Error);\n }\n return promise;\n }\n\n private send(msg: object): void {\n if (!this.proc?.stdin?.writable) {\n const detail: AgentError = {\n message: \"omp process not running\",\n category: \"process\",\n retryable: true,\n hint: \"The agent process is not available. It will restart automatically on the next prompt.\",\n };\n const err = Object.assign(new Error(detail.message), { detail });\n throw err;\n }\n this.proc.stdin.write(`${JSON.stringify(msg)}\\n`);\n }\n\n /**\n * Sends a prompt to the omp process via JSON-RPC and resolves when the turn\n * completes (after the `agent_end` event), honoring the `AgentDriver.prompt`\n * contract so driver-agnostic callers can await turn completion uniformly.\n *\n * The driver emits `agent-event` payloads as omp streams responses on stdout.\n * If the child process errors or exits before `agent_end`, the returned promise\n * rejects rather than hanging.\n *\n * @param message - Plain-text user prompt.\n * @throws {Error} When the omp process is not running, its stdin is closed, or\n * the child crashes/exits before the turn completes.\n */\n public prompt(message: string): Promise<void> {\n return this.enqueuePrompt(() => this.runPrompt({ message }));\n }\n\n /**\n * Run one prompt after every earlier one settled. A question omp is parked on\n * is cancelled first, synchronously and ahead of the queue: the parked turn\n * can only finish once its `ask` is released, so the new prompt (the user\n * typing instead of answering) must not wait behind it. The runner queues chat\n * prompts too; this queue still covers callers that drive the driver directly.\n */\n private enqueuePrompt(run: () => Promise<void>): Promise<void> {\n this.cancelPendingQuestion();\n const queued = this.promptTail.then(run);\n this.promptTail = queued.then(\n () => undefined,\n () => undefined,\n );\n return queued;\n }\n\n /**\n * Structured prompt: text plus image/file/skill attachments. Images travel as\n * omp `ImageContent` (`prompt.images`, base64 + mimeType); file and skill\n * attachments are named in a text preamble, because omp reads files itself.\n * Turn settlement is shared with {@link prompt}.\n */\n public override promptInput(input: AgentPromptInput): Promise<void> {\n if (input.toolAllowlist !== undefined)\n return Promise.reject(new Error(TOOL_ALLOWLIST_UNSUPPORTED));\n return this.enqueuePrompt(async () => this.runPrompt(await this.buildPromptPayload(input)));\n }\n\n /** Resolve attachments into the `message` + `images` fields of an omp `prompt` frame. */\n private async buildPromptPayload(\n input: AgentPromptInput,\n ): Promise<{ message: string; images?: OmpImageContent[] }> {\n const attachments = input.attachments ?? [];\n if (attachments.length === 0) return { message: input.text };\n const mimeByExt: Record<string, string> = {\n \".png\": \"image/png\",\n \".jpg\": \"image/jpeg\",\n \".jpeg\": \"image/jpeg\",\n \".gif\": \"image/gif\",\n \".webp\": \"image/webp\",\n };\n const images: OmpImageContent[] = [];\n const preamble: string[] = [];\n let root: string | undefined;\n for (const attachment of attachments) {\n if (attachment.type !== \"image\") {\n preamble.push(`[Attached ${attachment.type}: ${attachment.name} (${attachment.path})]`);\n continue;\n }\n // Image bytes are read here, so the path must stay inside the workspace.\n root ??= await fs.realpath(this.config.cwd);\n const resolved = await fs.realpath(path.resolve(root, attachment.path));\n const rel = path.relative(root, resolved);\n const escapes = rel === \"..\" || rel.startsWith(`..${path.sep}`);\n if (rel === \"\" || escapes || path.isAbsolute(rel)) {\n throw new Error(`Image attachment is outside the workspace: ${attachment.path}`);\n }\n const mimeType = mimeByExt[path.extname(resolved).toLowerCase()];\n if (!mimeType) {\n throw new Error(`Unsupported image type for attachment: ${attachment.path}`);\n }\n // Anthropic rejects images over 5 MB; fail before reading the bytes.\n const { size } = await fs.stat(resolved);\n if (size > OMP_MAX_IMAGE_BYTES) {\n throw new Error(`Image attachment too large (${size} bytes > 5 MB): ${attachment.path}`);\n }\n images.push({\n type: \"image\",\n data: (await fs.readFile(resolved)).toString(\"base64\"),\n mimeType,\n });\n }\n const message = preamble.length ? `${preamble.join(\"\\n\")}\\n\\n${input.text}` : input.text;\n return { message, ...(images.length ? { images } : {}) };\n }\n\n /**\n * Send one `prompt` frame and resolve when the turn completes (`agent_end`).\n * Rejects if the child dies first.\n */\n private async runPrompt(payload: { message: string; images?: OmpImageContent[] }): Promise<void> {\n await this.start();\n // A reconfigure that landed mid-turn or before `ready` applies now.\n await this.reconfig.flushBeforeTurn();\n const id = this.nextId();\n\n // Install the per-turn resolver BEFORE sending: omp can stream a fast\n // `agent_end` on the next readline tick, and if the resolver isn't wired\n // yet that event would be missed and prompt() would hang forever.\n const turnPromise = new Promise<void>((resolve, reject) => {\n this.turnResolve = resolve;\n this.turnReject = reject;\n });\n\n this.beginUsageTurn();\n try {\n this.send({ id, type: \"prompt\", ...payload });\n } catch (err) {\n this.turnResolve = null;\n this.turnReject = null;\n throw err;\n }\n\n await turnPromise;\n }\n\n /**\n * Sends an in-band abort RPC to the omp process, requesting it to stop the\n * current turn without terminating the child process.\n *\n * @remarks This is a best-effort signal — omp may not honour the abort\n * immediately. The process remains alive after `abort()`.\n */\n public async abort(): Promise<void> {\n if (!this.proc) return;\n const id = this.nextId();\n this.send({ id, type: \"abort\" });\n // The dialog's tool call is aborted with the turn; release what it owed.\n this.cancelPendingQuestion();\n }\n\n /** `true` when the omp child process is alive and has not been killed. */\n public get isRunning(): boolean {\n return this.proc !== null && !this.proc.killed;\n }\n\n /**\n * Sends SIGTERM to the omp child process and performs cleanup.\n *\n * The driver instance must not be reused after `kill()`. Create a new\n * `OmpDriver` to start a fresh session.\n */\n kill(): void {\n const proc = this.proc;\n if (!proc) return;\n // Settle this process's in-flight turn here: its late `exit` is ignored (the\n // process is superseded by then) and must not reach a successor's turn.\n if (this.turnEnded) this.resolveTurn();\n else this.rejectTurn(new Error(\"omp process killed\"));\n proc.kill(\"SIGTERM\");\n this.cleanup();\n }\n\n async resetSession(): Promise<void> {\n this.kill();\n // Otherwise the respawn passes `--session` and reopens the pre-reset session.\n this.config = { ...this.config, resumeSessionId: undefined };\n this._lastTokens = null;\n this._lastContextTokens = null;\n this._contextWindow = null;\n await this.start();\n }\n\n private classifyProcessError(err: NodeJS.ErrnoException): AgentError {\n if (err.code === \"ENOENT\") {\n return {\n message: \"omp command not found\",\n category: \"config\",\n retryable: false,\n hint: \"The omp agent is not installed or not on your PATH. Install it and try again.\",\n };\n }\n if (err.code === \"EACCES\") {\n return {\n message: \"Permission denied running omp\",\n category: \"config\",\n retryable: false,\n hint: \"Check file permissions for the omp binary.\",\n };\n }\n return {\n message: err.message,\n category: \"process\",\n retryable: true,\n hint: \"An unexpected process error occurred. Try sending your prompt again.\",\n };\n }\n\n private classifyErrorMessage(rawMsg: string): AgentError {\n const msg = ompCredentialMessage(rawMsg);\n // Shared keyword buckets live in error-classifier.ts; only the hint copy is omp-specific.\n const generic = classifyGenericErrorMessage(msg);\n if (!generic) return { message: msg, category: \"unknown\", retryable: true };\n\n const lower = msg.toLowerCase();\n const hint =\n generic.category === \"auth\"\n ? \"Check your API key configuration in Settings.\"\n : generic.category === \"rate_limit\"\n ? \"You have hit the provider rate limit. Wait a moment and try again.\"\n : generic.category === \"network\"\n ? \"A network error occurred. Check your connection and try again.\"\n : // model: distinguish unavailable-model from over-long-context.\n lower.includes(\"model\")\n ? \"The selected model is not available. Change the model in settings.\"\n : \"The conversation is too long. Start a new session or choose a model with a larger context window.\";\n return { message: msg, category: generic.category, retryable: generic.retryable, hint };\n }\n\n /**\n * The models this session can select.\n *\n * Answered entirely from the registry: the ids are exactly the\n * `<providerId>/<modelId>` selectors rendered into `models.yml`, so a\n * picker offers every enabled endpoint instead of whichever one the\n * ambient binary happens to be authenticated for. A registry whose\n * entries name no models yields no entries here — that gap is closed by\n * giving the entry a `discovery:` block (`PROVIDER-CONFIG-PLAN.md` §1.1),\n * not by asking the omp binary what it happens to know. omp's own catalog\n * (`omp models --json`) answers a different question — every model omp\n * knows across every provider, regardless of what this session's registry\n * enables or has credentials for — and shelling out to an ambient binary\n * from this code path is itself a liability: it can block indefinitely\n * reading a prompt from stdin when run inside another interactive session.\n */\n override async listModels(): Promise<ModelEntry[]> {\n return registryModelEntries(this.config.registry);\n }\n\n /** Delete the system prompt file of the process that is gone (or about to be replaced). */\n private removeSystemPromptFile(): void {\n const file = this.systemPromptFile;\n this.systemPromptFile = null;\n if (file) rmSync(file, { force: true });\n }\n\n /**\n * Delete the private omp home of the process that is gone: it holds symlinks to the login\n * and the agent files and omp's runtime databases, and nothing reads it afterwards (p811).\n */\n private removePrivateHome(): void {\n const home = this.privateHome;\n this.privateHome = null;\n if (home) rmSync(home, { recursive: true, force: true });\n }\n\n private cleanup(): void {\n this.removeSystemPromptFile();\n this.removePrivateHome();\n this.rl?.close();\n this.rl = null;\n this.proc = null;\n this.ready = false;\n this.reconfig.setSnapshot(null);\n this.startPromise = null;\n this.stderrBuffer = [];\n // A respawn re-subscribes and re-registers the host tools from scratch.\n this.unsubscribeToolsChanged?.();\n this.unsubscribeToolsChanged = null;\n this.hostToolCapabilities = new Map();\n // Nothing can receive these results any more; stop the handlers and close\n // their chat activity (the handlers' later settlement is ignored).\n for (const id of [...this.hostToolCalls.keys()]) this.abortHostToolCall(id);\n // No response can arrive any more: fail the waiters now instead of at their timeout.\n for (const fail of [...this.pendingRequests.values()]) fail(new Error(\"omp process ended\"));\n this.pendingRequests.clear();\n this.quietRequestIds.clear();\n // The process that asked is gone; there is nobody to answer to.\n this.pendingQuestion = null;\n }\n}\n\n/**\n * `DriverTarget` wrapper for the omp driver. Registered into the plugin\n * registry by `registerBuiltinDrivers()`.\n */\nexport const ompDriverTarget: DriverTarget<AgentConfig> = {\n id: \"omp\",\n displayName: BUILTIN_DRIVER_CATALOG.omp?.name ?? \"omp (oh-my-pi)\",\n apiVersion: 1,\n // Drivers take AgentConfig; passthrough — full schema validation is out of scope.\n configSchema: z.custom<AgentConfig>(() => true),\n create: async (config, _ctx) => new OmpDriver(config),\n listModels: async (registry, options) =>\n new OmpDriver({\n cwd: process.cwd(),\n sessionId: \"model-list\",\n ...registryDriverConfig(registry, options),\n }).listModels(),\n};\n"]}
|