@agimon-ai/doompi-team 0.0.1-alpha.32 → 0.0.1-alpha.34
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/dist/env.cjs +1 -1
- package/dist/env.d.cts +2 -2
- package/dist/env.d.mts +2 -2
- package/dist/env.mjs +1 -1
- package/dist/src/adapters/pi/extensions/subagentPromptRuntime.cjs +11 -11
- package/dist/src/adapters/pi/extensions/subagentPromptRuntime.cjs.map +1 -1
- package/dist/src/adapters/pi/extensions/subagentPromptRuntime.d.cts.map +1 -1
- package/dist/src/adapters/pi/extensions/subagentPromptRuntime.d.mts.map +1 -1
- package/dist/src/adapters/pi/extensions/subagentPromptRuntime.mjs +11 -11
- package/dist/src/adapters/pi/extensions/subagentPromptRuntime.mjs.map +1 -1
- package/dist/src/adapters/pi/tui/register.cjs +1 -1
- package/dist/src/adapters/pi/tui/register.cjs.map +1 -1
- package/dist/src/adapters/pi/tui/register.mjs +1 -1
- package/dist/src/adapters/pi/tui/register.mjs.map +1 -1
- package/dist/src/adapters/runs/background/asyncExecution.cjs +1 -1
- package/dist/src/adapters/runs/background/asyncExecution.cjs.map +1 -1
- package/dist/src/adapters/runs/background/asyncExecution.mjs +1 -1
- package/dist/src/adapters/runs/background/asyncExecution.mjs.map +1 -1
- package/dist/src/adapters/runs/shared/piArgs.cjs +1 -1
- package/dist/src/adapters/runs/shared/piArgs.cjs.map +1 -1
- package/dist/src/adapters/runs/shared/piArgs.mjs +1 -1
- package/dist/src/adapters/runs/shared/piArgs.mjs.map +1 -1
- package/dist/src/types/environment.cjs +1 -1
- package/dist/src/types/environment.cjs.map +1 -1
- package/dist/src/types/environment.d.cts +1 -2
- package/dist/src/types/environment.d.cts.map +1 -1
- package/dist/src/types/environment.d.mts +1 -2
- package/dist/src/types/environment.d.mts.map +1 -1
- package/dist/src/types/environment.mjs +1 -1
- package/dist/src/types/environment.mjs.map +1 -1
- package/package.json +6 -5
package/dist/env.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./src/types/environment.cjs");let t=require("@agimon-ai/doompi-extension-contracts/child-process");exports.CHILD_TOOL_DIAGNOSTIC_PATH_ENV=e.CHILD_TOOL_DIAGNOSTIC_PATH_ENV,exports.DOOMPI_CHILD_EXTENSIONS_ENV=e.DOOMPI_CHILD_EXTENSIONS_ENV,exports.DOOMPI_SKILL_DIRS_ENV=e.DOOMPI_SKILL_DIRS_ENV,exports.EXTRA_AGENT_DIRS_ENV=e.EXTRA_AGENT_DIRS_ENV,exports.EXTRA_SKILL_DIRS_ENV=e.EXTRA_SKILL_DIRS_ENV,exports.INHERIT_PROJECT_CONTEXT_ENV=e.INHERIT_PROJECT_CONTEXT_ENV,exports.INHERIT_SKILLS_ENV=e.INHERIT_SKILLS_ENV,exports.MAX_SPAWNS_PER_SESSION_ENV=e.MAX_SPAWNS_PER_SESSION_ENV,exports.MCP_DIRECT_CHILD_TOOLS_ENV=e.MCP_DIRECT_CHILD_TOOLS_ENV,exports.MCP_DIRECT_TOOLS_ENV=e.MCP_DIRECT_TOOLS_ENV,exports.
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./src/types/environment.cjs");let t=require("@agimon-ai/doompi-extension-contracts/child-process");exports.CHILD_TOOL_DIAGNOSTIC_PATH_ENV=e.CHILD_TOOL_DIAGNOSTIC_PATH_ENV,exports.DOOMPI_CHILD_EXTENSIONS_ENV=e.DOOMPI_CHILD_EXTENSIONS_ENV,exports.DOOMPI_SKILL_DIRS_ENV=e.DOOMPI_SKILL_DIRS_ENV,exports.EXTRA_AGENT_DIRS_ENV=e.EXTRA_AGENT_DIRS_ENV,exports.EXTRA_SKILL_DIRS_ENV=e.EXTRA_SKILL_DIRS_ENV,exports.INHERIT_PROJECT_CONTEXT_ENV=e.INHERIT_PROJECT_CONTEXT_ENV,exports.INHERIT_SKILLS_ENV=e.INHERIT_SKILLS_ENV,exports.MAX_SPAWNS_PER_SESSION_ENV=e.MAX_SPAWNS_PER_SESSION_ENV,exports.MCP_DIRECT_CHILD_TOOLS_ENV=e.MCP_DIRECT_CHILD_TOOLS_ENV,exports.MCP_DIRECT_TOOLS_ENV=e.MCP_DIRECT_TOOLS_ENV,exports.PI_CODING_AGENT_PACKAGE_ROOT_ENV=e.PI_CODING_AGENT_PACKAGE_ROOT_ENV,exports.PI_INTERCOM_SESSION_ID_ENV=e.PI_INTERCOM_SESSION_ID_ENV,exports.PI_INTERCOM_STABLE_ID_ENV=e.PI_INTERCOM_STABLE_ID_ENV,exports.PI_RUNTIME_NAME=e.PI_RUNTIME_NAME,exports.PI_SUBAGENT_PI_BINARY_ENV=e.PI_SUBAGENT_PI_BINARY_ENV,exports.REQUIRED_CHILD_TOOLS_ENV=e.REQUIRED_CHILD_TOOLS_ENV,exports.STRUCTURED_OUTPUT_CAPTURE_ENV=e.STRUCTURED_OUTPUT_CAPTURE_ENV,exports.STRUCTURED_OUTPUT_SCHEMA_ENV=e.STRUCTURED_OUTPUT_SCHEMA_ENV,exports.SUBAGENT_CAPABILITY_CEILING_ENV=e.SUBAGENT_CAPABILITY_CEILING_ENV,exports.SUBAGENT_CHILD_AGENT_ENV=e.SUBAGENT_CHILD_AGENT_ENV,Object.defineProperty(exports,"SUBAGENT_CHILD_ENV",{enumerable:!0,get:function(){return t.SUBAGENT_CHILD_ENV}}),exports.SUBAGENT_CHILD_INDEX_ENV=e.SUBAGENT_CHILD_INDEX_ENV,exports.SUBAGENT_FANOUT_CHILD_ENV=e.SUBAGENT_FANOUT_CHILD_ENV,exports.SUBAGENT_INTERCOM_SESSION_NAME_ENV=e.SUBAGENT_INTERCOM_SESSION_NAME_ENV,exports.SUBAGENT_PARENT_CAPABILITY_TOKEN_ENV=e.SUBAGENT_PARENT_CAPABILITY_TOKEN_ENV,exports.SUBAGENT_PARENT_CHILD_INDEX_ENV=e.SUBAGENT_PARENT_CHILD_INDEX_ENV,exports.SUBAGENT_PARENT_CONTROL_INBOX_ENV=e.SUBAGENT_PARENT_CONTROL_INBOX_ENV,exports.SUBAGENT_PARENT_DEPTH_ENV=e.SUBAGENT_PARENT_DEPTH_ENV,exports.SUBAGENT_PARENT_EVENT_SINK_ENV=e.SUBAGENT_PARENT_EVENT_SINK_ENV,exports.SUBAGENT_PARENT_PATH_ENV=e.SUBAGENT_PARENT_PATH_ENV,exports.SUBAGENT_PARENT_ROOT_RUN_ID_ENV=e.SUBAGENT_PARENT_ROOT_RUN_ID_ENV,exports.SUBAGENT_PARENT_RUN_ID_ENV=e.SUBAGENT_PARENT_RUN_ID_ENV,Object.defineProperty(exports,"SUBAGENT_PARENT_SESSION_ENV",{enumerable:!0,get:function(){return t.SUBAGENT_PARENT_SESSION_ENV}}),exports.SUBAGENT_PROTECTED_PARENT_PIDS_ENV=e.SUBAGENT_PROTECTED_PARENT_PIDS_ENV,Object.defineProperty(exports,"SUBAGENT_ROOT_SESSION_ENV",{enumerable:!0,get:function(){return t.SUBAGENT_ROOT_SESSION_ENV}}),exports.SUBAGENT_RUN_ID_ENV=e.SUBAGENT_RUN_ID_ENV,exports.SUBAGENT_STEER_ACK_DIR_ENV=e.SUBAGENT_STEER_ACK_DIR_ENV,exports.SUBAGENT_STEER_CAPABILITY_ENV=e.SUBAGENT_STEER_CAPABILITY_ENV,exports.SUBAGENT_STEER_INBOX_ENV=e.SUBAGENT_STEER_INBOX_ENV,exports.SUBAGENT_TEAM_ID_ENV=e.SUBAGENT_TEAM_ID_ENV,exports.SUBAGENT_TEAM_MAIN_MEMBER_ENV=e.SUBAGENT_TEAM_MAIN_MEMBER_ENV,exports.SUBAGENT_TEAM_MEMBER_ID_ENV=e.SUBAGENT_TEAM_MEMBER_ID_ENV,exports.SUBAGENT_TEAM_MEMBER_TOKEN_ENV=e.SUBAGENT_TEAM_MEMBER_TOKEN_ENV,exports.SUBAGENT_TEAM_ROOT_SESSION_ENV=e.SUBAGENT_TEAM_ROOT_SESSION_ENV,exports.TOOL_BUDGET_ENV=e.TOOL_BUDGET_ENV,exports.TOOL_BUDGET_ZERO_AUTH_ENV=e.TOOL_BUDGET_ZERO_AUTH_ENV,exports.WORKTREE_BASE_DIR_ENV=e.WORKTREE_BASE_DIR_ENV,exports.decodeProtectedParentProcessIds=e.decodeProtectedParentProcessIds,exports.runtimeBinaryEnvVar=e.runtimeBinaryEnvVar;
|
package/dist/env.d.cts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { CHILD_TOOL_DIAGNOSTIC_PATH_ENV, DOOMPI_CHILD_EXTENSIONS_ENV, DOOMPI_SKILL_DIRS_ENV, EXTRA_AGENT_DIRS_ENV, EXTRA_SKILL_DIRS_ENV, INHERIT_PROJECT_CONTEXT_ENV, INHERIT_SKILLS_ENV, MAX_SPAWNS_PER_SESSION_ENV, MCP_DIRECT_CHILD_TOOLS_ENV, MCP_DIRECT_TOOLS_ENV,
|
|
2
|
-
export { CHILD_TOOL_DIAGNOSTIC_PATH_ENV, DOOMPI_CHILD_EXTENSIONS_ENV, DOOMPI_SKILL_DIRS_ENV, EXTRA_AGENT_DIRS_ENV, EXTRA_SKILL_DIRS_ENV, INHERIT_PROJECT_CONTEXT_ENV, INHERIT_SKILLS_ENV, MAX_SPAWNS_PER_SESSION_ENV, MCP_DIRECT_CHILD_TOOLS_ENV, MCP_DIRECT_TOOLS_ENV,
|
|
1
|
+
import { CHILD_TOOL_DIAGNOSTIC_PATH_ENV, DOOMPI_CHILD_EXTENSIONS_ENV, DOOMPI_SKILL_DIRS_ENV, EXTRA_AGENT_DIRS_ENV, EXTRA_SKILL_DIRS_ENV, INHERIT_PROJECT_CONTEXT_ENV, INHERIT_SKILLS_ENV, MAX_SPAWNS_PER_SESSION_ENV, MCP_DIRECT_CHILD_TOOLS_ENV, MCP_DIRECT_TOOLS_ENV, PI_CODING_AGENT_PACKAGE_ROOT_ENV, PI_INTERCOM_SESSION_ID_ENV, PI_INTERCOM_STABLE_ID_ENV, PI_RUNTIME_NAME, PI_SUBAGENT_PI_BINARY_ENV, REQUIRED_CHILD_TOOLS_ENV, STRUCTURED_OUTPUT_CAPTURE_ENV, STRUCTURED_OUTPUT_SCHEMA_ENV, SUBAGENT_CAPABILITY_CEILING_ENV, SUBAGENT_CHILD_AGENT_ENV, SUBAGENT_CHILD_ENV, SUBAGENT_CHILD_INDEX_ENV, SUBAGENT_FANOUT_CHILD_ENV, SUBAGENT_INTERCOM_SESSION_NAME_ENV, SUBAGENT_PARENT_CAPABILITY_TOKEN_ENV, SUBAGENT_PARENT_CHILD_INDEX_ENV, SUBAGENT_PARENT_CONTROL_INBOX_ENV, SUBAGENT_PARENT_DEPTH_ENV, SUBAGENT_PARENT_EVENT_SINK_ENV, SUBAGENT_PARENT_PATH_ENV, SUBAGENT_PARENT_ROOT_RUN_ID_ENV, SUBAGENT_PARENT_RUN_ID_ENV, SUBAGENT_PARENT_SESSION_ENV, SUBAGENT_PROTECTED_PARENT_PIDS_ENV, SUBAGENT_ROOT_SESSION_ENV, SUBAGENT_RUN_ID_ENV, SUBAGENT_STEER_ACK_DIR_ENV, SUBAGENT_STEER_CAPABILITY_ENV, SUBAGENT_STEER_INBOX_ENV, SUBAGENT_TEAM_ID_ENV, SUBAGENT_TEAM_MAIN_MEMBER_ENV, SUBAGENT_TEAM_MEMBER_ID_ENV, SUBAGENT_TEAM_MEMBER_TOKEN_ENV, SUBAGENT_TEAM_ROOT_SESSION_ENV, TOOL_BUDGET_ENV, TOOL_BUDGET_ZERO_AUTH_ENV, WORKTREE_BASE_DIR_ENV, decodeProtectedParentProcessIds, runtimeBinaryEnvVar } from "./src/types/environment.cjs";
|
|
2
|
+
export { CHILD_TOOL_DIAGNOSTIC_PATH_ENV, DOOMPI_CHILD_EXTENSIONS_ENV, DOOMPI_SKILL_DIRS_ENV, EXTRA_AGENT_DIRS_ENV, EXTRA_SKILL_DIRS_ENV, INHERIT_PROJECT_CONTEXT_ENV, INHERIT_SKILLS_ENV, MAX_SPAWNS_PER_SESSION_ENV, MCP_DIRECT_CHILD_TOOLS_ENV, MCP_DIRECT_TOOLS_ENV, PI_CODING_AGENT_PACKAGE_ROOT_ENV, PI_INTERCOM_SESSION_ID_ENV, PI_INTERCOM_STABLE_ID_ENV, PI_RUNTIME_NAME, PI_SUBAGENT_PI_BINARY_ENV, REQUIRED_CHILD_TOOLS_ENV, STRUCTURED_OUTPUT_CAPTURE_ENV, STRUCTURED_OUTPUT_SCHEMA_ENV, SUBAGENT_CAPABILITY_CEILING_ENV, SUBAGENT_CHILD_AGENT_ENV, SUBAGENT_CHILD_ENV, SUBAGENT_CHILD_INDEX_ENV, SUBAGENT_FANOUT_CHILD_ENV, SUBAGENT_INTERCOM_SESSION_NAME_ENV, SUBAGENT_PARENT_CAPABILITY_TOKEN_ENV, SUBAGENT_PARENT_CHILD_INDEX_ENV, SUBAGENT_PARENT_CONTROL_INBOX_ENV, SUBAGENT_PARENT_DEPTH_ENV, SUBAGENT_PARENT_EVENT_SINK_ENV, SUBAGENT_PARENT_PATH_ENV, SUBAGENT_PARENT_ROOT_RUN_ID_ENV, SUBAGENT_PARENT_RUN_ID_ENV, SUBAGENT_PARENT_SESSION_ENV, SUBAGENT_PROTECTED_PARENT_PIDS_ENV, SUBAGENT_ROOT_SESSION_ENV, SUBAGENT_RUN_ID_ENV, SUBAGENT_STEER_ACK_DIR_ENV, SUBAGENT_STEER_CAPABILITY_ENV, SUBAGENT_STEER_INBOX_ENV, SUBAGENT_TEAM_ID_ENV, SUBAGENT_TEAM_MAIN_MEMBER_ENV, SUBAGENT_TEAM_MEMBER_ID_ENV, SUBAGENT_TEAM_MEMBER_TOKEN_ENV, SUBAGENT_TEAM_ROOT_SESSION_ENV, TOOL_BUDGET_ENV, TOOL_BUDGET_ZERO_AUTH_ENV, WORKTREE_BASE_DIR_ENV, decodeProtectedParentProcessIds, runtimeBinaryEnvVar };
|
package/dist/env.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { CHILD_TOOL_DIAGNOSTIC_PATH_ENV, DOOMPI_CHILD_EXTENSIONS_ENV, DOOMPI_SKILL_DIRS_ENV, EXTRA_AGENT_DIRS_ENV, EXTRA_SKILL_DIRS_ENV, INHERIT_PROJECT_CONTEXT_ENV, INHERIT_SKILLS_ENV, MAX_SPAWNS_PER_SESSION_ENV, MCP_DIRECT_CHILD_TOOLS_ENV, MCP_DIRECT_TOOLS_ENV,
|
|
2
|
-
export { CHILD_TOOL_DIAGNOSTIC_PATH_ENV, DOOMPI_CHILD_EXTENSIONS_ENV, DOOMPI_SKILL_DIRS_ENV, EXTRA_AGENT_DIRS_ENV, EXTRA_SKILL_DIRS_ENV, INHERIT_PROJECT_CONTEXT_ENV, INHERIT_SKILLS_ENV, MAX_SPAWNS_PER_SESSION_ENV, MCP_DIRECT_CHILD_TOOLS_ENV, MCP_DIRECT_TOOLS_ENV,
|
|
1
|
+
import { CHILD_TOOL_DIAGNOSTIC_PATH_ENV, DOOMPI_CHILD_EXTENSIONS_ENV, DOOMPI_SKILL_DIRS_ENV, EXTRA_AGENT_DIRS_ENV, EXTRA_SKILL_DIRS_ENV, INHERIT_PROJECT_CONTEXT_ENV, INHERIT_SKILLS_ENV, MAX_SPAWNS_PER_SESSION_ENV, MCP_DIRECT_CHILD_TOOLS_ENV, MCP_DIRECT_TOOLS_ENV, PI_CODING_AGENT_PACKAGE_ROOT_ENV, PI_INTERCOM_SESSION_ID_ENV, PI_INTERCOM_STABLE_ID_ENV, PI_RUNTIME_NAME, PI_SUBAGENT_PI_BINARY_ENV, REQUIRED_CHILD_TOOLS_ENV, STRUCTURED_OUTPUT_CAPTURE_ENV, STRUCTURED_OUTPUT_SCHEMA_ENV, SUBAGENT_CAPABILITY_CEILING_ENV, SUBAGENT_CHILD_AGENT_ENV, SUBAGENT_CHILD_ENV, SUBAGENT_CHILD_INDEX_ENV, SUBAGENT_FANOUT_CHILD_ENV, SUBAGENT_INTERCOM_SESSION_NAME_ENV, SUBAGENT_PARENT_CAPABILITY_TOKEN_ENV, SUBAGENT_PARENT_CHILD_INDEX_ENV, SUBAGENT_PARENT_CONTROL_INBOX_ENV, SUBAGENT_PARENT_DEPTH_ENV, SUBAGENT_PARENT_EVENT_SINK_ENV, SUBAGENT_PARENT_PATH_ENV, SUBAGENT_PARENT_ROOT_RUN_ID_ENV, SUBAGENT_PARENT_RUN_ID_ENV, SUBAGENT_PARENT_SESSION_ENV, SUBAGENT_PROTECTED_PARENT_PIDS_ENV, SUBAGENT_ROOT_SESSION_ENV, SUBAGENT_RUN_ID_ENV, SUBAGENT_STEER_ACK_DIR_ENV, SUBAGENT_STEER_CAPABILITY_ENV, SUBAGENT_STEER_INBOX_ENV, SUBAGENT_TEAM_ID_ENV, SUBAGENT_TEAM_MAIN_MEMBER_ENV, SUBAGENT_TEAM_MEMBER_ID_ENV, SUBAGENT_TEAM_MEMBER_TOKEN_ENV, SUBAGENT_TEAM_ROOT_SESSION_ENV, TOOL_BUDGET_ENV, TOOL_BUDGET_ZERO_AUTH_ENV, WORKTREE_BASE_DIR_ENV, decodeProtectedParentProcessIds, runtimeBinaryEnvVar } from "./src/types/environment.mjs";
|
|
2
|
+
export { CHILD_TOOL_DIAGNOSTIC_PATH_ENV, DOOMPI_CHILD_EXTENSIONS_ENV, DOOMPI_SKILL_DIRS_ENV, EXTRA_AGENT_DIRS_ENV, EXTRA_SKILL_DIRS_ENV, INHERIT_PROJECT_CONTEXT_ENV, INHERIT_SKILLS_ENV, MAX_SPAWNS_PER_SESSION_ENV, MCP_DIRECT_CHILD_TOOLS_ENV, MCP_DIRECT_TOOLS_ENV, PI_CODING_AGENT_PACKAGE_ROOT_ENV, PI_INTERCOM_SESSION_ID_ENV, PI_INTERCOM_STABLE_ID_ENV, PI_RUNTIME_NAME, PI_SUBAGENT_PI_BINARY_ENV, REQUIRED_CHILD_TOOLS_ENV, STRUCTURED_OUTPUT_CAPTURE_ENV, STRUCTURED_OUTPUT_SCHEMA_ENV, SUBAGENT_CAPABILITY_CEILING_ENV, SUBAGENT_CHILD_AGENT_ENV, SUBAGENT_CHILD_ENV, SUBAGENT_CHILD_INDEX_ENV, SUBAGENT_FANOUT_CHILD_ENV, SUBAGENT_INTERCOM_SESSION_NAME_ENV, SUBAGENT_PARENT_CAPABILITY_TOKEN_ENV, SUBAGENT_PARENT_CHILD_INDEX_ENV, SUBAGENT_PARENT_CONTROL_INBOX_ENV, SUBAGENT_PARENT_DEPTH_ENV, SUBAGENT_PARENT_EVENT_SINK_ENV, SUBAGENT_PARENT_PATH_ENV, SUBAGENT_PARENT_ROOT_RUN_ID_ENV, SUBAGENT_PARENT_RUN_ID_ENV, SUBAGENT_PARENT_SESSION_ENV, SUBAGENT_PROTECTED_PARENT_PIDS_ENV, SUBAGENT_ROOT_SESSION_ENV, SUBAGENT_RUN_ID_ENV, SUBAGENT_STEER_ACK_DIR_ENV, SUBAGENT_STEER_CAPABILITY_ENV, SUBAGENT_STEER_INBOX_ENV, SUBAGENT_TEAM_ID_ENV, SUBAGENT_TEAM_MAIN_MEMBER_ENV, SUBAGENT_TEAM_MEMBER_ID_ENV, SUBAGENT_TEAM_MEMBER_TOKEN_ENV, SUBAGENT_TEAM_ROOT_SESSION_ENV, TOOL_BUDGET_ENV, TOOL_BUDGET_ZERO_AUTH_ENV, WORKTREE_BASE_DIR_ENV, decodeProtectedParentProcessIds, runtimeBinaryEnvVar };
|
package/dist/env.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{CHILD_TOOL_DIAGNOSTIC_PATH_ENV as e,DOOMPI_CHILD_EXTENSIONS_ENV as t,DOOMPI_SKILL_DIRS_ENV as n,EXTRA_AGENT_DIRS_ENV as r,EXTRA_SKILL_DIRS_ENV as i,INHERIT_PROJECT_CONTEXT_ENV as a,INHERIT_SKILLS_ENV as o,MAX_SPAWNS_PER_SESSION_ENV as s,MCP_DIRECT_CHILD_TOOLS_ENV as c,MCP_DIRECT_TOOLS_ENV as l,
|
|
1
|
+
import{CHILD_TOOL_DIAGNOSTIC_PATH_ENV as e,DOOMPI_CHILD_EXTENSIONS_ENV as t,DOOMPI_SKILL_DIRS_ENV as n,EXTRA_AGENT_DIRS_ENV as r,EXTRA_SKILL_DIRS_ENV as i,INHERIT_PROJECT_CONTEXT_ENV as a,INHERIT_SKILLS_ENV as o,MAX_SPAWNS_PER_SESSION_ENV as s,MCP_DIRECT_CHILD_TOOLS_ENV as c,MCP_DIRECT_TOOLS_ENV as l,PI_CODING_AGENT_PACKAGE_ROOT_ENV as u,PI_INTERCOM_SESSION_ID_ENV as d,PI_INTERCOM_STABLE_ID_ENV as f,PI_RUNTIME_NAME as p,PI_SUBAGENT_PI_BINARY_ENV as m,REQUIRED_CHILD_TOOLS_ENV as h,STRUCTURED_OUTPUT_CAPTURE_ENV as g,STRUCTURED_OUTPUT_SCHEMA_ENV as _,SUBAGENT_CAPABILITY_CEILING_ENV as v,SUBAGENT_CHILD_AGENT_ENV as y,SUBAGENT_CHILD_ENV as b,SUBAGENT_CHILD_INDEX_ENV as x,SUBAGENT_FANOUT_CHILD_ENV as S,SUBAGENT_INTERCOM_SESSION_NAME_ENV as C,SUBAGENT_PARENT_CAPABILITY_TOKEN_ENV as w,SUBAGENT_PARENT_CHILD_INDEX_ENV as T,SUBAGENT_PARENT_CONTROL_INBOX_ENV as E,SUBAGENT_PARENT_DEPTH_ENV as D,SUBAGENT_PARENT_EVENT_SINK_ENV as O,SUBAGENT_PARENT_PATH_ENV as k,SUBAGENT_PARENT_ROOT_RUN_ID_ENV as A,SUBAGENT_PARENT_RUN_ID_ENV as j,SUBAGENT_PARENT_SESSION_ENV as M,SUBAGENT_PROTECTED_PARENT_PIDS_ENV as N,SUBAGENT_ROOT_SESSION_ENV as P,SUBAGENT_RUN_ID_ENV as F,SUBAGENT_STEER_ACK_DIR_ENV as I,SUBAGENT_STEER_CAPABILITY_ENV as L,SUBAGENT_STEER_INBOX_ENV as R,SUBAGENT_TEAM_ID_ENV as z,SUBAGENT_TEAM_MAIN_MEMBER_ENV as B,SUBAGENT_TEAM_MEMBER_ID_ENV as V,SUBAGENT_TEAM_MEMBER_TOKEN_ENV as H,SUBAGENT_TEAM_ROOT_SESSION_ENV as U,TOOL_BUDGET_ENV as W,TOOL_BUDGET_ZERO_AUTH_ENV as G,WORKTREE_BASE_DIR_ENV as K,decodeProtectedParentProcessIds as q,init_environment as J,runtimeBinaryEnvVar as Y}from"./src/types/environment.mjs";J(),J();export{e as CHILD_TOOL_DIAGNOSTIC_PATH_ENV,t as DOOMPI_CHILD_EXTENSIONS_ENV,n as DOOMPI_SKILL_DIRS_ENV,r as EXTRA_AGENT_DIRS_ENV,i as EXTRA_SKILL_DIRS_ENV,a as INHERIT_PROJECT_CONTEXT_ENV,o as INHERIT_SKILLS_ENV,s as MAX_SPAWNS_PER_SESSION_ENV,c as MCP_DIRECT_CHILD_TOOLS_ENV,l as MCP_DIRECT_TOOLS_ENV,u as PI_CODING_AGENT_PACKAGE_ROOT_ENV,d as PI_INTERCOM_SESSION_ID_ENV,f as PI_INTERCOM_STABLE_ID_ENV,p as PI_RUNTIME_NAME,m as PI_SUBAGENT_PI_BINARY_ENV,h as REQUIRED_CHILD_TOOLS_ENV,g as STRUCTURED_OUTPUT_CAPTURE_ENV,_ as STRUCTURED_OUTPUT_SCHEMA_ENV,v as SUBAGENT_CAPABILITY_CEILING_ENV,y as SUBAGENT_CHILD_AGENT_ENV,b as SUBAGENT_CHILD_ENV,x as SUBAGENT_CHILD_INDEX_ENV,S as SUBAGENT_FANOUT_CHILD_ENV,C as SUBAGENT_INTERCOM_SESSION_NAME_ENV,w as SUBAGENT_PARENT_CAPABILITY_TOKEN_ENV,T as SUBAGENT_PARENT_CHILD_INDEX_ENV,E as SUBAGENT_PARENT_CONTROL_INBOX_ENV,D as SUBAGENT_PARENT_DEPTH_ENV,O as SUBAGENT_PARENT_EVENT_SINK_ENV,k as SUBAGENT_PARENT_PATH_ENV,A as SUBAGENT_PARENT_ROOT_RUN_ID_ENV,j as SUBAGENT_PARENT_RUN_ID_ENV,M as SUBAGENT_PARENT_SESSION_ENV,N as SUBAGENT_PROTECTED_PARENT_PIDS_ENV,P as SUBAGENT_ROOT_SESSION_ENV,F as SUBAGENT_RUN_ID_ENV,I as SUBAGENT_STEER_ACK_DIR_ENV,L as SUBAGENT_STEER_CAPABILITY_ENV,R as SUBAGENT_STEER_INBOX_ENV,z as SUBAGENT_TEAM_ID_ENV,B as SUBAGENT_TEAM_MAIN_MEMBER_ENV,V as SUBAGENT_TEAM_MEMBER_ID_ENV,H as SUBAGENT_TEAM_MEMBER_TOKEN_ENV,U as SUBAGENT_TEAM_ROOT_SESSION_ENV,W as TOOL_BUDGET_ENV,G as TOOL_BUDGET_ZERO_AUTH_ENV,K as WORKTREE_BASE_DIR_ENV,q as decodeProtectedParentProcessIds,Y as runtimeBinaryEnvVar};
|
|
2
2
|
//# sourceMappingURL=env.mjs.map
|
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
const e=require("../../../../_virtual/_rolldown/runtime.cjs"),t=require("../../../types/environment.cjs"),n=require("../../filesystem/configDir.cjs"),r=require("../../filesystem/paths.cjs"),i=require("../../intercom/nativeTeamChannel.cjs"),a=require("../../intercom/supervisorControlChannel.cjs"),o=require("../../runs/shared/toolBudget.cjs"),s=require("../promptRuntime.cjs"),c=require("../../runs/shared/structuredOutput.cjs"),l=require("../../runs/shared/toolAvailability.cjs"),u=require("../../process/childTranscript.cjs");let d=require("node:fs");d=e.__toESM(d,1);let f=require("node:path");f=e.__toESM(f,1);let p=require("@agimon-ai/doompi-extension-contracts/cordis-host")
|
|
2
|
-
`),
|
|
3
|
-
`),
|
|
4
|
-
`),
|
|
5
|
-
`);function
|
|
6
|
-
`).trim();if(r)return r}return``}function
|
|
1
|
+
const e=require("../../../../_virtual/_rolldown/runtime.cjs"),t=require("../../../types/environment.cjs"),n=require("../../filesystem/configDir.cjs"),r=require("../../filesystem/paths.cjs"),i=require("../../intercom/nativeTeamChannel.cjs"),a=require("../../intercom/supervisorControlChannel.cjs"),o=require("../../runs/shared/toolBudget.cjs"),s=require("../promptRuntime.cjs"),c=require("../../runs/shared/structuredOutput.cjs"),l=require("../../runs/shared/toolAvailability.cjs"),u=require("../../process/childTranscript.cjs");let d=require("node:fs");d=e.__toESM(d,1);let f=require("node:path");f=e.__toESM(f,1);let p=require("@agimon-ai/doompi-extension-contracts/cordis-host");const m=/\bkill(?:pg)?\b/i,h=/(?:^|[^\w.-])(?:pkill|killall|shutdown|reboot|poweroff|halt)(?=$|[^\w.-])/i,g=/\b(?:tmux|cmux)\b[\s\S]*\b(?:kill-server|kill-session|close|quit)\b/i,_=/\$(?:PPID|\{PPID\})|\bprocess\.ppid\b|\bgetppid\s*\(|\bppid\b/i,v=/\$\(|`|\$(?:\{[^}]+\}|[A-Za-z_][A-Za-z0-9_]*)/,y=/(?:^|[\s"'`])-1(?=$|[\s"'`;|&])/,b=`Blocked: subagents may use Bash, but cannot signal parent or workflow processes. Ask the parent to perform that process cleanup.`,x=`@agimon-ai/doompi-team/prompt-runtime`;function S(){return{steerNudgeFailures:0,watchErrors:0,watchCloseFailures:0}}const C=[`This subagent step has a strict structured output contract.`,"Your final action must be to call the `structured_output` tool with JSON matching the provided schema.","Do not rely on prose-only completion; if you do not call `structured_output`, the parent will fail this step."].join(`
|
|
2
|
+
`),w=[`When the assigned task includes a parent context pack, treat it as the authoritative starting point.`,`That pack satisfies generic instructions to explore or understand repository context first.`,`Read its listed paths directly before broad discovery, and do not re-derive established facts unless direct evidence contradicts them.`,`Do not begin with repository-wide listing, find, or grep. Expand only after consuming the pack and naming a concrete missing dependency or invalid path; search narrowly for that item and state why.`].join(`
|
|
3
|
+
`),T=[`You are a child subagent, not the parent orchestrator.`,`The parent session owns delegation, orchestration, review fanout, and follow-up worker launches.`,`Ignore prior parent-only orchestration instructions in inherited conversation history.`,`Do not propose or run subagents. Complete only your assigned role-specific task with the tools available to you.`,`If you need to edit files, use the available editing tools. Do not print tool-call syntax, patches, or pseudo-tool calls as text.`,w].join(`
|
|
4
|
+
`),E=[`You are a child subagent with explicit fanout responsibility for this assigned task.`,`The parent session owns final orchestration, acceptance, and follow-up implementation launches.`,"You may use the `subagent` tool only for the fanout work explicitly requested in this task.",`Do not broaden yourself into general parent orchestration. Do not launch follow-up workers unless the task explicitly asks for that.`,`The maxSubagentDepth cap still applies and may block further fanout.`,`If you need to edit files, use the available editing tools. Do not print tool-call syntax, patches, or pseudo-tool calls as text.`,w].join(`
|
|
5
|
+
`);function D(e,t,n){e.on.call(e,t,n)}function ee(e,t){return RegExp(`(?:^|\\D)-?${t}(?!\\d)`).test(e)}function O(e,t){if(h.test(e)||g.test(e))return b;if(m.test(e))return _.test(e)||v.test(e)||y.test(e)||/\bxargs\s+(?:[^;&|\n]+\s+)?kill(?:pg)?\b/i.test(e)||t.some(t=>ee(e,t))?b:void 0}function k(e,n={}){let r=[...new Set(n.protectedProcessIds??[...t.decodeProtectedParentProcessIds(process.env.PI_SUBAGENT_PROTECTED_PARENT_PIDS),process.pid,process.ppid])].filter(e=>Number.isSafeInteger(e)&&e>1);D(e,`tool_call`,e=>{if(e.toolName!==`bash`||!e.input||typeof e.input!=`object`)return;let t=e.input.command;if(typeof t!=`string`)return;let n=O(t,r);return n?{block:!0,reason:n}:void 0})}function te(e){return typeof e==`object`&&!!e&&e.type===`text`&&typeof e.text==`string`}function A(e){for(let t=e.length-1;t>=0;--t){let n=e[t];if(n?.role!==`assistant`||!Array.isArray(n.content))continue;let r=n.content.filter(te).map(e=>e.text).join(`
|
|
6
|
+
`).trim();if(r)return r}return``}function j(e,n=s.createTeamPromptRuntime()){let r=process.env[t.SUBAGENT_RUN_ID_ENV]?.trim();if(!r)return;let{pollScheduler:a,bootstrap:o,execution:c,reporting:l}=n,d,f,p=0,m=new WeakSet;D(e,`session_start`,(t,n)=>{if(d)return;a.start();let s=n.sessionManager.getSessionFile(),u=s?l.recordSessionFile(s):void 0,f=o.bootstrap(r,u);f.teamContext&&Object.assign(process.env,i.nativeTeamMemberEnvironment(f.teamContext)),c.start(r,{onSteer:t=>{let n=e.sendUserMessage;if(!n){Z(t,`failed`,`Child Pi session does not support sendUserMessage steering.`);return}try{n(X(t),{deliverAs:`steer`}),Z(t,`delivered`,`Pi accepted the correlated steering input.`)}catch(e){throw Z(t,`failed`,e instanceof Error?e.message:String(e)),e}}}),d={teamContext:f.teamContext},c.setActivity(`working`)}),D(e,`agent_start`,()=>{d&&c.setActivity(`working`)}),D(e,`message_update`,e=>{if(!d||!e.message)return;let t=u.getMessageActivity(e.message);t&&c.setProgress({currentTool:t})}),D(e,`message_end`,e=>{if(!d||!e.message||typeof e.message!=`object`||m.has(e.message))return;m.add(e.message);let t=u.getMessageUsageTokens(e.message);t!==void 0&&(f=(f??0)+t,c.setProgress({tokens:f}))}),D(e,`tool_execution_start`,e=>{if(!d)return;let t=e.toolName??e.tool?.name;p+=1,c.setProgress({toolCount:p,...typeof t==`string`&&t.length>0?{currentTool:u.formatToolActivity(t,e.args)}:{}}),c.setActivity(t===`intercom`&&e.args?.action===`ask`?`waiting_for_reply`:`tool`)}),D(e,`tool_execution_end`,()=>{d&&(c.setProgress({currentTool:`working`}),c.setActivity(`working`))}),D(e,`agent_end`,e=>{if(!d)return;c.setActivity(`finalizing`);let t=A(e.messages);c.complete(!0,t)})}const ne=new Set([`subagent-orchestration-instructions`,`subagent-slash-result`,`subagent-slash-text-result`,`subagent-notify`,`subagent_control_notice`,`subagent-control`,`subagent-control-notice`]),M=/<name>\s*pi-subagents\s*<\/name>/,N=`
|
|
7
7
|
|
|
8
|
-
The following skills provide specialized instructions for specific tasks.`,
|
|
9
|
-
Current date:`;function
|
|
8
|
+
The following skills provide specialized instructions for specific tasks.`,P=`
|
|
9
|
+
Current date:`;function F(e){let t=process.env[e];if(t!==void 0)return t!==`0`}function I(){let e=process.env[t.REQUIRED_CHILD_TOOLS_ENV]?.trim();if(!e)return;let n=JSON.parse(e);if(!Array.isArray(n)||n.some(e=>typeof e!=`string`||!e))throw Error(`Invalid ${t.REQUIRED_CHILD_TOOLS_ENV} payload.`);return n}function L(){let e=process.env[t.MCP_DIRECT_CHILD_TOOLS_ENV]?.trim();if(e)try{let t=JSON.parse(e);return!Array.isArray(t)||t.some(e=>typeof e!=`string`||!e)?void 0:t}catch{return}}function R(e){let n=process.env[t.CHILD_TOOL_DIAGNOSTIC_PATH_ENV]?.trim(),r=I();if(!n||!r)return;let i=e.getAllTools().map(e=>e.name);return l.writeChildToolDiagnostic(n,r,i,process.env[t.SUBAGENT_CHILD_AGENT_ENV]?.trim(),L())}function z(e,t,n){let r=e.length;for(let i of n){let n=e.indexOf(i,t);n!==-1&&n<r&&(r=n)}return r}function B(e){let t=e.indexOf(`
|
|
10
10
|
|
|
11
11
|
# Project Context
|
|
12
12
|
|
|
13
13
|
Project-specific instructions and guidelines:
|
|
14
14
|
|
|
15
|
-
`);if(t===-1)return e;let n=
|
|
15
|
+
`);if(t===-1)return e;let n=z(e,t+68,[N,P]);return`${e.slice(0,t)}${e.slice(n)}`}function V(e){let t=e.indexOf(N);if(t===-1)return e;let n=z(e,t+75,[P]);return`${e.slice(0,t)}${e.slice(n)}`}function H(e){return e.replace(/\n{0,2}<skill\s+name=["']pi-subagents["'][^>]*>[\s\S]*?<\/skill>\n{0,2}/g,`
|
|
16
16
|
|
|
17
|
-
`).replace(/[ \t]*<skill>\s*[\s\S]*?<\/skill>\s*/g,e=>
|
|
18
|
-
`)}function Z(e,n,r){let i=process.env[t.SUBAGENT_STEER_ACK_DIR_ENV]?.trim(),o=Number(process.env[t.SUBAGENT_CHILD_INDEX_ENV]);!i||!Number.isInteger(o)||o<0||a.writeSteerAckAt(a.steerAckPathFromDir(i,e.id),{requestId:e.id,index:o,ts:Date.now(),state:n,message:r})}function
|
|
17
|
+
`).replace(/[ \t]*<skill>\s*[\s\S]*?<\/skill>\s*/g,e=>M.test(e)?``:e)}function U(e){let t=e;for(let e of[T,E,C])t=t.split(e).join(``);return t.replace(/^(?:[ \t]*\r?\n)+/,``)}function W(e,t){let n=e;return t.inheritProjectContext||(n=B(n)),t.inheritSkills||(n=V(n)),n=H(n),n=U(n),`${t.fanoutChild?E:T}${process.env.PI_SUBAGENT_STRUCTURED_OUTPUT_CAPTURE?`\n\n${C}`:``}\n\n${n}`}function G(e){let t=e;return t?.role!==`custom`||typeof t.customType!=`string`?!1:ne.has(t.customType)}function K(e){let t=e;return t?.role===`toolResult`&&t.toolName===`subagent`}function q(e){let t=e;return t?.type===`toolCall`&&t.name===`subagent`}function J(e){let t=e;if(t?.role!==`assistant`||!Array.isArray(t.content))return e;let n=t.content.filter(e=>!q(e));if(n.length===t.content.length)return e;if(n.length!==0)return{...t,content:n}}function Y(e){let n=process.env[t.SUBAGENT_FANOUT_CHILD_ENV]===`1`,r=!1,i=[];for(let t of e){if(G(t)||!n&&K(t)){r=!0;continue}let e=n?t:J(t);if(e===void 0){r=!0;continue}e!==t&&(r=!0),i.push(e)}return r?i:e}function X(e){return[`Mid-run steering from the parent orchestrator:`,``,e.message,``,`Incorporate this guidance at the next safe point. Do not restart the task unless the guidance explicitly asks you to.`].join(`
|
|
18
|
+
`)}function Z(e,n,r){let i=process.env[t.SUBAGENT_STEER_ACK_DIR_ENV]?.trim(),o=Number(process.env[t.SUBAGENT_CHILD_INDEX_ENV]);!i||!Number.isInteger(o)||o<0||a.writeSteerAckAt(a.steerAckPathFromDir(i,e.id),{requestId:e.id,index:o,ts:Date.now(),state:n,message:r})}function re(e,t,n){if(!t)return;let r=0,i=!1,a=e.sendUserMessage;D(e,`tool_call`,e=>{let s=typeof e.toolName==`string`?e.toolName:`tool`;if(r++,t.soft!==void 0&&r>=t.soft&&!i){i=!0;try{a?.(o.toolBudgetSoftNudge(t,r),{deliverAs:`steer`})}catch(e){n.steerNudgeFailures+=1,n.lastError=e}}if(o.shouldBlockToolForBudget(t,s,r))return{block:!0,reason:o.toolBudgetBlockedMessage(t,s,r)}})}function Q(e,r={}){let i=r.diagnostics??S(),o=process.env[t.SUBAGENT_STEER_INBOX_ENV]?.trim();if(!o)return;let s=process.env[t.SUBAGENT_STEER_CAPABILITY_ENV]?.trim(),c=process.env[t.SUBAGENT_STEER_ACK_DIR_ENV]?.trim(),l=e.sendUserMessage,u=Number(process.env[t.SUBAGENT_CHILD_INDEX_ENV]),f=new Map,p=!1,m=!1,h=!1,g=typeof l==`function`,_,v,y=(e,t,n)=>{!c||!Number.isInteger(u)||u<0||a.writeSteerAckAt(a.steerAckPathFromDir(c,e.id),{requestId:e.id,index:u,ts:Date.now(),state:t,message:n})},b=()=>{!s||!Number.isInteger(u)||u<0||a.writeSteerCapabilityAt(s,{index:u,pid:process.pid,readyAt:Date.now(),supported:g})},x=()=>{if(!(p||m)){m=!0;try{for(let e of a.claimSteerRequestsFromDir(o)){if(!g||typeof l!=`function`){y(e.request,`failed`,`Child Pi session does not support sendUserMessage steering.`),e.commit();continue}let t=X(e.request),n=f.get(t)??[];n.push(e.request.id),f.set(t,n);try{l(t,{deliverAs:`steer`}),e.commit()}catch(r){n.pop(),n.length===0&&f.delete(t),e.release(),y(e.request,`failed`,r instanceof Error?r.message:String(r))}}}finally{m=!1}}},C=e=>{if(p||!e||typeof e!=`object`)return;let t=e;if(t.source!==`extension`||t.streamingBehavior!==`steer`)return;let n=typeof t.text==`string`?t.text:typeof t.content==`string`?t.content:void 0;if(!n)return;let r=f.get(n),i=r?.shift();i&&(r?.length===0&&f.delete(n),y({type:`steer`,id:i,ts:Date.now(),message:n},`delivered`,`Pi accepted the correlated steering input.`))},w=()=>{if(!(h||p)){try{d.mkdirSync(o,{recursive:!0}),b()}catch{return}h=!0;try{_=(r.watch??d.watch)(n.resolveWatchPath(o,r.nativeRealpath),()=>x()),_.on(`error`,e=>{i.watchErrors+=1,i.lastError=e})}catch{_=void 0}v=setInterval(x,250),v.unref?.()}},T=()=>{w(),x()};D(e,`input`,C),D(e,`session_start`,()=>w());for(let t of[`message_start`,`message_update`,`message_end`,`tool_execution_start`,`tool_execution_end`,`turn_end`])D(e,t,T);D(e,`session_shutdown`,()=>{p=!0;try{_?.close()}catch(e){i.watchCloseFailures+=1,i.lastError=e}v&&clearInterval(v)})}function $(e,n,i=S()){r.adoptSessionScopeFromEnv(),k(n),Q(n,{diagnostics:i}),re(n,o.decodeToolBudgetEnv(process.env[t.TOOL_BUDGET_ENV],{allowZero:process.env[t.TOOL_BUDGET_ZERO_AUTH_ENV]===`1`}),i);let a=s.createTeamPromptRuntime();j(n,a),e.effect(()=>()=>{a.pollScheduler.stop(),a.terminalPersistence.dispose()},`${x}/runner`);let l=a.teamChannel,u;D(n,`session_start`,()=>{u?.dispose(),u=l.createRuntime(n),u.bindChildFromEnvironment()}),e.effect(()=>()=>{u?.dispose(),u=void 0},`${x}/channel`),D(n,`agent_start`,()=>{R(n)});let p=process.env[t.STRUCTURED_OUTPUT_CAPTURE_ENV],m=process.env[t.STRUCTURED_OUTPUT_SCHEMA_ENV];if(p&&m){let e=JSON.parse(d.readFileSync(m,`utf-8`)),t=c.createStructuredOutputToolParameters(e),r=new c.StructuredOutputValidator;n.registerTool.bind(n)({name:`structured_output`,label:`Structured Output`,description:`Submit the required final structured output for this subagent step. This terminates the step.`,parameters:t,async execute(t,n){let i=await r.validateValue(e,n.value);if(i.status===`invalid`)throw Error(`Structured output validation failed: ${i.message}`);return d.mkdirSync(f.dirname(p),{recursive:!0}),d.writeFileSync(p,JSON.stringify(n.value),{mode:384}),{content:[{type:`text`,text:`Structured output captured.`}],details:{path:p},terminate:!0}}})}D(n,`context`,e=>{let t=Y(e.messages);if(t!==e.messages)return{messages:t}}),D(n,`before_agent_start`,async e=>{let r=process.env[t.SUBAGENT_INTERCOM_SESSION_NAME_ENV]?.trim();r&&typeof n.setSessionName==`function`&&n.setSessionName(r);let i=F(t.INHERIT_PROJECT_CONTEXT_ENV),a=F(t.INHERIT_SKILLS_ENV),o=F(t.SUBAGENT_FANOUT_CHILD_ENV),s=e.systemPrompt;if((i!==void 0||a!==void 0||o!==void 0)&&(s=W(e.systemPrompt,{inheritProjectContext:i??!0,inheritSkills:a??!0,fanoutChild:o===!0})),s!==e.systemPrompt)return{systemPrompt:s}})}function ie(e,t){$(e,t.pi,t.diagnostics)}async function ae(e,t){let n=await(0,p.connectDoomCordisHost)(e,x),r=n.root.plugin(ie,{pi:e,...t?{diagnostics:t}:{}});try{await r}catch(e){throw await r.dispose(),await n.dispose(),e}let i;e.on(`session_shutdown`,()=>i??=(async()=>{try{await r.dispose()}finally{await n.dispose()}})())}exports.CHILD_CONTEXT_FIRST_INSTRUCTIONS=w,exports.CHILD_FANOUT_BOUNDARY_INSTRUCTIONS=E,exports.CHILD_SUBAGENT_BOUNDARY_INSTRUCTIONS=T,exports.createPromptRuntimeDiagnostics=S,exports.extractAssistantSummaryText=A,exports.formatSteerMessage=X,exports.installSubagentPromptRuntime=$,exports.parentProcessTerminationBlockReason=O,exports.registerParentProcessGuard=k,exports.registerRunnerLifecycle=j,exports.registerSteeringInbox=Q,exports.registerSubagentPromptRuntime=ae,exports.rewriteSubagentPrompt=W,exports.stripInheritedSkills=V,exports.stripParentOnlySubagentMessages=Y,exports.stripProjectContext=B,exports.stripSubagentOrchestrationSkill=H;
|
|
19
19
|
//# sourceMappingURL=subagentPromptRuntime.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"subagentPromptRuntime.cjs","names":["SUBAGENT_ROOT_SESSION_ENV","decodeProtectedParentProcessIds","createTeamPromptRuntime","SUBAGENT_RUN_ID_ENV","nativeTeamMemberEnvironment","getMessageActivity","getMessageUsageTokens","formatToolActivity","REQUIRED_CHILD_TOOLS_ENV","MCP_DIRECT_CHILD_TOOLS_ENV","CHILD_TOOL_DIAGNOSTIC_PATH_ENV","writeChildToolDiagnostic","SUBAGENT_CHILD_AGENT_ENV","SUBAGENT_FANOUT_CHILD_ENV","SUBAGENT_STEER_ACK_DIR_ENV","SUBAGENT_CHILD_INDEX_ENV","steerAckPathFromDir","toolBudgetSoftNudge","shouldBlockToolForBudget","toolBudgetBlockedMessage","SUBAGENT_STEER_INBOX_ENV","SUBAGENT_STEER_CAPABILITY_ENV","claimSteerRequestsFromDir","fs","resolveWatchPath","decodeToolBudgetEnv","TOOL_BUDGET_ENV","TOOL_BUDGET_ZERO_AUTH_ENV","STRUCTURED_OUTPUT_CAPTURE_ENV","STRUCTURED_OUTPUT_SCHEMA_ENV","createStructuredOutputToolParameters","StructuredOutputValidator","path","SUBAGENT_INTERCOM_SESSION_NAME_ENV","INHERIT_PROJECT_CONTEXT_ENV","INHERIT_SKILLS_ENV","connectDoomCordisHost"],"sources":["../../../../../src/adapters/pi/extensions/subagentPromptRuntime.ts"],"sourcesContent":["/**\n * The extension loaded INSIDE every spawned child: prompt rewriting,\n * mid-run steering delivery, the tool-call budget, native supervisor/team\n * messaging, and the `structured_output` tool.\n *\n * WHY THIS RUNS IN A DIFFERENT WORLD THAN EVERYTHING ELSE PORTED SO FAR:\n * Every other module in this package runs in the parent or the runner\n * process. This one is loaded BY the child's own Pi process\n * (`piArgs.ts`'s `resolveRuntimeExtensionPath` resolves it onto the\n * child's `--extension` args). The child's stdout IS its captured\n * transcript - a stray console write here does not go to a developer's\n * terminal, it becomes part of the child's output. Nothing in this file\n * writes to the console, ever; a failure that would have been\n * logged elsewhere is swallowed with a comment when there is no safe channel\n * to report it.\n *\n * FIX (claim-by-rename for the per-child steer inbox):\n * The predecessor's `registerSteeringInbox` called\n * `consumeSteerRequestsFromDir`, which deletes every queued request before\n * attempting delivery, then manually re-queued whatever it had not yet\n * attempted (`requests.slice(index + 1)`) if `sendUserMessage` threw\n * partway through a batch - but the request that was actually attempted\n * when the throw happened was already gone, lost the same way FIX 1 in\n * `control-channel.ts` was written to close for the runner-side steer\n * queue. This module's `flush()` uses `claimSteerRequestsFromDir` (already\n * exported from `control-channel.ts`, directory-agnostic) instead: each\n * request is claimed individually, and a failed `sendUserMessage` call\n * calls `release()` on that one claim so it is retried on the next flush,\n * while every OTHER claim in the same batch is still committed or released\n * independently. That is also a behavioural improvement over the\n * predecessor's `break`-on-first-failure, which abandoned the rest of a\n * batch rather than giving each message its own outcome - the same\n * per-item independence `ControlChannelWatcher.check()` already applies on\n * the runner side.\n *\n * Child runtimes keep the native team transport for lifecycle and result\n * delivery, but model-visible coordination tools are filtered by Team package\n * policy. They never register the root orchestration tool or a separate wait\n * alias.\n *\n * AVOID:\n * - Writing to the console. See the header above\n * - Reintroducing the predecessor's \"delete the whole batch, dispatch,\n * re-queue what failed\" shape for the steer inbox. See the FIX above\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { connectDoomCordisHost } from '@agimon-ai/doompi-extension-contracts/cordis-host';\nimport type { Context } from '@deepseek-ai/cordis';\nimport type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';\nimport {\n CHILD_TOOL_DIAGNOSTIC_PATH_ENV,\n decodeProtectedParentProcessIds,\n INHERIT_PROJECT_CONTEXT_ENV,\n INHERIT_SKILLS_ENV,\n MCP_DIRECT_CHILD_TOOLS_ENV,\n REQUIRED_CHILD_TOOLS_ENV,\n STRUCTURED_OUTPUT_CAPTURE_ENV,\n STRUCTURED_OUTPUT_SCHEMA_ENV,\n SUBAGENT_CHILD_AGENT_ENV,\n SUBAGENT_CHILD_INDEX_ENV,\n SUBAGENT_FANOUT_CHILD_ENV,\n SUBAGENT_INTERCOM_SESSION_NAME_ENV,\n SUBAGENT_PROTECTED_PARENT_PIDS_ENV,\n SUBAGENT_ROOT_SESSION_ENV,\n SUBAGENT_RUN_ID_ENV,\n SUBAGENT_STEER_ACK_DIR_ENV,\n SUBAGENT_STEER_CAPABILITY_ENV,\n SUBAGENT_STEER_INBOX_ENV,\n TOOL_BUDGET_ENV,\n TOOL_BUDGET_ZERO_AUTH_ENV,\n} from '../../../types/environment';\nimport { createTeamPromptRuntime } from '../promptRuntime';\nimport {\n NATIVE_TEAM_TOOL_NAME,\n nativeTeamMemberEnvironment,\n type TeamMemberContext,\n} from '../../intercom/nativeTeamChannel';\nimport {\n claimSteerRequestsFromDir,\n type SteerRequest,\n steerAckPathFromDir,\n writeSteerAckAt,\n writeSteerCapabilityAt,\n} from '../../intercom/supervisorControlChannel';\nimport type { RunnerBootstrapContract } from '../../runs/background/runnerBootstrap';\nimport type { RunnerExecutionContract } from '../../runs/background/runnerExecution';\nimport type { RunnerReportingContract } from '../../runs/background/runnerReporting';\nimport { createStructuredOutputToolParameters, StructuredOutputValidator } from '../../runs/shared/structuredOutput';\nimport { type ChildToolDiagnostic, writeChildToolDiagnostic } from '../../runs/shared/toolAvailability';\nimport type { ResolvedToolBudget } from '../../runs/shared/toolBudget';\nimport {\n decodeToolBudgetEnv,\n shouldBlockToolForBudget,\n toolBudgetBlockedMessage,\n toolBudgetSoftNudge,\n} from '../../runs/shared/toolBudget';\nimport {\n type ChildTranscriptMessage,\n formatToolActivity,\n getMessageActivity,\n getMessageUsageTokens,\n} from '../../process/childTranscript';\nimport { resolveWatchPath } from '../../filesystem/configDir';\nimport { adoptSessionScopeFromEnv } from '../../filesystem/paths';\nimport type { PollSchedulerContract } from '../../pollScheduler';\nimport type { JsonSchemaObject } from '../../../types';\n\nconst STEER_FLUSH_POLL_INTERVAL_MS = 250;\nconst PROCESS_SIGNAL_COMMAND_PATTERN = /\\bkill(?:pg)?\\b/i;\nconst BROAD_PROCESS_TERMINATION_PATTERN = /(?:^|[^\\w.-])(?:pkill|killall|shutdown|reboot|poweroff|halt)(?=$|[^\\w.-])/i;\nconst WORKFLOW_TERMINAL_TERMINATION_PATTERN = /\\b(?:tmux|cmux)\\b[\\s\\S]*\\b(?:kill-server|kill-session|close|quit)\\b/i;\nconst PARENT_PID_REFERENCE_PATTERN = /\\$(?:PPID|\\{PPID\\})|\\bprocess\\.ppid\\b|\\bgetppid\\s*\\(|\\bppid\\b/i;\nconst DYNAMIC_PROCESS_TARGET_PATTERN = /\\$\\(|`|\\$(?:\\{[^}]+\\}|[A-Za-z_][A-Za-z0-9_]*)/;\nconst ALL_PROCESSES_KILL_TARGET_PATTERN = /(?:^|[\\s\"'`])-1(?=$|[\\s\"'`;|&])/;\nconst PARENT_PROCESS_BLOCK_REASON =\n 'Blocked: subagents may use Bash, but cannot signal parent or workflow processes. Ask the parent to perform that process cleanup.';\nconst PROMPT_CACHE_ROUTING_APIS = new Set(['openai-responses', 'azure-openai-responses', 'openai-codex-responses']);\nconst PROMPT_RUNTIME_SOURCE = '@agimon-ai/doompi-team/prompt-runtime';\n\n/**\n * Routes equivalent children through their root session's provider cache key\n * without changing the child's own Pi session identity or any other request\n * property. Returning `undefined` preserves Pi's original payload.\n */\nexport function rewriteChildPromptCacheKey(\n payload: unknown,\n modelApi: unknown,\n environment: Readonly<Record<string, string | undefined>> = process.env,\n): Record<string, unknown> | undefined {\n if (typeof modelApi !== 'string' || !PROMPT_CACHE_ROUTING_APIS.has(modelApi)) return undefined;\n const rootSessionId = environment[SUBAGENT_ROOT_SESSION_ENV]?.trim();\n if (!rootSessionId || typeof payload !== 'object' || payload === null || Array.isArray(payload)) return undefined;\n\n const request = payload as Record<string, unknown>;\n const currentCacheKey = request.prompt_cache_key;\n if (typeof currentCacheKey !== 'string' || !currentCacheKey.trim()) return undefined;\n\n return { ...request, prompt_cache_key: rootSessionId };\n}\n\n/**\n * Failures this runtime absorbed rather than propagated.\n *\n * WHY RECORD RATHER THAN LOG:\n * This module runs inside the spawned child, where stdout IS the child's\n * captured transcript. Writing a diagnostic there would corrupt the very\n * output the run exists to produce, so nothing here may reach stdio. But a\n * discarded error is indistinguishable from one that never happened, and a\n * watcher that fails on every event looks exactly like a quiet inbox. These\n * counters are the compromise: cheap, bounded, and queryable by a caller that\n * wants to know whether the child's steering path was actually healthy.\n *\n * WHY THIS IS CALLER-OWNED, NOT MODULE STATE:\n * A module-level singleton here would be exactly the bug this package's \"no\n * module-level mutable state\" rule exists to prevent - see\n * `nativeTeamChannel.ts`'s header: \"a second session in the same process\n * cannot inherit the first one's [state]\". `registerSubagentPromptRuntime`\n * runs once per real child process, so a singleton would rarely matter in\n * production, but every test in this file registers multiple independent\n * runtimes in one process, and a shared singleton would leak counts between\n * them silently. `createPromptRuntimeDiagnostics()` hands each registration\n * its own object instead; the caller keeps the reference to read later, and\n * a fresh registration is what \"reset\" means - there is no shared state left\n * to reset.\n *\n * AVOID:\n * - Adding a `console.*` here, on any path, for any reason\n * - Treating a non-zero count as fatal; every one of these is a degraded-mode\n * path with a working fallback, which is why it was absorbed in the first place\n * - Reintroducing a module-level instance of this. See the header above\n */\nexport interface PromptRuntimeDiagnostics {\n /** Advisory tool-budget nudges that could not be delivered to the child. */\n steerNudgeFailures: number;\n /** Errors emitted by the steer-inbox watcher. The interval poll covers these. */\n watchErrors: number;\n /** Failures closing the watcher during shutdown. */\n watchCloseFailures: number;\n /** The most recent absorbed failure, whichever kind it was. */\n lastError?: unknown;\n}\n\n/** A fresh, zeroed diagnostics object for one registration. See the interface doc for why this is not a singleton. */\nexport function createPromptRuntimeDiagnostics(): PromptRuntimeDiagnostics {\n return { steerNudgeFailures: 0, watchErrors: 0, watchCloseFailures: 0 };\n}\n\nconst STRUCTURED_OUTPUT_INSTRUCTIONS = [\n 'This subagent step has a strict structured output contract.',\n 'Your final action must be to call the `structured_output` tool with JSON matching the provided schema.',\n 'Do not rely on prose-only completion; if you do not call `structured_output`, the parent will fail this step.',\n].join('\\n');\n\nexport const CHILD_CONTEXT_FIRST_INSTRUCTIONS = [\n 'When the assigned task includes a parent context pack, treat it as the authoritative starting point.',\n 'That pack satisfies generic instructions to explore or understand repository context first.',\n 'Read its listed paths directly before broad discovery, and do not re-derive established facts unless direct evidence contradicts them.',\n 'Do not begin with repository-wide listing, find, or grep. Expand only after consuming the pack and naming a concrete missing dependency or invalid path; search narrowly for that item and state why.',\n].join('\\n');\n\nexport const CHILD_SUBAGENT_BOUNDARY_INSTRUCTIONS = [\n 'You are a child subagent, not the parent orchestrator.',\n 'The parent session owns delegation, orchestration, review fanout, and follow-up worker launches.',\n 'Ignore prior parent-only orchestration instructions in inherited conversation history.',\n 'Do not propose or run subagents. Complete only your assigned role-specific task with the tools available to you.',\n 'If you need to edit files, use the available editing tools. Do not print tool-call syntax, patches, or pseudo-tool calls as text.',\n CHILD_CONTEXT_FIRST_INSTRUCTIONS,\n].join('\\n');\n\nexport const CHILD_FANOUT_BOUNDARY_INSTRUCTIONS = [\n 'You are a child subagent with explicit fanout responsibility for this assigned task.',\n 'The parent session owns final orchestration, acceptance, and follow-up implementation launches.',\n 'You may use the `subagent` tool only for the fanout work explicitly requested in this task.',\n 'Do not broaden yourself into general parent orchestration. Do not launch follow-up workers unless the task explicitly asks for that.',\n 'The maxSubagentDepth cap still applies and may block further fanout.',\n 'If you need to edit files, use the available editing tools. Do not print tool-call syntax, patches, or pseudo-tool calls as text.',\n CHILD_CONTEXT_FIRST_INSTRUCTIONS,\n].join('\\n');\n\n/**\n * `pi.on` typed loosely: the extension API's event payloads are not typed\n * per event name, so every call site narrows its own handler's parameter.\n * `.call(pi, ...)` binds `this` explicitly rather than extracting `pi.on` as\n * a bare reference, which is what an unbound method call would otherwise risk.\n *\n * The handler is given `ctx: ExtensionContext` as a second parameter,\n * matching the real `pi.on` signature (`ExtensionHandler<E, R> = (event: E,\n * ctx: ExtensionContext) => ...`) even though most registrations here never\n * read it - existing single-parameter handlers stay valid without change\n * (JS ignores a callback's unused trailing parameters), and the one call\n * site that DOES need it (`session_start`, for `ctx.sessionManager` - see\n * `registerDeliverableGuardCheck`'s doc) no longer has to reach past this\n * wrapper to get it.\n */\nfunction onEvent<E = unknown>(\n pi: ExtensionAPI,\n event: string,\n handler: (event: E, ctx: ExtensionContext) => unknown,\n): void {\n (pi.on as unknown as (event: string, handler: (event: E, ctx: ExtensionContext) => unknown) => void).call(\n pi,\n event,\n handler,\n );\n}\n\nfunction commandMentionsProcessId(command: string, pid: number): boolean {\n return new RegExp(`(?:^|\\\\D)-?${pid}(?!\\\\d)`).test(command);\n}\n\n/**\n * Return the blocking reason only when Bash could reach workflow-owned\n * processes. Literal signals to another PID remain available for child-owned\n * cleanup; name-wide selectors and dynamic parent lookup fail closed because\n * their target set cannot be proven not to include the parent.\n */\nexport function parentProcessTerminationBlockReason(\n command: string,\n protectedProcessIds: readonly number[],\n): string | undefined {\n if (BROAD_PROCESS_TERMINATION_PATTERN.test(command) || WORKFLOW_TERMINAL_TERMINATION_PATTERN.test(command)) {\n return PARENT_PROCESS_BLOCK_REASON;\n }\n if (!PROCESS_SIGNAL_COMMAND_PATTERN.test(command)) return undefined;\n if (\n PARENT_PID_REFERENCE_PATTERN.test(command) ||\n DYNAMIC_PROCESS_TARGET_PATTERN.test(command) ||\n ALL_PROCESSES_KILL_TARGET_PATTERN.test(command) ||\n /\\bxargs\\s+(?:[^;&|\\n]+\\s+)?kill(?:pg)?\\b/i.test(command)\n ) {\n return PARENT_PROCESS_BLOCK_REASON;\n }\n return protectedProcessIds.some((pid) => commandMentionsProcessId(command, pid))\n ? PARENT_PROCESS_BLOCK_REASON\n : undefined;\n}\n\nexport function registerParentProcessGuard(\n pi: ExtensionAPI,\n options: { protectedProcessIds?: readonly number[] } = {},\n): void {\n const protectedProcessIds = [\n ...new Set(\n options.protectedProcessIds ?? [\n ...decodeProtectedParentProcessIds(process.env[SUBAGENT_PROTECTED_PARENT_PIDS_ENV]),\n process.pid,\n process.ppid,\n ],\n ),\n ].filter((pid) => Number.isSafeInteger(pid) && pid > 1);\n\n onEvent<{ toolName?: unknown; input?: unknown }>(pi, 'tool_call', (event) => {\n if (event.toolName !== 'bash' || !event.input || typeof event.input !== 'object') return undefined;\n const command = (event.input as { command?: unknown }).command;\n if (typeof command !== 'string') return undefined;\n const reason = parentProcessTerminationBlockReason(command, protectedProcessIds);\n return reason ? { block: true, reason } : undefined;\n });\n}\n\n/** A text block from an assistant message's content array. Narrowed structurally, not imported from `@earendil-works/pi-ai`, matching this file's habit of ad-hoc event-payload types (see `onEvent`'s own doc). */\ninterface AssistantTextBlock {\n type: 'text';\n text: string;\n}\n\n/** The subset of `AgentEndEvent`/message shape this file actually reads. */\ninterface DeliverableCheckMessage {\n role?: string;\n content?: unknown;\n}\n\nfunction isAssistantTextBlock(block: unknown): block is AssistantTextBlock {\n return (\n typeof block === 'object' &&\n block !== null &&\n (block as { type?: unknown }).type === 'text' &&\n typeof (block as { text?: unknown }).text === 'string'\n );\n}\n\n/**\n * The last non-empty assistant text found in `messages`, or `''`.\n *\n * `DeliverableGuardInput.summary` is checked for the `'summary'`-kind\n * expectation, and nothing in this package tracks a run's summary text\n * per-turn - `RunnerReporting` only computes one at the terminal\n * `mutateTerminalStatus` callback, which has not happened yet when a\n * mid-run deliverable check needs to run. The assistant's own most recent\n * text output is the best available proxy for \"what would this run's\n * summary be if it stopped now\" without a dedicated tracking mechanism this\n * package does not have yet. Best-effort by construction: an unparseable or\n * missing message reads as an empty summary, which is the SAFE failure\n * direction for this guard (nudging once more than strictly necessary,\n * never fewer times than necessary).\n */\nexport function extractAssistantSummaryText(messages: readonly DeliverableCheckMessage[]): string {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n const message = messages[index];\n if (message?.role !== 'assistant' || !Array.isArray(message.content)) continue;\n const text = message.content\n .filter(isAssistantTextBlock)\n .map((block) => block.text)\n .join('\\n')\n .trim();\n if (text) return text;\n }\n return '';\n}\n\n/**\n * Wires `DeliverableGuard`'s write side into this process. See the module\n * doc's overall framing: everything else in the missing-deliverable chain\n * (detection, the single nudge, escalation, the fold into `status.json`,\n * `AsyncJobTracker`'s read, and internal completion monitoring) already exist;\n * nothing called them. This is that call.\n *\n * WHY THIS ACCEPTS AN EXPLICIT RUNTIME:\n * The spawned Pi child has a deliberately narrow object graph built by\n * `createTeamPromptRuntime()`. Accepting that typed graph here keeps the\n * production composition in one place while allowing tests to supply the four\n * lifecycle collaborators without starting filesystem-backed services.\n *\n * WHY `session_start` BOOTSTRAPS, AND WHY IT ONLY EVER RUNS ONCE:\n * `RunnerBootstrap.bootstrap()` is genuinely the FIRST real caller this\n * package has ever had for it - it opens `status.json`, wires\n * `TerminalPersistenceService`'s finalize callback, and writes the startup\n * handshake `SpawnHandshake.waitForHandshake()` on the parent side blocks\n * on. `RunnerExecution.start()` then begins watching the control inbox.\n * `ControlChannelWatcher` depends on `PollScheduler`\n * (`control-channel.ts:809`), which nothing in this package's runner\n * services ever calls `.start()` on by itself (see `pollScheduler.ts`'s own\n * AVOID note: \"a registered-but-unstarted PollScheduler never ticks\") - so\n * this starts it explicitly, once, alongside bootstrap. The `resolved` guard\n * makes a stray second `session_start` (nothing in this file's other\n * registrations assumes it fires only once) a no-op rather than a second\n * bootstrap of the same run.\n *\n * WHY `execution.start()` IS GIVEN AN `onSteer` HANDLER:\n * `DeliverableGuard.deliverNudge()` drops a nudge into this run's OWN\n * steer-requests queue via `requestAsyncSteer` (see that method's doc) and\n * calls it delivered once the write succeeds. But the write alone does not\n * reach the child: `ControlChannelWatcher`, wired up by `execution.start()`,\n * claims and commits (deletes) every request it finds in that queue whether\n * or not a handler is registered for it - found by testing this file\n * against the REAL `ControlChannelWatcher` rather than a fake with no side\n * effects, which is exactly the failure mode this task kept turning up\n * elsewhere (`createRunsModule()` never loaded into any root;\n * `PollScheduler.start()` never called). `onSteer` is the missing delivery\n * half: it reuses `formatSteerMessage`/`sendUserMessage`, the same\n * mechanism `registerSteeringInbox` already uses for its own, separate\n * steer queue, so a nudge actually lands in the child's conversation instead\n * of being silently claimed and discarded.\n *\n * WHY `agent_end`, NOT `turn_end`:\n * `agent_end`'s own event (`AgentEndEvent.messages`) carries the full\n * message history for this agent loop, which `extractAssistantSummaryText`\n * reads from - `turn_end` only carries the one message that ended that turn,\n * not the memory of what preceded it, and `DeliverableGuard`'s own doc\n * frames this check as \"end-of-turn or idle\", not \"every turn.\"\n *\n * `unansweredAsks` AND `memberId`:\n * Both come from this run's own bound `TeamMemberContext`, which\n * `RunnerBootstrap.bootstrap()` already holds (from registering as a team\n * member) and now returns on its result. `memberId` is `teamContext.memberId`\n * directly. `unansweredAsks` calls `pendingAsksAddressedTo(teamContext,\n * teamContext.memberId, now)` - see `deliverable-guard.ts`'s own AVOID\n * section for why `DeliverableGuard` cannot call that itself, and that\n * function's own doc for why it deliberately returns id/sender/time only,\n * never the question's text (this maps its result into a factual, non-\n * fabricated placeholder message rather than guessing at content it was\n * never given). A standalone run with no team root forwarded has no\n * `teamContext` at all, in which case both are simply omitted - narrower\n * than the real behaviour, never wider, matching every other gap in this\n * file when there is genuinely nothing to report rather than something\n * unknown to guess at.\n *\n * `session_start` ALSO RECORDS THIS RUN'S OWN SESSION FILE:\n * `ctx.sessionManager.getSessionFile()` is the only place in this process\n * that ever answers \"what is my own transcript path\" - see\n * `runnerReporting.ts`'s header for why the value has to come from here\n * (the child) rather than be derived by the parent. `RunnerReporting`\n * validates and retains it while `RunnerBootstrap` writes it before the\n * ready handshake. `getSessionFile()` can return `undefined` (no persisted\n * transcript for this run); that case is simply not recorded, the same\n * \"omit rather than guess\" shape as `unansweredAsks`/`teamContext` above.\n */\nexport interface RunnerLifecycleRuntime {\n readonly pollScheduler: PollSchedulerContract;\n readonly bootstrap: RunnerBootstrapContract;\n readonly execution: RunnerExecutionContract;\n readonly reporting: Pick<RunnerReportingContract, 'recordSessionFile'>;\n}\n\nexport function registerRunnerLifecycle(\n pi: ExtensionAPI,\n runtime: RunnerLifecycleRuntime = createTeamPromptRuntime(),\n): void {\n const runId = process.env[SUBAGENT_RUN_ID_ENV]?.trim();\n if (!runId) return;\n\n const { pollScheduler, bootstrap, execution, reporting } = runtime;\n\n let resolved: { teamContext: TeamMemberContext | undefined } | undefined;\n let cumulativeTokens: number | undefined;\n let toolCount = 0;\n const countedMessages = new WeakSet<object>();\n\n onEvent(pi, 'session_start', (_event, ctx) => {\n if (resolved) return;\n pollScheduler.start();\n const sessionFile = ctx.sessionManager.getSessionFile();\n const recordedSessionFile = sessionFile ? reporting.recordSessionFile(sessionFile) : undefined;\n const bootstrapped = bootstrap.bootstrap(runId, recordedSessionFile);\n if (bootstrapped.teamContext) Object.assign(process.env, nativeTeamMemberEnvironment(bootstrapped.teamContext));\n // `onSteer` is the delivery half of `DeliverableGuard.deliverNudge`'s\n // write side (see `RunnerExecutionHandlers.onSteer`'s own doc, which\n // cross-references it): `deliverNudge` drops a request into this run's\n // OWN steer-requests queue via `requestAsyncSteer`, and\n // `ControlChannelWatcher` (wired up by `execution.start()` below) claims\n // it and calls this handler. Without it, `execution.start()` still\n // claims and commits the nudge - `deliverNudge` reports\n // `nudgeDelivered: true`, `status.json` still shows `needs_attention` -\n // but the request is silently discarded before it ever reaches the\n // child's own conversation. `formatSteerMessage`/`sendUserMessage` are\n // the exact same delivery this file already uses for\n // `registerSteeringInbox`'s separate queue.\n execution.start(runId, {\n onSteer: (request) => {\n const sendUserMessage = (\n pi as { sendUserMessage?: (content: string, options: { deliverAs: 'steer' }) => unknown }\n ).sendUserMessage;\n if (!sendUserMessage) {\n acknowledgeRunnerSteer(request, 'failed', 'Child Pi session does not support sendUserMessage steering.');\n return;\n }\n try {\n sendUserMessage(formatSteerMessage(request), { deliverAs: 'steer' });\n acknowledgeRunnerSteer(request, 'delivered', 'Pi accepted the correlated steering input.');\n } catch (error) {\n acknowledgeRunnerSteer(request, 'failed', error instanceof Error ? error.message : String(error));\n throw error;\n }\n },\n });\n resolved = { teamContext: bootstrapped.teamContext };\n execution.setActivity('working');\n });\n\n onEvent(pi, 'agent_start', () => {\n if (resolved) execution.setActivity('working');\n });\n onEvent<{ message?: ChildTranscriptMessage }>(pi, 'message_update', (event) => {\n if (!resolved || !event.message) return;\n const currentTool = getMessageActivity(event.message);\n if (currentTool) execution.setProgress({ currentTool });\n });\n onEvent<{ message?: ChildTranscriptMessage }>(pi, 'message_end', (event) => {\n if (!resolved || !event.message || typeof event.message !== 'object') return;\n if (countedMessages.has(event.message)) return;\n countedMessages.add(event.message);\n const messageTokens = getMessageUsageTokens(event.message);\n if (messageTokens === undefined) return;\n cumulativeTokens = (cumulativeTokens ?? 0) + messageTokens;\n execution.setProgress({ tokens: cumulativeTokens });\n });\n onEvent<{ toolName?: string; tool?: { name?: string }; args?: Record<string, unknown> }>(\n pi,\n 'tool_execution_start',\n (event) => {\n if (!resolved) return;\n const toolName = event.toolName ?? event.tool?.name;\n toolCount += 1;\n execution.setProgress({\n toolCount,\n ...(typeof toolName === 'string' && toolName.length > 0\n ? { currentTool: formatToolActivity(toolName, event.args) }\n : {}),\n });\n execution.setActivity(\n toolName === NATIVE_TEAM_TOOL_NAME && event.args?.action === 'ask' ? 'waiting_for_reply' : 'tool',\n );\n },\n );\n onEvent(pi, 'tool_execution_end', () => {\n if (!resolved) return;\n execution.setProgress({ currentTool: 'working' });\n execution.setActivity('working');\n });\n onEvent<{ messages: DeliverableCheckMessage[] }>(pi, 'agent_end', (event) => {\n if (!resolved) return; // session_start has not bootstrapped yet; nothing to report against.\n execution.setActivity('finalizing');\n const summary = extractAssistantSummaryText(event.messages);\n execution.complete(true, summary);\n });\n}\n\nconst PARENT_ONLY_CUSTOM_MESSAGE_TYPES = new Set([\n 'subagent-orchestration-instructions',\n 'subagent-slash-result',\n 'subagent-slash-text-result',\n 'subagent-notify',\n 'subagent_control_notice',\n 'subagent-control',\n 'subagent-control-notice',\n]);\nconst SUBAGENT_ORCHESTRATION_SKILL_NAME_PATTERN = /<name>\\s*pi-subagents\\s*<\\/name>/;\nconst PROJECT_CONTEXT_HEADER = '\\n\\n# Project Context\\n\\nProject-specific instructions and guidelines:\\n\\n';\nconst SKILLS_HEADER = '\\n\\nThe following skills provide specialized instructions for specific tasks.';\nconst DATE_HEADER = '\\nCurrent date:';\n\nfunction readBooleanEnv(name: string): boolean | undefined {\n const value = process.env[name];\n if (value === undefined) return undefined;\n return value !== '0';\n}\n\nfunction readRequiredChildTools(): string[] | undefined {\n const encoded = process.env[REQUIRED_CHILD_TOOLS_ENV]?.trim();\n if (!encoded) return undefined;\n const required = JSON.parse(encoded) as unknown;\n if (!Array.isArray(required) || required.some((name) => typeof name !== 'string' || !name)) {\n throw new Error(`Invalid ${REQUIRED_CHILD_TOOLS_ENV} payload.`);\n }\n return required;\n}\n\nfunction readMcpDirectChildTools(): string[] | undefined {\n const encoded = process.env[MCP_DIRECT_CHILD_TOOLS_ENV]?.trim();\n if (!encoded) return undefined;\n try {\n const tools = JSON.parse(encoded) as unknown;\n if (!Array.isArray(tools) || tools.some((name) => typeof name !== 'string' || !name)) return undefined;\n return tools;\n } catch {\n return undefined;\n }\n}\n\nfunction refreshChildToolDiagnostic(pi: ExtensionAPI): ChildToolDiagnostic | undefined {\n const filePath = process.env[CHILD_TOOL_DIAGNOSTIC_PATH_ENV]?.trim();\n const required = readRequiredChildTools();\n if (!filePath || !required) return undefined;\n const available = pi.getAllTools().map((tool) => tool.name);\n return writeChildToolDiagnostic(\n filePath,\n required,\n available,\n process.env[SUBAGENT_CHILD_AGENT_ENV]?.trim(),\n readMcpDirectChildTools(),\n );\n}\n\nfunction findSectionEnd(prompt: string, startIndex: number, nextHeaders: string[]): number {\n let endIndex = prompt.length;\n for (const header of nextHeaders) {\n const index = prompt.indexOf(header, startIndex);\n if (index !== -1 && index < endIndex) {\n endIndex = index;\n }\n }\n return endIndex;\n}\n\nexport function stripProjectContext(prompt: string): string {\n const startIndex = prompt.indexOf(PROJECT_CONTEXT_HEADER);\n if (startIndex === -1) return prompt;\n const endIndex = findSectionEnd(prompt, startIndex + PROJECT_CONTEXT_HEADER.length, [SKILLS_HEADER, DATE_HEADER]);\n return `${prompt.slice(0, startIndex)}${prompt.slice(endIndex)}`;\n}\n\nexport function stripInheritedSkills(prompt: string): string {\n const startIndex = prompt.indexOf(SKILLS_HEADER);\n if (startIndex === -1) return prompt;\n const endIndex = findSectionEnd(prompt, startIndex + SKILLS_HEADER.length, [DATE_HEADER]);\n return `${prompt.slice(0, startIndex)}${prompt.slice(endIndex)}`;\n}\n\nexport function stripSubagentOrchestrationSkill(prompt: string): string {\n return prompt\n .replace(/\\n{0,2}<skill\\s+name=[\"']pi-subagents[\"'][^>]*>[\\s\\S]*?<\\/skill>\\n{0,2}/g, '\\n\\n')\n .replace(/[ \\t]*<skill>\\s*[\\s\\S]*?<\\/skill>\\s*/g, (block) =>\n SUBAGENT_ORCHESTRATION_SKILL_NAME_PATTERN.test(block) ? '' : block,\n );\n}\n\nfunction stripChildBoundaryInstructions(prompt: string): string {\n let rewritten = prompt;\n for (const injectedInstructions of [\n CHILD_SUBAGENT_BOUNDARY_INSTRUCTIONS,\n CHILD_FANOUT_BOUNDARY_INSTRUCTIONS,\n STRUCTURED_OUTPUT_INSTRUCTIONS,\n ]) {\n rewritten = rewritten.split(injectedInstructions).join('');\n }\n return rewritten.replace(/^(?:[ \\t]*\\r?\\n)+/, '');\n}\n\nexport function rewriteSubagentPrompt(\n prompt: string,\n options: { inheritProjectContext: boolean; inheritSkills: boolean; fanoutChild?: boolean },\n): string {\n let rewritten = prompt;\n if (!options.inheritProjectContext) {\n rewritten = stripProjectContext(rewritten);\n }\n if (!options.inheritSkills) {\n rewritten = stripInheritedSkills(rewritten);\n }\n rewritten = stripSubagentOrchestrationSkill(rewritten);\n rewritten = stripChildBoundaryInstructions(rewritten);\n const boundary = options.fanoutChild ? CHILD_FANOUT_BOUNDARY_INSTRUCTIONS : CHILD_SUBAGENT_BOUNDARY_INSTRUCTIONS;\n const structured = process.env[STRUCTURED_OUTPUT_CAPTURE_ENV] ? `\\n\\n${STRUCTURED_OUTPUT_INSTRUCTIONS}` : '';\n return `${boundary}${structured}\\n\\n${rewritten}`;\n}\n\nfunction isParentOnlySubagentMessage(message: unknown): boolean {\n const m = message as { role?: string; customType?: string };\n if (m?.role !== 'custom' || typeof m.customType !== 'string') return false;\n return PARENT_ONLY_CUSTOM_MESSAGE_TYPES.has(m.customType);\n}\n\nfunction isSubagentToolResultMessage(message: unknown): boolean {\n const m = message as { role?: string; toolName?: string };\n return m?.role === 'toolResult' && m.toolName === 'subagent';\n}\n\nfunction isSubagentToolCallBlock(block: unknown): boolean {\n const b = block as { type?: string; name?: string };\n return b?.type === 'toolCall' && b.name === 'subagent';\n}\n\nfunction stripAssistantSubagentToolCallBlocks(message: unknown): unknown {\n const m = message as { role?: string; content?: unknown };\n if (m?.role !== 'assistant' || !Array.isArray(m.content)) return message;\n const filteredContent = m.content.filter((block) => !isSubagentToolCallBlock(block));\n if (filteredContent.length === m.content.length) return message;\n if (filteredContent.length === 0) return undefined;\n return { ...m, content: filteredContent };\n}\n\nexport function stripParentOnlySubagentMessages(messages: unknown[]): unknown[] {\n const preserveCurrentFanoutToolHistory = process.env[SUBAGENT_FANOUT_CHILD_ENV] === '1';\n let changed = false;\n const filtered: unknown[] = [];\n for (const message of messages) {\n if (\n isParentOnlySubagentMessage(message) ||\n (!preserveCurrentFanoutToolHistory && isSubagentToolResultMessage(message))\n ) {\n changed = true;\n continue;\n }\n const stripped = preserveCurrentFanoutToolHistory ? message : stripAssistantSubagentToolCallBlocks(message);\n if (stripped === undefined) {\n changed = true;\n continue;\n }\n if (stripped !== message) changed = true;\n filtered.push(stripped);\n }\n return changed ? filtered : messages;\n}\n\nexport function formatSteerMessage(request: SteerRequest): string {\n return [\n 'Mid-run steering from the parent orchestrator:',\n '',\n request.message,\n '',\n 'Incorporate this guidance at the next safe point. Do not restart the task unless the guidance explicitly asks you to.',\n ].join('\\n');\n}\n\nfunction acknowledgeRunnerSteer(request: SteerRequest, state: 'delivered' | 'failed', message: string): void {\n const ackDir = process.env[SUBAGENT_STEER_ACK_DIR_ENV]?.trim();\n const childIndex = Number(process.env[SUBAGENT_CHILD_INDEX_ENV]);\n if (!ackDir || !Number.isInteger(childIndex) || childIndex < 0) return;\n writeSteerAckAt(steerAckPathFromDir(ackDir, request.id), {\n requestId: request.id,\n index: childIndex,\n ts: Date.now(),\n state,\n message,\n });\n}\n\nfunction registerToolBudget(\n pi: ExtensionAPI,\n budget: ResolvedToolBudget | undefined,\n diagnostics: PromptRuntimeDiagnostics,\n): void {\n if (!budget) return;\n let toolCount = 0;\n let softNudged = false;\n const sendUserMessage = (pi as { sendUserMessage?: (content: string, options: { deliverAs: 'steer' }) => unknown })\n .sendUserMessage;\n onEvent<{ toolName?: string }>(pi, 'tool_call', (event) => {\n const toolName = typeof event.toolName === 'string' ? event.toolName : 'tool';\n toolCount++;\n if (budget.soft !== undefined && toolCount >= budget.soft && !softNudged) {\n softNudged = true;\n try {\n sendUserMessage?.(toolBudgetSoftNudge(budget, toolCount), { deliverAs: 'steer' });\n } catch (error) {\n // Advisory nudge only; the child's own output is what matters. Recorded\n // rather than discarded so a host that never accepts steering is\n // discoverable instead of silently dropping every nudge.\n diagnostics.steerNudgeFailures += 1;\n diagnostics.lastError = error;\n }\n }\n if (!shouldBlockToolForBudget(budget, toolName, toolCount)) return undefined;\n return { block: true, reason: toolBudgetBlockedMessage(budget, toolName, toolCount) };\n });\n}\n\n/**\n * Deliver mid-run steer requests queued for THIS child (by fan-out index)\n * into its own session via `sendUserMessage`. See the module doc's FIX for\n * why this claims each request individually rather than batch-deleting.\n */\nexport function registerSteeringInbox(\n pi: ExtensionAPI,\n deps: {\n watch?: typeof fs.watch;\n nativeRealpath?: (filePath: string) => string;\n diagnostics?: PromptRuntimeDiagnostics;\n } = {},\n): void {\n const diagnostics = deps.diagnostics ?? createPromptRuntimeDiagnostics();\n const steerInbox = process.env[SUBAGENT_STEER_INBOX_ENV]?.trim();\n if (!steerInbox) return;\n const capabilityPath = process.env[SUBAGENT_STEER_CAPABILITY_ENV]?.trim();\n const ackDir = process.env[SUBAGENT_STEER_ACK_DIR_ENV]?.trim();\n const sendUserMessage = (pi as { sendUserMessage?: (content: string, options: { deliverAs: 'steer' }) => unknown })\n .sendUserMessage;\n const childIndex = Number(process.env[SUBAGENT_CHILD_INDEX_ENV]);\n const pending = new Map<string, string[]>();\n let disposed = false;\n let flushing = false;\n let started = false;\n const canSteer = typeof sendUserMessage === 'function';\n let watcher: fs.FSWatcher | undefined;\n let interval: NodeJS.Timeout | undefined;\n\n const acknowledge = (request: SteerRequest, state: 'delivered' | 'failed', message: string): void => {\n if (!ackDir || !Number.isInteger(childIndex) || childIndex < 0) return;\n writeSteerAckAt(steerAckPathFromDir(ackDir, request.id), {\n requestId: request.id,\n index: childIndex,\n ts: Date.now(),\n state,\n message,\n });\n };\n const publishCapability = (): void => {\n if (!capabilityPath || !Number.isInteger(childIndex) || childIndex < 0) return;\n writeSteerCapabilityAt(capabilityPath, {\n index: childIndex,\n pid: process.pid,\n readyAt: Date.now(),\n supported: canSteer,\n });\n };\n\n const flush = (): void => {\n if (disposed || flushing) return;\n flushing = true;\n try {\n for (const claim of claimSteerRequestsFromDir(steerInbox)) {\n if (!canSteer || typeof sendUserMessage !== 'function') {\n acknowledge(claim.request, 'failed', 'Child Pi session does not support sendUserMessage steering.');\n claim.commit();\n continue;\n }\n const formatted = formatSteerMessage(claim.request);\n const ids = pending.get(formatted) ?? [];\n ids.push(claim.request.id);\n pending.set(formatted, ids);\n try {\n sendUserMessage(formatted, { deliverAs: 'steer' });\n claim.commit();\n } catch (error) {\n ids.pop();\n if (ids.length === 0) pending.delete(formatted);\n // Recoverable: this claim goes back to the queue for the next\n // flush to retry, instead of being lost. See the module doc's FIX.\n claim.release();\n acknowledge(claim.request, 'failed', error instanceof Error ? error.message : String(error));\n }\n }\n } finally {\n flushing = false;\n }\n };\n const onInput = (event: unknown): undefined => {\n if (disposed || !event || typeof event !== 'object') return undefined;\n const input = event as { source?: unknown; streamingBehavior?: unknown; text?: unknown; content?: unknown };\n if (input.source !== 'extension' || input.streamingBehavior !== 'steer') return undefined;\n const text =\n typeof input.text === 'string' ? input.text : typeof input.content === 'string' ? input.content : undefined;\n if (!text) return undefined;\n const ids = pending.get(text);\n const requestId = ids?.shift();\n if (!requestId) return undefined;\n if (ids?.length === 0) pending.delete(text);\n acknowledge(\n { type: 'steer', id: requestId, ts: Date.now(), message: text },\n 'delivered',\n 'Pi accepted the correlated steering input.',\n );\n return undefined;\n };\n const start = (): void => {\n if (started || disposed) return;\n try {\n fs.mkdirSync(steerInbox, { recursive: true });\n publishCapability();\n } catch {\n // No channel to report a startup failure on from inside the child;\n // the parent observes a missing capability file and treats it as\n // \"steering unsupported for this child\" on its own.\n return;\n }\n started = true;\n try {\n watcher = (deps.watch ?? fs.watch)(resolveWatchPath(steerInbox, deps.nativeRealpath), () => flush());\n watcher.on('error', (error) => {\n // fs.watch emits on transient FS errors and the interval poll below\n // keeps delivery live regardless, so this is not fatal. Recorded so a\n // watch that fails on every event is distinguishable from a quiet inbox.\n diagnostics.watchErrors += 1;\n diagnostics.lastError = error;\n });\n } catch {\n watcher = undefined;\n }\n interval = setInterval(flush, STEER_FLUSH_POLL_INTERVAL_MS);\n interval.unref?.();\n };\n const activate = (): undefined => {\n start();\n flush();\n return undefined;\n };\n\n // Register input before the watcher so an accepted extension input cannot race request dispatch.\n onEvent(pi, 'input', onInput);\n onEvent(pi, 'session_start', () => start());\n for (const eventName of [\n 'message_start',\n 'message_update',\n 'message_end',\n 'tool_execution_start',\n 'tool_execution_end',\n 'turn_end',\n ] as const) {\n onEvent(pi, eventName, activate);\n }\n onEvent(pi, 'session_shutdown', () => {\n disposed = true;\n try {\n watcher?.close();\n } catch (error) {\n // Best effort; the process is shutting down regardless. Still recorded,\n // because a close that always fails is a leaked descriptor per run.\n diagnostics.watchCloseFailures += 1;\n diagnostics.lastError = error;\n }\n if (interval) clearInterval(interval);\n });\n}\n\n/**\n * `diagnostics` is optional and defaults to a fresh object: the `.cts` entry\n * point calls this with a single argument (`pi`), matching the host contract\n * `resolveRuntimeExtensionPath` resolves onto every child's `--extension`\n * args, so that call keeps working unchanged. A caller that wants to observe\n * what this runtime absorbed - see `PromptRuntimeDiagnostics` - passes its\n * own object and keeps the reference; this function only ever mutates it, it\n * never owns or resets it.\n */\nexport function installSubagentPromptRuntime(\n cordis: Context,\n pi: ExtensionAPI,\n diagnostics: PromptRuntimeDiagnostics = createPromptRuntimeDiagnostics(),\n): void {\n // First, before any scoped path is touched. Pi loads extensions through jiti\n // with `moduleCache: false`, so this extension gets its OWN instance of\n // `shared/paths.ts` - the scope the surrounding runner process adopted is not\n // visible here, and has to be read from the environment again.\n adoptSessionScopeFromEnv();\n registerParentProcessGuard(pi);\n registerSteeringInbox(pi, { diagnostics });\n onEvent<{ payload?: unknown }>(pi, 'before_provider_request', (event, ctx) =>\n rewriteChildPromptCacheKey(event.payload, ctx.model?.api),\n );\n registerToolBudget(\n pi,\n decodeToolBudgetEnv(process.env[TOOL_BUDGET_ENV], { allowZero: process.env[TOOL_BUDGET_ZERO_AUTH_ENV] === '1' }),\n diagnostics,\n );\n // One explicit graph for this whole child registration. Building another\n // graph inside an individual resolver would duplicate scheduler, reporting,\n // and intercom state in the same process.\n const runtime = createTeamPromptRuntime();\n registerRunnerLifecycle(pi, runtime);\n cordis.effect(\n () => () => {\n runtime.pollScheduler.stop();\n runtime.terminalPersistence.dispose();\n },\n `${PROMPT_RUNTIME_SOURCE}/runner`,\n );\n\n const teamChannels = runtime.teamChannel;\n let teamRuntime: ReturnType<typeof teamChannels.createRuntime> | undefined;\n\n onEvent(pi, 'session_start', () => {\n teamRuntime?.dispose();\n teamRuntime = teamChannels.createRuntime(pi);\n teamRuntime.bindChildFromEnvironment();\n });\n cordis.effect(\n () => () => {\n teamRuntime?.dispose();\n teamRuntime = undefined;\n },\n `${PROMPT_RUNTIME_SOURCE}/channel`,\n );\n onEvent(pi, 'agent_start', () => {\n refreshChildToolDiagnostic(pi);\n });\n // `agent_end` intentionally does not drain outstanding work here. See the\n // module doc's \"WHAT IS DELIBERATELY NOT WIRED YET\" for why.\n\n const structuredOutputPath = process.env[STRUCTURED_OUTPUT_CAPTURE_ENV];\n const structuredSchemaPath = process.env[STRUCTURED_OUTPUT_SCHEMA_ENV];\n if (structuredOutputPath && structuredSchemaPath) {\n const schema = JSON.parse(fs.readFileSync(structuredSchemaPath, 'utf-8')) as JsonSchemaObject;\n const parameters = createStructuredOutputToolParameters(schema);\n const validator = new StructuredOutputValidator();\n const registerTool = (\n pi.registerTool as unknown as (tool: {\n name: string;\n label: string;\n description: string;\n parameters: unknown;\n execute: (_id: string, params: { value: unknown }) => Promise<unknown>;\n }) => void\n ).bind(pi);\n registerTool({\n name: 'structured_output',\n label: 'Structured Output',\n description: 'Submit the required final structured output for this subagent step. This terminates the step.',\n parameters: parameters as never,\n async execute(_id: string, params: { value: unknown }) {\n const validation = await validator.validateValue(schema, params.value);\n if (validation.status === 'invalid') {\n throw new Error(`Structured output validation failed: ${validation.message}`);\n }\n fs.mkdirSync(path.dirname(structuredOutputPath), { recursive: true });\n fs.writeFileSync(structuredOutputPath, JSON.stringify(params.value), { mode: 0o600 });\n return {\n content: [{ type: 'text', text: 'Structured output captured.' }],\n details: { path: structuredOutputPath },\n terminate: true,\n };\n },\n });\n }\n\n onEvent<{ messages: unknown[] }>(pi, 'context', (event) => {\n const messages = stripParentOnlySubagentMessages(event.messages);\n if (messages === event.messages) return undefined;\n return { messages };\n });\n\n onEvent<{ systemPrompt: string }>(pi, 'before_agent_start', async (event) => {\n const intercomSessionName = process.env[SUBAGENT_INTERCOM_SESSION_NAME_ENV]?.trim();\n if (intercomSessionName && typeof pi.setSessionName === 'function') {\n pi.setSessionName(intercomSessionName);\n }\n\n const inheritProjectContext = readBooleanEnv(INHERIT_PROJECT_CONTEXT_ENV);\n const inheritSkills = readBooleanEnv(INHERIT_SKILLS_ENV);\n const fanoutChild = readBooleanEnv(SUBAGENT_FANOUT_CHILD_ENV);\n let rewritten = event.systemPrompt;\n if (inheritProjectContext !== undefined || inheritSkills !== undefined || fanoutChild !== undefined) {\n rewritten = rewriteSubagentPrompt(event.systemPrompt, {\n inheritProjectContext: inheritProjectContext ?? true,\n inheritSkills: inheritSkills ?? true,\n fanoutChild: fanoutChild === true,\n });\n }\n if (rewritten === event.systemPrompt) return;\n return { systemPrompt: rewritten };\n });\n}\n\ninterface PromptRuntimePluginConfig {\n readonly pi: ExtensionAPI;\n readonly diagnostics?: PromptRuntimeDiagnostics;\n}\n\nfunction promptRuntimePlugin(cordis: Context, config: PromptRuntimePluginConfig): void {\n installSubagentPromptRuntime(cordis, config.pi, config.diagnostics);\n}\n\n/** Private child-process Pi factory, mounted into the shared or standalone Cordis host. */\nexport async function registerSubagentPromptRuntime(\n pi: ExtensionAPI,\n diagnostics?: PromptRuntimeDiagnostics,\n): Promise<void> {\n const connection = await connectDoomCordisHost(pi, PROMPT_RUNTIME_SOURCE);\n const fiber = connection.root.plugin(promptRuntimePlugin, { pi, ...(diagnostics ? { diagnostics } : {}) });\n try {\n await fiber;\n } catch (error) {\n await fiber.dispose();\n await connection.dispose();\n throw error;\n }\n\n let disposal: Promise<void> | undefined;\n pi.on(\n 'session_shutdown',\n () =>\n (disposal ??= (async () => {\n try {\n await fiber.dispose();\n } finally {\n await connection.dispose();\n }\n })()),\n );\n}\n"],"mappings":"0uBA6GA,MACM,EAAiC,mBACjC,EAAoC,6EACpC,EAAwC,uEACxC,EAA+B,iEAC/B,EAAiC,gDACjC,EAAoC,kCACpC,EACJ,mIACI,EAA4B,IAAI,IAAI,CAAC,mBAAoB,yBAA0B,wBAAwB,CAAC,EAC5G,EAAwB,wCAO9B,SAAgB,EACd,EACA,EACA,EAA4D,QAAQ,IAC/B,CACrC,GAAI,OAAO,GAAa,UAAY,CAAC,EAA0B,IAAI,CAAQ,EAAG,OAC9E,IAAM,EAAgB,EAAYA,EAAAA,0BAA0B,EAAE,KAAK,EACnE,GAAI,CAAC,GAAiB,OAAO,GAAY,WAAY,GAAoB,MAAM,QAAQ,CAAO,EAAG,OAEjG,IAAM,EAAU,EACV,EAAkB,EAAQ,iBAC5B,YAAO,GAAoB,UAAY,CAAC,EAAgB,KAAK,GAEjE,MAAO,CAAE,GAAG,EAAS,iBAAkB,CAAc,CACvD,CA6CA,SAAgB,GAA2D,CACzE,MAAO,CAAE,mBAAoB,EAAG,YAAa,EAAG,mBAAoB,CAAE,CACxE,CAEA,MAAM,EAAiC,CACrC,8DACA,yGACA,+GACF,CAAC,CAAC,KAAK;CAAI,EAEE,EAAmC,CAC9C,uGACA,8FACA,yIACA,uMACF,CAAC,CAAC,KAAK;CAAI,EAEE,EAAuC,CAClD,yDACA,mGACA,yFACA,mHACA,oIACA,CACF,CAAC,CAAC,KA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AAM,QAAQ,CACtB,QAAU,CACR,MAAM,EAAW,QAAQ,CAC3B,CACF,EAAA,CAAG,CACP,CACF"}
|
|
1
|
+
{"version":3,"file":"subagentPromptRuntime.cjs","names":["decodeProtectedParentProcessIds","createTeamPromptRuntime","SUBAGENT_RUN_ID_ENV","nativeTeamMemberEnvironment","getMessageActivity","getMessageUsageTokens","formatToolActivity","REQUIRED_CHILD_TOOLS_ENV","MCP_DIRECT_CHILD_TOOLS_ENV","CHILD_TOOL_DIAGNOSTIC_PATH_ENV","writeChildToolDiagnostic","SUBAGENT_CHILD_AGENT_ENV","SUBAGENT_FANOUT_CHILD_ENV","SUBAGENT_STEER_ACK_DIR_ENV","SUBAGENT_CHILD_INDEX_ENV","steerAckPathFromDir","toolBudgetSoftNudge","shouldBlockToolForBudget","toolBudgetBlockedMessage","SUBAGENT_STEER_INBOX_ENV","SUBAGENT_STEER_CAPABILITY_ENV","claimSteerRequestsFromDir","fs","resolveWatchPath","decodeToolBudgetEnv","TOOL_BUDGET_ENV","TOOL_BUDGET_ZERO_AUTH_ENV","STRUCTURED_OUTPUT_CAPTURE_ENV","STRUCTURED_OUTPUT_SCHEMA_ENV","createStructuredOutputToolParameters","StructuredOutputValidator","path","SUBAGENT_INTERCOM_SESSION_NAME_ENV","INHERIT_PROJECT_CONTEXT_ENV","INHERIT_SKILLS_ENV","connectDoomCordisHost"],"sources":["../../../../../src/adapters/pi/extensions/subagentPromptRuntime.ts"],"sourcesContent":["/**\n * The extension loaded INSIDE every spawned child: prompt rewriting,\n * mid-run steering delivery, the tool-call budget, native supervisor/team\n * messaging, and the `structured_output` tool.\n *\n * WHY THIS RUNS IN A DIFFERENT WORLD THAN EVERYTHING ELSE PORTED SO FAR:\n * Every other module in this package runs in the parent or the runner\n * process. This one is loaded BY the child's own Pi process\n * (`piArgs.ts`'s `resolveRuntimeExtensionPath` resolves it onto the\n * child's `--extension` args). The child's stdout IS its captured\n * transcript - a stray console write here does not go to a developer's\n * terminal, it becomes part of the child's output. Nothing in this file\n * writes to the console, ever; a failure that would have been\n * logged elsewhere is swallowed with a comment when there is no safe channel\n * to report it.\n *\n * FIX (claim-by-rename for the per-child steer inbox):\n * The predecessor's `registerSteeringInbox` called\n * `consumeSteerRequestsFromDir`, which deletes every queued request before\n * attempting delivery, then manually re-queued whatever it had not yet\n * attempted (`requests.slice(index + 1)`) if `sendUserMessage` threw\n * partway through a batch - but the request that was actually attempted\n * when the throw happened was already gone, lost the same way FIX 1 in\n * `control-channel.ts` was written to close for the runner-side steer\n * queue. This module's `flush()` uses `claimSteerRequestsFromDir` (already\n * exported from `control-channel.ts`, directory-agnostic) instead: each\n * request is claimed individually, and a failed `sendUserMessage` call\n * calls `release()` on that one claim so it is retried on the next flush,\n * while every OTHER claim in the same batch is still committed or released\n * independently. That is also a behavioural improvement over the\n * predecessor's `break`-on-first-failure, which abandoned the rest of a\n * batch rather than giving each message its own outcome - the same\n * per-item independence `ControlChannelWatcher.check()` already applies on\n * the runner side.\n *\n * Child runtimes keep the native team transport for lifecycle and result\n * delivery, but model-visible coordination tools are filtered by Team package\n * policy. They never register the root orchestration tool or a separate wait\n * alias.\n *\n * AVOID:\n * - Writing to the console. See the header above\n * - Reintroducing the predecessor's \"delete the whole batch, dispatch,\n * re-queue what failed\" shape for the steer inbox. See the FIX above\n */\n\nimport * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { connectDoomCordisHost } from '@agimon-ai/doompi-extension-contracts/cordis-host';\nimport type { Context } from '@deepseek-ai/cordis';\nimport type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';\nimport {\n CHILD_TOOL_DIAGNOSTIC_PATH_ENV,\n decodeProtectedParentProcessIds,\n INHERIT_PROJECT_CONTEXT_ENV,\n INHERIT_SKILLS_ENV,\n MCP_DIRECT_CHILD_TOOLS_ENV,\n REQUIRED_CHILD_TOOLS_ENV,\n STRUCTURED_OUTPUT_CAPTURE_ENV,\n STRUCTURED_OUTPUT_SCHEMA_ENV,\n SUBAGENT_CHILD_AGENT_ENV,\n SUBAGENT_CHILD_INDEX_ENV,\n SUBAGENT_FANOUT_CHILD_ENV,\n SUBAGENT_INTERCOM_SESSION_NAME_ENV,\n SUBAGENT_PROTECTED_PARENT_PIDS_ENV,\n SUBAGENT_RUN_ID_ENV,\n SUBAGENT_STEER_ACK_DIR_ENV,\n SUBAGENT_STEER_CAPABILITY_ENV,\n SUBAGENT_STEER_INBOX_ENV,\n TOOL_BUDGET_ENV,\n TOOL_BUDGET_ZERO_AUTH_ENV,\n} from '../../../types/environment';\nimport { createTeamPromptRuntime } from '../promptRuntime';\nimport {\n NATIVE_TEAM_TOOL_NAME,\n nativeTeamMemberEnvironment,\n type TeamMemberContext,\n} from '../../intercom/nativeTeamChannel';\nimport {\n claimSteerRequestsFromDir,\n type SteerRequest,\n steerAckPathFromDir,\n writeSteerAckAt,\n writeSteerCapabilityAt,\n} from '../../intercom/supervisorControlChannel';\nimport type { RunnerBootstrapContract } from '../../runs/background/runnerBootstrap';\nimport type { RunnerExecutionContract } from '../../runs/background/runnerExecution';\nimport type { RunnerReportingContract } from '../../runs/background/runnerReporting';\nimport { createStructuredOutputToolParameters, StructuredOutputValidator } from '../../runs/shared/structuredOutput';\nimport { type ChildToolDiagnostic, writeChildToolDiagnostic } from '../../runs/shared/toolAvailability';\nimport type { ResolvedToolBudget } from '../../runs/shared/toolBudget';\nimport {\n decodeToolBudgetEnv,\n shouldBlockToolForBudget,\n toolBudgetBlockedMessage,\n toolBudgetSoftNudge,\n} from '../../runs/shared/toolBudget';\nimport {\n type ChildTranscriptMessage,\n formatToolActivity,\n getMessageActivity,\n getMessageUsageTokens,\n} from '../../process/childTranscript';\nimport { resolveWatchPath } from '../../filesystem/configDir';\nimport { adoptSessionScopeFromEnv } from '../../filesystem/paths';\nimport type { PollSchedulerContract } from '../../pollScheduler';\nimport type { JsonSchemaObject } from '../../../types';\n\nconst STEER_FLUSH_POLL_INTERVAL_MS = 250;\nconst PROCESS_SIGNAL_COMMAND_PATTERN = /\\bkill(?:pg)?\\b/i;\nconst BROAD_PROCESS_TERMINATION_PATTERN = /(?:^|[^\\w.-])(?:pkill|killall|shutdown|reboot|poweroff|halt)(?=$|[^\\w.-])/i;\nconst WORKFLOW_TERMINAL_TERMINATION_PATTERN = /\\b(?:tmux|cmux)\\b[\\s\\S]*\\b(?:kill-server|kill-session|close|quit)\\b/i;\nconst PARENT_PID_REFERENCE_PATTERN = /\\$(?:PPID|\\{PPID\\})|\\bprocess\\.ppid\\b|\\bgetppid\\s*\\(|\\bppid\\b/i;\nconst DYNAMIC_PROCESS_TARGET_PATTERN = /\\$\\(|`|\\$(?:\\{[^}]+\\}|[A-Za-z_][A-Za-z0-9_]*)/;\nconst ALL_PROCESSES_KILL_TARGET_PATTERN = /(?:^|[\\s\"'`])-1(?=$|[\\s\"'`;|&])/;\nconst PARENT_PROCESS_BLOCK_REASON =\n 'Blocked: subagents may use Bash, but cannot signal parent or workflow processes. Ask the parent to perform that process cleanup.';\nconst PROMPT_RUNTIME_SOURCE = '@agimon-ai/doompi-team/prompt-runtime';\n\n/**\n * Failures this runtime absorbed rather than propagated.\n *\n * WHY RECORD RATHER THAN LOG:\n * This module runs inside the spawned child, where stdout IS the child's\n * captured transcript. Writing a diagnostic there would corrupt the very\n * output the run exists to produce, so nothing here may reach stdio. But a\n * discarded error is indistinguishable from one that never happened, and a\n * watcher that fails on every event looks exactly like a quiet inbox. These\n * counters are the compromise: cheap, bounded, and queryable by a caller that\n * wants to know whether the child's steering path was actually healthy.\n *\n * WHY THIS IS CALLER-OWNED, NOT MODULE STATE:\n * A module-level singleton here would be exactly the bug this package's \"no\n * module-level mutable state\" rule exists to prevent - see\n * `nativeTeamChannel.ts`'s header: \"a second session in the same process\n * cannot inherit the first one's [state]\". `registerSubagentPromptRuntime`\n * runs once per real child process, so a singleton would rarely matter in\n * production, but every test in this file registers multiple independent\n * runtimes in one process, and a shared singleton would leak counts between\n * them silently. `createPromptRuntimeDiagnostics()` hands each registration\n * its own object instead; the caller keeps the reference to read later, and\n * a fresh registration is what \"reset\" means - there is no shared state left\n * to reset.\n *\n * AVOID:\n * - Adding a `console.*` here, on any path, for any reason\n * - Treating a non-zero count as fatal; every one of these is a degraded-mode\n * path with a working fallback, which is why it was absorbed in the first place\n * - Reintroducing a module-level instance of this. See the header above\n */\nexport interface PromptRuntimeDiagnostics {\n /** Advisory tool-budget nudges that could not be delivered to the child. */\n steerNudgeFailures: number;\n /** Errors emitted by the steer-inbox watcher. The interval poll covers these. */\n watchErrors: number;\n /** Failures closing the watcher during shutdown. */\n watchCloseFailures: number;\n /** The most recent absorbed failure, whichever kind it was. */\n lastError?: unknown;\n}\n\n/** A fresh, zeroed diagnostics object for one registration. See the interface doc for why this is not a singleton. */\nexport function createPromptRuntimeDiagnostics(): PromptRuntimeDiagnostics {\n return { steerNudgeFailures: 0, watchErrors: 0, watchCloseFailures: 0 };\n}\n\nconst STRUCTURED_OUTPUT_INSTRUCTIONS = [\n 'This subagent step has a strict structured output contract.',\n 'Your final action must be to call the `structured_output` tool with JSON matching the provided schema.',\n 'Do not rely on prose-only completion; if you do not call `structured_output`, the parent will fail this step.',\n].join('\\n');\n\nexport const CHILD_CONTEXT_FIRST_INSTRUCTIONS = [\n 'When the assigned task includes a parent context pack, treat it as the authoritative starting point.',\n 'That pack satisfies generic instructions to explore or understand repository context first.',\n 'Read its listed paths directly before broad discovery, and do not re-derive established facts unless direct evidence contradicts them.',\n 'Do not begin with repository-wide listing, find, or grep. Expand only after consuming the pack and naming a concrete missing dependency or invalid path; search narrowly for that item and state why.',\n].join('\\n');\n\nexport const CHILD_SUBAGENT_BOUNDARY_INSTRUCTIONS = [\n 'You are a child subagent, not the parent orchestrator.',\n 'The parent session owns delegation, orchestration, review fanout, and follow-up worker launches.',\n 'Ignore prior parent-only orchestration instructions in inherited conversation history.',\n 'Do not propose or run subagents. Complete only your assigned role-specific task with the tools available to you.',\n 'If you need to edit files, use the available editing tools. Do not print tool-call syntax, patches, or pseudo-tool calls as text.',\n CHILD_CONTEXT_FIRST_INSTRUCTIONS,\n].join('\\n');\n\nexport const CHILD_FANOUT_BOUNDARY_INSTRUCTIONS = [\n 'You are a child subagent with explicit fanout responsibility for this assigned task.',\n 'The parent session owns final orchestration, acceptance, and follow-up implementation launches.',\n 'You may use the `subagent` tool only for the fanout work explicitly requested in this task.',\n 'Do not broaden yourself into general parent orchestration. Do not launch follow-up workers unless the task explicitly asks for that.',\n 'The maxSubagentDepth cap still applies and may block further fanout.',\n 'If you need to edit files, use the available editing tools. Do not print tool-call syntax, patches, or pseudo-tool calls as text.',\n CHILD_CONTEXT_FIRST_INSTRUCTIONS,\n].join('\\n');\n\n/**\n * `pi.on` typed loosely: the extension API's event payloads are not typed\n * per event name, so every call site narrows its own handler's parameter.\n * `.call(pi, ...)` binds `this` explicitly rather than extracting `pi.on` as\n * a bare reference, which is what an unbound method call would otherwise risk.\n *\n * The handler is given `ctx: ExtensionContext` as a second parameter,\n * matching the real `pi.on` signature (`ExtensionHandler<E, R> = (event: E,\n * ctx: ExtensionContext) => ...`) even though most registrations here never\n * read it - existing single-parameter handlers stay valid without change\n * (JS ignores a callback's unused trailing parameters), and the one call\n * site that DOES need it (`session_start`, for `ctx.sessionManager` - see\n * `registerDeliverableGuardCheck`'s doc) no longer has to reach past this\n * wrapper to get it.\n */\nfunction onEvent<E = unknown>(\n pi: ExtensionAPI,\n event: string,\n handler: (event: E, ctx: ExtensionContext) => unknown,\n): void {\n (pi.on as unknown as (event: string, handler: (event: E, ctx: ExtensionContext) => unknown) => void).call(\n pi,\n event,\n handler,\n );\n}\n\nfunction commandMentionsProcessId(command: string, pid: number): boolean {\n return new RegExp(`(?:^|\\\\D)-?${pid}(?!\\\\d)`).test(command);\n}\n\n/**\n * Return the blocking reason only when Bash could reach workflow-owned\n * processes. Literal signals to another PID remain available for child-owned\n * cleanup; name-wide selectors and dynamic parent lookup fail closed because\n * their target set cannot be proven not to include the parent.\n */\nexport function parentProcessTerminationBlockReason(\n command: string,\n protectedProcessIds: readonly number[],\n): string | undefined {\n if (BROAD_PROCESS_TERMINATION_PATTERN.test(command) || WORKFLOW_TERMINAL_TERMINATION_PATTERN.test(command)) {\n return PARENT_PROCESS_BLOCK_REASON;\n }\n if (!PROCESS_SIGNAL_COMMAND_PATTERN.test(command)) return undefined;\n if (\n PARENT_PID_REFERENCE_PATTERN.test(command) ||\n DYNAMIC_PROCESS_TARGET_PATTERN.test(command) ||\n ALL_PROCESSES_KILL_TARGET_PATTERN.test(command) ||\n /\\bxargs\\s+(?:[^;&|\\n]+\\s+)?kill(?:pg)?\\b/i.test(command)\n ) {\n return PARENT_PROCESS_BLOCK_REASON;\n }\n return protectedProcessIds.some((pid) => commandMentionsProcessId(command, pid))\n ? PARENT_PROCESS_BLOCK_REASON\n : undefined;\n}\n\nexport function registerParentProcessGuard(\n pi: ExtensionAPI,\n options: { protectedProcessIds?: readonly number[] } = {},\n): void {\n const protectedProcessIds = [\n ...new Set(\n options.protectedProcessIds ?? [\n ...decodeProtectedParentProcessIds(process.env[SUBAGENT_PROTECTED_PARENT_PIDS_ENV]),\n process.pid,\n process.ppid,\n ],\n ),\n ].filter((pid) => Number.isSafeInteger(pid) && pid > 1);\n\n onEvent<{ toolName?: unknown; input?: unknown }>(pi, 'tool_call', (event) => {\n if (event.toolName !== 'bash' || !event.input || typeof event.input !== 'object') return undefined;\n const command = (event.input as { command?: unknown }).command;\n if (typeof command !== 'string') return undefined;\n const reason = parentProcessTerminationBlockReason(command, protectedProcessIds);\n return reason ? { block: true, reason } : undefined;\n });\n}\n\n/** A text block from an assistant message's content array. Narrowed structurally, not imported from `@earendil-works/pi-ai`, matching this file's habit of ad-hoc event-payload types (see `onEvent`'s own doc). */\ninterface AssistantTextBlock {\n type: 'text';\n text: string;\n}\n\n/** The subset of `AgentEndEvent`/message shape this file actually reads. */\ninterface DeliverableCheckMessage {\n role?: string;\n content?: unknown;\n}\n\nfunction isAssistantTextBlock(block: unknown): block is AssistantTextBlock {\n return (\n typeof block === 'object' &&\n block !== null &&\n (block as { type?: unknown }).type === 'text' &&\n typeof (block as { text?: unknown }).text === 'string'\n );\n}\n\n/**\n * The last non-empty assistant text found in `messages`, or `''`.\n *\n * `DeliverableGuardInput.summary` is checked for the `'summary'`-kind\n * expectation, and nothing in this package tracks a run's summary text\n * per-turn - `RunnerReporting` only computes one at the terminal\n * `mutateTerminalStatus` callback, which has not happened yet when a\n * mid-run deliverable check needs to run. The assistant's own most recent\n * text output is the best available proxy for \"what would this run's\n * summary be if it stopped now\" without a dedicated tracking mechanism this\n * package does not have yet. Best-effort by construction: an unparseable or\n * missing message reads as an empty summary, which is the SAFE failure\n * direction for this guard (nudging once more than strictly necessary,\n * never fewer times than necessary).\n */\nexport function extractAssistantSummaryText(messages: readonly DeliverableCheckMessage[]): string {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n const message = messages[index];\n if (message?.role !== 'assistant' || !Array.isArray(message.content)) continue;\n const text = message.content\n .filter(isAssistantTextBlock)\n .map((block) => block.text)\n .join('\\n')\n .trim();\n if (text) return text;\n }\n return '';\n}\n\n/**\n * Wires `DeliverableGuard`'s write side into this process. See the module\n * doc's overall framing: everything else in the missing-deliverable chain\n * (detection, the single nudge, escalation, the fold into `status.json`,\n * `AsyncJobTracker`'s read, and internal completion monitoring) already exist;\n * nothing called them. This is that call.\n *\n * WHY THIS ACCEPTS AN EXPLICIT RUNTIME:\n * The spawned Pi child has a deliberately narrow object graph built by\n * `createTeamPromptRuntime()`. Accepting that typed graph here keeps the\n * production composition in one place while allowing tests to supply the four\n * lifecycle collaborators without starting filesystem-backed services.\n *\n * WHY `session_start` BOOTSTRAPS, AND WHY IT ONLY EVER RUNS ONCE:\n * `RunnerBootstrap.bootstrap()` is genuinely the FIRST real caller this\n * package has ever had for it - it opens `status.json`, wires\n * `TerminalPersistenceService`'s finalize callback, and writes the startup\n * handshake `SpawnHandshake.waitForHandshake()` on the parent side blocks\n * on. `RunnerExecution.start()` then begins watching the control inbox.\n * `ControlChannelWatcher` depends on `PollScheduler`\n * (`control-channel.ts:809`), which nothing in this package's runner\n * services ever calls `.start()` on by itself (see `pollScheduler.ts`'s own\n * AVOID note: \"a registered-but-unstarted PollScheduler never ticks\") - so\n * this starts it explicitly, once, alongside bootstrap. The `resolved` guard\n * makes a stray second `session_start` (nothing in this file's other\n * registrations assumes it fires only once) a no-op rather than a second\n * bootstrap of the same run.\n *\n * WHY `execution.start()` IS GIVEN AN `onSteer` HANDLER:\n * `DeliverableGuard.deliverNudge()` drops a nudge into this run's OWN\n * steer-requests queue via `requestAsyncSteer` (see that method's doc) and\n * calls it delivered once the write succeeds. But the write alone does not\n * reach the child: `ControlChannelWatcher`, wired up by `execution.start()`,\n * claims and commits (deletes) every request it finds in that queue whether\n * or not a handler is registered for it - found by testing this file\n * against the REAL `ControlChannelWatcher` rather than a fake with no side\n * effects, which is exactly the failure mode this task kept turning up\n * elsewhere (`createRunsModule()` never loaded into any root;\n * `PollScheduler.start()` never called). `onSteer` is the missing delivery\n * half: it reuses `formatSteerMessage`/`sendUserMessage`, the same\n * mechanism `registerSteeringInbox` already uses for its own, separate\n * steer queue, so a nudge actually lands in the child's conversation instead\n * of being silently claimed and discarded.\n *\n * WHY `agent_end`, NOT `turn_end`:\n * `agent_end`'s own event (`AgentEndEvent.messages`) carries the full\n * message history for this agent loop, which `extractAssistantSummaryText`\n * reads from - `turn_end` only carries the one message that ended that turn,\n * not the memory of what preceded it, and `DeliverableGuard`'s own doc\n * frames this check as \"end-of-turn or idle\", not \"every turn.\"\n *\n * `unansweredAsks` AND `memberId`:\n * Both come from this run's own bound `TeamMemberContext`, which\n * `RunnerBootstrap.bootstrap()` already holds (from registering as a team\n * member) and now returns on its result. `memberId` is `teamContext.memberId`\n * directly. `unansweredAsks` calls `pendingAsksAddressedTo(teamContext,\n * teamContext.memberId, now)` - see `deliverable-guard.ts`'s own AVOID\n * section for why `DeliverableGuard` cannot call that itself, and that\n * function's own doc for why it deliberately returns id/sender/time only,\n * never the question's text (this maps its result into a factual, non-\n * fabricated placeholder message rather than guessing at content it was\n * never given). A standalone run with no team root forwarded has no\n * `teamContext` at all, in which case both are simply omitted - narrower\n * than the real behaviour, never wider, matching every other gap in this\n * file when there is genuinely nothing to report rather than something\n * unknown to guess at.\n *\n * `session_start` ALSO RECORDS THIS RUN'S OWN SESSION FILE:\n * `ctx.sessionManager.getSessionFile()` is the only place in this process\n * that ever answers \"what is my own transcript path\" - see\n * `runnerReporting.ts`'s header for why the value has to come from here\n * (the child) rather than be derived by the parent. `RunnerReporting`\n * validates and retains it while `RunnerBootstrap` writes it before the\n * ready handshake. `getSessionFile()` can return `undefined` (no persisted\n * transcript for this run); that case is simply not recorded, the same\n * \"omit rather than guess\" shape as `unansweredAsks`/`teamContext` above.\n */\nexport interface RunnerLifecycleRuntime {\n readonly pollScheduler: PollSchedulerContract;\n readonly bootstrap: RunnerBootstrapContract;\n readonly execution: RunnerExecutionContract;\n readonly reporting: Pick<RunnerReportingContract, 'recordSessionFile'>;\n}\n\nexport function registerRunnerLifecycle(\n pi: ExtensionAPI,\n runtime: RunnerLifecycleRuntime = createTeamPromptRuntime(),\n): void {\n const runId = process.env[SUBAGENT_RUN_ID_ENV]?.trim();\n if (!runId) return;\n\n const { pollScheduler, bootstrap, execution, reporting } = runtime;\n\n let resolved: { teamContext: TeamMemberContext | undefined } | undefined;\n let cumulativeTokens: number | undefined;\n let toolCount = 0;\n const countedMessages = new WeakSet<object>();\n\n onEvent(pi, 'session_start', (_event, ctx) => {\n if (resolved) return;\n pollScheduler.start();\n const sessionFile = ctx.sessionManager.getSessionFile();\n const recordedSessionFile = sessionFile ? reporting.recordSessionFile(sessionFile) : undefined;\n const bootstrapped = bootstrap.bootstrap(runId, recordedSessionFile);\n if (bootstrapped.teamContext) Object.assign(process.env, nativeTeamMemberEnvironment(bootstrapped.teamContext));\n // `onSteer` is the delivery half of `DeliverableGuard.deliverNudge`'s\n // write side (see `RunnerExecutionHandlers.onSteer`'s own doc, which\n // cross-references it): `deliverNudge` drops a request into this run's\n // OWN steer-requests queue via `requestAsyncSteer`, and\n // `ControlChannelWatcher` (wired up by `execution.start()` below) claims\n // it and calls this handler. Without it, `execution.start()` still\n // claims and commits the nudge - `deliverNudge` reports\n // `nudgeDelivered: true`, `status.json` still shows `needs_attention` -\n // but the request is silently discarded before it ever reaches the\n // child's own conversation. `formatSteerMessage`/`sendUserMessage` are\n // the exact same delivery this file already uses for\n // `registerSteeringInbox`'s separate queue.\n execution.start(runId, {\n onSteer: (request) => {\n const sendUserMessage = (\n pi as { sendUserMessage?: (content: string, options: { deliverAs: 'steer' }) => unknown }\n ).sendUserMessage;\n if (!sendUserMessage) {\n acknowledgeRunnerSteer(request, 'failed', 'Child Pi session does not support sendUserMessage steering.');\n return;\n }\n try {\n sendUserMessage(formatSteerMessage(request), { deliverAs: 'steer' });\n acknowledgeRunnerSteer(request, 'delivered', 'Pi accepted the correlated steering input.');\n } catch (error) {\n acknowledgeRunnerSteer(request, 'failed', error instanceof Error ? error.message : String(error));\n throw error;\n }\n },\n });\n resolved = { teamContext: bootstrapped.teamContext };\n execution.setActivity('working');\n });\n\n onEvent(pi, 'agent_start', () => {\n if (resolved) execution.setActivity('working');\n });\n onEvent<{ message?: ChildTranscriptMessage }>(pi, 'message_update', (event) => {\n if (!resolved || !event.message) return;\n const currentTool = getMessageActivity(event.message);\n if (currentTool) execution.setProgress({ currentTool });\n });\n onEvent<{ message?: ChildTranscriptMessage }>(pi, 'message_end', (event) => {\n if (!resolved || !event.message || typeof event.message !== 'object') return;\n if (countedMessages.has(event.message)) return;\n countedMessages.add(event.message);\n const messageTokens = getMessageUsageTokens(event.message);\n if (messageTokens === undefined) return;\n cumulativeTokens = (cumulativeTokens ?? 0) + messageTokens;\n execution.setProgress({ tokens: cumulativeTokens });\n });\n onEvent<{ toolName?: string; tool?: { name?: string }; args?: Record<string, unknown> }>(\n pi,\n 'tool_execution_start',\n (event) => {\n if (!resolved) return;\n const toolName = event.toolName ?? event.tool?.name;\n toolCount += 1;\n execution.setProgress({\n toolCount,\n ...(typeof toolName === 'string' && toolName.length > 0\n ? { currentTool: formatToolActivity(toolName, event.args) }\n : {}),\n });\n execution.setActivity(\n toolName === NATIVE_TEAM_TOOL_NAME && event.args?.action === 'ask' ? 'waiting_for_reply' : 'tool',\n );\n },\n );\n onEvent(pi, 'tool_execution_end', () => {\n if (!resolved) return;\n execution.setProgress({ currentTool: 'working' });\n execution.setActivity('working');\n });\n onEvent<{ messages: DeliverableCheckMessage[] }>(pi, 'agent_end', (event) => {\n if (!resolved) return; // session_start has not bootstrapped yet; nothing to report against.\n execution.setActivity('finalizing');\n const summary = extractAssistantSummaryText(event.messages);\n execution.complete(true, summary);\n });\n}\n\nconst PARENT_ONLY_CUSTOM_MESSAGE_TYPES = new Set([\n 'subagent-orchestration-instructions',\n 'subagent-slash-result',\n 'subagent-slash-text-result',\n 'subagent-notify',\n 'subagent_control_notice',\n 'subagent-control',\n 'subagent-control-notice',\n]);\nconst SUBAGENT_ORCHESTRATION_SKILL_NAME_PATTERN = /<name>\\s*pi-subagents\\s*<\\/name>/;\nconst PROJECT_CONTEXT_HEADER = '\\n\\n# Project Context\\n\\nProject-specific instructions and guidelines:\\n\\n';\nconst SKILLS_HEADER = '\\n\\nThe following skills provide specialized instructions for specific tasks.';\nconst DATE_HEADER = '\\nCurrent date:';\n\nfunction readBooleanEnv(name: string): boolean | undefined {\n const value = process.env[name];\n if (value === undefined) return undefined;\n return value !== '0';\n}\n\nfunction readRequiredChildTools(): string[] | undefined {\n const encoded = process.env[REQUIRED_CHILD_TOOLS_ENV]?.trim();\n if (!encoded) return undefined;\n const required = JSON.parse(encoded) as unknown;\n if (!Array.isArray(required) || required.some((name) => typeof name !== 'string' || !name)) {\n throw new Error(`Invalid ${REQUIRED_CHILD_TOOLS_ENV} payload.`);\n }\n return required;\n}\n\nfunction readMcpDirectChildTools(): string[] | undefined {\n const encoded = process.env[MCP_DIRECT_CHILD_TOOLS_ENV]?.trim();\n if (!encoded) return undefined;\n try {\n const tools = JSON.parse(encoded) as unknown;\n if (!Array.isArray(tools) || tools.some((name) => typeof name !== 'string' || !name)) return undefined;\n return tools;\n } catch {\n return undefined;\n }\n}\n\nfunction refreshChildToolDiagnostic(pi: ExtensionAPI): ChildToolDiagnostic | undefined {\n const filePath = process.env[CHILD_TOOL_DIAGNOSTIC_PATH_ENV]?.trim();\n const required = readRequiredChildTools();\n if (!filePath || !required) return undefined;\n const available = pi.getAllTools().map((tool) => tool.name);\n return writeChildToolDiagnostic(\n filePath,\n required,\n available,\n process.env[SUBAGENT_CHILD_AGENT_ENV]?.trim(),\n readMcpDirectChildTools(),\n );\n}\n\nfunction findSectionEnd(prompt: string, startIndex: number, nextHeaders: string[]): number {\n let endIndex = prompt.length;\n for (const header of nextHeaders) {\n const index = prompt.indexOf(header, startIndex);\n if (index !== -1 && index < endIndex) {\n endIndex = index;\n }\n }\n return endIndex;\n}\n\nexport function stripProjectContext(prompt: string): string {\n const startIndex = prompt.indexOf(PROJECT_CONTEXT_HEADER);\n if (startIndex === -1) return prompt;\n const endIndex = findSectionEnd(prompt, startIndex + PROJECT_CONTEXT_HEADER.length, [SKILLS_HEADER, DATE_HEADER]);\n return `${prompt.slice(0, startIndex)}${prompt.slice(endIndex)}`;\n}\n\nexport function stripInheritedSkills(prompt: string): string {\n const startIndex = prompt.indexOf(SKILLS_HEADER);\n if (startIndex === -1) return prompt;\n const endIndex = findSectionEnd(prompt, startIndex + SKILLS_HEADER.length, [DATE_HEADER]);\n return `${prompt.slice(0, startIndex)}${prompt.slice(endIndex)}`;\n}\n\nexport function stripSubagentOrchestrationSkill(prompt: string): string {\n return prompt\n .replace(/\\n{0,2}<skill\\s+name=[\"']pi-subagents[\"'][^>]*>[\\s\\S]*?<\\/skill>\\n{0,2}/g, '\\n\\n')\n .replace(/[ \\t]*<skill>\\s*[\\s\\S]*?<\\/skill>\\s*/g, (block) =>\n SUBAGENT_ORCHESTRATION_SKILL_NAME_PATTERN.test(block) ? '' : block,\n );\n}\n\nfunction stripChildBoundaryInstructions(prompt: string): string {\n let rewritten = prompt;\n for (const injectedInstructions of [\n CHILD_SUBAGENT_BOUNDARY_INSTRUCTIONS,\n CHILD_FANOUT_BOUNDARY_INSTRUCTIONS,\n STRUCTURED_OUTPUT_INSTRUCTIONS,\n ]) {\n rewritten = rewritten.split(injectedInstructions).join('');\n }\n return rewritten.replace(/^(?:[ \\t]*\\r?\\n)+/, '');\n}\n\nexport function rewriteSubagentPrompt(\n prompt: string,\n options: { inheritProjectContext: boolean; inheritSkills: boolean; fanoutChild?: boolean },\n): string {\n let rewritten = prompt;\n if (!options.inheritProjectContext) {\n rewritten = stripProjectContext(rewritten);\n }\n if (!options.inheritSkills) {\n rewritten = stripInheritedSkills(rewritten);\n }\n rewritten = stripSubagentOrchestrationSkill(rewritten);\n rewritten = stripChildBoundaryInstructions(rewritten);\n const boundary = options.fanoutChild ? CHILD_FANOUT_BOUNDARY_INSTRUCTIONS : CHILD_SUBAGENT_BOUNDARY_INSTRUCTIONS;\n const structured = process.env[STRUCTURED_OUTPUT_CAPTURE_ENV] ? `\\n\\n${STRUCTURED_OUTPUT_INSTRUCTIONS}` : '';\n return `${boundary}${structured}\\n\\n${rewritten}`;\n}\n\nfunction isParentOnlySubagentMessage(message: unknown): boolean {\n const m = message as { role?: string; customType?: string };\n if (m?.role !== 'custom' || typeof m.customType !== 'string') return false;\n return PARENT_ONLY_CUSTOM_MESSAGE_TYPES.has(m.customType);\n}\n\nfunction isSubagentToolResultMessage(message: unknown): boolean {\n const m = message as { role?: string; toolName?: string };\n return m?.role === 'toolResult' && m.toolName === 'subagent';\n}\n\nfunction isSubagentToolCallBlock(block: unknown): boolean {\n const b = block as { type?: string; name?: string };\n return b?.type === 'toolCall' && b.name === 'subagent';\n}\n\nfunction stripAssistantSubagentToolCallBlocks(message: unknown): unknown {\n const m = message as { role?: string; content?: unknown };\n if (m?.role !== 'assistant' || !Array.isArray(m.content)) return message;\n const filteredContent = m.content.filter((block) => !isSubagentToolCallBlock(block));\n if (filteredContent.length === m.content.length) return message;\n if (filteredContent.length === 0) return undefined;\n return { ...m, content: filteredContent };\n}\n\nexport function stripParentOnlySubagentMessages(messages: unknown[]): unknown[] {\n const preserveCurrentFanoutToolHistory = process.env[SUBAGENT_FANOUT_CHILD_ENV] === '1';\n let changed = false;\n const filtered: unknown[] = [];\n for (const message of messages) {\n if (\n isParentOnlySubagentMessage(message) ||\n (!preserveCurrentFanoutToolHistory && isSubagentToolResultMessage(message))\n ) {\n changed = true;\n continue;\n }\n const stripped = preserveCurrentFanoutToolHistory ? message : stripAssistantSubagentToolCallBlocks(message);\n if (stripped === undefined) {\n changed = true;\n continue;\n }\n if (stripped !== message) changed = true;\n filtered.push(stripped);\n }\n return changed ? filtered : messages;\n}\n\nexport function formatSteerMessage(request: SteerRequest): string {\n return [\n 'Mid-run steering from the parent orchestrator:',\n '',\n request.message,\n '',\n 'Incorporate this guidance at the next safe point. Do not restart the task unless the guidance explicitly asks you to.',\n ].join('\\n');\n}\n\nfunction acknowledgeRunnerSteer(request: SteerRequest, state: 'delivered' | 'failed', message: string): void {\n const ackDir = process.env[SUBAGENT_STEER_ACK_DIR_ENV]?.trim();\n const childIndex = Number(process.env[SUBAGENT_CHILD_INDEX_ENV]);\n if (!ackDir || !Number.isInteger(childIndex) || childIndex < 0) return;\n writeSteerAckAt(steerAckPathFromDir(ackDir, request.id), {\n requestId: request.id,\n index: childIndex,\n ts: Date.now(),\n state,\n message,\n });\n}\n\nfunction registerToolBudget(\n pi: ExtensionAPI,\n budget: ResolvedToolBudget | undefined,\n diagnostics: PromptRuntimeDiagnostics,\n): void {\n if (!budget) return;\n let toolCount = 0;\n let softNudged = false;\n const sendUserMessage = (pi as { sendUserMessage?: (content: string, options: { deliverAs: 'steer' }) => unknown })\n .sendUserMessage;\n onEvent<{ toolName?: string }>(pi, 'tool_call', (event) => {\n const toolName = typeof event.toolName === 'string' ? event.toolName : 'tool';\n toolCount++;\n if (budget.soft !== undefined && toolCount >= budget.soft && !softNudged) {\n softNudged = true;\n try {\n sendUserMessage?.(toolBudgetSoftNudge(budget, toolCount), { deliverAs: 'steer' });\n } catch (error) {\n // Advisory nudge only; the child's own output is what matters. Recorded\n // rather than discarded so a host that never accepts steering is\n // discoverable instead of silently dropping every nudge.\n diagnostics.steerNudgeFailures += 1;\n diagnostics.lastError = error;\n }\n }\n if (!shouldBlockToolForBudget(budget, toolName, toolCount)) return undefined;\n return { block: true, reason: toolBudgetBlockedMessage(budget, toolName, toolCount) };\n });\n}\n\n/**\n * Deliver mid-run steer requests queued for THIS child (by fan-out index)\n * into its own session via `sendUserMessage`. See the module doc's FIX for\n * why this claims each request individually rather than batch-deleting.\n */\nexport function registerSteeringInbox(\n pi: ExtensionAPI,\n deps: {\n watch?: typeof fs.watch;\n nativeRealpath?: (filePath: string) => string;\n diagnostics?: PromptRuntimeDiagnostics;\n } = {},\n): void {\n const diagnostics = deps.diagnostics ?? createPromptRuntimeDiagnostics();\n const steerInbox = process.env[SUBAGENT_STEER_INBOX_ENV]?.trim();\n if (!steerInbox) return;\n const capabilityPath = process.env[SUBAGENT_STEER_CAPABILITY_ENV]?.trim();\n const ackDir = process.env[SUBAGENT_STEER_ACK_DIR_ENV]?.trim();\n const sendUserMessage = (pi as { sendUserMessage?: (content: string, options: { deliverAs: 'steer' }) => unknown })\n .sendUserMessage;\n const childIndex = Number(process.env[SUBAGENT_CHILD_INDEX_ENV]);\n const pending = new Map<string, string[]>();\n let disposed = false;\n let flushing = false;\n let started = false;\n const canSteer = typeof sendUserMessage === 'function';\n let watcher: fs.FSWatcher | undefined;\n let interval: NodeJS.Timeout | undefined;\n\n const acknowledge = (request: SteerRequest, state: 'delivered' | 'failed', message: string): void => {\n if (!ackDir || !Number.isInteger(childIndex) || childIndex < 0) return;\n writeSteerAckAt(steerAckPathFromDir(ackDir, request.id), {\n requestId: request.id,\n index: childIndex,\n ts: Date.now(),\n state,\n message,\n });\n };\n const publishCapability = (): void => {\n if (!capabilityPath || !Number.isInteger(childIndex) || childIndex < 0) return;\n writeSteerCapabilityAt(capabilityPath, {\n index: childIndex,\n pid: process.pid,\n readyAt: Date.now(),\n supported: canSteer,\n });\n };\n\n const flush = (): void => {\n if (disposed || flushing) return;\n flushing = true;\n try {\n for (const claim of claimSteerRequestsFromDir(steerInbox)) {\n if (!canSteer || typeof sendUserMessage !== 'function') {\n acknowledge(claim.request, 'failed', 'Child Pi session does not support sendUserMessage steering.');\n claim.commit();\n continue;\n }\n const formatted = formatSteerMessage(claim.request);\n const ids = pending.get(formatted) ?? [];\n ids.push(claim.request.id);\n pending.set(formatted, ids);\n try {\n sendUserMessage(formatted, { deliverAs: 'steer' });\n claim.commit();\n } catch (error) {\n ids.pop();\n if (ids.length === 0) pending.delete(formatted);\n // Recoverable: this claim goes back to the queue for the next\n // flush to retry, instead of being lost. See the module doc's FIX.\n claim.release();\n acknowledge(claim.request, 'failed', error instanceof Error ? error.message : String(error));\n }\n }\n } finally {\n flushing = false;\n }\n };\n const onInput = (event: unknown): undefined => {\n if (disposed || !event || typeof event !== 'object') return undefined;\n const input = event as { source?: unknown; streamingBehavior?: unknown; text?: unknown; content?: unknown };\n if (input.source !== 'extension' || input.streamingBehavior !== 'steer') return undefined;\n const text =\n typeof input.text === 'string' ? input.text : typeof input.content === 'string' ? input.content : undefined;\n if (!text) return undefined;\n const ids = pending.get(text);\n const requestId = ids?.shift();\n if (!requestId) return undefined;\n if (ids?.length === 0) pending.delete(text);\n acknowledge(\n { type: 'steer', id: requestId, ts: Date.now(), message: text },\n 'delivered',\n 'Pi accepted the correlated steering input.',\n );\n return undefined;\n };\n const start = (): void => {\n if (started || disposed) return;\n try {\n fs.mkdirSync(steerInbox, { recursive: true });\n publishCapability();\n } catch {\n // No channel to report a startup failure on from inside the child;\n // the parent observes a missing capability file and treats it as\n // \"steering unsupported for this child\" on its own.\n return;\n }\n started = true;\n try {\n watcher = (deps.watch ?? fs.watch)(resolveWatchPath(steerInbox, deps.nativeRealpath), () => flush());\n watcher.on('error', (error) => {\n // fs.watch emits on transient FS errors and the interval poll below\n // keeps delivery live regardless, so this is not fatal. Recorded so a\n // watch that fails on every event is distinguishable from a quiet inbox.\n diagnostics.watchErrors += 1;\n diagnostics.lastError = error;\n });\n } catch {\n watcher = undefined;\n }\n interval = setInterval(flush, STEER_FLUSH_POLL_INTERVAL_MS);\n interval.unref?.();\n };\n const activate = (): undefined => {\n start();\n flush();\n return undefined;\n };\n\n // Register input before the watcher so an accepted extension input cannot race request dispatch.\n onEvent(pi, 'input', onInput);\n onEvent(pi, 'session_start', () => start());\n for (const eventName of [\n 'message_start',\n 'message_update',\n 'message_end',\n 'tool_execution_start',\n 'tool_execution_end',\n 'turn_end',\n ] as const) {\n onEvent(pi, eventName, activate);\n }\n onEvent(pi, 'session_shutdown', () => {\n disposed = true;\n try {\n watcher?.close();\n } catch (error) {\n // Best effort; the process is shutting down regardless. Still recorded,\n // because a close that always fails is a leaked descriptor per run.\n diagnostics.watchCloseFailures += 1;\n diagnostics.lastError = error;\n }\n if (interval) clearInterval(interval);\n });\n}\n\n/**\n * `diagnostics` is optional and defaults to a fresh object: the `.cts` entry\n * point calls this with a single argument (`pi`), matching the host contract\n * `resolveRuntimeExtensionPath` resolves onto every child's `--extension`\n * args, so that call keeps working unchanged. A caller that wants to observe\n * what this runtime absorbed - see `PromptRuntimeDiagnostics` - passes its\n * own object and keeps the reference; this function only ever mutates it, it\n * never owns or resets it.\n */\nexport function installSubagentPromptRuntime(\n cordis: Context,\n pi: ExtensionAPI,\n diagnostics: PromptRuntimeDiagnostics = createPromptRuntimeDiagnostics(),\n): void {\n // First, before any scoped path is touched. Pi loads extensions through jiti\n // with `moduleCache: false`, so this extension gets its OWN instance of\n // `shared/paths.ts` - the scope the surrounding runner process adopted is not\n // visible here, and has to be read from the environment again.\n adoptSessionScopeFromEnv();\n registerParentProcessGuard(pi);\n registerSteeringInbox(pi, { diagnostics });\n registerToolBudget(\n pi,\n decodeToolBudgetEnv(process.env[TOOL_BUDGET_ENV], { allowZero: process.env[TOOL_BUDGET_ZERO_AUTH_ENV] === '1' }),\n diagnostics,\n );\n // One explicit graph for this whole child registration. Building another\n // graph inside an individual resolver would duplicate scheduler, reporting,\n // and intercom state in the same process.\n const runtime = createTeamPromptRuntime();\n registerRunnerLifecycle(pi, runtime);\n cordis.effect(\n () => () => {\n runtime.pollScheduler.stop();\n runtime.terminalPersistence.dispose();\n },\n `${PROMPT_RUNTIME_SOURCE}/runner`,\n );\n\n const teamChannels = runtime.teamChannel;\n let teamRuntime: ReturnType<typeof teamChannels.createRuntime> | undefined;\n\n onEvent(pi, 'session_start', () => {\n teamRuntime?.dispose();\n teamRuntime = teamChannels.createRuntime(pi);\n teamRuntime.bindChildFromEnvironment();\n });\n cordis.effect(\n () => () => {\n teamRuntime?.dispose();\n teamRuntime = undefined;\n },\n `${PROMPT_RUNTIME_SOURCE}/channel`,\n );\n onEvent(pi, 'agent_start', () => {\n refreshChildToolDiagnostic(pi);\n });\n // `agent_end` intentionally does not drain outstanding work here. See the\n // module doc's \"WHAT IS DELIBERATELY NOT WIRED YET\" for why.\n\n const structuredOutputPath = process.env[STRUCTURED_OUTPUT_CAPTURE_ENV];\n const structuredSchemaPath = process.env[STRUCTURED_OUTPUT_SCHEMA_ENV];\n if (structuredOutputPath && structuredSchemaPath) {\n const schema = JSON.parse(fs.readFileSync(structuredSchemaPath, 'utf-8')) as JsonSchemaObject;\n const parameters = createStructuredOutputToolParameters(schema);\n const validator = new StructuredOutputValidator();\n const registerTool = (\n pi.registerTool as unknown as (tool: {\n name: string;\n label: string;\n description: string;\n parameters: unknown;\n execute: (_id: string, params: { value: unknown }) => Promise<unknown>;\n }) => void\n ).bind(pi);\n registerTool({\n name: 'structured_output',\n label: 'Structured Output',\n description: 'Submit the required final structured output for this subagent step. This terminates the step.',\n parameters: parameters as never,\n async execute(_id: string, params: { value: unknown }) {\n const validation = await validator.validateValue(schema, params.value);\n if (validation.status === 'invalid') {\n throw new Error(`Structured output validation failed: ${validation.message}`);\n }\n fs.mkdirSync(path.dirname(structuredOutputPath), { recursive: true });\n fs.writeFileSync(structuredOutputPath, JSON.stringify(params.value), { mode: 0o600 });\n return {\n content: [{ type: 'text', text: 'Structured output captured.' }],\n details: { path: structuredOutputPath },\n terminate: true,\n };\n },\n });\n }\n\n onEvent<{ messages: unknown[] }>(pi, 'context', (event) => {\n const messages = stripParentOnlySubagentMessages(event.messages);\n if (messages === event.messages) return undefined;\n return { messages };\n });\n\n onEvent<{ systemPrompt: string }>(pi, 'before_agent_start', async (event) => {\n const intercomSessionName = process.env[SUBAGENT_INTERCOM_SESSION_NAME_ENV]?.trim();\n if (intercomSessionName && typeof pi.setSessionName === 'function') {\n pi.setSessionName(intercomSessionName);\n }\n\n const inheritProjectContext = readBooleanEnv(INHERIT_PROJECT_CONTEXT_ENV);\n const inheritSkills = readBooleanEnv(INHERIT_SKILLS_ENV);\n const fanoutChild = readBooleanEnv(SUBAGENT_FANOUT_CHILD_ENV);\n let rewritten = event.systemPrompt;\n if (inheritProjectContext !== undefined || inheritSkills !== undefined || fanoutChild !== undefined) {\n rewritten = rewriteSubagentPrompt(event.systemPrompt, {\n inheritProjectContext: inheritProjectContext ?? true,\n inheritSkills: inheritSkills ?? true,\n fanoutChild: fanoutChild === true,\n });\n }\n if (rewritten === event.systemPrompt) return;\n return { systemPrompt: rewritten };\n });\n}\n\ninterface PromptRuntimePluginConfig {\n readonly pi: ExtensionAPI;\n readonly diagnostics?: PromptRuntimeDiagnostics;\n}\n\nfunction promptRuntimePlugin(cordis: Context, config: PromptRuntimePluginConfig): void {\n installSubagentPromptRuntime(cordis, config.pi, config.diagnostics);\n}\n\n/** Private child-process Pi factory, mounted into the shared or standalone Cordis host. */\nexport async function registerSubagentPromptRuntime(\n pi: ExtensionAPI,\n diagnostics?: PromptRuntimeDiagnostics,\n): Promise<void> {\n const connection = await connectDoomCordisHost(pi, PROMPT_RUNTIME_SOURCE);\n const fiber = connection.root.plugin(promptRuntimePlugin, { pi, ...(diagnostics ? { diagnostics } : {}) });\n try {\n await fiber;\n } catch (error) {\n await fiber.dispose();\n await connection.dispose();\n throw error;\n }\n\n let disposal: Promise<void> | undefined;\n pi.on(\n 'session_shutdown',\n () =>\n (disposal ??= (async () => {\n try {\n await fiber.dispose();\n } finally {\n await connection.dispose();\n }\n })()),\n );\n}\n"],"mappings":"yqBA4GA,MACM,EAAiC,mBACjC,EAAoC,6EACpC,EAAwC,uEACxC,EAA+B,iEAC/B,EAAiC,gDACjC,EAAoC,kCACpC,EACJ,mIACI,EAAwB,wCA6C9B,SAAgB,GAA2D,CACzE,MAAO,CAAE,mBAAoB,EAAG,YAAa,EAAG,mBAAoB,CAAE,CACxE,CAEA,MAAM,EAAiC,CACrC,8DACA,yGACA,+GACF,CAAC,CAAC,KAAK;CAAI,EAEE,EAAmC,CAC9C,uGACA,8FACA,yIACA,uMACF,CAAC,CAAC,KAAK;CAAI,EAEE,EAAuC,CAClD,yDACA,mGACA,yFACA,mHACA,oIACA,CACF,CAAC,CAAC,KAAK;CAAI,EAEE,EAAqC,CAChD,uFACA,kGACA,8FACA,uIACA,uEACA,oIACA,CACF,CAAC,CAAC,KAAK;CAAI,EAiBX,SAAS,EACP,EACA,EACA,EACM,CACN,EAAI,GAAiG,KACnG,EACA,EACA,CACF,CACF,CAEA,SAAS,GAAyB,EAAiB,EAAsB,CACvE,OAAW,OAAO,cAAc,EAAI,QAAQ,CAAC,CAAC,KAAK,CAAO,CAC5D,CAQA,SAAgB,EACd,EACA,EACoB,CACpB,GAAI,EAAkC,KAAK,CAAO,GAAK,EAAsC,KAAK,CAAO,EACvG,OAAO,EAEJ,KAA+B,KAAK,CAAO,EAShD,OAPE,EAA6B,KAAK,CAAO,GACzC,EAA+B,KAAK,CAAO,GAC3C,EAAkC,KAAK,CAAO,GAC9C,4CAA4C,KAAK,CAAO,GAInD,EAAoB,KAAM,GAAQ,GAAyB,EAAS,CAAG,CAAC,EAFtE,EAIL,IAAA,EACN,CAEA,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AiB,GAChC,YAAa,IAAgB,EAC/B,CAAC,GAEC,IAAc,EAAM,aACxB,MAAO,CAAE,aAAc,CAAU,CACnC,CAAC,CACH,CAOA,SAAS,GAAoB,EAAiB,EAAyC,CACrF,EAA6B,EAAQ,EAAO,GAAI,EAAO,WAAW,CACpE,CAGA,eAAsB,GACpB,EACA,EACe,CACf,IAAM,EAAa,MAAA,EAAMuB,EAAAA,sBAAAA,CAAsB,EAAI,CAAqB,EAClE,EAAQ,EAAW,KAAK,OAAO,GAAqB,CAAE,KAAI,GAAI,EAAc,CAAE,aAAY,EAAI,CAAC,CAAG,CAAC,EACzG,GAAI,CACF,MAAM,CACR,OAAS,EAAO,CAGd,MAFA,MAAM,EAAM,QAAQ,EACpB,MAAM,EAAW,QAAQ,EACnB,CACR,CAEA,IAAI,EACJ,EAAG,GACD,uBAEG,KAAc,SAAY,CACzB,GAAI,CACF,MAAM,EAAM,QAAQ,CACtB,QAAU,CACR,MAAM,EAAW,QAAQ,CAC3B,CACF,EAAA,CAAG,CACP,CACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"subagentPromptRuntime.d.cts","names":[],"sources":["../../../../../src/adapters/pi/extensions/subagentPromptRuntime.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"subagentPromptRuntime.d.cts","names":[],"sources":["../../../../../src/adapters/pi/extensions/subagentPromptRuntime.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAsJiB;;EAEf;;EAEA;;EAEA;;EAEA;;;iBAq2BoB,8BACpB,IAAI,cACJ,cAAc,2BACb"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"subagentPromptRuntime.d.mts","names":[],"sources":["../../../../../src/adapters/pi/extensions/subagentPromptRuntime.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"subagentPromptRuntime.d.mts","names":[],"sources":["../../../../../src/adapters/pi/extensions/subagentPromptRuntime.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAsJiB;;EAEf;;EAEA;;EAEA;;EAEA;;;iBAq2BoB,8BACpB,IAAI,cACJ,cAAc,2BACb"}
|