@ashx-j/lunr 0.2.18 → 0.2.20
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 +31 -1
- package/README.md +2 -2
- package/dist/builtin-extensions/ashxj-tui.d.ts +2 -2
- package/dist/builtin-extensions/ashxj-tui.d.ts.map +1 -1
- package/dist/builtin-extensions/ashxj-tui.js +11 -8
- package/dist/builtin-extensions/ashxj-tui.js.map +1 -1
- package/dist/builtin-extensions/index.d.ts.map +1 -1
- package/dist/builtin-extensions/index.js +0 -2
- package/dist/builtin-extensions/index.js.map +1 -1
- package/dist/builtin-extensions/pi-intercom/broker/spawn.d.ts +6 -4
- package/dist/builtin-extensions/pi-intercom/broker/spawn.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-intercom/broker/spawn.js +93 -49
- package/dist/builtin-extensions/pi-intercom/broker/spawn.js.map +1 -1
- package/dist/builtin-extensions/pi-intercom/index.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-intercom/index.js +351 -351
- package/dist/builtin-extensions/pi-intercom/index.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/extension/index.d.ts +2 -1
- package/dist/builtin-extensions/pi-subagents/src/extension/index.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/extension/index.js +80 -43
- package/dist/builtin-extensions/pi-subagents/src/extension/index.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/extension/schemas.d.ts +18 -8
- package/dist/builtin-extensions/pi-subagents/src/extension/schemas.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/extension/schemas.js +36 -11
- 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 -3
- 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 +21 -12
- package/dist/builtin-extensions/pi-subagents/src/extension/tool-description.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/intercom/native-supervisor-channel.d.ts +7 -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 +225 -15
- package/dist/builtin-extensions/pi-subagents/src/intercom/native-supervisor-channel.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/intercom/supervisor-ask.d.ts +29 -0
- package/dist/builtin-extensions/pi-subagents/src/intercom/supervisor-ask.d.ts.map +1 -0
- package/dist/builtin-extensions/pi-subagents/src/intercom/supervisor-ask.js +179 -0
- package/dist/builtin-extensions/pi-subagents/src/intercom/supervisor-ask.js.map +1 -0
- package/dist/builtin-extensions/pi-subagents/src/intercom/supervisor-questions.d.ts +89 -0
- package/dist/builtin-extensions/pi-subagents/src/intercom/supervisor-questions.d.ts.map +1 -0
- package/dist/builtin-extensions/pi-subagents/src/intercom/supervisor-questions.js +541 -0
- package/dist/builtin-extensions/pi-subagents/src/intercom/supervisor-questions.js.map +1 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/background/async-execution.d.ts +9 -1
- 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 +34 -9
- package/dist/builtin-extensions/pi-subagents/src/runs/background/async-execution.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/background/async-job-tracker.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/background/async-job-tracker.js +1 -2
- package/dist/builtin-extensions/pi-subagents/src/runs/background/async-job-tracker.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/background/async-resume.d.ts +2 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/background/async-resume.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/background/async-resume.js +35 -8
- package/dist/builtin-extensions/pi-subagents/src/runs/background/async-resume.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/background/notify.d.ts +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/background/notify.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/background/notify.js +3 -3
- package/dist/builtin-extensions/pi-subagents/src/runs/background/notify.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/background/result-watcher.d.ts +1 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/background/result-watcher.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/background/result-watcher.js +54 -38
- package/dist/builtin-extensions/pi-subagents/src/runs/background/result-watcher.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/background/subagent-wait.d.ts +3 -6
- package/dist/builtin-extensions/pi-subagents/src/runs/background/subagent-wait.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/background/subagent-wait.js +64 -5
- package/dist/builtin-extensions/pi-subagents/src/runs/background/subagent-wait.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/background/wait-tool.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/background/wait-tool.js +1 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/background/wait-tool.js.map +1 -1
- 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 +21 -8
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/chain-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 +62 -16
- package/dist/builtin-extensions/pi-subagents/src/runs/foreground/subagent-executor.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/shared/acceptance.d.ts +2 -0
- package/dist/builtin-extensions/pi-subagents/src/runs/shared/acceptance.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/shared/acceptance.js +75 -18
- package/dist/builtin-extensions/pi-subagents/src/runs/shared/acceptance.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/shared/model-fallback.d.ts +13 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/shared/model-fallback.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/runs/shared/model-fallback.js +67 -11
- package/dist/builtin-extensions/pi-subagents/src/runs/shared/model-fallback.js.map +1 -1
- 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 +5 -2
- 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 +13 -3
- 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 +3 -0
- 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 +68 -11
- package/dist/builtin-extensions/pi-subagents/src/shared/child-spec.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/shared/formatters.d.ts +12 -1
- package/dist/builtin-extensions/pi-subagents/src/shared/formatters.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/shared/formatters.js +21 -2
- package/dist/builtin-extensions/pi-subagents/src/shared/formatters.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/shared/types.d.ts +16 -4
- package/dist/builtin-extensions/pi-subagents/src/shared/types.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/shared/types.js +1 -1
- package/dist/builtin-extensions/pi-subagents/src/shared/types.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/slash/slash-commands.d.ts +2 -0
- package/dist/builtin-extensions/pi-subagents/src/slash/slash-commands.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/slash/slash-commands.js +24 -6
- package/dist/builtin-extensions/pi-subagents/src/slash/slash-commands.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/tui/render.d.ts +44 -4
- package/dist/builtin-extensions/pi-subagents/src/tui/render.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/tui/render.js +227 -133
- package/dist/builtin-extensions/pi-subagents/src/tui/render.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/watchdog/register-main.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/watchdog/register-main.js +1 -1
- package/dist/builtin-extensions/pi-subagents/src/watchdog/register-main.js.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/watchdog/tool-actions.d.ts +2 -13
- package/dist/builtin-extensions/pi-subagents/src/watchdog/tool-actions.d.ts.map +1 -1
- package/dist/builtin-extensions/pi-subagents/src/watchdog/tool-actions.js +5 -91
- package/dist/builtin-extensions/pi-subagents/src/watchdog/tool-actions.js.map +1 -1
- package/dist/core/permissions.d.ts +1 -0
- package/dist/core/permissions.d.ts.map +1 -1
- package/dist/core/permissions.js +8 -4
- package/dist/core/permissions.js.map +1 -1
- package/dist/core/plan-mode.d.ts.map +1 -1
- package/dist/core/plan-mode.js +0 -5
- 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 +0 -2
- package/dist/core/runtime-bridges.js.map +1 -1
- package/dist/core/subagent-cancellation.d.ts +21 -0
- package/dist/core/subagent-cancellation.d.ts.map +1 -0
- package/dist/core/subagent-cancellation.js +53 -0
- package/dist/core/subagent-cancellation.js.map +1 -0
- package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/assistant-message.js +12 -18
- package/dist/modes/interactive/components/assistant-message.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +12 -0
- 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 +29 -22
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/node-runtime/{agent-session-services-35WNVGMR.js → agent-session-services-75JKASCW.js} +3 -3
- package/dist/node-runtime/{builtin-extensions-QATGXENO.js → builtin-extensions-X4JMM4ZS.js} +3 -3
- package/dist/node-runtime/{chunk-XATUM2HK.js → chunk-25I2BHAA.js} +1 -1
- package/dist/node-runtime/{chunk-MCUNIRD5.js → chunk-46ECNOLF.js} +477 -246
- package/dist/node-runtime/{chunk-J26TSGDL.js → chunk-6N22HULO.js} +8 -5
- package/dist/node-runtime/{chunk-NI6OTSBH.js → chunk-AL2FMKKM.js} +7 -7
- package/dist/node-runtime/chunk-AOFXZQKA.js +24 -0
- package/dist/node-runtime/chunk-BBUVIEZB.js +51 -0
- package/dist/node-runtime/{chunk-EBF6COVM.js → chunk-ELWEXVO5.js} +7 -7
- package/dist/node-runtime/{chunk-R5EDISSV.js → chunk-JHYKXIMM.js} +5 -2
- package/dist/node-runtime/{chunk-ATGA2WLC.js → chunk-JYNNB7DU.js} +397 -34
- package/dist/node-runtime/{chunk-ZBV7FAHG.js → chunk-K3646JTM.js} +17 -118
- package/dist/node-runtime/{chunk-PNJSG3IZ.js → chunk-LTYWTR3V.js} +1 -369
- package/dist/node-runtime/{chunk-G4P75AIS.js → chunk-QKFMBRAL.js} +47 -54
- package/dist/node-runtime/cli-runtime.js +1 -1
- package/dist/node-runtime/{command-AAV3YRR5.js → command-RBTRL55A.js} +1 -1
- package/dist/node-runtime/{gateway-OAC4OBBL.js → gateway-L4ANRTVE.js} +2 -2
- package/dist/node-runtime/index.js +10 -9
- package/dist/node-runtime/{interactive-mode-2SZUO53H.js → interactive-mode-HPUNH7SV.js} +5 -4
- package/dist/node-runtime/{interactive-view-S6J3QHEF.js → interactive-view-ILS6TAN5.js} +1 -1
- package/dist/node-runtime/{lunr-cron-AUUYP4N4.js → lunr-cron-NNYTWTGF.js} +2 -2
- package/dist/node-runtime/main.js +8 -8
- package/dist/node-runtime/{pi-intercom-EEMBGQID.js → pi-intercom-DDQMRNPJ.js} +96 -76
- package/dist/node-runtime/{pi-subagents-7YJ3I4VE.js → pi-subagents-T5WMMLBB.js} +1040 -318
- package/dist/node-runtime/rpc-entry.js +8 -8
- package/dist/node-runtime/{runtime-bridges-3RKBDLNA.js → runtime-bridges-NJQERQ72.js} +2 -4
- package/dist/node-runtime/{subagent-executor-5Q5A4HJ2.js → subagent-executor-SRFC26SJ.js} +168 -249
- package/docs/features.md +17 -3
- package/docs/keybindings.md +3 -1
- package/docs/settings.md +1 -1
- 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/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/builtin-extensions/lunr-settings-tools.d.ts +0 -4
- package/dist/builtin-extensions/lunr-settings-tools.d.ts.map +0 -1
- package/dist/builtin-extensions/lunr-settings-tools.js +0 -120
- package/dist/builtin-extensions/lunr-settings-tools.js.map +0 -1
- package/dist/core/settings-tools-bridge.d.ts +0 -35
- package/dist/core/settings-tools-bridge.d.ts.map +0 -1
- package/dist/core/settings-tools-bridge.js +0 -56
- package/dist/core/settings-tools-bridge.js.map +0 -1
- package/dist/modes/interactive/injected-context.d.ts +0 -2
- package/dist/modes/interactive/injected-context.d.ts.map +0 -1
- package/dist/modes/interactive/injected-context.js +0 -7
- package/dist/modes/interactive/injected-context.js.map +0 -1
- package/dist/node-runtime/chunk-3NMWLTPV.js +0 -64
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"native-supervisor-channel.js","sourceRoot":"","sources":["../../../../../src/builtin-extensions/pi-subagents/src/intercom/native-supervisor-channel.ts"],"names":[],"mappings":"AAAA,cAAc;AACd,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAGlC,OAAO,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAC/B,OAAO,EACN,wBAAwB,EACxB,wBAAwB,EACxB,oCAAoC,EACpC,gCAAgC,EAChC,mBAAmB,EACnB,mCAAmC,GACnC,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,6BAA6B,EAAE,gBAAgB,EAAE,aAAa,EAA6C,MAAM,oBAAoB,CAAC;AAC/I,OAAO,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAE3D,MAAM,uBAAuB,GAAG,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,qBAAqB,CAAC,CAAC;AAChF,MAAM,YAAY,GAAG,UAAU,CAAC;AAChC,MAAM,WAAW,GAAG,SAAS,CAAC;AAC9B,MAAM,CAAC,MAAM,2BAA2B,GAAG,qBAAqB,CAAC;AACjE,MAAM,iBAAiB,GAAG,EAAE,GAAG,IAAI,CAAC;AACpC,MAAM,sBAAsB,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAC9C,MAAM,eAAe,GAAG,IAAI,CAAC,GAAG,CAAC,gBAAgB,EAAE,GAAG,CAAC,CAAC;AACxD,MAAM,0BAA0B,GAAG,EAAE,GAAG,IAAI,CAAC;AAC7C,MAAM,uCAAuC,GAAG,EAAE,GAAG,IAAI,CAAC;AA8C1D,MAAM,6BAA6B,GAAG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BACtB,YAAY,EAAE,OAAO,CAAC,YAAY;oBAClC,KAAK,EAAE,OAAO,CAAC,KAAK;oBACpB,KAAK,EAAE,OAAO,CAAC,KAAK;oBACpB,UAAU,EAAE,OAAO,CAAC,UAAU;iBAC9B;aACD,CAAC,CAAC;YACH,IAAI,OAAO,CAAC,YAAY,EAAE,CAAC;gBACzB,EAAoC,CAAC,MAAM,EAAE,IAAI,CAAC,6BAA6B,EAAE;oBACjF,SAAS,EAAE,OAAO,CAAC,EAAE;oBACrB,KAAK,EAAE,OAAO,CAAC,KAAK;oBACpB,KAAK,EAAE,OAAO,CAAC,KAAK;oBACpB,UAAU,EAAE,OAAO,CAAC,UAAU;iBAC9B,CAAC,CAAC;YACJ,CAAC;QACF,CAAC;IAAA,CACD,CAAC;IAEF,OAAO;QACN,KAAK,EAAE,GAAG,EAAE,CAAC;YACZ,IAAI,MAAM;gBAAE,OAAO;YACnB,mBAAmB,EAAE,CAAC;YACtB,IAAI,EAAE,CAAC;YACP,MAAM,GAAG,WAAW,CAAC,IAAI,EAAE,eAAe,CAAC,CAAC;YAC5C,MAAM,CAAC,KAAK,EAAE,EAAE,CAAC;QAAA,CACjB;QACD,OAAO,EAAE,GAAG,EAAE,CAAC;YACd,IAAI,MAAM;gBAAE,aAAa,CAAC,MAAM,CAAC,CAAC;YAClC,MAAM,GAAG,SAAS,CAAC;YACnB,OAAO,CAAC,KAAK,EAAE,CAAC;YAChB,SAAS,CAAC,KAAK,EAAE,CAAC;QAAA,CAClB;QACD,OAAO;KACP,CAAC;AAAA,CACF","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} from \"../runs/shared/pi-args.ts\";\nimport { INTERCOM_DETACH_REQUEST_EVENT, POLL_INTERVAL_MS, TEMP_ROOT_DIR, type IntercomEventBus, type SubagentState } from \"../shared/types.ts\";\nimport { writeAtomicJson } from \"../shared/atomic-json.ts\";\n\nconst SUPERVISOR_CHANNEL_ROOT = path.join(TEMP_ROOT_DIR, \"supervisor-channels\");\nconst REQUESTS_DIR = \"requests\";\nconst REPLIES_DIR = \"replies\";\nexport const NATIVE_SUPERVISOR_TOOL_NAME = \"subagent_supervisor\";\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\";\n\ninterface SupervisorRequest {\n\ttype: \"subagent.supervisor.request\";\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\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}\n\ninterface IntercomParams {\n\taction: \"list\" | \"send\" | \"ask\" | \"reply\" | \"pending\" | \"status\";\n\tto?: string;\n\tmessage?: string;\n\treplyTo?: string;\n}\n\nconst ContactSupervisorParamsSchema = Type.Object({\n\treason: Type.String({ enum: [\"need_decision\", \"interview_request\", \"progress_update\"] }),\n\tmessage: Type.Optional(Type.String()),\n\tinterview: Type.Optional(Type.Unsafe({ type: \"object\", additionalProperties: true })),\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}, { 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 resolveSupervisorChannelDir(runId: string, agent: string, childIndex: number): string {\n\treturn path.join(SUPERVISOR_CHANNEL_ROOT, `${safeSegment(runId)}-${safeSegment(agent)}-${childIndex}`);\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}\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\tchannelDir: string;\n\trunId: string;\n\tagent: string;\n\tchildIndex: number;\n\torchestratorTarget?: string;\n\torchestratorSessionId?: string;\n\tchildTarget?: 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\tchildTarget: readTextEnv(\"PI_SUBAGENT_INTERCOM_SESSION_NAME\"),\n\t};\n}\n\nfunction reasonHeading(reason: SupervisorReason): string {\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 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\tconst metadata = readChildMetadata();\n\tif (!metadata) throw new Error(\"Native supervisor channel is not available for this subagent.\");\n\tif (params.reason !== \"progress_update\" && !params.message?.trim() && params.reason !== \"interview_request\") {\n\t\tthrow new Error(\"message is required for supervisor decisions.\");\n\t}\n\tensureSupervisorChannelDir(metadata.channelDir);\n\tconst requestId = randomUUID();\n\tconst expectsReply = params.reason !== \"progress_update\";\n\tconst createdAt = Date.now();\n\tconst replyDeadline = createdAt + askTimeoutMs();\n\tconst expiresAt = expectsReply ? replyDeadline : undefined;\n\tconst message = formatChildMessage({ ...metadata, reason: params.reason, message: params.message, interview: params.interview });\n\tconst request: SupervisorRequest = {\n\t\ttype: \"subagent.supervisor.request\",\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\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\n\tif (!expectsReply) {\n\t\treturn {\n\t\t\tcontent: [{ type: \"text\", text: \"Supervisor progress update queued.\" }],\n\t\t\tdetails: { delivered: true, requestId, reason: params.reason },\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 };\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: \"Contact the parent/supervisor session for a blocking decision, structured interview, or progress update.\",\n\t\t\tparameters: ContactSupervisorParamsSchema,\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: \"Native supervisor-channel intercom fallback for subagents. Prefer contact_supervisor when available.\",\n\t\t\tparameters: IntercomParamsSchema,\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 (typeof parsed.id !== \"string\" || !parsed.id) return undefined;\n\t\tif (parsed.reason !== \"need_decision\" && parsed.reason !== \"interview_request\" && parsed.reason !== \"progress_update\") 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\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 newestKnownMtimeMs = Math.max(\n\t\tdirectoryMtimeMs(channelDir),\n\t\tdirectoryMtimeMs(requestsDir),\n\t\tdirectoryMtimeMs(repliesDir),\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\n\tif (!removeEmptyDirectory(requestsDir)) return false;\n\tif (!removeEmptyDirectory(repliesDir)) 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 requestMatchesContext(request: SupervisorRequest, state: Pick<SubagentState, \"currentSessionId\">, ctx: ExtensionContext): boolean {\n\tconst currentSessionId = currentContextSessionId(state, ctx);\n\treturn Boolean(currentSessionId && 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 requestRunInactive(request: SupervisorRequest, state: SubagentState): boolean {\n\tif (state.foregroundControls.has(request.runId)) return false;\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 !== \"detached\";\n\n\tconst asyncJob = state.asyncJobs.get(request.runId);\n\tif (!asyncJob) return false;\n\tif (asyncJob.status === \"complete\" || asyncJob.status === \"failed\" || asyncJob.status === \"paused\") return true;\n\tconst stepStatus = asyncJob.steps?.[request.childIndex]?.status;\n\treturn stepStatus === \"complete\" || stepStatus === \"completed\" || stepStatus === \"failed\" || stepStatus === \"paused\";\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\tif (request.expectsReply && requestRunInactive(request, state)) 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): string {\n\tconst lines = [request.message];\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 IntercomParamsSchema, Record<string, unknown>> {\n\treturn {\n\t\tname,\n\t\tlabel: name === \"intercom\" ? \"Intercom\" : \"Subagent Supervisor\",\n\t\tdescription: name === \"intercom\"\n\t\t\t? \"Native pi-subagents supervisor channel. Use reply/pending/status to answer child subagent requests.\"\n\t\t\t: \"Native pi-subagents supervisor channel. Use reply/pending/status to answer child subagent requests without overriding pi-intercom.\",\n\t\tparameters: IntercomParamsSchema,\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 supervisor request ${request.id}.` }], details: { replyTo: request.id, runId: request.runId, agent: request.agent } };\n\t\t\t}\n\t\t\tif (input.action === \"send\" || input.action === \"ask\") {\n\t\t\t\tthrow new Error(\"Native pi-subagents intercom currently handles supervisor replies. Child agents initiate asks with contact_supervisor.\");\n\t\t\t}\n\t\t\tthrow new Error(`Unsupported intercom action: ${input.action}`);\n\t\t},\n\t};\n}\n\nexport function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentState): { start: () => void; dispose: () => void; pending: Map<string, PendingSupervisorRequest> } {\n\tconst pending = new Map<string, PendingSupervisorRequest>();\n\tconst seenFiles = 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 poll = (): void => {\n\t\tcleanupStaleChannelsIfDue();\n\t\tconst ctx = state.lastUiContext;\n\t\tif (!ctx) return;\n\t\trefreshPendingRequests(pending, 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\tseenFiles.add(file);\n\t\t\tif (request.expectsReply) pending.set(request.id, request);\n\t\t\telse {\n\t\t\t\tremoveRequestFile(request.requestFile);\n\t\t\t}\n\t\t\tpi.sendMessage({\n\t\t\t\tcustomType: \"subagent_supervisor_request\",\n\t\t\t\tcontent: requestVisibleText(request),\n\t\t\t\tdisplay: true,\n\t\t\t\tdetails: {\n\t\t\t\t\tid: request.id,\n\t\t\t\t\treason: request.reason,\n\t\t\t\t\texpectsReply: request.expectsReply,\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});\n\t\t\tif (request.expectsReply) {\n\t\t\t\t(pi as { events?: IntercomEventBus }).events?.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}\n\t\t}\n\t};\n\n\treturn {\n\t\tstart: () => {\n\t\t\tif (poller) return;\n\t\t\tregisterParentTools();\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\tif (poller) clearInterval(poller);\n\t\t\tpoller = undefined;\n\t\t\tpending.clear();\n\t\t\tseenFiles.clear();\n\t\t},\n\t\tpending,\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"native-supervisor-channel.js","sourceRoot":"","sources":["../../../../../src/builtin-extensions/pi-subagents/src/intercom/native-supervisor-channel.ts"],"names":[],"mappings":"AAAA,cAAc;AACd,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAGlC,OAAO,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAC/B,OAAO,EACN,wBAAwB,EACxB,wBAAwB,EACxB,oCAAoC,EACpC,gCAAgC,EAChC,mBAAmB,EACnB,mCAAmC,GACnC,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,6BAA6B,EAAE,gBAAgB,EAAE,sBAAsB,EAA6C,MAAM,oBAAoB,CAAC;AACxJ,OAAO,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAC3D,OAAO,EAAE,oBAAoB,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AACnF,OAAO,EACN,wBAAwB,EACxB,wCAAwC,EACxC,wBAAwB,EACxB,yBAAyB,EACzB,8BAA8B,EAC9B,8BAA8B,EAC9B,oBAAoB,EACpB,yBAAyB,EACzB,uBAAuB,EACvB,+BAA+B,EAC/B,4BAA4B,EAC5B,qCAAqC,EACrC,aAAa,EACb,2BAA2B,IAAI,yBAAyB,EACxD,uBAAuB,EACvB,+BAA+B,EAC/B,uBAAuB,EACvB,4BAA4B,EAC5B,6BAA6B,GAG7B,MAAM,2BAA2B,CAAC;AAEnC,MAAM,YAAY,GAAG,UAAU,CAAC;AAChC,MAAM,WAAW,GAAG,SAAS,CAAC;AAC9B,MAAM,CAAC,MAAM,2BAA2B,GAAG,qBAAqB,CAAC;AACjE,MAAM,CAAC,MAAM,2BAA2B,GAAG,yBAAyB,CAAC;AACrE,MAAM,iBAAiB,GAAG,EAAE,GAAG,IAAI,CA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":["// @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} from \"../runs/shared/pi-args.ts\";\nimport { 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 {\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\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\";\n\ninterface SupervisorRequest {\n\ttype: \"subagent.supervisor.request\";\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\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 parent/supervisor session for a blocking decision, structured interview, progress update, or reply to a parent question.\",\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\"] })),\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\tchannelDir: string;\n\trunId: string;\n\tagent: string;\n\tchildIndex: number;\n\torchestratorTarget?: string;\n\torchestratorSessionId?: string;\n\tchildTarget?: 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\tchildTarget: readTextEnv(\"PI_SUBAGENT_INTERCOM_SESSION_NAME\"),\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 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},\n\t};\n}\n\nfunction reasonHeading(reason: SupervisorReason): string {\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 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 (params.reason !== \"progress_update\" && 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.reason !== \"progress_update\" && !params.message?.trim() && params.reason !== \"interview_request\") {\n\t\tthrow new Error(\"message is required for supervisor decisions.\");\n\t}\n\tensureSupervisorChannelDir(metadata.channelDir);\n\tconst requestId = randomUUID();\n\tconst expectsReply = params.reason !== \"progress_update\";\n\tconst createdAt = Date.now();\n\tconst replyDeadline = createdAt + askTimeoutMs();\n\tconst expiresAt = expectsReply ? replyDeadline : undefined;\n\tconst message = formatChildMessage({ ...metadata, reason: params.reason, message: params.message, interview: params.interview });\n\tconst request: SupervisorRequest = {\n\t\ttype: \"subagent.supervisor.request\",\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\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: \"Supervisor progress update queued.\" }],\n\t\t\tdetails: { delivered: true, requestId, reason: params.reason },\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 };\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,\n\t\t\tparameters: ContactSupervisorParamsSchema,\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: \"Native supervisor-channel intercom fallback for subagents. Prefer contact_supervisor when available.\",\n\t\t\tparameters: IntercomParamsSchema,\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 (typeof parsed.id !== \"string\" || !parsed.id) return undefined;\n\t\tif (parsed.reason !== \"need_decision\" && parsed.reason !== \"interview_request\" && parsed.reason !== \"progress_update\") 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.orchestratorSessionId && 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 requestMatchesContext(request: SupervisorRequest, state: Pick<SubagentState, \"currentSessionId\">, ctx: ExtensionContext): boolean {\n\tconst currentSessionId = currentContextSessionId(state, ctx);\n\treturn Boolean(currentSessionId && 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 requestRunInactive(request: SupervisorRequest, state: SubagentState): boolean {\n\tif (state.foregroundControls.has(request.runId)) return false;\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 !== \"detached\";\n\n\tconst asyncJob = state.asyncJobs.get(request.runId);\n\tif (!asyncJob) return false;\n\tif (asyncJob.status === \"complete\" || asyncJob.status === \"failed\" || asyncJob.status === \"paused\") return true;\n\tconst stepStatus = asyncJob.steps?.[request.childIndex]?.status;\n\treturn stepStatus === \"complete\" || stepStatus === \"completed\" || stepStatus === \"failed\" || stepStatus === \"paused\";\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\tif (request.expectsReply && requestRunInactive(request, state)) 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): string {\n\tconst lines = [request.message];\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\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 supervisor request ${request.id}.` }], details: { replyTo: request.id, runId: request.runId, agent: request.agent } };\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 = currentContextSessionId(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): 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 state = supervisorQuestionPublicState(question);\n\tpi.sendMessage({\n\t\tcustomType: SUBAGENT_SUPERVISOR_ANSWER_TYPE,\n\t\tcontent: formatSupervisorQuestionAnswer(question),\n\t\tdisplay: state === \"answered\",\n\t\tdetails: {\n\t\t\tquestionId: question.id,\n\t\t\tstate,\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: state === \"answered\",\n\t\t\tdelivered: Boolean(question.deliveredAt),\n\t\t},\n\t}, { triggerTurn: state === \"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);\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\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\tseenFiles.add(file);\n\t\t\tif (request.expectsReply) pending.set(request.id, request);\n\t\t\telse {\n\t\t\t\tremoveRequestFile(request.requestFile);\n\t\t\t}\n\t\t\tpi.sendMessage({\n\t\t\t\tcustomType: \"subagent_supervisor_request\",\n\t\t\t\tcontent: requestVisibleText(request),\n\t\t\t\tdisplay: true,\n\t\t\t\tdetails: {\n\t\t\t\t\tid: request.id,\n\t\t\t\t\treason: request.reason,\n\t\t\t\t\texpectsReply: request.expectsReply,\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});\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\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},\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.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\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"]}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { AgentToolResult } from "@ashx-j/lunr-agent";
|
|
2
|
+
import type { AsyncStatus, SubagentState } from "../shared/types.ts";
|
|
3
|
+
import { type SupervisorQuestion } from "./supervisor-questions.ts";
|
|
4
|
+
export interface ParentAskParams {
|
|
5
|
+
id?: string;
|
|
6
|
+
index?: number;
|
|
7
|
+
childId?: string;
|
|
8
|
+
reason?: string;
|
|
9
|
+
message?: string;
|
|
10
|
+
}
|
|
11
|
+
export interface ParentAskRequestFile {
|
|
12
|
+
expectsReply?: boolean;
|
|
13
|
+
runId?: string;
|
|
14
|
+
childIndex?: number;
|
|
15
|
+
agent?: string;
|
|
16
|
+
childTarget?: string;
|
|
17
|
+
}
|
|
18
|
+
export declare function resolveAskChild(status: AsyncStatus, params: Pick<ParentAskParams, "index" | "childId">): {
|
|
19
|
+
index: number;
|
|
20
|
+
childId: string;
|
|
21
|
+
agent: string;
|
|
22
|
+
};
|
|
23
|
+
export declare function reconcileAsyncQuestion(channelDir: string, question: SupervisorQuestion, state: SubagentState): SupervisorQuestion;
|
|
24
|
+
export declare function askRunningAsyncChild(input: {
|
|
25
|
+
params: ParentAskParams;
|
|
26
|
+
state: SubagentState;
|
|
27
|
+
childRequests?: Iterable<ParentAskRequestFile>;
|
|
28
|
+
}): AgentToolResult<Record<string, unknown>>;
|
|
29
|
+
//# sourceMappingURL=supervisor-ask.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"supervisor-ask.d.ts","sourceRoot":"","sources":["../../../../../src/builtin-extensions/pi-subagents/src/intercom/supervisor-ask.ts"],"names":[],"mappings":"AAAA,OAA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apability, requestAsyncSteer } from \"../runs/background/control-channel.ts\";\nimport { resolveSubagentRunId } from \"../runs/background/run-id-resolver.ts\";\nimport { readStatus } from \"../shared/utils.ts\";\nimport type { AsyncStatus, SubagentState } from \"../shared/types.ts\";\nimport {\n\tcancelSupervisorQuestion,\n\tcreateSupervisorQuestion,\n\tformatParentQuestionForChild,\n\texpireSupervisorQuestion,\n\thasOutstandingQuestionForChild,\n\thasBlockingSupervisorRequest,\n\tincarnationMatches,\n\treadSupervisorQuestion,\n\tsupervisorQuestionIsTerminal,\n\tresolveSupervisorChannelDir,\n\ttype SupervisorChildIncarnation,\n\ttype SupervisorQuestion,\n} from \"./supervisor-questions.ts\";\n\nexport interface ParentAskParams {\n\tid?: string;\n\tindex?: number;\n\tchildId?: string;\n\treason?: string;\n\tmessage?: string;\n}\n\nexport interface ParentAskRequestFile {\n\texpectsReply?: boolean;\n\trunId?: string;\n\tchildIndex?: number;\n\tagent?: string;\n\tchildTarget?: string;\n}\n\nfunction runningSteps(status: AsyncStatus): Array<{ index: number; childId: string; agent: string }> {\n\treturn (status.steps ?? [])\n\t\t.map((step, index) => ({\n\t\t\tindex,\n\t\t\tchildId: step.childId ?? step.agent,\n\t\t\tagent: step.agent,\n\t\t\tstatus: step.status,\n\t\t}))\n\t\t.filter((step) => step.status === \"running\")\n\t\t.map((step) => ({ index: step.index, childId: step.childId, agent: step.agent }));\n}\n\nexport function resolveAskChild(\n\tstatus: AsyncStatus,\n\tparams: Pick<ParentAskParams, \"index\" | \"childId\">,\n): { index: number; childId: string; agent: string } {\n\tif (params.index !== undefined && (!Number.isInteger(params.index) || params.index < 0)) {\n\t\tthrow new Error(\"index must be a non-negative integer.\");\n\t}\n\tconst running = runningSteps(status);\n\tif (params.childId?.trim()) {\n\t\tconst childId = params.childId.trim();\n\t\tconst matches = (status.steps ?? [])\n\t\t\t.map((step, index) => ({ index, childId: step.childId ?? step.agent, agent: step.agent, status: step.status }))\n\t\t\t.filter((step) => step.childId === childId);\n\t\tif (matches.length === 0) throw new Error(`Async run '${status.runId}' has no child '${childId}'.`);\n\t\tif (matches.length > 1) throw new Error(`Async run '${status.runId}' has multiple children named '${childId}'. Pass index.`);\n\t\tconst match = matches[0]!;\n\t\tif (params.index !== undefined && params.index !== match.index) {\n\t\t\tthrow new Error(`Child '${childId}' is index ${match.index}, not ${params.index}.`);\n\t\t}\n\t\tif (match.status !== \"running\") throw new Error(`Async run '${status.runId}' child ${match.index} is ${match.status} and cannot be asked.`);\n\t\treturn { index: match.index, childId: match.childId, agent: match.agent };\n\t}\n\tif (params.index !== undefined) {\n\t\tconst steps = status.steps ?? [];\n\t\tif (params.index >= steps.length) {\n\t\t\tthrow new Error(`Async run '${status.runId}' has ${steps.length} children. Index ${params.index} is out of range.`);\n\t\t}\n\t\tconst step = steps[params.index]!;\n\t\tif (step.status !== \"running\") throw new Error(`Async run '${status.runId}' child ${params.index} is ${step.status} and cannot be asked.`);\n\t\treturn { index: params.index, childId: step.childId ?? step.agent, agent: step.agent };\n\t}\n\tif (running.length === 1) return running[0]!;\n\tif (running.length === 0) throw new Error(`Async run '${status.runId}' has no running child to ask.`);\n\tthrow new Error(`Async run '${status.runId}' has ${running.length} running children. Pass index or childId; broadcast asks are not supported.`);\n}\n\nfunction requestMatchesChild(request: ParentAskRequestFile, runId: string, child: { index: number; childId: string; agent: string }): boolean {\n\tif (!request.expectsReply) return false;\n\tif (typeof request.runId !== \"string\" || request.runId !== runId) return false;\n\tconst indexMatches = Number.isInteger(request.childIndex) && request.childIndex === child.index;\n\tconst idMatches = request.agent === child.childId\n\t\t|| request.agent === child.agent\n\t\t|| request.childTarget === child.childId;\n\treturn indexMatches && idMatches;\n}\n\nexport function reconcileAsyncQuestion(channelDir: string, question: SupervisorQuestion, state: SubagentState): SupervisorQuestion {\n\texpireSupervisorQuestion(channelDir, question.id);\n\tconst current = readSupervisorQuestion(channelDir, question.id) ?? question;\n\tif (supervisorQuestionIsTerminal(current)) return current;\n\tconst resolved = resolveSubagentRunId(current.runId, { state });\n\tif (resolved?.kind !== \"async\" || !resolved.location.asyncDir) return current;\n\tconst status = readStatus(resolved.location.asyncDir);\n\tif (!status) return current;\n\tconst step = status.steps?.[current.childIndex];\n\tconst capability = readSteerCapability(resolved.location.asyncDir, current.childIndex);\n\tlet reason: string | undefined;\n\tif (status.sessionId !== current.parentSessionId) reason = \"async run ownership changed\";\n\telse if (status.state !== \"running\" || !step || step.status !== \"running\") reason = \"target child is no longer running\";\n\telse if ((step.childId ?? step.agent) !== current.childId) reason = \"target child identity changed\";\n\telse if (capability && !incarnationMatches(current.childIncarnation, capability)) reason = \"target child process changed\";\n\telse if (capability && !capability.supported) reason = \"target child no longer accepts questions\";\n\tconst delivery = status.steering?.recent.find((request) => request.id === current.id)?.targets.find((target) => target.index === current.childIndex);\n\tif (delivery?.state === \"failed\" || delivery?.state === \"late\") reason = delivery.reason ?? \"question delivery failed\";\n\treturn reason ? cancelSupervisorQuestion(channelDir, current.id, reason) ?? current : current;\n}\n\nexport function askRunningAsyncChild(input: {\n\tparams: ParentAskParams;\n\tstate: SubagentState;\n\tchildRequests?: Iterable<ParentAskRequestFile>;\n}): AgentToolResult<Record<string, unknown>> {\n\tconst runId = input.params.id?.trim();\n\tif (!runId) throw new Error(\"action='ask' requires id for the async run.\");\n\tconst reason = input.params.reason?.trim();\n\tconst message = input.params.message?.trim();\n\tif (!reason) throw new Error(\"action='ask' requires reason naming the concrete decision the child's answer will change.\");\n\tif (!message) throw new Error(\"action='ask' requires message.\");\n\tconst sessionId = input.state.currentSessionId;\n\tif (!sessionId) throw new Error(\"action='ask' requires an active session identity.\");\n\n\tconst resolved = resolveSubagentRunId(runId, { state: input.state });\n\tif (!resolved) throw new Error(`No async run matched '${runId}'.`);\n\tif (resolved.kind !== \"async\") throw new Error(\"action='ask' targets a running async child only. It does not revive, reassign, or broadcast.\");\n\tif (!resolved.location.asyncDir) throw new Error(`Async run '${resolved.id}' has no live run directory.`);\n\n\tconst status = readStatus(resolved.location.asyncDir);\n\tif (!status) throw new Error(`Async run '${resolved.id}' has no status.`);\n\tif (!status.sessionId || status.sessionId !== sessionId) {\n\t\tthrow new Error(`Async run '${resolved.id}' was not found in the active session.`);\n\t}\n\tif (status.state !== \"running\") throw new Error(`Async run '${resolved.id}' is ${status.state} and cannot be asked.`);\n\n\tconst child = resolveAskChild(status, input.params);\n\tconst channelDir = resolveSupervisorChannelDir(status.runId, child.childId, child.index);\n\tif (hasOutstandingQuestionForChild(channelDir, child.index, child.childId)) {\n\t\tthrow new Error(`A question is already outstanding for async run '${status.runId}' child ${child.index}. Wait for that answer or expiry before asking again.`);\n\t}\n\tfor (const request of input.childRequests ?? []) {\n\t\tif (requestMatchesChild(request, status.runId, child)) {\n\t\t\tthrow new Error(`Child ${child.index} is waiting for a supervisor reply. Asking now would deadlock. Reply to the child request first.`);\n\t\t}\n\t}\n\n\tif (hasBlockingSupervisorRequest(channelDir, status.runId, child.index)) {\n\t\tthrow new Error(\"Child is waiting for a supervisor reply. Reply to its request before asking a question.\");\n\t}\n\tconst capability = readSteerCapability(resolved.location.asyncDir, child.index);\n\tif (!capability?.supported) {\n\t\tthrow new Error(\"This child is not ready to receive questions. Continue other work until it is ready; no question was queued.\");\n\t}\n\tconst incarnation: SupervisorChildIncarnation = { pid: capability.pid, readyAt: capability.readyAt };\n\tconst question: SupervisorQuestion = createSupervisorQuestion({\n\t\tchannelDir,\n\t\treason,\n\t\tmessage,\n\t\trunId: status.runId,\n\t\tchildIndex: child.index,\n\t\tchildId: child.childId,\n\t\tparentSessionId: sessionId,\n\t\tparentGeneration: input.state.sessionGeneration ?? 0,\n\t\tchildIncarnation: incarnation,\n\t});\n\ttry {\n\t\tif (hasBlockingSupervisorRequest(channelDir, status.runId, child.index)) {\n\t\t\tthrow new Error(\"Child is waiting for a supervisor reply. Reply to its request before asking a question.\");\n\t\t}\n\t\trequestAsyncSteer(resolved.location.asyncDir, {\n\t\t\tmessage: formatParentQuestionForChild(question),\n\t\t\ttargetIndex: child.index,\n\t\t\tsource: \"supervisor-question\",\n\t\t\tid: question.id,\n\t\t});\n\t} catch (error) {\n\t\tcancelSupervisorQuestion(channelDir, question.id, \"failed to queue delivery to child\");\n\t\tthrow error instanceof Error ? error : new Error(String(error));\n\t}\n\treturn {\n\t\tcontent: [{ type: \"text\", text: `Question ${question.id} queued for async run ${status.runId} child ${child.index}. The child's answer is delivered separately from the run result.` }],\n\t\tdetails: {\n\t\t\tquestionId: question.id,\n\t\t\tstate: \"pending\",\n\t\t\trunId: status.runId,\n\t\t\tchildIndex: child.index,\n\t\t\tchildId: child.childId,\n\t\t\tdelivered: false,\n\t\t\tanswered: false,\n\t\t},\n\t};\n}\n"]}
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import { readSteerCapability, requestAsyncSteer } from "../runs/background/control-channel.js";
|
|
2
|
+
import { resolveSubagentRunId } from "../runs/background/run-id-resolver.js";
|
|
3
|
+
import { readStatus } from "../shared/utils.js";
|
|
4
|
+
import { cancelSupervisorQuestion, createSupervisorQuestion, formatParentQuestionForChild, expireSupervisorQuestion, hasOutstandingQuestionForChild, hasBlockingSupervisorRequest, incarnationMatches, readSupervisorQuestion, supervisorQuestionIsTerminal, resolveSupervisorChannelDir, } from "./supervisor-questions.js";
|
|
5
|
+
function runningSteps(status) {
|
|
6
|
+
return (status.steps ?? [])
|
|
7
|
+
.map((step, index) => ({
|
|
8
|
+
index,
|
|
9
|
+
childId: step.childId ?? step.agent,
|
|
10
|
+
agent: step.agent,
|
|
11
|
+
status: step.status,
|
|
12
|
+
}))
|
|
13
|
+
.filter((step) => step.status === "running")
|
|
14
|
+
.map((step) => ({ index: step.index, childId: step.childId, agent: step.agent }));
|
|
15
|
+
}
|
|
16
|
+
export function resolveAskChild(status, params) {
|
|
17
|
+
if (params.index !== undefined && (!Number.isInteger(params.index) || params.index < 0)) {
|
|
18
|
+
throw new Error("index must be a non-negative integer.");
|
|
19
|
+
}
|
|
20
|
+
const running = runningSteps(status);
|
|
21
|
+
if (params.childId?.trim()) {
|
|
22
|
+
const childId = params.childId.trim();
|
|
23
|
+
const matches = (status.steps ?? [])
|
|
24
|
+
.map((step, index) => ({ index, childId: step.childId ?? step.agent, agent: step.agent, status: step.status }))
|
|
25
|
+
.filter((step) => step.childId === childId);
|
|
26
|
+
if (matches.length === 0)
|
|
27
|
+
throw new Error(`Async run '${status.runId}' has no child '${childId}'.`);
|
|
28
|
+
if (matches.length > 1)
|
|
29
|
+
throw new Error(`Async run '${status.runId}' has multiple children named '${childId}'. Pass index.`);
|
|
30
|
+
const match = matches[0];
|
|
31
|
+
if (params.index !== undefined && params.index !== match.index) {
|
|
32
|
+
throw new Error(`Child '${childId}' is index ${match.index}, not ${params.index}.`);
|
|
33
|
+
}
|
|
34
|
+
if (match.status !== "running")
|
|
35
|
+
throw new Error(`Async run '${status.runId}' child ${match.index} is ${match.status} and cannot be asked.`);
|
|
36
|
+
return { index: match.index, childId: match.childId, agent: match.agent };
|
|
37
|
+
}
|
|
38
|
+
if (params.index !== undefined) {
|
|
39
|
+
const steps = status.steps ?? [];
|
|
40
|
+
if (params.index >= steps.length) {
|
|
41
|
+
throw new Error(`Async run '${status.runId}' has ${steps.length} children. Index ${params.index} is out of range.`);
|
|
42
|
+
}
|
|
43
|
+
const step = steps[params.index];
|
|
44
|
+
if (step.status !== "running")
|
|
45
|
+
throw new Error(`Async run '${status.runId}' child ${params.index} is ${step.status} and cannot be asked.`);
|
|
46
|
+
return { index: params.index, childId: step.childId ?? step.agent, agent: step.agent };
|
|
47
|
+
}
|
|
48
|
+
if (running.length === 1)
|
|
49
|
+
return running[0];
|
|
50
|
+
if (running.length === 0)
|
|
51
|
+
throw new Error(`Async run '${status.runId}' has no running child to ask.`);
|
|
52
|
+
throw new Error(`Async run '${status.runId}' has ${running.length} running children. Pass index or childId; broadcast asks are not supported.`);
|
|
53
|
+
}
|
|
54
|
+
function requestMatchesChild(request, runId, child) {
|
|
55
|
+
if (!request.expectsReply)
|
|
56
|
+
return false;
|
|
57
|
+
if (typeof request.runId !== "string" || request.runId !== runId)
|
|
58
|
+
return false;
|
|
59
|
+
const indexMatches = Number.isInteger(request.childIndex) && request.childIndex === child.index;
|
|
60
|
+
const idMatches = request.agent === child.childId
|
|
61
|
+
|| request.agent === child.agent
|
|
62
|
+
|| request.childTarget === child.childId;
|
|
63
|
+
return indexMatches && idMatches;
|
|
64
|
+
}
|
|
65
|
+
export function reconcileAsyncQuestion(channelDir, question, state) {
|
|
66
|
+
expireSupervisorQuestion(channelDir, question.id);
|
|
67
|
+
const current = readSupervisorQuestion(channelDir, question.id) ?? question;
|
|
68
|
+
if (supervisorQuestionIsTerminal(current))
|
|
69
|
+
return current;
|
|
70
|
+
const resolved = resolveSubagentRunId(current.runId, { state });
|
|
71
|
+
if (resolved?.kind !== "async" || !resolved.location.asyncDir)
|
|
72
|
+
return current;
|
|
73
|
+
const status = readStatus(resolved.location.asyncDir);
|
|
74
|
+
if (!status)
|
|
75
|
+
return current;
|
|
76
|
+
const step = status.steps?.[current.childIndex];
|
|
77
|
+
const capability = readSteerCapability(resolved.location.asyncDir, current.childIndex);
|
|
78
|
+
let reason;
|
|
79
|
+
if (status.sessionId !== current.parentSessionId)
|
|
80
|
+
reason = "async run ownership changed";
|
|
81
|
+
else if (status.state !== "running" || !step || step.status !== "running")
|
|
82
|
+
reason = "target child is no longer running";
|
|
83
|
+
else if ((step.childId ?? step.agent) !== current.childId)
|
|
84
|
+
reason = "target child identity changed";
|
|
85
|
+
else if (capability && !incarnationMatches(current.childIncarnation, capability))
|
|
86
|
+
reason = "target child process changed";
|
|
87
|
+
else if (capability && !capability.supported)
|
|
88
|
+
reason = "target child no longer accepts questions";
|
|
89
|
+
const delivery = status.steering?.recent.find((request) => request.id === current.id)?.targets.find((target) => target.index === current.childIndex);
|
|
90
|
+
if (delivery?.state === "failed" || delivery?.state === "late")
|
|
91
|
+
reason = delivery.reason ?? "question delivery failed";
|
|
92
|
+
return reason ? cancelSupervisorQuestion(channelDir, current.id, reason) ?? current : current;
|
|
93
|
+
}
|
|
94
|
+
export function askRunningAsyncChild(input) {
|
|
95
|
+
const runId = input.params.id?.trim();
|
|
96
|
+
if (!runId)
|
|
97
|
+
throw new Error("action='ask' requires id for the async run.");
|
|
98
|
+
const reason = input.params.reason?.trim();
|
|
99
|
+
const message = input.params.message?.trim();
|
|
100
|
+
if (!reason)
|
|
101
|
+
throw new Error("action='ask' requires reason naming the concrete decision the child's answer will change.");
|
|
102
|
+
if (!message)
|
|
103
|
+
throw new Error("action='ask' requires message.");
|
|
104
|
+
const sessionId = input.state.currentSessionId;
|
|
105
|
+
if (!sessionId)
|
|
106
|
+
throw new Error("action='ask' requires an active session identity.");
|
|
107
|
+
const resolved = resolveSubagentRunId(runId, { state: input.state });
|
|
108
|
+
if (!resolved)
|
|
109
|
+
throw new Error(`No async run matched '${runId}'.`);
|
|
110
|
+
if (resolved.kind !== "async")
|
|
111
|
+
throw new Error("action='ask' targets a running async child only. It does not revive, reassign, or broadcast.");
|
|
112
|
+
if (!resolved.location.asyncDir)
|
|
113
|
+
throw new Error(`Async run '${resolved.id}' has no live run directory.`);
|
|
114
|
+
const status = readStatus(resolved.location.asyncDir);
|
|
115
|
+
if (!status)
|
|
116
|
+
throw new Error(`Async run '${resolved.id}' has no status.`);
|
|
117
|
+
if (!status.sessionId || status.sessionId !== sessionId) {
|
|
118
|
+
throw new Error(`Async run '${resolved.id}' was not found in the active session.`);
|
|
119
|
+
}
|
|
120
|
+
if (status.state !== "running")
|
|
121
|
+
throw new Error(`Async run '${resolved.id}' is ${status.state} and cannot be asked.`);
|
|
122
|
+
const child = resolveAskChild(status, input.params);
|
|
123
|
+
const channelDir = resolveSupervisorChannelDir(status.runId, child.childId, child.index);
|
|
124
|
+
if (hasOutstandingQuestionForChild(channelDir, child.index, child.childId)) {
|
|
125
|
+
throw new Error(`A question is already outstanding for async run '${status.runId}' child ${child.index}. Wait for that answer or expiry before asking again.`);
|
|
126
|
+
}
|
|
127
|
+
for (const request of input.childRequests ?? []) {
|
|
128
|
+
if (requestMatchesChild(request, status.runId, child)) {
|
|
129
|
+
throw new Error(`Child ${child.index} is waiting for a supervisor reply. Asking now would deadlock. Reply to the child request first.`);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
if (hasBlockingSupervisorRequest(channelDir, status.runId, child.index)) {
|
|
133
|
+
throw new Error("Child is waiting for a supervisor reply. Reply to its request before asking a question.");
|
|
134
|
+
}
|
|
135
|
+
const capability = readSteerCapability(resolved.location.asyncDir, child.index);
|
|
136
|
+
if (!capability?.supported) {
|
|
137
|
+
throw new Error("This child is not ready to receive questions. Continue other work until it is ready; no question was queued.");
|
|
138
|
+
}
|
|
139
|
+
const incarnation = { pid: capability.pid, readyAt: capability.readyAt };
|
|
140
|
+
const question = createSupervisorQuestion({
|
|
141
|
+
channelDir,
|
|
142
|
+
reason,
|
|
143
|
+
message,
|
|
144
|
+
runId: status.runId,
|
|
145
|
+
childIndex: child.index,
|
|
146
|
+
childId: child.childId,
|
|
147
|
+
parentSessionId: sessionId,
|
|
148
|
+
parentGeneration: input.state.sessionGeneration ?? 0,
|
|
149
|
+
childIncarnation: incarnation,
|
|
150
|
+
});
|
|
151
|
+
try {
|
|
152
|
+
if (hasBlockingSupervisorRequest(channelDir, status.runId, child.index)) {
|
|
153
|
+
throw new Error("Child is waiting for a supervisor reply. Reply to its request before asking a question.");
|
|
154
|
+
}
|
|
155
|
+
requestAsyncSteer(resolved.location.asyncDir, {
|
|
156
|
+
message: formatParentQuestionForChild(question),
|
|
157
|
+
targetIndex: child.index,
|
|
158
|
+
source: "supervisor-question",
|
|
159
|
+
id: question.id,
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
catch (error) {
|
|
163
|
+
cancelSupervisorQuestion(channelDir, question.id, "failed to queue delivery to child");
|
|
164
|
+
throw error instanceof Error ? error : new Error(String(error));
|
|
165
|
+
}
|
|
166
|
+
return {
|
|
167
|
+
content: [{ type: "text", text: `Question ${question.id} queued for async run ${status.runId} child ${child.index}. The child's answer is delivered separately from the run result.` }],
|
|
168
|
+
details: {
|
|
169
|
+
questionId: question.id,
|
|
170
|
+
state: "pending",
|
|
171
|
+
runId: status.runId,
|
|
172
|
+
childIndex: child.index,
|
|
173
|
+
childId: child.childId,
|
|
174
|
+
delivered: false,
|
|
175
|
+
answered: false,
|
|
176
|
+
},
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
//# sourceMappingURL=supervisor-ask.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"supervisor-ask.js","sourceRoot":"","sources":["../../../../../src/builtin-extensions/pi-subagents/src/intercom/supervisor-ask.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,MAAM,uCAAuC,CAAC;AAC/F,OAAO,EAAE,oBAAoB,EAAE,MAAM,uCAAuC,CAAC;AAC7E,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAEhD,OAAO,EACN,wBAAwB,EACxB,wBAAwB,EACxB,4BAA4B,EAC5B,wBAAwB,EACxB,8BAA8B,EAC9B,4BAA4B,EAC5B,kBAAkB,EAClB,sBAAsB,EACtB,4BAA4B,EAC5B,2BAA2B,GAG3B,MAAM,2BAA2B,CAAC;AAkBnC,SAAS,YAAY,CAAC,MAAmB,EAA4D;IACpG,OAAO,CAAC,MAAM,CAAC,KAAK,IAAI,EAAE,CAAC;SACzB,GAAG,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC;QACtB,KAAK;QACL,OAAO,EAAE,IAAI,CAAC,OAAO,IAAI,IAAI,CAAC,KAAK;QACnC,KAAK,EAAE,IAAI,CAAC,KAAK;QACjB,MAAM,EAAE,IAAI,CAAC,MAAM;KACnB,CAAC,CAAC;SACF,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,MAAM,KAAK,SAAS,CAAC;SAC3C,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC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C;QACD,iBAAiB,CAAC,QAAQ,CAAC,QAAQ,CAAC,QAAQ,EAAE;YAC7C,OAAO,EAAE,4BAA4B,CAAC,QAAQ,CAAC;YAC/C,WAAW,EAAE,KAAK,CAAC,KAAK;YACxB,MAAM,EAAE,qBAAqB;YAC7B,EAAE,EAAE,QAAQ,CAAC,EAAE;SACf,CAAC,CAAC;IACJ,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QAChB,wBAAwB,CAAC,UAAU,EAAE,QAAQ,CAAC,EAAE,EAAE,mCAAmC,CAAC,CAAC;QACvF,MAAM,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC;IACjE,CAAC;IACD,OAAO;QACN,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,YAAY,QAAQ,CAAC,EAAE,yBAAyB,MAAM,CAAC,KAAK,UAAU,KAAK,CAAC,KAAK,mEAAmE,EAAE,CAAC;QACvL,OAAO,EAAE;YACR,UAAU,EAAE,QAAQ,CAAC,EAAE;YACvB,KAAK,EAAE,SAAS;YAChB,KAAK,EAAE,MAAM,CAAC,KAAK;YACnB,UAAU,EAAE,KAAK,CAAC,KAAK;YACvB,OAAO,EAAE,KAAK,CAAC,OAAO;YACtB,SAAS,EAAE,KAAK;YAChB,QAAQ,EAAE,KAAK;SACf;KACD,CAAC;AAAA,CACF","sourcesContent":["import type { AgentToolResult } from \"@ashx-j/lunr-agent\";\nimport { readSteerCapability, requestAsyncSteer } from \"../runs/background/control-channel.ts\";\nimport { resolveSubagentRunId } from \"../runs/background/run-id-resolver.ts\";\nimport { readStatus } from \"../shared/utils.ts\";\nimport type { AsyncStatus, SubagentState } from \"../shared/types.ts\";\nimport {\n\tcancelSupervisorQuestion,\n\tcreateSupervisorQuestion,\n\tformatParentQuestionForChild,\n\texpireSupervisorQuestion,\n\thasOutstandingQuestionForChild,\n\thasBlockingSupervisorRequest,\n\tincarnationMatches,\n\treadSupervisorQuestion,\n\tsupervisorQuestionIsTerminal,\n\tresolveSupervisorChannelDir,\n\ttype SupervisorChildIncarnation,\n\ttype SupervisorQuestion,\n} from \"./supervisor-questions.ts\";\n\nexport interface ParentAskParams {\n\tid?: string;\n\tindex?: number;\n\tchildId?: string;\n\treason?: string;\n\tmessage?: string;\n}\n\nexport interface ParentAskRequestFile {\n\texpectsReply?: boolean;\n\trunId?: string;\n\tchildIndex?: number;\n\tagent?: string;\n\tchildTarget?: string;\n}\n\nfunction runningSteps(status: AsyncStatus): Array<{ index: number; childId: string; agent: string }> {\n\treturn (status.steps ?? [])\n\t\t.map((step, index) => ({\n\t\t\tindex,\n\t\t\tchildId: step.childId ?? step.agent,\n\t\t\tagent: step.agent,\n\t\t\tstatus: step.status,\n\t\t}))\n\t\t.filter((step) => step.status === \"running\")\n\t\t.map((step) => ({ index: step.index, childId: step.childId, agent: step.agent }));\n}\n\nexport function resolveAskChild(\n\tstatus: AsyncStatus,\n\tparams: Pick<ParentAskParams, \"index\" | \"childId\">,\n): { index: number; childId: string; agent: string } {\n\tif (params.index !== undefined && (!Number.isInteger(params.index) || params.index < 0)) {\n\t\tthrow new Error(\"index must be a non-negative integer.\");\n\t}\n\tconst running = runningSteps(status);\n\tif (params.childId?.trim()) {\n\t\tconst childId = params.childId.trim();\n\t\tconst matches = (status.steps ?? [])\n\t\t\t.map((step, index) => ({ index, childId: step.childId ?? step.agent, agent: step.agent, status: step.status }))\n\t\t\t.filter((step) => step.childId === childId);\n\t\tif (matches.length === 0) throw new Error(`Async run '${status.runId}' has no child '${childId}'.`);\n\t\tif (matches.length > 1) throw new Error(`Async run '${status.runId}' has multiple children named '${childId}'. Pass index.`);\n\t\tconst match = matches[0]!;\n\t\tif (params.index !== undefined && params.index !== match.index) {\n\t\t\tthrow new Error(`Child '${childId}' is index ${match.index}, not ${params.index}.`);\n\t\t}\n\t\tif (match.status !== \"running\") throw new Error(`Async run '${status.runId}' child ${match.index} is ${match.status} and cannot be asked.`);\n\t\treturn { index: match.index, childId: match.childId, agent: match.agent };\n\t}\n\tif (params.index !== undefined) {\n\t\tconst steps = status.steps ?? [];\n\t\tif (params.index >= steps.length) {\n\t\t\tthrow new Error(`Async run '${status.runId}' has ${steps.length} children. Index ${params.index} is out of range.`);\n\t\t}\n\t\tconst step = steps[params.index]!;\n\t\tif (step.status !== \"running\") throw new Error(`Async run '${status.runId}' child ${params.index} is ${step.status} and cannot be asked.`);\n\t\treturn { index: params.index, childId: step.childId ?? step.agent, agent: step.agent };\n\t}\n\tif (running.length === 1) return running[0]!;\n\tif (running.length === 0) throw new Error(`Async run '${status.runId}' has no running child to ask.`);\n\tthrow new Error(`Async run '${status.runId}' has ${running.length} running children. Pass index or childId; broadcast asks are not supported.`);\n}\n\nfunction requestMatchesChild(request: ParentAskRequestFile, runId: string, child: { index: number; childId: string; agent: string }): boolean {\n\tif (!request.expectsReply) return false;\n\tif (typeof request.runId !== \"string\" || request.runId !== runId) return false;\n\tconst indexMatches = Number.isInteger(request.childIndex) && request.childIndex === child.index;\n\tconst idMatches = request.agent === child.childId\n\t\t|| request.agent === child.agent\n\t\t|| request.childTarget === child.childId;\n\treturn indexMatches && idMatches;\n}\n\nexport function reconcileAsyncQuestion(channelDir: string, question: SupervisorQuestion, state: SubagentState): SupervisorQuestion {\n\texpireSupervisorQuestion(channelDir, question.id);\n\tconst current = readSupervisorQuestion(channelDir, question.id) ?? question;\n\tif (supervisorQuestionIsTerminal(current)) return current;\n\tconst resolved = resolveSubagentRunId(current.runId, { state });\n\tif (resolved?.kind !== \"async\" || !resolved.location.asyncDir) return current;\n\tconst status = readStatus(resolved.location.asyncDir);\n\tif (!status) return current;\n\tconst step = status.steps?.[current.childIndex];\n\tconst capability = readSteerCapability(resolved.location.asyncDir, current.childIndex);\n\tlet reason: string | undefined;\n\tif (status.sessionId !== current.parentSessionId) reason = \"async run ownership changed\";\n\telse if (status.state !== \"running\" || !step || step.status !== \"running\") reason = \"target child is no longer running\";\n\telse if ((step.childId ?? step.agent) !== current.childId) reason = \"target child identity changed\";\n\telse if (capability && !incarnationMatches(current.childIncarnation, capability)) reason = \"target child process changed\";\n\telse if (capability && !capability.supported) reason = \"target child no longer accepts questions\";\n\tconst delivery = status.steering?.recent.find((request) => request.id === current.id)?.targets.find((target) => target.index === current.childIndex);\n\tif (delivery?.state === \"failed\" || delivery?.state === \"late\") reason = delivery.reason ?? \"question delivery failed\";\n\treturn reason ? cancelSupervisorQuestion(channelDir, current.id, reason) ?? current : current;\n}\n\nexport function askRunningAsyncChild(input: {\n\tparams: ParentAskParams;\n\tstate: SubagentState;\n\tchildRequests?: Iterable<ParentAskRequestFile>;\n}): AgentToolResult<Record<string, unknown>> {\n\tconst runId = input.params.id?.trim();\n\tif (!runId) throw new Error(\"action='ask' requires id for the async run.\");\n\tconst reason = input.params.reason?.trim();\n\tconst message = input.params.message?.trim();\n\tif (!reason) throw new Error(\"action='ask' requires reason naming the concrete decision the child's answer will change.\");\n\tif (!message) throw new Error(\"action='ask' requires message.\");\n\tconst sessionId = input.state.currentSessionId;\n\tif (!sessionId) throw new Error(\"action='ask' requires an active session identity.\");\n\n\tconst resolved = resolveSubagentRunId(runId, { state: input.state });\n\tif (!resolved) throw new Error(`No async run matched '${runId}'.`);\n\tif (resolved.kind !== \"async\") throw new Error(\"action='ask' targets a running async child only. It does not revive, reassign, or broadcast.\");\n\tif (!resolved.location.asyncDir) throw new Error(`Async run '${resolved.id}' has no live run directory.`);\n\n\tconst status = readStatus(resolved.location.asyncDir);\n\tif (!status) throw new Error(`Async run '${resolved.id}' has no status.`);\n\tif (!status.sessionId || status.sessionId !== sessionId) {\n\t\tthrow new Error(`Async run '${resolved.id}' was not found in the active session.`);\n\t}\n\tif (status.state !== \"running\") throw new Error(`Async run '${resolved.id}' is ${status.state} and cannot be asked.`);\n\n\tconst child = resolveAskChild(status, input.params);\n\tconst channelDir = resolveSupervisorChannelDir(status.runId, child.childId, child.index);\n\tif (hasOutstandingQuestionForChild(channelDir, child.index, child.childId)) {\n\t\tthrow new Error(`A question is already outstanding for async run '${status.runId}' child ${child.index}. Wait for that answer or expiry before asking again.`);\n\t}\n\tfor (const request of input.childRequests ?? []) {\n\t\tif (requestMatchesChild(request, status.runId, child)) {\n\t\t\tthrow new Error(`Child ${child.index} is waiting for a supervisor reply. Asking now would deadlock. Reply to the child request first.`);\n\t\t}\n\t}\n\n\tif (hasBlockingSupervisorRequest(channelDir, status.runId, child.index)) {\n\t\tthrow new Error(\"Child is waiting for a supervisor reply. Reply to its request before asking a question.\");\n\t}\n\tconst capability = readSteerCapability(resolved.location.asyncDir, child.index);\n\tif (!capability?.supported) {\n\t\tthrow new Error(\"This child is not ready to receive questions. Continue other work until it is ready; no question was queued.\");\n\t}\n\tconst incarnation: SupervisorChildIncarnation = { pid: capability.pid, readyAt: capability.readyAt };\n\tconst question: SupervisorQuestion = createSupervisorQuestion({\n\t\tchannelDir,\n\t\treason,\n\t\tmessage,\n\t\trunId: status.runId,\n\t\tchildIndex: child.index,\n\t\tchildId: child.childId,\n\t\tparentSessionId: sessionId,\n\t\tparentGeneration: input.state.sessionGeneration ?? 0,\n\t\tchildIncarnation: incarnation,\n\t});\n\ttry {\n\t\tif (hasBlockingSupervisorRequest(channelDir, status.runId, child.index)) {\n\t\t\tthrow new Error(\"Child is waiting for a supervisor reply. Reply to its request before asking a question.\");\n\t\t}\n\t\trequestAsyncSteer(resolved.location.asyncDir, {\n\t\t\tmessage: formatParentQuestionForChild(question),\n\t\t\ttargetIndex: child.index,\n\t\t\tsource: \"supervisor-question\",\n\t\t\tid: question.id,\n\t\t});\n\t} catch (error) {\n\t\tcancelSupervisorQuestion(channelDir, question.id, \"failed to queue delivery to child\");\n\t\tthrow error instanceof Error ? error : new Error(String(error));\n\t}\n\treturn {\n\t\tcontent: [{ type: \"text\", text: `Question ${question.id} queued for async run ${status.runId} child ${child.index}. The child's answer is delivered separately from the run result.` }],\n\t\tdetails: {\n\t\t\tquestionId: question.id,\n\t\t\tstate: \"pending\",\n\t\t\trunId: status.runId,\n\t\t\tchildIndex: child.index,\n\t\t\tchildId: child.childId,\n\t\t\tdelivered: false,\n\t\t\tanswered: false,\n\t\t},\n\t};\n}\n"]}
|