@xzzpig/pi-subagents 0.24.2 → 0.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +22 -0
- package/bundle/agent-management.js +4 -4
- package/bundle/agents.js +3 -3
- package/bundle/child-tool-plan.js +2 -2
- package/bundle/chunk-34TUUBRN.js +1107 -0
- package/bundle/{chunk-SW2VMNIU.js → chunk-5OD3OWTE.js} +2 -2
- package/bundle/{chunk-XWWUDWUW.js → chunk-5YEOWNSD.js} +371 -135
- package/bundle/{chunk-EUPJB4S7.js → chunk-5Z7JAORM.js} +196 -1219
- package/bundle/{chunk-LCDJWBVM.js → chunk-66JNFRFS.js} +1 -1
- package/bundle/{chunk-4UH4WS4G.js → chunk-6MNRKUHY.js} +23 -12
- package/bundle/{chunk-ED55MIC2.js → chunk-CGFF4WA3.js} +42 -19
- package/bundle/{chunk-TMHVDPYW.js → chunk-DLVPMML3.js} +263 -154
- package/bundle/chunk-HXRB42AF.js +108 -0
- package/bundle/{chunk-355ECEP2.js → chunk-IH7LQVEE.js} +29 -14
- package/bundle/{chunk-CYY5UMJU.js → chunk-IJWITCC6.js} +411 -249
- package/bundle/{chunk-RU522D5W.js → chunk-IKFKH5EL.js} +369 -50
- package/bundle/{chunk-Z6TFJ6BR.js → chunk-INWSUNI6.js} +1 -1
- package/bundle/{chunk-JEA2ZKUA.js → chunk-IUDEI6FJ.js} +35 -200
- package/bundle/{chunk-WW76JRIX.js → chunk-JAXVBXGF.js} +1 -1
- package/bundle/{chunk-ICNYIALB.js → chunk-JH5H4CYJ.js} +784 -474
- package/bundle/{chunk-35GII5EF.js → chunk-JWFLPSTP.js} +41 -117
- package/bundle/{chunk-224WMDIV.js → chunk-KCJFGKVK.js} +350 -123
- package/bundle/{chunk-RB4GELQA.js → chunk-LPJEKHOY.js} +1 -1
- package/bundle/chunk-LYKG4FKH.js +523 -0
- package/bundle/{chunk-X6LOM3Z4.js → chunk-LZ3HBDTR.js} +161 -78
- package/bundle/{chunk-FG6SQJAR.js → chunk-OGPOCGWX.js} +24 -6
- package/bundle/{chunk-BQ2OAB4Q.js → chunk-OSVXFWPG.js} +67 -30
- package/bundle/{chunk-FJWI64H7.js → chunk-RMSABUN3.js} +27 -13
- package/bundle/{chunk-H36HBZB2.js → chunk-SJPABBZG.js} +2 -2
- package/bundle/{chunk-3U633XDZ.js → chunk-U3ZDUUTM.js} +11 -3
- package/bundle/{chunk-LVWU2HOO.js → chunk-ULGMXABL.js} +16 -7
- package/bundle/{chunk-WPW4V6HM.js → chunk-W7ZA6TYD.js} +2 -2
- package/bundle/{chunk-V2KFIGFH.js → chunk-XAC2XNAP.js} +503 -304
- package/bundle/{chunk-O4D5PBVI.js → chunk-YWXILP5N.js} +3 -2
- package/bundle/control-channel.js +2 -2
- package/bundle/index.js +1 -1
- package/bundle/intercom-bridge.js +2 -2
- package/bundle/preflight.js +12 -10
- package/bundle/project-panes.js +3 -3
- package/bundle/workflow-resources.js +1 -1
- package/docs/agents.md +27 -6
- package/docs/configuration.md +20 -8
- package/docs/extension-api.md +18 -1
- package/docs/models.md +6 -2
- package/docs/observability.md +2 -0
- package/docs/tool-reference.md +7 -1
- package/docs/workflows.md +30 -2
- package/package.json +2 -2
- package/skills/pi-subagents/SKILL.md +15 -6
- package/skills/pi-subagents/references/prompting-and-roles.md +1 -0
- package/src/agents/agent-management.d.ts +1 -0
- package/src/agents/agent-management.js +46 -18
- package/src/agents/agent-memory.d.ts +1 -4
- package/src/agents/agent-memory.js +1 -4
- package/src/agents/agent-serializer.d.ts +2 -0
- package/src/agents/agent-serializer.js +1 -1
- package/src/agents/agents.d.ts +2 -3
- package/src/agents/agents.js +46 -20
- package/src/agents/frontmatter.js +1 -8
- package/src/agents/global-npm-root.d.ts +1 -0
- package/src/agents/global-npm-root.js +11 -3
- package/src/agents/skills.d.ts +0 -3
- package/src/agents/skills.js +0 -3
- package/src/api/preflight.d.ts +3 -1
- package/src/api/preflight.js +2 -0
- package/src/extension/config.d.ts +1 -0
- package/src/extension/config.js +13 -1
- package/src/extension/herdr-pi-bridge.js +10 -2
- package/src/extension/index.d.ts +0 -13
- package/src/extension/index.js +51 -37
- package/src/extension/public-execution.d.ts +1 -0
- package/src/extension/public-execution.js +4 -0
- package/src/extension/reply-workflow-script.js +24 -4
- package/src/extension/schemas.d.ts +12 -3
- package/src/extension/schemas.js +7 -3
- package/src/extension/session-switch.d.ts +25 -0
- package/src/extension/session-switch.js +138 -0
- package/src/extension/subagent-guide.d.ts +1 -1
- package/src/extension/subagent-guide.js +1 -1
- package/src/extension/subagent-launch-tool.d.ts +25 -0
- package/src/extension/subagent-launch-tool.js +48 -0
- package/src/extension/tool-activation.js +55 -15
- package/src/extension/tool-description.d.ts +1 -1
- package/src/extension/tool-description.js +14 -8
- package/src/inspectors/herdr/actions.d.ts +0 -1
- package/src/inspectors/herdr/actions.js +0 -1
- package/src/inspectors/session-roots-codec.d.ts +0 -1
- package/src/inspectors/session-roots-codec.js +0 -1
- package/src/inspectors/tmux/actions.d.ts +0 -1
- package/src/inspectors/tmux/actions.js +0 -1
- package/src/integrations/herdr-status.js +3 -8
- package/src/intercom/native-supervisor-channel.js +65 -9
- package/src/runs/background/async-execution.d.ts +7 -10
- package/src/runs/background/async-execution.js +66 -29
- package/src/runs/background/async-job-tracker.js +12 -0
- package/src/runs/background/async-resume.d.ts +2 -1
- package/src/runs/background/async-resume.js +114 -40
- package/src/runs/background/async-retention.d.ts +0 -2
- package/src/runs/background/async-retention.js +17 -6
- package/src/runs/background/async-status.d.ts +2 -0
- package/src/runs/background/async-status.js +4 -0
- package/src/runs/background/auto-drain.js +2 -1
- package/src/runs/background/boot-id.d.ts +1 -3
- package/src/runs/background/boot-id.js +1 -3
- package/src/runs/background/completion-batcher.d.ts +3 -4
- package/src/runs/background/completion-batcher.js +2 -3
- package/src/runs/background/control-channel.d.ts +0 -6
- package/src/runs/background/control-channel.js +0 -6
- package/src/runs/background/fleet-view.js +2 -3
- package/src/runs/background/notify.d.ts +0 -2
- package/src/runs/background/notify.js +0 -2
- package/src/runs/background/result-watcher.d.ts +1 -0
- package/src/runs/background/result-watcher.js +59 -29
- package/src/runs/background/resume-guidance.js +4 -2
- package/src/runs/background/retained-children.js +2 -1
- package/src/runs/background/run-child-session.d.ts +2 -3
- package/src/runs/background/run-child-session.js +5 -8
- package/src/runs/background/run-status.js +9 -7
- package/src/runs/background/runner-aliases.js +15 -0
- package/src/runs/background/scheduled-runs.d.ts +3 -1
- package/src/runs/background/scheduled-runs.js +13 -16
- package/src/runs/background/steering.d.ts +2 -11
- package/src/runs/background/steering.js +11 -6
- package/src/runs/background/subagent-runner.d.ts +2 -6
- package/src/runs/background/subagent-runner.js +88 -70
- package/src/runs/background/subagent-wait.js +12 -15
- package/src/runs/background/wait-config.d.ts +2 -0
- package/src/runs/background/wait-config.js +17 -3
- package/src/runs/background/wait-subscriptions.js +124 -12
- package/src/runs/background/wait-tool.js +4 -2
- package/src/runs/background/workflow-terminal-proof.d.ts +0 -1
- package/src/runs/background/workflow-terminal-proof.js +0 -1
- package/src/runs/foreground/async-steering-action.js +24 -9
- package/src/runs/foreground/async-stop-action.d.ts +1 -1
- package/src/runs/foreground/async-stop-action.js +9 -1
- package/src/runs/foreground/execution.d.ts +0 -3
- package/src/runs/foreground/execution.js +56 -24
- package/src/runs/foreground/prompt-audit.js +1 -0
- package/src/runs/foreground/subagent-executor.d.ts +5 -10
- package/src/runs/foreground/subagent-executor.js +164 -49
- package/src/runs/shared/acceptance.js +69 -26
- package/src/runs/shared/async-status-projection.d.ts +2 -0
- package/src/runs/shared/async-status-projection.js +10 -0
- package/src/runs/shared/child-commands.js +15 -2
- package/src/runs/shared/child-hooks.d.ts +1 -7
- package/src/runs/shared/child-hooks.js +13 -5
- package/src/runs/shared/child-launch.js +6 -2
- package/src/runs/shared/child-runtime-config.d.ts +0 -1
- package/src/runs/shared/child-session.d.ts +6 -5
- package/src/runs/shared/child-session.js +85 -38
- package/src/runs/shared/child-tool-plan.d.ts +0 -1
- package/src/runs/shared/child-tool-plan.js +0 -1
- package/src/runs/shared/claude-code-adapter.js +11 -0
- package/src/runs/shared/external-cli-contract.d.ts +49 -0
- package/src/runs/shared/external-cli-contract.js +18 -13
- package/src/runs/shared/external-cli-runner.js +26 -6
- package/src/runs/shared/herdr-connection.js +2 -1
- package/src/runs/shared/herdr-pane-host.d.ts +2 -2
- package/src/runs/shared/herdr-pane-host.js +17 -1
- package/src/runs/shared/herdr-placed-run.js +51 -24
- package/src/runs/shared/lane-metadata.d.ts +0 -1
- package/src/runs/shared/lane-metadata.js +0 -1
- package/src/runs/shared/mcp-config-sources.d.ts +4 -1
- package/src/runs/shared/mcp-config-sources.js +1 -1
- package/src/runs/shared/mcp-direct-tool-allowlist.d.ts +0 -3
- package/src/runs/shared/mcp-direct-tool-allowlist.js +26 -17
- package/src/runs/shared/mcp-direct-tool-grant.js +8 -1
- package/src/runs/shared/model-resolution-diagnostic.d.ts +0 -1
- package/src/runs/shared/model-resolution.d.ts +20 -5
- package/src/runs/shared/model-resolution.js +55 -50
- package/src/runs/shared/model-scope.d.ts +1 -5
- package/src/runs/shared/model-scope.js +1 -5
- package/src/runs/shared/mutation-evidence.d.ts +1 -1
- package/src/runs/shared/mutation-evidence.js +52 -7
- package/src/runs/shared/nested-events.d.ts +1 -0
- package/src/runs/shared/nested-events.js +1 -1
- package/src/runs/shared/parallel-utils.d.ts +0 -1
- package/src/runs/shared/permissions.js +5 -3
- package/src/runs/shared/placement-host.d.ts +5 -1
- package/src/runs/shared/rex-pane-host.d.ts +0 -1
- package/src/runs/shared/rex-pane-host.js +0 -2
- package/src/runs/shared/run-launch-folder.d.ts +12 -0
- package/src/runs/shared/run-launch-folder.js +21 -0
- package/src/runs/shared/runner-launcher.d.ts +12 -1
- package/src/runs/shared/runner-launcher.js +16 -0
- package/src/runs/shared/single-output.d.ts +3 -3
- package/src/runs/shared/single-output.js +5 -3
- package/src/runs/shared/structured-output.d.ts +8 -0
- package/src/runs/shared/structured-output.js +40 -5
- package/src/runs/shared/subagent-prompt-runtime.d.ts +0 -1
- package/src/runs/shared/subagent-prompt-runtime.js +18 -4
- package/src/runs/shared/supervisor-wait-timer.d.ts +16 -0
- package/src/runs/shared/supervisor-wait-timer.js +61 -0
- package/src/runs/shared/tool-timeout.js +2 -1
- package/src/runs/shared/worktree-cleanup-plan.d.ts +0 -1
- package/src/runs/shared/worktree-cleanup-plan.js +0 -1
- package/src/runs/shared/worktree.d.ts +3 -0
- package/src/runs/shared/worktree.js +20 -0
- package/src/shared/artifacts.d.ts +1 -0
- package/src/shared/artifacts.js +132 -22
- package/src/shared/capacity-resilient-json.d.ts +1 -1
- package/src/shared/child-cache-retention.d.ts +1 -2
- package/src/shared/child-cache-retention.js +1 -2
- package/src/shared/fleet-transcript-reader.d.ts +51 -0
- package/src/shared/fleet-transcript-reader.js +333 -0
- package/src/shared/formatters.d.ts +0 -18
- package/src/shared/formatters.js +0 -18
- package/src/shared/pruned-fork.js +2 -2
- package/src/shared/reported-progress.d.ts +1 -0
- package/src/shared/reported-progress.js +12 -0
- package/src/shared/session-succession.d.ts +16 -1
- package/src/shared/session-succession.js +41 -2
- package/src/shared/session-warnings.d.ts +7 -0
- package/src/shared/session-warnings.js +26 -0
- package/src/shared/settings.d.ts +0 -23
- package/src/shared/settings.js +3 -35
- package/src/shared/status-format.d.ts +1 -0
- package/src/shared/status-format.js +1 -1
- package/src/shared/types.d.ts +108 -59
- package/src/shared/types.js +0 -12
- package/src/shared/utils.d.ts +3 -15
- package/src/shared/utils.js +4 -22
- package/src/shared/wait-tool-name.d.ts +8 -0
- package/src/shared/wait-tool-name.js +13 -0
- package/src/slash/slash-commands.js +2 -1
- package/src/slash/subagent-cost.d.ts +3 -2
- package/src/slash/subagent-cost.js +22 -3
- package/src/slash/subagents-admin.js +0 -1
- package/src/tui/fleet-status.d.ts +0 -5
- package/src/tui/fleet-status.js +4 -24
- package/src/tui/fleet.js +6 -4
- package/src/tui/render.d.ts +0 -9
- package/src/tui/render.js +194 -68
- package/src/tui/subagent-messages.js +3 -2
- package/src/watchdog/model-selection.js +2 -2
- package/src/watchdog/permission-arbiter.js +1 -0
- package/src/watchdog/register-child.d.ts +2 -3
- package/src/watchdog/register-child.js +2 -3
- package/src/watchdog/review.d.ts +0 -5
- package/src/watchdog/review.js +4 -3
- package/src/watchdog/turn-delta.js +2 -1
- package/src/workflows/scripted-workflow.d.ts +2 -0
- package/src/workflows/scripted-workflow.js +344 -59
- package/src/workflows/structured-workflow-scripts.d.ts +4 -3
- package/src/workflows/structured-workflow-scripts.js +32 -11
- package/src/workflows/workflow-launch-record.d.ts +15 -6
- package/src/workflows/workflow-launch-record.js +30 -12
- package/src/workflows/workflow-receipt.js +36 -53
- package/src/workflows/workflow-resources.js +4 -4
- package/src/workflows/workflow-resume-claim.d.ts +2 -0
- package/src/workflows/workflow-resume-claim.js +3 -3
- package/src/workflows/workflow-resume.d.ts +1 -1
- package/src/workflows/workflow-resume.js +13 -8
- package/src/workflows/workflow-script-worker.d.ts +13 -0
- package/src/workflows/workflow-script-worker.js +81 -0
- package/workflow-script-process.cjs +36 -0
- package/workflow-script-worker.cjs +4 -1
- package/bundle/chunk-U4ODUYAG.js +0 -235
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
createHerdrClient,
|
|
3
3
|
detectHerdr
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-SJPABBZG.js";
|
|
5
5
|
import {
|
|
6
6
|
MainWatchdogRuntime,
|
|
7
7
|
SUBAGENT_OPTION_KEYS,
|
|
@@ -15,24 +15,28 @@ import {
|
|
|
15
15
|
startWatchdogDiffBaselineCapture,
|
|
16
16
|
writeUserWatchdogEnabled,
|
|
17
17
|
writeWatchdogModelSettings
|
|
18
|
-
} from "./chunk-
|
|
18
|
+
} from "./chunk-5Z7JAORM.js";
|
|
19
19
|
import {
|
|
20
20
|
resolveGitRepositoryIdentity
|
|
21
|
-
} from "./chunk-
|
|
21
|
+
} from "./chunk-ULGMXABL.js";
|
|
22
22
|
import {
|
|
23
23
|
listAsyncRuns,
|
|
24
|
-
ownsRun,
|
|
25
24
|
parallelHandoffPath,
|
|
26
25
|
parseWorkflowChildSummary,
|
|
27
26
|
readAsyncRecoveryDescriptor,
|
|
27
|
+
readWorkflowLaunchRecord,
|
|
28
28
|
resolveRetainedWorktreeCwd
|
|
29
|
-
} from "./chunk-
|
|
29
|
+
} from "./chunk-DLVPMML3.js";
|
|
30
|
+
import {
|
|
31
|
+
ownsRun
|
|
32
|
+
} from "./chunk-HXRB42AF.js";
|
|
30
33
|
import {
|
|
31
34
|
deepFreezeWorkflowArgs,
|
|
32
35
|
normalizeWorkflowArgs
|
|
33
|
-
} from "./chunk-
|
|
36
|
+
} from "./chunk-RMSABUN3.js";
|
|
34
37
|
import {
|
|
35
38
|
HOST_STEP_MAX_COUNT,
|
|
39
|
+
REQUIRE_LAUNCHER_SHAPE_ERROR,
|
|
36
40
|
WORKFLOW_STOP_CAUSE_OWNER_EXITED,
|
|
37
41
|
WORKFLOW_STOP_CAUSE_RUNTIME_REPLACED,
|
|
38
42
|
assertUniqueHostStepIds,
|
|
@@ -54,17 +58,17 @@ import {
|
|
|
54
58
|
resolveMissionStoreLocation,
|
|
55
59
|
validateMissionId,
|
|
56
60
|
workflowRunParamsFingerprint
|
|
57
|
-
} from "./chunk-
|
|
61
|
+
} from "./chunk-JH5H4CYJ.js";
|
|
58
62
|
import {
|
|
59
63
|
getProjectSubagentsDir
|
|
60
|
-
} from "./chunk-
|
|
64
|
+
} from "./chunk-LYKG4FKH.js";
|
|
61
65
|
import {
|
|
62
66
|
requestAsyncCommand,
|
|
63
67
|
watchAsyncControlInbox
|
|
64
|
-
} from "./chunk-
|
|
68
|
+
} from "./chunk-LPJEKHOY.js";
|
|
65
69
|
import {
|
|
66
70
|
supervisorChannelDir
|
|
67
|
-
} from "./chunk-
|
|
71
|
+
} from "./chunk-IH7LQVEE.js";
|
|
68
72
|
import {
|
|
69
73
|
ExternalJobProviderError,
|
|
70
74
|
getExternalJobProvider,
|
|
@@ -72,6 +76,7 @@ import {
|
|
|
72
76
|
validateExternalJobResult
|
|
73
77
|
} from "./chunk-YYREO77V.js";
|
|
74
78
|
import {
|
|
79
|
+
EXTERNAL_CLI_ADAPTER_SAFETY,
|
|
75
80
|
PI_CODING_AGENT_PACKAGE,
|
|
76
81
|
PI_CODING_AGENT_PACKAGE_ROOT_ENV,
|
|
77
82
|
PROMPT_REDACTED,
|
|
@@ -84,8 +89,11 @@ import {
|
|
|
84
89
|
getAgentDir,
|
|
85
90
|
getConfigDirName,
|
|
86
91
|
getSupportedThinkingLevels,
|
|
92
|
+
isCodeOwnedExternalCliAdapterId,
|
|
93
|
+
knownModelProviders,
|
|
87
94
|
normalizeModelSegment,
|
|
88
95
|
normalizeWorkflowLaneMetadata,
|
|
96
|
+
parseAcceptanceReport,
|
|
89
97
|
readStatus,
|
|
90
98
|
resolveEffectiveThinking,
|
|
91
99
|
resolveHostPiPackageRoot,
|
|
@@ -94,10 +102,11 @@ import {
|
|
|
94
102
|
splitKnownThinkingSuffix,
|
|
95
103
|
toModelInfo,
|
|
96
104
|
validateExecutionAcceptance,
|
|
105
|
+
waitToolName,
|
|
97
106
|
withFileLease,
|
|
98
107
|
writeAtomicJson,
|
|
99
108
|
writePrivateAtomicJson
|
|
100
|
-
} from "./chunk-
|
|
109
|
+
} from "./chunk-XAC2XNAP.js";
|
|
101
110
|
import {
|
|
102
111
|
DIRS,
|
|
103
112
|
INTERCOM_DETACH_REQUEST_EVENT,
|
|
@@ -644,7 +653,7 @@ var DEFAULT_FAST_TOOL_TIMEOUT_TOOLS = /* @__PURE__ */ new Set([
|
|
|
644
653
|
]);
|
|
645
654
|
var TOOL_TIMEOUT_EXEMPT_TOOLS = /* @__PURE__ */ new Set(["contact_supervisor", "intercom", "bg_wait"]);
|
|
646
655
|
function isToolTimeoutExempt(toolName) {
|
|
647
|
-
return toolName !== void 0 && TOOL_TIMEOUT_EXEMPT_TOOLS.has(toolName);
|
|
656
|
+
return toolName !== void 0 && (TOOL_TIMEOUT_EXEMPT_TOOLS.has(toolName) || toolName === waitToolName());
|
|
648
657
|
}
|
|
649
658
|
function defaultToolTimeoutMs(toolName) {
|
|
650
659
|
return toolName !== void 0 && DEFAULT_FAST_TOOL_TIMEOUT_TOOLS.has(toolName) ? DEFAULT_FAST_TOOL_TIMEOUT_MS : void 0;
|
|
@@ -1465,6 +1474,9 @@ function parseScheduleInterval(every) {
|
|
|
1465
1474
|
function timestamp(value) {
|
|
1466
1475
|
return new Date(value).toISOString();
|
|
1467
1476
|
}
|
|
1477
|
+
function errorText3(error2) {
|
|
1478
|
+
return error2 instanceof Error ? error2.message : String(error2);
|
|
1479
|
+
}
|
|
1468
1480
|
function validateScheduleId(id) {
|
|
1469
1481
|
if (!SCHEDULE_ID.test(id)) throw new Error("Schedule id must be 1-64 characters and contain only letters, numbers, '.', '_', or '-'.");
|
|
1470
1482
|
return id;
|
|
@@ -1635,7 +1647,7 @@ function parseSchedule(value, file) {
|
|
|
1635
1647
|
if (record.trigger.kind === "once") {
|
|
1636
1648
|
if (typeof record.trigger.at !== "string" || record.trigger.nextRunAt !== void 0 && typeof record.trigger.nextRunAt !== "string") throw new Error(`Schedule record '${file}' has an invalid one-shot trigger.`);
|
|
1637
1649
|
} else if (record.trigger.kind === "interval") {
|
|
1638
|
-
if (typeof record.trigger.every !== "string" || typeof record.trigger.everyMs !== "number" || typeof record.trigger.anchorAt !== "string" || typeof record.trigger.nextRunAt !== "string") throw new Error(`Schedule record '${file}' has an invalid interval trigger.`);
|
|
1650
|
+
if (typeof record.trigger.every !== "string" || typeof record.trigger.everyMs !== "number" || typeof record.trigger.anchorAt !== "string" || (!record.paused || record.trigger.nextRunAt !== void 0) && typeof record.trigger.nextRunAt !== "string") throw new Error(`Schedule record '${file}' has an invalid interval trigger.`);
|
|
1639
1651
|
} else if (record.trigger.kind === "calendar") {
|
|
1640
1652
|
restoreCalendarTrigger(record.trigger);
|
|
1641
1653
|
} else throw new Error(`Schedule record '${file}' has an unsupported trigger.`);
|
|
@@ -1906,7 +1918,7 @@ var ScheduledRunManager = class {
|
|
|
1906
1918
|
try {
|
|
1907
1919
|
ids = store.ids();
|
|
1908
1920
|
} catch (error2) {
|
|
1909
|
-
|
|
1921
|
+
this.deps.reportWarning?.(`Failed to inspect schedule store '${store.root}': ${errorText3(error2)}`, `schedule-store:${store.root}:${errorText3(error2)}`);
|
|
1910
1922
|
continue;
|
|
1911
1923
|
}
|
|
1912
1924
|
for (const id of ids) {
|
|
@@ -1918,7 +1930,7 @@ var ScheduledRunManager = class {
|
|
|
1918
1930
|
this.finishRun(store, schedule, run, data.success === true, typeof data.summary === "string" ? data.summary : void 0);
|
|
1919
1931
|
return;
|
|
1920
1932
|
} catch (error2) {
|
|
1921
|
-
|
|
1933
|
+
this.deps.reportWarning?.(`Failed to inspect schedule '${id}' in '${store.root}': ${errorText3(error2)}`, `schedule-record:${store.root}:${id}`);
|
|
1922
1934
|
}
|
|
1923
1935
|
}
|
|
1924
1936
|
}
|
|
@@ -2010,6 +2022,7 @@ Mission: ${schedule.target.missionId}`}`, [schedule]);
|
|
|
2010
2022
|
const schedule = this.resolve(params);
|
|
2011
2023
|
if (schedule.paused === paused) return textResult(`Schedule ${schedule.id} is already ${paused ? "paused" : "active"}.`, [schedule]);
|
|
2012
2024
|
schedule.paused = paused;
|
|
2025
|
+
if (!paused && schedule.trigger.kind === "interval" && schedule.trigger.nextRunAt === void 0) schedule.trigger.nextRunAt = timestamp(this.now() + schedule.trigger.everyMs);
|
|
2013
2026
|
schedule.updatedAt = timestamp(this.now());
|
|
2014
2027
|
this.requireStore().write(schedule);
|
|
2015
2028
|
this.requireStore().appendEvent(schedule, paused ? "schedule.paused" : "schedule.resumed");
|
|
@@ -2536,12 +2549,29 @@ function parseExternalCliMachine(value, label) {
|
|
|
2536
2549
|
const unknownRemoteGit = Object.keys(remoteGit).filter((field) => !["head", "branch", "dirty"].includes(field));
|
|
2537
2550
|
if (unknownRemoteGit.length > 0 || remoteGit.head !== void 0 && (typeof remoteGit.head !== "string" || !remoteGit.head.trim()) || remoteGit.branch !== void 0 && (typeof remoteGit.branch !== "string" || !remoteGit.branch.trim()) || remoteGit.dirty !== void 0 && typeof remoteGit.dirty !== "boolean") throw new Error(`${label}.machine.remoteGit is invalid.`);
|
|
2538
2551
|
}
|
|
2552
|
+
function parseCodeOwnedSafety(value, adapter, label) {
|
|
2553
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`${label}.safety is missing.`);
|
|
2554
|
+
const safety = value;
|
|
2555
|
+
const profile = EXTERNAL_CLI_ADAPTER_SAFETY[adapter];
|
|
2556
|
+
const unknownSafety = Object.keys(safety).filter((field) => !Object.hasOwn(profile, field));
|
|
2557
|
+
if (unknownSafety.length > 0) throw new Error(`${label}.safety has unsupported fields: ${unknownSafety.join(", ")}.`);
|
|
2558
|
+
if (Object.entries(profile).some(([field, expected]) => safety[field] !== expected)) throw new Error(`${label}.safety is invalid.`);
|
|
2559
|
+
}
|
|
2560
|
+
function parseExternalCliSafetySource(value, label) {
|
|
2561
|
+
if (value === void 0) return false;
|
|
2562
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`${label}.safetySource must be an object.`);
|
|
2563
|
+
const source = value;
|
|
2564
|
+
const unknownSource = Object.keys(source).filter((field) => !["measured", "command"].includes(field));
|
|
2565
|
+
if (unknownSource.length > 0) throw new Error(`${label}.safetySource has unsupported fields: ${unknownSource.join(", ")}.`);
|
|
2566
|
+
if (source.measured !== false || source.command !== void 0 && (typeof source.command !== "string" || !source.command.trim())) throw new Error(`${label}.safetySource is invalid.`);
|
|
2567
|
+
return true;
|
|
2568
|
+
}
|
|
2539
2569
|
function parseExternalCliReceiptMetadata(value, key, source) {
|
|
2540
2570
|
if (value === void 0) return void 0;
|
|
2541
2571
|
const label = `Invalid workflow receipt '${source}': entry '${key}' externalAdapter`;
|
|
2542
2572
|
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`${label} must be an object.`);
|
|
2543
2573
|
const metadata = value;
|
|
2544
|
-
const unknownMetadata = Object.keys(metadata).filter((field) => !["adapter", "capabilities", "machine", "safety", "outputArtifacts", "handoff", "supervisor", "nonResumableReason"].includes(field));
|
|
2574
|
+
const unknownMetadata = Object.keys(metadata).filter((field) => !["adapter", "capabilities", "machine", "safety", "safetySource", "outputArtifacts", "handoff", "supervisor", "nonResumableReason"].includes(field));
|
|
2545
2575
|
if (unknownMetadata.length > 0) throw new Error(`${label} has unsupported fields: ${unknownMetadata.join(", ")}.`);
|
|
2546
2576
|
const adapter = metadata.adapter;
|
|
2547
2577
|
if (!adapter || typeof adapter !== "object" || Array.isArray(adapter)) throw new Error(`${label}.adapter must be an object.`);
|
|
@@ -2559,47 +2589,23 @@ function parseExternalCliReceiptMetadata(value, key, source) {
|
|
|
2559
2589
|
}
|
|
2560
2590
|
if (metadata.machine !== void 0) parseExternalCliMachine(metadata.machine, label);
|
|
2561
2591
|
const safety = metadata.safety;
|
|
2562
|
-
|
|
2563
|
-
|
|
2564
|
-
const safetyRecord = safety;
|
|
2565
|
-
const unknownSafety = Object.keys(safetyRecord).filter((field) => !["sandbox", "approvalPolicy", "ephemeral"].includes(field));
|
|
2566
|
-
if (unknownSafety.length > 0) throw new Error(`${label}.safety has unsupported fields: ${unknownSafety.join(", ")}.`);
|
|
2567
|
-
if (safetyRecord.sandbox !== "read-only" || safetyRecord.approvalPolicy !== "never" || safetyRecord.ephemeral !== true) throw new Error(`${label}.safety is invalid.`);
|
|
2568
|
-
} else if (adapterRecord.id === "codex-exec-writer") {
|
|
2569
|
-
if (!safety || typeof safety !== "object" || Array.isArray(safety)) throw new Error(`${label}.safety is missing.`);
|
|
2570
|
-
const safetyRecord = safety;
|
|
2571
|
-
const unknownSafety = Object.keys(safetyRecord).filter((field) => !["access", "sandbox", "approvalPolicy", "ephemeral"].includes(field));
|
|
2572
|
-
if (unknownSafety.length > 0) throw new Error(`${label}.safety has unsupported fields: ${unknownSafety.join(", ")}.`);
|
|
2573
|
-
if (safetyRecord.access !== "workspace-write" || safetyRecord.sandbox !== "workspace-write" || safetyRecord.approvalPolicy !== "never" || safetyRecord.ephemeral !== true) throw new Error(`${label}.safety is invalid.`);
|
|
2574
|
-
} else if (adapterRecord.id === "claude-code") {
|
|
2575
|
-
if (!safety || typeof safety !== "object" || Array.isArray(safety)) throw new Error(`${label}.safety is missing.`);
|
|
2576
|
-
const safetyRecord = safety;
|
|
2577
|
-
const legacy = safetyRecord.authentication === void 0;
|
|
2578
|
-
const unknownSafety = Object.keys(safetyRecord).filter((field) => !(legacy ? ["permissionMode", "tools", "mcp", "settingSources", "sessionPersistence"] : ["access", "authentication", "permissionMode", "tools", "mcp", "settingSources", "userSettingsTrust", "sessionPersistence"]).includes(field));
|
|
2579
|
-
if (unknownSafety.length > 0) throw new Error(`${label}.safety has unsupported fields: ${unknownSafety.join(", ")}.`);
|
|
2580
|
-
if (legacy) {
|
|
2581
|
-
if (safetyRecord.permissionMode !== "plan" || safetyRecord.tools !== "none" || safetyRecord.mcp !== "empty-strict" || safetyRecord.settingSources !== "none" || safetyRecord.sessionPersistence !== false) throw new Error(`${label}.safety is invalid.`);
|
|
2582
|
-
} else if (safetyRecord.access !== "read-only" || safetyRecord.authentication !== "existing-cli-required" || safetyRecord.permissionMode !== "plan" || safetyRecord.tools !== "none" || safetyRecord.mcp !== "empty-strict" || safetyRecord.settingSources !== "user" || safetyRecord.userSettingsTrust !== "required" || safetyRecord.sessionPersistence !== false) throw new Error(`${label}.safety is invalid.`);
|
|
2583
|
-
} else if (adapterRecord.id === "claude-code-writer") {
|
|
2584
|
-
if (!safety || typeof safety !== "object" || Array.isArray(safety)) throw new Error(`${label}.safety is missing.`);
|
|
2585
|
-
const safetyRecord = safety;
|
|
2586
|
-
const unknownSafety = Object.keys(safetyRecord).filter((field) => !["access", "authentication", "permissionMode", "tools", "mcp", "settingSources", "userSettingsTrust", "sessionPersistence"].includes(field));
|
|
2587
|
-
if (unknownSafety.length > 0) throw new Error(`${label}.safety has unsupported fields: ${unknownSafety.join(", ")}.`);
|
|
2588
|
-
if (safetyRecord.access !== "workspace-write" || safetyRecord.authentication !== "existing-cli-required" || safetyRecord.permissionMode !== "acceptEdits" || safetyRecord.tools !== "Read,Write,Edit,Glob,Grep" || safetyRecord.mcp !== "empty-strict" || safetyRecord.settingSources !== "user" || safetyRecord.userSettingsTrust !== "required" || safetyRecord.sessionPersistence !== false) throw new Error(`${label}.safety is invalid.`);
|
|
2589
|
-
} else if (adapterRecord.id === "cursor-agent" || adapterRecord.id === "cursor-agent-writer") {
|
|
2590
|
-
if (!safety || typeof safety !== "object" || Array.isArray(safety)) throw new Error(`${label}.safety is missing.`);
|
|
2592
|
+
const hasSafetySource = parseExternalCliSafetySource(metadata.safetySource, label);
|
|
2593
|
+
if (adapterRecord.id === "claude-code" && !hasSafetySource && safety && typeof safety === "object" && !Array.isArray(safety) && safety.authentication === void 0) {
|
|
2591
2594
|
const safetyRecord = safety;
|
|
2592
|
-
const unknownSafety = Object.keys(safetyRecord).filter((field) => !["
|
|
2595
|
+
const unknownSafety = Object.keys(safetyRecord).filter((field) => !["permissionMode", "tools", "mcp", "settingSources", "sessionPersistence"].includes(field));
|
|
2593
2596
|
if (unknownSafety.length > 0) throw new Error(`${label}.safety has unsupported fields: ${unknownSafety.join(", ")}.`);
|
|
2594
|
-
|
|
2595
|
-
|
|
2597
|
+
if (safetyRecord.permissionMode !== "plan" || safetyRecord.tools !== "none" || safetyRecord.mcp !== "empty-strict" || safetyRecord.settingSources !== "none" || safetyRecord.sessionPersistence !== false) throw new Error(`${label}.safety is invalid.`);
|
|
2598
|
+
} else if (isCodeOwnedExternalCliAdapterId(adapterRecord.id)) {
|
|
2599
|
+
parseCodeOwnedSafety(safety, adapterRecord.id, label);
|
|
2596
2600
|
} else if (adapterRecord.id === "grok-build") {
|
|
2601
|
+
if (hasSafetySource) throw new Error(`${label}.safetySource is invalid for the legacy grok-build adapter.`);
|
|
2597
2602
|
if (!safety || typeof safety !== "object" || Array.isArray(safety)) throw new Error(`${label}.safety is missing.`);
|
|
2598
2603
|
const safetyRecord = safety;
|
|
2599
2604
|
const unknownSafety = Object.keys(safetyRecord).filter((field) => !["access", "authentication", "permissionMode", "tools", "deniedTools", "sandbox", "webSearch", "subagents", "config", "updates", "sessionPersistence"].includes(field));
|
|
2600
2605
|
if (unknownSafety.length > 0) throw new Error(`${label}.safety has unsupported fields: ${unknownSafety.join(", ")}.`);
|
|
2601
2606
|
if (safetyRecord.access !== "read-only" || safetyRecord.authentication !== "xai-api-key-required" || safetyRecord.permissionMode !== "plan" || safetyRecord.tools !== "read_file,grep,list_dir" || safetyRecord.deniedTools !== "run_terminal_cmd,search_replace,Agent,Bash,Edit,Write,MCPTool" || safetyRecord.sandbox !== "read-only" || safetyRecord.webSearch !== false || safetyRecord.subagents !== false || safetyRecord.config !== "temporary-home" || safetyRecord.updates !== "disabled" || safetyRecord.sessionPersistence !== false) throw new Error(`${label}.safety is invalid.`);
|
|
2602
|
-
} else if (
|
|
2607
|
+
} else if (hasSafetySource) throw new Error(`${label}.safetySource is invalid for the generic adapter.`);
|
|
2608
|
+
else if (safety !== void 0) throw new Error(`${label}.safety is invalid for the generic adapter.`);
|
|
2603
2609
|
const handoff = metadata.handoff;
|
|
2604
2610
|
if (!handoff || typeof handoff !== "object" || Array.isArray(handoff)) throw new Error(`${label}.handoff must be an object.`);
|
|
2605
2611
|
const handoffRecord = handoff;
|
|
@@ -2938,7 +2944,7 @@ function resolveWatchdogModelInput(ctx, rawModel) {
|
|
|
2938
2944
|
if (!trimmed) throw new Error("Watchdog model must be a non-empty provider/model value.");
|
|
2939
2945
|
const availableModels = modelRegistryEntries(ctx);
|
|
2940
2946
|
const preferredProvider = typeof ctx.model?.provider === "string" ? ctx.model.provider : void 0;
|
|
2941
|
-
const resolved = resolveModelCandidate(trimmed, availableModels, preferredProvider) ?? trimmed;
|
|
2947
|
+
const resolved = resolveModelCandidate(trimmed, availableModels, preferredProvider, knownModelProviders(ctx.modelRegistry)) ?? trimmed;
|
|
2942
2948
|
const { baseModel, thinkingSuffix } = splitKnownThinkingSuffix(resolved);
|
|
2943
2949
|
const named = splitProviderModel(baseModel);
|
|
2944
2950
|
if (!named) throw new Error(`Watchdog model '${rawModel}' did not resolve to provider/model. Use a provider-qualified model such as openai-codex/gpt-5.5:high or anthropic/claude-opus-4-8:high.`);
|
|
@@ -3509,6 +3515,9 @@ function normalizePublicSubagentExecution(params, options = {}) {
|
|
|
3509
3515
|
return { ok: false, error: "action must be a non-empty management/control action, or omit action and use workflow.", mode: "management" };
|
|
3510
3516
|
}
|
|
3511
3517
|
const normalizedAction = typeof action === "string" ? action.trim() : void 0;
|
|
3518
|
+
if (params.requireLauncher !== void 0 && (normalizedAction !== void 0 || hasWorkflowInput || params.tasks !== void 0 || params.chain !== void 0 || params.parallel !== void 0 || params.resume !== void 0)) {
|
|
3519
|
+
return { ok: false, error: REQUIRE_LAUNCHER_SHAPE_ERROR, mode: normalizedAction !== void 0 ? "management" : "workflow" };
|
|
3520
|
+
}
|
|
3512
3521
|
if (params.baseRef !== void 0 && normalizedAction !== void 0 && normalizedAction !== "resume" && normalizedAction !== "schedule.create") {
|
|
3513
3522
|
return { ok: false, error: "baseRef is only supported for child execution, resume, and schedule.create.", mode: "management" };
|
|
3514
3523
|
}
|
|
@@ -3671,49 +3680,10 @@ function createParentWake(pi, now = Date.now) {
|
|
|
3671
3680
|
};
|
|
3672
3681
|
}
|
|
3673
3682
|
|
|
3674
|
-
// src/workflows/workflow-launch-record.ts
|
|
3675
|
-
import * as fs8 from "node:fs";
|
|
3676
|
-
import * as path7 from "node:path";
|
|
3677
|
-
var WORKFLOW_LAUNCH_RECORD_FILE = "launch.json";
|
|
3678
|
-
function launchRecordPath(asyncDir) {
|
|
3679
|
-
return path7.join(asyncDir, WORKFLOW_LAUNCH_RECORD_FILE);
|
|
3680
|
-
}
|
|
3681
|
-
function writeWorkflowLaunchRecord(asyncDir, record) {
|
|
3682
|
-
writeAtomicJson(launchRecordPath(asyncDir), record);
|
|
3683
|
-
}
|
|
3684
|
-
function isPlainObject(value) {
|
|
3685
|
-
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
3686
|
-
}
|
|
3687
|
-
function invalid(error2) {
|
|
3688
|
-
return { ok: false, missing: false, error: error2 };
|
|
3689
|
-
}
|
|
3690
|
-
function readWorkflowLaunchRecord(asyncDir) {
|
|
3691
|
-
let text2;
|
|
3692
|
-
try {
|
|
3693
|
-
text2 = fs8.readFileSync(launchRecordPath(asyncDir), "utf-8");
|
|
3694
|
-
} catch (error2) {
|
|
3695
|
-
if (error2.code === "ENOENT") return { ok: false, missing: true, error: "launch.json is missing" };
|
|
3696
|
-
return invalid(`could not be read: ${error2 instanceof Error ? error2.message : String(error2)}`);
|
|
3697
|
-
}
|
|
3698
|
-
let value;
|
|
3699
|
-
try {
|
|
3700
|
-
value = JSON.parse(text2);
|
|
3701
|
-
} catch (error2) {
|
|
3702
|
-
return invalid(`not valid JSON: ${error2 instanceof Error ? error2.message : String(error2)}`);
|
|
3703
|
-
}
|
|
3704
|
-
if (!isPlainObject(value)) return invalid("not a JSON object");
|
|
3705
|
-
if (value.version !== 1) return invalid("version must be 1");
|
|
3706
|
-
if (typeof value.scriptDigest !== "string" || !value.scriptDigest) return invalid("scriptDigest must be a non-empty string");
|
|
3707
|
-
if (value.source === "structured") return { ok: true, record: { version: 1, source: "structured", scriptDigest: value.scriptDigest } };
|
|
3708
|
-
if (value.source !== "script" && value.source !== "resource") return invalid('source must be "script", "resource", or "structured"');
|
|
3709
|
-
if (!isPlainObject(value.params)) return invalid("params must be an object");
|
|
3710
|
-
return { ok: true, record: { version: 1, source: value.source, params: value.params, scriptDigest: value.scriptDigest } };
|
|
3711
|
-
}
|
|
3712
|
-
|
|
3713
3683
|
// src/workflows/workflow-resume-claim.ts
|
|
3714
3684
|
import { randomUUID as randomUUID3 } from "node:crypto";
|
|
3715
|
-
import * as
|
|
3716
|
-
import * as
|
|
3685
|
+
import * as fs8 from "node:fs";
|
|
3686
|
+
import * as path7 from "node:path";
|
|
3717
3687
|
var CLAIM_FILE_PATTERN = /^resumed-by\.([1-9][0-9]*)\.json$/;
|
|
3718
3688
|
var RELEASED_CLAIM_FILE_PATTERN = /^resumed-by\.([1-9][0-9]*)\.json\.released-/;
|
|
3719
3689
|
var REFUSAL_FILE = "resume-refused.json";
|
|
@@ -3722,7 +3692,7 @@ var heldClaimsKey = /* @__PURE__ */ Symbol.for("pi-subagents.workflow-resume-cla
|
|
|
3722
3692
|
var heldClaimsGlobal = globalThis;
|
|
3723
3693
|
var heldClaims = heldClaimsGlobal[heldClaimsKey] ?? (heldClaimsGlobal[heldClaimsKey] = /* @__PURE__ */ new Set());
|
|
3724
3694
|
function claimFilePath(asyncDir, generation) {
|
|
3725
|
-
return
|
|
3695
|
+
return path7.join(asyncDir, `resumed-by.${generation}.json`);
|
|
3726
3696
|
}
|
|
3727
3697
|
function isClaim(value) {
|
|
3728
3698
|
if (!isRecordedPid(value) || Array.isArray(value)) return false;
|
|
@@ -3733,7 +3703,7 @@ function readTopClaim(asyncDir, retries = 3) {
|
|
|
3733
3703
|
let generation = 0;
|
|
3734
3704
|
let releasedGeneration = 0;
|
|
3735
3705
|
try {
|
|
3736
|
-
for (const name of
|
|
3706
|
+
for (const name of fs8.readdirSync(asyncDir)) {
|
|
3737
3707
|
const live = CLAIM_FILE_PATTERN.exec(name);
|
|
3738
3708
|
if (live) generation = Math.max(generation, Number(live[1]));
|
|
3739
3709
|
const released = RELEASED_CLAIM_FILE_PATTERN.exec(name);
|
|
@@ -3746,7 +3716,7 @@ function readTopClaim(asyncDir, retries = 3) {
|
|
|
3746
3716
|
const filePath = claimFilePath(asyncDir, generation);
|
|
3747
3717
|
let text2;
|
|
3748
3718
|
try {
|
|
3749
|
-
text2 =
|
|
3719
|
+
text2 = fs8.readFileSync(filePath, "utf-8");
|
|
3750
3720
|
} catch (error2) {
|
|
3751
3721
|
if (error2.code === "ENOENT" && retries > 0) return readTopClaim(asyncDir, retries - 1);
|
|
3752
3722
|
return { kind: "unreadable" };
|
|
@@ -3763,7 +3733,7 @@ function readWorkflowResumeClaim(asyncDir) {
|
|
|
3763
3733
|
return top.kind === "claim" ? top.claim : void 0;
|
|
3764
3734
|
}
|
|
3765
3735
|
function resumedRunStarted(sourceAsyncDir, newRunId) {
|
|
3766
|
-
return
|
|
3736
|
+
return path7.basename(newRunId) === newRunId && fs8.existsSync(path7.join(path7.dirname(sourceAsyncDir), newRunId, "status.json"));
|
|
3767
3737
|
}
|
|
3768
3738
|
function claimantLiveness(filePath, claim, liveness) {
|
|
3769
3739
|
if (claim.pid === process.pid && claim.bootId === currentBootId() && claim.pidNamespaceScope === currentPidNamespaceScope()) return heldClaims.has(filePath) ? "alive" : "dead";
|
|
@@ -3779,14 +3749,14 @@ function workflowResumeClaimState(asyncDir, options = {}) {
|
|
|
3779
3749
|
function createClaimFile(filePath, claim) {
|
|
3780
3750
|
const tempPath = `${filePath}.${process.pid}.${randomUUID3()}.tmp`;
|
|
3781
3751
|
try {
|
|
3782
|
-
|
|
3783
|
-
|
|
3752
|
+
fs8.writeFileSync(tempPath, JSON.stringify(claim, null, 2), "utf-8");
|
|
3753
|
+
fs8.linkSync(tempPath, filePath);
|
|
3784
3754
|
return true;
|
|
3785
3755
|
} catch (error2) {
|
|
3786
3756
|
if (error2.code === "EEXIST") return false;
|
|
3787
3757
|
throw error2;
|
|
3788
3758
|
} finally {
|
|
3789
|
-
|
|
3759
|
+
fs8.rmSync(tempPath, { force: true });
|
|
3790
3760
|
}
|
|
3791
3761
|
}
|
|
3792
3762
|
function claimWorkflowResume(asyncDir, input) {
|
|
@@ -3821,18 +3791,18 @@ function releaseWorkflowResumeClaim(asyncDir, newRunId) {
|
|
|
3821
3791
|
const top = readTopClaim(asyncDir);
|
|
3822
3792
|
if (top.kind !== "claim" || top.claim.newRunId !== newRunId || top.claim.pid !== process.pid) return;
|
|
3823
3793
|
try {
|
|
3824
|
-
|
|
3794
|
+
fs8.renameSync(top.filePath, `${top.filePath}.released-${randomUUID3()}`);
|
|
3825
3795
|
} catch (error2) {
|
|
3826
3796
|
if (error2.code !== "ENOENT") throw error2;
|
|
3827
3797
|
}
|
|
3828
3798
|
heldClaims.delete(top.filePath);
|
|
3829
3799
|
}
|
|
3830
3800
|
function recordWorkflowResumeRefusal(asyncDir, refusal, now = Date.now()) {
|
|
3831
|
-
writeAtomicJson(
|
|
3801
|
+
writeAtomicJson(path7.join(asyncDir, REFUSAL_FILE), { version: 1, ...refusal, refusedAt: now });
|
|
3832
3802
|
}
|
|
3833
3803
|
function readWorkflowResumeRefusal(asyncDir) {
|
|
3834
3804
|
try {
|
|
3835
|
-
const value = JSON.parse(
|
|
3805
|
+
const value = JSON.parse(fs8.readFileSync(path7.join(asyncDir, REFUSAL_FILE), "utf-8"));
|
|
3836
3806
|
return value?.version === 1 && typeof value.reason === "string" && typeof value.byHand === "string" && typeof value.refusedAt === "number" && (value.newRunId === void 0 || typeof value.newRunId === "string") ? value : void 0;
|
|
3837
3807
|
} catch {
|
|
3838
3808
|
return void 0;
|
|
@@ -3848,7 +3818,7 @@ function refusalSentence(reason, byHand) {
|
|
|
3848
3818
|
return `${reason.replace(/\.$/, "")}.${byHand ? ` ${byHand}` : ""}`;
|
|
3849
3819
|
}
|
|
3850
3820
|
function hasWorkflowResumeRefusal(asyncDir) {
|
|
3851
|
-
return
|
|
3821
|
+
return fs8.existsSync(path7.join(asyncDir, REFUSAL_FILE));
|
|
3852
3822
|
}
|
|
3853
3823
|
var RESUMED_AS = { auto: "Auto-resumed as", manual: "Resumed as", reuse: "Relaunched as" };
|
|
3854
3824
|
function describeWorkflowResume(asyncDir, runId) {
|
|
@@ -3858,8 +3828,8 @@ function describeWorkflowResume(asyncDir, runId) {
|
|
|
3858
3828
|
return `Not auto-resumed: ${refusalSentence(refusal.reason, refusal.byHand)}`;
|
|
3859
3829
|
}
|
|
3860
3830
|
if (claim) return `${RESUMED_AS[claim.trigger]} ${claim.newRunId}.`;
|
|
3861
|
-
const launch = readWorkflowLaunchRecord(asyncDir);
|
|
3862
|
-
return launch.ok && launch.record.source
|
|
3831
|
+
const launch = readWorkflowLaunchRecord(path7.dirname(asyncDir), runId);
|
|
3832
|
+
return launch.ok && (launch.record.source === "script" || launch.record.source === "resource") ? resumeByHandText(runId) : relaunchByHandText(runId);
|
|
3863
3833
|
}
|
|
3864
3834
|
|
|
3865
3835
|
// src/runs/background/notify.ts
|
|
@@ -4838,7 +4808,6 @@ var DEFAULT_SOURCE = "pi-subagents:herdr";
|
|
|
4838
4808
|
var DEFAULT_TTL_MS = 12e4;
|
|
4839
4809
|
var DEFAULT_REFRESH_MS = 45e3;
|
|
4840
4810
|
var MAX_TASK_LABEL_CHARS = 80;
|
|
4841
|
-
var MAX_TITLE_TASK_CHARS = 42;
|
|
4842
4811
|
var MAX_WORKFLOW_LABEL_NODES = 128;
|
|
4843
4812
|
var MAX_WORKFLOW_LABEL_DEPTH = 8;
|
|
4844
4813
|
var metadataReportSeq = Date.now() * 1e3;
|
|
@@ -4849,11 +4818,11 @@ function nextMetadataReportSeq() {
|
|
|
4849
4818
|
function isRecord(value) {
|
|
4850
4819
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
4851
4820
|
}
|
|
4852
|
-
function boundedTaskLabel(value
|
|
4821
|
+
function boundedTaskLabel(value) {
|
|
4853
4822
|
if (typeof value !== "string") return void 0;
|
|
4854
4823
|
const normalized = sanitizeDisplayText(value).trim();
|
|
4855
4824
|
if (!normalized) return void 0;
|
|
4856
|
-
return previewDisplayText(normalized,
|
|
4825
|
+
return previewDisplayText(normalized, MAX_TASK_LABEL_CHARS);
|
|
4857
4826
|
}
|
|
4858
4827
|
function workflowTaskLabel(data) {
|
|
4859
4828
|
const explicit = boundedTaskLabel(data.taskLabel);
|
|
@@ -4934,11 +4903,7 @@ function registerHerdrStatusBridge(options) {
|
|
|
4934
4903
|
};
|
|
4935
4904
|
const titleSuffix = () => {
|
|
4936
4905
|
if (runs.size === 0) return void 0;
|
|
4937
|
-
|
|
4938
|
-
const activeCount = activeSubagentCount();
|
|
4939
|
-
const task = boundedTaskLabel(activeTaskLabel(), MAX_TITLE_TASK_CHARS);
|
|
4940
|
-
const target = task ?? (activeCount === 1 && agentNames.length === 1 ? agentNames[0] : String(activeCount));
|
|
4941
|
-
return `\u23F3${target}${attentionRuns.size > 0 ? "\u26A0" : ""}`;
|
|
4906
|
+
return `\u23F3${activeSubagentCount()}${attentionRuns.size > 0 ? "\u26A0" : ""}`;
|
|
4942
4907
|
};
|
|
4943
4908
|
const enqueue = (args) => {
|
|
4944
4909
|
pendingReport = args;
|
|
@@ -5194,9 +5159,9 @@ function registerPiWebSessionLiveness(registration) {
|
|
|
5194
5159
|
}
|
|
5195
5160
|
|
|
5196
5161
|
// src/runs/background/wait-subscriptions.ts
|
|
5197
|
-
import * as
|
|
5198
|
-
import * as
|
|
5199
|
-
import { randomUUID as randomUUID4 } from "node:crypto";
|
|
5162
|
+
import * as fs9 from "node:fs";
|
|
5163
|
+
import * as path8 from "node:path";
|
|
5164
|
+
import { createHash as createHash3, randomUUID as randomUUID4 } from "node:crypto";
|
|
5200
5165
|
var SUBSCRIPTION_VERSION = 1;
|
|
5201
5166
|
var STATUS_OUTCOMES = /* @__PURE__ */ new Set(["timed out", "could not be reconciled", "needs attention", "reconciliation failed"]);
|
|
5202
5167
|
var RECONCILE_INTERVAL_MS = 1e3;
|
|
@@ -5208,14 +5173,34 @@ function isNotFound(error2) {
|
|
|
5208
5173
|
function parseRecord(value) {
|
|
5209
5174
|
if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
|
|
5210
5175
|
const record = value;
|
|
5211
|
-
if (record.version !== SUBSCRIPTION_VERSION || typeof record.token !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(record.token) || typeof record.sessionId !== "string" || record.targetKind !== "async" && record.targetKind !== "foreground" || typeof record.runId !== "string" || typeof record.requestedId !== "string" || typeof record.createdAt !== "number" || typeof record.expiresAt !== "number") return void 0;
|
|
5176
|
+
if (record.version !== SUBSCRIPTION_VERSION || typeof record.token !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(record.token) || typeof record.sessionId !== "string" || record.completionOwnerId !== void 0 && typeof record.completionOwnerId !== "string" || record.completionOwnerProcess !== void 0 && !isRecordedPid(record.completionOwnerProcess) || record.targetKind !== "async" && record.targetKind !== "foreground" || typeof record.runId !== "string" || typeof record.requestedId !== "string" || typeof record.createdAt !== "number" || typeof record.expiresAt !== "number") return void 0;
|
|
5212
5177
|
return record;
|
|
5213
5178
|
}
|
|
5214
5179
|
function needsAttention(run) {
|
|
5215
5180
|
return run.activityState === "needs_attention" || run.steps.some((step) => step.activityState === "needs_attention");
|
|
5216
5181
|
}
|
|
5217
5182
|
function subscriptionFile(dir, token) {
|
|
5218
|
-
return
|
|
5183
|
+
return path8.join(dir, `${token}.json`);
|
|
5184
|
+
}
|
|
5185
|
+
function claimPrefix(token, replacedOwnerId) {
|
|
5186
|
+
return `${token}.claim-${createHash3("sha256").update(replacedOwnerId).digest("hex").slice(0, 16)}.`;
|
|
5187
|
+
}
|
|
5188
|
+
function latestClaimGeneration(files, prefix) {
|
|
5189
|
+
let latest = 0;
|
|
5190
|
+
for (const file of files) {
|
|
5191
|
+
const generation = file.startsWith(prefix) ? file.slice(prefix.length) : "";
|
|
5192
|
+
if (/^[1-9][0-9]*$/.test(generation)) latest = Math.max(latest, Number(generation));
|
|
5193
|
+
}
|
|
5194
|
+
return latest;
|
|
5195
|
+
}
|
|
5196
|
+
function removeClaimFiles(dir, token) {
|
|
5197
|
+
try {
|
|
5198
|
+
for (const file of fs9.readdirSync(dir)) {
|
|
5199
|
+
if (file.startsWith(`${token}.claim-`)) fs9.rmSync(path8.join(dir, file), { force: true });
|
|
5200
|
+
}
|
|
5201
|
+
} catch (error2) {
|
|
5202
|
+
if (!isNotFound(error2)) console.error(`Failed to remove claims of wait subscription '${token}':`, error2);
|
|
5203
|
+
}
|
|
5219
5204
|
}
|
|
5220
5205
|
function formatWaitSubscriptions(state, now = Date.now()) {
|
|
5221
5206
|
const subscriptions = [...state.waitSubscriptions?.values() ?? []].sort((left, right) => left.createdAt - right.createdAt);
|
|
@@ -5229,7 +5214,7 @@ function formatWaitSubscriptions(state, now = Date.now()) {
|
|
|
5229
5214
|
function createWaitSubscriptionManager(pi, state, options = {}) {
|
|
5230
5215
|
const asyncDirRoot = options.asyncDirRoot ?? DIRS.async;
|
|
5231
5216
|
const resultsDir = options.resultsDir ?? DIRS.results;
|
|
5232
|
-
const subscriptionsDir = options.subscriptionsDir ??
|
|
5217
|
+
const subscriptionsDir = options.subscriptionsDir ?? path8.join(path8.dirname(asyncDirRoot), "wait-subscriptions");
|
|
5233
5218
|
const now = options.now ?? Date.now;
|
|
5234
5219
|
const subscriptions = state.waitSubscriptions ?? /* @__PURE__ */ new Map();
|
|
5235
5220
|
state.waitSubscriptions = subscriptions;
|
|
@@ -5237,22 +5222,67 @@ function createWaitSubscriptionManager(pi, state, options = {}) {
|
|
|
5237
5222
|
let disposed = false;
|
|
5238
5223
|
let interval;
|
|
5239
5224
|
let lastForeignSweepAt = 0;
|
|
5225
|
+
const readRecordFile = (filePath) => {
|
|
5226
|
+
try {
|
|
5227
|
+
return parseRecord(JSON.parse(fs9.readFileSync(filePath, "utf-8")));
|
|
5228
|
+
} catch (error2) {
|
|
5229
|
+
if (isNotFound(error2)) return void 0;
|
|
5230
|
+
throw error2;
|
|
5231
|
+
}
|
|
5232
|
+
};
|
|
5233
|
+
const isDead = (recorded) => recorded !== void 0 && checkRecordedPidLiveness(recorded, {
|
|
5234
|
+
observedScope: currentPidNamespaceScope(),
|
|
5235
|
+
observedBootId: currentBootId(),
|
|
5236
|
+
kill: options.kill
|
|
5237
|
+
}) === "dead";
|
|
5238
|
+
const latestClaimantHolds = (claimPath) => {
|
|
5239
|
+
let body;
|
|
5240
|
+
try {
|
|
5241
|
+
body = JSON.parse(fs9.readFileSync(claimPath, "utf-8"));
|
|
5242
|
+
} catch (error2) {
|
|
5243
|
+
return !(error2 instanceof SyntaxError);
|
|
5244
|
+
}
|
|
5245
|
+
const claimant = body?.process;
|
|
5246
|
+
return isRecordedPid(claimant) && !isDead(claimant);
|
|
5247
|
+
};
|
|
5248
|
+
const claimRecord = (filePath, record) => {
|
|
5249
|
+
if (!record.completionOwnerId || record.completionOwnerId === state.completionOwnerId) return record;
|
|
5250
|
+
if (!isDead(record.completionOwnerProcess)) return void 0;
|
|
5251
|
+
if (!state.completionOwnerId) return record;
|
|
5252
|
+
const prefix = claimPrefix(record.token, record.completionOwnerId);
|
|
5253
|
+
const latest = latestClaimGeneration(fs9.readdirSync(subscriptionsDir), prefix);
|
|
5254
|
+
if (latest > 0 && latestClaimantHolds(path8.join(subscriptionsDir, `${prefix}${latest}`))) return void 0;
|
|
5255
|
+
const claimPath = path8.join(subscriptionsDir, `${prefix}${latest + 1}`);
|
|
5256
|
+
if (!createClaimFile(claimPath, { ownerId: state.completionOwnerId, process: currentRecordedPid() })) return void 0;
|
|
5257
|
+
try {
|
|
5258
|
+
if (readRecordFile(filePath)?.completionOwnerId !== record.completionOwnerId) {
|
|
5259
|
+
fs9.rmSync(claimPath, { force: true });
|
|
5260
|
+
return void 0;
|
|
5261
|
+
}
|
|
5262
|
+
const claimed = { ...record, completionOwnerId: state.completionOwnerId, completionOwnerProcess: currentRecordedPid() };
|
|
5263
|
+
writeAtomicJson(filePath, claimed);
|
|
5264
|
+
return claimed;
|
|
5265
|
+
} catch (error2) {
|
|
5266
|
+
fs9.rmSync(claimPath, { force: true });
|
|
5267
|
+
throw error2;
|
|
5268
|
+
}
|
|
5269
|
+
};
|
|
5240
5270
|
const sweepExpiredForeignSubscriptions = (force = false) => {
|
|
5241
5271
|
const sweptAt = now();
|
|
5242
5272
|
if (!force && sweptAt - lastForeignSweepAt < FOREIGN_SWEEP_INTERVAL_MS) return;
|
|
5243
5273
|
lastForeignSweepAt = sweptAt;
|
|
5244
5274
|
let files;
|
|
5245
5275
|
try {
|
|
5246
|
-
files =
|
|
5276
|
+
files = fs9.readdirSync(subscriptionsDir).filter((file) => file.endsWith(".json"));
|
|
5247
5277
|
} catch (error2) {
|
|
5248
5278
|
if (!isNotFound(error2)) console.error(`Failed to scan wait subscriptions in '${subscriptionsDir}':`, error2);
|
|
5249
5279
|
return;
|
|
5250
5280
|
}
|
|
5251
5281
|
for (const file of files) {
|
|
5252
|
-
const filePath =
|
|
5282
|
+
const filePath = path8.join(subscriptionsDir, file);
|
|
5253
5283
|
let record;
|
|
5254
5284
|
try {
|
|
5255
|
-
record =
|
|
5285
|
+
record = readRecordFile(filePath);
|
|
5256
5286
|
} catch (error2) {
|
|
5257
5287
|
console.error(`Ignoring invalid wait subscription '${filePath}':`, error2);
|
|
5258
5288
|
continue;
|
|
@@ -5261,25 +5291,33 @@ function createWaitSubscriptionManager(pi, state, options = {}) {
|
|
|
5261
5291
|
if (record.sessionId === state.currentSessionId) continue;
|
|
5262
5292
|
if (sweptAt < record.expiresAt + FOREIGN_SWEEP_GRACE_MS) continue;
|
|
5263
5293
|
try {
|
|
5264
|
-
|
|
5294
|
+
fs9.unlinkSync(filePath);
|
|
5265
5295
|
} catch (error2) {
|
|
5266
|
-
if (!isNotFound(error2))
|
|
5296
|
+
if (!isNotFound(error2)) {
|
|
5297
|
+
console.error(`Failed to remove expired wait subscription '${filePath}':`, error2);
|
|
5298
|
+
continue;
|
|
5299
|
+
}
|
|
5267
5300
|
}
|
|
5301
|
+
removeClaimFiles(subscriptionsDir, record.token);
|
|
5268
5302
|
}
|
|
5269
5303
|
};
|
|
5270
5304
|
const remove = (record) => {
|
|
5305
|
+
let removed = true;
|
|
5271
5306
|
try {
|
|
5272
|
-
|
|
5307
|
+
fs9.unlinkSync(subscriptionFile(subscriptionsDir, record.token));
|
|
5273
5308
|
} catch (error2) {
|
|
5274
5309
|
if (!isNotFound(error2)) throw error2;
|
|
5310
|
+
removed = false;
|
|
5275
5311
|
}
|
|
5276
5312
|
subscriptions.delete(record.token);
|
|
5277
5313
|
unresolvedRestoredForegroundTokens.delete(record.token);
|
|
5314
|
+
removeClaimFiles(subscriptionsDir, record.token);
|
|
5315
|
+
return removed;
|
|
5278
5316
|
};
|
|
5279
5317
|
const settle = (record, outcome, detail, completion) => {
|
|
5280
5318
|
if (disposed || state.currentSessionId !== record.sessionId) return;
|
|
5281
5319
|
try {
|
|
5282
|
-
remove(record);
|
|
5320
|
+
if (!remove(record)) return;
|
|
5283
5321
|
} catch (error2) {
|
|
5284
5322
|
console.error(`Failed to clear wait subscription '${record.token}'; it remains armed:`, error2);
|
|
5285
5323
|
return;
|
|
@@ -5392,13 +5430,14 @@ Parent action: ${STATUS_OUTCOMES.has(outcome) ? STATUS_ACTION : COMPLETION_ACTIO
|
|
|
5392
5430
|
version: SUBSCRIPTION_VERSION,
|
|
5393
5431
|
token: randomUUID4(),
|
|
5394
5432
|
sessionId,
|
|
5433
|
+
...state.completionOwnerId ? { completionOwnerId: state.completionOwnerId, completionOwnerProcess: currentRecordedPid() } : {},
|
|
5395
5434
|
targetKind: input.targetKind,
|
|
5396
5435
|
runId: input.runId,
|
|
5397
5436
|
requestedId: input.requestedId,
|
|
5398
5437
|
createdAt,
|
|
5399
5438
|
expiresAt: createdAt + input.timeoutMs
|
|
5400
5439
|
};
|
|
5401
|
-
|
|
5440
|
+
fs9.mkdirSync(subscriptionsDir, { recursive: true });
|
|
5402
5441
|
writeAtomicJson(subscriptionFile(subscriptionsDir, record.token), record);
|
|
5403
5442
|
subscriptions.set(record.token, record);
|
|
5404
5443
|
return record;
|
|
@@ -5410,22 +5449,25 @@ Parent action: ${STATUS_OUTCOMES.has(outcome) ? STATUS_ACTION : COMPLETION_ACTIO
|
|
|
5410
5449
|
if (!state.currentSessionId) return;
|
|
5411
5450
|
let files;
|
|
5412
5451
|
try {
|
|
5413
|
-
files =
|
|
5452
|
+
files = fs9.readdirSync(subscriptionsDir).filter((file) => file.endsWith(".json"));
|
|
5414
5453
|
} catch (error2) {
|
|
5415
5454
|
if (isNotFound(error2)) return;
|
|
5416
5455
|
throw error2;
|
|
5417
5456
|
}
|
|
5418
5457
|
for (const file of files) {
|
|
5458
|
+
const filePath = path8.join(subscriptionsDir, file);
|
|
5459
|
+
let record;
|
|
5419
5460
|
try {
|
|
5420
|
-
const
|
|
5421
|
-
if (!
|
|
5422
|
-
|
|
5423
|
-
subscriptions.set(record.token, record);
|
|
5424
|
-
if (record.targetKind === "foreground" && !state.foregroundRuns?.has(record.runId)) unresolvedRestoredForegroundTokens.add(record.token);
|
|
5425
|
-
}
|
|
5461
|
+
const found = readRecordFile(filePath);
|
|
5462
|
+
if (!found || file !== `${found.token}.json` || found.sessionId !== state.currentSessionId) continue;
|
|
5463
|
+
record = claimRecord(filePath, found);
|
|
5426
5464
|
} catch (error2) {
|
|
5427
|
-
console.error(`
|
|
5465
|
+
console.error(`Failed to restore wait subscription '${filePath}':`, error2);
|
|
5466
|
+
continue;
|
|
5428
5467
|
}
|
|
5468
|
+
if (!record) continue;
|
|
5469
|
+
subscriptions.set(record.token, record);
|
|
5470
|
+
if (record.targetKind === "foreground" && !state.foregroundRuns?.has(record.runId)) unresolvedRestoredForegroundTokens.add(record.token);
|
|
5429
5471
|
}
|
|
5430
5472
|
reconcile();
|
|
5431
5473
|
},
|
|
@@ -5447,25 +5489,26 @@ Parent action: ${STATUS_OUTCOMES.has(outcome) ? STATUS_ACTION : COMPLETION_ACTIO
|
|
|
5447
5489
|
}
|
|
5448
5490
|
|
|
5449
5491
|
// src/runs/shared/child-session.ts
|
|
5450
|
-
import * as
|
|
5451
|
-
import * as
|
|
5492
|
+
import * as fs12 from "node:fs";
|
|
5493
|
+
import * as path11 from "node:path";
|
|
5452
5494
|
import { pathToFileURL } from "node:url";
|
|
5495
|
+
import { cleanupSessionResources, registerSessionResourceCleanup } from "@earendil-works/pi-ai";
|
|
5453
5496
|
|
|
5454
5497
|
// src/runs/shared/child-commands.ts
|
|
5455
5498
|
import { randomUUID as randomUUID5 } from "node:crypto";
|
|
5456
|
-
import * as
|
|
5457
|
-
import * as
|
|
5499
|
+
import * as fs10 from "node:fs";
|
|
5500
|
+
import * as path9 from "node:path";
|
|
5458
5501
|
import { Type } from "typebox";
|
|
5459
5502
|
var CHILD_COMMAND_TOOL = "subagent_command";
|
|
5460
5503
|
var writeAtomicJson2 = createAtomicJsonWriter({ mode: 384 });
|
|
5461
5504
|
var MAX_OUTPUT_BYTES = 8 * 1024;
|
|
5462
5505
|
var RECENT_COMMANDS = 20;
|
|
5463
5506
|
function childCommandStatePath(channelDir) {
|
|
5464
|
-
return
|
|
5507
|
+
return path9.join(channelDir, "commands.json");
|
|
5465
5508
|
}
|
|
5466
5509
|
function readChildCommandState(channelDir) {
|
|
5467
5510
|
try {
|
|
5468
|
-
return JSON.parse(
|
|
5511
|
+
return JSON.parse(fs10.readFileSync(childCommandStatePath(channelDir), "utf8"));
|
|
5469
5512
|
} catch (error2) {
|
|
5470
5513
|
if (error2.code === "ENOENT") return void 0;
|
|
5471
5514
|
throw error2;
|
|
@@ -5573,7 +5616,15 @@ Optional yieldTimeMs returns a command handle without stopping execution. Use su
|
|
|
5573
5616
|
persist();
|
|
5574
5617
|
startInbox();
|
|
5575
5618
|
let timer;
|
|
5576
|
-
|
|
5619
|
+
let yieldSaveError;
|
|
5620
|
+
if (typeof yieldTimeMs === "number") timer = setTimeout(() => {
|
|
5621
|
+
if (closed) return;
|
|
5622
|
+
try {
|
|
5623
|
+
operate("yield", toolCallId);
|
|
5624
|
+
} catch (error2) {
|
|
5625
|
+
yieldSaveError = error2;
|
|
5626
|
+
}
|
|
5627
|
+
}, yieldTimeMs);
|
|
5577
5628
|
const execution = Promise.resolve().then(() => tool.execute(toolCallId, args, commandSignal, (update) => {
|
|
5578
5629
|
job.snapshot.output = text(update);
|
|
5579
5630
|
if (job.snapshot.state === "running") onUpdate?.(update);
|
|
@@ -5597,7 +5648,9 @@ Optional yieldTimeMs returns a command handle without stopping execution. Use su
|
|
|
5597
5648
|
});
|
|
5598
5649
|
const result4 = await Promise.race([execution.then((value) => ({ value })), yielded.then(() => void 0)]);
|
|
5599
5650
|
if (result4) return result4.value;
|
|
5600
|
-
|
|
5651
|
+
const saveWarning = yieldSaveError === void 0 ? "" : `
|
|
5652
|
+
The command's saved state is out of date because it could not be saved: ${yieldSaveError instanceof Error ? yieldSaveError.message : String(yieldSaveError)}`;
|
|
5653
|
+
return { content: [{ type: "text", text: `Command is still running (toolCallId: ${toolCallId}). This is not a successful exit. Use subagent_command({ action: "status", toolCallId: ${JSON.stringify(toolCallId)} }) to inspect or wait, or action: "cancel" to stop it.${saveWarning}
|
|
5601
5654
|
${job.snapshot.output}` }], details: { command: { ...job.snapshot } } };
|
|
5602
5655
|
}
|
|
5603
5656
|
};
|
|
@@ -5637,7 +5690,7 @@ async function waitForCommand(settled, waitMs, signal) {
|
|
|
5637
5690
|
}
|
|
5638
5691
|
}
|
|
5639
5692
|
function commandReplyPath(channelDir, id) {
|
|
5640
|
-
return
|
|
5693
|
+
return path9.join(channelDir, "command-replies", `${id}.json`);
|
|
5641
5694
|
}
|
|
5642
5695
|
async function controlChildCommand(channelDir, operation, toolCallId, signal) {
|
|
5643
5696
|
const current = readChildCommandState(channelDir);
|
|
@@ -5661,7 +5714,7 @@ async function controlChildCommand(channelDir, operation, toolCallId, signal) {
|
|
|
5661
5714
|
while (Date.now() < deadlineAt) {
|
|
5662
5715
|
if (signal?.aborted) throw new Error("Command control wait aborted; delivery may still be pending.");
|
|
5663
5716
|
try {
|
|
5664
|
-
const reply = JSON.parse(
|
|
5717
|
+
const reply = JSON.parse(fs10.readFileSync(replyPath, "utf8"));
|
|
5665
5718
|
if (reply.error) throw new Error(reply.error);
|
|
5666
5719
|
if (reply.state) return reply.state;
|
|
5667
5720
|
} catch (error2) {
|
|
@@ -5671,7 +5724,7 @@ async function controlChildCommand(channelDir, operation, toolCallId, signal) {
|
|
|
5671
5724
|
}
|
|
5672
5725
|
throw new Error("Command control acknowledgement timed out. Inspect command status; cancellation is not confirmed.");
|
|
5673
5726
|
} finally {
|
|
5674
|
-
|
|
5727
|
+
fs10.rmSync(replyPath, { force: true });
|
|
5675
5728
|
}
|
|
5676
5729
|
}
|
|
5677
5730
|
|
|
@@ -5695,8 +5748,8 @@ function pinChildCacheRetention(agent, env) {
|
|
|
5695
5748
|
}
|
|
5696
5749
|
|
|
5697
5750
|
// src/runs/background/runner-aliases.ts
|
|
5698
|
-
import * as
|
|
5699
|
-
import * as
|
|
5751
|
+
import * as fs11 from "node:fs";
|
|
5752
|
+
import * as path10 from "node:path";
|
|
5700
5753
|
var JITI_ALIAS_ENV = "JITI_ALIAS";
|
|
5701
5754
|
var HOST_PEER_ALIASES = [
|
|
5702
5755
|
{ specifier: "@earendil-works/pi-coding-agent", pkg: "@earendil-works/pi-coding-agent", subpath: "." },
|
|
@@ -5717,9 +5770,10 @@ var CHORD_PEER_ALIASES = [
|
|
|
5717
5770
|
{ specifier: "@earendil-works/chord", pkg: "@earendil-works/chord", subpath: "." },
|
|
5718
5771
|
{ specifier: "@earendil-works/chord/context", pkg: "@earendil-works/chord", subpath: "./context" }
|
|
5719
5772
|
];
|
|
5773
|
+
var SCHEMA_PACKAGE = "@earendil-works/pi-schema";
|
|
5720
5774
|
function readManifest(packageDir) {
|
|
5721
5775
|
try {
|
|
5722
|
-
return JSON.parse(
|
|
5776
|
+
return JSON.parse(fs11.readFileSync(path10.join(packageDir, "package.json"), "utf-8"));
|
|
5723
5777
|
} catch {
|
|
5724
5778
|
return void 0;
|
|
5725
5779
|
}
|
|
@@ -5756,7 +5810,7 @@ function resolvePackageSubpath(packageDir, subpath) {
|
|
|
5756
5810
|
const map = typeof exportsField === "string" || Array.isArray(exportsField) || exportsField && typeof exportsField === "object" && !Object.keys(exportsField).some((key) => key.startsWith(".")) ? { ".": exportsField } : exportsField;
|
|
5757
5811
|
if (subpath in map) {
|
|
5758
5812
|
const exact = exportTarget(map[subpath]);
|
|
5759
|
-
return typeof exact === "string" ?
|
|
5813
|
+
return typeof exact === "string" ? path10.resolve(packageDir, exact) : void 0;
|
|
5760
5814
|
}
|
|
5761
5815
|
let best;
|
|
5762
5816
|
for (const [pattern, entry] of Object.entries(map)) {
|
|
@@ -5771,23 +5825,23 @@ function resolvePackageSubpath(packageDir, subpath) {
|
|
|
5771
5825
|
const target = exportTarget(best.entry);
|
|
5772
5826
|
if (typeof target !== "string") return void 0;
|
|
5773
5827
|
const wildcard = subpath.slice(best.prefix.length, subpath.length - best.suffix.length);
|
|
5774
|
-
return
|
|
5828
|
+
return path10.resolve(packageDir, target.replaceAll("*", () => wildcard));
|
|
5775
5829
|
}
|
|
5776
5830
|
if (subpath !== ".") return void 0;
|
|
5777
|
-
return
|
|
5831
|
+
return path10.resolve(packageDir, typeof manifest.main === "string" && manifest.main.trim() ? manifest.main : "index.js");
|
|
5778
5832
|
}
|
|
5779
5833
|
function findPeerPackageDir(piPackageRoot, pkg, hostName) {
|
|
5780
5834
|
if (hostName === pkg) return piPackageRoot;
|
|
5781
|
-
const candidates = [
|
|
5835
|
+
const candidates = [path10.join(piPackageRoot, "node_modules", pkg)];
|
|
5782
5836
|
let dir = piPackageRoot;
|
|
5783
5837
|
for (; ; ) {
|
|
5784
|
-
const parent =
|
|
5838
|
+
const parent = path10.dirname(dir);
|
|
5785
5839
|
if (parent === dir) break;
|
|
5786
|
-
if (
|
|
5787
|
-
const modulesRoot =
|
|
5788
|
-
candidates.push(
|
|
5840
|
+
if (path10.basename(parent) === "node_modules" || path10.basename(path10.dirname(parent)) === "node_modules") {
|
|
5841
|
+
const modulesRoot = path10.basename(parent) === "node_modules" ? parent : path10.dirname(parent);
|
|
5842
|
+
candidates.push(path10.join(modulesRoot, pkg));
|
|
5789
5843
|
}
|
|
5790
|
-
candidates.push(
|
|
5844
|
+
candidates.push(path10.join(parent, "node_modules", pkg));
|
|
5791
5845
|
dir = parent;
|
|
5792
5846
|
}
|
|
5793
5847
|
return candidates.find((candidate) => readManifest(candidate)?.name === pkg);
|
|
@@ -5820,13 +5874,22 @@ function resolveHostPeerAliases(piPackageRoot) {
|
|
|
5820
5874
|
const packageDir = findPeerPackageDir(piPackageRoot, pkg, hostManifest?.name);
|
|
5821
5875
|
const target = packageDir ? resolvePackageSubpath(packageDir, subpath) : void 0;
|
|
5822
5876
|
if (optional && packageDir && target === void 0) continue;
|
|
5823
|
-
if (target &&
|
|
5824
|
-
aliases[specifier] =
|
|
5877
|
+
if (target && fs11.existsSync(target)) {
|
|
5878
|
+
aliases[specifier] = fs11.realpathSync(target);
|
|
5825
5879
|
continue;
|
|
5826
5880
|
}
|
|
5827
5881
|
if (packageDir && subpath !== "." && !exportsDeclareSubpath(packageDir, subpath)) continue;
|
|
5828
5882
|
if (pkg !== CHORD_PACKAGE || chordRequired) missing.push(specifier);
|
|
5829
5883
|
}
|
|
5884
|
+
const piAiDir = findPeerPackageDir(piPackageRoot, "@earendil-works/pi-ai", hostManifest?.name);
|
|
5885
|
+
const piAiManifest = piAiDir ? readManifest(piAiDir) : void 0;
|
|
5886
|
+
if (piAiDir && piAiManifest && declaresDependency(piAiManifest, SCHEMA_PACKAGE)) {
|
|
5887
|
+
const schemaDir = findPeerPackageDir(fs11.realpathSync(piAiDir), SCHEMA_PACKAGE, void 0);
|
|
5888
|
+
for (const subpath of [".", "./formats"]) {
|
|
5889
|
+
const target = schemaDir ? resolvePackageSubpath(schemaDir, subpath) : void 0;
|
|
5890
|
+
if (!target || !fs11.existsSync(target)) missing.push(subpath === "." ? SCHEMA_PACKAGE : `${SCHEMA_PACKAGE}/formats`);
|
|
5891
|
+
}
|
|
5892
|
+
}
|
|
5830
5893
|
return { aliases, missing };
|
|
5831
5894
|
}
|
|
5832
5895
|
|
|
@@ -5874,9 +5937,9 @@ var CHILD_PROMPT_RUNTIME_EXTENSION_PATH = "<inline:pi-subagents:prompt-runtime>"
|
|
|
5874
5937
|
var CHILD_PROMPT_BOUNDARY_EXTENSION_PATH = "<inline:pi-subagents:prompt-boundary>";
|
|
5875
5938
|
var PI_UNICODE_SPACES = new RegExp("[\\u00A0\\u2000-\\u200A\\u202F\\u205F\\u3000]", "g");
|
|
5876
5939
|
function childExtensionFileIdentity(extensionPath) {
|
|
5877
|
-
if (!
|
|
5940
|
+
if (!path11.isAbsolute(extensionPath)) return void 0;
|
|
5878
5941
|
try {
|
|
5879
|
-
const stat =
|
|
5942
|
+
const stat = fs12.statSync(extensionPath, { bigint: true });
|
|
5880
5943
|
return stat.isFile() ? `${stat.dev}:${stat.ino}` : void 0;
|
|
5881
5944
|
} catch {
|
|
5882
5945
|
return void 0;
|
|
@@ -5925,6 +5988,18 @@ function prioritizeChildCommandRuntime(result4) {
|
|
|
5925
5988
|
extensions.unshift(commands);
|
|
5926
5989
|
return { ...result4, extensions };
|
|
5927
5990
|
}
|
|
5991
|
+
function disposeChildSession(session) {
|
|
5992
|
+
let released = false;
|
|
5993
|
+
const unregister = registerSessionResourceCleanup((sessionId) => {
|
|
5994
|
+
if (sessionId === session.sessionId) released = true;
|
|
5995
|
+
});
|
|
5996
|
+
try {
|
|
5997
|
+
session.dispose();
|
|
5998
|
+
} finally {
|
|
5999
|
+
unregister();
|
|
6000
|
+
if (!released) cleanupSessionResources(session.sessionId);
|
|
6001
|
+
}
|
|
6002
|
+
}
|
|
5928
6003
|
var loading = Promise.resolve();
|
|
5929
6004
|
function resetExtensionCacheOnReload(loader) {
|
|
5930
6005
|
if (!("loaded" in loader)) return false;
|
|
@@ -6065,14 +6140,14 @@ async function loadHostPiCodingAgent() {
|
|
|
6065
6140
|
const overrideRoot = process.env[PI_CODING_AGENT_PACKAGE_ROOT_ENV]?.trim() || void 0;
|
|
6066
6141
|
const root = resolveHostPiPackageRoot();
|
|
6067
6142
|
if (root) {
|
|
6068
|
-
const entry =
|
|
6143
|
+
const entry = fs12.realpathSync(resolveHostPackageEntry(root, root === overrideRoot ? overrideRoot : void 0));
|
|
6069
6144
|
return import(pathToFileURL(entry).href);
|
|
6070
6145
|
}
|
|
6071
6146
|
return import(PI_CODING_AGENT_PACKAGE);
|
|
6072
6147
|
}
|
|
6073
6148
|
function resolveHostPackageEntry(root, overrideRoot) {
|
|
6074
|
-
const packageJson =
|
|
6075
|
-
const source =
|
|
6149
|
+
const packageJson = path11.join(root, "package.json");
|
|
6150
|
+
const source = fs12.readFileSync(packageJson, "utf8");
|
|
6076
6151
|
let parsed;
|
|
6077
6152
|
try {
|
|
6078
6153
|
parsed = JSON.parse(source);
|
|
@@ -6096,10 +6171,12 @@ function createDefaultChildSessionFactory(options = {}) {
|
|
|
6096
6171
|
const loadPiCodingAgent = options.loadPiCodingAgent ?? loadHostPiCodingAgent;
|
|
6097
6172
|
const shutdownTimeoutMs = options.shutdownTimeoutMs ?? 5e3;
|
|
6098
6173
|
let runtime;
|
|
6099
|
-
const live = /* @__PURE__ */ new
|
|
6174
|
+
const live = /* @__PURE__ */ new Map();
|
|
6100
6175
|
const shutdowns = /* @__PURE__ */ new Set();
|
|
6101
6176
|
const mcpWaits = /* @__PURE__ */ new Map();
|
|
6102
|
-
let
|
|
6177
|
+
let globalDisposals = 0;
|
|
6178
|
+
const parentDisposals = /* @__PURE__ */ new Map();
|
|
6179
|
+
const parentDisposalEpoch = (parent) => parentDisposals.get(parent) ?? 0;
|
|
6103
6180
|
const sharedRuntime = async (pi) => {
|
|
6104
6181
|
runtime ??= pi.ModelRuntime.create().catch((error2) => {
|
|
6105
6182
|
runtime = void 0;
|
|
@@ -6107,9 +6184,28 @@ function createDefaultChildSessionFactory(options = {}) {
|
|
|
6107
6184
|
});
|
|
6108
6185
|
return runtime;
|
|
6109
6186
|
};
|
|
6187
|
+
const disposeMatching = async (matches) => {
|
|
6188
|
+
for (const [cancel, wait] of mcpWaits) if (matches(wait.parent)) cancel.abort();
|
|
6189
|
+
const children = [...live.keys()].filter((child) => !child.detached && matches(live.get(child)));
|
|
6190
|
+
for (const child of children) child.shutDown = true;
|
|
6191
|
+
await Promise.allSettled(children.map((child) => child.abort()));
|
|
6192
|
+
for (const child of children) {
|
|
6193
|
+
try {
|
|
6194
|
+
void child.dispose();
|
|
6195
|
+
} catch {
|
|
6196
|
+
}
|
|
6197
|
+
}
|
|
6198
|
+
await Promise.allSettled([
|
|
6199
|
+
...shutdowns,
|
|
6200
|
+
...[...mcpWaits.values()].filter((wait) => matches(wait.parent)).map((wait) => wait.ready)
|
|
6201
|
+
]);
|
|
6202
|
+
if (live.size === 0) runtime = void 0;
|
|
6203
|
+
};
|
|
6110
6204
|
return {
|
|
6111
6205
|
async create(launch) {
|
|
6112
|
-
const
|
|
6206
|
+
const globalDisposalsAtStart = globalDisposals;
|
|
6207
|
+
const parentEpochAtStart = parentDisposalEpoch(launch.parentSessionFile);
|
|
6208
|
+
const disposedSinceStart = () => globalDisposals !== globalDisposalsAtStart || parentDisposalEpoch(launch.parentSessionFile) !== parentEpochAtStart;
|
|
6113
6209
|
const pi = await loadPiCodingAgent();
|
|
6114
6210
|
const builtinMcpTools = launch.builtinMcpTools ?? [];
|
|
6115
6211
|
let readinessTool;
|
|
@@ -6173,7 +6269,7 @@ function createDefaultChildSessionFactory(options = {}) {
|
|
|
6173
6269
|
} catch (error2) {
|
|
6174
6270
|
launch.onExtensionError?.({ extensionPath: "<session>", event: "session_shutdown", error: error2 });
|
|
6175
6271
|
} finally {
|
|
6176
|
-
session2
|
|
6272
|
+
disposeChildSession(session2);
|
|
6177
6273
|
}
|
|
6178
6274
|
};
|
|
6179
6275
|
let inheritedProviders = /* @__PURE__ */ new Set();
|
|
@@ -6200,7 +6296,7 @@ function createDefaultChildSessionFactory(options = {}) {
|
|
|
6200
6296
|
}
|
|
6201
6297
|
}
|
|
6202
6298
|
const newSessionOptions = launch.parentSessionFile ? { parentSession: launch.parentSessionFile } : void 0;
|
|
6203
|
-
const newSessionFile = launch.storage.kind === "file" && !
|
|
6299
|
+
const newSessionFile = launch.storage.kind === "file" && !fs12.existsSync(launch.storage.sessionFile);
|
|
6204
6300
|
const sessionManager = launch.storage.kind === "file" ? pi.SessionManager.open(launch.storage.sessionFile, void 0, launch.cwd) : launch.storage.kind === "dir" ? pi.SessionManager.create(launch.cwd, launch.storage.sessionDir, newSessionOptions) : launch.storage.kind === "memory" ? pi.SessionManager.inMemory(launch.cwd, newSessionOptions) : pi.SessionManager.create(launch.cwd, void 0, newSessionOptions);
|
|
6205
6301
|
const header = newSessionFile && launch.parentSessionFile ? sessionManager.getHeader() : null;
|
|
6206
6302
|
if (header) header.parentSession = launch.parentSessionFile;
|
|
@@ -6231,7 +6327,7 @@ function createDefaultChildSessionFactory(options = {}) {
|
|
|
6231
6327
|
}
|
|
6232
6328
|
});
|
|
6233
6329
|
} catch (error2) {
|
|
6234
|
-
session2
|
|
6330
|
+
disposeChildSession(session2);
|
|
6235
6331
|
throw error2;
|
|
6236
6332
|
} finally {
|
|
6237
6333
|
binding = false;
|
|
@@ -6261,11 +6357,11 @@ function createDefaultChildSessionFactory(options = {}) {
|
|
|
6261
6357
|
if (builtinMcp) {
|
|
6262
6358
|
const cancel = new AbortController();
|
|
6263
6359
|
const signal = launch.signal ? AbortSignal.any([cancel.signal, launch.signal]) : cancel.signal;
|
|
6264
|
-
if (
|
|
6360
|
+
if (disposedSinceStart()) cancel.abort();
|
|
6265
6361
|
const ready = (async () => {
|
|
6266
6362
|
try {
|
|
6267
6363
|
await builtinMcp.waitForTools(signal, () => loader.getExtensions().errors.find(({ path: path16 }) => path16 === "builtin:mcp")?.error);
|
|
6268
|
-
if (
|
|
6364
|
+
if (disposedSinceStart()) throw new Error("The child session factory was disposed while the child waited for its MCP tools.");
|
|
6269
6365
|
if (signal.aborted) throw new Error("The child launch was cancelled while waiting for its MCP tools.");
|
|
6270
6366
|
const missing = missingBuiltinMcpTools(session, builtinMcpTools.map(({ name }) => name));
|
|
6271
6367
|
if (missing.length) throw new Error(`Selected built-in MCP tools did not register in the child session: ${missing.join(", ")}. The MCP server may have failed to connect, or the name belongs to a different tool than the selector names; check it with /mcp.`);
|
|
@@ -6274,19 +6370,46 @@ function createDefaultChildSessionFactory(options = {}) {
|
|
|
6274
6370
|
throw error2;
|
|
6275
6371
|
}
|
|
6276
6372
|
})();
|
|
6277
|
-
mcpWaits.set(cancel, ready);
|
|
6373
|
+
mcpWaits.set(cancel, { ready, parent: launch.parentSessionFile });
|
|
6278
6374
|
try {
|
|
6279
6375
|
await ready;
|
|
6280
6376
|
} finally {
|
|
6281
6377
|
mcpWaits.delete(cancel);
|
|
6282
6378
|
}
|
|
6283
6379
|
}
|
|
6380
|
+
let reportCompleted = false;
|
|
6381
|
+
const guidanceClosed = "Child completed its acceptance report; resume it for further guidance.";
|
|
6382
|
+
const assertAcceptsGuidance = () => {
|
|
6383
|
+
if (reportCompleted) throw new Error(guidanceClosed);
|
|
6384
|
+
};
|
|
6385
|
+
const rejectQueuedGuidance = () => {
|
|
6386
|
+
session.clearQueue();
|
|
6387
|
+
throw new Error(guidanceClosed);
|
|
6388
|
+
};
|
|
6284
6389
|
const child = {
|
|
6285
|
-
subscribe: (listener) => session.subscribe((event) =>
|
|
6390
|
+
subscribe: (listener) => session.subscribe((event) => {
|
|
6391
|
+
if (event.type === "message_end" && event.message.role === "assistant" && event.message.stopReason === "stop") {
|
|
6392
|
+
const text2 = event.message.content.filter((part) => part.type === "text").map((part) => part.text).join("\n");
|
|
6393
|
+
const report = parseAcceptanceReport(text2);
|
|
6394
|
+
if (report.report || report.malformed) {
|
|
6395
|
+
reportCompleted = true;
|
|
6396
|
+
session.clearQueue();
|
|
6397
|
+
session.agent.steer = rejectQueuedGuidance;
|
|
6398
|
+
session.agent.followUp = rejectQueuedGuidance;
|
|
6399
|
+
}
|
|
6400
|
+
}
|
|
6401
|
+
listener(event);
|
|
6402
|
+
}),
|
|
6286
6403
|
prompt: (text2) => session.prompt(text2),
|
|
6287
6404
|
...commands ? { finishCommands: () => commands.finish() } : {},
|
|
6288
|
-
steer:
|
|
6289
|
-
|
|
6405
|
+
steer: async (text2) => {
|
|
6406
|
+
assertAcceptsGuidance();
|
|
6407
|
+
await session.steer(text2);
|
|
6408
|
+
},
|
|
6409
|
+
followUp: async (text2) => {
|
|
6410
|
+
assertAcceptsGuidance();
|
|
6411
|
+
await session.followUp(text2);
|
|
6412
|
+
},
|
|
6290
6413
|
abort: () => session.abort(),
|
|
6291
6414
|
hasQueuedMessages: () => session.agent?.hasQueuedMessages?.() === true,
|
|
6292
6415
|
dispose: () => {
|
|
@@ -6324,23 +6447,16 @@ function createDefaultChildSessionFactory(options = {}) {
|
|
|
6324
6447
|
return session.model?.contextWindow;
|
|
6325
6448
|
}
|
|
6326
6449
|
};
|
|
6327
|
-
live.
|
|
6450
|
+
live.set(child, launch.parentSessionFile);
|
|
6328
6451
|
return child;
|
|
6329
6452
|
},
|
|
6330
6453
|
async dispose() {
|
|
6331
|
-
|
|
6332
|
-
|
|
6333
|
-
|
|
6334
|
-
|
|
6335
|
-
|
|
6336
|
-
|
|
6337
|
-
try {
|
|
6338
|
-
void child.dispose();
|
|
6339
|
-
} catch {
|
|
6340
|
-
}
|
|
6341
|
-
}
|
|
6342
|
-
await Promise.allSettled([...shutdowns, ...mcpWaits.values()]);
|
|
6343
|
-
if (live.size === 0) runtime = void 0;
|
|
6454
|
+
globalDisposals += 1;
|
|
6455
|
+
await disposeMatching(() => true);
|
|
6456
|
+
},
|
|
6457
|
+
async disposeForParent(parentSessionFile) {
|
|
6458
|
+
parentDisposals.set(parentSessionFile, parentDisposalEpoch(parentSessionFile) + 1);
|
|
6459
|
+
await disposeMatching((parent) => parent === parentSessionFile);
|
|
6344
6460
|
}
|
|
6345
6461
|
};
|
|
6346
6462
|
}
|
|
@@ -6352,24 +6468,24 @@ function childSessionFactory() {
|
|
|
6352
6468
|
}
|
|
6353
6469
|
function createLazyPlacementFactory(local) {
|
|
6354
6470
|
let placed;
|
|
6355
|
-
const factory = async () => placed ??= (await import("./chunk-
|
|
6471
|
+
const factory = async () => placed ??= (await import("./chunk-OSVXFWPG.js")).createPlacementAwareChildSessionFactory(local);
|
|
6356
6472
|
return {
|
|
6357
6473
|
async create(launch) {
|
|
6358
6474
|
return launch.machine ? (await factory()).create(launch) : local.create(launch);
|
|
6359
6475
|
},
|
|
6360
6476
|
async dispose() {
|
|
6361
|
-
|
|
6362
|
-
|
|
6477
|
+
await (placed ?? local).dispose();
|
|
6478
|
+
},
|
|
6479
|
+
async disposeForParent(parentSessionFile) {
|
|
6480
|
+
await (placed ?? local).disposeForParent(parentSessionFile);
|
|
6363
6481
|
}
|
|
6364
6482
|
};
|
|
6365
6483
|
}
|
|
6366
6484
|
function childSessionFactoryModule() {
|
|
6367
6485
|
return activeFactoryModule;
|
|
6368
6486
|
}
|
|
6369
|
-
async function
|
|
6370
|
-
|
|
6371
|
-
if (!factory) return;
|
|
6372
|
-
await factory.dispose();
|
|
6487
|
+
async function disposeChildSessionsForParent(parentSessionFile) {
|
|
6488
|
+
await activeFactory?.disposeForParent(parentSessionFile);
|
|
6373
6489
|
}
|
|
6374
6490
|
|
|
6375
6491
|
// src/extension/context-injection.ts
|
|
@@ -6445,9 +6561,9 @@ function renderInjectionBlock(agents) {
|
|
|
6445
6561
|
}
|
|
6446
6562
|
|
|
6447
6563
|
// src/workflows/workflow-reuse.ts
|
|
6448
|
-
import { createHash as
|
|
6449
|
-
import * as
|
|
6450
|
-
import * as
|
|
6564
|
+
import { createHash as createHash4 } from "node:crypto";
|
|
6565
|
+
import * as fs13 from "node:fs";
|
|
6566
|
+
import * as path12 from "node:path";
|
|
6451
6567
|
var WORKFLOW_CHILD_JOURNAL_FILE = "workflow-children.jsonl";
|
|
6452
6568
|
var WORKFLOW_RUNTIME_REPLACED_STOP_NOTICE = "Async children that were still running keep running, and finished children are kept.";
|
|
6453
6569
|
function runtimeReplacedAbortReason() {
|
|
@@ -6457,7 +6573,7 @@ function workflowStopCause(reason) {
|
|
|
6457
6573
|
return reason instanceof Error && "workflowStopCause" in reason && reason.workflowStopCause === WORKFLOW_STOP_CAUSE_RUNTIME_REPLACED ? WORKFLOW_STOP_CAUSE_RUNTIME_REPLACED : void 0;
|
|
6458
6574
|
}
|
|
6459
6575
|
function sha256(text2) {
|
|
6460
|
-
return
|
|
6576
|
+
return createHash4("sha256").update(text2).digest("hex");
|
|
6461
6577
|
}
|
|
6462
6578
|
function workflowScriptDigest(script) {
|
|
6463
6579
|
return sha256(script);
|
|
@@ -6466,9 +6582,9 @@ function workflowChildFingerprint(params) {
|
|
|
6466
6582
|
return sha256(workflowRunParamsFingerprint(params));
|
|
6467
6583
|
}
|
|
6468
6584
|
function appendWorkflowChildJournal(workflowAsyncDir, record) {
|
|
6469
|
-
const journalPath =
|
|
6585
|
+
const journalPath = path12.join(workflowAsyncDir, WORKFLOW_CHILD_JOURNAL_FILE);
|
|
6470
6586
|
try {
|
|
6471
|
-
|
|
6587
|
+
fs13.appendFileSync(journalPath, `${JSON.stringify(record)}
|
|
6472
6588
|
`, "utf-8");
|
|
6473
6589
|
} catch (error2) {
|
|
6474
6590
|
console.error(`Failed to append workflow child journal '${journalPath}':`, error2);
|
|
@@ -6478,7 +6594,7 @@ function readWorkflowChildJournal(runId, workflowAsyncDir) {
|
|
|
6478
6594
|
const source = { runId, started: /* @__PURE__ */ new Map(), settled: /* @__PURE__ */ new Map() };
|
|
6479
6595
|
let text2 = "";
|
|
6480
6596
|
try {
|
|
6481
|
-
text2 =
|
|
6597
|
+
text2 = fs13.readFileSync(path12.join(workflowAsyncDir, WORKFLOW_CHILD_JOURNAL_FILE), "utf-8");
|
|
6482
6598
|
} catch {
|
|
6483
6599
|
return source;
|
|
6484
6600
|
}
|
|
@@ -6500,12 +6616,12 @@ function readWorkflowChildJournal(runId, workflowAsyncDir) {
|
|
|
6500
6616
|
}
|
|
6501
6617
|
var WORKFLOW_REUSE_CHAIN_MAX_LINKS = 16;
|
|
6502
6618
|
function readWorkflowReuseChain(asyncDirRoot, headRunId, headStatus) {
|
|
6503
|
-
const source = readWorkflowChildJournal(headRunId,
|
|
6619
|
+
const source = readWorkflowChildJournal(headRunId, path12.join(asyncDirRoot, headRunId));
|
|
6504
6620
|
const visited = /* @__PURE__ */ new Set([headRunId]);
|
|
6505
6621
|
let next = headStatus.workflow?.reusedFrom;
|
|
6506
6622
|
for (let links = 0; isRunId(next) && links < WORKFLOW_REUSE_CHAIN_MAX_LINKS && !visited.has(next); links++) {
|
|
6507
6623
|
visited.add(next);
|
|
6508
|
-
const asyncDir =
|
|
6624
|
+
const asyncDir = path12.join(asyncDirRoot, next);
|
|
6509
6625
|
let status;
|
|
6510
6626
|
try {
|
|
6511
6627
|
status = readStatus(asyncDir);
|
|
@@ -6544,7 +6660,7 @@ function findWorkflowReuseSource(asyncDirRoot, sessionId, scriptDigest, argsDige
|
|
|
6544
6660
|
return void 0;
|
|
6545
6661
|
}
|
|
6546
6662
|
for (const runId of runIds) {
|
|
6547
|
-
const asyncDir =
|
|
6663
|
+
const asyncDir = path12.join(asyncDirRoot, runId);
|
|
6548
6664
|
let status;
|
|
6549
6665
|
try {
|
|
6550
6666
|
status = readStatus(asyncDir);
|
|
@@ -6560,14 +6676,14 @@ function findWorkflowReuseSource(asyncDirRoot, sessionId, scriptDigest, argsDige
|
|
|
6560
6676
|
}
|
|
6561
6677
|
function readNamedWorkflowReuseSource(asyncDirRoot, runId, scriptDigest, cwd, claimOwnerRunId) {
|
|
6562
6678
|
const runName = isRunId(runId);
|
|
6563
|
-
if (runName) reconcileAsyncRun(
|
|
6564
|
-
const status = runName ? readStatus(
|
|
6679
|
+
if (runName) reconcileAsyncRun(path12.join(asyncDirRoot, runId));
|
|
6680
|
+
const status = runName ? readStatus(path12.join(asyncDirRoot, runId)) : null;
|
|
6565
6681
|
if (!status) throw new Error(`options.reuseFrom: workflow run '${runId}' was not found.`);
|
|
6566
6682
|
if (status.mode !== "workflow") throw new Error(`options.reuseFrom: run '${runId}' is not a workflow run.`);
|
|
6567
6683
|
if (!isReusableWorkflowStopCause(status.workflow?.stopCause)) throw new Error(`options.reuseFrom: workflow run '${runId}' did not stop because its session was replaced or its Pi process exited, so its children cannot be reused.`);
|
|
6568
6684
|
if (status.workflow.scriptDigest !== scriptDigest) throw new Error(`options.reuseFrom: workflow run '${runId}' ran a different workflow script.`);
|
|
6569
6685
|
if (status.cwd !== cwd) throw new Error(`options.reuseFrom: workflow run '${runId}' ran in '${status.cwd}', not '${cwd}'.`);
|
|
6570
|
-
assertWorkflowRunNotClaimed(
|
|
6686
|
+
assertWorkflowRunNotClaimed(path12.join(asyncDirRoot, runId), runId, true, claimOwnerRunId);
|
|
6571
6687
|
return readWorkflowReuseChain(asyncDirRoot, runId, status);
|
|
6572
6688
|
}
|
|
6573
6689
|
function matchWorkflowReuse(source, key, fingerprint) {
|
|
@@ -6579,10 +6695,10 @@ function matchWorkflowReuse(source, key, fingerprint) {
|
|
|
6579
6695
|
|
|
6580
6696
|
// src/workflows/workflow-resume.ts
|
|
6581
6697
|
import { randomUUID as randomUUID6 } from "node:crypto";
|
|
6582
|
-
import * as
|
|
6698
|
+
import * as path13 from "node:path";
|
|
6583
6699
|
var MAX_WORKFLOW_RESUME_ATTEMPTS = 3;
|
|
6584
6700
|
function workflowResumeRefusal(code, reason, runId) {
|
|
6585
|
-
const byHand = code === "launch-missing" || code === "launch-invalid" || code === "structured" || code === "digest" || code === "authority" ? relaunchByHandText(runId) : code === "capacity" || code === "attempts" || code === "launch-failed" ? resumeByHandText(runId) : "";
|
|
6701
|
+
const byHand = code === "launch-missing" || code === "launch-invalid" || code === "structured" || code === "internal" || code === "digest" || code === "authority" || code === "drained" ? relaunchByHandText(runId) : code === "capacity" || code === "attempts" || code === "launch-failed" ? resumeByHandText(runId) : "";
|
|
6586
6702
|
return { code, reason, byHand };
|
|
6587
6703
|
}
|
|
6588
6704
|
function manualWorkflowResumeRefusalText(runId, refusal) {
|
|
@@ -6595,7 +6711,7 @@ function workflowResumeTargetId(asyncDirRoot, params) {
|
|
|
6595
6711
|
if (!isRunId(id)) return void 0;
|
|
6596
6712
|
let status;
|
|
6597
6713
|
try {
|
|
6598
|
-
status = readStatus(
|
|
6714
|
+
status = readStatus(path13.join(asyncDirRoot, id));
|
|
6599
6715
|
} catch {
|
|
6600
6716
|
return void 0;
|
|
6601
6717
|
}
|
|
@@ -6604,18 +6720,19 @@ function workflowResumeTargetId(asyncDirRoot, params) {
|
|
|
6604
6720
|
function prepareWorkflowResume(input) {
|
|
6605
6721
|
const { asyncDirRoot, sourceRunId, trigger } = input;
|
|
6606
6722
|
const refuse = (code, reason) => ({ ok: false, ...workflowResumeRefusal(code, reason, sourceRunId) });
|
|
6607
|
-
const sourceAsyncDir =
|
|
6608
|
-
const
|
|
6609
|
-
if (
|
|
6723
|
+
const sourceAsyncDir = path13.join(asyncDirRoot, sourceRunId);
|
|
6724
|
+
const read = readWorkflowLaunchRecord(asyncDirRoot, sourceRunId);
|
|
6725
|
+
if (!read.ok) return read.missing ? refuse("launch-missing", "launch.json is missing (the run started before launches were saved outside its run directory)") : refuse("launch-invalid", `launch.json is invalid: ${read.error}`);
|
|
6726
|
+
const record = read.record;
|
|
6727
|
+
if (!ownsRun(input.currentSessionId, record.sessionId)) return refuse("not-owned", "it was started in another session; reopen that session to resume it");
|
|
6610
6728
|
if (trigger === "manual") reconcileAsyncRun(sourceAsyncDir);
|
|
6611
6729
|
const status = readStatus(sourceAsyncDir);
|
|
6612
6730
|
if (!status || status.mode !== "workflow" || !isReusableWorkflowStopCause(status.workflow?.stopCause)) return refuse("not-interrupted", "not interrupted; pass message to revive one of its children");
|
|
6731
|
+
if (status.workflow?.drainRequestedAt !== void 0) return refuse("drained", "it was being drained when it was interrupted");
|
|
6613
6732
|
const attempt = (status.workflow?.resumeOrigin?.attempt ?? 0) + (status.workflow?.stopCause === WORKFLOW_STOP_CAUSE_OWNER_EXITED ? 1 : 0);
|
|
6614
6733
|
if (trigger === "auto" && attempt > MAX_WORKFLOW_RESUME_ATTEMPTS) return refuse("attempts", `${MAX_WORKFLOW_RESUME_ATTEMPTS} resumes already followed Pi exits`);
|
|
6615
|
-
const read = readWorkflowLaunchRecord(sourceAsyncDir);
|
|
6616
|
-
if (!read.ok) return read.missing ? refuse("launch-missing", "launch.json is missing (the run started before launches were saved)") : refuse("launch-invalid", `launch.json is invalid: ${read.error}`);
|
|
6617
|
-
const record = read.record;
|
|
6618
6734
|
if (record.source === "structured") return refuse("structured", "launched from tasks/chain");
|
|
6735
|
+
if (record.source === "internal") return refuse("internal", "launched by a schedule or prompt-template delegation");
|
|
6619
6736
|
if (record.source === "script" && (typeof record.params.workflowScript !== "string" || workflowScriptDigest(record.params.workflowScript) !== record.scriptDigest)) {
|
|
6620
6737
|
return refuse("launch-invalid", "launch.json is invalid: its script does not match its scriptDigest");
|
|
6621
6738
|
}
|
|
@@ -6637,7 +6754,7 @@ function prepareWorkflowResume(input) {
|
|
|
6637
6754
|
...record.params,
|
|
6638
6755
|
async: true,
|
|
6639
6756
|
reuseFrom: sourceRunId,
|
|
6640
|
-
...
|
|
6757
|
+
...record.admissionCapabilityCeiling ? { capabilityCeiling: record.admissionCapabilityCeiling } : {}
|
|
6641
6758
|
},
|
|
6642
6759
|
expectedScriptDigest: record.scriptDigest,
|
|
6643
6760
|
resumeOrigin: { sourceRunId, attempt }
|
|
@@ -6692,7 +6809,8 @@ function flattenSubagentToolOptions(params, disabled) {
|
|
|
6692
6809
|
}
|
|
6693
6810
|
|
|
6694
6811
|
// src/runs/background/retained-children.ts
|
|
6695
|
-
import * as
|
|
6812
|
+
import * as fs14 from "node:fs";
|
|
6813
|
+
import * as path14 from "node:path";
|
|
6696
6814
|
var MAX_RETAINED_CHILDREN = 10;
|
|
6697
6815
|
var MAX_RETAINED_CHILD_CANDIDATES = 100;
|
|
6698
6816
|
var MAX_TASK_SUMMARY_LENGTH = 120;
|
|
@@ -6706,7 +6824,7 @@ function retainedSessionFile(sessionFile) {
|
|
|
6706
6824
|
if (!sessionFile) return { state: "not-resumable", reason: "no persisted session file" };
|
|
6707
6825
|
if (!sessionFile.endsWith(".jsonl")) return { state: "not-resumable", reason: "persisted session file is not a .jsonl file" };
|
|
6708
6826
|
try {
|
|
6709
|
-
const stat =
|
|
6827
|
+
const stat = fs14.lstatSync(sessionFile);
|
|
6710
6828
|
if (!stat.isFile() || stat.isSymbolicLink()) return { state: "not-resumable", reason: "persisted session file is not a regular file" };
|
|
6711
6829
|
return { state: "resumable", sessionPath: sessionFile };
|
|
6712
6830
|
} catch (error2) {
|
|
@@ -6723,7 +6841,7 @@ function childResumability(run, step) {
|
|
|
6723
6841
|
if (session.state === "not-resumable") return session;
|
|
6724
6842
|
let recoveryDescriptor;
|
|
6725
6843
|
try {
|
|
6726
|
-
recoveryDescriptor = readAsyncRecoveryDescriptor(run.asyncDir);
|
|
6844
|
+
recoveryDescriptor = readAsyncRecoveryDescriptor(path14.dirname(run.asyncDir), path14.basename(run.asyncDir));
|
|
6727
6845
|
if (!recoveryDescriptor) return { state: "not-resumable", reason: "missing recovery descriptor" };
|
|
6728
6846
|
if (recoveryDescriptor.sourceRunId !== run.id) return { state: "not-resumable", reason: `recovery descriptor belongs to run ${recoveryDescriptor.sourceRunId}` };
|
|
6729
6847
|
if (recoveryDescriptor.agent !== step.agent) return { state: "not-resumable", reason: `recovery descriptor belongs to agent ${recoveryDescriptor.agent}` };
|
|
@@ -6733,7 +6851,7 @@ function childResumability(run, step) {
|
|
|
6733
6851
|
let requiredCwd;
|
|
6734
6852
|
try {
|
|
6735
6853
|
requiredCwd = resolveRetainedWorktreeCwd(parallelHandoffPath(run.asyncDir), run.id, step.index, step.worktreePath) ?? recoveryDescriptor.cwd ?? run.cwd;
|
|
6736
|
-
if (!requiredCwd || !
|
|
6854
|
+
if (!requiredCwd || !fs14.statSync(requiredCwd).isDirectory()) return { state: "not-resumable", reason: `required cwd is missing: ${requiredCwd ?? "unknown"}` };
|
|
6737
6855
|
} catch (error2) {
|
|
6738
6856
|
return { state: "not-resumable", reason: `resume dependency unavailable: ${error2 instanceof Error ? error2.message : String(error2)}` };
|
|
6739
6857
|
}
|
|
@@ -6793,9 +6911,52 @@ function formatRetainedChildren(children) {
|
|
|
6793
6911
|
].join("\n");
|
|
6794
6912
|
}
|
|
6795
6913
|
|
|
6914
|
+
// src/extension/subagent-launch-tool.ts
|
|
6915
|
+
import { Type as Type2 } from "typebox";
|
|
6916
|
+
var SUBAGENT_LAUNCH_TOOL = "subagent_launch";
|
|
6917
|
+
var parameters = Type2.Object({
|
|
6918
|
+
workflowRunId: Type2.String(),
|
|
6919
|
+
key: Type2.String(),
|
|
6920
|
+
agent: Type2.Optional(Type2.String()),
|
|
6921
|
+
task: Type2.Optional(Type2.String()),
|
|
6922
|
+
cwd: Type2.Optional(Type2.String()),
|
|
6923
|
+
model: Type2.Optional(Type2.String()),
|
|
6924
|
+
async: Type2.Optional(Type2.Boolean()),
|
|
6925
|
+
worktree: Type2.Optional(Type2.Boolean()),
|
|
6926
|
+
resume: Type2.Optional(Type2.String()),
|
|
6927
|
+
commands: Type2.Optional(Type2.Array(Type2.Object({
|
|
6928
|
+
command: Type2.String(),
|
|
6929
|
+
cwd: Type2.Optional(Type2.String()),
|
|
6930
|
+
env: Type2.Optional(Type2.Record(Type2.String(), Type2.String()))
|
|
6931
|
+
}))),
|
|
6932
|
+
output: Type2.Optional(Type2.String())
|
|
6933
|
+
});
|
|
6934
|
+
function registerSubagentLaunchTool(pi) {
|
|
6935
|
+
pi.registerTool({
|
|
6936
|
+
name: SUBAGENT_LAUNCH_TOOL,
|
|
6937
|
+
label: "Subagent launch",
|
|
6938
|
+
description: "A workflow is about to start this subagent. Blocking this call stops that child from starting.",
|
|
6939
|
+
parameters,
|
|
6940
|
+
exposure: "deferred",
|
|
6941
|
+
async execute() {
|
|
6942
|
+
return { content: [{ type: "text", text: "Records approval for a workflow child launch; it starts nothing itself." }], details: {} };
|
|
6943
|
+
}
|
|
6944
|
+
});
|
|
6945
|
+
}
|
|
6946
|
+
async function approveWorkflowChildLaunch(ctx, describe, signal) {
|
|
6947
|
+
if (!("executeTool" in ctx)) return void 0;
|
|
6948
|
+
const toolCtx = ctx;
|
|
6949
|
+
if (!toolCtx.tools.some((tool) => tool.name === SUBAGENT_LAUNCH_TOOL)) return void 0;
|
|
6950
|
+
const args = describe();
|
|
6951
|
+
const outcome = await toolCtx.executeTool(SUBAGENT_LAUNCH_TOOL, args, { signal });
|
|
6952
|
+
if (!outcome.isError) return void 0;
|
|
6953
|
+
const reason = outcome.result.content.flatMap((block) => block.type === "text" ? [block.text] : []).join("\n").trim();
|
|
6954
|
+
return `Workflow child '${args.key}' was not started: the ${SUBAGENT_LAUNCH_TOOL} call was refused${reason ? `: ${reason}` : "."}`;
|
|
6955
|
+
}
|
|
6956
|
+
|
|
6796
6957
|
// src/runs/shared/external-job-bridge.ts
|
|
6797
6958
|
import { randomUUID as randomUUID7 } from "node:crypto";
|
|
6798
|
-
import * as
|
|
6959
|
+
import * as fs15 from "node:fs";
|
|
6799
6960
|
import * as os2 from "node:os";
|
|
6800
6961
|
import * as path15 from "node:path";
|
|
6801
6962
|
var EXTERNAL_JOB_BRIDGE_REQUEST_DIR = "external-job-requests";
|
|
@@ -6828,18 +6989,18 @@ function dispatchClaimHandlePath(claimDir) {
|
|
|
6828
6989
|
return path15.join(claimDir, "handle.json");
|
|
6829
6990
|
}
|
|
6830
6991
|
function completedDispatchClaimExists(asyncDir, id) {
|
|
6831
|
-
return
|
|
6992
|
+
return fs15.existsSync(dispatchClaimCompletedPath(dispatchClaimDir(asyncDir, id)));
|
|
6832
6993
|
}
|
|
6833
6994
|
function responsePath(asyncDir, id) {
|
|
6834
6995
|
return path15.join(responseDir(asyncDir), `${id}.json`);
|
|
6835
6996
|
}
|
|
6836
6997
|
function readJson2(filePath) {
|
|
6837
|
-
return JSON.parse(
|
|
6998
|
+
return JSON.parse(fs15.readFileSync(filePath, "utf-8"));
|
|
6838
6999
|
}
|
|
6839
7000
|
function processStartIdentity(pid) {
|
|
6840
7001
|
if (process.platform === "linux") {
|
|
6841
7002
|
try {
|
|
6842
|
-
const stat =
|
|
7003
|
+
const stat = fs15.readFileSync(`/proc/${pid}/stat`, "utf-8");
|
|
6843
7004
|
const commandEnd = stat.lastIndexOf(")");
|
|
6844
7005
|
if (commandEnd === -1) return void 0;
|
|
6845
7006
|
const fields = stat.slice(commandEnd + 1).trim().split(/\s+/);
|
|
@@ -6959,16 +7120,16 @@ function claimDispatchRequest(asyncDir, filePath, request) {
|
|
|
6959
7120
|
const claimDir = dispatchClaimDir(asyncDir, request.id);
|
|
6960
7121
|
const tempClaimDir = dispatchClaimTempDir(asyncDir, request.id);
|
|
6961
7122
|
try {
|
|
6962
|
-
|
|
7123
|
+
fs15.mkdirSync(tempClaimDir);
|
|
6963
7124
|
writeAtomicJson(path15.join(tempClaimDir, "owner.json"), owner);
|
|
6964
7125
|
writeAtomicJson(path15.join(tempClaimDir, "request.json"), claimed);
|
|
6965
|
-
|
|
7126
|
+
fs15.renameSync(tempClaimDir, claimDir);
|
|
6966
7127
|
} catch (error2) {
|
|
6967
|
-
|
|
7128
|
+
fs15.rmSync(tempClaimDir, { recursive: true, force: true });
|
|
6968
7129
|
if (isClaimConflictError(error2)) return void 0;
|
|
6969
7130
|
throw error2;
|
|
6970
7131
|
}
|
|
6971
|
-
|
|
7132
|
+
fs15.rmSync(filePath, { force: true });
|
|
6972
7133
|
return { request: claimed, filePath: claimDir };
|
|
6973
7134
|
}
|
|
6974
7135
|
function parseClaimOwner(value) {
|
|
@@ -7050,18 +7211,18 @@ function createChildExternalJobBridgeSweeper() {
|
|
|
7050
7211
|
function serviceExternalJobBridgeRequests(asyncDir) {
|
|
7051
7212
|
let files;
|
|
7052
7213
|
try {
|
|
7053
|
-
files =
|
|
7214
|
+
files = fs15.readdirSync(requestDir(asyncDir), { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".json") && !completedDispatchClaimExists(asyncDir, entry.name.replace(/\.json$/, "")) || entry.isDirectory() && entry.name.endsWith(".claim") && !fs15.existsSync(dispatchClaimCompletedPath(path15.join(requestDir(asyncDir), entry.name)))).map((entry) => entry.name).slice(0, MAX_REQUESTS_PER_SWEEP);
|
|
7054
7215
|
} catch (error2) {
|
|
7055
7216
|
if (error2.code === "ENOENT") return;
|
|
7056
7217
|
throw error2;
|
|
7057
7218
|
}
|
|
7058
|
-
|
|
7219
|
+
fs15.mkdirSync(responseDir(asyncDir), { recursive: true });
|
|
7059
7220
|
for (const file of files) {
|
|
7060
7221
|
serviceExternalJobBridgeRequestFile(asyncDir, file);
|
|
7061
7222
|
}
|
|
7062
7223
|
}
|
|
7063
7224
|
function serviceExternalJobBridgeRequestFile(asyncDir, file) {
|
|
7064
|
-
|
|
7225
|
+
fs15.mkdirSync(responseDir(asyncDir), { recursive: true });
|
|
7065
7226
|
if (file.endsWith(".claim")) {
|
|
7066
7227
|
serviceExternalJobDispatchClaim(asyncDir, file);
|
|
7067
7228
|
return;
|
|
@@ -7082,14 +7243,14 @@ function serviceExternalJobBridgeRequestFile(asyncDir, file) {
|
|
|
7082
7243
|
message: error2 instanceof Error ? error2.message : String(error2),
|
|
7083
7244
|
completedAt: Date.now()
|
|
7084
7245
|
});
|
|
7085
|
-
|
|
7246
|
+
fs15.rmSync(filePath, { force: true });
|
|
7086
7247
|
return;
|
|
7087
7248
|
}
|
|
7088
7249
|
if (isDispatchOperation(request.operation) && completedDispatchClaimExists(asyncDir, request.id)) {
|
|
7089
|
-
|
|
7250
|
+
fs15.rmSync(filePath, { force: true });
|
|
7090
7251
|
return;
|
|
7091
7252
|
}
|
|
7092
|
-
if (inFlight.has(request.id) ||
|
|
7253
|
+
if (inFlight.has(request.id) || fs15.existsSync(responsePath(asyncDir, request.id))) return;
|
|
7093
7254
|
if (isDispatchOperation(request.operation) && request.claimedAt !== void 0) return;
|
|
7094
7255
|
const claimed = isDispatchOperation(request.operation) ? claimDispatchRequest(asyncDir, filePath, request) : { request, filePath };
|
|
7095
7256
|
if (!claimed) return;
|
|
@@ -7100,7 +7261,7 @@ function serviceExternalJobBridgeRequestFile(asyncDir, file) {
|
|
|
7100
7261
|
if (isDispatchOperation(claimedRequest.operation)) {
|
|
7101
7262
|
writeAtomicJson(dispatchClaimCompletedPath(claimed.filePath), { completedAt: Date.now() });
|
|
7102
7263
|
} else {
|
|
7103
|
-
|
|
7264
|
+
fs15.rmSync(claimed.filePath, { recursive: true, force: true });
|
|
7104
7265
|
}
|
|
7105
7266
|
}).catch((error2) => {
|
|
7106
7267
|
writeAtomicJson(responsePath(asyncDir, claimedRequest.id), {
|
|
@@ -7119,10 +7280,10 @@ function serviceExternalJobBridgeRequestFile(asyncDir, file) {
|
|
|
7119
7280
|
}
|
|
7120
7281
|
function serviceExternalJobDispatchClaim(asyncDir, file) {
|
|
7121
7282
|
const claimDir = path15.join(requestDir(asyncDir), file);
|
|
7122
|
-
if (
|
|
7283
|
+
if (fs15.existsSync(dispatchClaimCompletedPath(claimDir))) return;
|
|
7123
7284
|
const owner = readClaimOwner(claimDir);
|
|
7124
|
-
if (!owner &&
|
|
7125
|
-
|
|
7285
|
+
if (!owner && fs15.existsSync(requestPath(asyncDir, file.replace(/\.claim$/, ""))) && !fs15.existsSync(responsePath(asyncDir, file.replace(/\.claim$/, "")))) {
|
|
7286
|
+
fs15.rmSync(claimDir, { recursive: true, force: true });
|
|
7126
7287
|
return;
|
|
7127
7288
|
}
|
|
7128
7289
|
if (!claimOwnerIsDead(owner)) return;
|
|
@@ -7132,7 +7293,7 @@ function serviceExternalJobDispatchClaim(asyncDir, file) {
|
|
|
7132
7293
|
} catch {
|
|
7133
7294
|
return;
|
|
7134
7295
|
}
|
|
7135
|
-
if (!isDispatchOperation(request.operation) ||
|
|
7296
|
+
if (!isDispatchOperation(request.operation) || fs15.existsSync(responsePath(asyncDir, request.id))) return;
|
|
7136
7297
|
const handle = readClaimHandle(request.provider, claimDir);
|
|
7137
7298
|
if (handle) {
|
|
7138
7299
|
writeAtomicJson(responsePath(asyncDir, request.id), {
|
|
@@ -7144,7 +7305,7 @@ function serviceExternalJobDispatchClaim(asyncDir, file) {
|
|
|
7144
7305
|
completedAt: Date.now()
|
|
7145
7306
|
});
|
|
7146
7307
|
writeAtomicJson(dispatchClaimCompletedPath(claimDir), { completedAt: Date.now() });
|
|
7147
|
-
|
|
7308
|
+
fs15.rmSync(requestPath(asyncDir, request.id), { force: true });
|
|
7148
7309
|
return;
|
|
7149
7310
|
}
|
|
7150
7311
|
writeAtomicJson(responsePath(asyncDir, request.id), {
|
|
@@ -7156,8 +7317,8 @@ function serviceExternalJobDispatchClaim(asyncDir, file) {
|
|
|
7156
7317
|
message: `External-job ${request.operation} for provider '${request.provider}' was claimed by a host process that is no longer alive before a provider job id was committed. Refusing to redispatch the prompt automatically.`,
|
|
7157
7318
|
completedAt: Date.now()
|
|
7158
7319
|
});
|
|
7159
|
-
|
|
7160
|
-
|
|
7320
|
+
fs15.rmSync(claimDir, { recursive: true, force: true });
|
|
7321
|
+
fs15.rmSync(requestPath(asyncDir, request.id), { force: true });
|
|
7161
7322
|
}
|
|
7162
7323
|
|
|
7163
7324
|
// src/shared/provider-diagnostics.ts
|
|
@@ -7283,7 +7444,6 @@ export {
|
|
|
7283
7444
|
COMPLETION_ACTION,
|
|
7284
7445
|
STATUS_ACTION,
|
|
7285
7446
|
createParentWake,
|
|
7286
|
-
writeWorkflowLaunchRecord,
|
|
7287
7447
|
resumedRunStarted,
|
|
7288
7448
|
workflowResumeClaimState,
|
|
7289
7449
|
claimWorkflowResume,
|
|
@@ -7312,7 +7472,7 @@ export {
|
|
|
7312
7472
|
childSessionHasQueuedMessages,
|
|
7313
7473
|
childSessionFactory,
|
|
7314
7474
|
childSessionFactoryModule,
|
|
7315
|
-
|
|
7475
|
+
disposeChildSessionsForParent,
|
|
7316
7476
|
resolveInjectableAgents,
|
|
7317
7477
|
applyInjectionBlock,
|
|
7318
7478
|
renderInjectionBlock,
|
|
@@ -7332,5 +7492,7 @@ export {
|
|
|
7332
7492
|
prepareWorkflowResume,
|
|
7333
7493
|
flattenSubagentToolOptions,
|
|
7334
7494
|
listRetainedChildren,
|
|
7335
|
-
formatRetainedChildren
|
|
7495
|
+
formatRetainedChildren,
|
|
7496
|
+
registerSubagentLaunchTool,
|
|
7497
|
+
approveWorkflowChildLaunch
|
|
7336
7498
|
};
|