@ashx-j/lunr 0.2.23 → 0.2.25
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -1
- package/README.md +10 -10
- package/dist/builtin-extensions/ashxj-tui.d.ts.map +1 -1
- package/dist/builtin-extensions/ashxj-tui.js +2 -2
- package/dist/builtin-extensions/ashxj-tui.js.map +1 -1
- package/dist/builtin-extensions/lunr-plan-tools.d.ts +7 -7
- package/dist/builtin-extensions/lunr-plan-tools.d.ts.map +1 -1
- package/dist/builtin-extensions/lunr-plan-tools.js +12 -12
- package/dist/builtin-extensions/lunr-plan-tools.js.map +1 -1
- package/dist/builtin-extensions/pi-intercom/index.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-intercom/index.js +2 -0
- package/dist/builtin-extensions/pi-intercom/index.js.map +1 -1
- package/dist/builtin-extensions/pi-mcp-adapter/direct-tools.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-mcp-adapter/direct-tools.js +1 -0
- package/dist/builtin-extensions/pi-mcp-adapter/direct-tools.js.map +1 -1
- package/dist/builtin-extensions/pi-mcp-adapter/index.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-mcp-adapter/index.js +1 -1
- package/dist/builtin-extensions/pi-mcp-adapter/index.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/extension/schemas.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/extension/schemas.js +1 -1
- package/dist/builtin-extensions/pi-subagents/src/extension/schemas.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/extension/tool-description.d.ts +4 -4
- package/dist/builtin-extensions/pi-subagents/src/extension/tool-description.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/extension/tool-description.js +6 -4
- package/dist/builtin-extensions/pi-subagents/src/extension/tool-description.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/intercom/intercom-bridge.d.ts +2 -0
- package/dist/builtin-extensions/pi-subagents/src/intercom/intercom-bridge.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/intercom/intercom-bridge.js +6 -3
- package/dist/builtin-extensions/pi-subagents/src/intercom/intercom-bridge.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/intercom/native-supervisor-channel.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/intercom/native-supervisor-channel.js +7 -2
- package/dist/builtin-extensions/pi-subagents/src/intercom/native-supervisor-channel.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/background/async-execution.d.ts +2 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/background/async-execution.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/background/async-execution.js +4 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/background/async-execution.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/background/subagent-runner.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/background/subagent-runner.js +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/background/subagent-runner.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/chain-execution.d.ts +1 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/chain-execution.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/chain-execution.js +5 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/chain-execution.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/execution.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/execution.js +3 -2
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/execution.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.js +19 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/shared/child-tools.d.ts +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/shared/child-tools.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/shared/child-tools.js +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/shared/child-tools.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/shared/pi-args.d.ts +2 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/shared/pi-args.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/shared/pi-args.js +17 -15
- package/dist/builtin-extensions/pi-subagents/src/runs/shared/pi-args.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/shared/subagent-prompt-runtime.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/shared/subagent-prompt-runtime.js +3 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/shared/subagent-prompt-runtime.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/shared/child-spec.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/shared/child-spec.js +2 -2
- package/dist/builtin-extensions/pi-subagents/src/shared/child-spec.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/shared/types.d.ts +1 -0
- package/dist/builtin-extensions/pi-subagents/src/shared/types.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/shared/types.js.map +1 -1
- package/dist/core/agent-session.d.ts +1 -1
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +5 -4
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/browser/schema.d.ts +1 -1
- package/dist/core/browser/schema.d.ts.map +1 -1
- package/dist/core/browser/schema.js +1 -1
- package/dist/core/browser/schema.js.map +1 -1
- package/dist/core/catalog-cache-scope.d.ts.map +1 -1
- package/dist/core/catalog-cache-scope.js +3 -1
- package/dist/core/catalog-cache-scope.js.map +1 -1
- package/dist/core/model-runtime.d.ts.map +1 -1
- package/dist/core/model-runtime.js +3 -2
- package/dist/core/model-runtime.js.map +1 -1
- package/dist/core/permissions.d.ts +16 -23
- package/dist/core/permissions.d.ts.map +1 -1
- package/dist/core/permissions.js +66 -141
- package/dist/core/permissions.js.map +1 -1
- package/dist/core/plan-mode.d.ts +10 -12
- package/dist/core/plan-mode.d.ts.map +1 -1
- package/dist/core/plan-mode.js +16 -18
- package/dist/core/plan-mode.js.map +1 -1
- package/dist/core/runtime-bridges.d.ts.map +1 -1
- package/dist/core/runtime-bridges.js +2 -0
- package/dist/core/runtime-bridges.js.map +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +13 -6
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +9 -2
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/settings-manager.d.ts +9 -1
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +40 -1
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/slash-commands.d.ts.map +1 -1
- package/dist/core/slash-commands.js +4 -4
- package/dist/core/slash-commands.js.map +1 -1
- package/dist/core/subagent-permission-inherit.d.ts +6 -10
- package/dist/core/subagent-permission-inherit.d.ts.map +1 -1
- package/dist/core/subagent-permission-inherit.js +14 -14
- package/dist/core/subagent-permission-inherit.js.map +1 -1
- package/dist/core/system-prompt.d.ts +2 -0
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +9 -4
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/gateway/adapters/discord.d.ts.map +1 -1
- package/dist/gateway/adapters/discord.js +3 -8
- package/dist/gateway/adapters/discord.js.map +1 -1
- package/dist/gateway/adapters/telegram.d.ts.map +1 -1
- package/dist/gateway/adapters/telegram.js +7 -0
- package/dist/gateway/adapters/telegram.js.map +1 -1
- package/dist/gateway/agent-bridge.d.ts +4 -1
- package/dist/gateway/agent-bridge.d.ts.map +1 -1
- package/dist/gateway/agent-bridge.js +57 -17
- package/dist/gateway/agent-bridge.js.map +1 -1
- package/dist/gateway/approval.d.ts +2 -6
- package/dist/gateway/approval.d.ts.map +1 -1
- package/dist/gateway/approval.js +3 -7
- package/dist/gateway/approval.js.map +1 -1
- package/dist/gateway/buttons.d.ts.map +1 -1
- package/dist/gateway/buttons.js +29 -19
- package/dist/gateway/buttons.js.map +1 -1
- package/dist/gateway/commands.d.ts +2 -0
- package/dist/gateway/commands.d.ts.map +1 -1
- package/dist/gateway/commands.js +39 -18
- package/dist/gateway/commands.js.map +1 -1
- package/dist/gateway/config.d.ts +1 -0
- package/dist/gateway/config.d.ts.map +1 -1
- package/dist/gateway/config.js +2 -0
- package/dist/gateway/config.js.map +1 -1
- package/dist/gateway/cron.d.ts +1 -1
- package/dist/gateway/cron.d.ts.map +1 -1
- package/dist/gateway/cron.js +2 -2
- package/dist/gateway/cron.js.map +1 -1
- package/dist/gateway/index.d.ts.map +1 -1
- package/dist/gateway/index.js +26 -26
- package/dist/gateway/index.js.map +1 -1
- package/dist/gateway/mobile-commands.d.ts.map +1 -1
- package/dist/gateway/mobile-commands.js +15 -14
- package/dist/gateway/mobile-commands.js.map +1 -1
- package/dist/gateway/presenter.d.ts +12 -1
- package/dist/gateway/presenter.d.ts.map +1 -1
- package/dist/gateway/presenter.js +146 -48
- package/dist/gateway/presenter.js.map +1 -1
- package/dist/gateway/router.d.ts +5 -5
- package/dist/gateway/router.d.ts.map +1 -1
- package/dist/gateway/router.js +96 -42
- package/dist/gateway/router.js.map +1 -1
- package/dist/gateway/service.d.ts.map +1 -1
- package/dist/gateway/service.js +13 -4
- package/dist/gateway/service.js.map +1 -1
- package/dist/gateway/setup.d.ts +5 -0
- package/dist/gateway/setup.d.ts.map +1 -1
- package/dist/gateway/setup.js +98 -42
- package/dist/gateway/setup.js.map +1 -1
- package/dist/gateway/stream.d.ts +6 -5
- package/dist/gateway/stream.d.ts.map +1 -1
- package/dist/gateway/stream.js +24 -11
- package/dist/gateway/stream.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +1 -2
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector.d.ts +4 -0
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +23 -3
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/components/thinking-tail.d.ts.map +1 -1
- package/dist/modes/interactive/components/thinking-tail.js +2 -2
- package/dist/modes/interactive/components/thinking-tail.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts +1 -0
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +12 -2
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +1 -2
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +76 -90
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/node-runtime/{agent-session-services-GZVSOGYR.js → agent-session-services-YXXFCP5J.js} +12 -12
- package/dist/node-runtime/{builtin-extensions-QVCXNQT4.js → builtin-extensions-ZLAX7TUH.js} +3 -3
- package/dist/node-runtime/{chunk-W64JC4E7.js → chunk-2HHLJWGD.js} +3 -87
- package/dist/node-runtime/{chunk-VWCE2HSZ.js → chunk-2HMIRK7W.js} +4 -4
- package/dist/node-runtime/{chunk-XLTL257W.js → chunk-2KIPT4HJ.js} +5 -1
- package/dist/node-runtime/{chunk-RIR5EDDJ.js → chunk-3XPLBUEM.js} +17 -12
- package/dist/node-runtime/{chunk-QAZOULTU.js → chunk-6XL67VVY.js} +40 -6
- package/dist/node-runtime/chunk-7S3T6YEA.js +97 -0
- package/dist/node-runtime/{chunk-R3K2F5GI.js → chunk-B4HP6ZWM.js} +2 -0
- package/dist/node-runtime/{chunk-TQGPP4SC.js → chunk-CDVHZOOK.js} +1 -1
- package/dist/node-runtime/{chunk-YJMMG7C6.js → chunk-DSIKTUPW.js} +1 -1
- package/dist/node-runtime/{chunk-LFZDVKSP.js → chunk-E4D3IGP2.js} +41 -25
- package/dist/node-runtime/{chunk-OFKSVRV7.js → chunk-GYIXXQAO.js} +1 -1
- package/dist/node-runtime/{chunk-BX2RB477.js → chunk-HFVZUPFJ.js} +1 -1
- package/dist/node-runtime/{chunk-AZJHNQKQ.js → chunk-I54LGHWM.js} +1 -1
- package/dist/node-runtime/{chunk-YHQ3NBB3.js → chunk-IJIFHRTB.js} +20 -18
- package/dist/node-runtime/{chunk-GS66LV4M.js → chunk-KJ6DWS3K.js} +4 -4
- package/dist/node-runtime/{chunk-HPUP7E4T.js → chunk-KWIYUUZK.js} +68 -42
- package/dist/node-runtime/{chunk-TVJUOJZJ.js → chunk-LQP3RB67.js} +184 -1527
- package/dist/node-runtime/{chunk-VSELYKWU.js → chunk-LWYIVUGV.js} +2 -1
- package/dist/node-runtime/{chunk-JHYKXIMM.js → chunk-MPKSOJBT.js} +1 -1
- package/dist/node-runtime/{chunk-GMHJCCEN.js → chunk-NRKGMJYU.js} +4 -1
- package/dist/node-runtime/{chunk-CSUZVNYE.js → chunk-OVX6X377.js} +10 -6
- package/dist/node-runtime/{chunk-DD5YWFSJ.js → chunk-QTU6AKNJ.js} +130 -65
- package/dist/node-runtime/{chunk-LLUIPGDR.js → chunk-RC7DMV45.js} +110 -77
- package/dist/node-runtime/{chunk-UWPJL22I.js → chunk-SLVOAQOY.js} +15 -4
- package/dist/node-runtime/{chunk-EKVFP6YF.js → chunk-TORR5XBV.js} +17 -16
- package/dist/node-runtime/{chunk-UP2XBVH5.js → chunk-UOEDI7RP.js} +1 -1
- package/dist/node-runtime/{chunk-DQMGU675.js → chunk-VQFSUJJG.js} +20 -17
- package/dist/node-runtime/{chunk-X3URCYCU.js → chunk-WF7PGWRZ.js} +14 -14
- package/dist/node-runtime/chunk-YCUZEGJG.js +1361 -0
- package/dist/node-runtime/{chunk-5D7LC2ZQ.js → chunk-ZXSGTGJ6.js} +54 -85
- package/dist/node-runtime/cli-runtime.js +1 -1
- package/dist/node-runtime/{command-PDVTBRWA.js → command-6WDOYKS6.js} +5 -5
- package/dist/node-runtime/{commands-KAMO2T6P.js → commands-NZLSOHPE.js} +2 -2
- package/dist/node-runtime/{commands-XDCFGIGW.js → commands-QC6VUZJQ.js} +9 -9
- package/dist/node-runtime/{config-RORQUQFG.js → config-D4QUPAHX.js} +1 -1
- package/dist/node-runtime/{direct-tool-executor-YAVOLDFY.js → direct-tool-executor-77GW4F5P.js} +3 -3
- package/dist/node-runtime/{export-html-KSOIMVPI.js → export-html-VM4J2MNR.js} +1 -1
- package/dist/node-runtime/{gateway-AYWM5DIO.js → gateway-INAYBF4Q.js} +141 -85
- package/dist/node-runtime/index.js +23 -21
- package/dist/node-runtime/{init-X2LIUB2H.js → init-HS6NQXSK.js} +2 -2
- package/dist/node-runtime/{install-cli-3BO4MMQ6.js → install-cli-KL4UDDAD.js} +3 -3
- package/dist/node-runtime/{interactive-mode-4MFRKAHG.js → interactive-mode-Z5M7WYYZ.js} +14 -14
- package/dist/node-runtime/{interactive-view-TUZHCQM3.js → interactive-view-NGFAMHPW.js} +2 -2
- package/dist/node-runtime/{lunr-browser-RYFIIVJN.js → lunr-browser-IR7TL3J7.js} +4 -4
- package/dist/node-runtime/{lunr-cron-YWXEPZMQ.js → lunr-cron-LWIZJM2N.js} +8 -8
- package/dist/node-runtime/main.js +19 -18
- package/dist/node-runtime/{mobile-commands-LVHDAUDP.js → mobile-commands-J7OJEKFO.js} +6 -6
- package/dist/node-runtime/{model-runtime-PLQKAG4B.js → model-runtime-OO5HFLWE.js} +1 -1
- package/dist/node-runtime/{package-manager-cli-6GT3Z3CK.js → package-manager-cli-VYZM5WHN.js} +10 -8
- package/dist/node-runtime/{pi-intercom-HBPK5HSJ.js → pi-intercom-QM53RLTS.js} +2 -0
- package/dist/node-runtime/{pi-mcp-adapter-E6WULBKF.js → pi-mcp-adapter-5UKBZP44.js} +7 -6
- package/dist/node-runtime/{pi-subagents-CDWK2AKY.js → pi-subagents-DNY7EAIG.js} +23 -13
- package/dist/node-runtime/{proxy-modes-OSQCWRBI.js → proxy-modes-LGEUYD7R.js} +3 -3
- package/dist/node-runtime/rpc-entry.js +19 -18
- package/dist/node-runtime/{runtime-bridges-3XUQ46XW.js → runtime-bridges-VRDDR73P.js} +8 -1
- package/dist/node-runtime/{service-ISSP6VHE.js → service-MDQIPQ26.js} +1 -1
- package/dist/node-runtime/{session-handoff-HC7R5E24.js → session-handoff-GWARVEWT.js} +2 -2
- package/dist/node-runtime/{session-manager-CFN4UFM2.js → session-manager-JB5J6XBN.js} +1 -1
- package/dist/node-runtime/{settings-manager-6VEMXRDL.js → settings-manager-J4SPQPDJ.js} +10 -7
- package/dist/node-runtime/setup-CQ2NLVK5.js +214 -0
- package/dist/node-runtime/{subagent-executor-M5VWB3D3.js → subagent-executor-KZZQGAKV.js} +40 -7
- package/dist/node-runtime/{update-cli-UVKJWRRJ.js → update-cli-GTFJC7XK.js} +4 -5
- package/dist/startup/interactive-view.d.ts.map +1 -1
- package/dist/startup/interactive-view.js +5 -1
- package/dist/startup/interactive-view.js.map +1 -1
- package/docs/browser.md +1 -1
- package/docs/features.md +19 -18
- package/docs/index.md +1 -1
- package/docs/keybindings.md +1 -1
- package/docs/providers.md +6 -2
- package/docs/quickstart.md +2 -2
- package/docs/settings.md +1 -1
- package/docs/usage.md +4 -4
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/plan-mode/README.md +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/package.json +4 -4
- package/dist/node-runtime/chunk-LISUTZS3.js +0 -19
- package/dist/node-runtime/setup-5SR2J35A.js +0 -155
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"intercom-bridge.d.ts","sourceRoot":"","sources":["../../../../../src/builtin-extensions/pi-subagents/src/intercom/intercom-bridge.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"intercom-bridge.d.ts","sourceRoot":"","sources":["../../../../../src/builtin-extensions/pi-subagents/src/intercom/intercom-bridge.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAC7D,OAAO,KAAK,EAAE,eAAe,EAAwB,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAGpG,eAAO,MAAM,6BAA6B,2CAA2C,CAAC;AAWtF,eAAO,MAAM,sBAAsB,oCAAoC,CAAC;AAMxE,MAAM,WAAW,mBAAmB;IACnC,MAAM,EAAE,OAAO,CAAC;IAChB,oBAAoB,EAAE,OAAO,CAAC;IAC9B,IAAI,EAAE,kBAAkB,CAAC;IACzB,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,YAAY,EAAE,MAAM,CAAC;IACrB,WAAW,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,wBAAwB;IACxC,MAAM,EAAE,OAAO,CAAC;IAChB,IAAI,EAAE,kBAAkB,CAAC;IACzB,aAAa,EAAE,OAAO,CAAC;IACvB,0BAA0B,EAAE,OAAO,CAAC;IACpC,YAAY,EAAE,MAAM,CAAC;IACrB,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,MAAM,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,UAAU,0BAA0B;IACnC,MAAM,EAAE,eAAe,CAAC,gBAAgB,CAAC,CAAC;IAC1C,OAAO,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAAC;IACtC,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,GAAG,CAAC,EAAE,MAAM,CAAC;CACb;AAED,wBAAgB,4BAA4B,CAAC,WAAW,EAAE,MAAM,GAAG,SAAS,EAAE,SAAS,EAAE,MAAM,GAAG,MAAM,CAKvG;AAMD,wBAAgB,6BAA6B,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,GAAG,MAAM,CAGlG;AAED,wBAAgB,yBAAyB,CAAC,KAAK,EAAE,OAAO,GAAG,kBAAkB,CAG5E;AA2CD,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,0BAA0B,GAAG,wBAAwB,CAelG;AAED,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,0BAA0B,GAAG,mBAAmB,CAuB5F;AAED,wBAAgB,0BAA0B,CAAC,KAAK,EAAE,kBAAkB,EAAE,MAAM,EAAE,mBAAmB,GAAG,kBAAkB,CAqBrH","sourcesContent":["// @ts-nocheck\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport { subagentCommunicationEnabled } from \"../../../../core/settings-manager.ts\";\nimport type { ChildRuntimeConfig } from \"../shared/types.ts\";\nimport type { ExtensionConfig, IntercomBridgeConfig, IntercomBridgeMode } from \"../shared/types.ts\";\nimport { getAgentDir } from \"../shared/utils.ts\";\n\nexport const NATIVE_INTERCOM_EXTENSION_DIR = \"native:pi-subagents-supervisor-channel\";\n\nfunction defaultAgentDir(): string {\n\treturn getAgentDir();\n}\n\nfunction defaultSubagentConfigDir(agentDir = defaultAgentDir()): string {\n\treturn path.join(agentDir, \"extensions\", \"subagent\");\n}\n\nconst DEFAULT_INTERCOM_TARGET_PREFIX = \"subagent-chat\";\nexport const INTERCOM_BRIDGE_MARKER = \"Intercom orchestration channel:\";\nconst DEFAULT_INTERCOM_BRIDGE_TEMPLATE = `You own reversible implementation decisions within your assigned scope. Use contact_supervisor for coordination with \"{orchestratorTarget}\"; its tool description defines delivery and reply behavior.\nConsolidate dependency findings into one handoff when another task needs them before completion. Escalate permission, safety, scope changes, or a blocked decision with evidence and your recommended choice. Continue independent work before opening a blocking request.\nNative intercom reaches only the supervisor, not siblings. Use the supplied contracts and artifacts instead of discovering sibling sessions.\nReturn one self-contained final result; the runtime delivers it. If you cannot write a configured output artifact with your available tools, return its complete contents for the runtime to persist.`;\n\nexport interface IntercomBridgeState {\n\tactive: boolean;\n\tcommunicationEnabled: boolean;\n\tmode: IntercomBridgeMode;\n\torchestratorTarget?: string;\n\textensionDir: string;\n\tinstruction: string;\n}\n\nexport interface IntercomBridgeDiagnostic {\n\tactive: boolean;\n\tmode: IntercomBridgeMode;\n\twantsIntercom: boolean;\n\tsupervisorChannelAvailable: boolean;\n\textensionDir: string;\n\torchestratorTarget?: string;\n\treason?: string;\n}\n\ninterface ResolveIntercomBridgeInput {\n\tconfig: ExtensionConfig[\"intercomBridge\"];\n\tcontext: \"fresh\" | \"fork\" | undefined;\n\torchestratorTarget?: string;\n\tsettingsDir?: string;\n\tagentDir?: string;\n\tcwd?: string;\n}\n\nexport function resolveIntercomSessionTarget(sessionName: string | undefined, sessionId: string): string {\n\tconst trimmedName = sessionName?.trim();\n\tif (trimmedName) return trimmedName;\n\tconst normalizedSessionId = sessionId.startsWith(\"session-\") ? sessionId.slice(\"session-\".length) : sessionId;\n\treturn `${DEFAULT_INTERCOM_TARGET_PREFIX}-${normalizedSessionId.slice(0, 8)}`;\n}\n\nfunction sanitizeIntercomTargetPart(value: string): string {\n\treturn value.trim().toLowerCase().replace(/[^a-z0-9_-]+/g, \"-\").replace(/^-+|-+$/g, \"\") || \"agent\";\n}\n\nexport function resolveSubagentIntercomTarget(runId: string, agent: string, index?: number): string {\n\tconst stepSuffix = index !== undefined ? `-${index + 1}` : \"\";\n\treturn `subagent-${sanitizeIntercomTargetPart(agent)}-${sanitizeIntercomTargetPart(runId)}${stepSuffix}`;\n}\n\nexport function resolveIntercomBridgeMode(value: unknown): IntercomBridgeMode {\n\tif (value === \"off\" || value === \"always\" || value === \"fork-only\") return value;\n\treturn \"always\";\n}\n\nfunction resolveIntercomBridgeConfig(value: ExtensionConfig[\"intercomBridge\"]): Required<IntercomBridgeConfig> {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) {\n\t\treturn { mode: \"always\", instructionFile: \"\" };\n\t}\n\treturn {\n\t\tmode: resolveIntercomBridgeMode(value.mode),\n\t\tinstructionFile: typeof value.instructionFile === \"string\" ? value.instructionFile : \"\",\n\t};\n}\n\nfunction expandTilde(filePath: string): string {\n\treturn filePath.startsWith(\"~/\") ? path.join(os.homedir(), filePath.slice(2)) : filePath;\n}\n\nfunction resolveInstructionTemplate(instructionFile: string, settingsDir: string): string {\n\tif (!instructionFile) return DEFAULT_INTERCOM_BRIDGE_TEMPLATE;\n\tconst expandedPath = expandTilde(instructionFile);\n\tconst resolvedPath = path.isAbsolute(expandedPath)\n\t\t? expandedPath\n\t\t: path.resolve(settingsDir, expandedPath);\n\ttry {\n\t\treturn fs.readFileSync(resolvedPath, \"utf-8\");\n\t} catch (error) {\n\t\tconsole.warn(`Failed to read intercom bridge instructionFile at '${resolvedPath}'. Using default instructions.`, error);\n\t\treturn DEFAULT_INTERCOM_BRIDGE_TEMPLATE;\n\t}\n}\n\nfunction buildIntercomBridgeInstruction(orchestratorTarget: string, template: string): string {\n\tconst instruction = template.replaceAll(\"{orchestratorTarget}\", orchestratorTarget).trim();\n\tif (instruction.startsWith(INTERCOM_BRIDGE_MARKER)) return instruction;\n\treturn `${INTERCOM_BRIDGE_MARKER}\\n${instruction}`;\n}\n\nfunction inactiveReason(mode: IntercomBridgeMode, context: \"fresh\" | \"fork\" | undefined, orchestratorTarget: string | undefined): string | undefined {\n\tif (mode === \"off\") return \"bridge mode is off\";\n\tif (mode === \"fork-only\" && context !== \"fork\") return \"bridge mode is fork-only and context is not fork\";\n\tif (!orchestratorTarget) return \"orchestrator target is not available\";\n\treturn undefined;\n}\n\nexport function diagnoseIntercomBridge(input: ResolveIntercomBridgeInput): IntercomBridgeDiagnostic {\n\tconst config = resolveIntercomBridgeConfig(input.config);\n\tconst mode = subagentCommunicationEnabled(input.cwd ?? process.cwd(), input.agentDir ?? defaultAgentDir()) ? config.mode : \"off\";\n\tconst orchestratorTarget = input.orchestratorTarget?.trim();\n\tconst wantsIntercom = mode !== \"off\" && !(mode === \"fork-only\" && input.context !== \"fork\");\n\tconst reason = inactiveReason(mode, input.context, orchestratorTarget);\n\treturn {\n\t\tactive: reason === undefined,\n\t\tmode,\n\t\twantsIntercom,\n\t\tsupervisorChannelAvailable: true,\n\t\textensionDir: NATIVE_INTERCOM_EXTENSION_DIR,\n\t\t...(orchestratorTarget ? { orchestratorTarget } : {}),\n\t\t...(reason ? { reason } : {}),\n\t};\n}\n\nexport function resolveIntercomBridge(input: ResolveIntercomBridgeInput): IntercomBridgeState {\n\tconst config = resolveIntercomBridgeConfig(input.config);\n\tconst communicationEnabled = subagentCommunicationEnabled(input.cwd ?? process.cwd(), input.agentDir ?? defaultAgentDir());\n\tconst mode = communicationEnabled ? config.mode : \"off\";\n\tconst orchestratorTarget = input.orchestratorTarget?.trim();\n\tconst agentDir = path.resolve(input.agentDir ?? defaultAgentDir());\n\tconst settingsDir = path.resolve(input.settingsDir ?? defaultSubagentConfigDir(agentDir));\n\tconst defaultInstruction = buildIntercomBridgeInstruction(\n\t\torchestratorTarget || \"{orchestratorTarget}\",\n\t\tDEFAULT_INTERCOM_BRIDGE_TEMPLATE,\n\t);\n\tconst reason = inactiveReason(mode, input.context, orchestratorTarget);\n\tif (reason || !orchestratorTarget) {\n\t\treturn { active: false, communicationEnabled, mode, extensionDir: NATIVE_INTERCOM_EXTENSION_DIR, instruction: defaultInstruction };\n\t}\n\treturn {\n\t\tactive: true,\n\t\tcommunicationEnabled,\n\t\tmode,\n\t\torchestratorTarget,\n\t\textensionDir: NATIVE_INTERCOM_EXTENSION_DIR,\n\t\tinstruction: buildIntercomBridgeInstruction(orchestratorTarget, resolveInstructionTemplate(config.instructionFile, settingsDir)),\n\t};\n}\n\nexport function applyIntercomBridgeToAgent(agent: ChildRuntimeConfig, bridge: IntercomBridgeState): ChildRuntimeConfig {\n\tif (!bridge.active || !bridge.orchestratorTarget) return agent;\n\n\tconst bridgeTools = [\"intercom\", \"contact_supervisor\"];\n\tconst tools = agent.tools\n\t\t? [...agent.tools, ...bridgeTools.filter((tool) => !agent.tools?.includes(tool))]\n\t\t: agent.tools;\n\tconst instruction = bridge.instruction;\n\tconst trimmedPrompt = agent.systemPrompt?.trim() || \"\";\n\tconst systemPrompt = trimmedPrompt.includes(INTERCOM_BRIDGE_MARKER)\n\t\t? trimmedPrompt\n\t\t: trimmedPrompt\n\t\t\t? `${trimmedPrompt}\\n\\n${instruction}`\n\t\t\t: instruction;\n\n\tif (tools === agent.tools && systemPrompt === agent.systemPrompt) return agent;\n\treturn {\n\t\t...agent,\n\t\ttools,\n\t\tsystemPrompt,\n\t};\n}\n"]}
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
import * as fs from "node:fs";
|
|
3
3
|
import * as os from "node:os";
|
|
4
4
|
import * as path from "node:path";
|
|
5
|
+
import { subagentCommunicationEnabled } from "../../../../core/settings-manager.js";
|
|
5
6
|
import { getAgentDir } from "../shared/utils.js";
|
|
6
7
|
export const NATIVE_INTERCOM_EXTENSION_DIR = "native:pi-subagents-supervisor-channel";
|
|
7
8
|
function defaultAgentDir() {
|
|
@@ -79,7 +80,7 @@ function inactiveReason(mode, context, orchestratorTarget) {
|
|
|
79
80
|
}
|
|
80
81
|
export function diagnoseIntercomBridge(input) {
|
|
81
82
|
const config = resolveIntercomBridgeConfig(input.config);
|
|
82
|
-
const mode = config.mode;
|
|
83
|
+
const mode = subagentCommunicationEnabled(input.cwd ?? process.cwd(), input.agentDir ?? defaultAgentDir()) ? config.mode : "off";
|
|
83
84
|
const orchestratorTarget = input.orchestratorTarget?.trim();
|
|
84
85
|
const wantsIntercom = mode !== "off" && !(mode === "fork-only" && input.context !== "fork");
|
|
85
86
|
const reason = inactiveReason(mode, input.context, orchestratorTarget);
|
|
@@ -95,17 +96,19 @@ export function diagnoseIntercomBridge(input) {
|
|
|
95
96
|
}
|
|
96
97
|
export function resolveIntercomBridge(input) {
|
|
97
98
|
const config = resolveIntercomBridgeConfig(input.config);
|
|
98
|
-
const
|
|
99
|
+
const communicationEnabled = subagentCommunicationEnabled(input.cwd ?? process.cwd(), input.agentDir ?? defaultAgentDir());
|
|
100
|
+
const mode = communicationEnabled ? config.mode : "off";
|
|
99
101
|
const orchestratorTarget = input.orchestratorTarget?.trim();
|
|
100
102
|
const agentDir = path.resolve(input.agentDir ?? defaultAgentDir());
|
|
101
103
|
const settingsDir = path.resolve(input.settingsDir ?? defaultSubagentConfigDir(agentDir));
|
|
102
104
|
const defaultInstruction = buildIntercomBridgeInstruction(orchestratorTarget || "{orchestratorTarget}", DEFAULT_INTERCOM_BRIDGE_TEMPLATE);
|
|
103
105
|
const reason = inactiveReason(mode, input.context, orchestratorTarget);
|
|
104
106
|
if (reason || !orchestratorTarget) {
|
|
105
|
-
return { active: false, mode, extensionDir: NATIVE_INTERCOM_EXTENSION_DIR, instruction: defaultInstruction };
|
|
107
|
+
return { active: false, communicationEnabled, mode, extensionDir: NATIVE_INTERCOM_EXTENSION_DIR, instruction: defaultInstruction };
|
|
106
108
|
}
|
|
107
109
|
return {
|
|
108
110
|
active: true,
|
|
111
|
+
communicationEnabled,
|
|
109
112
|
mode,
|
|
110
113
|
orchestratorTarget,
|
|
111
114
|
extensionDir: NATIVE_INTERCOM_EXTENSION_DIR,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"intercom-bridge.js","sourceRoot":"","sources":["../../../../../src/builtin-extensions/pi-subagents/src/intercom/intercom-bridge.ts"],"names":[],"mappings":"AAAA,cAAc;AACd,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,KAAK,IAAI,MA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,GAAG,KAAK;QACR,KAAK;QACL,YAAY;KACZ,CAAC;AAAA,CACF","sourcesContent":["// @ts-nocheck\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport type { ChildRuntimeConfig } from \"../shared/types.ts\";\nimport type { ExtensionConfig, IntercomBridgeConfig, IntercomBridgeMode } from \"../shared/types.ts\";\nimport { getAgentDir } from \"../shared/utils.ts\";\n\nexport const NATIVE_INTERCOM_EXTENSION_DIR = \"native:pi-subagents-supervisor-channel\";\n\nfunction defaultAgentDir(): string {\n\treturn getAgentDir();\n}\n\nfunction defaultSubagentConfigDir(agentDir = defaultAgentDir()): string {\n\treturn path.join(agentDir, \"extensions\", \"subagent\");\n}\n\nconst DEFAULT_INTERCOM_TARGET_PREFIX = \"subagent-chat\";\nexport const INTERCOM_BRIDGE_MARKER = \"Intercom orchestration channel:\";\nconst DEFAULT_INTERCOM_BRIDGE_TEMPLATE = `You own reversible implementation decisions within your assigned scope. Use contact_supervisor for coordination with \"{orchestratorTarget}\"; its tool description defines delivery and reply behavior.\nConsolidate dependency findings into one handoff when another task needs them before completion. Escalate permission, safety, scope changes, or a blocked decision with evidence and your recommended choice. Continue independent work before opening a blocking request.\nNative intercom reaches only the supervisor, not siblings. Use the supplied contracts and artifacts instead of discovering sibling sessions.\nReturn one self-contained final result; the runtime delivers it. If you cannot write a configured output artifact with your available tools, return its complete contents for the runtime to persist.`;\n\nexport interface IntercomBridgeState {\n\tactive: boolean;\n\tmode: IntercomBridgeMode;\n\torchestratorTarget?: string;\n\textensionDir: string;\n\tinstruction: string;\n}\n\nexport interface IntercomBridgeDiagnostic {\n\tactive: boolean;\n\tmode: IntercomBridgeMode;\n\twantsIntercom: boolean;\n\tsupervisorChannelAvailable: boolean;\n\textensionDir: string;\n\torchestratorTarget?: string;\n\treason?: string;\n}\n\ninterface ResolveIntercomBridgeInput {\n\tconfig: ExtensionConfig[\"intercomBridge\"];\n\tcontext: \"fresh\" | \"fork\" | undefined;\n\torchestratorTarget?: string;\n\tsettingsDir?: string;\n\tagentDir?: string;\n}\n\nexport function resolveIntercomSessionTarget(sessionName: string | undefined, sessionId: string): string {\n\tconst trimmedName = sessionName?.trim();\n\tif (trimmedName) return trimmedName;\n\tconst normalizedSessionId = sessionId.startsWith(\"session-\") ? sessionId.slice(\"session-\".length) : sessionId;\n\treturn `${DEFAULT_INTERCOM_TARGET_PREFIX}-${normalizedSessionId.slice(0, 8)}`;\n}\n\nfunction sanitizeIntercomTargetPart(value: string): string {\n\treturn value.trim().toLowerCase().replace(/[^a-z0-9_-]+/g, \"-\").replace(/^-+|-+$/g, \"\") || \"agent\";\n}\n\nexport function resolveSubagentIntercomTarget(runId: string, agent: string, index?: number): string {\n\tconst stepSuffix = index !== undefined ? `-${index + 1}` : \"\";\n\treturn `subagent-${sanitizeIntercomTargetPart(agent)}-${sanitizeIntercomTargetPart(runId)}${stepSuffix}`;\n}\n\nexport function resolveIntercomBridgeMode(value: unknown): IntercomBridgeMode {\n\tif (value === \"off\" || value === \"always\" || value === \"fork-only\") return value;\n\treturn \"always\";\n}\n\nfunction resolveIntercomBridgeConfig(value: ExtensionConfig[\"intercomBridge\"]): Required<IntercomBridgeConfig> {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) {\n\t\treturn { mode: \"always\", instructionFile: \"\" };\n\t}\n\treturn {\n\t\tmode: resolveIntercomBridgeMode(value.mode),\n\t\tinstructionFile: typeof value.instructionFile === \"string\" ? value.instructionFile : \"\",\n\t};\n}\n\nfunction expandTilde(filePath: string): string {\n\treturn filePath.startsWith(\"~/\") ? path.join(os.homedir(), filePath.slice(2)) : filePath;\n}\n\nfunction resolveInstructionTemplate(instructionFile: string, settingsDir: string): string {\n\tif (!instructionFile) return DEFAULT_INTERCOM_BRIDGE_TEMPLATE;\n\tconst expandedPath = expandTilde(instructionFile);\n\tconst resolvedPath = path.isAbsolute(expandedPath)\n\t\t? expandedPath\n\t\t: path.resolve(settingsDir, expandedPath);\n\ttry {\n\t\treturn fs.readFileSync(resolvedPath, \"utf-8\");\n\t} catch (error) {\n\t\tconsole.warn(`Failed to read intercom bridge instructionFile at '${resolvedPath}'. Using default instructions.`, error);\n\t\treturn DEFAULT_INTERCOM_BRIDGE_TEMPLATE;\n\t}\n}\n\nfunction buildIntercomBridgeInstruction(orchestratorTarget: string, template: string): string {\n\tconst instruction = template.replaceAll(\"{orchestratorTarget}\", orchestratorTarget).trim();\n\tif (instruction.startsWith(INTERCOM_BRIDGE_MARKER)) return instruction;\n\treturn `${INTERCOM_BRIDGE_MARKER}\\n${instruction}`;\n}\n\nfunction inactiveReason(mode: IntercomBridgeMode, context: \"fresh\" | \"fork\" | undefined, orchestratorTarget: string | undefined): string | undefined {\n\tif (mode === \"off\") return \"bridge mode is off\";\n\tif (mode === \"fork-only\" && context !== \"fork\") return \"bridge mode is fork-only and context is not fork\";\n\tif (!orchestratorTarget) return \"orchestrator target is not available\";\n\treturn undefined;\n}\n\nexport function diagnoseIntercomBridge(input: ResolveIntercomBridgeInput): IntercomBridgeDiagnostic {\n\tconst config = resolveIntercomBridgeConfig(input.config);\n\tconst mode = config.mode;\n\tconst orchestratorTarget = input.orchestratorTarget?.trim();\n\tconst wantsIntercom = mode !== \"off\" && !(mode === \"fork-only\" && input.context !== \"fork\");\n\tconst reason = inactiveReason(mode, input.context, orchestratorTarget);\n\treturn {\n\t\tactive: reason === undefined,\n\t\tmode,\n\t\twantsIntercom,\n\t\tsupervisorChannelAvailable: true,\n\t\textensionDir: NATIVE_INTERCOM_EXTENSION_DIR,\n\t\t...(orchestratorTarget ? { orchestratorTarget } : {}),\n\t\t...(reason ? { reason } : {}),\n\t};\n}\n\nexport function resolveIntercomBridge(input: ResolveIntercomBridgeInput): IntercomBridgeState {\n\tconst config = resolveIntercomBridgeConfig(input.config);\n\tconst mode = config.mode;\n\tconst orchestratorTarget = input.orchestratorTarget?.trim();\n\tconst agentDir = path.resolve(input.agentDir ?? defaultAgentDir());\n\tconst settingsDir = path.resolve(input.settingsDir ?? defaultSubagentConfigDir(agentDir));\n\tconst defaultInstruction = buildIntercomBridgeInstruction(\n\t\torchestratorTarget || \"{orchestratorTarget}\",\n\t\tDEFAULT_INTERCOM_BRIDGE_TEMPLATE,\n\t);\n\tconst reason = inactiveReason(mode, input.context, orchestratorTarget);\n\tif (reason || !orchestratorTarget) {\n\t\treturn { active: false, mode, extensionDir: NATIVE_INTERCOM_EXTENSION_DIR, instruction: defaultInstruction };\n\t}\n\treturn {\n\t\tactive: true,\n\t\tmode,\n\t\torchestratorTarget,\n\t\textensionDir: NATIVE_INTERCOM_EXTENSION_DIR,\n\t\tinstruction: buildIntercomBridgeInstruction(orchestratorTarget, resolveInstructionTemplate(config.instructionFile, settingsDir)),\n\t};\n}\n\nexport function applyIntercomBridgeToAgent(agent: ChildRuntimeConfig, bridge: IntercomBridgeState): ChildRuntimeConfig {\n\tif (!bridge.active || !bridge.orchestratorTarget) return agent;\n\n\tconst bridgeTools = [\"intercom\", \"contact_supervisor\"];\n\tconst tools = agent.tools\n\t\t? [...agent.tools, ...bridgeTools.filter((tool) => !agent.tools?.includes(tool))]\n\t\t: agent.tools;\n\tconst instruction = bridge.instruction;\n\tconst trimmedPrompt = agent.systemPrompt?.trim() || \"\";\n\tconst systemPrompt = trimmedPrompt.includes(INTERCOM_BRIDGE_MARKER)\n\t\t? trimmedPrompt\n\t\t: trimmedPrompt\n\t\t\t? `${trimmedPrompt}\\n\\n${instruction}`\n\t\t\t: instruction;\n\n\tif (tools === agent.tools && systemPrompt === agent.systemPrompt) return agent;\n\treturn {\n\t\t...agent,\n\t\ttools,\n\t\tsystemPrompt,\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"intercom-bridge.js","sourceRoot":"","sources":["../../../../../src/builtin-extensions/pi-subagents/src/intercom/intercom-bridge.ts"],"names":[],"mappings":"AAAA,cAAc;AACd,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,KAAK,EAAE,MAAM,SAAS,CA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AAC,KAAK,CAAC,KAAK,CAAC;IACf,MAAM,WAAW,GAAG,MAAM,CAAC,WAAW,CAAC;IACvC,MAAM,aAAa,GAAG,KAAK,CAAC,YAAY,EAAE,IAAI,EAAE,IAAI,EAAE,CAAC;IACvD,MAAM,YAAY,GAAG,aAAa,CAAC,QAAQ,CAAC,sBAAsB,CAAC;QAClE,CAAC,CAAC,aAAa;QACf,CAAC,CAAC,aAAa;YACd,CAAC,CAAC,GAAG,aAAa,OAAO,WAAW,EAAE;YACtC,CAAC,CAAC,WAAW,CAAC;IAEhB,IAAI,KAAK,KAAK,KAAK,CAAC,KAAK,IAAI,YAAY,KAAK,KAAK,CAAC,YAAY;QAAE,OAAO,KAAK,CAAC;IAC/E,OAAO;QACN,GAAG,KAAK;QACR,KAAK;QACL,YAAY;KACZ,CAAC;AAAA,CACF","sourcesContent":["// @ts-nocheck\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport { subagentCommunicationEnabled } from \"../../../../core/settings-manager.ts\";\nimport type { ChildRuntimeConfig } from \"../shared/types.ts\";\nimport type { ExtensionConfig, IntercomBridgeConfig, IntercomBridgeMode } from \"../shared/types.ts\";\nimport { getAgentDir } from \"../shared/utils.ts\";\n\nexport const NATIVE_INTERCOM_EXTENSION_DIR = \"native:pi-subagents-supervisor-channel\";\n\nfunction defaultAgentDir(): string {\n\treturn getAgentDir();\n}\n\nfunction defaultSubagentConfigDir(agentDir = defaultAgentDir()): string {\n\treturn path.join(agentDir, \"extensions\", \"subagent\");\n}\n\nconst DEFAULT_INTERCOM_TARGET_PREFIX = \"subagent-chat\";\nexport const INTERCOM_BRIDGE_MARKER = \"Intercom orchestration channel:\";\nconst DEFAULT_INTERCOM_BRIDGE_TEMPLATE = `You own reversible implementation decisions within your assigned scope. Use contact_supervisor for coordination with \"{orchestratorTarget}\"; its tool description defines delivery and reply behavior.\nConsolidate dependency findings into one handoff when another task needs them before completion. Escalate permission, safety, scope changes, or a blocked decision with evidence and your recommended choice. Continue independent work before opening a blocking request.\nNative intercom reaches only the supervisor, not siblings. Use the supplied contracts and artifacts instead of discovering sibling sessions.\nReturn one self-contained final result; the runtime delivers it. If you cannot write a configured output artifact with your available tools, return its complete contents for the runtime to persist.`;\n\nexport interface IntercomBridgeState {\n\tactive: boolean;\n\tcommunicationEnabled: boolean;\n\tmode: IntercomBridgeMode;\n\torchestratorTarget?: string;\n\textensionDir: string;\n\tinstruction: string;\n}\n\nexport interface IntercomBridgeDiagnostic {\n\tactive: boolean;\n\tmode: IntercomBridgeMode;\n\twantsIntercom: boolean;\n\tsupervisorChannelAvailable: boolean;\n\textensionDir: string;\n\torchestratorTarget?: string;\n\treason?: string;\n}\n\ninterface ResolveIntercomBridgeInput {\n\tconfig: ExtensionConfig[\"intercomBridge\"];\n\tcontext: \"fresh\" | \"fork\" | undefined;\n\torchestratorTarget?: string;\n\tsettingsDir?: string;\n\tagentDir?: string;\n\tcwd?: string;\n}\n\nexport function resolveIntercomSessionTarget(sessionName: string | undefined, sessionId: string): string {\n\tconst trimmedName = sessionName?.trim();\n\tif (trimmedName) return trimmedName;\n\tconst normalizedSessionId = sessionId.startsWith(\"session-\") ? sessionId.slice(\"session-\".length) : sessionId;\n\treturn `${DEFAULT_INTERCOM_TARGET_PREFIX}-${normalizedSessionId.slice(0, 8)}`;\n}\n\nfunction sanitizeIntercomTargetPart(value: string): string {\n\treturn value.trim().toLowerCase().replace(/[^a-z0-9_-]+/g, \"-\").replace(/^-+|-+$/g, \"\") || \"agent\";\n}\n\nexport function resolveSubagentIntercomTarget(runId: string, agent: string, index?: number): string {\n\tconst stepSuffix = index !== undefined ? `-${index + 1}` : \"\";\n\treturn `subagent-${sanitizeIntercomTargetPart(agent)}-${sanitizeIntercomTargetPart(runId)}${stepSuffix}`;\n}\n\nexport function resolveIntercomBridgeMode(value: unknown): IntercomBridgeMode {\n\tif (value === \"off\" || value === \"always\" || value === \"fork-only\") return value;\n\treturn \"always\";\n}\n\nfunction resolveIntercomBridgeConfig(value: ExtensionConfig[\"intercomBridge\"]): Required<IntercomBridgeConfig> {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) {\n\t\treturn { mode: \"always\", instructionFile: \"\" };\n\t}\n\treturn {\n\t\tmode: resolveIntercomBridgeMode(value.mode),\n\t\tinstructionFile: typeof value.instructionFile === \"string\" ? value.instructionFile : \"\",\n\t};\n}\n\nfunction expandTilde(filePath: string): string {\n\treturn filePath.startsWith(\"~/\") ? path.join(os.homedir(), filePath.slice(2)) : filePath;\n}\n\nfunction resolveInstructionTemplate(instructionFile: string, settingsDir: string): string {\n\tif (!instructionFile) return DEFAULT_INTERCOM_BRIDGE_TEMPLATE;\n\tconst expandedPath = expandTilde(instructionFile);\n\tconst resolvedPath = path.isAbsolute(expandedPath)\n\t\t? expandedPath\n\t\t: path.resolve(settingsDir, expandedPath);\n\ttry {\n\t\treturn fs.readFileSync(resolvedPath, \"utf-8\");\n\t} catch (error) {\n\t\tconsole.warn(`Failed to read intercom bridge instructionFile at '${resolvedPath}'. Using default instructions.`, error);\n\t\treturn DEFAULT_INTERCOM_BRIDGE_TEMPLATE;\n\t}\n}\n\nfunction buildIntercomBridgeInstruction(orchestratorTarget: string, template: string): string {\n\tconst instruction = template.replaceAll(\"{orchestratorTarget}\", orchestratorTarget).trim();\n\tif (instruction.startsWith(INTERCOM_BRIDGE_MARKER)) return instruction;\n\treturn `${INTERCOM_BRIDGE_MARKER}\\n${instruction}`;\n}\n\nfunction inactiveReason(mode: IntercomBridgeMode, context: \"fresh\" | \"fork\" | undefined, orchestratorTarget: string | undefined): string | undefined {\n\tif (mode === \"off\") return \"bridge mode is off\";\n\tif (mode === \"fork-only\" && context !== \"fork\") return \"bridge mode is fork-only and context is not fork\";\n\tif (!orchestratorTarget) return \"orchestrator target is not available\";\n\treturn undefined;\n}\n\nexport function diagnoseIntercomBridge(input: ResolveIntercomBridgeInput): IntercomBridgeDiagnostic {\n\tconst config = resolveIntercomBridgeConfig(input.config);\n\tconst mode = subagentCommunicationEnabled(input.cwd ?? process.cwd(), input.agentDir ?? defaultAgentDir()) ? config.mode : \"off\";\n\tconst orchestratorTarget = input.orchestratorTarget?.trim();\n\tconst wantsIntercom = mode !== \"off\" && !(mode === \"fork-only\" && input.context !== \"fork\");\n\tconst reason = inactiveReason(mode, input.context, orchestratorTarget);\n\treturn {\n\t\tactive: reason === undefined,\n\t\tmode,\n\t\twantsIntercom,\n\t\tsupervisorChannelAvailable: true,\n\t\textensionDir: NATIVE_INTERCOM_EXTENSION_DIR,\n\t\t...(orchestratorTarget ? { orchestratorTarget } : {}),\n\t\t...(reason ? { reason } : {}),\n\t};\n}\n\nexport function resolveIntercomBridge(input: ResolveIntercomBridgeInput): IntercomBridgeState {\n\tconst config = resolveIntercomBridgeConfig(input.config);\n\tconst communicationEnabled = subagentCommunicationEnabled(input.cwd ?? process.cwd(), input.agentDir ?? defaultAgentDir());\n\tconst mode = communicationEnabled ? config.mode : \"off\";\n\tconst orchestratorTarget = input.orchestratorTarget?.trim();\n\tconst agentDir = path.resolve(input.agentDir ?? defaultAgentDir());\n\tconst settingsDir = path.resolve(input.settingsDir ?? defaultSubagentConfigDir(agentDir));\n\tconst defaultInstruction = buildIntercomBridgeInstruction(\n\t\torchestratorTarget || \"{orchestratorTarget}\",\n\t\tDEFAULT_INTERCOM_BRIDGE_TEMPLATE,\n\t);\n\tconst reason = inactiveReason(mode, input.context, orchestratorTarget);\n\tif (reason || !orchestratorTarget) {\n\t\treturn { active: false, communicationEnabled, mode, extensionDir: NATIVE_INTERCOM_EXTENSION_DIR, instruction: defaultInstruction };\n\t}\n\treturn {\n\t\tactive: true,\n\t\tcommunicationEnabled,\n\t\tmode,\n\t\torchestratorTarget,\n\t\textensionDir: NATIVE_INTERCOM_EXTENSION_DIR,\n\t\tinstruction: buildIntercomBridgeInstruction(orchestratorTarget, resolveInstructionTemplate(config.instructionFile, settingsDir)),\n\t};\n}\n\nexport function applyIntercomBridgeToAgent(agent: ChildRuntimeConfig, bridge: IntercomBridgeState): ChildRuntimeConfig {\n\tif (!bridge.active || !bridge.orchestratorTarget) return agent;\n\n\tconst bridgeTools = [\"intercom\", \"contact_supervisor\"];\n\tconst tools = agent.tools\n\t\t? [...agent.tools, ...bridgeTools.filter((tool) => !agent.tools?.includes(tool))]\n\t\t: agent.tools;\n\tconst instruction = bridge.instruction;\n\tconst trimmedPrompt = agent.systemPrompt?.trim() || \"\";\n\tconst systemPrompt = trimmedPrompt.includes(INTERCOM_BRIDGE_MARKER)\n\t\t? trimmedPrompt\n\t\t: trimmedPrompt\n\t\t\t? `${trimmedPrompt}\\n\\n${instruction}`\n\t\t\t: instruction;\n\n\tif (tools === agent.tools && systemPrompt === agent.systemPrompt) return agent;\n\treturn {\n\t\t...agent,\n\t\ttools,\n\t\tsystemPrompt,\n\t};\n}\n"]}
|
package/dist/builtin-extensions/pi-subagents/src/intercom/native-supervisor-channel.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"native-supervisor-channel.d.ts","sourceRoot":"","sources":["../../../../../src/builtin-extensions/pi-subagents/src/intercom/native-supervisor-channel.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,YAAY,EAAoC,MAAM,iCAAiC,CAAC;AAWtG,OAAO,EAA6G,KAAK,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAOnK,OAAO,EAeN,2BAA2B,IAAI,yBAAyB,EAQxD,MAAM,2BAA2B,CAAC;AAInC,eAAO,MAAM,2BAA2B,wBAAwB,CAAC;AACjE,eAAO,MAAM,2BAA2B,kCAA4B,CAAC;AAOrE,KAAK,gBAAgB,GAAG,eAAe,GAAG,mBAAmB,GAAG,iBAAiB,GAAG,SAAS,CAAC;AAE9F,UAAU,iBAAiB;IAC1B,IAAI,EAAE,6BAA6B,CAAC;IACpC,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,EAAE,EAAE,MAAM,CAAC;IACX,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;IAC/C,kBAAkB,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,KAAK,IAAI,CAAC;CAC5D,CAoIA;AAED,wBAAgB,gCAAgC,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAO5E;AAED,wBAAgB,wCAAwC,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAY9E","sourcesContent":["// @ts-nocheck\nimport { randomUUID } from \"node:crypto\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport type { AgentToolResult } from \"@ashx-j/lunr-agent\";\nimport type { ExtensionAPI, ExtensionContext, ToolDefinition } from \"@ashx-j/lunr\";\nimport { Type } from \"typebox\";\nimport {\n\tSUBAGENT_CHILD_AGENT_ENV,\n\tSUBAGENT_CHILD_INDEX_ENV,\n\tSUBAGENT_ORCHESTRATOR_SESSION_ID_ENV,\n\tSUBAGENT_ORCHESTRATOR_TARGET_ENV,\n\tSUBAGENT_RUN_ID_ENV,\n\tSUBAGENT_SUPERVISOR_CHANNEL_DIR_ENV,\n\tSUBAGENT_SUPERVISOR_SESSION_ID_ENV,\n} from \"../runs/shared/pi-args.ts\";\nimport { ASYNC_DIR, INTERCOM_DETACH_REQUEST_EVENT, POLL_INTERVAL_MS, SUBAGENT_CONTROL_EVENT, type IntercomEventBus, type SubagentState } from \"../shared/types.ts\";\nimport { writeAtomicJson } from \"../shared/atomic-json.ts\";\nimport { askRunningAsyncChild, reconcileAsyncQuestion } from \"./supervisor-ask.ts\";\nimport { CHILD_DESCRIPTION_ENV, SUPERVISOR_PROGRESS_TYPE, SUPERVISOR_PROTOCOL_VERSION, SUPERVISOR_REQUEST_TYPE, legacySupervisorBody, readCommunication, resolveCommunicationPeer, supervisorProtocolAvailable, type SubagentCommunication } from \"./communication.ts\";\nimport { renderCommunicationCall, renderCommunicationCard, renderCommunicationResult } from \"../tui/communication.ts\";\nimport { stopRequestPath } from \"../runs/background/control-channel.ts\";\nimport { readStatus } from \"../shared/utils.ts\";\nimport {\n\tanswerSupervisorQuestion,\n\tcancelPendingSupervisorQuestionsForOwner,\n\tcancelSupervisorQuestion,\n\tclaimQuestionNotification,\n\tformatSupervisorQuestionAnswer,\n\thasOutstandingQuestionForChild,\n\tisQuestionWaitActive,\n\tlistSupervisorChannelDirs,\n\tlistSupervisorQuestions,\n\tmarkSupervisorQuestionDelivered,\n\toutstandingQuestionsForChild,\n\tpendingSupervisorQuestionsForDelivery,\n\tQUESTIONS_DIR,\n\treadSupervisorQuestion,\n\tresolveSupervisorChannelDir as resolveQuestionChannelDir,\n\tSUBAGENT_QUESTION_EVENT,\n\tSUBAGENT_SUPERVISOR_ANSWER_TYPE,\n\tSUPERVISOR_CHANNEL_ROOT,\n\tsupervisorQuestionIsTerminal,\n\tsupervisorQuestionPublicState,\n\ttype SupervisorQuestion,\n\ttype SupervisorQuestionOwner,\n} from \"./supervisor-questions.ts\";\n\nconst REQUESTS_DIR = \"requests\";\nconst REPLIES_DIR = \"replies\";\nexport const NATIVE_SUPERVISOR_TOOL_NAME = \"subagent_supervisor\";\nexport const resolveSupervisorChannelDir = resolveQuestionChannelDir;\nconst MAX_MESSAGE_BYTES = 64 * 1024;\nconst DEFAULT_ASK_TIMEOUT_MS = 10 * 60 * 1000;\nconst CHANNEL_POLL_MS = Math.min(POLL_INTERVAL_MS, 500);\nconst STALE_EMPTY_CHANNEL_AGE_MS = 60 * 1000;\nconst STALE_EMPTY_CHANNEL_CLEANUP_INTERVAL_MS = 60 * 1000;\n\ntype SupervisorReason = \"need_decision\" | \"interview_request\" | \"progress_update\" | \"handoff\";\n\ninterface SupervisorRequest {\n\ttype: \"subagent.supervisor.request\";\n\tprotocolVersion?: number;\n\tdescription?: string;\n\tid: string;\n\tcreatedAt: number;\n\texpiresAt?: number;\n\treason: SupervisorReason;\n\tmessage: string;\n\texpectsReply: boolean;\n\torchestratorTarget?: string;\n\torchestratorSessionId?: string;\n\tsupervisorSessionId?: string;\n\trunId: string;\n\tagent: string;\n\tchildIndex: number;\n\tchildTarget?: string;\n\tinterview?: unknown;\n}\n\ninterface PendingSupervisorRequest extends SupervisorRequest {\n\tchannelDir: string;\n\trequestFile: string;\n}\n\ninterface SupervisorReply {\n\ttype: \"subagent.supervisor.reply\";\n\trequestId: string;\n\tcreatedAt: number;\n\tmessage: string;\n}\n\ninterface ContactSupervisorParams {\n\treason?: SupervisorReason;\n\tmessage?: string;\n\tinterview?: unknown;\n\taction?: \"reply\";\n\treplyTo?: string;\n}\n\ninterface IntercomParams {\n\taction: \"list\" | \"send\" | \"ask\" | \"reply\" | \"pending\" | \"status\";\n\tto?: string;\n\tmessage?: string;\n\treplyTo?: string;\n\tid?: string;\n\tindex?: number;\n\tchildId?: string;\n\treason?: string;\n}\n\nconst PARENT_ASK_DESCRIPTION = [\n\t\"Ask a specific running async child, or reply to a child supervisor request.\",\n\t\"Ask only when the child owns missing context, the answer changes a concrete next decision, and waiting risks a block or rework.\",\n\t\"Use available results first, batch related questions, and keep working while awaiting the answer. Do not use ask for status checks, polling, duplicate queries, or step-by-step supervision. Follow up only when the answer leaves the original decision unresolved.\",\n\t\"Returns a question id immediately. The child's explicit answer is delivered separately from the final run result.\",\n\t'Ask: { action: \"ask\", id: \"<runId>\", index?: 0, childId?: \"...\", reason: \"<concrete decision>\", message: \"...\" }',\n\t\"Use pending or list to find child requests awaiting your reply; status reports channel availability. Free-form send is unsupported. Asking never revives a child or changes its assignment.\",\n\t'Reply: { action: \"reply\", replyTo: \"<requestId>\", message: \"...\" }',\n].join(\" \");\n\nconst CHILD_CONTACT_DESCRIPTION = [\n\t\"Contact the supervisor for decisions outside your assigned authority, safety concerns, or blockers. Make reversible implementation choices within your scope yourself.\",\n\t\"need_decision/interview_request wait for a reply: state the blocked decision, evidence, and recommended choice. Consolidate related questions; continue independent work before opening a blocking request.\",\n\t\"Return one self-contained final report with outcomes, verification, blockers, and artifact paths; the runtime delivers it. Routine work already appears in activity indicators.\",\n\t\"For parent questions use action='reply' with replyTo set to the question id. Answer from current findings and uncertainty; do not start extra investigation just to reply. Continue the assigned task after replying.\",\n\t\"Do not open a blocking need_decision while a parent question is already outstanding for this child.\",\n].join(\" \");\n\nconst ContactSupervisorParamsSchema = Type.Object({\n\treason: Type.Optional(Type.String({ enum: [\"need_decision\", \"interview_request\", \"progress_update\", \"handoff\"] })),\n\tmessage: Type.Optional(Type.String()),\n\tinterview: Type.Optional(Type.Unsafe({ type: \"object\", additionalProperties: true })),\n\taction: Type.Optional(Type.String({ enum: [\"reply\"] })),\n\treplyTo: Type.Optional(Type.String()),\n}, { additionalProperties: false });\n\nconst IntercomParamsSchema = Type.Object({\n\taction: Type.String({ enum: [\"list\", \"send\", \"ask\", \"reply\", \"pending\", \"status\"] }),\n\tto: Type.Optional(Type.String()),\n\tmessage: Type.Optional(Type.String()),\n\treplyTo: Type.Optional(Type.String()),\n\tid: Type.Optional(Type.String({ description: \"Async run id for action='ask'.\" })),\n\tindex: Type.Optional(Type.Integer({ minimum: 0, description: \"Zero-based child index for action='ask'. Select index or childId when more than one child is running.\" })),\n\tchildId: Type.Optional(Type.String({ description: \"Private child identity for action='ask'.\" })),\n\treason: Type.Optional(Type.String({ description: \"Concrete decision the child's answer will change. Required for action='ask'.\" })),\n}, { additionalProperties: false });\n\nconst ParentSupervisorParamsSchema = Type.Object({\n\t...IntercomParamsSchema.properties,\n\taction: Type.String({ enum: [\"list\", \"ask\", \"reply\", \"pending\", \"status\"] }),\n}, { additionalProperties: false });\n\nfunction safeSegment(value: string): string {\n\treturn value.trim().replace(/[^A-Za-z0-9._-]+/g, \"-\").replace(/^-+|-+$/g, \"\") || \"unknown\";\n}\n\nexport function ensureSupervisorChannelDir(channelDir: string): void {\n\tfs.mkdirSync(path.join(channelDir, REQUESTS_DIR), { recursive: true, mode: 0o700 });\n\tfs.mkdirSync(path.join(channelDir, REPLIES_DIR), { recursive: true, mode: 0o700 });\n\tfs.mkdirSync(path.join(channelDir, QUESTIONS_DIR), { recursive: true, mode: 0o700 });\n}\n\nfunction requestPath(channelDir: string, requestId: string): string {\n\treturn path.join(channelDir, REQUESTS_DIR, `${safeSegment(requestId)}.json`);\n}\n\nfunction replyPath(channelDir: string, requestId: string): string {\n\treturn path.join(channelDir, REPLIES_DIR, `${safeSegment(requestId)}.json`);\n}\n\nfunction readTextEnv(name: string): string | undefined {\n\tconst value = process.env[name]?.trim();\n\treturn value ? value : undefined;\n}\n\nfunction readChildMetadata(): {\n\tdescription?: string;\n\tchannelDir: string;\n\trunId: string;\n\tagent: string;\n\tchildIndex: number;\n\torchestratorTarget?: string;\n\torchestratorSessionId?: string;\n\tchildTarget?: string;\n\tsupervisorSessionId?: string;\n} | undefined {\n\tconst channelDir = readTextEnv(SUBAGENT_SUPERVISOR_CHANNEL_DIR_ENV);\n\tconst runId = readTextEnv(SUBAGENT_RUN_ID_ENV);\n\tconst agent = readTextEnv(SUBAGENT_CHILD_AGENT_ENV);\n\tconst rawIndex = readTextEnv(SUBAGENT_CHILD_INDEX_ENV);\n\tconst orchestratorSessionId = readTextEnv(SUBAGENT_ORCHESTRATOR_SESSION_ID_ENV);\n\tif (!channelDir || !runId || !agent || !orchestratorSessionId || rawIndex === undefined || !/^\\d+$/.test(rawIndex)) return undefined;\n\treturn {\n\t\tchannelDir,\n\t\trunId,\n\t\tagent,\n\t\tchildIndex: Number(rawIndex),\n\t\torchestratorTarget: readTextEnv(SUBAGENT_ORCHESTRATOR_TARGET_ENV),\n\t\torchestratorSessionId,\n\t\tsupervisorSessionId: readTextEnv(SUBAGENT_SUPERVISOR_SESSION_ID_ENV),\n\t\tchildTarget: readTextEnv(\"PI_SUBAGENT_INTERCOM_SESSION_NAME\"),\n\t\tdescription: readTextEnv(CHILD_DESCRIPTION_ENV),\n\t};\n}\n\nfunction readChildQuestionOwner(metadata = readChildMetadata()): SupervisorQuestionOwner | undefined {\n\tif (!metadata) return undefined;\n\tconst readyAt = Number(process.env.PI_SUBAGENT_STEER_READY_AT);\n\tif (!Number.isFinite(readyAt) || readyAt <= 0) return undefined;\n\treturn {\n\t\trunId: metadata.runId,\n\t\tchildIndex: metadata.childIndex,\n\t\tchildId: metadata.agent,\n\t\tpid: process.pid,\n\t\treadyAt,\n\t};\n}\n\nfunction answerParentQuestion(params: ContactSupervisorParams): AgentToolResult<Record<string, unknown>> {\n\tconst metadata = readChildMetadata();\n\tconst owner = readChildQuestionOwner(metadata);\n\tif (!metadata || !owner) throw new Error(\"Native supervisor channel is not available for this subagent.\");\n\tconst replyTo = params.replyTo?.trim();\n\tif (!replyTo) throw new Error(\"action='reply' requires replyTo with the parent question id.\");\n\tconst message = params.message?.trim();\n\tif (!message) throw new Error(\"message is required for supervisor question replies.\");\n\tconst question = readSupervisorQuestion(metadata.channelDir, replyTo);\n\tif (question?.parentSessionId !== (metadata.supervisorSessionId ?? metadata.orchestratorSessionId)) throw new Error(\"Question belongs to a different supervisor session.\");\n\tconst answered = answerSupervisorQuestion(metadata.channelDir, replyTo, message, owner);\n\treturn {\n\t\tcontent: [{ type: \"text\", text: `Replied to parent question ${answered.id}. Continue the assigned task.` }],\n\t\tdetails: {\n\t\t\treplyTo: answered.id,\n\t\t\tstate: supervisorQuestionPublicState(answered),\n\t\t\tanswered: true,\n\t\t\tcommunication: { direction: \"to\", peer: \"Supervisor\", kind: \"reply\", message },\n\t\t},\n\t};\n}\n\nfunction reasonHeading(reason: SupervisorReason): string {\n\tif (reason === \"handoff\") return \"Subagent dependency handoff.\";\n\tif (reason === \"interview_request\") return \"Subagent requests a structured supervisor interview.\";\n\tif (reason === \"progress_update\") return \"Subagent progress update.\";\n\treturn \"Subagent needs a supervisor decision.\";\n}\n\nfunction formatChildMessage(input: {\n\treason: SupervisorReason;\n\tmessage?: string;\n\tinterview?: unknown;\n\trunId: string;\n\tagent: string;\n\tchildIndex: number;\n\tchildTarget?: string;\n}): string {\n\tconst lines = [\n\t\treasonHeading(input.reason),\n\t\t`Run: ${input.runId}`,\n\t\t`Agent: ${input.agent}`,\n\t\t`Child index: ${input.childIndex}`,\n\t];\n\tif (input.childTarget) lines.push(`Child intercom target: ${input.childTarget}`);\n\tlines.push(\"\");\n\tif (input.message?.trim()) lines.push(input.message.trim());\n\tif (input.reason === \"interview_request\") {\n\t\tlines.push(\n\t\t\t\"\",\n\t\t\t\"Structured response requested. Reply with JSON, optionally fenced in ```json, matching the requested interview shape.\",\n\t\t);\n\t\tif (input.interview !== undefined) lines.push(JSON.stringify(input.interview, null, \"\\t\"));\n\t}\n\treturn lines.join(\"\\n\").trimEnd();\n}\n\nfunction communicationKind(reason?: SupervisorReason): SubagentCommunication[\"kind\"] {\n\treturn reason === \"progress_update\" ? \"progress\" : reason === \"handoff\" ? \"handoff\" : reason === \"interview_request\" ? \"interview\" : \"request\";\n}\n\nfunction communicationBody(message: string, interview?: unknown, protocolVersion?: number): string {\n\tconst body = protocolVersion === SUPERVISOR_PROTOCOL_VERSION ? message : legacySupervisorBody(message);\n\treturn interview !== undefined && protocolVersion === SUPERVISOR_PROTOCOL_VERSION ? `${body}\\n\\n${JSON.stringify(interview, null, 2)}` : body;\n}\n\nfunction requestCommunication(request: SupervisorRequest, state: SubagentState): SubagentCommunication {\n\treturn {\n\t\tdirection: \"from\",\n\t\tpeer: resolveCommunicationPeer(state, request.runId, request.childIndex, request.agent, request.description),\n\t\tmessage: communicationBody(request.message, request.interview, request.protocolVersion),\n\t\tkind: communicationKind(request.reason),\n\t};\n}\n\nexport function registerSupervisorRenderers(pi: ExtensionAPI, state: SubagentState): void {\n\tfor (const customType of [SUPERVISOR_REQUEST_TYPE, SUBAGENT_SUPERVISOR_ANSWER_TYPE]) {\n\t\tpi.registerMessageRenderer(customType, (message, options, theme) => {\n\t\t\tconst details = message.details as { communication?: unknown; runId?: string; childIndex?: number; agent?: string; childId?: string; reason?: SupervisorReason } | undefined;\n\t\t\tconst communication = readCommunication(details?.communication) ?? {\n\t\t\t\tdirection: \"from\" as const,\n\t\t\t\tpeer: details?.runId ? resolveCommunicationPeer(state, details.runId, details.childIndex ?? 0, details.childId ?? details.agent) : \"Subagent\",\n\t\t\t\tmessage: legacySupervisorBody(typeof message.content === \"string\" ? message.content : message.content.filter((part) => part.type === \"text\").map((part) => part.text).join(\"\\n\")),\n\t\t\t\tkind: customType === SUBAGENT_SUPERVISOR_ANSWER_TYPE ? \"answer\" as const : communicationKind(details?.reason),\n\t\t\t};\n\t\t\treturn renderCommunicationCard(communication, options.expanded, theme);\n\t\t});\n\t}\n\tpi.registerEntryRenderer(SUPERVISOR_PROGRESS_TYPE, (entry, options, theme) => {\n\t\tconst communication = readCommunication((entry.data as { communication?: unknown } | undefined)?.communication);\n\t\treturn communication ? renderCommunicationCard(communication, options.expanded, theme) : undefined;\n\t});\n}\n\nfunction parseStructuredReply(message: string): { value?: unknown; error?: string } {\n\tconst trimmed = message.trim();\n\tconst fenced = trimmed.match(/^```(?:json)?\\s*([\\s\\S]*?)\\s*```$/i)?.[1]?.trim();\n\ttry {\n\t\treturn { value: JSON.parse(fenced ?? trimmed) };\n\t} catch (error) {\n\t\treturn { error: error instanceof Error ? `${error.name}: ${error.message}` : String(error) };\n\t}\n}\n\nfunction askTimeoutMs(): number {\n\tconst parsed = Number(process.env.PI_INTERCOM_ASK_TIMEOUT_MS);\n\treturn Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_ASK_TIMEOUT_MS;\n}\n\nfunction delay(ms: number, signal?: AbortSignal): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(new Error(\"Supervisor request cancelled.\"));\n\t\t\treturn;\n\t\t}\n\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\tconst cleanup = () => {\n\t\t\tif (timer) clearTimeout(timer);\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t};\n\t\tconst onAbort = () => {\n\t\t\tcleanup();\n\t\t\treject(new Error(\"Supervisor request cancelled.\"));\n\t\t};\n\t\ttimer = setTimeout(() => {\n\t\t\tcleanup();\n\t\t\tresolve();\n\t\t}, ms);\n\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t});\n}\n\nasync function waitForReply(channelDir: string, requestId: string, deadline: number, signal?: AbortSignal): Promise<SupervisorReply> {\n\tconst file = replyPath(channelDir, requestId);\n\twhile (Date.now() <= deadline) {\n\t\tif (signal?.aborted) throw new Error(\"Supervisor request cancelled.\");\n\t\tif (fs.existsSync(file)) {\n\t\t\tconst parsed = JSON.parse(fs.readFileSync(file, \"utf-8\")) as Partial<SupervisorReply>;\n\t\t\tif (parsed.type === \"subagent.supervisor.reply\" && parsed.requestId === requestId && typeof parsed.message === \"string\") {\n\t\t\t\treturn parsed as SupervisorReply;\n\t\t\t}\n\t\t}\n\t\tawait delay(250, signal);\n\t}\n\tthrow new Error(\"Timed out waiting for supervisor reply.\");\n}\n\nasync function sendSupervisorRequest(params: ContactSupervisorParams, signal?: AbortSignal): Promise<AgentToolResult<Record<string, unknown>>> {\n\tif (params.action === \"reply\" || params.replyTo?.trim()) {\n\t\treturn answerParentQuestion(params);\n\t}\n\tconst metadata = readChildMetadata();\n\tif (!metadata) throw new Error(\"Native supervisor channel is not available for this subagent.\");\n\tif (!params.reason) throw new Error(\"reason is required for supervisor contact.\");\n\tif (signal?.aborted) throw new Error(\"Supervisor request cancelled.\");\n\tconst protocolVersion = supervisorProtocolAvailable() ? SUPERVISOR_PROTOCOL_VERSION : undefined;\n\tif (params.reason === \"handoff\" && !protocolVersion) throw new Error(\"This supervisor uses the legacy protocol. Send actionable findings with progress_update instead.\");\n\tconst expectsReply = params.reason === \"need_decision\" || params.reason === \"interview_request\";\n\tif (expectsReply && hasOutstandingQuestionForChild(metadata.channelDir, metadata.childIndex, metadata.agent)) {\n\t\tthrow new Error(\"A parent question is already outstanding for this child. Answer it with action='reply' before opening a blocking supervisor request.\");\n\t}\n\tif (!params.message?.trim() && params.reason !== \"interview_request\") {\n\t\tthrow new Error(\"message is required for supervisor contact.\");\n\t}\n\tensureSupervisorChannelDir(metadata.channelDir);\n\tconst requestId = randomUUID();\n\tconst createdAt = Date.now();\n\tconst replyDeadline = createdAt + askTimeoutMs();\n\tconst expiresAt = expectsReply ? replyDeadline : undefined;\n\tconst message = protocolVersion ? params.message?.trim() || \"Structured supervisor input requested.\" : formatChildMessage({ ...metadata, reason: params.reason, message: params.message, interview: params.interview });\n\tconst communication: SubagentCommunication = { direction: \"to\", peer: \"Supervisor\", kind: communicationKind(params.reason), message: communicationBody(message, params.interview, protocolVersion) };\n\tconst request: SupervisorRequest = {\n\t\ttype: \"subagent.supervisor.request\",\n\t\t...(protocolVersion ? { protocolVersion } : {}),\n\t\t...(metadata.description ? { description: metadata.description } : {}),\n\t\tid: requestId,\n\t\tcreatedAt,\n\t\t...(expiresAt !== undefined ? { expiresAt } : {}),\n\t\treason: params.reason,\n\t\tmessage,\n\t\texpectsReply,\n\t\t...(metadata.orchestratorTarget ? { orchestratorTarget: metadata.orchestratorTarget } : {}),\n\t\t...(metadata.orchestratorSessionId ? { orchestratorSessionId: metadata.orchestratorSessionId } : {}),\n\t\t...(metadata.supervisorSessionId ? { supervisorSessionId: metadata.supervisorSessionId } : {}),\n\t\trunId: metadata.runId,\n\t\tagent: metadata.agent,\n\t\tchildIndex: metadata.childIndex,\n\t\t...(metadata.childTarget ? { childTarget: metadata.childTarget } : {}),\n\t\t...(params.interview !== undefined ? { interview: params.interview } : {}),\n\t};\n\tconst serialized = JSON.stringify(request, null, \"\\t\");\n\tif (Buffer.byteLength(serialized, \"utf-8\") > MAX_MESSAGE_BYTES) throw new Error(\"Supervisor request is too large.\");\n\twriteAtomicJson(requestPath(metadata.channelDir, requestId), request);\n\tif (expectsReply) {\n\t\tfor (const question of outstandingQuestionsForChild(metadata.channelDir, metadata.childIndex, metadata.agent)) {\n\t\t\tcancelSupervisorQuestion(metadata.channelDir, question.id, \"child needs a supervisor decision; reply to its request first\");\n\t\t}\n\t}\n\n\tif (!expectsReply) {\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: params.reason === \"handoff\" ? \"Dependency handoff queued. Continue independent work.\" : protocolVersion ? \"Progress recorded for the UI only; the supervisor model will not receive it.\" : \"Supervisor progress update queued.\" }],\n\t\t\tdetails: { queued: true, requestId, reason: params.reason, communication },\n\t\t};\n\t}\n\n\ttry {\n\t\tconst reply = await waitForReply(metadata.channelDir, requestId, replyDeadline, signal);\n\t\tconst details: Record<string, unknown> = { requestId, reason: params.reason, communication, response: reply.message };\n\t\tif (params.reason === \"interview_request\") {\n\t\t\tconst structured = parseStructuredReply(reply.message);\n\t\t\tif (structured.error) details.structuredReplyParseError = structured.error;\n\t\t\telse details.structuredReply = structured.value;\n\t\t}\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: `**Reply from supervisor:**\\n${reply.message}` }],\n\t\t\tdetails,\n\t\t};\n\t} catch (error) {\n\t\tremoveRequestFile(requestPath(metadata.channelDir, requestId));\n\t\tthrow error;\n\t}\n}\n\nfunction hasTool(pi: ExtensionAPI, name: string): boolean {\n\ttry {\n\t\treturn pi.getAllTools?.().some((tool: { name?: unknown }) => tool.name === name) === true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport function registerNativeSupervisorClient(pi: ExtensionAPI, options: { includeIntercomFallback?: boolean } = {}): void {\n\tif (!readChildMetadata()) return;\n\tconst includeIntercomFallback = options.includeIntercomFallback !== false;\n\tif (!hasTool(pi, \"contact_supervisor\")) {\n\t\tconst tool: ToolDefinition<typeof ContactSupervisorParamsSchema, Record<string, unknown>> = {\n\t\t\tname: \"contact_supervisor\",\n\t\t\tlabel: \"Contact Supervisor\",\n\t\t\tdescription: `${CHILD_CONTACT_DESCRIPTION} ${supervisorProtocolAvailable()\n\t\t\t\t? \"handoff delivers actionable dependency findings or corrections without waiting: state what changes and consolidate evidence or reference one artifact. progress_update is UI-only and never reaches the supervisor model.\"\n\t\t\t\t: \"This legacy supervisor delivers progress_update to its model. Reserve it for actionable dependency findings or corrections.\"}`,\n\t\t\tparameters: supervisorProtocolAvailable() ? ContactSupervisorParamsSchema : Type.Object({ ...ContactSupervisorParamsSchema.properties, reason: Type.Optional(Type.String({ enum: [\"need_decision\", \"interview_request\", \"progress_update\"] })) }, { additionalProperties: false }),\n\t\t\trenderCall(args, theme, context) {\n\t\t\t\treturn renderCommunicationCall(\"contact_supervisor\", args, theme, context, { direction: \"to\", peer: \"Supervisor\", kind: args.action === \"reply\" ? \"reply\" : communicationKind(args.reason), message: communicationBody(args.message ?? \"\", args.interview, SUPERVISOR_PROTOCOL_VERSION) });\n\t\t\t},\n\t\t\trenderResult(result, options, theme, context) {\n\t\t\t\treturn renderCommunicationResult(result.content, result.details, options.expanded, context.isError, theme);\n\t\t\t},\n\t\t\texecute(_id, params, signal) {\n\t\t\t\treturn sendSupervisorRequest(params as ContactSupervisorParams, signal);\n\t\t\t},\n\t\t};\n\t\tpi.registerTool(tool);\n\t}\n\tif (includeIntercomFallback && !hasTool(pi, \"intercom\")) {\n\t\tconst tool: ToolDefinition<typeof IntercomParamsSchema, Record<string, unknown>> = {\n\t\t\tname: \"intercom\",\n\t\t\tlabel: \"Intercom\",\n\t\t\tdescription: \"Supervisor-only fallback; sibling discovery and sibling messaging are unavailable. Use contact_supervisor for decisions, replies, and dependency handoffs. list reports no sibling sessions; ask blocks for a supervisor decision; send is progress only.\",\n\t\t\tparameters: IntercomParamsSchema,\n\t\t\trenderCall(args, theme, context) {\n\t\t\t\treturn renderCommunicationCall(\"intercom\", args, theme, context, args.message ? { direction: \"to\", peer: \"Supervisor\", kind: args.action === \"ask\" ? \"request\" : \"progress\", message: args.message } : undefined);\n\t\t\t},\n\t\t\trenderResult(result, options, theme, context) {\n\t\t\t\treturn renderCommunicationResult(result.content, result.details, options.expanded, context.isError, theme);\n\t\t\t},\n\t\t\tasync execute(_id, params, signal) {\n\t\t\t\tconst action = (params as IntercomParams).action;\n\t\t\t\tif (action === \"status\") return { content: [{ type: \"text\", text: \"Native supervisor channel is active.\" }], details: { active: true } };\n\t\t\t\tif (action === \"list\") return { content: [{ type: \"text\", text: \"Supervisor session available through contact_supervisor.\" }], details: { sessions: [] } };\n\t\t\t\tif (action === \"send\") return sendSupervisorRequest({ reason: \"progress_update\", message: (params as IntercomParams).message ?? \"\" }, signal);\n\t\t\t\tif (action === \"ask\") return sendSupervisorRequest({ reason: \"need_decision\", message: (params as IntercomParams).message ?? \"\" }, signal);\n\t\t\t\tthrow new Error(\"Native child intercom supports status, list, send, and ask. Use parent intercom reply from the supervisor session.\");\n\t\t\t},\n\t\t};\n\t\tpi.registerTool(tool);\n\t}\n}\n\nfunction parseRequestFile(file: string, channelDir: string): PendingSupervisorRequest | undefined {\n\ttry {\n\t\tconst parsed = JSON.parse(fs.readFileSync(file, \"utf-8\")) as Partial<SupervisorRequest>;\n\t\tif (parsed.type !== \"subagent.supervisor.request\") return undefined;\n\t\tif (parsed.supervisorSessionId !== undefined && (typeof parsed.supervisorSessionId !== \"string\" || !parsed.supervisorSessionId.trim())) return undefined;\n\t\tif (typeof parsed.id !== \"string\" || !parsed.id) return undefined;\n\t\tif (parsed.reason !== \"need_decision\" && parsed.reason !== \"interview_request\" && parsed.reason !== \"progress_update\" && parsed.reason !== \"handoff\") return undefined;\n\t\tif (parsed.protocolVersion !== undefined && parsed.protocolVersion !== SUPERVISOR_PROTOCOL_VERSION) return undefined;\n\t\tif (parsed.protocolVersion === SUPERVISOR_PROTOCOL_VERSION && parsed.expectsReply !== (parsed.reason === \"need_decision\" || parsed.reason === \"interview_request\")) return undefined;\n\t\tif (parsed.reason === \"handoff\" && parsed.protocolVersion !== SUPERVISOR_PROTOCOL_VERSION) return undefined;\n\t\tif (parsed.description !== undefined && typeof parsed.description !== \"string\") return undefined;\n\t\tif (typeof parsed.message !== \"string\" || !parsed.message) return undefined;\n\t\tif (typeof parsed.runId !== \"string\" || typeof parsed.agent !== \"string\" || typeof parsed.childIndex !== \"number\") return undefined;\n\t\treturn { ...parsed as SupervisorRequest, channelDir, requestFile: file };\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nexport function hasPendingBlockingSupervisorRequest(runId: string, sessionId?: string | null, now = Date.now()): boolean {\n\tif (!runId) return false;\n\tfor (const { channelDir, file } of listRequestFiles()) {\n\t\tconst request = parseRequestFile(file, channelDir);\n\t\tif (!request?.expectsReply) continue;\n\t\tif (request.runId !== runId) continue;\n\t\tif (sessionId && (request.supervisorSessionId ?? request.orchestratorSessionId) !== sessionId) continue;\n\t\tif (fs.existsSync(replyPath(request.channelDir, request.id))) continue;\n\t\tif (now > requestExpiresAt(request, now)) continue;\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nfunction listRequestFiles(): Array<{ channelDir: string; file: string }> {\n\tlet channelEntries: fs.Dirent[];\n\ttry {\n\t\tchannelEntries = fs.readdirSync(SUPERVISOR_CHANNEL_ROOT, { withFileTypes: true });\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n\t\tthrow error;\n\t}\n\tconst files: Array<{ channelDir: string; file: string }> = [];\n\tfor (const entry of channelEntries) {\n\t\tif (!entry.isDirectory()) continue;\n\t\tconst channelDir = path.join(SUPERVISOR_CHANNEL_ROOT, entry.name);\n\t\tconst requestsDir = path.join(channelDir, REQUESTS_DIR);\n\t\tlet requestEntries: fs.Dirent[];\n\t\ttry {\n\t\t\trequestEntries = fs.readdirSync(requestsDir, { withFileTypes: true });\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const requestEntry of requestEntries) {\n\t\t\tif (requestEntry.isFile() && requestEntry.name.endsWith(\".json\")) files.push({ channelDir, file: path.join(requestsDir, requestEntry.name) });\n\t\t}\n\t}\n\treturn files;\n}\n\nfunction readDirectoryEntries(dir: string): fs.Dirent[] | undefined {\n\ttry {\n\t\treturn fs.readdirSync(dir, { withFileTypes: true });\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n\t\treturn undefined;\n\t}\n}\n\nfunction directoryMtimeMs(dir: string): number {\n\ttry {\n\t\treturn fs.statSync(dir).mtimeMs;\n\t} catch {\n\t\treturn 0;\n\t}\n}\n\nfunction removeEmptyDirectory(dir: string): boolean {\n\ttry {\n\t\tfs.rmdirSync(dir);\n\t\treturn true;\n\t} catch (error) {\n\t\tconst code = (error as NodeJS.ErrnoException).code;\n\t\tif (code === \"ENOENT\") return true;\n\t\tif (code === \"ENOTEMPTY\" || code === \"EEXIST\" || code === \"EPERM\" || code === \"EBUSY\") return false;\n\t\tthrow error;\n\t}\n}\n\nfunction removeStaleEmptySupervisorChannel(channelDir: string, nowMs: number): boolean {\n\tconst requestsDir = path.join(channelDir, REQUESTS_DIR);\n\tconst repliesDir = path.join(channelDir, REPLIES_DIR);\n\tconst questionsPath = path.join(channelDir, QUESTIONS_DIR);\n\tconst newestKnownMtimeMs = Math.max(\n\t\tdirectoryMtimeMs(channelDir),\n\t\tdirectoryMtimeMs(requestsDir),\n\t\tdirectoryMtimeMs(repliesDir),\n\t\tdirectoryMtimeMs(questionsPath),\n\t);\n\tif (nowMs - newestKnownMtimeMs < STALE_EMPTY_CHANNEL_AGE_MS) return false;\n\n\tconst requestEntries = readDirectoryEntries(requestsDir);\n\tif (!requestEntries || requestEntries.length > 0) return false;\n\tconst replyEntries = readDirectoryEntries(repliesDir);\n\tif (!replyEntries || replyEntries.length > 0) return false;\n\tconst questionEntries = readDirectoryEntries(questionsPath);\n\tif (!questionEntries || questionEntries.length > 0) return false;\n\n\tif (!removeEmptyDirectory(requestsDir)) return false;\n\tif (!removeEmptyDirectory(repliesDir)) return false;\n\tif (!removeEmptyDirectory(questionsPath)) return false;\n\tif (!removeEmptyDirectory(channelDir)) return false;\n\treturn true;\n}\n\nfunction cleanupStaleEmptySupervisorChannels(nowMs = Date.now()): number {\n\tlet channelEntries: fs.Dirent[];\n\ttry {\n\t\tchannelEntries = fs.readdirSync(SUPERVISOR_CHANNEL_ROOT, { withFileTypes: true });\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") return 0;\n\t\tthrow error;\n\t}\n\n\tlet removed = 0;\n\tfor (const entry of channelEntries) {\n\t\tif (!entry.isDirectory()) continue;\n\t\ttry {\n\t\t\tif (removeStaleEmptySupervisorChannel(path.join(SUPERVISOR_CHANNEL_ROOT, entry.name), nowMs)) removed++;\n\t\t} catch {\n\t\t\t// Cleanup is opportunistic; active writers can race with us and will be picked up by a later pass.\n\t\t}\n\t}\n\treturn removed;\n}\n\nfunction currentContextSessionId(state: Pick<SubagentState, \"currentSessionId\">, ctx: ExtensionContext): string | undefined {\n\ttry {\n\t\tconst sessionId = ctx.sessionManager.getSessionId();\n\t\tif (sessionId) return sessionId;\n\t} catch {\n\t\t// Fall through to the last known identity.\n\t}\n\treturn state.currentSessionId ?? undefined;\n}\n\nfunction currentSupervisorSessionId(state: Pick<SubagentState, \"currentSessionId\">, ctx: ExtensionContext): string | undefined {\n\ttry {\n\t\treturn ctx.sessionManager.getSessionFile?.() ?? currentContextSessionId(state, ctx);\n\t} catch {\n\t\treturn state.currentSessionId ?? undefined;\n\t}\n}\n\nfunction requestMatchesContext(request: SupervisorRequest, state: Pick<SubagentState, \"currentSessionId\">, ctx: ExtensionContext): boolean {\n\tconst currentSessionId = request.supervisorSessionId !== undefined\n\t\t? currentSupervisorSessionId(state, ctx)\n\t\t: currentContextSessionId(state, ctx);\n\treturn Boolean(currentSessionId && (request.supervisorSessionId ?? request.orchestratorSessionId) === currentSessionId);\n}\n\nfunction removeRequestFile(file: string): void {\n\ttry {\n\t\tfs.rmSync(file, { force: true });\n\t} catch {\n\t\t// Request cleanup is best-effort; reply files and timeout errors remain authoritative.\n\t}\n}\n\ntype SupervisorRequestLifecycle = \"pending\" | \"resolved\" | \"expired\" | \"inactive\" | \"missing\" | \"wrong-session\";\n\nfunction requestExpiresAt(request: SupervisorRequest, now: number): number {\n\tconst expiresAt = (request as { expiresAt?: unknown }).expiresAt;\n\tif (typeof expiresAt === \"number\" && Number.isFinite(expiresAt)) return expiresAt;\n\treturn Number.isFinite(request.createdAt) ? request.createdAt + askTimeoutMs() : now;\n}\n\nfunction requestRunState(request: SupervisorRequest, state: SubagentState): \"active\" | \"inactive\" | \"stopped\" {\n\tif (state.foregroundControls.has(request.runId)) return \"active\";\n\tconst foregroundRun = state.foregroundRuns?.get(request.runId);\n\tconst foregroundChild = foregroundRun?.children.find((child) => child.index === request.childIndex && child.agent === request.agent)\n\t\t?? foregroundRun?.children[request.childIndex];\n\tif (foregroundChild) return foregroundChild.status === \"stopped\" ? \"stopped\" : foregroundChild.status === \"detached\" ? \"active\" : \"inactive\";\n\n\tconst job = state.asyncJobs.get(request.runId) ?? state.fleetJobs?.get(request.runId);\n\tconst asyncDir = job?.asyncDir ?? path.join(ASYNC_DIR, safeSegment(request.runId));\n\tconst status = readStatus(asyncDir);\n\tconst runStatus = status?.state ?? job?.status;\n\tconst stepStatus = (status?.steps ?? job?.steps)?.[request.childIndex]?.status;\n\tif (fs.existsSync(stopRequestPath(asyncDir)) || runStatus === \"stopped\" || job?.status === \"stopped\" || status?.stopped || stepStatus === \"stopped\") return \"stopped\";\n\tif ([\"complete\", \"failed\", \"paused\"].includes(runStatus ?? \"\") || [\"complete\", \"completed\", \"failed\", \"paused\"].includes(stepStatus ?? \"\")) return \"inactive\";\n\treturn \"active\";\n}\n\nfunction requestLifecycle(request: PendingSupervisorRequest, state: SubagentState, ctx: ExtensionContext | undefined, now: number): SupervisorRequestLifecycle {\n\tif (ctx && !requestMatchesContext(request, state, ctx)) return \"wrong-session\";\n\tif (!fs.existsSync(request.requestFile)) return \"missing\";\n\tif (request.expectsReply && fs.existsSync(replyPath(request.channelDir, request.id))) return \"resolved\";\n\tif (request.expectsReply && now > requestExpiresAt(request, now)) return \"expired\";\n\tconst runState = requestRunState(request, state);\n\tif (runState === \"stopped\" || (request.expectsReply && runState === \"inactive\")) return \"inactive\";\n\treturn \"pending\";\n}\n\nfunction cleanupRequestLifecycle(request: PendingSupervisorRequest, lifecycle: SupervisorRequestLifecycle): void {\n\tif (lifecycle === \"resolved\" || lifecycle === \"expired\" || lifecycle === \"inactive\") removeRequestFile(request.requestFile);\n}\n\nfunction refreshPendingRequests(pending: Map<string, PendingSupervisorRequest>, state: SubagentState, ctx: ExtensionContext | undefined): void {\n\tconst now = Date.now();\n\tfor (const request of pending.values()) {\n\t\tconst lifecycle = requestLifecycle(request, state, ctx, now);\n\t\tif (lifecycle === \"pending\") continue;\n\t\tpending.delete(request.id);\n\t\tcleanupRequestLifecycle(request, lifecycle);\n\t}\n}\n\nfunction formatPendingLine(request: PendingSupervisorRequest): string {\n\tconst replyHint = request.expectsReply ? ` Reply: ${NATIVE_SUPERVISOR_TOOL_NAME}({ action: \"reply\", replyTo: \"${request.id}\", message: \"...\" })` : \"\";\n\treturn `- ${request.id}: ${request.agent} [${request.runId}#${request.childIndex}] ${request.reason}.${replyHint}`;\n}\n\nfunction requestVisibleText(request: PendingSupervisorRequest, communication: SubagentCommunication): string {\n\tconst lines = [`From: ${communication.peer}`, \"\", communication.message];\n\tif (request.reason === \"interview_request\") lines.push(\"\", \"Reply with JSON matching the requested interview shape.\");\n\tif (request.expectsReply) {\n\t\tlines.push(\"\", `Reply with: ${NATIVE_SUPERVISOR_TOOL_NAME}({ action: \"reply\", replyTo: \"${request.id}\", message: \"...\" })`);\n\t}\n\treturn lines.join(\"\\n\");\n}\n\nfunction writeReply(request: PendingSupervisorRequest, message: string): void {\n\tif (!message.trim()) throw new Error(\"message is required for supervisor replies.\");\n\tconst reply: SupervisorReply = {\n\t\ttype: \"subagent.supervisor.reply\",\n\t\trequestId: request.id,\n\t\tcreatedAt: Date.now(),\n\t\tmessage: message.trim(),\n\t};\n\twriteAtomicJson(replyPath(request.channelDir, request.id), reply);\n\tremoveRequestFile(request.requestFile);\n}\n\nfunction resolvePendingRequest(pending: Map<string, PendingSupervisorRequest>, params: IntercomParams): PendingSupervisorRequest {\n\tif (params.replyTo) {\n\t\tconst request = pending.get(params.replyTo);\n\t\tif (!request) throw new Error(`No pending supervisor request found for replyTo '${params.replyTo}'.`);\n\t\treturn request;\n\t}\n\tconst requests = [...pending.values()].filter((request) => request.expectsReply);\n\tif (params.to) {\n\t\tconst normalizedTo = params.to.toLowerCase();\n\t\tconst matches = requests.filter((request) =>\n\t\t\trequest.id.toLowerCase().startsWith(normalizedTo)\n\t\t\t|| request.agent.toLowerCase() === normalizedTo\n\t\t\t|| request.childTarget?.toLowerCase() === normalizedTo,\n\t\t);\n\t\tif (matches.length === 1) return matches[0]!;\n\t\tif (matches.length > 1) throw new Error(`Multiple pending supervisor requests match '${params.to}'. Use replyTo.`);\n\t}\n\tif (requests.length === 1) return requests[0]!;\n\tif (requests.length === 0) throw new Error(\"No pending supervisor requests need a reply.\");\n\tthrow new Error(\"Multiple pending supervisor requests need replies. Use replyTo.\");\n}\n\nfunction publicPendingRequests(pending: Map<string, PendingSupervisorRequest>): Array<Record<string, unknown>> {\n\treturn [...pending.values()].map((request) => ({\n\t\tid: request.id,\n\t\trunId: request.runId,\n\t\tagent: request.agent,\n\t\tchildIndex: request.childIndex,\n\t\treason: request.reason,\n\t\texpectsReply: request.expectsReply,\n\t}));\n}\n\nfunction buildParentIntercomTool(pending: Map<string, PendingSupervisorRequest>, state: SubagentState, name = \"intercom\"): ToolDefinition<typeof ParentSupervisorParamsSchema, Record<string, unknown>> {\n\treturn {\n\t\tname,\n\t\tlabel: name === \"intercom\" ? \"Intercom\" : \"Subagent Supervisor\",\n\t\tdescription: PARENT_ASK_DESCRIPTION,\n\t\tparameters: ParentSupervisorParamsSchema,\n\t\trenderCall(args, theme, context) {\n\t\t\tconst request = args.action === \"reply\" ? pending.get(args.replyTo) : undefined;\n\t\t\tconst peer = request ? requestCommunication(request, state).peer : args.id ? resolveCommunicationPeer(state, args.id, args.index ?? 0, args.childId) : \"Subagent\";\n\t\t\treturn renderCommunicationCall(name, args, theme, context, args.message ? { direction: \"to\", peer, message: args.message, kind: args.action === \"ask\" ? \"question\" : \"reply\" } : undefined);\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\treturn renderCommunicationResult(result.content, result.details, options.expanded, context.isError, theme);\n\t\t},\n\t\tasync execute(_id, params) {\n\t\t\trefreshPendingRequests(pending, state, state.lastUiContext ?? undefined);\n\t\t\tconst input = params as IntercomParams;\n\t\t\tif (input.action === \"status\") {\n\t\t\t\treturn { content: [{ type: \"text\", text: `Native supervisor channel active. Pending replies: ${pending.size}.` }], details: { active: true, pending: pending.size, root: SUPERVISOR_CHANNEL_ROOT } };\n\t\t\t}\n\t\t\tif (input.action === \"pending\" || input.action === \"list\") {\n\t\t\t\tconst lines = [...pending.values()].filter((request) => request.expectsReply).map(formatPendingLine);\n\t\t\t\treturn { content: [{ type: \"text\", text: lines.length ? lines.join(\"\\n\") : \"No pending supervisor requests.\" }], details: { pending: publicPendingRequests(pending) } };\n\t\t\t}\n\t\t\tif (input.action === \"reply\") {\n\t\t\t\tconst request = resolvePendingRequest(pending, input);\n\t\t\t\twriteReply(request, input.message ?? \"\");\n\t\t\t\tpending.delete(request.id);\n\t\t\t\treturn { content: [{ type: \"text\", text: `Replied to ${requestCommunication(request, state).peer}.` }], details: { replyTo: request.id, runId: request.runId, agent: request.agent, communication: { ...requestCommunication(request, state), direction: \"to\", kind: \"reply\", message: input.message } } };\n\t\t\t}\n\t\t\tif (input.action === \"ask\") {\n\t\t\t\treturn askRunningAsyncChild({\n\t\t\t\t\tparams: {\n\t\t\t\t\t\tid: input.id,\n\t\t\t\t\t\tindex: input.index,\n\t\t\t\t\t\tchildId: input.childId,\n\t\t\t\t\t\treason: input.reason,\n\t\t\t\t\t\tmessage: input.message,\n\t\t\t\t\t},\n\t\t\t\t\tstate,\n\t\t\t\t\tchildRequests: pending.values(),\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (input.action === \"send\") {\n\t\t\t\tthrow new Error(\"Native pi-subagents intercom does not support free-form send. Use action='ask' for a running async child or action='reply' for a pending child request.\");\n\t\t\t}\n\t\t\tthrow new Error(`Unsupported intercom action: ${input.action}`);\n\t\t},\n\t};\n}\n\nfunction questionMatchesParentContext(question: SupervisorQuestion, state: SubagentState, ctx: ExtensionContext): boolean {\n\tconst sessionId = currentSupervisorSessionId(state, ctx);\n\tif (!sessionId || question.parentSessionId !== sessionId) return false;\n\tif ((state.sessionGeneration ?? 0) !== question.parentGeneration) return false;\n\treturn true;\n}\n\nfunction notifyQuestionTerminal(pi: ExtensionAPI, question: SupervisorQuestion, channelDir: string, state: SubagentState): void {\n\tif (!supervisorQuestionIsTerminal(question) || question.notifiedAt) return;\n\t(pi as { events?: IntercomEventBus }).events?.emit(SUBAGENT_QUESTION_EVENT, {\n\t\tquestionId: question.id,\n\t\tstate: supervisorQuestionPublicState(question),\n\t\trunId: question.runId,\n\t});\n\tif (isQuestionWaitActive(question.id)) return;\n\tif (!claimQuestionNotification(channelDir, question.id)) return;\n\tconst outcome = supervisorQuestionPublicState(question);\n\tconst communication: SubagentCommunication = { direction: \"from\", peer: question.childDescription ?? resolveCommunicationPeer(state, question.runId, question.childIndex, question.childId), message: question.answer ?? question.cancelReason ?? outcome, kind: \"answer\" };\n\tpi.sendMessage({\n\t\tcustomType: SUBAGENT_SUPERVISOR_ANSWER_TYPE,\n\t\tcontent: formatSupervisorQuestionAnswer(question),\n\t\tdisplay: outcome === \"answered\",\n\t\tdetails: {\n\t\t\tquestionId: question.id,\n\t\t\tstate: outcome,\n\t\t\tcommunication,\n\t\t\trunId: question.runId,\n\t\t\tchildIndex: question.childIndex,\n\t\t\tchildId: question.childId,\n\t\t\treason: question.reason,\n\t\t\tanswered: outcome === \"answered\",\n\t\t\tdelivered: Boolean(question.deliveredAt),\n\t\t},\n\t}, { triggerTurn: outcome === \"answered\" });\n}\n\nfunction pollSupervisorQuestions(pi: ExtensionAPI, state: SubagentState, ctx: ExtensionContext): void {\n\tfor (const channelDir of listSupervisorChannelDirs()) {\n\t\tfor (const question of listSupervisorQuestions(channelDir)) {\n\t\t\tif (!questionMatchesParentContext(question, state, ctx)) continue;\n\t\t\tconst current = reconcileAsyncQuestion(channelDir, question, state);\n\t\t\tnotifyQuestionTerminal(pi, current, channelDir, state);\n\t\t}\n\t}\n}\n\nexport function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentState): {\n\tstart: () => void;\n\tdispose: () => void;\n\tpending: Map<string, PendingSupervisorRequest>;\n\tcancelOwnedQuestions: (reason: string) => void;\n\tsettleRunQuestions: (runId: string, reason: string) => void;\n} {\n\tconst pending = new Map<string, PendingSupervisorRequest>();\n\tconst seenFiles = new Set<string>();\n\tconst deliveredRequests = new Set<string>();\n\tlet poller: ReturnType<typeof setInterval> | undefined;\n\tlet lastStaleCleanupAt = 0;\n\n\tconst registerParentTools = (): void => {\n\t\tif (!hasTool(pi, NATIVE_SUPERVISOR_TOOL_NAME)) pi.registerTool(buildParentIntercomTool(pending, state, NATIVE_SUPERVISOR_TOOL_NAME));\n\t\tif (!hasTool(pi, \"intercom\")) pi.registerTool(buildParentIntercomTool(pending, state));\n\t};\n\n\tconst cleanupStaleChannelsIfDue = (): void => {\n\t\tconst nowMs = Date.now();\n\t\tif (nowMs - lastStaleCleanupAt < STALE_EMPTY_CHANNEL_CLEANUP_INTERVAL_MS) return;\n\t\tlastStaleCleanupAt = nowMs;\n\t\ttry {\n\t\t\tcleanupStaleEmptySupervisorChannels(nowMs);\n\t\t} catch {\n\t\t\t// Supervisor delivery must not fail because best-effort temp cleanup failed.\n\t\t}\n\t};\n\n\tconst cancelOwnedQuestions = (reason: string): void => {\n\t\tif (!state.currentSessionId) return;\n\t\tcancelPendingSupervisorQuestionsForOwner({\n\t\t\tparentSessionId: state.currentSessionId,\n\t\t\tparentGeneration: state.sessionGeneration ?? 0,\n\t\t\treason,\n\t\t});\n\t};\n\n\tconst settleRunQuestions = (runId: string, reason: string): void => {\n\t\tif (!state.currentSessionId) return;\n\t\tcancelPendingSupervisorQuestionsForOwner({\n\t\t\tparentSessionId: state.currentSessionId,\n\t\t\trunId,\n\t\t\treason,\n\t\t});\n\t};\n\n\tconst poll = (): void => {\n\t\tcleanupStaleChannelsIfDue();\n\t\tconst ctx = state.lastUiContext;\n\t\tif (!ctx) return;\n\t\trefreshPendingRequests(pending, state, ctx);\n\t\tpollSupervisorQuestions(pi, state, ctx);\n\t\tconst now = Date.now();\n\t\tfor (const { channelDir, file } of listRequestFiles()) {\n\t\t\tif (seenFiles.has(file)) continue;\n\t\t\tconst request = parseRequestFile(file, channelDir);\n\t\t\tif (!request || !requestMatchesContext(request, state, ctx)) continue;\n\t\t\tconst lifecycle = requestLifecycle(request, state, undefined, now);\n\t\t\tif (lifecycle !== \"pending\") {\n\t\t\t\tseenFiles.add(file);\n\t\t\t\tcleanupRequestLifecycle(request, lifecycle);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (request.expectsReply) pending.set(request.id, request);\n\t\t\tif (deliveredRequests.has(request.id)) {\n\t\t\t\tseenFiles.add(file);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst communication = requestCommunication(request, state);\n\t\t\tconst details = {\n\t\t\t\tid: request.id,\n\t\t\t\treason: request.reason,\n\t\t\t\texpectsReply: request.expectsReply,\n\t\t\t\trunId: request.runId,\n\t\t\t\tagent: request.agent,\n\t\t\t\tchildIndex: request.childIndex,\n\t\t\t\tcommunication,\n\t\t\t};\n\t\t\tif (request.reason === \"progress_update\" && request.protocolVersion === SUPERVISOR_PROTOCOL_VERSION) {\n\t\t\t\tpi.appendEntry(SUPERVISOR_PROGRESS_TYPE, details);\n\t\t\t} else {\n\t\t\t\tpi.sendMessage({\n\t\t\t\t\tcustomType: SUPERVISOR_REQUEST_TYPE,\n\t\t\t\t\tcontent: requestVisibleText(request, communication),\n\t\t\t\t\tdisplay: true,\n\t\t\t\t\tdetails,\n\t\t\t\t}, { triggerTurn: request.expectsReply || request.reason === \"handoff\" });\n\t\t\t}\n\t\t\tdeliveredRequests.add(request.id);\n\t\t\tseenFiles.add(file);\n\t\t\tif (!request.expectsReply) removeRequestFile(request.requestFile);\n\t\t\tif (request.expectsReply) {\n\t\t\t\tconst job = state.asyncJobs.get(request.runId);\n\t\t\t\tif (job) job.activityState = \"needs_attention\";\n\t\t\t\tconst events = (pi as { events?: IntercomEventBus }).events;\n\t\t\t\tevents?.emit(INTERCOM_DETACH_REQUEST_EVENT, {\n\t\t\t\t\trequestId: request.id,\n\t\t\t\t\trunId: request.runId,\n\t\t\t\t\tagent: request.agent,\n\t\t\t\t\tchildIndex: request.childIndex,\n\t\t\t\t});\n\t\t\t\tevents?.emit(SUBAGENT_CONTROL_EVENT, {\n\t\t\t\t\ttype: \"needs_attention\",\n\t\t\t\t\tto: \"needs_attention\",\n\t\t\t\t\trunId: request.runId,\n\t\t\t\t\tagent: request.agent,\n\t\t\t\t\tindex: request.childIndex,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t};\n\n\treturn {\n\t\tstart: () => {\n\t\t\tif (poller) return;\n\t\t\tregisterParentTools();\n\t\t\tfor (const entry of state.lastUiContext?.sessionManager.getBranch?.() ?? []) {\n\t\t\t\tconst data = entry.type === \"custom_message\" && entry.customType === SUPERVISOR_REQUEST_TYPE ? entry.details\n\t\t\t\t\t: entry.type === \"custom\" && entry.customType === SUPERVISOR_PROGRESS_TYPE ? entry.data : undefined;\n\t\t\t\tif (data && typeof data === \"object\" && \"id\" in data && typeof data.id === \"string\") deliveredRequests.add(data.id);\n\t\t\t}\n\t\t\tpoll();\n\t\t\tpoller = setInterval(poll, CHANNEL_POLL_MS);\n\t\t\tpoller.unref?.();\n\t\t},\n\t\tdispose: () => {\n\t\t\tcancelOwnedQuestions(\"parent supervisor channel disposed\");\n\t\t\tif (poller) clearInterval(poller);\n\t\t\tpoller = undefined;\n\t\t\tpending.clear();\n\t\t\tseenFiles.clear();\n\t\t\tdeliveredRequests.clear();\n\t\t},\n\t\tpending,\n\t\tcancelOwnedQuestions,\n\t\tsettleRunQuestions,\n\t};\n}\n\nexport function isPendingQuestionForCurrentChild(questionId: string): boolean {\n\tconst metadata = readChildMetadata();\n\tconst owner = readChildQuestionOwner(metadata);\n\tif (!metadata || !owner) return false;\n\treturn pendingSupervisorQuestionsForDelivery(metadata.channelDir, owner).some((question) =>\n\t\tquestion.id === questionId && question.parentSessionId === (metadata.supervisorSessionId ?? metadata.orchestratorSessionId),\n\t);\n}\n\nexport function markDeliveredSupervisorQuestionFromChild(message: string): void {\n\tconst match = message.match(/Parent question \\(([^)\\s]+)\\)/);\n\tif (!match?.[1]) return;\n\tconst metadata = readChildMetadata();\n\tconst owner = readChildQuestionOwner(metadata);\n\tif (!metadata || !owner) return;\n\tif (!isPendingQuestionForCurrentChild(match[1])) return;\n\ttry {\n\t\tmarkSupervisorQuestionDelivered(metadata.channelDir, match[1], owner);\n\t} catch {\n\t\t// Delivery markers are best-effort; answer ownership still enforces identity.\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"native-supervisor-channel.d.ts","sourceRoot":"","sources":["../../../../../src/builtin-extensions/pi-subagents/src/intercom/native-supervisor-channel.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,YAAY,EAAoC,MAAM,iCAAiC,CAAC;AAatG,OAAO,EAA6G,KAAK,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAOnK,OAAO,EAeN,2BAA2B,IAAI,yBAAyB,EAQxD,MAAM,2BAA2B,CAAC;AAInC,eAAO,MAAM,2BAA2B,wBAAwB,CAAC;AACjE,eAAO,MAAM,2BAA2B,kCAA4B,CAAC;AAOrE,KAAK,gBAAgB,GAAG,eAAe,GAAG,mBAAmB,GAAG,iBAAiB,GAAG,SAAS,CAAC;AAE9F,UAAU,iBAAiB;IAC1B,IAAI,EAAE,6BAA6B,CAAC;IACpC,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,EAAE,EAAE,MAAM,CAAC;IACX,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,EAAE,gBAAgB,CAAC;IACzB,OAAO,EAAE,MAAM,CAAC;IAChB,YAAY,EAAE,OAAO,CAAC;IACtB,kBAAkB,CA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AED,wBAAgB,wCAAwC,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAY9E","sourcesContent":["// @ts-nocheck\nimport { randomUUID } from \"node:crypto\";\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport type { AgentToolResult } from \"@ashx-j/lunr-agent\";\nimport type { ExtensionAPI, ExtensionContext, ToolDefinition } from \"@ashx-j/lunr\";\nimport { Type } from \"typebox\";\nimport { subagentCommunicationEnabled } from \"../../../../core/settings-manager.ts\";\nimport { getAgentDir } from \"../shared/utils.ts\";\nimport {\n\tSUBAGENT_CHILD_AGENT_ENV,\n\tSUBAGENT_CHILD_INDEX_ENV,\n\tSUBAGENT_ORCHESTRATOR_SESSION_ID_ENV,\n\tSUBAGENT_ORCHESTRATOR_TARGET_ENV,\n\tSUBAGENT_RUN_ID_ENV,\n\tSUBAGENT_SUPERVISOR_CHANNEL_DIR_ENV,\n\tSUBAGENT_SUPERVISOR_SESSION_ID_ENV,\n} from \"../runs/shared/pi-args.ts\";\nimport { ASYNC_DIR, INTERCOM_DETACH_REQUEST_EVENT, POLL_INTERVAL_MS, SUBAGENT_CONTROL_EVENT, type IntercomEventBus, type SubagentState } from \"../shared/types.ts\";\nimport { writeAtomicJson } from \"../shared/atomic-json.ts\";\nimport { askRunningAsyncChild, reconcileAsyncQuestion } from \"./supervisor-ask.ts\";\nimport { CHILD_DESCRIPTION_ENV, SUPERVISOR_PROGRESS_TYPE, SUPERVISOR_PROTOCOL_VERSION, SUPERVISOR_REQUEST_TYPE, legacySupervisorBody, readCommunication, resolveCommunicationPeer, supervisorProtocolAvailable, type SubagentCommunication } from \"./communication.ts\";\nimport { renderCommunicationCall, renderCommunicationCard, renderCommunicationResult } from \"../tui/communication.ts\";\nimport { stopRequestPath } from \"../runs/background/control-channel.ts\";\nimport { readStatus } from \"../shared/utils.ts\";\nimport {\n\tanswerSupervisorQuestion,\n\tcancelPendingSupervisorQuestionsForOwner,\n\tcancelSupervisorQuestion,\n\tclaimQuestionNotification,\n\tformatSupervisorQuestionAnswer,\n\thasOutstandingQuestionForChild,\n\tisQuestionWaitActive,\n\tlistSupervisorChannelDirs,\n\tlistSupervisorQuestions,\n\tmarkSupervisorQuestionDelivered,\n\toutstandingQuestionsForChild,\n\tpendingSupervisorQuestionsForDelivery,\n\tQUESTIONS_DIR,\n\treadSupervisorQuestion,\n\tresolveSupervisorChannelDir as resolveQuestionChannelDir,\n\tSUBAGENT_QUESTION_EVENT,\n\tSUBAGENT_SUPERVISOR_ANSWER_TYPE,\n\tSUPERVISOR_CHANNEL_ROOT,\n\tsupervisorQuestionIsTerminal,\n\tsupervisorQuestionPublicState,\n\ttype SupervisorQuestion,\n\ttype SupervisorQuestionOwner,\n} from \"./supervisor-questions.ts\";\n\nconst REQUESTS_DIR = \"requests\";\nconst REPLIES_DIR = \"replies\";\nexport const NATIVE_SUPERVISOR_TOOL_NAME = \"subagent_supervisor\";\nexport const resolveSupervisorChannelDir = resolveQuestionChannelDir;\nconst MAX_MESSAGE_BYTES = 64 * 1024;\nconst DEFAULT_ASK_TIMEOUT_MS = 10 * 60 * 1000;\nconst CHANNEL_POLL_MS = Math.min(POLL_INTERVAL_MS, 500);\nconst STALE_EMPTY_CHANNEL_AGE_MS = 60 * 1000;\nconst STALE_EMPTY_CHANNEL_CLEANUP_INTERVAL_MS = 60 * 1000;\n\ntype SupervisorReason = \"need_decision\" | \"interview_request\" | \"progress_update\" | \"handoff\";\n\ninterface SupervisorRequest {\n\ttype: \"subagent.supervisor.request\";\n\tprotocolVersion?: number;\n\tdescription?: string;\n\tid: string;\n\tcreatedAt: number;\n\texpiresAt?: number;\n\treason: SupervisorReason;\n\tmessage: string;\n\texpectsReply: boolean;\n\torchestratorTarget?: string;\n\torchestratorSessionId?: string;\n\tsupervisorSessionId?: string;\n\trunId: string;\n\tagent: string;\n\tchildIndex: number;\n\tchildTarget?: string;\n\tinterview?: unknown;\n}\n\ninterface PendingSupervisorRequest extends SupervisorRequest {\n\tchannelDir: string;\n\trequestFile: string;\n}\n\ninterface SupervisorReply {\n\ttype: \"subagent.supervisor.reply\";\n\trequestId: string;\n\tcreatedAt: number;\n\tmessage: string;\n}\n\ninterface ContactSupervisorParams {\n\treason?: SupervisorReason;\n\tmessage?: string;\n\tinterview?: unknown;\n\taction?: \"reply\";\n\treplyTo?: string;\n}\n\ninterface IntercomParams {\n\taction: \"list\" | \"send\" | \"ask\" | \"reply\" | \"pending\" | \"status\";\n\tto?: string;\n\tmessage?: string;\n\treplyTo?: string;\n\tid?: string;\n\tindex?: number;\n\tchildId?: string;\n\treason?: string;\n}\n\nconst PARENT_ASK_DESCRIPTION = [\n\t\"Ask a specific running async child, or reply to a child supervisor request. Asking is unavailable when Subagent communication is off in /settings; final results still arrive normally.\",\n\t\"Ask only when the child owns missing context, the answer changes a concrete next decision, and waiting risks a block or rework.\",\n\t\"Use available results first, batch related questions, and keep working while awaiting the answer. Do not use ask for status checks, polling, duplicate queries, or step-by-step supervision. Follow up only when the answer leaves the original decision unresolved.\",\n\t\"Returns a question id immediately. The child's explicit answer is delivered separately from the final run result.\",\n\t'Ask: { action: \"ask\", id: \"<runId>\", index?: 0, childId?: \"...\", reason: \"<concrete decision>\", message: \"...\" }',\n\t\"Use pending or list to find child requests awaiting your reply; status reports channel availability. Free-form send is unsupported. Asking never revives a child or changes its assignment.\",\n\t'Reply: { action: \"reply\", replyTo: \"<requestId>\", message: \"...\" }',\n].join(\" \");\n\nconst CHILD_CONTACT_DESCRIPTION = [\n\t\"Contact the supervisor for decisions outside your assigned authority, safety concerns, or blockers. Make reversible implementation choices within your scope yourself.\",\n\t\"need_decision/interview_request wait for a reply: state the blocked decision, evidence, and recommended choice. Consolidate related questions; continue independent work before opening a blocking request.\",\n\t\"Return one self-contained final report with outcomes, verification, blockers, and artifact paths; the runtime delivers it. Routine work already appears in activity indicators.\",\n\t\"For parent questions use action='reply' with replyTo set to the question id. Answer from current findings and uncertainty; do not start extra investigation just to reply. Continue the assigned task after replying.\",\n\t\"Do not open a blocking need_decision while a parent question is already outstanding for this child.\",\n].join(\" \");\n\nconst ContactSupervisorParamsSchema = Type.Object({\n\treason: Type.Optional(Type.String({ enum: [\"need_decision\", \"interview_request\", \"progress_update\", \"handoff\"] })),\n\tmessage: Type.Optional(Type.String()),\n\tinterview: Type.Optional(Type.Unsafe({ type: \"object\", additionalProperties: true })),\n\taction: Type.Optional(Type.String({ enum: [\"reply\"] })),\n\treplyTo: Type.Optional(Type.String()),\n}, { additionalProperties: false });\n\nconst IntercomParamsSchema = Type.Object({\n\taction: Type.String({ enum: [\"list\", \"send\", \"ask\", \"reply\", \"pending\", \"status\"] }),\n\tto: Type.Optional(Type.String()),\n\tmessage: Type.Optional(Type.String()),\n\treplyTo: Type.Optional(Type.String()),\n\tid: Type.Optional(Type.String({ description: \"Async run id for action='ask'.\" })),\n\tindex: Type.Optional(Type.Integer({ minimum: 0, description: \"Zero-based child index for action='ask'. Select index or childId when more than one child is running.\" })),\n\tchildId: Type.Optional(Type.String({ description: \"Private child identity for action='ask'.\" })),\n\treason: Type.Optional(Type.String({ description: \"Concrete decision the child's answer will change. Required for action='ask'.\" })),\n}, { additionalProperties: false });\n\nconst ParentSupervisorParamsSchema = Type.Object({\n\t...IntercomParamsSchema.properties,\n\taction: Type.String({ enum: [\"list\", \"ask\", \"reply\", \"pending\", \"status\"] }),\n}, { additionalProperties: false });\n\nfunction safeSegment(value: string): string {\n\treturn value.trim().replace(/[^A-Za-z0-9._-]+/g, \"-\").replace(/^-+|-+$/g, \"\") || \"unknown\";\n}\n\nexport function ensureSupervisorChannelDir(channelDir: string): void {\n\tfs.mkdirSync(path.join(channelDir, REQUESTS_DIR), { recursive: true, mode: 0o700 });\n\tfs.mkdirSync(path.join(channelDir, REPLIES_DIR), { recursive: true, mode: 0o700 });\n\tfs.mkdirSync(path.join(channelDir, QUESTIONS_DIR), { recursive: true, mode: 0o700 });\n}\n\nfunction requestPath(channelDir: string, requestId: string): string {\n\treturn path.join(channelDir, REQUESTS_DIR, `${safeSegment(requestId)}.json`);\n}\n\nfunction replyPath(channelDir: string, requestId: string): string {\n\treturn path.join(channelDir, REPLIES_DIR, `${safeSegment(requestId)}.json`);\n}\n\nfunction readTextEnv(name: string): string | undefined {\n\tconst value = process.env[name]?.trim();\n\treturn value ? value : undefined;\n}\n\nfunction readChildMetadata(): {\n\tdescription?: string;\n\tchannelDir: string;\n\trunId: string;\n\tagent: string;\n\tchildIndex: number;\n\torchestratorTarget?: string;\n\torchestratorSessionId?: string;\n\tchildTarget?: string;\n\tsupervisorSessionId?: string;\n} | undefined {\n\tconst channelDir = readTextEnv(SUBAGENT_SUPERVISOR_CHANNEL_DIR_ENV);\n\tconst runId = readTextEnv(SUBAGENT_RUN_ID_ENV);\n\tconst agent = readTextEnv(SUBAGENT_CHILD_AGENT_ENV);\n\tconst rawIndex = readTextEnv(SUBAGENT_CHILD_INDEX_ENV);\n\tconst orchestratorSessionId = readTextEnv(SUBAGENT_ORCHESTRATOR_SESSION_ID_ENV);\n\tif (!channelDir || !runId || !agent || !orchestratorSessionId || rawIndex === undefined || !/^\\d+$/.test(rawIndex)) return undefined;\n\treturn {\n\t\tchannelDir,\n\t\trunId,\n\t\tagent,\n\t\tchildIndex: Number(rawIndex),\n\t\torchestratorTarget: readTextEnv(SUBAGENT_ORCHESTRATOR_TARGET_ENV),\n\t\torchestratorSessionId,\n\t\tsupervisorSessionId: readTextEnv(SUBAGENT_SUPERVISOR_SESSION_ID_ENV),\n\t\tchildTarget: readTextEnv(\"PI_SUBAGENT_INTERCOM_SESSION_NAME\"),\n\t\tdescription: readTextEnv(CHILD_DESCRIPTION_ENV),\n\t};\n}\n\nfunction readChildQuestionOwner(metadata = readChildMetadata()): SupervisorQuestionOwner | undefined {\n\tif (!metadata) return undefined;\n\tconst readyAt = Number(process.env.PI_SUBAGENT_STEER_READY_AT);\n\tif (!Number.isFinite(readyAt) || readyAt <= 0) return undefined;\n\treturn {\n\t\trunId: metadata.runId,\n\t\tchildIndex: metadata.childIndex,\n\t\tchildId: metadata.agent,\n\t\tpid: process.pid,\n\t\treadyAt,\n\t};\n}\n\nfunction answerParentQuestion(params: ContactSupervisorParams): AgentToolResult<Record<string, unknown>> {\n\tconst metadata = readChildMetadata();\n\tconst owner = readChildQuestionOwner(metadata);\n\tif (!metadata || !owner) throw new Error(\"Native supervisor channel is not available for this subagent.\");\n\tconst replyTo = params.replyTo?.trim();\n\tif (!replyTo) throw new Error(\"action='reply' requires replyTo with the parent question id.\");\n\tconst message = params.message?.trim();\n\tif (!message) throw new Error(\"message is required for supervisor question replies.\");\n\tconst question = readSupervisorQuestion(metadata.channelDir, replyTo);\n\tif (question?.parentSessionId !== (metadata.supervisorSessionId ?? metadata.orchestratorSessionId)) throw new Error(\"Question belongs to a different supervisor session.\");\n\tconst answered = answerSupervisorQuestion(metadata.channelDir, replyTo, message, owner);\n\treturn {\n\t\tcontent: [{ type: \"text\", text: `Replied to parent question ${answered.id}. Continue the assigned task.` }],\n\t\tdetails: {\n\t\t\treplyTo: answered.id,\n\t\t\tstate: supervisorQuestionPublicState(answered),\n\t\t\tanswered: true,\n\t\t\tcommunication: { direction: \"to\", peer: \"Supervisor\", kind: \"reply\", message },\n\t\t},\n\t};\n}\n\nfunction reasonHeading(reason: SupervisorReason): string {\n\tif (reason === \"handoff\") return \"Subagent dependency handoff.\";\n\tif (reason === \"interview_request\") return \"Subagent requests a structured supervisor interview.\";\n\tif (reason === \"progress_update\") return \"Subagent progress update.\";\n\treturn \"Subagent needs a supervisor decision.\";\n}\n\nfunction formatChildMessage(input: {\n\treason: SupervisorReason;\n\tmessage?: string;\n\tinterview?: unknown;\n\trunId: string;\n\tagent: string;\n\tchildIndex: number;\n\tchildTarget?: string;\n}): string {\n\tconst lines = [\n\t\treasonHeading(input.reason),\n\t\t`Run: ${input.runId}`,\n\t\t`Agent: ${input.agent}`,\n\t\t`Child index: ${input.childIndex}`,\n\t];\n\tif (input.childTarget) lines.push(`Child intercom target: ${input.childTarget}`);\n\tlines.push(\"\");\n\tif (input.message?.trim()) lines.push(input.message.trim());\n\tif (input.reason === \"interview_request\") {\n\t\tlines.push(\n\t\t\t\"\",\n\t\t\t\"Structured response requested. Reply with JSON, optionally fenced in ```json, matching the requested interview shape.\",\n\t\t);\n\t\tif (input.interview !== undefined) lines.push(JSON.stringify(input.interview, null, \"\\t\"));\n\t}\n\treturn lines.join(\"\\n\").trimEnd();\n}\n\nfunction communicationKind(reason?: SupervisorReason): SubagentCommunication[\"kind\"] {\n\treturn reason === \"progress_update\" ? \"progress\" : reason === \"handoff\" ? \"handoff\" : reason === \"interview_request\" ? \"interview\" : \"request\";\n}\n\nfunction communicationBody(message: string, interview?: unknown, protocolVersion?: number): string {\n\tconst body = protocolVersion === SUPERVISOR_PROTOCOL_VERSION ? message : legacySupervisorBody(message);\n\treturn interview !== undefined && protocolVersion === SUPERVISOR_PROTOCOL_VERSION ? `${body}\\n\\n${JSON.stringify(interview, null, 2)}` : body;\n}\n\nfunction requestCommunication(request: SupervisorRequest, state: SubagentState): SubagentCommunication {\n\treturn {\n\t\tdirection: \"from\",\n\t\tpeer: resolveCommunicationPeer(state, request.runId, request.childIndex, request.agent, request.description),\n\t\tmessage: communicationBody(request.message, request.interview, request.protocolVersion),\n\t\tkind: communicationKind(request.reason),\n\t};\n}\n\nexport function registerSupervisorRenderers(pi: ExtensionAPI, state: SubagentState): void {\n\tfor (const customType of [SUPERVISOR_REQUEST_TYPE, SUBAGENT_SUPERVISOR_ANSWER_TYPE]) {\n\t\tpi.registerMessageRenderer(customType, (message, options, theme) => {\n\t\t\tconst details = message.details as { communication?: unknown; runId?: string; childIndex?: number; agent?: string; childId?: string; reason?: SupervisorReason } | undefined;\n\t\t\tconst communication = readCommunication(details?.communication) ?? {\n\t\t\t\tdirection: \"from\" as const,\n\t\t\t\tpeer: details?.runId ? resolveCommunicationPeer(state, details.runId, details.childIndex ?? 0, details.childId ?? details.agent) : \"Subagent\",\n\t\t\t\tmessage: legacySupervisorBody(typeof message.content === \"string\" ? message.content : message.content.filter((part) => part.type === \"text\").map((part) => part.text).join(\"\\n\")),\n\t\t\t\tkind: customType === SUBAGENT_SUPERVISOR_ANSWER_TYPE ? \"answer\" as const : communicationKind(details?.reason),\n\t\t\t};\n\t\t\treturn renderCommunicationCard(communication, options.expanded, theme);\n\t\t});\n\t}\n\tpi.registerEntryRenderer(SUPERVISOR_PROGRESS_TYPE, (entry, options, theme) => {\n\t\tconst communication = readCommunication((entry.data as { communication?: unknown } | undefined)?.communication);\n\t\treturn communication ? renderCommunicationCard(communication, options.expanded, theme) : undefined;\n\t});\n}\n\nfunction parseStructuredReply(message: string): { value?: unknown; error?: string } {\n\tconst trimmed = message.trim();\n\tconst fenced = trimmed.match(/^```(?:json)?\\s*([\\s\\S]*?)\\s*```$/i)?.[1]?.trim();\n\ttry {\n\t\treturn { value: JSON.parse(fenced ?? trimmed) };\n\t} catch (error) {\n\t\treturn { error: error instanceof Error ? `${error.name}: ${error.message}` : String(error) };\n\t}\n}\n\nfunction askTimeoutMs(): number {\n\tconst parsed = Number(process.env.PI_INTERCOM_ASK_TIMEOUT_MS);\n\treturn Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_ASK_TIMEOUT_MS;\n}\n\nfunction delay(ms: number, signal?: AbortSignal): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tif (signal?.aborted) {\n\t\t\treject(new Error(\"Supervisor request cancelled.\"));\n\t\t\treturn;\n\t\t}\n\t\tlet timer: ReturnType<typeof setTimeout> | undefined;\n\t\tconst cleanup = () => {\n\t\t\tif (timer) clearTimeout(timer);\n\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t};\n\t\tconst onAbort = () => {\n\t\t\tcleanup();\n\t\t\treject(new Error(\"Supervisor request cancelled.\"));\n\t\t};\n\t\ttimer = setTimeout(() => {\n\t\t\tcleanup();\n\t\t\tresolve();\n\t\t}, ms);\n\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t});\n}\n\nasync function waitForReply(channelDir: string, requestId: string, deadline: number, signal?: AbortSignal): Promise<SupervisorReply> {\n\tconst file = replyPath(channelDir, requestId);\n\twhile (Date.now() <= deadline) {\n\t\tif (signal?.aborted) throw new Error(\"Supervisor request cancelled.\");\n\t\tif (fs.existsSync(file)) {\n\t\t\tconst parsed = JSON.parse(fs.readFileSync(file, \"utf-8\")) as Partial<SupervisorReply>;\n\t\t\tif (parsed.type === \"subagent.supervisor.reply\" && parsed.requestId === requestId && typeof parsed.message === \"string\") {\n\t\t\t\treturn parsed as SupervisorReply;\n\t\t\t}\n\t\t}\n\t\tawait delay(250, signal);\n\t}\n\tthrow new Error(\"Timed out waiting for supervisor reply.\");\n}\n\nasync function sendSupervisorRequest(params: ContactSupervisorParams, signal?: AbortSignal): Promise<AgentToolResult<Record<string, unknown>>> {\n\tif (params.action === \"reply\" || params.replyTo?.trim()) {\n\t\treturn answerParentQuestion(params);\n\t}\n\tconst metadata = readChildMetadata();\n\tif (!metadata) throw new Error(\"Native supervisor channel is not available for this subagent.\");\n\tif (!params.reason) throw new Error(\"reason is required for supervisor contact.\");\n\tif (signal?.aborted) throw new Error(\"Supervisor request cancelled.\");\n\tconst protocolVersion = supervisorProtocolAvailable() ? SUPERVISOR_PROTOCOL_VERSION : undefined;\n\tif (params.reason === \"handoff\" && !protocolVersion) throw new Error(\"This supervisor uses the legacy protocol. Send actionable findings with progress_update instead.\");\n\tconst expectsReply = params.reason === \"need_decision\" || params.reason === \"interview_request\";\n\tif (expectsReply && hasOutstandingQuestionForChild(metadata.channelDir, metadata.childIndex, metadata.agent)) {\n\t\tthrow new Error(\"A parent question is already outstanding for this child. Answer it with action='reply' before opening a blocking supervisor request.\");\n\t}\n\tif (!params.message?.trim() && params.reason !== \"interview_request\") {\n\t\tthrow new Error(\"message is required for supervisor contact.\");\n\t}\n\tensureSupervisorChannelDir(metadata.channelDir);\n\tconst requestId = randomUUID();\n\tconst createdAt = Date.now();\n\tconst replyDeadline = createdAt + askTimeoutMs();\n\tconst expiresAt = expectsReply ? replyDeadline : undefined;\n\tconst message = protocolVersion ? params.message?.trim() || \"Structured supervisor input requested.\" : formatChildMessage({ ...metadata, reason: params.reason, message: params.message, interview: params.interview });\n\tconst communication: SubagentCommunication = { direction: \"to\", peer: \"Supervisor\", kind: communicationKind(params.reason), message: communicationBody(message, params.interview, protocolVersion) };\n\tconst request: SupervisorRequest = {\n\t\ttype: \"subagent.supervisor.request\",\n\t\t...(protocolVersion ? { protocolVersion } : {}),\n\t\t...(metadata.description ? { description: metadata.description } : {}),\n\t\tid: requestId,\n\t\tcreatedAt,\n\t\t...(expiresAt !== undefined ? { expiresAt } : {}),\n\t\treason: params.reason,\n\t\tmessage,\n\t\texpectsReply,\n\t\t...(metadata.orchestratorTarget ? { orchestratorTarget: metadata.orchestratorTarget } : {}),\n\t\t...(metadata.orchestratorSessionId ? { orchestratorSessionId: metadata.orchestratorSessionId } : {}),\n\t\t...(metadata.supervisorSessionId ? { supervisorSessionId: metadata.supervisorSessionId } : {}),\n\t\trunId: metadata.runId,\n\t\tagent: metadata.agent,\n\t\tchildIndex: metadata.childIndex,\n\t\t...(metadata.childTarget ? { childTarget: metadata.childTarget } : {}),\n\t\t...(params.interview !== undefined ? { interview: params.interview } : {}),\n\t};\n\tconst serialized = JSON.stringify(request, null, \"\\t\");\n\tif (Buffer.byteLength(serialized, \"utf-8\") > MAX_MESSAGE_BYTES) throw new Error(\"Supervisor request is too large.\");\n\twriteAtomicJson(requestPath(metadata.channelDir, requestId), request);\n\tif (expectsReply) {\n\t\tfor (const question of outstandingQuestionsForChild(metadata.channelDir, metadata.childIndex, metadata.agent)) {\n\t\t\tcancelSupervisorQuestion(metadata.channelDir, question.id, \"child needs a supervisor decision; reply to its request first\");\n\t\t}\n\t}\n\n\tif (!expectsReply) {\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: params.reason === \"handoff\" ? \"Dependency handoff queued. Continue independent work.\" : protocolVersion ? \"Progress recorded for the UI only; the supervisor model will not receive it.\" : \"Supervisor progress update queued.\" }],\n\t\t\tdetails: { queued: true, requestId, reason: params.reason, communication },\n\t\t};\n\t}\n\n\ttry {\n\t\tconst reply = await waitForReply(metadata.channelDir, requestId, replyDeadline, signal);\n\t\tconst details: Record<string, unknown> = { requestId, reason: params.reason, communication, response: reply.message };\n\t\tif (params.reason === \"interview_request\") {\n\t\t\tconst structured = parseStructuredReply(reply.message);\n\t\t\tif (structured.error) details.structuredReplyParseError = structured.error;\n\t\t\telse details.structuredReply = structured.value;\n\t\t}\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: `**Reply from supervisor:**\\n${reply.message}` }],\n\t\t\tdetails,\n\t\t};\n\t} catch (error) {\n\t\tremoveRequestFile(requestPath(metadata.channelDir, requestId));\n\t\tthrow error;\n\t}\n}\n\nfunction hasTool(pi: ExtensionAPI, name: string): boolean {\n\ttry {\n\t\treturn pi.getAllTools?.().some((tool: { name?: unknown }) => tool.name === name) === true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nexport function registerNativeSupervisorClient(pi: ExtensionAPI, options: { includeIntercomFallback?: boolean } = {}): void {\n\tif (process.env.PI_SUBAGENT_COMMUNICATION_ENABLED === \"0\" || !readChildMetadata()) return;\n\tconst includeIntercomFallback = options.includeIntercomFallback !== false;\n\tif (!hasTool(pi, \"contact_supervisor\")) {\n\t\tconst tool: ToolDefinition<typeof ContactSupervisorParamsSchema, Record<string, unknown>> = {\n\t\t\tname: \"contact_supervisor\",\n\t\t\tlabel: \"Contact Supervisor\",\n\t\t\tdescription: `${CHILD_CONTACT_DESCRIPTION} ${supervisorProtocolAvailable()\n\t\t\t\t? \"handoff delivers actionable dependency findings or corrections without waiting: state what changes and consolidate evidence or reference one artifact. progress_update is UI-only and never reaches the supervisor model.\"\n\t\t\t\t: \"This legacy supervisor delivers progress_update to its model. Reserve it for actionable dependency findings or corrections.\"}`,\n\t\t\tparameters: supervisorProtocolAvailable() ? ContactSupervisorParamsSchema : Type.Object({ ...ContactSupervisorParamsSchema.properties, reason: Type.Optional(Type.String({ enum: [\"need_decision\", \"interview_request\", \"progress_update\"] })) }, { additionalProperties: false }),\n\t\t\trenderCall(args, theme, context) {\n\t\t\t\treturn renderCommunicationCall(\"contact_supervisor\", args, theme, context, { direction: \"to\", peer: \"Supervisor\", kind: args.action === \"reply\" ? \"reply\" : communicationKind(args.reason), message: communicationBody(args.message ?? \"\", args.interview, SUPERVISOR_PROTOCOL_VERSION) });\n\t\t\t},\n\t\t\trenderResult(result, options, theme, context) {\n\t\t\t\treturn renderCommunicationResult(result.content, result.details, options.expanded, context.isError, theme);\n\t\t\t},\n\t\t\texecute(_id, params, signal) {\n\t\t\t\treturn sendSupervisorRequest(params as ContactSupervisorParams, signal);\n\t\t\t},\n\t\t};\n\t\tpi.registerTool(tool);\n\t}\n\tif (includeIntercomFallback && !hasTool(pi, \"intercom\")) {\n\t\tconst tool: ToolDefinition<typeof IntercomParamsSchema, Record<string, unknown>> = {\n\t\t\tname: \"intercom\",\n\t\t\tlabel: \"Intercom\",\n\t\t\tdescription: \"Supervisor-only fallback; sibling discovery and sibling messaging are unavailable. Use contact_supervisor for decisions, replies, and dependency handoffs. list reports no sibling sessions; ask blocks for a supervisor decision; send is progress only.\",\n\t\t\tparameters: IntercomParamsSchema,\n\t\t\trenderCall(args, theme, context) {\n\t\t\t\treturn renderCommunicationCall(\"intercom\", args, theme, context, args.message ? { direction: \"to\", peer: \"Supervisor\", kind: args.action === \"ask\" ? \"request\" : \"progress\", message: args.message } : undefined);\n\t\t\t},\n\t\t\trenderResult(result, options, theme, context) {\n\t\t\t\treturn renderCommunicationResult(result.content, result.details, options.expanded, context.isError, theme);\n\t\t\t},\n\t\t\tasync execute(_id, params, signal) {\n\t\t\t\tconst action = (params as IntercomParams).action;\n\t\t\t\tif (action === \"status\") return { content: [{ type: \"text\", text: \"Native supervisor channel is active.\" }], details: { active: true } };\n\t\t\t\tif (action === \"list\") return { content: [{ type: \"text\", text: \"Supervisor session available through contact_supervisor.\" }], details: { sessions: [] } };\n\t\t\t\tif (action === \"send\") return sendSupervisorRequest({ reason: \"progress_update\", message: (params as IntercomParams).message ?? \"\" }, signal);\n\t\t\t\tif (action === \"ask\") return sendSupervisorRequest({ reason: \"need_decision\", message: (params as IntercomParams).message ?? \"\" }, signal);\n\t\t\t\tthrow new Error(\"Native child intercom supports status, list, send, and ask. Use parent intercom reply from the supervisor session.\");\n\t\t\t},\n\t\t};\n\t\tpi.registerTool(tool);\n\t}\n}\n\nfunction parseRequestFile(file: string, channelDir: string): PendingSupervisorRequest | undefined {\n\ttry {\n\t\tconst parsed = JSON.parse(fs.readFileSync(file, \"utf-8\")) as Partial<SupervisorRequest>;\n\t\tif (parsed.type !== \"subagent.supervisor.request\") return undefined;\n\t\tif (parsed.supervisorSessionId !== undefined && (typeof parsed.supervisorSessionId !== \"string\" || !parsed.supervisorSessionId.trim())) return undefined;\n\t\tif (typeof parsed.id !== \"string\" || !parsed.id) return undefined;\n\t\tif (parsed.reason !== \"need_decision\" && parsed.reason !== \"interview_request\" && parsed.reason !== \"progress_update\" && parsed.reason !== \"handoff\") return undefined;\n\t\tif (parsed.protocolVersion !== undefined && parsed.protocolVersion !== SUPERVISOR_PROTOCOL_VERSION) return undefined;\n\t\tif (parsed.protocolVersion === SUPERVISOR_PROTOCOL_VERSION && parsed.expectsReply !== (parsed.reason === \"need_decision\" || parsed.reason === \"interview_request\")) return undefined;\n\t\tif (parsed.reason === \"handoff\" && parsed.protocolVersion !== SUPERVISOR_PROTOCOL_VERSION) return undefined;\n\t\tif (parsed.description !== undefined && typeof parsed.description !== \"string\") return undefined;\n\t\tif (typeof parsed.message !== \"string\" || !parsed.message) return undefined;\n\t\tif (typeof parsed.runId !== \"string\" || typeof parsed.agent !== \"string\" || typeof parsed.childIndex !== \"number\") return undefined;\n\t\treturn { ...parsed as SupervisorRequest, channelDir, requestFile: file };\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nexport function hasPendingBlockingSupervisorRequest(runId: string, sessionId?: string | null, now = Date.now()): boolean {\n\tif (!runId) return false;\n\tfor (const { channelDir, file } of listRequestFiles()) {\n\t\tconst request = parseRequestFile(file, channelDir);\n\t\tif (!request?.expectsReply) continue;\n\t\tif (request.runId !== runId) continue;\n\t\tif (sessionId && (request.supervisorSessionId ?? request.orchestratorSessionId) !== sessionId) continue;\n\t\tif (fs.existsSync(replyPath(request.channelDir, request.id))) continue;\n\t\tif (now > requestExpiresAt(request, now)) continue;\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nfunction listRequestFiles(): Array<{ channelDir: string; file: string }> {\n\tlet channelEntries: fs.Dirent[];\n\ttry {\n\t\tchannelEntries = fs.readdirSync(SUPERVISOR_CHANNEL_ROOT, { withFileTypes: true });\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n\t\tthrow error;\n\t}\n\tconst files: Array<{ channelDir: string; file: string }> = [];\n\tfor (const entry of channelEntries) {\n\t\tif (!entry.isDirectory()) continue;\n\t\tconst channelDir = path.join(SUPERVISOR_CHANNEL_ROOT, entry.name);\n\t\tconst requestsDir = path.join(channelDir, REQUESTS_DIR);\n\t\tlet requestEntries: fs.Dirent[];\n\t\ttry {\n\t\t\trequestEntries = fs.readdirSync(requestsDir, { withFileTypes: true });\n\t\t} catch {\n\t\t\tcontinue;\n\t\t}\n\t\tfor (const requestEntry of requestEntries) {\n\t\t\tif (requestEntry.isFile() && requestEntry.name.endsWith(\".json\")) files.push({ channelDir, file: path.join(requestsDir, requestEntry.name) });\n\t\t}\n\t}\n\treturn files;\n}\n\nfunction readDirectoryEntries(dir: string): fs.Dirent[] | undefined {\n\ttry {\n\t\treturn fs.readdirSync(dir, { withFileTypes: true });\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n\t\treturn undefined;\n\t}\n}\n\nfunction directoryMtimeMs(dir: string): number {\n\ttry {\n\t\treturn fs.statSync(dir).mtimeMs;\n\t} catch {\n\t\treturn 0;\n\t}\n}\n\nfunction removeEmptyDirectory(dir: string): boolean {\n\ttry {\n\t\tfs.rmdirSync(dir);\n\t\treturn true;\n\t} catch (error) {\n\t\tconst code = (error as NodeJS.ErrnoException).code;\n\t\tif (code === \"ENOENT\") return true;\n\t\tif (code === \"ENOTEMPTY\" || code === \"EEXIST\" || code === \"EPERM\" || code === \"EBUSY\") return false;\n\t\tthrow error;\n\t}\n}\n\nfunction removeStaleEmptySupervisorChannel(channelDir: string, nowMs: number): boolean {\n\tconst requestsDir = path.join(channelDir, REQUESTS_DIR);\n\tconst repliesDir = path.join(channelDir, REPLIES_DIR);\n\tconst questionsPath = path.join(channelDir, QUESTIONS_DIR);\n\tconst newestKnownMtimeMs = Math.max(\n\t\tdirectoryMtimeMs(channelDir),\n\t\tdirectoryMtimeMs(requestsDir),\n\t\tdirectoryMtimeMs(repliesDir),\n\t\tdirectoryMtimeMs(questionsPath),\n\t);\n\tif (nowMs - newestKnownMtimeMs < STALE_EMPTY_CHANNEL_AGE_MS) return false;\n\n\tconst requestEntries = readDirectoryEntries(requestsDir);\n\tif (!requestEntries || requestEntries.length > 0) return false;\n\tconst replyEntries = readDirectoryEntries(repliesDir);\n\tif (!replyEntries || replyEntries.length > 0) return false;\n\tconst questionEntries = readDirectoryEntries(questionsPath);\n\tif (!questionEntries || questionEntries.length > 0) return false;\n\n\tif (!removeEmptyDirectory(requestsDir)) return false;\n\tif (!removeEmptyDirectory(repliesDir)) return false;\n\tif (!removeEmptyDirectory(questionsPath)) return false;\n\tif (!removeEmptyDirectory(channelDir)) return false;\n\treturn true;\n}\n\nfunction cleanupStaleEmptySupervisorChannels(nowMs = Date.now()): number {\n\tlet channelEntries: fs.Dirent[];\n\ttry {\n\t\tchannelEntries = fs.readdirSync(SUPERVISOR_CHANNEL_ROOT, { withFileTypes: true });\n\t} catch (error) {\n\t\tif ((error as NodeJS.ErrnoException).code === \"ENOENT\") return 0;\n\t\tthrow error;\n\t}\n\n\tlet removed = 0;\n\tfor (const entry of channelEntries) {\n\t\tif (!entry.isDirectory()) continue;\n\t\ttry {\n\t\t\tif (removeStaleEmptySupervisorChannel(path.join(SUPERVISOR_CHANNEL_ROOT, entry.name), nowMs)) removed++;\n\t\t} catch {\n\t\t\t// Cleanup is opportunistic; active writers can race with us and will be picked up by a later pass.\n\t\t}\n\t}\n\treturn removed;\n}\n\nfunction currentContextSessionId(state: Pick<SubagentState, \"currentSessionId\">, ctx: ExtensionContext): string | undefined {\n\ttry {\n\t\tconst sessionId = ctx.sessionManager.getSessionId();\n\t\tif (sessionId) return sessionId;\n\t} catch {\n\t\t// Fall through to the last known identity.\n\t}\n\treturn state.currentSessionId ?? undefined;\n}\n\nfunction currentSupervisorSessionId(state: Pick<SubagentState, \"currentSessionId\">, ctx: ExtensionContext): string | undefined {\n\ttry {\n\t\treturn ctx.sessionManager.getSessionFile?.() ?? currentContextSessionId(state, ctx);\n\t} catch {\n\t\treturn state.currentSessionId ?? undefined;\n\t}\n}\n\nfunction requestMatchesContext(request: SupervisorRequest, state: Pick<SubagentState, \"currentSessionId\">, ctx: ExtensionContext): boolean {\n\tconst currentSessionId = request.supervisorSessionId !== undefined\n\t\t? currentSupervisorSessionId(state, ctx)\n\t\t: currentContextSessionId(state, ctx);\n\treturn Boolean(currentSessionId && (request.supervisorSessionId ?? request.orchestratorSessionId) === currentSessionId);\n}\n\nfunction removeRequestFile(file: string): void {\n\ttry {\n\t\tfs.rmSync(file, { force: true });\n\t} catch {\n\t\t// Request cleanup is best-effort; reply files and timeout errors remain authoritative.\n\t}\n}\n\ntype SupervisorRequestLifecycle = \"pending\" | \"resolved\" | \"expired\" | \"inactive\" | \"missing\" | \"wrong-session\";\n\nfunction requestExpiresAt(request: SupervisorRequest, now: number): number {\n\tconst expiresAt = (request as { expiresAt?: unknown }).expiresAt;\n\tif (typeof expiresAt === \"number\" && Number.isFinite(expiresAt)) return expiresAt;\n\treturn Number.isFinite(request.createdAt) ? request.createdAt + askTimeoutMs() : now;\n}\n\nfunction requestRunState(request: SupervisorRequest, state: SubagentState): \"active\" | \"inactive\" | \"stopped\" {\n\tif (state.foregroundControls.has(request.runId)) return \"active\";\n\tconst foregroundRun = state.foregroundRuns?.get(request.runId);\n\tconst foregroundChild = foregroundRun?.children.find((child) => child.index === request.childIndex && child.agent === request.agent)\n\t\t?? foregroundRun?.children[request.childIndex];\n\tif (foregroundChild) return foregroundChild.status === \"stopped\" ? \"stopped\" : foregroundChild.status === \"detached\" ? \"active\" : \"inactive\";\n\n\tconst job = state.asyncJobs.get(request.runId) ?? state.fleetJobs?.get(request.runId);\n\tconst asyncDir = job?.asyncDir ?? path.join(ASYNC_DIR, safeSegment(request.runId));\n\tconst status = readStatus(asyncDir);\n\tconst runStatus = status?.state ?? job?.status;\n\tconst stepStatus = (status?.steps ?? job?.steps)?.[request.childIndex]?.status;\n\tif (fs.existsSync(stopRequestPath(asyncDir)) || runStatus === \"stopped\" || job?.status === \"stopped\" || status?.stopped || stepStatus === \"stopped\") return \"stopped\";\n\tif ([\"complete\", \"failed\", \"paused\"].includes(runStatus ?? \"\") || [\"complete\", \"completed\", \"failed\", \"paused\"].includes(stepStatus ?? \"\")) return \"inactive\";\n\treturn \"active\";\n}\n\nfunction requestLifecycle(request: PendingSupervisorRequest, state: SubagentState, ctx: ExtensionContext | undefined, now: number): SupervisorRequestLifecycle {\n\tif (ctx && !requestMatchesContext(request, state, ctx)) return \"wrong-session\";\n\tif (!fs.existsSync(request.requestFile)) return \"missing\";\n\tif (request.expectsReply && fs.existsSync(replyPath(request.channelDir, request.id))) return \"resolved\";\n\tif (request.expectsReply && now > requestExpiresAt(request, now)) return \"expired\";\n\tconst runState = requestRunState(request, state);\n\tif (runState === \"stopped\" || (request.expectsReply && runState === \"inactive\")) return \"inactive\";\n\treturn \"pending\";\n}\n\nfunction cleanupRequestLifecycle(request: PendingSupervisorRequest, lifecycle: SupervisorRequestLifecycle): void {\n\tif (lifecycle === \"resolved\" || lifecycle === \"expired\" || lifecycle === \"inactive\") removeRequestFile(request.requestFile);\n}\n\nfunction refreshPendingRequests(pending: Map<string, PendingSupervisorRequest>, state: SubagentState, ctx: ExtensionContext | undefined): void {\n\tconst now = Date.now();\n\tfor (const request of pending.values()) {\n\t\tconst lifecycle = requestLifecycle(request, state, ctx, now);\n\t\tif (lifecycle === \"pending\") continue;\n\t\tpending.delete(request.id);\n\t\tcleanupRequestLifecycle(request, lifecycle);\n\t}\n}\n\nfunction formatPendingLine(request: PendingSupervisorRequest): string {\n\tconst replyHint = request.expectsReply ? ` Reply: ${NATIVE_SUPERVISOR_TOOL_NAME}({ action: \"reply\", replyTo: \"${request.id}\", message: \"...\" })` : \"\";\n\treturn `- ${request.id}: ${request.agent} [${request.runId}#${request.childIndex}] ${request.reason}.${replyHint}`;\n}\n\nfunction requestVisibleText(request: PendingSupervisorRequest, communication: SubagentCommunication): string {\n\tconst lines = [`From: ${communication.peer}`, \"\", communication.message];\n\tif (request.reason === \"interview_request\") lines.push(\"\", \"Reply with JSON matching the requested interview shape.\");\n\tif (request.expectsReply) {\n\t\tlines.push(\"\", `Reply with: ${NATIVE_SUPERVISOR_TOOL_NAME}({ action: \"reply\", replyTo: \"${request.id}\", message: \"...\" })`);\n\t}\n\treturn lines.join(\"\\n\");\n}\n\nfunction writeReply(request: PendingSupervisorRequest, message: string): void {\n\tif (!message.trim()) throw new Error(\"message is required for supervisor replies.\");\n\tconst reply: SupervisorReply = {\n\t\ttype: \"subagent.supervisor.reply\",\n\t\trequestId: request.id,\n\t\tcreatedAt: Date.now(),\n\t\tmessage: message.trim(),\n\t};\n\twriteAtomicJson(replyPath(request.channelDir, request.id), reply);\n\tremoveRequestFile(request.requestFile);\n}\n\nfunction resolvePendingRequest(pending: Map<string, PendingSupervisorRequest>, params: IntercomParams): PendingSupervisorRequest {\n\tif (params.replyTo) {\n\t\tconst request = pending.get(params.replyTo);\n\t\tif (!request) throw new Error(`No pending supervisor request found for replyTo '${params.replyTo}'.`);\n\t\treturn request;\n\t}\n\tconst requests = [...pending.values()].filter((request) => request.expectsReply);\n\tif (params.to) {\n\t\tconst normalizedTo = params.to.toLowerCase();\n\t\tconst matches = requests.filter((request) =>\n\t\t\trequest.id.toLowerCase().startsWith(normalizedTo)\n\t\t\t|| request.agent.toLowerCase() === normalizedTo\n\t\t\t|| request.childTarget?.toLowerCase() === normalizedTo,\n\t\t);\n\t\tif (matches.length === 1) return matches[0]!;\n\t\tif (matches.length > 1) throw new Error(`Multiple pending supervisor requests match '${params.to}'. Use replyTo.`);\n\t}\n\tif (requests.length === 1) return requests[0]!;\n\tif (requests.length === 0) throw new Error(\"No pending supervisor requests need a reply.\");\n\tthrow new Error(\"Multiple pending supervisor requests need replies. Use replyTo.\");\n}\n\nfunction publicPendingRequests(pending: Map<string, PendingSupervisorRequest>): Array<Record<string, unknown>> {\n\treturn [...pending.values()].map((request) => ({\n\t\tid: request.id,\n\t\trunId: request.runId,\n\t\tagent: request.agent,\n\t\tchildIndex: request.childIndex,\n\t\treason: request.reason,\n\t\texpectsReply: request.expectsReply,\n\t}));\n}\n\nfunction buildParentIntercomTool(pending: Map<string, PendingSupervisorRequest>, state: SubagentState, name = \"intercom\"): ToolDefinition<typeof ParentSupervisorParamsSchema, Record<string, unknown>> {\n\treturn {\n\t\tname,\n\t\tlabel: name === \"intercom\" ? \"Intercom\" : \"Subagent Supervisor\",\n\t\tdescription: PARENT_ASK_DESCRIPTION,\n\t\tparameters: ParentSupervisorParamsSchema,\n\t\trenderCall(args, theme, context) {\n\t\t\tconst request = args.action === \"reply\" ? pending.get(args.replyTo) : undefined;\n\t\t\tconst peer = request ? requestCommunication(request, state).peer : args.id ? resolveCommunicationPeer(state, args.id, args.index ?? 0, args.childId) : \"Subagent\";\n\t\t\treturn renderCommunicationCall(name, args, theme, context, args.message ? { direction: \"to\", peer, message: args.message, kind: args.action === \"ask\" ? \"question\" : \"reply\" } : undefined);\n\t\t},\n\t\trenderResult(result, options, theme, context) {\n\t\t\treturn renderCommunicationResult(result.content, result.details, options.expanded, context.isError, theme);\n\t\t},\n\t\tasync execute(_id, params) {\n\t\t\trefreshPendingRequests(pending, state, state.lastUiContext ?? undefined);\n\t\t\tconst input = params as IntercomParams;\n\t\t\tif (input.action === \"status\") {\n\t\t\t\treturn { content: [{ type: \"text\", text: `Native supervisor channel active. Pending replies: ${pending.size}.` }], details: { active: true, pending: pending.size, root: SUPERVISOR_CHANNEL_ROOT } };\n\t\t\t}\n\t\t\tif (input.action === \"pending\" || input.action === \"list\") {\n\t\t\t\tconst lines = [...pending.values()].filter((request) => request.expectsReply).map(formatPendingLine);\n\t\t\t\treturn { content: [{ type: \"text\", text: lines.length ? lines.join(\"\\n\") : \"No pending supervisor requests.\" }], details: { pending: publicPendingRequests(pending) } };\n\t\t\t}\n\t\t\tif (input.action === \"reply\") {\n\t\t\t\tconst request = resolvePendingRequest(pending, input);\n\t\t\t\twriteReply(request, input.message ?? \"\");\n\t\t\t\tpending.delete(request.id);\n\t\t\t\treturn { content: [{ type: \"text\", text: `Replied to ${requestCommunication(request, state).peer}.` }], details: { replyTo: request.id, runId: request.runId, agent: request.agent, communication: { ...requestCommunication(request, state), direction: \"to\", kind: \"reply\", message: input.message } } };\n\t\t\t}\n\t\t\tif (input.action === \"ask\") {\n\t\t\t\tif (!subagentCommunicationEnabled(process.cwd(), getAgentDir())) {\n\t\t\t\t\treturn { content: [{ type: \"text\", text: \"Subagent communication is off in /settings. Wait for the child to complete instead of asking it.\" }], isError: true, details: { disabled: true } };\n\t\t\t\t}\n\t\t\t\treturn askRunningAsyncChild({\n\t\t\t\t\tparams: {\n\t\t\t\t\t\tid: input.id,\n\t\t\t\t\t\tindex: input.index,\n\t\t\t\t\t\tchildId: input.childId,\n\t\t\t\t\t\treason: input.reason,\n\t\t\t\t\t\tmessage: input.message,\n\t\t\t\t\t},\n\t\t\t\t\tstate,\n\t\t\t\t\tchildRequests: pending.values(),\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (input.action === \"send\") {\n\t\t\t\tthrow new Error(\"Native pi-subagents intercom does not support free-form send. Use action='ask' for a running async child or action='reply' for a pending child request.\");\n\t\t\t}\n\t\t\tthrow new Error(`Unsupported intercom action: ${input.action}`);\n\t\t},\n\t};\n}\n\nfunction questionMatchesParentContext(question: SupervisorQuestion, state: SubagentState, ctx: ExtensionContext): boolean {\n\tconst sessionId = currentSupervisorSessionId(state, ctx);\n\tif (!sessionId || question.parentSessionId !== sessionId) return false;\n\tif ((state.sessionGeneration ?? 0) !== question.parentGeneration) return false;\n\treturn true;\n}\n\nfunction notifyQuestionTerminal(pi: ExtensionAPI, question: SupervisorQuestion, channelDir: string, state: SubagentState): void {\n\tif (!supervisorQuestionIsTerminal(question) || question.notifiedAt) return;\n\t(pi as { events?: IntercomEventBus }).events?.emit(SUBAGENT_QUESTION_EVENT, {\n\t\tquestionId: question.id,\n\t\tstate: supervisorQuestionPublicState(question),\n\t\trunId: question.runId,\n\t});\n\tif (isQuestionWaitActive(question.id)) return;\n\tif (!claimQuestionNotification(channelDir, question.id)) return;\n\tconst outcome = supervisorQuestionPublicState(question);\n\tconst communication: SubagentCommunication = { direction: \"from\", peer: question.childDescription ?? resolveCommunicationPeer(state, question.runId, question.childIndex, question.childId), message: question.answer ?? question.cancelReason ?? outcome, kind: \"answer\" };\n\tpi.sendMessage({\n\t\tcustomType: SUBAGENT_SUPERVISOR_ANSWER_TYPE,\n\t\tcontent: formatSupervisorQuestionAnswer(question),\n\t\tdisplay: outcome === \"answered\",\n\t\tdetails: {\n\t\t\tquestionId: question.id,\n\t\t\tstate: outcome,\n\t\t\tcommunication,\n\t\t\trunId: question.runId,\n\t\t\tchildIndex: question.childIndex,\n\t\t\tchildId: question.childId,\n\t\t\treason: question.reason,\n\t\t\tanswered: outcome === \"answered\",\n\t\t\tdelivered: Boolean(question.deliveredAt),\n\t\t},\n\t}, { triggerTurn: outcome === \"answered\" });\n}\n\nfunction pollSupervisorQuestions(pi: ExtensionAPI, state: SubagentState, ctx: ExtensionContext): void {\n\tfor (const channelDir of listSupervisorChannelDirs()) {\n\t\tfor (const question of listSupervisorQuestions(channelDir)) {\n\t\t\tif (!questionMatchesParentContext(question, state, ctx)) continue;\n\t\t\tconst current = reconcileAsyncQuestion(channelDir, question, state);\n\t\t\tnotifyQuestionTerminal(pi, current, channelDir, state);\n\t\t}\n\t}\n}\n\nexport function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentState): {\n\tstart: () => void;\n\tdispose: () => void;\n\tpending: Map<string, PendingSupervisorRequest>;\n\tcancelOwnedQuestions: (reason: string) => void;\n\tsettleRunQuestions: (runId: string, reason: string) => void;\n} {\n\tconst pending = new Map<string, PendingSupervisorRequest>();\n\tconst seenFiles = new Set<string>();\n\tconst deliveredRequests = new Set<string>();\n\tlet poller: ReturnType<typeof setInterval> | undefined;\n\tlet lastStaleCleanupAt = 0;\n\n\tconst registerParentTools = (): void => {\n\t\tif (!hasTool(pi, NATIVE_SUPERVISOR_TOOL_NAME)) pi.registerTool(buildParentIntercomTool(pending, state, NATIVE_SUPERVISOR_TOOL_NAME));\n\t\tif (!hasTool(pi, \"intercom\")) pi.registerTool(buildParentIntercomTool(pending, state));\n\t};\n\n\tconst cleanupStaleChannelsIfDue = (): void => {\n\t\tconst nowMs = Date.now();\n\t\tif (nowMs - lastStaleCleanupAt < STALE_EMPTY_CHANNEL_CLEANUP_INTERVAL_MS) return;\n\t\tlastStaleCleanupAt = nowMs;\n\t\ttry {\n\t\t\tcleanupStaleEmptySupervisorChannels(nowMs);\n\t\t} catch {\n\t\t\t// Supervisor delivery must not fail because best-effort temp cleanup failed.\n\t\t}\n\t};\n\n\tconst cancelOwnedQuestions = (reason: string): void => {\n\t\tif (!state.currentSessionId) return;\n\t\tcancelPendingSupervisorQuestionsForOwner({\n\t\t\tparentSessionId: state.currentSessionId,\n\t\t\tparentGeneration: state.sessionGeneration ?? 0,\n\t\t\treason,\n\t\t});\n\t};\n\n\tconst settleRunQuestions = (runId: string, reason: string): void => {\n\t\tif (!state.currentSessionId) return;\n\t\tcancelPendingSupervisorQuestionsForOwner({\n\t\t\tparentSessionId: state.currentSessionId,\n\t\t\trunId,\n\t\t\treason,\n\t\t});\n\t};\n\n\tconst poll = (): void => {\n\t\tcleanupStaleChannelsIfDue();\n\t\tconst ctx = state.lastUiContext;\n\t\tif (!ctx) return;\n\t\trefreshPendingRequests(pending, state, ctx);\n\t\tpollSupervisorQuestions(pi, state, ctx);\n\t\tconst now = Date.now();\n\t\tfor (const { channelDir, file } of listRequestFiles()) {\n\t\t\tif (seenFiles.has(file)) continue;\n\t\t\tconst request = parseRequestFile(file, channelDir);\n\t\t\tif (!request || !requestMatchesContext(request, state, ctx)) continue;\n\t\t\tconst lifecycle = requestLifecycle(request, state, undefined, now);\n\t\t\tif (lifecycle !== \"pending\") {\n\t\t\t\tseenFiles.add(file);\n\t\t\t\tcleanupRequestLifecycle(request, lifecycle);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (request.expectsReply) pending.set(request.id, request);\n\t\t\tif (deliveredRequests.has(request.id)) {\n\t\t\t\tseenFiles.add(file);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst communication = requestCommunication(request, state);\n\t\t\tconst details = {\n\t\t\t\tid: request.id,\n\t\t\t\treason: request.reason,\n\t\t\t\texpectsReply: request.expectsReply,\n\t\t\t\trunId: request.runId,\n\t\t\t\tagent: request.agent,\n\t\t\t\tchildIndex: request.childIndex,\n\t\t\t\tcommunication,\n\t\t\t};\n\t\t\tif (request.reason === \"progress_update\" && request.protocolVersion === SUPERVISOR_PROTOCOL_VERSION) {\n\t\t\t\tpi.appendEntry(SUPERVISOR_PROGRESS_TYPE, details);\n\t\t\t} else {\n\t\t\t\tpi.sendMessage({\n\t\t\t\t\tcustomType: SUPERVISOR_REQUEST_TYPE,\n\t\t\t\t\tcontent: requestVisibleText(request, communication),\n\t\t\t\t\tdisplay: true,\n\t\t\t\t\tdetails,\n\t\t\t\t}, { triggerTurn: request.expectsReply || request.reason === \"handoff\" });\n\t\t\t}\n\t\t\tdeliveredRequests.add(request.id);\n\t\t\tseenFiles.add(file);\n\t\t\tif (!request.expectsReply) removeRequestFile(request.requestFile);\n\t\t\tif (request.expectsReply) {\n\t\t\t\tconst job = state.asyncJobs.get(request.runId);\n\t\t\t\tif (job) job.activityState = \"needs_attention\";\n\t\t\t\tconst events = (pi as { events?: IntercomEventBus }).events;\n\t\t\t\tevents?.emit(INTERCOM_DETACH_REQUEST_EVENT, {\n\t\t\t\t\trequestId: request.id,\n\t\t\t\t\trunId: request.runId,\n\t\t\t\t\tagent: request.agent,\n\t\t\t\t\tchildIndex: request.childIndex,\n\t\t\t\t});\n\t\t\t\tevents?.emit(SUBAGENT_CONTROL_EVENT, {\n\t\t\t\t\ttype: \"needs_attention\",\n\t\t\t\t\tto: \"needs_attention\",\n\t\t\t\t\trunId: request.runId,\n\t\t\t\t\tagent: request.agent,\n\t\t\t\t\tindex: request.childIndex,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t};\n\n\treturn {\n\t\tstart: () => {\n\t\t\tif (poller) return;\n\t\t\tregisterParentTools();\n\t\t\tfor (const entry of state.lastUiContext?.sessionManager.getBranch?.() ?? []) {\n\t\t\t\tconst data = entry.type === \"custom_message\" && entry.customType === SUPERVISOR_REQUEST_TYPE ? entry.details\n\t\t\t\t\t: entry.type === \"custom\" && entry.customType === SUPERVISOR_PROGRESS_TYPE ? entry.data : undefined;\n\t\t\t\tif (data && typeof data === \"object\" && \"id\" in data && typeof data.id === \"string\") deliveredRequests.add(data.id);\n\t\t\t}\n\t\t\tpoll();\n\t\t\tpoller = setInterval(poll, CHANNEL_POLL_MS);\n\t\t\tpoller.unref?.();\n\t\t},\n\t\tdispose: () => {\n\t\t\tcancelOwnedQuestions(\"parent supervisor channel disposed\");\n\t\t\tif (poller) clearInterval(poller);\n\t\t\tpoller = undefined;\n\t\t\tpending.clear();\n\t\t\tseenFiles.clear();\n\t\t\tdeliveredRequests.clear();\n\t\t},\n\t\tpending,\n\t\tcancelOwnedQuestions,\n\t\tsettleRunQuestions,\n\t};\n}\n\nexport function isPendingQuestionForCurrentChild(questionId: string): boolean {\n\tconst metadata = readChildMetadata();\n\tconst owner = readChildQuestionOwner(metadata);\n\tif (!metadata || !owner) return false;\n\treturn pendingSupervisorQuestionsForDelivery(metadata.channelDir, owner).some((question) =>\n\t\tquestion.id === questionId && question.parentSessionId === (metadata.supervisorSessionId ?? metadata.orchestratorSessionId),\n\t);\n}\n\nexport function markDeliveredSupervisorQuestionFromChild(message: string): void {\n\tconst match = message.match(/Parent question \\(([^)\\s]+)\\)/);\n\tif (!match?.[1]) return;\n\tconst metadata = readChildMetadata();\n\tconst owner = readChildQuestionOwner(metadata);\n\tif (!metadata || !owner) return;\n\tif (!isPendingQuestionForCurrentChild(match[1])) return;\n\ttry {\n\t\tmarkSupervisorQuestionDelivered(metadata.channelDir, match[1], owner);\n\t} catch {\n\t\t// Delivery markers are best-effort; answer ownership still enforces identity.\n\t}\n}\n"]}
|
|
@@ -3,6 +3,8 @@ import { randomUUID } from "node:crypto";
|
|
|
3
3
|
import * as fs from "node:fs";
|
|
4
4
|
import * as path from "node:path";
|
|
5
5
|
import { Type } from "typebox";
|
|
6
|
+
import { subagentCommunicationEnabled } from "../../../../core/settings-manager.js";
|
|
7
|
+
import { getAgentDir } from "../shared/utils.js";
|
|
6
8
|
import { SUBAGENT_CHILD_AGENT_ENV, SUBAGENT_CHILD_INDEX_ENV, SUBAGENT_ORCHESTRATOR_SESSION_ID_ENV, SUBAGENT_ORCHESTRATOR_TARGET_ENV, SUBAGENT_RUN_ID_ENV, SUBAGENT_SUPERVISOR_CHANNEL_DIR_ENV, SUBAGENT_SUPERVISOR_SESSION_ID_ENV, } from "../runs/shared/pi-args.js";
|
|
7
9
|
import { ASYNC_DIR, INTERCOM_DETACH_REQUEST_EVENT, POLL_INTERVAL_MS, SUBAGENT_CONTROL_EVENT } from "../shared/types.js";
|
|
8
10
|
import { writeAtomicJson } from "../shared/atomic-json.js";
|
|
@@ -22,7 +24,7 @@ const CHANNEL_POLL_MS = Math.min(POLL_INTERVAL_MS, 500);
|
|
|
22
24
|
const STALE_EMPTY_CHANNEL_AGE_MS = 60 * 1000;
|
|
23
25
|
const STALE_EMPTY_CHANNEL_CLEANUP_INTERVAL_MS = 60 * 1000;
|
|
24
26
|
const PARENT_ASK_DESCRIPTION = [
|
|
25
|
-
"Ask a specific running async child, or reply to a child supervisor request.",
|
|
27
|
+
"Ask a specific running async child, or reply to a child supervisor request. Asking is unavailable when Subagent communication is off in /settings; final results still arrive normally.",
|
|
26
28
|
"Ask only when the child owns missing context, the answer changes a concrete next decision, and waiting risks a block or rework.",
|
|
27
29
|
"Use available results first, batch related questions, and keep working while awaiting the answer. Do not use ask for status checks, polling, duplicate queries, or step-by-step supervision. Follow up only when the answer leaves the original decision unresolved.",
|
|
28
30
|
"Returns a question id immediately. The child's explicit answer is delivered separately from the final run result.",
|
|
@@ -339,7 +341,7 @@ function hasTool(pi, name) {
|
|
|
339
341
|
}
|
|
340
342
|
}
|
|
341
343
|
export function registerNativeSupervisorClient(pi, options = {}) {
|
|
342
|
-
if (!readChildMetadata())
|
|
344
|
+
if (process.env.PI_SUBAGENT_COMMUNICATION_ENABLED === "0" || !readChildMetadata())
|
|
343
345
|
return;
|
|
344
346
|
const includeIntercomFallback = options.includeIntercomFallback !== false;
|
|
345
347
|
if (!hasTool(pi, "contact_supervisor")) {
|
|
@@ -726,6 +728,9 @@ function buildParentIntercomTool(pending, state, name = "intercom") {
|
|
|
726
728
|
return { content: [{ type: "text", text: `Replied to ${requestCommunication(request, state).peer}.` }], details: { replyTo: request.id, runId: request.runId, agent: request.agent, communication: { ...requestCommunication(request, state), direction: "to", kind: "reply", message: input.message } } };
|
|
727
729
|
}
|
|
728
730
|
if (input.action === "ask") {
|
|
731
|
+
if (!subagentCommunicationEnabled(process.cwd(), getAgentDir())) {
|
|
732
|
+
return { content: [{ type: "text", text: "Subagent communication is off in /settings. Wait for the child to complete instead of asking it." }], isError: true, details: { disabled: true } };
|
|
733
|
+
}
|
|
729
734
|
return askRunningAsyncChild({
|
|
730
735
|
params: {
|
|
731
736
|
id: input.id,
|