@agimon-ai/po-runner 0.0.0-alpha.21 → 0.0.0-alpha.211
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/LICENSE +21 -149
- package/README.md +34 -206
- package/dist/apiContracts.cjs +45 -2
- package/dist/apiContracts.cjs.map +1 -1
- package/dist/apiContracts.d.mts +2 -2
- package/dist/apiContracts.d.mts.map +1 -1
- package/dist/apiContracts.mjs +45 -2
- package/dist/apiContracts.mjs.map +1 -1
- package/dist/{bashResult-BqDa7sbC.mjs → bashResult-BLCLerXE.mjs} +57 -7
- package/dist/bashResult-BLCLerXE.mjs.map +1 -0
- package/dist/{bashResult-C2iKhHpD.cjs → bashResult-CZYiyl4p.cjs} +74 -6
- package/dist/bashResult-CZYiyl4p.cjs.map +1 -0
- package/dist/{bashResult-DcrRaBLv.d.mts → bashResult-CgVS_JpL.d.mts} +8 -3
- package/dist/{bashResult-DcrRaBLv.d.mts.map → bashResult-CgVS_JpL.d.mts.map} +1 -1
- package/dist/{bashRunService-DjOH5kye.cjs → bashRunService-DmuA1mKL.cjs} +52 -31
- package/dist/bashRunService-DmuA1mKL.cjs.map +1 -0
- package/dist/{bashRunService-Ci0cGdYO.d.mts → bashRunService-Iotfc_nV.d.mts} +21 -2
- package/dist/bashRunService-Iotfc_nV.d.mts.map +1 -0
- package/dist/{bashRunService-Cl3pYccr.mjs → bashRunService-Luy2hPMS.mjs} +52 -31
- package/dist/bashRunService-Luy2hPMS.mjs.map +1 -0
- package/dist/bashRunService.cjs +1 -1
- package/dist/bashRunService.d.mts +4 -4
- package/dist/bashRunService.d.mts.map +1 -1
- package/dist/bashRunService.mjs +1 -1
- package/dist/bashSchema.cjs +1 -1
- package/dist/bashSchema.d.mts +1 -1
- package/dist/bashSchema.mjs +1 -1
- package/dist/bashTool-D2ECDAhc.cjs +43 -0
- package/dist/bashTool-D2ECDAhc.cjs.map +1 -0
- package/dist/{bashTool-B1EwZLo_.d.mts → bashTool-Dc1ld2E3.d.mts} +3 -9
- package/dist/bashTool-Dc1ld2E3.d.mts.map +1 -0
- package/dist/bashTool-vg8uhbkj.mjs +26 -0
- package/dist/bashTool-vg8uhbkj.mjs.map +1 -0
- package/dist/bashTool.cjs +3 -3
- package/dist/bashTool.cjs.map +1 -1
- package/dist/bashTool.d.mts +4 -4
- package/dist/bashTool.d.mts.map +1 -1
- package/dist/bashTool.mjs +3 -3
- package/dist/bashTool.mjs.map +1 -1
- package/dist/bin/cli.cjs +372 -9
- package/dist/bin/cli.cjs.map +1 -1
- package/dist/bin/cli.d.mts.map +1 -1
- package/dist/bin/cli.mjs +369 -8
- package/dist/bin/cli.mjs.map +1 -1
- package/dist/bin/logSink.cjs +27 -24
- package/dist/bin/logSink.cjs.map +1 -1
- package/dist/bin/logSink.mjs +24 -21
- package/dist/bin/logSink.mjs.map +1 -1
- package/dist/bin/runnerHost.cjs +141 -53
- package/dist/bin/runnerHost.cjs.map +1 -1
- package/dist/bin/runnerHost.d.mts.map +1 -1
- package/dist/bin/runnerHost.mjs +141 -53
- package/dist/bin/runnerHost.mjs.map +1 -1
- package/dist/cliApp-7iTUx5KZ.cjs +351 -0
- package/dist/cliApp-7iTUx5KZ.cjs.map +1 -0
- package/dist/cliApp-S4iEO-fi.mjs +338 -0
- package/dist/cliApp-S4iEO-fi.mjs.map +1 -0
- package/dist/cliApp.cjs +2 -1
- package/dist/cliApp.d.mts +9 -4
- package/dist/cliApp.d.mts.map +1 -1
- package/dist/cliApp.mjs +1 -1
- package/dist/compaction.d.mts +1 -1
- package/dist/extensions/mcp-ui.mjs +7 -6
- package/dist/extensions/mcp-ui.mjs.map +1 -1
- package/dist/extensions/mcp.cjs +37 -17
- package/dist/extensions/mcp.cjs.map +1 -1
- package/dist/extensions/mcp.d.mts.map +1 -1
- package/dist/extensions/mcp.mjs +37 -17
- package/dist/extensions/mcp.mjs.map +1 -1
- package/dist/extensions/native.mjs +1225 -374
- package/dist/extensions/native.mjs.map +1 -1
- package/dist/extensions/server.cjs +900 -221
- package/dist/extensions/server.cjs.map +1 -1
- package/dist/extensions/server.d.mts.map +1 -1
- package/dist/extensions/server.mjs +908 -227
- package/dist/extensions/server.mjs.map +1 -1
- package/dist/extensions/web.mjs +924 -766
- package/dist/extensions/web.mjs.map +1 -1
- package/dist/headless-CMj9hunm.cjs +237 -0
- package/dist/headless-CMj9hunm.cjs.map +1 -0
- package/dist/headless-CUJt5Ihx.mjs +226 -0
- package/dist/headless-CUJt5Ihx.mjs.map +1 -0
- package/dist/{index-DM7yJpMs.d.mts → index-7_nuKoVm.d.mts} +6 -6
- package/dist/index-7_nuKoVm.d.mts.map +1 -0
- package/dist/index-BCCF1sGD.d.mts.map +1 -1
- package/dist/{index-CzCF_OP9.d.mts → index-CH-z0BX3.d.mts} +11 -4
- package/dist/index-CH-z0BX3.d.mts.map +1 -0
- package/dist/{index-C-IC35d9.d.mts → index-CJNsR-Ir.d.mts} +10 -7
- package/dist/index-CJNsR-Ir.d.mts.map +1 -0
- package/dist/{index--xF7DvsE.d.mts → index-CNCb1usM.d.mts} +8 -2
- package/dist/index-CNCb1usM.d.mts.map +1 -0
- package/dist/index-EMbmq9gu.d.mts +45 -0
- package/dist/index-EMbmq9gu.d.mts.map +1 -0
- package/dist/index-QlfncPRs.d.mts +58 -0
- package/dist/index-QlfncPRs.d.mts.map +1 -0
- package/dist/index-qSi4-EJW.d.mts +49 -0
- package/dist/index-qSi4-EJW.d.mts.map +1 -0
- package/dist/index.cjs +4 -4
- package/dist/index.d.mts +4 -4
- package/dist/index.mjs +4 -4
- package/dist/launch.cjs +4 -0
- package/dist/launch.d.mts +55 -0
- package/dist/launch.d.mts.map +1 -0
- package/dist/launch.mjs +1 -0
- package/dist/{launcher-CCYsFBM9.mjs → launcher-3xMxw72I.mjs} +45 -31
- package/dist/launcher-3xMxw72I.mjs.map +1 -0
- package/dist/{launcher-BG5t9nvG.d.mts → launcher-CDDBTvZq.d.mts} +4 -3
- package/dist/launcher-CDDBTvZq.d.mts.map +1 -0
- package/dist/{launcher-ZgDdyXpq.cjs → launcher-D7qAhSRL.cjs} +47 -33
- package/dist/launcher-D7qAhSRL.cjs.map +1 -0
- package/dist/launcher.cjs +1 -1
- package/dist/launcher.d.mts +5 -5
- package/dist/launcher.d.mts.map +1 -1
- package/dist/launcher.mjs +1 -1
- package/dist/lifeline-26IaW5w7.d.mts +34 -0
- package/dist/lifeline-26IaW5w7.d.mts.map +1 -0
- package/dist/lifeline-B4cjtrBe.cjs +27 -0
- package/dist/lifeline-B4cjtrBe.cjs.map +1 -0
- package/dist/lifeline-C1v2ItCY.mjs +214 -0
- package/dist/lifeline-C1v2ItCY.mjs.map +1 -0
- package/dist/lifeline-D4_ZRAhO.cjs +229 -0
- package/dist/lifeline-D4_ZRAhO.cjs.map +1 -0
- package/dist/lifeline-nPh3cx5A.mjs +10 -0
- package/dist/lifeline-nPh3cx5A.mjs.map +1 -0
- package/dist/lifeline.cjs +4 -1
- package/dist/lifeline.d.mts +4 -21
- package/dist/lifeline.mjs +3 -3
- package/dist/logFile-B9FSwmE0.cjs +44 -0
- package/dist/logFile-B9FSwmE0.cjs.map +1 -0
- package/dist/{logFile-C7oQ_v-g.d.mts → logFile-BirfZtS1.d.mts} +4 -4
- package/dist/logFile-BirfZtS1.d.mts.map +1 -0
- package/dist/logFile-D1EOKqmL.mjs +39 -0
- package/dist/logFile-D1EOKqmL.mjs.map +1 -0
- package/dist/logFile.cjs +1 -1
- package/dist/logFile.d.mts +3 -3
- package/dist/logFile.d.mts.map +1 -1
- package/dist/logFile.mjs +1 -1
- package/dist/{logReader-mq9uVurh.mjs → logReader-BYKii_s_.mjs} +99 -52
- package/dist/logReader-BYKii_s_.mjs.map +1 -0
- package/dist/{logReader-MdW9ffvV.d.mts → logReader-Bn3WEdjg.d.mts} +4 -2
- package/dist/{logReader-MdW9ffvV.d.mts.map → logReader-Bn3WEdjg.d.mts.map} +1 -1
- package/dist/{logReader-DHCK2BEr.cjs → logReader-DpMjBqfn.cjs} +101 -54
- package/dist/logReader-DpMjBqfn.cjs.map +1 -0
- package/dist/logReader.cjs +1 -1
- package/dist/logReader.d.mts +2 -2
- package/dist/logReader.mjs +1 -1
- package/dist/po-runtime-identity.json +1 -0
- package/dist/{ptyHost-D35hNmtd.cjs → ptyHost-C-oWV455.cjs} +20 -14
- package/dist/ptyHost-C-oWV455.cjs.map +1 -0
- package/dist/{ptyHost-CwbLLr90.mjs → ptyHost-C2zu-ZfO.mjs} +19 -13
- package/dist/ptyHost-C2zu-ZfO.mjs.map +1 -0
- package/dist/{ptyHost-DWWtRrGn.d.mts → ptyHost-C_6x2xuJ.d.mts} +2 -2
- package/dist/{ptyHost-DWWtRrGn.d.mts.map → ptyHost-C_6x2xuJ.d.mts.map} +1 -1
- package/dist/ptyHost.cjs +1 -1
- package/dist/ptyHost.d.mts +2 -2
- package/dist/ptyHost.d.mts.map +1 -1
- package/dist/ptyHost.mjs +1 -1
- package/dist/{reconcile-wNYQJZF-.mjs → reconcile-DUaX_vKZ.mjs} +2 -2
- package/dist/reconcile-DUaX_vKZ.mjs.map +1 -0
- package/dist/{reconcile-5cZ11jSD.cjs → reconcile-DjF9T1hN.cjs} +2 -2
- package/dist/reconcile-DjF9T1hN.cjs.map +1 -0
- package/dist/reconcile.cjs +1 -1
- package/dist/reconcile.d.mts +3 -3
- package/dist/reconcile.mjs +1 -1
- package/dist/responseEnvelope.cjs +5 -2
- package/dist/responseEnvelope.d.mts +15 -6
- package/dist/responseEnvelope.d.mts.map +1 -1
- package/dist/responseEnvelope.mjs +3 -3
- package/dist/{rmuxBackend-Dh0CYVAL.cjs → rmuxBackend-9tHTx1vf.cjs} +82 -48
- package/dist/rmuxBackend-9tHTx1vf.cjs.map +1 -0
- package/dist/{rmuxBackend-rjrVTG6K.mjs → rmuxBackend-BaK-R35I.mjs} +79 -45
- package/dist/rmuxBackend-BaK-R35I.mjs.map +1 -0
- package/dist/{rmuxBackend-CaEWooWn.d.mts → rmuxBackend-xFzlANM9.d.mts} +4 -4
- package/dist/rmuxBackend-xFzlANM9.d.mts.map +1 -0
- package/dist/rmuxBackend.cjs +1 -1
- package/dist/rmuxBackend.d.mts +2 -2
- package/dist/rmuxBackend.mjs +1 -1
- package/dist/rolldown-runtime-8H4AJuhK.mjs +14 -0
- package/dist/{rolldown-runtime-VH7oDXx4.cjs → rolldown-runtime-C0BPl7ul.cjs} +15 -0
- package/dist/{rtkProcessor-Iw9gP5Xp.mjs → rtkProcessor-DOXcp51z.mjs} +6 -5
- package/dist/rtkProcessor-DOXcp51z.mjs.map +1 -0
- package/dist/{rtkProcessor-DSGbM-Cm.cjs → rtkProcessor-J2gLQvM4.cjs} +8 -6
- package/dist/rtkProcessor-J2gLQvM4.cjs.map +1 -0
- package/dist/rtkProcessor.cjs +1 -1
- package/dist/rtkProcessor.mjs +1 -1
- package/dist/{runnerDependencies-DSun3xO-.cjs → runnerDependencies-CABYjW7H.cjs} +97 -64
- package/dist/runnerDependencies-CABYjW7H.cjs.map +1 -0
- package/dist/{runnerDependencies-7h_cxOva.mjs → runnerDependencies-DmvIcpZi.mjs} +95 -62
- package/dist/runnerDependencies-DmvIcpZi.mjs.map +1 -0
- package/dist/runnerDependencies.cjs +1 -1
- package/dist/runnerDependencies.d.mts +1 -1
- package/dist/runnerDependencies.mjs +1 -1
- package/dist/runnerHost-BvNYPMeh.mjs +165 -0
- package/dist/runnerHost-BvNYPMeh.mjs.map +1 -0
- package/dist/runnerHost-C2F5oxzn.cjs +184 -0
- package/dist/runnerHost-C2F5oxzn.cjs.map +1 -0
- package/dist/runnerLaunch-BAf7hXMr.cjs +192 -0
- package/dist/runnerLaunch-BAf7hXMr.cjs.map +1 -0
- package/dist/runnerLaunch-Bimgdh4h.mjs +175 -0
- package/dist/runnerLaunch-Bimgdh4h.mjs.map +1 -0
- package/dist/runnerNamer.d.mts +1 -1
- package/dist/{runnerPaths-B41rMOY6.cjs → runnerPaths-CSkswyjR.cjs} +97 -179
- package/dist/runnerPaths-CSkswyjR.cjs.map +1 -0
- package/dist/{runnerPaths-Dibbvyx_.mjs → runnerPaths-D3P7_EhW.mjs} +91 -179
- package/dist/runnerPaths-D3P7_EhW.mjs.map +1 -0
- package/dist/runnerPaths.cjs +1 -1
- package/dist/runnerPaths.d.mts +7 -9
- package/dist/runnerPaths.d.mts.map +1 -1
- package/dist/runnerPaths.mjs +1 -1
- package/dist/{runnerRegistry-dQYlMSpQ.cjs → runnerRegistry-B8K1L3lq.cjs} +68 -45
- package/dist/runnerRegistry-B8K1L3lq.cjs.map +1 -0
- package/dist/{runnerRegistry-V-Ocaf4N.d.mts → runnerRegistry-BlZhS9yL.d.mts} +2 -2
- package/dist/{runnerRegistry-V-Ocaf4N.d.mts.map → runnerRegistry-BlZhS9yL.d.mts.map} +1 -1
- package/dist/{runnerRegistry-BgaR5O86.mjs → runnerRegistry-Dqca6SD3.mjs} +53 -29
- package/dist/runnerRegistry-Dqca6SD3.mjs.map +1 -0
- package/dist/runnerRegistry-NW6oAJ71.cjs +60 -0
- package/dist/runnerRegistry-NW6oAJ71.cjs.map +1 -0
- package/dist/runnerRegistry-l0C_55oO.mjs +13 -0
- package/dist/runnerRegistry-l0C_55oO.mjs.map +1 -0
- package/dist/runnerRegistry.cjs +1 -1
- package/dist/runnerRegistry.d.mts +2 -2
- package/dist/runnerRegistry.mjs +1 -1
- package/dist/runnerSequence-ZTYgZ_2W.cjs +32 -0
- package/dist/runnerSequence-ZTYgZ_2W.cjs.map +1 -0
- package/dist/runnerSequence-k-_Fd77y.mjs +9 -0
- package/dist/runnerSequence-k-_Fd77y.mjs.map +1 -0
- package/dist/runnerSequenceStore-CaY7S_Sd.mjs +76 -0
- package/dist/runnerSequenceStore-CaY7S_Sd.mjs.map +1 -0
- package/dist/runnerSequenceStore-Ck6M-8r_.cjs +89 -0
- package/dist/runnerSequenceStore-Ck6M-8r_.cjs.map +1 -0
- package/dist/services/lifeline/client.cjs +88 -4
- package/dist/services/lifeline/client.cjs.map +1 -1
- package/dist/services/lifeline/client.d.mts +16 -0
- package/dist/services/lifeline/client.d.mts.map +1 -1
- package/dist/services/lifeline/client.mjs +83 -2
- package/dist/services/lifeline/client.mjs.map +1 -1
- package/dist/services/runnerSupervisor/index.cjs +36 -22
- package/dist/services/runnerSupervisor/index.cjs.map +1 -1
- package/dist/services/runnerSupervisor/index.d.mts +7 -5
- package/dist/services/runnerSupervisor/index.d.mts.map +1 -1
- package/dist/services/runnerSupervisor/index.mjs +35 -21
- package/dist/services/runnerSupervisor/index.mjs.map +1 -1
- package/dist/session-CdVeSD7F.mjs +8 -0
- package/dist/session-CdVeSD7F.mjs.map +1 -0
- package/dist/session-DnUj8Q71.cjs +25 -0
- package/dist/session-DnUj8Q71.cjs.map +1 -0
- package/dist/session-ISEGK4z9.mjs +26 -0
- package/dist/session-ISEGK4z9.mjs.map +1 -0
- package/dist/session-PQd3azWf.cjs +43 -0
- package/dist/session-PQd3azWf.cjs.map +1 -0
- package/dist/session.cjs +4 -3
- package/dist/session.d.mts +3 -1
- package/dist/session.d.mts.map +1 -1
- package/dist/session.mjs +3 -3
- package/dist/{type-DwMZoINK.d.mts → type-BWY9vvSq.d.mts} +6 -4
- package/dist/type-BWY9vvSq.d.mts.map +1 -0
- package/dist/{type-Do0YxwVQ.d.mts → type-bZgYQ7hv.d.mts} +11 -11
- package/dist/{type-Do0YxwVQ.d.mts.map → type-bZgYQ7hv.d.mts.map} +1 -1
- package/dist/types.d.mts +1 -1
- package/llms.txt +2 -1
- package/locales/vi.json +169 -0
- package/locales/zh-CN.json +169 -0
- package/package.json +95 -30
- package/skills/po-runner/SKILL.md +32 -14
- package/src/prompts/codemode-how-to-runner/SKILL.md +85 -0
- package/src/prompts/help-how-to-runner/SKILL.md +51 -0
- package/dist/bashResult-BqDa7sbC.mjs.map +0 -1
- package/dist/bashResult-C2iKhHpD.cjs.map +0 -1
- package/dist/bashRunService-Ci0cGdYO.d.mts.map +0 -1
- package/dist/bashRunService-Cl3pYccr.mjs.map +0 -1
- package/dist/bashRunService-DjOH5kye.cjs.map +0 -1
- package/dist/bashTool-B1EwZLo_.d.mts.map +0 -1
- package/dist/bashTool-BvC3YOgG.mjs +0 -24
- package/dist/bashTool-BvC3YOgG.mjs.map +0 -1
- package/dist/bashTool-euL6zMDl.cjs +0 -41
- package/dist/bashTool-euL6zMDl.cjs.map +0 -1
- package/dist/cliApp-T8Fx_-1j.cjs +0 -244
- package/dist/cliApp-T8Fx_-1j.cjs.map +0 -1
- package/dist/cliApp-q97eVh4E.mjs +0 -237
- package/dist/cliApp-q97eVh4E.mjs.map +0 -1
- package/dist/headless-DOlCixyf.mjs +0 -169
- package/dist/headless-DOlCixyf.mjs.map +0 -1
- package/dist/headless-Dko_yBiy.cjs +0 -180
- package/dist/headless-Dko_yBiy.cjs.map +0 -1
- package/dist/index--xF7DvsE.d.mts.map +0 -1
- package/dist/index-BzeXJk6V.d.mts +0 -12
- package/dist/index-BzeXJk6V.d.mts.map +0 -1
- package/dist/index-C-IC35d9.d.mts.map +0 -1
- package/dist/index-CzCF_OP9.d.mts.map +0 -1
- package/dist/index-DM7yJpMs.d.mts.map +0 -1
- package/dist/launcher-BG5t9nvG.d.mts.map +0 -1
- package/dist/launcher-CCYsFBM9.mjs.map +0 -1
- package/dist/launcher-ZgDdyXpq.cjs.map +0 -1
- package/dist/lifeline-Bm-bHIjS.mjs +0 -88
- package/dist/lifeline-Bm-bHIjS.mjs.map +0 -1
- package/dist/lifeline-eJdZV0nN.d.mts +0 -19
- package/dist/lifeline-eJdZV0nN.d.mts.map +0 -1
- package/dist/lifeline-m7laIzIP.cjs +0 -98
- package/dist/lifeline-m7laIzIP.cjs.map +0 -1
- package/dist/lifeline.d.mts.map +0 -1
- package/dist/logFile-C7oQ_v-g.d.mts.map +0 -1
- package/dist/logFile-CnPKtxPy.cjs +0 -67
- package/dist/logFile-CnPKtxPy.cjs.map +0 -1
- package/dist/logFile-XcDHBwu1.mjs +0 -60
- package/dist/logFile-XcDHBwu1.mjs.map +0 -1
- package/dist/logReader-DHCK2BEr.cjs.map +0 -1
- package/dist/logReader-mq9uVurh.mjs.map +0 -1
- package/dist/ptyHost-CwbLLr90.mjs.map +0 -1
- package/dist/ptyHost-D35hNmtd.cjs.map +0 -1
- package/dist/reconcile-5cZ11jSD.cjs.map +0 -1
- package/dist/reconcile-wNYQJZF-.mjs.map +0 -1
- package/dist/rmuxBackend-CaEWooWn.d.mts.map +0 -1
- package/dist/rmuxBackend-Dh0CYVAL.cjs.map +0 -1
- package/dist/rmuxBackend-rjrVTG6K.mjs.map +0 -1
- package/dist/rtkProcessor-DSGbM-Cm.cjs.map +0 -1
- package/dist/rtkProcessor-Iw9gP5Xp.mjs.map +0 -1
- package/dist/runnerDependencies-7h_cxOva.mjs.map +0 -1
- package/dist/runnerDependencies-DSun3xO-.cjs.map +0 -1
- package/dist/runnerPaths-B41rMOY6.cjs.map +0 -1
- package/dist/runnerPaths-Dibbvyx_.mjs.map +0 -1
- package/dist/runnerRegistry-BgaR5O86.mjs.map +0 -1
- package/dist/runnerRegistry-dQYlMSpQ.cjs.map +0 -1
- package/dist/session-BKYnH4R6.mjs +0 -18
- package/dist/session-BKYnH4R6.mjs.map +0 -1
- package/dist/session-BvqzhXZY.cjs +0 -29
- package/dist/session-BvqzhXZY.cjs.map +0 -1
- package/dist/session-DE2Acesp.mjs +0 -6
- package/dist/session-DE2Acesp.mjs.map +0 -1
- package/dist/session-SfIPtdZO.cjs +0 -11
- package/dist/session-SfIPtdZO.cjs.map +0 -1
- package/dist/type-DwMZoINK.d.mts.map +0 -1
- package/src/prompts/po-use-runner/SKILL.md +0 -47
package/dist/extensions/mcp.cjs
CHANGED
|
@@ -26,34 +26,45 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
26
26
|
//#endregion
|
|
27
27
|
let _agimon_ai_po_core_mcpFacet = require("@agimon-ai/po-core/mcpFacet");
|
|
28
28
|
let _agimon_ai_po_core_serverPlugin = require("@agimon-ai/po-core/serverPlugin");
|
|
29
|
+
require("@agimon-ai/po-core/codemode");
|
|
30
|
+
require("@agimon-ai/po-core/locale");
|
|
31
|
+
require("@agimon-ai/po-core/platform");
|
|
32
|
+
require("@agimon-ai/po-core/telemetry");
|
|
33
|
+
require("@agimon-ai/po-core/workflow");
|
|
29
34
|
let typebox = require("typebox");
|
|
35
|
+
let node_child_process = require("node:child_process");
|
|
30
36
|
require("@agimon-ai/po-core/packageApi");
|
|
31
37
|
let _xterm_headless = require("@xterm/headless");
|
|
32
38
|
_xterm_headless = __toESM(_xterm_headless, 1);
|
|
33
39
|
require("@rmux/sdk");
|
|
34
|
-
let node_child_process = require("node:child_process");
|
|
35
|
-
require("@agimon-ai/po-core/piSettings");
|
|
36
40
|
let node_util = require("node:util");
|
|
37
41
|
require("@agimon-ai/foundation-process-registry");
|
|
38
|
-
require("@agimon-ai/po-core/childProcess");
|
|
39
42
|
require("@agimon-ai/po-core/backgroundWork");
|
|
43
|
+
require("typebox/value");
|
|
44
|
+
require("@agimon-ai/po-core/childProcess");
|
|
40
45
|
require("@agimon-ai/po-core/extensionFile");
|
|
41
|
-
require("@agimon-ai/po-telemetry");
|
|
42
46
|
require("@earendil-works/pi-coding-agent");
|
|
43
|
-
//#region src/extensions/workspaces/sessions/(backend)/skill/
|
|
44
|
-
var
|
|
45
|
-
name: "
|
|
47
|
+
//#region src/extensions/workspaces/sessions/(backend)/skill/help-how-to-runner.mcp.ts
|
|
48
|
+
var help_how_to_runner_mcp_default = (0, _agimon_ai_po_core_mcpFacet.defineMcpSkill)({
|
|
49
|
+
name: "help-how-to-runner",
|
|
46
50
|
description: "Use Po Pi Runner to supervise shell commands, inspect durable logs, provide interactive input, and stop background runs.",
|
|
47
|
-
read: () => (0, _agimon_ai_po_core_serverPlugin.readPackageResource)(require("url").pathToFileURL(__filename).href, "src/prompts/
|
|
51
|
+
read: () => (0, _agimon_ai_po_core_serverPlugin.readPackageResource)(require("url").pathToFileURL(__filename).href, "src/prompts/help-how-to-runner/SKILL.md")
|
|
48
52
|
});
|
|
49
53
|
//#endregion
|
|
50
54
|
//#region src/constants/runnerSettings.ts
|
|
51
55
|
const RATIO_KEYS = ["headRatio", "errorBudgetRatio"];
|
|
52
56
|
typebox.Type.Object({
|
|
53
|
-
command: typebox.Type.String({
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
+
command: typebox.Type.Array(typebox.Type.String({
|
|
58
|
+
minLength: 1,
|
|
59
|
+
maxLength: 65536
|
|
60
|
+
}), {
|
|
61
|
+
minItems: 1,
|
|
62
|
+
maxItems: 32,
|
|
63
|
+
description: "Bash commands to run in order, stopping on first failure. Use a one-item array for one command. Each command gets a full log; return all log paths and only the last executed result. Do not pipe or redirect output to a file, head, or tail. Logs are saved automatically and returned output is bounded."
|
|
64
|
+
}),
|
|
65
|
+
timeout: typebox.Type.Optional(typebox.Type.Number({ description: "Timeout in seconds for each command (optional, no default timeout)" })),
|
|
66
|
+
background: typebox.Type.Optional(typebox.Type.Boolean({ description: "Start a long-lived service (dev server, watcher) in the background immediately. Nothing waits for it and you are not woken when it exits. Omit for tests and builds, even slow ones: they move to the background after 60 seconds on their own and wake you when they finish." })),
|
|
67
|
+
interactive: typebox.Type.Optional(typebox.Type.Boolean({ description: "Run only the last command under a pseudo terminal when it needs input. Earlier commands are noninteractive. Send input to the last stage runner ID with runner.input in code mode, or po-runner input without code mode." })),
|
|
57
68
|
name: typebox.Type.Optional(typebox.Type.String({ description: "Preferred runner name if the command ends up in the background. A name in use gets a suffix." }))
|
|
58
69
|
});
|
|
59
70
|
new RegExp([
|
|
@@ -73,6 +84,7 @@ new RegExp([
|
|
|
73
84
|
/** Enough history for the overlay to scroll without holding a whole build. */
|
|
74
85
|
const { Terminal: HeadlessTerminal } = _xterm_headless.default;
|
|
75
86
|
(0, node_util.promisify)(node_child_process.execFile);
|
|
87
|
+
(0, node_util.promisify)(node_child_process.execFile);
|
|
76
88
|
//#endregion
|
|
77
89
|
//#region src/services/runnerSettings/index.ts
|
|
78
90
|
const COUNT_KEYS = [
|
|
@@ -96,7 +108,7 @@ var bash_mcp_default = (0, _agimon_ai_po_core_mcpFacet.defineMcpTool)((context)
|
|
|
96
108
|
if (!scope) throw new Error("Runner session service is unavailable.");
|
|
97
109
|
return {
|
|
98
110
|
...scope.remoteTool,
|
|
99
|
-
description: "Run
|
|
111
|
+
description: "Run an array of shell commands (bash, terminal, CLI) in the Po session's repository on the host machine, not on your local machine. Use a one-item array for one command. Commands run in order and stop on first failure. Only the last command may be interactive. Do not pipe or redirect output to a file, head, or tail: full logs are saved automatically and returned output is bounded. Long-running commands return a sequence id. No completion notice reaches you, so check with `po-runner status <id>` and `po-runner logs <id> --lines 100` instead of relaunching.",
|
|
100
112
|
async execute(toolCallId, parameters, signal, onUpdate, execution) {
|
|
101
113
|
const result = await scope.remoteTool.execute(toolCallId, parameters, AbortSignal.any([context.signal, signal ?? context.signal]), onUpdate, execution);
|
|
102
114
|
const details = result.details;
|
|
@@ -114,9 +126,17 @@ var bash_mcp_default = (0, _agimon_ai_po_core_mcpFacet.defineMcpTool)((context)
|
|
|
114
126
|
//#endregion
|
|
115
127
|
//#region generated/mcp.ts
|
|
116
128
|
const at = (value, context) => typeof value === "function" ? value(context) : value;
|
|
117
|
-
const via = (identity, value) =>
|
|
118
|
-
|
|
119
|
-
|
|
129
|
+
const via = (identity, value) => {
|
|
130
|
+
if (value === void 0) return void 0;
|
|
131
|
+
const declaration = value;
|
|
132
|
+
return {
|
|
133
|
+
...identity,
|
|
134
|
+
...declaration,
|
|
135
|
+
...declaration.relations === void 0 ? {} : { relations: declaration.relations.map((relation) => ({
|
|
136
|
+
evidence: "declared",
|
|
137
|
+
...relation
|
|
138
|
+
})) }
|
|
139
|
+
};
|
|
120
140
|
};
|
|
121
141
|
const withWidget = (key, value) => value === void 0 ? value : {
|
|
122
142
|
...value,
|
|
@@ -129,7 +149,7 @@ const mcp = (0, _agimon_ai_po_core_mcpFacet.defineMcpPlugin)({
|
|
|
129
149
|
name: "@agimon-ai/po-runner",
|
|
130
150
|
session: (context) => ({
|
|
131
151
|
get skills() {
|
|
132
|
-
return [at(
|
|
152
|
+
return [at(help_how_to_runner_mcp_default, context)];
|
|
133
153
|
},
|
|
134
154
|
get tools() {
|
|
135
155
|
return [withWidget("@agimon-ai/po-runner/bash", via({ name: "bash" }, at(bash_mcp_default, context)))];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mcp.cjs","names":["defineMcpSkill","readPackageResource","Type","headless","promisify","execFile","defineMcpTool","defineMcpPlugin","skillPoUseRunner","toolBash"],"sources":["../../src/extensions/workspaces/sessions/(backend)/skill/po-use-runner.mcp.ts","../../src/constants/runnerSettings.ts","../../src/schemas/bashTool.ts","../../src/services/ansiScrub/index.ts","../../src/services/ptyHost/index.ts","../../src/services/runnerRegistry/index.ts","../../src/services/runnerSettings/index.ts","../../src/extensions/workspaces/sessions/(backend)/_lib/serverRoot.ts","../../src/extensions/workspaces/sessions/(backend)/tool/bash.mcp.ts","../../generated/mcp.ts"],"sourcesContent":["import { defineMcpSkill } from '@agimon-ai/po-core/mcpFacet';\nimport { readPackageResource } from '@agimon-ai/po-core/serverPlugin';\n\nexport default defineMcpSkill({\n name: 'po-use-runner',\n description:\n 'Use Po Pi Runner to supervise shell commands, inspect durable logs, provide interactive input, and stop background runs.',\n read: () => readPackageResource(import.meta.url, 'src/prompts/po-use-runner/SKILL.md'),\n});\n","export const RUNNER_SETTINGS_FILE = 'po-runner.json';\nexport const RATIO_KEYS = ['headRatio', 'errorBudgetRatio'] as const;\nexport const MAX_RESULT_BYTES_CEILING = 262_144;\nexport const MAX_RESULT_LINES_CEILING = 5_000;\nexport const MAX_RESULT_TOKENS_CEILING = 100_000;\nexport const MAX_ERROR_ENTRIES_CEILING = 100;\nexport const MAX_PATTERNS = 32;\nexport const MAX_PATTERN_LENGTH = 512;\n","import { type Static, Type } from 'typebox';\n\n/** Replaces pi's built-in tool of the same name, so hooks keyed on `bash` keep working. */\n\n/**\n * Built-in bash parameters plus the backgrounding controls.\n *\n * `command` and `timeout` keep their original names and wording so the tool is\n * a drop-in replacement. Every `description` is prompt copy the model reads.\n */\nexport const BashParamsSchema = Type.Object({\n command: Type.String({ description: 'Bash command to execute' }),\n timeout: Type.Optional(Type.Number({ description: 'Timeout in seconds (optional, no default timeout)' })),\n background: Type.Optional(\n Type.Boolean({\n description:\n 'Start the command in the background immediately instead of waiting. Use for dev servers, watchers and other commands you already know will not finish.',\n }),\n ),\n interactive: Type.Optional(\n Type.Boolean({\n description:\n 'Run under a pseudo terminal so the command can prompt. Use only when the command asks for confirmation or input; answer it with po-runner input. Logs from interactive runs are noisier.',\n }),\n ),\n name: Type.Optional(\n Type.String({\n description: 'Preferred runner name if the command ends up in the background. A name in use gets a suffix.',\n }),\n ),\n});\n\nexport type BashParams = Static<typeof BashParamsSchema>;\n","import { CONTROL_PATTERN } from '../../constants/ansiScrub';\n/**\n * Turns terminal output into text worth grepping.\n *\n * PTY output is written for a screen, not a file: colours, cursor moves and\n * carriage-return redraws all end up in the byte stream. Without this a single\n * progress bar becomes thousands of near-identical log lines.\n */\n\n/**\n * CSI sequences (colours, cursor moves), OSC strings, the two-byte Fe escapes,\n * and the keypad-mode escapes shells emit around every prompt.\n */\nconst ANSI_PATTERN = new RegExp(\n [\n '\\\\u001B\\\\[[0-9;?]*[ -/]*[@-~]',\n '\\\\u001B\\\\][^\\\\u0007\\\\u001B]*(?:\\\\u0007|\\\\u001B\\\\\\\\)',\n '\\\\u001B[@-Z\\\\\\\\-_]',\n '\\\\u001B[=><]',\n ].join('|'),\n 'g',\n);\n\n/** Bell and backspace, which a terminal consumes rather than displays. */\n// oxlint-disable-next-line no-control-regex -- matching terminal control bytes is the whole job\n\n/**\n * The same set minus SGR, the sequence that only sets colour and weight.\n *\n * The final byte class omits `m`, so `ESC[32m` survives while cursor moves,\n * OSC strings and keypad escapes are still removed.\n */\nconst ANSI_PATTERN_KEEPING_COLOUR = new RegExp(\n [\n '\\\\u001B\\\\[[0-9;?]*[ -/]*[@-ln-~]',\n '\\\\u001B\\\\][^\\\\u0007\\\\u001B]*(?:\\\\u0007|\\\\u001B\\\\\\\\)',\n '\\\\u001B[@-Z\\\\\\\\-_]',\n '\\\\u001B[=><]',\n ].join('|'),\n 'g',\n);\n\n/** Removes escape sequences, leaving the characters a user would have seen. */\nexport function stripAnsi(text: string): string {\n return text.replace(ANSI_PATTERN, '').replace(CONTROL_PATTERN, '');\n}\n\n/**\n * Removes everything `stripAnsi` does except colour.\n *\n * Logs are read back by a terminal renderer as well as by grep, and a command\n * that colours its own output has already said how it should look.\n */\nexport function stripAnsiKeepingColour(text: string): string {\n return text.replace(ANSI_PATTERN_KEEPING_COLOUR, '').replace(CONTROL_PATTERN, '');\n}\n\n/**\n * Collapses carriage-return redraws.\n *\n * A bare `\\r` returns the cursor to the start of the current line, so whatever\n * follows overwrites it. Only the final state of each line is kept. The `\\r` of\n * a CRLF pair is a line terminator rather than a redraw, so it is normalised\n * away first: a pseudo terminal ends every line that way, and treating it as a\n * redraw would blank the whole log.\n */\nexport function collapseCarriageReturns(text: string): string {\n return text\n .replace(/\\r\\n/g, '\\n')\n .split('\\n')\n .map((line) => (line.includes('\\r') ? (line.split('\\r').at(-1) ?? '') : line))\n .join('\\n');\n}\n\n/** Full scrub applied to PTY output before it reaches the log file. */\nexport function scrubTerminalOutput(text: string): string {\n return collapseCarriageReturns(stripAnsiKeepingColour(text));\n}\n\n/** Plain-text scrub, for the copy the model reads. */\nexport function scrubTerminalOutputToPlainText(text: string): string {\n return collapseCarriageReturns(stripAnsi(text));\n}\n","import headless, { type Terminal } from '@xterm/headless';\n\nimport {\n DEFAULT_COLS,\n DEFAULT_ROWS,\n LIVENESS_POLL_MS,\n MEMORY_BUFFER_FACTOR,\n NEWLINE,\n SCROLLBACK,\n TERM_GRACE_MS,\n} from '../../constants/ptyHost';\nimport { PI_SESSION_ID_ENV } from '../../constants/session';\nimport type { IClock } from '../../types/clock';\nimport type { ILogFile } from '../../types/logFile';\nimport type { IProcessControl } from '../../types/processControl';\nimport type { IPtyHost, PtyLaunchRequest, PtyRun } from '../../types/ptyHost';\nimport type { IPtySpawner, PtyProcess } from '../../types/ptySpawner';\nimport type { RunnerSettings } from '../../types/runnerSettings';\nimport type { ExitResult } from '../../types/spawner';\nimport { scrubTerminalOutput } from '../ansiScrub';\nimport { getResultMaxBytes } from '../runnerConfig';\nimport { NO_TERMINAL_INPUT_ENV } from '../runnerSupervisor';\n\n/** Enough history for the overlay to scroll without holding a whole build. */\n\n// Use the CommonJS default export: Node cannot detect this package's named exports.\n// A static import also lets server bundles include it without a live node_modules lookup.\nconst { Terminal: HeadlessTerminal } = headless;\n\nexport class PtyHost implements IPtyHost {\n private readonly runs = new Map<string, PtyRun>();\n\n constructor(\n private readonly spawner: IPtySpawner,\n private readonly logFile: ILogFile,\n private readonly processControl: IProcessControl,\n private readonly clock: IClock,\n private readonly environment: Readonly<Record<string, string | undefined>> = process.env,\n private readonly settings?: RunnerSettings,\n ) {}\n\n async launch(request: PtyLaunchRequest): Promise<PtyRun> {\n const cols = request.cols ?? DEFAULT_COLS;\n const rows = request.rows ?? DEFAULT_ROWS;\n const writer = this.logFile.open(request.id);\n const terminal = new HeadlessTerminal({ cols, rows, scrollback: SCROLLBACK, allowProposedApi: true });\n const memoryLimit = getResultMaxBytes(this.environment, this.settings) * MEMORY_BUFFER_FACTOR;\n\n const child = await this.spawner.spawn({\n command: request.command,\n cwd: request.cwd,\n env: { ...this.environment, ...NO_TERMINAL_INPUT_ENV, [PI_SESSION_ID_ENV]: request.sessionId },\n cols,\n rows,\n });\n\n let buffer = '';\n let buffering = true;\n let settled = false;\n let resolveCompletion: (result: ExitResult) => void = () => undefined;\n const completion = new Promise<ExitResult>((resolve) => {\n resolveCompletion = resolve;\n });\n const dataHandlers = new Set<(data: string) => void>();\n\n child.onData((data) => {\n // The terminal keeps the screen; the log keeps text worth grepping.\n terminal.write(data);\n const scrubbed = scrubTerminalOutput(data);\n writer.append(scrubbed);\n if (buffering) {\n buffer += scrubbed;\n if (buffer.length > memoryLimit) buffer = buffer.slice(-memoryLimit);\n }\n for (const handler of dataHandlers) handler(data);\n });\n\n child.onExit((result) => {\n if (settled) return;\n settled = true;\n this.runs.delete(request.name);\n writer.close();\n resolveCompletion({ code: result.exitCode, signal: null });\n });\n\n const run: PtyRun = {\n id: request.id,\n name: request.name,\n pid: child.pid,\n logPath: writer.path,\n backend: 'native',\n output: () => buffer,\n completion: () => completion,\n detach: () => {\n buffering = false;\n buffer = '';\n },\n stop: () => this.stopChild(child, request.name),\n write: (text) => child.write(text),\n screen: () => renderScreen(terminal),\n onData: (handler) => {\n dataHandlers.add(handler);\n return () => dataHandlers.delete(handler);\n },\n resize: (nextCols, nextRows) => {\n child.resize(nextCols, nextRows);\n terminal.resize(nextCols, nextRows);\n },\n };\n\n this.runs.set(request.name, run);\n return run;\n }\n\n get(name: string): PtyRun | undefined {\n return this.runs.get(name);\n }\n\n write(name: string, text: string): boolean {\n const run = this.runs.get(name);\n if (!run) return false;\n run.write(text.endsWith(NEWLINE) ? text : `${text}${NEWLINE}`);\n return true;\n }\n\n list(): PtyRun[] {\n return [...this.runs.values()];\n }\n\n async disposeAll(): Promise<void> {\n const runs = [...this.runs.values()];\n this.runs.clear();\n for (const run of runs) await run.stop();\n }\n\n private async stopChild(child: PtyProcess, name: string): Promise<boolean> {\n this.runs.delete(name);\n if (!this.processControl.isAlive(child.pid)) return false;\n\n child.kill('SIGTERM');\n const deadline = this.clock.now() + TERM_GRACE_MS;\n while (this.clock.now() < deadline) {\n if (!this.processControl.isAlive(child.pid)) return true;\n await new Promise<void>((resolve) => {\n this.clock.after(LIVENESS_POLL_MS, resolve);\n });\n }\n child.kill('SIGKILL');\n return true;\n }\n}\n\n/** The visible rows, trimmed of trailing blanks, as plain text. */\nfunction renderScreen(terminal: Terminal): string {\n const buffer = terminal.buffer.active;\n const lines: string[] = [];\n for (let row = buffer.baseY; row < buffer.baseY + terminal.rows; row += 1) {\n lines.push(buffer.getLine(row)?.translateToString(true) ?? '');\n }\n while (lines.length > 0 && lines.at(-1) === '') lines.pop();\n return lines.join(NEWLINE);\n}\n","import { execFile } from 'node:child_process';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { promisify } from 'node:util';\n\nimport {\n createProcessRegistryService,\n normalizeRepositoryPath,\n type ProcessRegistryRecord,\n type ProcessRegistryService,\n resolveProcessTags,\n} from '@agimon-ai/foundation-process-registry';\nimport { resolveRootSessionId } from '@agimon-ai/po-core/childProcess';\n\nimport {\n COMMAND_SIDECAR_SUFFIX,\n EXIT_SIDECAR_SUFFIX,\n JSON_EXTENSION,\n NOT_FOUND_ERROR_CODE,\n REGISTRY_PATH_ENV,\n RUNNER_TAG,\n SERVICE_PREFIX,\n SERVICE_TYPE,\n} from '../../constants/runnerRegistry';\nimport type { IProcessControl } from '../../types/processControl';\nimport type {\n CompleteRunnerInput,\n IRunnerRegistry,\n RegisterRunnerInput,\n RunnerRecord,\n RunnerTerminationIntent,\n} from '../../types/runnerRegistry';\nimport type { IRunnerPaths } from '../runnerPaths/type';\nimport { isRunnerRecord } from '../runnerRecord';\n\n/** The slice of the shared registry service this wrapper depends on. */\nexport type ProcessRegistryPort = Pick<\n ProcessRegistryService,\n 'registerProcess' | 'releaseProcess' | 'listProcesses' | 'close'\n>;\n\n/** Opens the SQLite-backed registry the rest of the monorepo already shares. */\nexport function createDefaultProcessRegistry(\n env: Readonly<Record<string, string | undefined>> = process.env,\n): ProcessRegistryPort {\n return createProcessRegistryService(env[REGISTRY_PATH_ENV]);\n}\n\nfunction sessionTag(sessionId: string): string {\n return `session:${sessionId}`;\n}\n\nfunction readString(record: ProcessRegistryRecord, key: string): string {\n const value = record.metadata?.[key];\n return typeof value === 'string' ? value : '';\n}\n\nfunction readNumber(record: ProcessRegistryRecord, key: string): number {\n const value = record.metadata?.[key];\n return typeof value === 'number' ? value : 0;\n}\n\nconst runCommand = promisify(execFile);\n\n/**\n * The process start time the registry stores to prove a pid is still the\n * process it registered.\n *\n * The registry resolves it itself when the caller omits it, and it does so with\n * `execFileSync`, which stops this process for the length of a `ps` on every\n * runner that starts. Reading it here costs the same subprocess and blocks\n * nothing: the command is already running by the time a runner is registered.\n *\n * The value has to match what the registry would have read, so the command and\n * the trimming are deliberately identical to its own.\n */\nasync function processStartedAt(pid: number): Promise<string | undefined> {\n if (process.platform === 'win32') return undefined;\n try {\n const { stdout } = await runCommand('ps', ['-o', 'lstart=', '-p', String(pid)], { encoding: 'utf8' });\n return stdout.trim() || undefined;\n } catch {\n return undefined;\n }\n}\n\ntype ListenerRegistration = Readonly<{ key: string; listener: () => void }>;\n\n// Server plugin replacement can leave an in-flight tool and its publisher on different registry instances.\nconst listenersBySession = new Map<string, Set<() => void>>();\n\nexport class RunnerRegistry implements IRunnerRegistry {\n private readonly subscriptions = new Set<ListenerRegistration>();\n\n constructor(\n private readonly paths: IRunnerPaths,\n private readonly processControl: IProcessControl,\n private readonly registry: ProcessRegistryPort,\n private readonly environment: Readonly<Record<string, string | undefined>>,\n ) {}\n\n async register(input: RegisterRunnerInput): Promise<RunnerRecord> {\n const startedAt = new Date().toISOString();\n const rootSessionId = resolveRootSessionId(input.sessionId, this.environment);\n const identity = await processStartedAt(input.pid);\n const response = await this.registry.registerProcess({\n repositoryPath: this.repositoryPath(),\n serviceName: `${SERVICE_PREFIX}${input.id}`,\n serviceType: SERVICE_TYPE,\n pid: input.pid,\n command: input.command,\n ...(identity === undefined ? {} : { processStartedAt: identity }),\n tags: resolveProcessTags([RUNNER_TAG, `runner:${input.id}`, sessionTag(input.sessionId)]),\n metadata: {\n id: input.id,\n name: input.name,\n command: input.command,\n cwd: input.cwd,\n logPath: input.logPath,\n interactive: input.interactive,\n sessionId: input.sessionId,\n rootSessionId,\n backend: input.backend,\n ...(input.backendTarget ? { backendTarget: input.backendTarget } : {}),\n startedAt,\n hostPid: process.pid,\n },\n // The caller has already resolved name collisions against live records,\n // so anything still holding this name is stale.\n force: true,\n });\n if (!response.success) throw new Error(response.error ?? `Failed to register runner ${input.name}`);\n const record: RunnerRecord = {\n id: input.id,\n name: input.name,\n pid: input.pid,\n command: input.command,\n cwd: input.cwd,\n logPath: input.logPath,\n interactive: input.interactive,\n sessionId: input.sessionId,\n rootSessionId,\n startedAt,\n state: 'running',\n promoted: false,\n backend: input.backend,\n ...(input.backendTarget ? { backendTarget: input.backendTarget } : {}),\n hostPid: process.pid,\n };\n this.writeRecord(record);\n this.notify(record.sessionId);\n return record;\n }\n\n async list(): Promise<RunnerRecord[]> {\n const records = await this.registry.listProcesses({\n repositoryPath: this.repositoryPath(),\n serviceType: SERVICE_TYPE,\n tags: resolveProcessTags([RUNNER_TAG]),\n });\n return records.map(toRunnerRecord);\n }\n\n async listBySession(sessionId: string): Promise<RunnerRecord[]> {\n const records = await this.list();\n return records.filter((record) => record.sessionId === sessionId);\n }\n\n async listByRootSession(rootSessionId: string): Promise<RunnerRecord[]> {\n const records = await this.list();\n return records.filter((record) => (record.rootSessionId ?? record.sessionId) === rootSessionId);\n }\n\n async listAll(sessionId?: string): Promise<RunnerRecord[]> {\n this.paths.ensureDirectories(sessionId);\n const records: RunnerRecord[] = [];\n const directory = this.paths.stateDirectory(sessionId);\n for (const entry of fs.readdirSync(directory)) {\n if (!isPrimaryMetadataEntry(entry)) continue;\n try {\n const parsed: unknown = JSON.parse(fs.readFileSync(`${directory}/${entry}`, 'utf8'));\n if (isRunnerRecord(parsed)) records.push(parsed);\n } catch (error) {\n process.emitWarning(`Could not read runner metadata ${entry}: ${String(error)}`);\n }\n }\n return records.sort((left, right) => right.startedAt.localeCompare(left.startedAt));\n }\n\n async get(id: string, sessionId?: string): Promise<RunnerRecord | undefined> {\n const target = this.paths.statePathFor(id, sessionId);\n try {\n const parsed: unknown = JSON.parse(fs.readFileSync(target, 'utf8'));\n if (!isRunnerRecord(parsed) || parsed.id !== id) {\n process.emitWarning(`Could not read runner metadata ${path.basename(target)}: invalid runner record`);\n return undefined;\n }\n return parsed;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === NOT_FOUND_ERROR_CODE) return undefined;\n process.emitWarning(`Could not read runner metadata ${path.basename(target)}: ${String(error)}`);\n return undefined;\n }\n }\n\n async markPromoted(id: string): Promise<RunnerRecord | undefined> {\n const record = await this.get(id);\n if (!record) return undefined;\n const promoted = { ...record, promoted: true };\n this.writeRecord(promoted);\n this.notify(promoted.sessionId);\n return promoted;\n }\n\n async requestTermination(\n id: string,\n intent: RunnerTerminationIntent | undefined,\n sessionId?: string,\n ): Promise<RunnerRecord | undefined> {\n const record = await this.get(id, sessionId);\n if (!record) return undefined;\n if (record.state === 'completed') return record;\n if (intent !== undefined && record.terminationIntent !== undefined) return record;\n const { terminationIntent: _previous, ...rest } = record;\n const updated: RunnerRecord = { ...rest, ...(intent ? { terminationIntent: intent } : {}) };\n this.writeRecord(updated);\n return updated;\n }\n\n async complete(id: string, outcome: CompleteRunnerInput, sessionId?: string): Promise<RunnerRecord | undefined> {\n const persisted = await this.get(id, sessionId);\n if (persisted?.state === 'completed') {\n await this.release(id, persisted.sessionId);\n return persisted;\n }\n const active = await this.list();\n const record =\n persisted ??\n active.find((candidate) => candidate.id === id && (sessionId === undefined || candidate.sessionId === sessionId));\n if (!record) {\n const belongsToAnotherSession =\n sessionId !== undefined && active.some((candidate) => candidate.id === id && candidate.sessionId !== sessionId);\n if (!belongsToAnotherSession) await this.release(id, sessionId);\n return undefined;\n }\n const completed: RunnerRecord = {\n ...record,\n state: 'completed',\n exit: {\n ...outcome,\n ...(outcome.signal !== null && outcome.terminationReason === undefined && record.terminationIntent === undefined\n ? { terminationReason: 'external_signal' as const }\n : {}),\n ...record.terminationIntent,\n finishedAt: new Date().toISOString(),\n },\n };\n this.writeRecord(completed);\n await this.release(id, completed.sessionId);\n return completed;\n }\n\n async release(id: string, sessionId?: string): Promise<void> {\n const activeSessionId = sessionId ?? (await this.list()).find((record) => record.id === id)?.sessionId;\n const ownedSessionId = activeSessionId ?? (await this.get(id))?.sessionId;\n const response = await this.registry.releaseProcess({\n repositoryPath: this.repositoryPath(),\n serviceName: `${SERVICE_PREFIX}${id}`,\n serviceType: SERVICE_TYPE,\n kill: false,\n releasePort: false,\n force: true,\n });\n if (!response.success && !response.error?.includes('No matching process entry')) {\n throw new Error(response.error ?? `Failed to release runner ${id}`);\n }\n if (ownedSessionId !== undefined) this.notify(ownedSessionId);\n }\n\n async pruneDead(): Promise<string[]> {\n const dead = (await this.list()).filter((record) => !this.processControl.isAlive(record.pid));\n for (const record of dead) {\n await this.complete(record.id, { reason: 'backend_lost', code: null, signal: null }, record.sessionId);\n }\n return dead.map((record) => record.id);\n }\n\n subscribe(listener: () => void, sessionId: string): () => void {\n const subscribed = (): void => listener();\n const registration = { key: this.subscriptionKey(sessionId), listener: subscribed };\n const listeners = listenersBySession.get(registration.key) ?? new Set<() => void>();\n listeners.add(subscribed);\n listenersBySession.set(registration.key, listeners);\n this.subscriptions.add(registration);\n return () => this.removeSubscription(registration);\n }\n\n close(): void {\n for (const registration of this.subscriptions) this.removeSubscription(registration);\n this.registry.close();\n }\n\n private notify(sessionId: string): void {\n for (const listener of listenersBySession.get(this.subscriptionKey(sessionId)) ?? []) {\n try {\n listener();\n } catch (error) {\n process.emitWarning(`Runner registry listener failed: ${String(error)}`);\n }\n }\n }\n\n private removeSubscription(registration: ListenerRegistration): void {\n const listeners = listenersBySession.get(registration.key);\n listeners?.delete(registration.listener);\n if (listeners?.size === 0) listenersBySession.delete(registration.key);\n this.subscriptions.delete(registration);\n }\n\n private subscriptionKey(sessionId: string): string {\n return JSON.stringify([path.resolve(this.paths.stateDirectory(sessionId)), sessionId]);\n }\n\n private repositoryPath(): string {\n return normalizeRepositoryPath(this.paths.repositoryPath());\n }\n\n private writeRecord(record: RunnerRecord): void {\n this.paths.ensureDirectories(record.sessionId);\n const target = this.paths.statePathFor(record.id, record.sessionId);\n const temporary = `${target}.${process.pid}.tmp`;\n fs.writeFileSync(temporary, `${JSON.stringify(record, null, 2)}\\n`, 'utf8');\n fs.renameSync(temporary, target);\n }\n}\n\n/** Every field is read back from metadata this class wrote on registration. */\nfunction toRunnerRecord(record: ProcessRegistryRecord): RunnerRecord {\n return {\n id: readString(record, 'id'),\n name: readString(record, 'name'),\n pid: record.pid,\n command: readString(record, 'command'),\n cwd: readString(record, 'cwd'),\n logPath: readString(record, 'logPath'),\n interactive: record.metadata?.interactive === true,\n sessionId: readString(record, 'sessionId'),\n ...(readString(record, 'rootSessionId') ? { rootSessionId: readString(record, 'rootSessionId') } : {}),\n startedAt: readString(record, 'startedAt'),\n state: 'running',\n promoted: false,\n backend: readBackend(record.metadata?.backend),\n ...(readString(record, 'backendTarget') ? { backendTarget: readString(record, 'backendTarget') } : {}),\n hostPid: readNumber(record, 'hostPid'),\n };\n}\n\nfunction readBackend(value: unknown): RunnerRecord['backend'] {\n return value === 'rmux' || value === 'tmux' ? value : 'native';\n}\n\nfunction isPrimaryMetadataEntry(entry: string): boolean {\n return (\n entry.endsWith(JSON_EXTENSION) && !entry.endsWith(COMMAND_SIDECAR_SUFFIX) && !entry.endsWith(EXIT_SIDECAR_SUFFIX)\n );\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\n\nimport { CONFIG_DIR_NAME } from '@earendil-works/pi-coding-agent';\n\nimport {\n MAX_ERROR_ENTRIES_CEILING,\n MAX_PATTERNS,\n MAX_PATTERN_LENGTH,\n MAX_RESULT_BYTES_CEILING,\n MAX_RESULT_LINES_CEILING,\n MAX_RESULT_TOKENS_CEILING,\n RATIO_KEYS,\n RUNNER_SETTINGS_FILE,\n} from '../../constants/runnerSettings';\nimport type { IRunnerSettingsLoader, RunnerSettings, RunnerSettingsLoad } from '../../types/runnerSettings';\n\n/** Pi's convention is one JSON file per extension under the config directory. */\n\nconst EMPTY: RunnerSettingsLoad = { settings: {}, issues: [] };\nconst COUNT_KEYS = [\n 'maxResultBytes',\n 'maxResultLines',\n 'successMaxResultBytes',\n 'maxResultTokens',\n 'successMaxResultTokens',\n 'errorMaxEntries',\n 'errorMaxVariantsJoined',\n] as const;\nconst KNOWN_KEYS = new Set<string>([...RATIO_KEYS, ...COUNT_KEYS, 'errorPatterns']);\n/** Ceilings so a project file cannot flood the model's context. */\nconst CEILINGS: Readonly<Record<string, number>> = {\n maxResultBytes: MAX_RESULT_BYTES_CEILING,\n successMaxResultBytes: MAX_RESULT_BYTES_CEILING,\n maxResultTokens: MAX_RESULT_TOKENS_CEILING,\n successMaxResultTokens: MAX_RESULT_TOKENS_CEILING,\n maxResultLines: MAX_RESULT_LINES_CEILING,\n errorMaxEntries: MAX_ERROR_ENTRIES_CEILING,\n errorMaxVariantsJoined: MAX_ERROR_ENTRIES_CEILING,\n};\n\nexport class RunnerSettingsLoader implements IRunnerSettingsLoader {\n load(cwd: string, trusted: boolean): RunnerSettingsLoad {\n // Project-local configuration is untrusted input until the project is.\n if (!trusted) return EMPTY;\n\n let raw: string;\n try {\n raw = fs.readFileSync(path.join(cwd, CONFIG_DIR_NAME, RUNNER_SETTINGS_FILE), 'utf8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return EMPTY;\n return { settings: {}, issues: [`${RUNNER_SETTINGS_FILE} could not be read`] };\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return { settings: {}, issues: [`${RUNNER_SETTINGS_FILE} is not valid JSON`] };\n }\n return validate(parsed);\n }\n}\n\nfunction validate(parsed: unknown): RunnerSettingsLoad {\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n return { settings: {}, issues: [`${RUNNER_SETTINGS_FILE} must contain a JSON object`] };\n }\n\n const source = parsed as Record<string, unknown>;\n const settings: Record<string, unknown> = {};\n const issues: string[] = [];\n // A rejected key is reported rather than dropped: a silent typo reads as a\n // setting that simply does not work.\n for (const key of Object.keys(source)) if (!KNOWN_KEYS.has(key)) issues.push(`unknown key ${key}`);\n\n for (const key of COUNT_KEYS) {\n const value = source[key];\n if (value === undefined) continue;\n if (typeof value !== 'number' || !Number.isInteger(value) || value <= 0) {\n issues.push(`${key} must be a positive integer`);\n continue;\n }\n settings[key] = Math.min(value, CEILINGS[key] ?? value);\n }\n\n for (const key of RATIO_KEYS) {\n const value = source[key];\n if (value === undefined) continue;\n if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0 || value >= 1) {\n issues.push(`${key} must be a number above 0 and below 1`);\n continue;\n }\n settings[key] = value;\n }\n\n const patterns = source.errorPatterns;\n if (patterns !== undefined) {\n if (!Array.isArray(patterns) || patterns.some((entry) => typeof entry !== 'string')) {\n issues.push('errorPatterns must be an array of strings');\n } else {\n const accepted: string[] = [];\n for (const pattern of patterns.slice(0, MAX_PATTERNS) as string[]) {\n if (pattern.length > MAX_PATTERN_LENGTH) {\n issues.push('errorPatterns entry is too long');\n continue;\n }\n try {\n new RegExp(pattern, 'iu');\n accepted.push(pattern);\n } catch {\n issues.push(`errorPatterns entry is not a valid regular expression: ${pattern}`);\n }\n }\n if (accepted.length > 0) settings.errorPatterns = accepted;\n }\n }\n\n return { settings: settings as RunnerSettings, issues };\n}\n","import type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\nimport type { Context } from '@deepseek-ai/cordis';\n\nimport { REGISTRY_PATH_ENV } from '../../../../../constants/runnerRegistry';\nimport {\n HISTORY_SWEEP_INTERVAL_MS,\n RUNNER_FINISHED_MESSAGE,\n RUNNER_STATUS_POLL_MS,\n} from '../../../../../constants/runnerRuntime';\nimport { RUNNER_SETTINGS_FILE } from '../../../../../constants/runnerSettings';\nimport { SystemClock } from '../../../../../services/clock';\nimport { createHeadlessBashTool, createHeadlessRunnersCommand } from '../../../../../services/headless';\nimport { summarizeLog } from '../../../../../services/logReader';\nimport { createRunnerDependencies } from '../../../../../services/runnerDependencies';\nimport { createRunnerHost } from '../../../../../services/runnerHost';\nimport { createDefaultProcessRegistry } from '../../../../../services/runnerRegistry';\nimport { createRunnerServerRuntime } from '../../../../../services/runnerServerRuntime';\nimport { RunnerSettingsLoader } from '../../../../../services/runnerSettings';\n\nexport const RUNNER_SERVER_SCOPE_SERVICE = 'po/runner-server-scope';\n\ndeclare module '@deepseek-ai/cordis' {\n interface Context {\n 'po/runner-server-scope': RunnerServerScope;\n }\n}\n\nexport const createRunnerServerRoot = async ({ host, agent, signal, resources }: PoServerPluginContext) => {\n if (!host.context.directEvents) throw new Error('Runner server plugin requires the session direct event bus.');\n if (!host.context.cwd || !host.context.environment) {\n throw new Error('Runner server plugin requires session cwd and environment.');\n }\n // Inherit the current headless Pi bridge's isProjectTrusted: () => true.\n // This preserves runner configuration parity, not a new general trust policy.\n const loaded = new RunnerSettingsLoader().load(host.context.cwd, true);\n const settings = Object.freeze({\n ...loaded.settings,\n ...(loaded.settings.errorPatterns ? { errorPatterns: Object.freeze([...loaded.settings.errorPatterns]) } : {}),\n });\n for (const issue of loaded.issues) process.emitWarning(`${RUNNER_SETTINGS_FILE}: ${issue}`);\n const environment = host.context.environment;\n // One per registry for this build in the hub: every session shares the connection and the loop that\n // keeps house for it, and the last session to close disposes them.\n const runnerHost = await resources.acquire(\n ['runner-host', environment[REGISTRY_PATH_ENV] ?? null],\n () =>\n createRunnerHost({\n processRegistry: createDefaultProcessRegistry(environment),\n clock: new SystemClock(),\n statusPollMs: RUNNER_STATUS_POLL_MS,\n historySweepMs: HISTORY_SWEEP_INTERVAL_MS,\n onWarning: (message) => process.emitWarning(message),\n }),\n (shared) => shared.dispose(),\n );\n const dependencies = createRunnerDependencies({\n settings,\n cwd: host.context.cwd,\n environment,\n processRegistry: runnerHost.processRegistry,\n ...(host.context.executionBudget === undefined ? {} : { executionBudget: host.context.executionBudget }),\n });\n const execution = agent?.context;\n const wakeAgent =\n execution &&\n (async (content: string, requestId: string, notice: string): Promise<void> => {\n try {\n // 'steer' joins a running turn and starts one on an idle session.\n // Reuse completion identity across retries and acknowledge admission, not settlement.\n // A custom message, not a prompt: the model reads it as input, while the\n // transcript shows the notice as an event rather than as the person's words.\n if (!execution.session.admitMessage) throw new Error('The session cannot admit a runner notification.');\n await execution.session.admitMessage(\n { type: RUNNER_FINISHED_MESSAGE, text: content, display: true, details: { notice } },\n 'steer',\n requestId,\n );\n } catch (error) {\n // Keep completion ownership with the watcher until admission succeeds.\n await Promise.resolve()\n .then(() => execution.client.notify({ body: String(error), level: 'warning' }))\n .catch(() => undefined);\n throw error;\n }\n });\n const runtime = createRunnerServerRuntime(dependencies, runnerHost, host.context.directEvents, wakeAgent, execution);\n const bash = (wakeOnExit: boolean) =>\n createHeadlessBashTool(\n {\n run: async (request) => {\n await runtime.ensureSession(request.sessionId);\n const result = await dependencies.bashRunService.run({\n ...request,\n ...(signal ? { signal: request.signal ? AbortSignal.any([signal, request.signal]) : signal } : {}),\n });\n // Without this, nothing tells the agent the runner ended.\n if (wakeOnExit && result.kind === 'promoted') runtime.watchRunner(result.id);\n return result;\n },\n },\n (path, lines, bytes, tokens) => summarizeLog(path, lines, bytes, tokens, settings),\n settings,\n dependencies.environment,\n );\n const value = {\n tool: bash(true),\n // Remote MCP runners must not wake the local agent; the remote caller polls instead.\n remoteTool: bash(false),\n command: createHeadlessRunnersCommand(dependencies),\n recoverCompaction: runtime.recoverCompaction,\n };\n return {\n value,\n services: [\n runtime.backgroundWorkPlugin,\n (context: Context) => {\n context.plugin((providerContext) => providerContext.provide(RUNNER_SERVER_SCOPE_SERVICE, value));\n },\n ],\n activities: [runtime.activity],\n // Package install is on the session-create path; bash awaits supervision itself.\n onStart: execution\n ? () => {\n void runtime\n .ensureSession(execution.sessionId)\n .catch((error: unknown) =>\n process.emitWarning(`Could not initialize headless runner supervision: ${String(error)}`),\n );\n }\n : undefined,\n onStop: runtime.dispose,\n };\n};\n\nexport type RunnerServerScope = Awaited<ReturnType<typeof createRunnerServerRoot>>['value'];\n","import { defineMcpTool, type PoMcpPluginContext } from '@agimon-ai/po-core/mcpFacet';\n\nimport { RUNNER_SERVER_SCOPE_SERVICE, type RunnerServerScope } from '../_lib/serverRoot';\n\nconst pollHint = (id: string): string =>\n `You will not be notified when this runner ends. Check it with \\`po-runner status ${id}\\` and read output with \\`po-runner logs ${id} --lines 100\\`, both through this tool, until State is completed.`;\n\nexport default defineMcpTool((context: PoMcpPluginContext) => {\n const scope = context.services.get<RunnerServerScope>(RUNNER_SERVER_SCOPE_SERVICE);\n if (!scope) throw new Error('Runner session service is unavailable.');\n return {\n ...scope.remoteTool,\n description:\n \"Run a shell command (bash, terminal, CLI) in the Po session's repository on the host machine, not on your local machine. Use it for tests, builds, linters, git, and package scripts. Short commands return bounded output. Long-running ones return a runner id. No completion notice reaches you, so check them with `po-runner status <id>` and `po-runner logs <id> --lines 100` instead of relaunching.\",\n async execute(toolCallId, parameters, signal, onUpdate, execution) {\n const result = await scope.remoteTool.execute(\n toolCallId,\n parameters,\n AbortSignal.any([context.signal, signal ?? context.signal]),\n onUpdate,\n execution,\n );\n const details = result.details as { promoted?: unknown; id?: unknown } | undefined;\n if (details?.promoted !== true || typeof details.id !== 'string') return result;\n return { ...result, content: [...result.content, { type: 'text', text: pollHint(details.id) }] };\n },\n };\n});\n","// Generated by @agimon-ai/po-build. Do not edit by hand.\nimport { defineMcpPlugin, type PoMcpSessionPlugin } from '@agimon-ai/po-core/mcpFacet';\n\nimport skillPoUseRunner from '../src/extensions/workspaces/sessions/(backend)/skill/po-use-runner.mcp';\nimport toolBash from '../src/extensions/workspaces/sessions/(backend)/tool/bash.mcp';\n\ntype Factory<T, C> = (context: C) => T;\nconst at = <T, C>(value: T | Factory<T, C>, context: C): T =>\n typeof value === 'function' ? (value as Factory<T, C>)(context) : value;\nconst via = <T>(identity: Record<string, unknown>, value: unknown): T =>\n (value === undefined ? undefined : { ...identity, ...(value as object) }) as T;\n\nconst withWidget = <T>(key: string, value: T): T => value === undefined ? value : ({\n ...value, _meta: { ...(value as { _meta?: object })._meta, [\"po/widget\"]: key },\n});\n\nexport const mcp = defineMcpPlugin({\n name: '@agimon-ai/po-runner',\n session: (context) => ({\n get skills(): PoMcpSessionPlugin['skills'] { return [at(skillPoUseRunner, context)]; },\n get tools(): PoMcpSessionPlugin['tools'] { return [withWidget(\"@agimon-ai/po-runner/bash\", via({ name: 'bash' }, at(toolBash, context)))]; },\n }) satisfies PoMcpSessionPlugin,\n});\n\nexport default mcp;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGA,IAAA,6BAAA,GAAeA,4BAAAA,eAAAA,CAAe;CAC5B,MAAM;CACN,aACE;CACF,aAAA,GAAYC,gCAAAA,oBAAAA,CAAAA,QAAAA,KAAAA,CAAAA,CAAAA,cAAAA,UAAAA,CAAAA,CAAAA,MAAqC,oCAAoC;AACvF,CAAC;;;ACPD,MAAa,aAAa,CAAC,aAAa,kBAAkB;ACS1BC,QAAAA,KAAK,OAAO;CAC1C,SAASA,QAAAA,KAAK,OAAO,EAAE,aAAa,0BAA0B,CAAC;CAC/D,SAASA,QAAAA,KAAK,SAASA,QAAAA,KAAK,OAAO,EAAE,aAAa,oDAAoD,CAAC,CAAC;CACxG,YAAYA,QAAAA,KAAK,SACfA,QAAAA,KAAK,QAAQ,EACX,aACE,yJACJ,CAAC,CACH;CACA,aAAaA,QAAAA,KAAK,SAChBA,QAAAA,KAAK,QAAQ,EACX,aACE,2LACJ,CAAC,CACH;CACA,MAAMA,QAAAA,KAAK,SACTA,QAAAA,KAAK,OAAO,EACV,aAAa,+FACf,CAAC,CACH;AACF,CAAC;ACjBoB,IAAI,OACvB;CACE;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,GAAG,GACV,GACF;AAWoC,IAAI,OACtC;CACE;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,GAAG,GACV,GACF;;;;ACbA,MAAM,EAAE,UAAU,qBAAqBC,gBAAAA;CCmCjC,GAAaC,UAAAA,UAAAA,CAAUC,mBAAAA,QAAQ;;;AC1CrC,MAAM,aAAa;CACjB;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AACmC,CAAC,GAAG,YAAY,GAAG,UAA2B;;;ACVjF,MAAa,8BAA8B;;;ACf3C,MAAM,YAAY,OAChB,oFAAoF,GAAG,2CAA2C,GAAG;AAEvI,IAAA,oBAAA,GAAeC,4BAAAA,cAAAA,EAAe,YAAgC;CAC5D,MAAM,QAAQ,QAAQ,SAAS,IAAuB,2BAA2B;CACjF,IAAI,CAAC,OAAO,MAAM,IAAI,MAAM,wCAAwC;CACpE,OAAO;EACL,GAAG,MAAM;EACT,aACE;EACF,MAAM,QAAQ,YAAY,YAAY,QAAQ,UAAU,WAAW;GACjE,MAAM,SAAS,MAAM,MAAM,WAAW,QACpC,YACA,YACA,YAAY,IAAI,CAAC,QAAQ,QAAQ,UAAU,QAAQ,MAAM,CAAC,GAC1D,UACA,SACF;GACA,MAAM,UAAU,OAAO;GACvB,IAAI,SAAS,aAAa,QAAQ,OAAO,QAAQ,OAAO,UAAU,OAAO;GACzE,OAAO;IAAE,GAAG;IAAQ,SAAS,CAAC,GAAG,OAAO,SAAS;KAAE,MAAM;KAAQ,MAAM,SAAS,QAAQ,EAAE;IAAE,CAAC;GAAE;EACjG;CACF;AACF,CAAC;;;ACpBD,MAAM,MAAY,OAA0B,YAC1C,OAAO,UAAU,aAAc,MAAwB,OAAO,IAAI;AACpE,MAAM,OAAU,UAAmC,UAChD,UAAU,KAAA,IAAY,KAAA,IAAY;CAAE,GAAG;CAAU,GAAI;AAAiB;AAEzE,MAAM,cAAiB,KAAa,UAAgB,UAAU,KAAA,IAAY,QAAS;CACjF,GAAG;CAAO,OAAO;EAAE,GAAI,MAA6B;GAAQ,cAAc;CAAI;AAChF;AAEA,MAAa,OAAA,GAAMC,4BAAAA,gBAAAA,CAAgB;CACjC,MAAM;CACN,UAAU,aAAa;EACrB,IAAI,SAAuC;GAAE,OAAO,CAAC,GAAGC,2BAAkB,OAAO,CAAC;EAAG;EACrF,IAAI,QAAqC;GAAE,OAAO,CAAC,WAAW,6BAA6B,IAAI,EAAE,MAAM,OAAO,GAAG,GAAGC,kBAAU,OAAO,CAAC,CAAC,CAAC;EAAG;CAC7I;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"mcp.cjs","names":["defineMcpSkill","readPackageResource","Type","headless","runCommand","promisify","execFile","promisify","execFile","defineMcpTool","defineMcpPlugin","skillHelpHowToRunner","toolBash"],"sources":["../../src/extensions/workspaces/sessions/(backend)/skill/help-how-to-runner.mcp.ts","../../src/constants/runnerSettings.ts","../../src/constants/runnerSequence.ts","../../src/schemas/bashTool.ts","../../src/services/ansiScrub/index.ts","../../src/services/ptyHost/index.ts","../../src/services/runnerPaths/index.ts","../../src/services/runnerRegistry/index.ts","../../src/services/runnerSettings/index.ts","../../src/extensions/workspaces/sessions/(backend)/_lib/serverRoot.ts","../../src/extensions/workspaces/sessions/(backend)/tool/bash.mcp.ts","../../generated/mcp.ts"],"sourcesContent":["import { defineMcpSkill } from '@agimon-ai/po-core/mcpFacet';\nimport { readPackageResource } from '@agimon-ai/po-core/serverPlugin';\n\nexport default defineMcpSkill({\n name: 'help-how-to-runner',\n description:\n 'Use Po Pi Runner to supervise shell commands, inspect durable logs, provide interactive input, and stop background runs.',\n read: () => readPackageResource(import.meta.url, 'src/prompts/help-how-to-runner/SKILL.md'),\n});\n","export const RUNNER_SETTINGS_FILE = 'po-runner.json';\nexport const RATIO_KEYS = ['headRatio', 'errorBudgetRatio'] as const;\nexport const MAX_RESULT_BYTES_CEILING = 262_144;\nexport const MAX_RESULT_LINES_CEILING = 5_000;\nexport const MAX_RESULT_TOKENS_CEILING = 100_000;\nexport const MAX_ERROR_ENTRIES_CEILING = 100;\nexport const MAX_PATTERNS = 32;\nexport const MAX_PATTERN_LENGTH = 512;\n","export const MAX_SEQUENCE_COMMANDS = 32;\nexport const MAX_SEQUENCE_COMMAND_LENGTH = 65_536;\nexport const MAX_SEQUENCE_RECORD_BYTES = 4 * 1024 * 1024;\nexport const SEQUENCE_DIRECTORY = 'sequences';\nexport const SEQUENCE_PREFIX = 'sequence-';\n","import { type Static, Type } from 'typebox';\n\nimport { MAX_SEQUENCE_COMMANDS, MAX_SEQUENCE_COMMAND_LENGTH } from '../constants/runnerSequence';\n\n/** Replaces pi's built-in `bash` tool. Descriptions are agent-facing prompt copy. */\nexport const BashParamsSchema = Type.Object({\n command: Type.Array(Type.String({ minLength: 1, maxLength: MAX_SEQUENCE_COMMAND_LENGTH }), {\n minItems: 1,\n maxItems: MAX_SEQUENCE_COMMANDS,\n description:\n 'Bash commands to run in order, stopping on first failure. Use a one-item array for one command. Each command gets a full log; return all log paths and only the last executed result. Do not pipe or redirect output to a file, head, or tail. Logs are saved automatically and returned output is bounded.',\n }),\n timeout: Type.Optional(\n Type.Number({ description: 'Timeout in seconds for each command (optional, no default timeout)' }),\n ),\n background: Type.Optional(\n Type.Boolean({\n description:\n 'Start a long-lived service (dev server, watcher) in the background immediately. Nothing waits for it and you are not woken when it exits. Omit for tests and builds, even slow ones: they move to the background after 60 seconds on their own and wake you when they finish.',\n }),\n ),\n interactive: Type.Optional(\n Type.Boolean({\n description:\n 'Run only the last command under a pseudo terminal when it needs input. Earlier commands are noninteractive. Send input to the last stage runner ID with runner.input in code mode, or po-runner input without code mode.',\n }),\n ),\n name: Type.Optional(\n Type.String({\n description: 'Preferred runner name if the command ends up in the background. A name in use gets a suffix.',\n }),\n ),\n});\n\nexport type BashParams = Static<typeof BashParamsSchema>;\n","import { CONTROL_PATTERN } from '../../constants/ansiScrub';\n/**\n * Turns terminal output into text worth grepping.\n *\n * PTY output is written for a screen, not a file: colours, cursor moves and\n * carriage-return redraws all end up in the byte stream. Without this a single\n * progress bar becomes thousands of near-identical log lines.\n */\n\n/**\n * CSI sequences (colours, cursor moves), OSC strings, the two-byte Fe escapes,\n * and the keypad-mode escapes shells emit around every prompt.\n */\nconst ANSI_PATTERN = new RegExp(\n [\n '\\\\u001B\\\\[[0-9;?]*[ -/]*[@-~]',\n '\\\\u001B\\\\][^\\\\u0007\\\\u001B]*(?:\\\\u0007|\\\\u001B\\\\\\\\)',\n '\\\\u001B[@-Z\\\\\\\\-_]',\n '\\\\u001B[=><]',\n ].join('|'),\n 'g',\n);\n\n/** Bell and backspace, which a terminal consumes rather than displays. */\n// oxlint-disable-next-line no-control-regex -- matching terminal control bytes is the whole job\n\n/**\n * The same set minus SGR, the sequence that only sets colour and weight.\n *\n * The final byte class omits `m`, so `ESC[32m` survives while cursor moves,\n * OSC strings and keypad escapes are still removed.\n */\nconst ANSI_PATTERN_KEEPING_COLOUR = new RegExp(\n [\n '\\\\u001B\\\\[[0-9;?]*[ -/]*[@-ln-~]',\n '\\\\u001B\\\\][^\\\\u0007\\\\u001B]*(?:\\\\u0007|\\\\u001B\\\\\\\\)',\n '\\\\u001B[@-Z\\\\\\\\-_]',\n '\\\\u001B[=><]',\n ].join('|'),\n 'g',\n);\n\n/** Removes escape sequences, leaving the characters a user would have seen. */\nexport function stripAnsi(text: string): string {\n return text.replace(ANSI_PATTERN, '').replace(CONTROL_PATTERN, '');\n}\n\n/**\n * Removes everything `stripAnsi` does except colour.\n *\n * Logs are read back by a terminal renderer as well as by grep, and a command\n * that colours its own output has already said how it should look.\n */\nexport function stripAnsiKeepingColour(text: string): string {\n return text.replace(ANSI_PATTERN_KEEPING_COLOUR, '').replace(CONTROL_PATTERN, '');\n}\n\n/**\n * Collapses carriage-return redraws.\n *\n * A bare `\\r` returns the cursor to the start of the current line, so whatever\n * follows overwrites it. Only the final state of each line is kept. The `\\r` of\n * a CRLF pair is a line terminator rather than a redraw, so it is normalised\n * away first: a pseudo terminal ends every line that way, and treating it as a\n * redraw would blank the whole log.\n */\nexport function collapseCarriageReturns(text: string): string {\n return text\n .replace(/\\r\\n/g, '\\n')\n .split('\\n')\n .map((line) => (line.includes('\\r') ? (line.split('\\r').at(-1) ?? '') : line))\n .join('\\n');\n}\n\n/** Full scrub applied to PTY output before it reaches the log file. */\nexport function scrubTerminalOutput(text: string): string {\n return collapseCarriageReturns(stripAnsiKeepingColour(text));\n}\n\n/** Plain-text scrub, for the copy the model reads. */\nexport function scrubTerminalOutputToPlainText(text: string): string {\n return collapseCarriageReturns(stripAnsi(text));\n}\n","import headless, { type Terminal } from '@xterm/headless';\n\nimport {\n DEFAULT_COLS,\n DEFAULT_ROWS,\n LIVENESS_POLL_MS,\n MEMORY_BUFFER_FACTOR,\n NEWLINE,\n SCROLLBACK,\n TERM_GRACE_MS,\n} from '../../constants/ptyHost';\nimport { PO_SESSION_ID_ENV } from '../../constants/session';\nimport type { IClock } from '../../types/clock';\nimport type { ILogFile } from '../../types/logFile';\nimport type { IProcessControl } from '../../types/processControl';\nimport type { IPtyHost, PtyLaunchRequest, PtyRun } from '../../types/ptyHost';\nimport type { IPtySpawner, PtyProcess } from '../../types/ptySpawner';\nimport type { RunnerSettings } from '../../types/runnerSettings';\nimport type { ExitResult } from '../../types/spawner';\nimport { scrubTerminalOutput } from '../ansiScrub';\nimport { getResultMaxBytes } from '../runnerConfig';\nimport { NO_TERMINAL_INPUT_ENV } from '../runnerSupervisor';\n\n/** Enough history for the overlay to scroll without holding a whole build. */\n\n// Use the CommonJS default export: Node cannot detect this package's named exports.\n// A static import also lets server bundles include it without a live node_modules lookup.\nconst { Terminal: HeadlessTerminal } = headless;\n\nexport class PtyHost implements IPtyHost {\n private readonly runs = new Map<string, PtyRun>();\n\n constructor(\n private readonly spawner: IPtySpawner,\n private readonly logFile: ILogFile,\n private readonly processControl: IProcessControl,\n private readonly clock: IClock,\n private readonly environment: Readonly<Record<string, string | undefined>> = process.env,\n private readonly settings?: RunnerSettings,\n ) {}\n\n async launch(request: PtyLaunchRequest): Promise<PtyRun> {\n const cols = request.cols ?? DEFAULT_COLS;\n const rows = request.rows ?? DEFAULT_ROWS;\n const writer = await this.logFile.open(request.id);\n const terminal = new HeadlessTerminal({ cols, rows, scrollback: SCROLLBACK, allowProposedApi: true });\n const memoryLimit = getResultMaxBytes(this.environment, this.settings) * MEMORY_BUFFER_FACTOR;\n\n const child = await this.spawner.spawn({\n command: request.command,\n cwd: request.cwd,\n env: { ...this.environment, ...NO_TERMINAL_INPUT_ENV, [PO_SESSION_ID_ENV]: request.sessionId },\n cols,\n rows,\n });\n\n let buffer = '';\n let buffering = true;\n let settled = false;\n let resolveCompletion: (result: ExitResult) => void = () => undefined;\n let rejectCompletion: (error: unknown) => void = () => undefined;\n const completion = new Promise<ExitResult>((resolve, reject) => {\n resolveCompletion = resolve;\n rejectCompletion = reject;\n });\n const dataHandlers = new Set<(data: string) => void>();\n\n child.onData((data) => {\n // The terminal keeps the screen; the log keeps text worth grepping.\n terminal.write(data);\n const scrubbed = scrubTerminalOutput(data);\n void writer.append(scrubbed).catch((error: unknown) => process.emitWarning(String(error)));\n if (buffering) {\n buffer += scrubbed;\n if (buffer.length > memoryLimit) buffer = buffer.slice(-memoryLimit);\n }\n for (const handler of dataHandlers) handler(data);\n });\n\n child.onExit(async (result) => {\n if (settled) return;\n settled = true;\n this.runs.delete(request.name);\n try {\n await writer.close();\n resolveCompletion({ code: result.exitCode, signal: null });\n } catch (error) {\n rejectCompletion(error);\n }\n });\n\n const run: PtyRun = {\n id: request.id,\n name: request.name,\n pid: child.pid,\n logPath: writer.path,\n backend: 'native',\n output: async () => buffer,\n completion: () => completion,\n detach: () => {\n buffering = false;\n buffer = '';\n },\n stop: () => this.stopChild(child, request.name),\n write: (text) => child.write(text),\n screen: () => renderScreen(terminal),\n onData: (handler) => {\n dataHandlers.add(handler);\n return () => dataHandlers.delete(handler);\n },\n resize: (nextCols, nextRows) => {\n child.resize(nextCols, nextRows);\n terminal.resize(nextCols, nextRows);\n },\n };\n\n this.runs.set(request.name, run);\n return run;\n }\n\n get(name: string): PtyRun | undefined {\n return this.runs.get(name);\n }\n\n write(name: string, text: string): boolean {\n const run = this.runs.get(name);\n if (!run) return false;\n run.write(text.endsWith(NEWLINE) ? text : `${text}${NEWLINE}`);\n return true;\n }\n\n list(): PtyRun[] {\n return [...this.runs.values()];\n }\n\n async disposeAll(): Promise<void> {\n const runs = [...this.runs.values()];\n this.runs.clear();\n for (const run of runs) await run.stop();\n }\n\n private async stopChild(child: PtyProcess, name: string): Promise<boolean> {\n this.runs.delete(name);\n if (!this.processControl.isAlive(child.pid)) return false;\n\n child.kill('SIGTERM');\n const deadline = this.clock.now() + TERM_GRACE_MS;\n while (this.clock.now() < deadline) {\n if (!this.processControl.isAlive(child.pid)) return true;\n await new Promise<void>((resolve) => {\n this.clock.after(LIVENESS_POLL_MS, resolve);\n });\n }\n child.kill('SIGKILL');\n return true;\n }\n}\n\n/** The visible rows, trimmed of trailing blanks, as plain text. */\nfunction renderScreen(terminal: Terminal): string {\n const buffer = terminal.buffer.active;\n const lines: string[] = [];\n for (let row = buffer.baseY; row < buffer.baseY + terminal.rows; row += 1) {\n lines.push(buffer.getLine(row)?.translateToString(true) ?? '');\n }\n while (lines.length > 0 && lines.at(-1) === '') lines.pop();\n return lines.join(NEWLINE);\n}\n","import { execFile } from 'node:child_process';\nimport fs from 'node:fs';\nimport files from 'node:fs/promises';\nimport path from 'node:path';\nimport { promisify } from 'node:util';\n\nimport {\n EMPTY_SESSION_GRACE_MS,\n FILE_ENCODING,\n LOG_DIR_NAME,\n LOG_EXTENSION,\n NOT_FOUND_ERROR_CODE,\n RAW_SUFFIX,\n ROTATED_SUFFIX,\n STATE_DIR_NAME,\n STATE_EXTENSION,\n STORE_DIR_NAME,\n} from '../../constants/runnerPaths';\nimport { PO_SESSION_TEMP_DIR_ENV } from '../../constants/session';\nimport { getMaxCompletedRunners } from '../runnerConfig';\nimport { inheritedSessionId } from '../session';\nimport type { IRunnerPaths, LogSweepResult } from './type';\n\n/** Unscrubbed pane bytes, kept beside the log so an attached terminal can replay them. */\n/**\n * How long an entirely empty session directory is left alone before it counts\n * as an orphan. A session that has started but not yet run anything owns such a\n * directory for a moment, and reclaiming it out from under that session would\n * be churn for no gain.\n */\n\nconst runCommand = promisify(execFile);\n\n// Asynchronous: the server hosts every session, and a git call blocks its event loop for tens of ms.\nasync function git(args: string[], cwd: string): Promise<string | undefined> {\n try {\n const { stdout } = await runCommand('git', args, { cwd, encoding: FILE_ENCODING });\n const trimmed = stdout.trim();\n return trimmed.length > 0 ? trimmed : undefined;\n } catch {\n return undefined;\n }\n}\n\nasync function realPath(target: string): Promise<string> {\n try {\n return await files.realpath(target);\n } catch {\n return target;\n }\n}\n\n/**\n * Newest mtime anywhere one level inside the session, falling back to the\n * directory itself. A session still being written to therefore always looks\n * recent, whatever state its individual records are in.\n */\nasync function newestEntryTimeAsync(directory: string): Promise<number> {\n let newest = (await files.stat(directory)).mtimeMs;\n for (const entry of await files.readdir(directory, { withFileTypes: true })) {\n const target = path.join(directory, entry.name);\n newest = Math.max(newest, (await files.stat(target)).mtimeMs);\n if (!entry.isDirectory()) continue;\n for (const child of await files.readdir(target)) {\n newest = Math.max(newest, (await files.stat(path.join(target, child))).mtimeMs);\n }\n }\n return newest;\n}\n\n/**\n * Whether any run in this session names a pi process that is still running.\n *\n * One live record is enough: records are only ever written by their owner, so a\n * live host pid means the session is still in use however old its files look.\n */\nasync function ownerAliveAsync(stateDirectory: string): Promise<boolean> {\n let entries: string[];\n try {\n entries = await files.readdir(stateDirectory);\n } catch {\n return false;\n }\n\n for (const entry of entries) {\n if (!entry.endsWith(STATE_EXTENSION)) continue;\n try {\n const value: unknown = JSON.parse(await files.readFile(path.join(stateDirectory, entry), FILE_ENCODING));\n const hostPid = (value as { hostPid?: unknown }).hostPid;\n if (typeof hostPid !== 'number') continue;\n process.kill(hostPid, 0);\n return true;\n } catch {\n // An unreadable record and a dead pid mean the same thing here: no claim.\n }\n }\n return false;\n}\n\nfunction completedAt(value: unknown): number | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const record = value as { state?: unknown; exit?: { finishedAt?: unknown } };\n if (record.state !== 'completed' || typeof record.exit?.finishedAt !== 'string') return undefined;\n const timestamp = Date.parse(record.exit.finishedAt);\n return Number.isFinite(timestamp) ? timestamp : undefined;\n}\n\ninterface CompletedRecord {\n readonly id: string;\n readonly statePath: string;\n readonly finishedAt: number;\n}\n\n/**\n * Completed records a sweep may delete: everything past the TTL, and everything\n * beyond the newest `keep`.\n *\n * The count bound is what keeps a live session from growing without limit. Its\n * records only reach a multi-day TTL long after the session that is still\n * writing them would have filled its directory, so age alone bounds nothing\n * while the session lasts.\n */\nfunction expiredCompletedRecords(\n records: readonly CompletedRecord[],\n ttlMs: number,\n now: number,\n keep: number,\n): CompletedRecord[] {\n return [...records]\n .sort((left, right) => right.finishedAt - left.finishedAt)\n .filter((record, index) => index >= keep || now - record.finishedAt > ttlMs);\n}\n\n/**\n * Whether the directory holds no files at all, only empty subdirectories.\n *\n * A session that ran something leaves metadata behind, and a live session keeps\n * its lifeline socket in the state directory, so an entirely empty tree names\n * no owner and no history.\n */\nasync function isEmptySessionAsync(directory: string): Promise<boolean> {\n for (const entry of await files.readdir(directory, { withFileTypes: true })) {\n if (!entry.isDirectory()) return false;\n if ((await files.readdir(path.join(directory, entry.name))).length > 0) return false;\n }\n return true;\n}\n\n/**\n * The root this session's runner state lives under: `<PO_SESSION_TEMP_DIR>/po-runner/<session id>/{runs,logs}`. A reader in\n * another process, such as the cockpit hub, resolves the same root from its\n * own environment. There is no durable or global temporary directory fallback.\n */\nexport function resolveRunnerStoreDirectory(env: Readonly<Record<string, string | undefined>>): string {\n const temporaryDirectory = env[PO_SESSION_TEMP_DIR_ENV];\n if (!temporaryDirectory || !path.isAbsolute(temporaryDirectory)) {\n throw new Error('A host-admitted PO_SESSION_TEMP_DIR is required for po-runner storage');\n }\n return path.join(temporaryDirectory, STORE_DIR_NAME);\n}\n\n/** Temporary metadata directory for one session. Used by APIs and history reads, not live transport. */\nexport function runnerStateDirFor(storeDir: string, sessionId: string): string {\n return path.join(storeDir, sessionId, STATE_DIR_NAME);\n}\n\n/** Runner storage inside the host-admitted session temporary directory. */\nexport class RunnerPaths implements IRunnerPaths {\n private adoptedSessionId: string | undefined;\n private repository: Promise<string> | undefined;\n\n constructor(\n private readonly cwd: string = process.cwd(),\n private readonly env: Readonly<Record<string, string | undefined>> = { ...process.env },\n ) {}\n\n repositoryPath(): Promise<string> {\n this.repository ??= git(['rev-parse', '--show-toplevel'], this.cwd).then((root) => realPath(root ?? this.cwd));\n return this.repository;\n }\n\n setSessionId(sessionId: string): void {\n const trimmed = sessionId.trim();\n if (!trimmed) throw new Error('po-runner session id cannot be blank');\n if (!/^[a-zA-Z0-9_-]+$/u.test(trimmed)) throw new Error('Invalid runner session identity');\n this.adoptedSessionId = trimmed;\n }\n\n logDirectory(sessionId?: string): string {\n return path.join(this.sessionDirectory(sessionId), LOG_DIR_NAME);\n }\n\n stateDirectory(sessionId?: string): string {\n return path.join(this.sessionDirectory(sessionId), STATE_DIR_NAME);\n }\n\n logPathFor(id: string, sessionId?: string): string {\n return path.join(this.logDirectory(sessionId), `${id}${LOG_EXTENSION}`);\n }\n\n rotatedLogPathFor(id: string, sessionId?: string): string {\n return `${this.logPathFor(id, sessionId)}${ROTATED_SUFFIX}`;\n }\n\n rawLogPathFor(id: string, sessionId?: string): string {\n return `${this.logPathFor(id, sessionId)}${RAW_SUFFIX}`;\n }\n\n statePathFor(id: string, sessionId?: string): string {\n return path.join(this.stateDirectory(sessionId), `${id}${STATE_EXTENSION}`);\n }\n\n async ensureDirectories(sessionId?: string): Promise<void> {\n // Owner-only, as po-core requires of the session temp tree; a wider parent it created would make session removal refuse it.\n await files.mkdir(this.logDirectory(sessionId), { recursive: true, mode: 0o700 });\n await files.mkdir(this.stateDirectory(sessionId), { recursive: true, mode: 0o700 });\n }\n\n async sweepHistory(\n ttlMs: number,\n now: number = Date.now(),\n live: ReadonlySet<string> = this.liveSessions(),\n ): Promise<LogSweepResult> {\n const result: LogSweepResult = { removed: [], errors: [] };\n const root = this.storeDirectory();\n let sessions: string[];\n try {\n sessions = await files.readdir(root);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === NOT_FOUND_ERROR_CODE) return result;\n result.errors.push(`Could not read runner history directory ${root}: ${String(error)}`);\n return result;\n }\n\n for (const sessionId of sessions) {\n if (live.has(sessionId)) {\n await this.sweepActiveSessionAsync(sessionId, ttlMs, now, result);\n continue;\n }\n await this.sweepSessionDirectoryAsync(path.join(root, sessionId), ttlMs, now, result);\n }\n return result;\n }\n\n sweepHistoryAsync(ttlMs: number, now?: number, live?: ReadonlySet<string>): Promise<LogSweepResult> {\n return this.sweepHistory(ttlMs, now, live);\n }\n\n /** The live session, if one is known, so a sweep never deletes underneath itself. */\n private liveSessions(): ReadonlySet<string> {\n try {\n return new Set([this.sessionId()]);\n } catch {\n // A CLI invocation outside a session still sweeps; it just has nothing to spare.\n return new Set();\n }\n }\n\n /**\n * Retention inside the session that is still running.\n *\n * The whole-directory sweep cannot be pointed at the live session: it would\n * take the lifeline socket, the supervisor sidecars and the running runners'\n * own metadata with it. Per-record retention is safe there because it only\n * ever removes a record whose state is `completed` together with the two log\n * files that record names, and never the directory itself. A running record\n * has no `exit.finishedAt`, so it is not a candidate at any age.\n */\n private async sweepActiveSessionAsync(\n sessionId: string,\n ttlMs: number,\n now: number,\n result: LogSweepResult,\n ): Promise<void> {\n await this.sweepStateDirectoryAsync(this.stateDirectory(sessionId), sessionId, ttlMs, now, result);\n }\n\n /** Removes a session's whole directory once its newest entry is past the TTL. */\n private async sweepSessionDirectoryAsync(\n directory: string,\n ttlMs: number,\n now: number,\n result: LogSweepResult,\n ): Promise<void> {\n try {\n const newest = await newestEntryTimeAsync(directory);\n if (now - newest > EMPTY_SESSION_GRACE_MS && (await isEmptySessionAsync(directory))) {\n await files.rm(directory, { recursive: true, force: true });\n result.removed.push(directory);\n return;\n }\n if (now - newest <= ttlMs) return;\n if (await ownerAliveAsync(path.join(directory, STATE_DIR_NAME))) return;\n await files.rm(directory, { recursive: true, force: true });\n result.removed.push(directory);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== NOT_FOUND_ERROR_CODE) {\n result.errors.push(`Could not sweep runner session ${directory}: ${String(error)}`);\n }\n }\n }\n\n private sessionId(explicit?: string): string {\n const sessionId = explicit?.trim() || this.adoptedSessionId || inheritedSessionId(this.env);\n if (!sessionId) throw new Error('PO_SESSION_ID is required for po-runner storage');\n if (!/^[a-zA-Z0-9_-]+$/u.test(sessionId)) throw new Error('Invalid runner session identity');\n return sessionId;\n }\n\n storeDirectory(): string {\n return resolveRunnerStoreDirectory(this.env);\n }\n\n /** Delete only this session's runner subtree, never its other temporary output. */\n async removeSessionFiles(sessionId?: string, generation?: string): Promise<void> {\n let directory = this.sessionDirectory(sessionId);\n try {\n // sync: cleanup validates and detaches the owned generation before a replacement can create files.\n const root = fs.lstatSync(this.storeDirectory());\n if (root.isSymbolicLink() || !root.isDirectory()) throw new Error('Unsafe runner cleanup root');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === NOT_FOUND_ERROR_CODE) return;\n throw error;\n }\n if (generation !== undefined) {\n if (!/^[a-zA-Z0-9_-]+$/u.test(generation)) throw new Error('Invalid runner cleanup generation');\n try {\n // sync: cleanup fences ownership and detaches the old tree without yielding to a replacement.\n if (fs.readFileSync(path.join(directory, STATE_DIR_NAME, '.owner'), FILE_ENCODING) !== generation) return;\n // No await between checking ownership and detaching the old tree. A replacement\n // can now recreate its original path without racing the asynchronous removal.\n const detached = `${directory}.removing-${generation}`;\n // sync: the ownership check and cleanup rename must run in one turn.\n fs.renameSync(directory, detached);\n directory = detached;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === NOT_FOUND_ERROR_CODE) return;\n throw error;\n }\n }\n await files.rm(directory, { recursive: true, force: true });\n try {\n await files.rmdir(this.storeDirectory());\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code !== NOT_FOUND_ERROR_CODE && code !== 'ENOTEMPTY' && code !== 'EEXIST') throw error;\n }\n }\n\n private sessionDirectory(sessionId?: string): string {\n return path.join(this.storeDirectory(), this.sessionId(sessionId));\n }\n\n private async sweepStateDirectoryAsync(\n directory: string,\n sessionId: string,\n ttlMs: number,\n now: number,\n result: LogSweepResult,\n ): Promise<void> {\n let entries: string[];\n try {\n entries = await files.readdir(directory);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== NOT_FOUND_ERROR_CODE) {\n result.errors.push(`Could not read runner state directory ${directory}: ${String(error)}`);\n }\n return;\n }\n\n const completed: CompletedRecord[] = [];\n for (const entry of entries) {\n if (!entry.endsWith(STATE_EXTENSION)) continue;\n const statePath = path.join(directory, entry);\n try {\n const value: unknown = JSON.parse(await files.readFile(statePath, FILE_ENCODING));\n const finishedAt = completedAt(value);\n if (finishedAt === undefined) continue;\n completed.push({ id: entry.slice(0, -STATE_EXTENSION.length), statePath, finishedAt });\n } catch (error) {\n result.errors.push(`Could not sweep runner metadata ${statePath}: ${String(error)}`);\n }\n }\n\n for (const record of expiredCompletedRecords(completed, ttlMs, now, getMaxCompletedRunners(this.env))) {\n await this.removeHistoryFilesAsync(sessionId, record.id, record.statePath, result);\n }\n }\n\n private async removeHistoryFilesAsync(\n sessionId: string,\n id: string,\n statePath: string,\n result: LogSweepResult,\n ): Promise<void> {\n const candidates = [\n statePath,\n this.logPathFor(id, sessionId),\n this.rotatedLogPathFor(id, sessionId),\n this.rawLogPathFor(id, sessionId),\n ];\n for (const candidate of candidates) {\n try {\n await files.unlink(candidate);\n result.removed.push(candidate);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== NOT_FOUND_ERROR_CODE) {\n result.errors.push(`Could not remove runner history ${candidate}: ${String(error)}`);\n }\n }\n }\n }\n}\n","import { execFile } from 'node:child_process';\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\nimport { promisify } from 'node:util';\n\nimport {\n createProcessRegistryService,\n normalizeRepositoryPath,\n type ProcessRegistryRecord,\n type ProcessRegistryService,\n resolveProcessTags,\n} from '@agimon-ai/foundation-process-registry';\nimport type { PoTelemetry } from '@agimon-ai/po-core/telemetry';\n\nimport {\n COMMAND_SIDECAR_SUFFIX,\n EXIT_SIDECAR_SUFFIX,\n JSON_EXTENSION,\n NOT_FOUND_ERROR_CODE,\n REGISTRY_PATH_ENV,\n RUNNER_TAG,\n SERVICE_PREFIX,\n SERVICE_TYPE,\n} from '../../constants/runnerRegistry';\nimport type { IProcessControl } from '../../types/processControl';\nimport type {\n CompleteRunnerInput,\n IRunnerRegistry,\n RegisterRunnerInput,\n RunnerRecord,\n RunnerTerminationIntent,\n} from '../../types/runnerRegistry';\nimport type { IRunnerPaths } from '../runnerPaths/type';\nimport { isRunnerRecord } from '../runnerRecord';\nimport { resolveRootSessionId } from '../session';\n\n/** The slice of the shared registry service this wrapper depends on. */\nexport type ProcessRegistryPort = Pick<\n ProcessRegistryService,\n 'registerProcess' | 'releaseProcess' | 'listProcesses' | 'close'\n>;\n\n/** Opens the SQLite-backed registry the rest of the monorepo already shares. */\nexport function createDefaultProcessRegistry(\n env: Readonly<Record<string, string | undefined>> = process.env,\n): ProcessRegistryPort {\n return createProcessRegistryService(env[REGISTRY_PATH_ENV]);\n}\n\nfunction sessionTag(sessionId: string): string {\n return `session:${sessionId}`;\n}\n\nfunction readString(record: ProcessRegistryRecord, key: string): string {\n const value = record.metadata?.[key];\n return typeof value === 'string' ? value : '';\n}\n\nfunction readNumber(record: ProcessRegistryRecord, key: string): number {\n const value = record.metadata?.[key];\n return typeof value === 'number' ? value : 0;\n}\n\nconst runCommand = promisify(execFile);\n\n/**\n * The process start time the registry stores to prove a pid is still the\n * process it registered.\n *\n * The registry resolves it itself when the caller omits it, and it does so with\n * `execFileSync`, which stops this process for the length of a `ps` on every\n * runner that starts. Reading it here costs the same subprocess and blocks\n * nothing: the command is already running by the time a runner is registered.\n *\n * The value has to match what the registry would have read, so the command and\n * the trimming are deliberately identical to its own.\n */\nasync function processStartedAt(pid: number): Promise<string | undefined> {\n if (process.platform === 'win32') return undefined;\n try {\n const { stdout } = await runCommand('ps', ['-o', 'lstart=', '-p', String(pid)], { encoding: 'utf8' });\n return stdout.trim() || undefined;\n } catch {\n return undefined;\n }\n}\n\ntype ListenerRegistration = Readonly<{ key: string; listener: () => void }>;\n\n// Server plugin replacement can leave an in-flight tool and its publisher on different registry instances.\nconst listenersBySession = new Map<string, Set<() => void>>();\n\nexport class RunnerRegistry implements IRunnerRegistry {\n private readonly subscriptions = new Set<ListenerRegistration>();\n private recordWrites: Promise<void> = Promise.resolve();\n\n constructor(\n private readonly paths: IRunnerPaths,\n private readonly processControl: IProcessControl,\n private readonly registry: ProcessRegistryPort,\n private readonly environment: Readonly<Record<string, string | undefined>>,\n /** Records each runner once, here where it completes, instead of in every command's host process. */\n private readonly telemetry?: Pick<PoTelemetry, 'recordEvent'>,\n ) {}\n\n async register(input: RegisterRunnerInput): Promise<RunnerRecord> {\n const startedAt = new Date().toISOString();\n const rootSessionId = resolveRootSessionId(input.sessionId, this.environment);\n const identity = await processStartedAt(input.pid);\n const response = await this.registry.registerProcess({\n repositoryPath: await this.repositoryPath(),\n serviceName: `${SERVICE_PREFIX}${input.id}`,\n serviceType: SERVICE_TYPE,\n pid: input.pid,\n command: input.command,\n ...(identity === undefined ? {} : { processStartedAt: identity }),\n tags: resolveProcessTags([RUNNER_TAG, `runner:${input.id}`, sessionTag(input.sessionId)]),\n metadata: {\n id: input.id,\n name: input.name,\n command: input.command,\n cwd: input.cwd,\n logPath: input.logPath,\n interactive: input.interactive,\n sessionId: input.sessionId,\n rootSessionId,\n backend: input.backend,\n ...(input.backendTarget ? { backendTarget: input.backendTarget } : {}),\n startedAt,\n hostPid: process.pid,\n },\n // The caller has already resolved name collisions against live records,\n // so anything still holding this name is stale.\n force: true,\n });\n if (!response.success) throw new Error(response.error ?? `Failed to register runner ${input.name}`);\n const record: RunnerRecord = {\n id: input.id,\n name: input.name,\n pid: input.pid,\n command: input.command,\n cwd: input.cwd,\n logPath: input.logPath,\n interactive: input.interactive,\n sessionId: input.sessionId,\n rootSessionId,\n startedAt,\n state: 'running',\n promoted: false,\n backend: input.backend,\n ...(input.backendTarget ? { backendTarget: input.backendTarget } : {}),\n hostPid: process.pid,\n };\n await this.writeRecord(record);\n this.notify(record.sessionId);\n return record;\n }\n\n async list(): Promise<RunnerRecord[]> {\n const records = await this.registry.listProcesses({\n repositoryPath: await this.repositoryPath(),\n serviceType: SERVICE_TYPE,\n tags: resolveProcessTags([RUNNER_TAG]),\n });\n return records.map(toRunnerRecord);\n }\n\n async listBySession(sessionId: string): Promise<RunnerRecord[]> {\n const records = await this.list();\n return records.filter((record) => record.sessionId === sessionId);\n }\n\n async listByRootSession(rootSessionId: string): Promise<RunnerRecord[]> {\n const records = await this.list();\n return records.filter((record) => (record.rootSessionId ?? record.sessionId) === rootSessionId);\n }\n\n async listAll(sessionId?: string): Promise<RunnerRecord[]> {\n await this.paths.ensureDirectories(sessionId);\n const records: RunnerRecord[] = [];\n const directory = this.paths.stateDirectory(sessionId);\n for (const entry of await fs.readdir(directory)) {\n if (!isPrimaryMetadataEntry(entry)) continue;\n try {\n const parsed: unknown = JSON.parse(await fs.readFile(`${directory}/${entry}`, 'utf8'));\n if (isRunnerRecord(parsed)) records.push(parsed);\n } catch (error) {\n process.emitWarning(`Could not read runner metadata ${entry}: ${String(error)}`);\n }\n }\n return records.sort((left, right) => right.startedAt.localeCompare(left.startedAt));\n }\n\n async get(id: string, sessionId?: string): Promise<RunnerRecord | undefined> {\n const target = this.paths.statePathFor(id, sessionId);\n try {\n const parsed: unknown = JSON.parse(await fs.readFile(target, 'utf8'));\n if (!isRunnerRecord(parsed) || parsed.id !== id) {\n process.emitWarning(`Could not read runner metadata ${path.basename(target)}: invalid runner record`);\n return undefined;\n }\n return parsed;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === NOT_FOUND_ERROR_CODE) return undefined;\n process.emitWarning(`Could not read runner metadata ${path.basename(target)}: ${String(error)}`);\n return undefined;\n }\n }\n\n async markPromoted(id: string): Promise<RunnerRecord | undefined> {\n const record = await this.get(id);\n if (!record) return undefined;\n const promoted = { ...record, promoted: true };\n await this.writeRecord(promoted);\n this.notify(promoted.sessionId);\n return promoted;\n }\n\n async requestTermination(\n id: string,\n intent: RunnerTerminationIntent | undefined,\n sessionId?: string,\n ): Promise<RunnerRecord | undefined> {\n const record = await this.get(id, sessionId);\n if (!record) return undefined;\n if (record.state === 'completed') return record;\n if (intent !== undefined && record.terminationIntent !== undefined) return record;\n const { terminationIntent: _previous, ...rest } = record;\n const updated: RunnerRecord = { ...rest, ...(intent ? { terminationIntent: intent } : {}) };\n await this.writeRecord(updated);\n return updated;\n }\n\n async complete(id: string, outcome: CompleteRunnerInput, sessionId?: string): Promise<RunnerRecord | undefined> {\n const persisted = await this.get(id, sessionId);\n if (persisted?.state === 'completed') {\n await this.release(id, persisted.sessionId);\n return persisted;\n }\n const active = await this.list();\n const record =\n persisted ??\n active.find((candidate) => candidate.id === id && (sessionId === undefined || candidate.sessionId === sessionId));\n if (!record) {\n const belongsToAnotherSession =\n sessionId !== undefined && active.some((candidate) => candidate.id === id && candidate.sessionId !== sessionId);\n if (!belongsToAnotherSession) await this.release(id, sessionId);\n return undefined;\n }\n const completed: RunnerRecord = {\n ...record,\n state: 'completed',\n exit: {\n ...outcome,\n ...(outcome.signal !== null && outcome.terminationReason === undefined && record.terminationIntent === undefined\n ? { terminationReason: 'external_signal' as const }\n : {}),\n ...record.terminationIntent,\n finishedAt: new Date().toISOString(),\n },\n };\n await this.writeRecord(completed);\n await this.release(id, completed.sessionId);\n await this.recordFinished(completed);\n return completed;\n }\n\n async release(id: string, sessionId?: string): Promise<void> {\n const activeSessionId = sessionId ?? (await this.list()).find((record) => record.id === id)?.sessionId;\n const ownedSessionId = activeSessionId ?? (await this.get(id))?.sessionId;\n const response = await this.registry.releaseProcess({\n repositoryPath: await this.repositoryPath(),\n serviceName: `${SERVICE_PREFIX}${id}`,\n serviceType: SERVICE_TYPE,\n kill: false,\n releasePort: false,\n force: true,\n });\n if (!response.success && !response.error?.includes('No matching process entry')) {\n throw new Error(response.error ?? `Failed to release runner ${id}`);\n }\n if (ownedSessionId !== undefined) this.notify(ownedSessionId);\n }\n\n async pruneDead(): Promise<string[]> {\n const dead = (await this.list()).filter((record) => !this.processControl.isAlive(record.pid));\n for (const record of dead) {\n await this.complete(record.id, { reason: 'backend_lost', code: null, signal: null }, record.sessionId);\n }\n return dead.map((record) => record.id);\n }\n\n subscribe(listener: () => void, sessionId: string): () => void {\n const subscribed = (): void => listener();\n const registration = { key: this.subscriptionKey(sessionId), listener: subscribed };\n const listeners = listenersBySession.get(registration.key) ?? new Set<() => void>();\n listeners.add(subscribed);\n listenersBySession.set(registration.key, listeners);\n this.subscriptions.add(registration);\n return () => this.removeSubscription(registration);\n }\n\n close(): void {\n for (const registration of this.subscriptions) this.removeSubscription(registration);\n this.registry.close();\n }\n\n private notify(sessionId: string): void {\n for (const listener of listenersBySession.get(this.subscriptionKey(sessionId)) ?? []) {\n try {\n listener();\n } catch (error) {\n process.emitWarning(`Runner registry listener failed: ${String(error)}`);\n }\n }\n }\n\n private async recordFinished(record: RunnerRecord): Promise<void> {\n const { exit } = record;\n if (!this.telemetry || !exit) return;\n try {\n await this.telemetry.recordEvent('po_runner.process_finished', {\n outcome: exit.reason,\n 'runner.backend': record.backend,\n ...(exit.code === null ? {} : { 'runner.exit_code': exit.code }),\n ...(exit.signal ? { 'runner.signal': exit.signal } : {}),\n ...(exit.terminationReason ? { 'runner.termination_reason': exit.terminationReason } : {}),\n duration_ms: Date.parse(exit.finishedAt) - Date.parse(record.startedAt),\n });\n } catch (error) {\n process.emitWarning(`Could not record runner telemetry: ${String(error)}`);\n }\n }\n\n private removeSubscription(registration: ListenerRegistration): void {\n const listeners = listenersBySession.get(registration.key);\n listeners?.delete(registration.listener);\n if (listeners?.size === 0) listenersBySession.delete(registration.key);\n this.subscriptions.delete(registration);\n }\n\n private subscriptionKey(sessionId: string): string {\n return JSON.stringify([path.resolve(this.paths.stateDirectory(sessionId)), sessionId]);\n }\n\n private async repositoryPath(): Promise<string> {\n return normalizeRepositoryPath(await this.paths.repositoryPath());\n }\n\n private writeRecord(record: RunnerRecord): Promise<void> {\n const write = this.recordWrites.then(async () => {\n await this.paths.ensureDirectories(record.sessionId);\n const target = this.paths.statePathFor(record.id, record.sessionId);\n const temporary = `${target}.${process.pid}.tmp`;\n await fs.writeFile(temporary, `${JSON.stringify(record, null, 2)}\\n`, 'utf8');\n await fs.rename(temporary, target);\n });\n // Keep later writes ordered even after a failed write, which its caller observes.\n this.recordWrites = write.catch(() => undefined);\n return write;\n }\n}\n\n/** Every field is read back from metadata this class wrote on registration. */\nfunction toRunnerRecord(record: ProcessRegistryRecord): RunnerRecord {\n return {\n id: readString(record, 'id'),\n name: readString(record, 'name'),\n pid: record.pid,\n command: readString(record, 'command'),\n cwd: readString(record, 'cwd'),\n logPath: readString(record, 'logPath'),\n interactive: record.metadata?.interactive === true,\n sessionId: readString(record, 'sessionId'),\n ...(readString(record, 'rootSessionId') ? { rootSessionId: readString(record, 'rootSessionId') } : {}),\n startedAt: readString(record, 'startedAt'),\n state: 'running',\n promoted: false,\n backend: readBackend(record.metadata?.backend),\n ...(readString(record, 'backendTarget') ? { backendTarget: readString(record, 'backendTarget') } : {}),\n hostPid: readNumber(record, 'hostPid'),\n };\n}\n\nfunction readBackend(value: unknown): RunnerRecord['backend'] {\n return value === 'rmux' || value === 'tmux' ? value : 'native';\n}\n\nfunction isPrimaryMetadataEntry(entry: string): boolean {\n return (\n entry.endsWith(JSON_EXTENSION) && !entry.endsWith(COMMAND_SIDECAR_SUFFIX) && !entry.endsWith(EXIT_SIDECAR_SUFFIX)\n );\n}\n","import fs from 'node:fs/promises';\nimport path from 'node:path';\n\nimport { BACKGROUND_CONTEXT, readTextIfExists, type FileSystem } from '@agimon-ai/po-core/platform';\nimport { CONFIG_DIR_NAME } from '@earendil-works/pi-coding-agent';\n\nimport {\n MAX_ERROR_ENTRIES_CEILING,\n MAX_PATTERNS,\n MAX_PATTERN_LENGTH,\n MAX_RESULT_BYTES_CEILING,\n MAX_RESULT_LINES_CEILING,\n MAX_RESULT_TOKENS_CEILING,\n RATIO_KEYS,\n RUNNER_SETTINGS_FILE,\n} from '../../constants/runnerSettings';\nimport type { IRunnerSettingsLoader, RunnerSettings, RunnerSettingsLoad } from '../../types/runnerSettings';\n\n/** Pi's convention is one JSON file per extension under the config directory. */\n\nconst EMPTY: RunnerSettingsLoad = { settings: {}, issues: [] };\nconst COUNT_KEYS = [\n 'maxResultBytes',\n 'maxResultLines',\n 'successMaxResultBytes',\n 'maxResultTokens',\n 'successMaxResultTokens',\n 'errorMaxEntries',\n 'errorMaxVariantsJoined',\n] as const;\nconst KNOWN_KEYS = new Set<string>([...RATIO_KEYS, ...COUNT_KEYS, 'errorPatterns']);\n/** Ceilings so a project file cannot flood the model's context. */\nconst CEILINGS: Readonly<Record<string, number>> = {\n maxResultBytes: MAX_RESULT_BYTES_CEILING,\n successMaxResultBytes: MAX_RESULT_BYTES_CEILING,\n maxResultTokens: MAX_RESULT_TOKENS_CEILING,\n successMaxResultTokens: MAX_RESULT_TOKENS_CEILING,\n maxResultLines: MAX_RESULT_LINES_CEILING,\n errorMaxEntries: MAX_ERROR_ENTRIES_CEILING,\n errorMaxVariantsJoined: MAX_ERROR_ENTRIES_CEILING,\n};\n\nexport class RunnerSettingsLoader implements IRunnerSettingsLoader {\n constructor(private readonly files?: FileSystem) {}\n\n async load(cwd: string, trusted: boolean): Promise<RunnerSettingsLoad> {\n // Project-local configuration is untrusted input until the project is.\n if (!trusted) return EMPTY;\n\n let raw: string;\n try {\n const target = path.join(cwd, CONFIG_DIR_NAME, RUNNER_SETTINGS_FILE);\n const text = this.files\n ? await readTextIfExists(this.files, target, BACKGROUND_CONTEXT)\n : await fs.readFile(target, 'utf8');\n if (text === undefined) return EMPTY;\n raw = text;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return EMPTY;\n return { settings: {}, issues: [`${RUNNER_SETTINGS_FILE} could not be read`] };\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n return { settings: {}, issues: [`${RUNNER_SETTINGS_FILE} is not valid JSON`] };\n }\n return validate(parsed);\n }\n}\n\nfunction validate(parsed: unknown): RunnerSettingsLoad {\n if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {\n return { settings: {}, issues: [`${RUNNER_SETTINGS_FILE} must contain a JSON object`] };\n }\n\n const source = parsed as Record<string, unknown>;\n const settings: Record<string, unknown> = {};\n const issues: string[] = [];\n // A rejected key is reported rather than dropped: a silent typo reads as a\n // setting that simply does not work.\n for (const key of Object.keys(source)) if (!KNOWN_KEYS.has(key)) issues.push(`unknown key ${key}`);\n\n for (const key of COUNT_KEYS) {\n const value = source[key];\n if (value === undefined) continue;\n if (typeof value !== 'number' || !Number.isInteger(value) || value <= 0) {\n issues.push(`${key} must be a positive integer`);\n continue;\n }\n settings[key] = Math.min(value, CEILINGS[key] ?? value);\n }\n\n for (const key of RATIO_KEYS) {\n const value = source[key];\n if (value === undefined) continue;\n if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0 || value >= 1) {\n issues.push(`${key} must be a number above 0 and below 1`);\n continue;\n }\n settings[key] = value;\n }\n\n const patterns = source.errorPatterns;\n if (patterns !== undefined) {\n if (!Array.isArray(patterns) || patterns.some((entry) => typeof entry !== 'string')) {\n issues.push('errorPatterns must be an array of strings');\n } else {\n const accepted: string[] = [];\n for (const pattern of patterns.slice(0, MAX_PATTERNS) as string[]) {\n if (pattern.length > MAX_PATTERN_LENGTH) {\n issues.push('errorPatterns entry is too long');\n continue;\n }\n try {\n new RegExp(pattern, 'iu');\n accepted.push(pattern);\n } catch {\n issues.push(`errorPatterns entry is not a valid regular expression: ${pattern}`);\n }\n }\n if (accepted.length > 0) settings.errorPatterns = accepted;\n }\n }\n\n return { settings: settings as RunnerSettings, issues };\n}\n","import { PO_CODEMODE_SERVICE, readPoCodemode } from '@agimon-ai/po-core/codemode';\nimport { formatMessage, readPoLang, readPoPersonLocale } from '@agimon-ai/po-core/locale';\nimport { readPoFs, PO_SESSION_TEMP_DIR } from '@agimon-ai/po-core/platform';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\nimport { createPoTelemetry } from '@agimon-ai/po-core/telemetry';\nimport { readPoWorkflowContextService } from '@agimon-ai/po-core/workflow';\nimport type { Context } from '@deepseek-ai/cordis';\n\nimport { REGISTRY_PATH_ENV } from '../../../../../constants/runnerRegistry';\nimport {\n HISTORY_SWEEP_INTERVAL_MS,\n RUNNER_FINISHED_MESSAGE,\n RUNNER_STATUS_POLL_MS,\n} from '../../../../../constants/runnerRuntime';\nimport { RUNNER_SETTINGS_FILE } from '../../../../../constants/runnerSettings';\nimport { SystemClock } from '../../../../../services/clock';\nimport { createHeadlessBashTool, createHeadlessRunnersCommand } from '../../../../../services/headless';\nimport { LifelineObserver } from '../../../../../services/lifeline';\nimport { summarizeLog } from '../../../../../services/logReader';\nimport { createRunnerDependencies } from '../../../../../services/runnerDependencies';\nimport { createRunnerHost } from '../../../../../services/runnerHost';\nimport { createRunnerLaunch, PO_RUNNER_LAUNCH_SERVICE } from '../../../../../services/runnerLaunch';\nimport { createRunnerNamespace } from '../../../../../services/runnerNamespace';\nimport { createRunnerOperations } from '../../../../../services/runnerOperations';\nimport { createDefaultProcessRegistry } from '../../../../../services/runnerRegistry';\nimport { createRunnerSequenceService } from '../../../../../services/runnerSequence';\nimport { createRunnerSequenceStore } from '../../../../../services/runnerSequenceStore';\nimport { createRunnerServerRuntime } from '../../../../../services/runnerServerRuntime';\nimport { RunnerSettingsLoader } from '../../../../../services/runnerSettings';\n\nexport const RUNNER_SERVER_SCOPE_SERVICE = 'po/runner-server-scope';\n\ndeclare module '@deepseek-ai/cordis' {\n interface Context {\n 'po/runner-server-scope': RunnerServerScope;\n }\n}\n\nexport const createRunnerServerRoot = async ({ context, host, agent, signal, resources }: PoServerPluginContext) => {\n if (!host.context.directEvents) throw new Error('Runner server plugin requires the session direct event bus.');\n if (!host.context.cwd || !host.context.environment) {\n throw new Error('Runner server plugin requires session cwd and environment.');\n }\n // Inherit the current headless Pi bridge's isProjectTrusted: () => true.\n // This preserves runner configuration parity, not a new general trust policy.\n const fs = readPoFs(context);\n const loaded = await new RunnerSettingsLoader(fs).load(host.context.cwd, true);\n const settings = Object.freeze({\n ...loaded.settings,\n ...(loaded.settings.errorPatterns ? { errorPatterns: Object.freeze([...loaded.settings.errorPatterns]) } : {}),\n });\n for (const issue of loaded.issues) process.emitWarning(`${RUNNER_SETTINGS_FILE}: ${issue}`);\n const environment = host.context.environment;\n if (!environment[PO_SESSION_TEMP_DIR])\n throw new Error('Runner requires the host-admitted session temporary directory.');\n // One per registry for this build in the hub: every session shares the connection and the loop that\n // keeps house for it, and the last session to close disposes them.\n const runnerHost = await resources.acquire(\n ['runner-host', environment[REGISTRY_PATH_ENV] ?? null],\n () =>\n createRunnerHost({\n processRegistry: createDefaultProcessRegistry(environment),\n clock: new SystemClock(),\n statusPollMs: RUNNER_STATUS_POLL_MS,\n historySweepMs: HISTORY_SWEEP_INTERVAL_MS,\n onWarning: (message) => process.emitWarning(message),\n }),\n (shared) => shared.dispose(),\n );\n // One observer process cleans up after every session of the registry, rather than one each.\n const lifelineObserver = await resources.acquire(\n ['runner-lifeline-observer', environment[REGISTRY_PATH_ENV] ?? null],\n () => new LifelineObserver(environment),\n (shared) => shared.close(),\n );\n const execution = agent?.context;\n const telemetry = execution\n ? createPoTelemetry({\n serviceName: 'po-runner',\n packageName: '@agimon-ai/po-runner',\n cwd: execution.cwd,\n env: execution.environment,\n enableLogs: true,\n enableTraces: true,\n })\n : undefined;\n const dependencies = createRunnerDependencies({\n settings,\n cwd: host.context.cwd,\n environment,\n processRegistry: runnerHost.processRegistry,\n lifelineObserver,\n ...(telemetry === undefined ? {} : { telemetry }),\n ...(host.context.executionBudget === undefined ? {} : { executionBudget: host.context.executionBudget }),\n });\n const wakeAgent =\n execution &&\n (async (content: string, requestId: string, notice: string): Promise<void> => {\n try {\n // 'steer' joins a running turn and starts one on an idle session.\n // Reuse completion identity across retries and acknowledge admission, not settlement.\n // A custom message, not a prompt: the model reads it as input, while the\n // transcript shows the notice as an event rather than as the person's words.\n if (!execution.session.admitMessage) throw new Error('The session cannot admit a runner notification.');\n await execution.session.admitMessage(\n { type: RUNNER_FINISHED_MESSAGE, text: content, display: true, details: { notice } },\n 'steer',\n requestId,\n );\n } catch (error) {\n // Keep completion ownership with the watcher until admission succeeds.\n await Promise.resolve()\n .then(() => execution.client.notify({ body: String(error), level: 'warning' }))\n .catch(() => undefined);\n throw error;\n }\n });\n const runtime = createRunnerServerRuntime(\n dependencies,\n runnerHost,\n host.context.directEvents,\n wakeAgent,\n execution,\n telemetry,\n );\n const sequences =\n fs && execution\n ? createRunnerSequenceService({\n dependencies,\n store: createRunnerSequenceStore(fs, dependencies.paths, execution.sessionId),\n sessionId: execution.sessionId,\n signal,\n summarizeLog: (path, lines, bytes, tokens) => summarizeLog(path, lines, bytes, tokens, settings),\n onChange: () => runtime.sequenceChanged(),\n onWarning: (message) => process.emitWarning(message),\n onComplete: async (record) => {\n if (!record.result) return;\n await wakeAgent?.(\n record.result.content.flatMap((part) => (part.type === 'text' ? [part.text] : [])).join('\\n'),\n `runner-sequence-finished:${JSON.stringify([record.sessionId, record.id])}`,\n `Command sequence ${record.name} finished: ${record.outcome ?? record.state}`,\n );\n },\n })\n : undefined;\n if (sequences) runtime.setSequences(sequences);\n const bash = (wakeOnExit: boolean) =>\n createHeadlessBashTool(\n sequences\n ? async (params, context, toolCallId, callSignal, onUpdate) => {\n await runtime.ensureSession(context.sessionId);\n return sequences.run(params, context, toolCallId, callSignal, onUpdate, wakeOnExit);\n }\n : undefined,\n dependencies.environment,\n );\n const value = {\n sequences,\n tool: bash(true),\n // Remote MCP runners must not wake the local agent; the remote caller polls instead.\n remoteTool: bash(false),\n command: createHeadlessRunnersCommand(dependencies, {\n translate: (key, fallback, vars) =>\n readPoLang(context)?.t(readPoPersonLocale(context)?.read(), key, fallback, vars) ??\n formatMessage(fallback, vars),\n // Without the platform fs a missing folder still fails, only at spawn and less plainly.\n fs,\n sequences,\n onStart: (startedSessionId, failure) => runtime.reportStart(startedSessionId, failure),\n }),\n recoverCompaction: runtime.recoverCompaction,\n };\n let controlsDisposed = false;\n let launch: ReturnType<typeof createRunnerLaunch> | undefined;\n let unregisterOwner: (() => void) | undefined;\n if (fs && execution) {\n const operations = createRunnerOperations({\n ...dependencies,\n registry: dependencies.runnerRegistry,\n fs,\n sessionId: execution.sessionId,\n });\n const assertAvailable = () => {\n signal?.throwIfAborted();\n if (controlsDisposed) throw new Error('Runner session is disposed.');\n };\n launch = createRunnerLaunch({\n sessionId: execution.sessionId,\n // Only the trusted step-session bootstrap binds the workflow context. A plain session owns itself.\n ownerSessionId: readPoWorkflowContextService(context)?.run.ownerSessionId ?? execution.sessionId,\n getOwner: (ownerSessionId) => runnerHost.getOwner(ownerSessionId),\n runService: dependencies.bashRunService,\n registry: dependencies.runnerRegistry,\n operations,\n ensureSession: (sessionId) => runtime.ensureSession(sessionId),\n watchRunner: (id) => runtime.watchRunner(id),\n assertAvailable,\n });\n // Sessions of this hub and build reach this session's runners through its local launch only.\n unregisterOwner = runnerHost.registerOwner(execution.sessionId, launch);\n const namespace = createRunnerNamespace({\n sessionId: execution.sessionId,\n operations,\n sequences,\n assertAvailable,\n });\n context.inject([PO_CODEMODE_SERVICE], (scoped) => {\n const registration = readPoCodemode(scoped)?.register('@agimon-ai/po-runner', namespace);\n return () => registration?.dispose();\n });\n }\n return {\n value,\n services: [\n runtime.backgroundWorkPlugin,\n (context: Context) => {\n context.plugin((providerContext) => {\n providerContext.provide(RUNNER_SERVER_SCOPE_SERVICE, value);\n if (launch) providerContext.provide(PO_RUNNER_LAUNCH_SERVICE, launch);\n });\n },\n ],\n activities: [runtime.activity],\n // Package install is on the session-create path; bash awaits supervision itself.\n onStart: execution\n ? () => {\n void runtime\n .ensureSession(execution.sessionId)\n .catch((error: unknown) =>\n process.emitWarning(`Could not initialize headless runner supervision: ${String(error)}`),\n );\n }\n : undefined,\n onStop: async () => {\n // Before any await: no routed call may reach an owner that is going away.\n controlsDisposed = true;\n unregisterOwner?.();\n const failures: unknown[] = [];\n // Drain launches, then release the runtime's runners, even when the drain fails.\n for (const release of [() => launch?.dispose(), () => runtime.dispose()]) {\n try {\n await release();\n } catch (error) {\n failures.push(error);\n }\n }\n if (failures.length === 1) throw failures[0];\n if (failures.length > 1) throw new AggregateError(failures, 'Runner session cleanup failed.');\n },\n };\n};\n\nexport type RunnerServerScope = Awaited<ReturnType<typeof createRunnerServerRoot>>['value'];\n","import { defineMcpTool, type PoMcpPluginContext } from '@agimon-ai/po-core/mcpFacet';\n\nimport { RUNNER_SERVER_SCOPE_SERVICE, type RunnerServerScope } from '../_lib/serverRoot';\n\nconst pollHint = (id: string): string =>\n `You will not be notified when this runner ends. Check it with \\`po-runner status ${id}\\` and read output with \\`po-runner logs ${id} --lines 100\\`, both through this tool, until State is completed.`;\n\nexport default defineMcpTool((context: PoMcpPluginContext) => {\n const scope = context.services.get<RunnerServerScope>(RUNNER_SERVER_SCOPE_SERVICE);\n if (!scope) throw new Error('Runner session service is unavailable.');\n return {\n ...scope.remoteTool,\n description:\n \"Run an array of shell commands (bash, terminal, CLI) in the Po session's repository on the host machine, not on your local machine. Use a one-item array for one command. Commands run in order and stop on first failure. Only the last command may be interactive. Do not pipe or redirect output to a file, head, or tail: full logs are saved automatically and returned output is bounded. Long-running commands return a sequence id. No completion notice reaches you, so check with `po-runner status <id>` and `po-runner logs <id> --lines 100` instead of relaunching.\",\n async execute(toolCallId, parameters, signal, onUpdate, execution) {\n const result = await scope.remoteTool.execute(\n toolCallId,\n parameters,\n AbortSignal.any([context.signal, signal ?? context.signal]),\n onUpdate,\n execution,\n );\n const details = result.details as { promoted?: unknown; id?: unknown } | undefined;\n if (details?.promoted !== true || typeof details.id !== 'string') return result;\n return { ...result, content: [...result.content, { type: 'text', text: pollHint(details.id) }] };\n },\n };\n});\n","// Generated by @agimon-ai/po-build. Do not edit by hand.\nimport { defineMcpPlugin, type PoMcpSessionPlugin } from '@agimon-ai/po-core/mcpFacet';\n\nimport skillHelpHowToRunner from '../src/extensions/workspaces/sessions/(backend)/skill/help-how-to-runner.mcp';\nimport toolBash from '../src/extensions/workspaces/sessions/(backend)/tool/bash.mcp';\n\ntype Factory<T, C> = (context: C) => T;\nconst at = <T, C>(value: T | Factory<T, C>, context: C): T =>\n typeof value === 'function' ? (value as Factory<T, C>)(context) : value;\nconst via = <T>(identity: Record<string, unknown>, value: unknown): T => {\n if (value === undefined) return undefined as T;\n const declaration = value as { relations?: readonly Record<string, unknown>[] };\n return { ...identity, ...declaration, ...(declaration.relations === undefined ? {} : {\n relations: declaration.relations.map((relation) => ({ evidence: 'declared', ...relation })),\n }) } as T;\n};\n\nconst withWidget = <T>(key: string, value: T): T => value === undefined ? value : ({\n ...value, _meta: { ...(value as { _meta?: object })._meta, [\"po/widget\"]: key },\n});\n\nexport const mcp = defineMcpPlugin({\n name: '@agimon-ai/po-runner',\n session: (context) => ({\n get skills(): PoMcpSessionPlugin['skills'] { return [at(skillHelpHowToRunner, context)]; },\n get tools(): PoMcpSessionPlugin['tools'] { return [withWidget(\"@agimon-ai/po-runner/bash\", via({ name: 'bash' }, at(toolBash, context)))]; },\n }) satisfies PoMcpSessionPlugin,\n});\n\nexport default mcp;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGA,IAAA,kCAAA,GAAeA,4BAAAA,eAAAA,CAAe;CAC5B,MAAM;CACN,aACE;CACF,aAAA,GAAYC,gCAAAA,oBAAAA,CAAAA,QAAAA,KAAAA,CAAAA,CAAAA,cAAAA,UAAAA,CAAAA,CAAAA,MAAqC,yCAAyC;AAC5F,CAAC;;;ACPD,MAAa,aAAa,CAAC,aAAa,kBAAkB;AEI1BC,QAAAA,KAAK,OAAO;CAC1C,SAASA,QAAAA,KAAK,MAAMA,QAAAA,KAAK,OAAO;EAAE,WAAW;EAAG,WAAW;CAA4B,CAAC,GAAG;EACzF,UAAU;EACV,UAAA;EACA,aACE;CACJ,CAAC;CACD,SAASA,QAAAA,KAAK,SACZA,QAAAA,KAAK,OAAO,EAAE,aAAa,qEAAqE,CAAC,CACnG;CACA,YAAYA,QAAAA,KAAK,SACfA,QAAAA,KAAK,QAAQ,EACX,aACE,gRACJ,CAAC,CACH;CACA,aAAaA,QAAAA,KAAK,SAChBA,QAAAA,KAAK,QAAQ,EACX,aACE,2NACJ,CAAC,CACH;CACA,MAAMA,QAAAA,KAAK,SACTA,QAAAA,KAAK,OAAO,EACV,aAAa,+FACf,CAAC,CACH;AACF,CAAC;ACnBoB,IAAI,OACvB;CACE;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,GAAG,GACV,GACF;AAWoC,IAAI,OACtC;CACE;CACA;CACA;CACA;AACF,CAAC,CAAC,KAAK,GAAG,GACV,GACF;;;;ACbA,MAAM,EAAE,UAAU,qBAAqBC,gBAAAA;CCIjCC,GAAaC,UAAAA,UAAAA,CAAUC,mBAAAA,QAAQ;CCgC/B,GAAaC,UAAAA,UAAAA,CAAUC,mBAAAA,QAAQ;;;AC1CrC,MAAM,aAAa;CACjB;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AACmC,CAAC,GAAG,YAAY,GAAG,UAA2B;;;ACAjF,MAAa,8BAA8B;;;AC1B3C,MAAM,YAAY,OAChB,oFAAoF,GAAG,2CAA2C,GAAG;AAEvI,IAAA,oBAAA,GAAeC,4BAAAA,cAAAA,EAAe,YAAgC;CAC5D,MAAM,QAAQ,QAAQ,SAAS,IAAuB,2BAA2B;CACjF,IAAI,CAAC,OAAO,MAAM,IAAI,MAAM,wCAAwC;CACpE,OAAO;EACL,GAAG,MAAM;EACT,aACE;EACF,MAAM,QAAQ,YAAY,YAAY,QAAQ,UAAU,WAAW;GACjE,MAAM,SAAS,MAAM,MAAM,WAAW,QACpC,YACA,YACA,YAAY,IAAI,CAAC,QAAQ,QAAQ,UAAU,QAAQ,MAAM,CAAC,GAC1D,UACA,SACF;GACA,MAAM,UAAU,OAAO;GACvB,IAAI,SAAS,aAAa,QAAQ,OAAO,QAAQ,OAAO,UAAU,OAAO;GACzE,OAAO;IAAE,GAAG;IAAQ,SAAS,CAAC,GAAG,OAAO,SAAS;KAAE,MAAM;KAAQ,MAAM,SAAS,QAAQ,EAAE;IAAE,CAAC;GAAE;EACjG;CACF;AACF,CAAC;;;ACpBD,MAAM,MAAY,OAA0B,YAC1C,OAAO,UAAU,aAAc,MAAwB,OAAO,IAAI;AACpE,MAAM,OAAU,UAAmC,UAAsB;CACvE,IAAI,UAAU,KAAA,GAAW,OAAO,KAAA;CAChC,MAAM,cAAc;CACpB,OAAO;EAAE,GAAG;EAAU,GAAG;EAAa,GAAI,YAAY,cAAc,KAAA,IAAY,CAAC,IAAI,EACnF,WAAW,YAAY,UAAU,KAAK,cAAc;GAAE,UAAU;GAAY,GAAG;EAAS,EAAE,EAC5F;CAAG;AACL;AAEA,MAAM,cAAiB,KAAa,UAAgB,UAAU,KAAA,IAAY,QAAS;CACjF,GAAG;CAAO,OAAO;EAAE,GAAI,MAA6B;GAAQ,cAAc;CAAI;AAChF;AAEA,MAAa,OAAA,GAAMC,4BAAAA,gBAAAA,CAAgB;CACjC,MAAM;CACN,UAAU,aAAa;EACrB,IAAI,SAAuC;GAAE,OAAO,CAAC,GAAGC,gCAAsB,OAAO,CAAC;EAAG;EACzF,IAAI,QAAqC;GAAE,OAAO,CAAC,WAAW,6BAA6B,IAAI,EAAE,MAAM,OAAO,GAAG,GAAGC,kBAAU,OAAO,CAAC,CAAC,CAAC;EAAG;CAC7I;AACF,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mcp.d.mts","names":[],"sources":["../../generated/mcp.ts"],"mappings":";
|
|
1
|
+
{"version":3,"file":"mcp.d.mts","names":[],"sources":["../../generated/mcp.ts"],"mappings":";qBAqBa,2CAAG"}
|
package/dist/extensions/mcp.mjs
CHANGED
|
@@ -1,32 +1,43 @@
|
|
|
1
1
|
import { defineMcpPlugin, defineMcpSkill, defineMcpTool } from "@agimon-ai/po-core/mcpFacet";
|
|
2
2
|
import { readPackageResource } from "@agimon-ai/po-core/serverPlugin";
|
|
3
|
+
import "@agimon-ai/po-core/codemode";
|
|
4
|
+
import "@agimon-ai/po-core/locale";
|
|
5
|
+
import "@agimon-ai/po-core/platform";
|
|
6
|
+
import "@agimon-ai/po-core/telemetry";
|
|
7
|
+
import "@agimon-ai/po-core/workflow";
|
|
3
8
|
import { Type } from "typebox";
|
|
9
|
+
import { execFile } from "node:child_process";
|
|
4
10
|
import "@agimon-ai/po-core/packageApi";
|
|
5
11
|
import headless from "@xterm/headless";
|
|
6
12
|
import "@rmux/sdk";
|
|
7
|
-
import { execFile } from "node:child_process";
|
|
8
|
-
import "@agimon-ai/po-core/piSettings";
|
|
9
13
|
import { promisify } from "node:util";
|
|
10
14
|
import "@agimon-ai/foundation-process-registry";
|
|
11
|
-
import "@agimon-ai/po-core/childProcess";
|
|
12
15
|
import "@agimon-ai/po-core/backgroundWork";
|
|
16
|
+
import "typebox/value";
|
|
17
|
+
import "@agimon-ai/po-core/childProcess";
|
|
13
18
|
import "@agimon-ai/po-core/extensionFile";
|
|
14
|
-
import "@agimon-ai/po-telemetry";
|
|
15
19
|
import "@earendil-works/pi-coding-agent";
|
|
16
|
-
//#region src/extensions/workspaces/sessions/(backend)/skill/
|
|
17
|
-
var
|
|
18
|
-
name: "
|
|
20
|
+
//#region src/extensions/workspaces/sessions/(backend)/skill/help-how-to-runner.mcp.ts
|
|
21
|
+
var help_how_to_runner_mcp_default = defineMcpSkill({
|
|
22
|
+
name: "help-how-to-runner",
|
|
19
23
|
description: "Use Po Pi Runner to supervise shell commands, inspect durable logs, provide interactive input, and stop background runs.",
|
|
20
|
-
read: () => readPackageResource(import.meta.url, "src/prompts/
|
|
24
|
+
read: () => readPackageResource(import.meta.url, "src/prompts/help-how-to-runner/SKILL.md")
|
|
21
25
|
});
|
|
22
26
|
//#endregion
|
|
23
27
|
//#region src/constants/runnerSettings.ts
|
|
24
28
|
const RATIO_KEYS = ["headRatio", "errorBudgetRatio"];
|
|
25
29
|
Type.Object({
|
|
26
|
-
command: Type.String({
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
+
command: Type.Array(Type.String({
|
|
31
|
+
minLength: 1,
|
|
32
|
+
maxLength: 65536
|
|
33
|
+
}), {
|
|
34
|
+
minItems: 1,
|
|
35
|
+
maxItems: 32,
|
|
36
|
+
description: "Bash commands to run in order, stopping on first failure. Use a one-item array for one command. Each command gets a full log; return all log paths and only the last executed result. Do not pipe or redirect output to a file, head, or tail. Logs are saved automatically and returned output is bounded."
|
|
37
|
+
}),
|
|
38
|
+
timeout: Type.Optional(Type.Number({ description: "Timeout in seconds for each command (optional, no default timeout)" })),
|
|
39
|
+
background: Type.Optional(Type.Boolean({ description: "Start a long-lived service (dev server, watcher) in the background immediately. Nothing waits for it and you are not woken when it exits. Omit for tests and builds, even slow ones: they move to the background after 60 seconds on their own and wake you when they finish." })),
|
|
40
|
+
interactive: Type.Optional(Type.Boolean({ description: "Run only the last command under a pseudo terminal when it needs input. Earlier commands are noninteractive. Send input to the last stage runner ID with runner.input in code mode, or po-runner input without code mode." })),
|
|
30
41
|
name: Type.Optional(Type.String({ description: "Preferred runner name if the command ends up in the background. A name in use gets a suffix." }))
|
|
31
42
|
});
|
|
32
43
|
new RegExp([
|
|
@@ -46,6 +57,7 @@ new RegExp([
|
|
|
46
57
|
/** Enough history for the overlay to scroll without holding a whole build. */
|
|
47
58
|
const { Terminal: HeadlessTerminal } = headless;
|
|
48
59
|
promisify(execFile);
|
|
60
|
+
promisify(execFile);
|
|
49
61
|
//#endregion
|
|
50
62
|
//#region src/services/runnerSettings/index.ts
|
|
51
63
|
const COUNT_KEYS = [
|
|
@@ -69,7 +81,7 @@ var bash_mcp_default = defineMcpTool((context) => {
|
|
|
69
81
|
if (!scope) throw new Error("Runner session service is unavailable.");
|
|
70
82
|
return {
|
|
71
83
|
...scope.remoteTool,
|
|
72
|
-
description: "Run
|
|
84
|
+
description: "Run an array of shell commands (bash, terminal, CLI) in the Po session's repository on the host machine, not on your local machine. Use a one-item array for one command. Commands run in order and stop on first failure. Only the last command may be interactive. Do not pipe or redirect output to a file, head, or tail: full logs are saved automatically and returned output is bounded. Long-running commands return a sequence id. No completion notice reaches you, so check with `po-runner status <id>` and `po-runner logs <id> --lines 100` instead of relaunching.",
|
|
73
85
|
async execute(toolCallId, parameters, signal, onUpdate, execution) {
|
|
74
86
|
const result = await scope.remoteTool.execute(toolCallId, parameters, AbortSignal.any([context.signal, signal ?? context.signal]), onUpdate, execution);
|
|
75
87
|
const details = result.details;
|
|
@@ -87,9 +99,17 @@ var bash_mcp_default = defineMcpTool((context) => {
|
|
|
87
99
|
//#endregion
|
|
88
100
|
//#region generated/mcp.ts
|
|
89
101
|
const at = (value, context) => typeof value === "function" ? value(context) : value;
|
|
90
|
-
const via = (identity, value) =>
|
|
91
|
-
|
|
92
|
-
|
|
102
|
+
const via = (identity, value) => {
|
|
103
|
+
if (value === void 0) return void 0;
|
|
104
|
+
const declaration = value;
|
|
105
|
+
return {
|
|
106
|
+
...identity,
|
|
107
|
+
...declaration,
|
|
108
|
+
...declaration.relations === void 0 ? {} : { relations: declaration.relations.map((relation) => ({
|
|
109
|
+
evidence: "declared",
|
|
110
|
+
...relation
|
|
111
|
+
})) }
|
|
112
|
+
};
|
|
93
113
|
};
|
|
94
114
|
const withWidget = (key, value) => value === void 0 ? value : {
|
|
95
115
|
...value,
|
|
@@ -102,7 +122,7 @@ const mcp = defineMcpPlugin({
|
|
|
102
122
|
name: "@agimon-ai/po-runner",
|
|
103
123
|
session: (context) => ({
|
|
104
124
|
get skills() {
|
|
105
|
-
return [at(
|
|
125
|
+
return [at(help_how_to_runner_mcp_default, context)];
|
|
106
126
|
},
|
|
107
127
|
get tools() {
|
|
108
128
|
return [withWidget("@agimon-ai/po-runner/bash", via({ name: "bash" }, at(bash_mcp_default, context)))];
|