@fitchmultz/pi-subagents 0.0.0-stage → 0.44.4
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 +1645 -0
- package/LICENSE +21 -0
- package/README.md +1529 -2
- package/agents/context-builder.md +97 -0
- package/agents/debugger.md +51 -0
- package/agents/delegate.md +13 -0
- package/agents/fixer.md +37 -0
- package/agents/oracle.md +71 -0
- package/agents/planner.md +72 -0
- package/agents/researcher.md +51 -0
- package/agents/reviewer-claude.md +69 -0
- package/agents/reviewer-gpt.md +68 -0
- package/agents/reviewer-ponytail.md +82 -0
- package/agents/reviewer-security.md +81 -0
- package/agents/reviewer.md +69 -0
- package/agents/scout.md +66 -0
- package/agents/ui-designer.md +51 -0
- package/agents/watcher.md +26 -0
- package/agents/worker.md +46 -0
- package/agents/writer.md +36 -0
- package/dist/agents/agent-management.js +923 -0
- package/dist/agents/agent-scope.js +7 -0
- package/dist/agents/agent-selection.js +20 -0
- package/dist/agents/agent-serializer.js +100 -0
- package/dist/agents/agents.js +752 -0
- package/dist/agents/chain-serializer.js +367 -0
- package/dist/agents/frontmatter.js +21 -0
- package/dist/agents/identity.js +29 -0
- package/dist/agents/skills.js +570 -0
- package/dist/extension/build-info.js +1 -0
- package/dist/extension/compact-tools.js +112 -0
- package/dist/extension/config.js +22 -0
- package/dist/extension/control-notices.js +29 -0
- package/dist/extension/doctor.js +143 -0
- package/dist/extension/fanout-child.js +326 -0
- package/dist/extension/index.js +577 -0
- package/dist/extension/schemas.js +416 -0
- package/dist/extension/tool-input.js +20 -0
- package/dist/extension/tool-result.js +14 -0
- package/dist/history/canonical-result.js +81 -0
- package/dist/history/database.js +72 -0
- package/dist/history/index.js +194 -0
- package/dist/history/ingest.js +447 -0
- package/dist/history/queries.js +350 -0
- package/dist/history/store.js +216 -0
- package/dist/history/types.js +4 -0
- package/dist/history/worker.js +461 -0
- package/dist/intercom/intercom-bridge.js +112 -0
- package/dist/intercom/live-intercom.js +94 -0
- package/dist/intercom/result-intercom.js +373 -0
- package/dist/pi-intercom/agent-dir.js +10 -0
- package/dist/pi-intercom/broker/broker.js +426 -0
- package/dist/pi-intercom/broker/client.js +492 -0
- package/dist/pi-intercom/broker/framing.js +65 -0
- package/dist/pi-intercom/broker/paths.js +42 -0
- package/dist/pi-intercom/broker/pid.js +66 -0
- package/dist/pi-intercom/broker/spawn.js +221 -0
- package/dist/pi-intercom/config.js +102 -0
- package/dist/pi-intercom/index.js +2942 -0
- package/dist/pi-intercom/reply-tracker.js +182 -0
- package/dist/pi-intercom/session-targets.js +128 -0
- package/dist/pi-intercom/subagent-live-events.js +132 -0
- package/dist/pi-intercom/topics.js +157 -0
- package/dist/pi-intercom/types.js +163 -0
- package/dist/pi-intercom/ui/compose.js +269 -0
- package/dist/pi-intercom/ui/inline-message.js +80 -0
- package/dist/pi-intercom/ui/session-list.js +124 -0
- package/dist/runs/background/async-control.js +95 -0
- package/dist/runs/background/async-execution.js +676 -0
- package/dist/runs/background/async-job-tracker.js +383 -0
- package/dist/runs/background/async-result-file.js +58 -0
- package/dist/runs/background/async-resume.js +305 -0
- package/dist/runs/background/async-status.js +442 -0
- package/dist/runs/background/completion-dedupe.js +69 -0
- package/dist/runs/background/completion-delivery.js +245 -0
- package/dist/runs/background/notify.js +71 -0
- package/dist/runs/background/parallel-groups.js +55 -0
- package/dist/runs/background/result-watcher.js +426 -0
- package/dist/runs/background/run-id-resolver.js +64 -0
- package/dist/runs/background/run-status.js +382 -0
- package/dist/runs/background/stale-run-reconciler.js +335 -0
- package/dist/runs/background/subagent-runner-launcher.js +55 -0
- package/dist/runs/background/subagent-runner.js +1872 -0
- package/dist/runs/background/top-level-async.js +5 -0
- package/dist/runs/foreground/chain-clarify.js +1152 -0
- package/dist/runs/foreground/clarify-invocation.js +72 -0
- package/dist/runs/foreground/execution-input.js +423 -0
- package/dist/runs/foreground/foreground-control.js +817 -0
- package/dist/runs/foreground/question-control.js +77 -0
- package/dist/runs/foreground/run-async-path.js +205 -0
- package/dist/runs/foreground/subagent-executor.js +442 -0
- package/dist/runs/foreground/subagent-params.js +165 -0
- package/dist/runs/foreground/wait-run.js +139 -0
- package/dist/runs/shared/acceptance-contract.js +253 -0
- package/dist/runs/shared/acceptance-evaluation.js +256 -0
- package/dist/runs/shared/acceptance-finalization.js +280 -0
- package/dist/runs/shared/acceptance-reports.js +147 -0
- package/dist/runs/shared/acceptance.js +4 -0
- package/dist/runs/shared/chain-outputs.js +110 -0
- package/dist/runs/shared/child-attempt.js +693 -0
- package/dist/runs/shared/child-execution-cwd.js +96 -0
- package/dist/runs/shared/child-observations.js +114 -0
- package/dist/runs/shared/claude-code.js +199 -0
- package/dist/runs/shared/completion-guard.js +31 -0
- package/dist/runs/shared/dynamic-fanout.js +274 -0
- package/dist/runs/shared/history-index.js +72 -0
- package/dist/runs/shared/mcp-direct-tool-allowlist.js +334 -0
- package/dist/runs/shared/model-fallback.js +185 -0
- package/dist/runs/shared/mutating-tool-guard.js +170 -0
- package/dist/runs/shared/native-finalization.js +101 -0
- package/dist/runs/shared/native-usage.js +153 -0
- package/dist/runs/shared/nested-events.js +700 -0
- package/dist/runs/shared/nested-path.js +48 -0
- package/dist/runs/shared/nested-render.js +108 -0
- package/dist/runs/shared/parallel-utils.js +61 -0
- package/dist/runs/shared/parent-receipts.js +68 -0
- package/dist/runs/shared/parent-usage.js +121 -0
- package/dist/runs/shared/pi-args.js +310 -0
- package/dist/runs/shared/pi-spawn.js +52 -0
- package/dist/runs/shared/run-history-queries.js +45 -0
- package/dist/runs/shared/run-history.js +103 -0
- package/dist/runs/shared/run-id-ambiguity.js +4 -0
- package/dist/runs/shared/run-records.js +679 -0
- package/dist/runs/shared/session-cwd-preload.js +33 -0
- package/dist/runs/shared/single-output.js +222 -0
- package/dist/runs/shared/streaming-text.js +15 -0
- package/dist/runs/shared/structured-output.js +55 -0
- package/dist/runs/shared/subagent-control.js +179 -0
- package/dist/runs/shared/subagent-prompt-runtime.js +197 -0
- package/dist/runs/shared/subagent-tool-loop-guard.js +66 -0
- package/dist/runs/shared/supervisor-questions.js +320 -0
- package/dist/runs/shared/workflow-graph.js +214 -0
- package/dist/runs/shared/workflow-policy.js +84 -0
- package/dist/runs/shared/worktree.js +525 -0
- package/dist/shared/agent-context-policy.js +126 -0
- package/dist/shared/artifacts.js +96 -0
- package/dist/shared/atomic-json.js +13 -0
- package/dist/shared/cooperative.js +20 -0
- package/dist/shared/execution-cwd.js +14 -0
- package/dist/shared/file-coalescer.js +21 -0
- package/dist/shared/fork-context.js +49 -0
- package/dist/shared/formatters.js +85 -0
- package/dist/shared/journal-reader.js +407 -0
- package/dist/shared/lazy-tools.js +32 -0
- package/dist/shared/model-info.js +68 -0
- package/dist/shared/native-session.js +15 -0
- package/dist/shared/native-tui.js +18 -0
- package/dist/shared/native-typebox.js +20 -0
- package/dist/shared/post-exit-stdio-guard.js +197 -0
- package/dist/shared/prompt-sections.js +8 -0
- package/dist/shared/session-entries.js +52 -0
- package/dist/shared/session-identity.js +14 -0
- package/dist/shared/settings.js +254 -0
- package/dist/shared/status-format.js +111 -0
- package/dist/shared/temp-root.js +114 -0
- package/dist/shared/types.js +207 -0
- package/dist/shared/ui-mode.js +3 -0
- package/dist/shared/utils.js +334 -0
- package/dist/slash/prompt-template-bridge.js +298 -0
- package/dist/slash/slash-bridge.js +116 -0
- package/dist/slash/slash-commands.js +607 -0
- package/dist/slash/slash-live-state.js +246 -0
- package/dist/tui/action-hints.js +75 -0
- package/dist/tui/agent-history.js +197 -0
- package/dist/tui/agent-view.js +1656 -0
- package/dist/tui/render.js +1515 -0
- package/docs/intercom.md +579 -0
- package/docs/performance.md +121 -0
- package/package.json +101 -4
- package/prompts/gather-context-and-clarify.md +14 -0
- package/prompts/parallel-cleanup.md +62 -0
- package/prompts/parallel-context-build.md +56 -0
- package/prompts/parallel-handoff-plan.md +62 -0
- package/prompts/parallel-research.md +51 -0
- package/prompts/parallel-review.md +59 -0
- package/prompts/review-loop.md +42 -0
- package/scripts/build.mjs +134 -0
- package/scripts/check-compat.mjs +48 -0
- package/scripts/compat-host.mjs +19 -0
- package/scripts/linux-smoke.sh +51 -0
- package/scripts/local-install-smoke.mjs +66 -0
- package/scripts/native-package-smoke.mjs +82 -0
- package/scripts/package-smoke.mjs +205 -0
- package/scripts/prepare.mjs +67 -0
- package/scripts/real-pi-smoke.mjs +415 -0
- package/scripts/run-tests.mjs +149 -0
- package/skills/pi-intercom/SKILL.md +113 -0
- package/skills/pi-intercom/evals/evals.json +29 -0
- package/skills/pi-intercom/evals/trigger-evals.json +47 -0
- package/skills/pi-intercom/references/peer-sessions.md +69 -0
- package/skills/pi-subagents/SKILL.md +76 -0
- package/skills/pi-subagents/evals/evals.json +29 -0
- package/skills/pi-subagents/evals/trigger-evals.json +42 -0
- package/skills/pi-subagents/references/full-orchestration-guide.md +863 -0
- package/src/agents/agent-management.ts +813 -0
- package/src/agents/agent-scope.ts +7 -0
- package/src/agents/agent-selection.ts +23 -0
- package/src/agents/agent-serializer.ts +99 -0
- package/src/agents/agents.ts +916 -0
- package/src/agents/chain-serializer.ts +329 -0
- package/src/agents/frontmatter.ts +21 -0
- package/src/agents/identity.ts +30 -0
- package/src/agents/skills.ts +637 -0
- package/src/extension/build-info.ts +2 -0
- package/src/extension/compact-tools.ts +114 -0
- package/src/extension/config.ts +23 -0
- package/src/extension/control-notices.ts +47 -0
- package/src/extension/doctor.ts +171 -0
- package/src/extension/fanout-child.ts +312 -0
- package/src/extension/index.ts +649 -0
- package/src/extension/schemas.ts +444 -0
- package/src/extension/tool-input.ts +19 -0
- package/src/extension/tool-result.ts +16 -0
- package/src/history/canonical-result.ts +62 -0
- package/src/history/database.ts +59 -0
- package/src/history/index.ts +152 -0
- package/src/history/ingest.ts +332 -0
- package/src/history/queries.ts +241 -0
- package/src/history/store.ts +203 -0
- package/src/history/types.ts +166 -0
- package/src/history/worker.ts +317 -0
- package/src/intercom/intercom-bridge.ts +123 -0
- package/src/intercom/live-intercom.ts +104 -0
- package/src/intercom/result-intercom.ts +429 -0
- package/src/pi-intercom/agent-dir.ts +9 -0
- package/src/pi-intercom/broker/broker.ts +463 -0
- package/src/pi-intercom/broker/client.ts +558 -0
- package/src/pi-intercom/broker/framing.ts +77 -0
- package/src/pi-intercom/broker/paths.ts +47 -0
- package/src/pi-intercom/broker/pid.ts +59 -0
- package/src/pi-intercom/broker/spawn.ts +248 -0
- package/src/pi-intercom/config.ts +142 -0
- package/src/pi-intercom/index.ts +2929 -0
- package/src/pi-intercom/reply-tracker.ts +211 -0
- package/src/pi-intercom/session-targets.ts +172 -0
- package/src/pi-intercom/subagent-live-events.ts +133 -0
- package/src/pi-intercom/topics.ts +125 -0
- package/src/pi-intercom/types.ts +271 -0
- package/src/pi-intercom/ui/compose.ts +289 -0
- package/src/pi-intercom/ui/inline-message.ts +92 -0
- package/src/pi-intercom/ui/session-list.ts +139 -0
- package/src/runs/background/async-control.ts +89 -0
- package/src/runs/background/async-execution.ts +850 -0
- package/src/runs/background/async-job-tracker.ts +385 -0
- package/src/runs/background/async-result-file.ts +62 -0
- package/src/runs/background/async-resume.ts +333 -0
- package/src/runs/background/async-status.ts +481 -0
- package/src/runs/background/completion-dedupe.ts +79 -0
- package/src/runs/background/completion-delivery.ts +195 -0
- package/src/runs/background/notify.ts +123 -0
- package/src/runs/background/parallel-groups.ts +53 -0
- package/src/runs/background/result-watcher.ts +423 -0
- package/src/runs/background/run-id-resolver.ts +69 -0
- package/src/runs/background/run-status.ts +384 -0
- package/src/runs/background/stale-run-reconciler.ts +369 -0
- package/src/runs/background/subagent-runner-launcher.ts +56 -0
- package/src/runs/background/subagent-runner.ts +2053 -0
- package/src/runs/background/top-level-async.ts +13 -0
- package/src/runs/foreground/chain-clarify.ts +1340 -0
- package/src/runs/foreground/clarify-invocation.ts +77 -0
- package/src/runs/foreground/execution-input.ts +467 -0
- package/src/runs/foreground/foreground-control.ts +821 -0
- package/src/runs/foreground/question-control.ts +70 -0
- package/src/runs/foreground/run-async-path.ts +243 -0
- package/src/runs/foreground/subagent-executor.ts +501 -0
- package/src/runs/foreground/subagent-params.ts +320 -0
- package/src/runs/foreground/wait-run.ts +121 -0
- package/src/runs/shared/acceptance-contract.ts +257 -0
- package/src/runs/shared/acceptance-evaluation.ts +275 -0
- package/src/runs/shared/acceptance-finalization.ts +353 -0
- package/src/runs/shared/acceptance-reports.ts +152 -0
- package/src/runs/shared/acceptance.ts +33 -0
- package/src/runs/shared/chain-outputs.ts +114 -0
- package/src/runs/shared/child-attempt.ts +623 -0
- package/src/runs/shared/child-execution-cwd.ts +91 -0
- package/src/runs/shared/child-observations.ts +99 -0
- package/src/runs/shared/claude-code.ts +243 -0
- package/src/runs/shared/completion-guard.ts +35 -0
- package/src/runs/shared/dynamic-fanout.ts +295 -0
- package/src/runs/shared/history-index.ts +69 -0
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +376 -0
- package/src/runs/shared/model-fallback.ts +219 -0
- package/src/runs/shared/mutating-tool-guard.ts +194 -0
- package/src/runs/shared/native-finalization.ts +128 -0
- package/src/runs/shared/native-usage.ts +113 -0
- package/src/runs/shared/nested-events.ts +752 -0
- package/src/runs/shared/nested-path.ts +52 -0
- package/src/runs/shared/nested-render.ts +119 -0
- package/src/runs/shared/parallel-utils.ts +153 -0
- package/src/runs/shared/parent-receipts.ts +59 -0
- package/src/runs/shared/parent-usage.ts +121 -0
- package/src/runs/shared/pi-args.ts +350 -0
- package/src/runs/shared/pi-spawn.ts +52 -0
- package/src/runs/shared/run-history-queries.ts +44 -0
- package/src/runs/shared/run-history.ts +93 -0
- package/src/runs/shared/run-id-ambiguity.ts +4 -0
- package/src/runs/shared/run-records.ts +607 -0
- package/src/runs/shared/session-cwd-preload.ts +27 -0
- package/src/runs/shared/single-output.ts +267 -0
- package/src/runs/shared/streaming-text.ts +18 -0
- package/src/runs/shared/structured-output.ts +68 -0
- package/src/runs/shared/subagent-control.ts +219 -0
- package/src/runs/shared/subagent-prompt-runtime.ts +201 -0
- package/src/runs/shared/subagent-tool-loop-guard.ts +89 -0
- package/src/runs/shared/supervisor-questions.ts +372 -0
- package/src/runs/shared/workflow-graph.ts +220 -0
- package/src/runs/shared/workflow-policy.ts +125 -0
- package/src/runs/shared/worktree.ts +635 -0
- package/src/shared/agent-context-policy.ts +184 -0
- package/src/shared/artifacts.ts +95 -0
- package/src/shared/atomic-json.ts +16 -0
- package/src/shared/cooperative.ts +21 -0
- package/src/shared/execution-cwd.ts +14 -0
- package/src/shared/file-coalescer.ts +29 -0
- package/src/shared/fork-context.ts +68 -0
- package/src/shared/formatters.ts +84 -0
- package/src/shared/journal-reader.ts +333 -0
- package/src/shared/lazy-tools.ts +36 -0
- package/src/shared/model-info.ts +81 -0
- package/src/shared/native-session.ts +8 -0
- package/src/shared/native-tui.ts +10 -0
- package/src/shared/native-typebox.ts +14 -0
- package/src/shared/post-exit-stdio-guard.ts +204 -0
- package/src/shared/prompt-sections.ts +10 -0
- package/src/shared/session-entries.ts +49 -0
- package/src/shared/session-identity.ts +18 -0
- package/src/shared/settings.ts +384 -0
- package/src/shared/status-format.ts +123 -0
- package/src/shared/temp-root.ts +107 -0
- package/src/shared/types.ts +1259 -0
- package/src/shared/ui-mode.ts +5 -0
- package/src/shared/utils.ts +342 -0
- package/src/slash/prompt-template-bridge.ts +408 -0
- package/src/slash/slash-bridge.ts +178 -0
- package/src/slash/slash-commands.ts +617 -0
- package/src/slash/slash-live-state.ts +292 -0
- package/src/tui/action-hints.ts +69 -0
- package/src/tui/agent-history.ts +210 -0
- package/src/tui/agent-view.ts +1323 -0
- package/src/tui/render.ts +1550 -0
- package/tsconfig.build.json +12 -0
- package/tsconfig.json +19 -0
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
2
|
+
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
3
|
+
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
4
|
+
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
|
|
5
|
+
});
|
|
6
|
+
}
|
|
7
|
+
return path;
|
|
8
|
+
};
|
|
9
|
+
import { realpathSync } from "node:fs";
|
|
10
|
+
import { dirname, join, resolve } from "node:path";
|
|
11
|
+
import { pathToFileURL } from "node:url";
|
|
12
|
+
// Node loads this before Pi selects its session and creates cwd-bound services.
|
|
13
|
+
// Use the SDK beside the actual CLI (bundled or unbundled), never our dev peer.
|
|
14
|
+
const configuration = process.env.PI_SUBAGENT_SESSION_CWD;
|
|
15
|
+
if (configuration) {
|
|
16
|
+
const { sessionFile, cwd, nodeOptions } = JSON.parse(configuration);
|
|
17
|
+
const sdkUrl = pathToFileURL(join(dirname(realpathSync(process.argv[1])), "index.js"));
|
|
18
|
+
const { SessionManager } = await import(__rewriteRelativeImportExtension(sdkUrl.href));
|
|
19
|
+
const open = SessionManager.open;
|
|
20
|
+
SessionManager.open = (file, sessionDir, cwdOverride) => {
|
|
21
|
+
if (resolve(file) !== sessionFile)
|
|
22
|
+
return open(file, sessionDir, cwdOverride);
|
|
23
|
+
SessionManager.open = open;
|
|
24
|
+
// Keep the preload through a native launcher, then clear it before tools or nested children start.
|
|
25
|
+
delete process.env.PI_SUBAGENT_SESSION_CWD;
|
|
26
|
+
if (nodeOptions === undefined)
|
|
27
|
+
delete process.env.NODE_OPTIONS;
|
|
28
|
+
else
|
|
29
|
+
process.env.NODE_OPTIONS = nodeOptions;
|
|
30
|
+
// Public Pi SDK override preserves the file, header, identity and history.
|
|
31
|
+
return open(file, sessionDir, cwd);
|
|
32
|
+
};
|
|
33
|
+
}
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
export function normalizeSingleOutputOverride(output, defaultOutput) {
|
|
4
|
+
if (output === false || output === "false")
|
|
5
|
+
return false;
|
|
6
|
+
if (output === true || output === "true")
|
|
7
|
+
return defaultOutput;
|
|
8
|
+
if (typeof output === "string" && output.length > 0)
|
|
9
|
+
return output;
|
|
10
|
+
return undefined;
|
|
11
|
+
}
|
|
12
|
+
export function resolveSingleOutputPath(output, runtimeCwd, requestedCwd) {
|
|
13
|
+
if (typeof output !== "string" || !output || output === "false" || output === "true")
|
|
14
|
+
return undefined;
|
|
15
|
+
if (path.isAbsolute(output))
|
|
16
|
+
return output;
|
|
17
|
+
const baseCwd = requestedCwd
|
|
18
|
+
? (path.isAbsolute(requestedCwd) ? requestedCwd : path.resolve(runtimeCwd, requestedCwd))
|
|
19
|
+
: runtimeCwd;
|
|
20
|
+
return path.resolve(baseCwd, output);
|
|
21
|
+
}
|
|
22
|
+
function safeOutputSegment(value, fallback) {
|
|
23
|
+
const sanitized = value.replace(/[^\w.-]/g, "_").replace(/^\.+$/, "");
|
|
24
|
+
return sanitized || fallback;
|
|
25
|
+
}
|
|
26
|
+
export function materializeAgentDefaultOutputPath(params) {
|
|
27
|
+
if (typeof params.output !== "string" || !params.output || params.output === "false" || params.output === "true")
|
|
28
|
+
return params.output;
|
|
29
|
+
if (path.isAbsolute(params.output))
|
|
30
|
+
return params.output;
|
|
31
|
+
const suffix = params.index !== undefined ? `_${safeOutputSegment(String(params.index), "index")}` : "";
|
|
32
|
+
const safeAgent = safeOutputSegment(params.agent, "agent");
|
|
33
|
+
const safeBaseName = safeOutputSegment(path.basename(params.output), "output.md");
|
|
34
|
+
return path.join(params.artifactsDir, "requested-outputs", `${params.runId}_${safeAgent}${suffix}_${safeBaseName}`);
|
|
35
|
+
}
|
|
36
|
+
export function injectSingleOutputInstruction(task, outputPath) {
|
|
37
|
+
if (!outputPath)
|
|
38
|
+
return task;
|
|
39
|
+
return `${task}\n\n---\n**Output:** Write your findings to: ${outputPath}`;
|
|
40
|
+
}
|
|
41
|
+
function countLines(text) {
|
|
42
|
+
if (!text)
|
|
43
|
+
return 0;
|
|
44
|
+
const newlineMatches = text.match(/\r\n|\r|\n/g);
|
|
45
|
+
return (newlineMatches?.length ?? 0) + (/[\r\n]$/.test(text) ? 0 : 1);
|
|
46
|
+
}
|
|
47
|
+
function formatByteSize(bytes) {
|
|
48
|
+
if (bytes < 1024)
|
|
49
|
+
return `${bytes} B`;
|
|
50
|
+
const units = ["KB", "MB", "GB", "TB"];
|
|
51
|
+
let value = bytes / 1024;
|
|
52
|
+
let unitIndex = 0;
|
|
53
|
+
while (value >= 1024 && unitIndex < units.length - 1) {
|
|
54
|
+
value /= 1024;
|
|
55
|
+
unitIndex++;
|
|
56
|
+
}
|
|
57
|
+
return `${value.toFixed(1)} ${units[unitIndex]}`;
|
|
58
|
+
}
|
|
59
|
+
export function formatSavedOutputReference(savedPath, fullOutput) {
|
|
60
|
+
const absolutePath = path.resolve(savedPath);
|
|
61
|
+
const bytes = Buffer.byteLength(fullOutput, "utf-8");
|
|
62
|
+
const lines = countLines(fullOutput);
|
|
63
|
+
return {
|
|
64
|
+
path: absolutePath,
|
|
65
|
+
bytes,
|
|
66
|
+
lines,
|
|
67
|
+
message: `Output saved to: ${absolutePath} (${formatByteSize(bytes)}, ${lines} ${lines === 1 ? "line" : "lines"}). Read this file if needed.`,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
export function formatConsumedOutputReference(outputPath, fullOutput, cleanup) {
|
|
71
|
+
const absolutePath = path.resolve(outputPath);
|
|
72
|
+
const bytes = Buffer.byteLength(fullOutput, "utf-8");
|
|
73
|
+
const lines = countLines(fullOutput);
|
|
74
|
+
const status = cleanup.action === "deleted"
|
|
75
|
+
? "removed after capture"
|
|
76
|
+
: cleanup.action === "already-missing"
|
|
77
|
+
? "already absent after capture"
|
|
78
|
+
: `not removed${cleanup.reason ? `: ${cleanup.reason}` : ""}`;
|
|
79
|
+
return {
|
|
80
|
+
path: absolutePath,
|
|
81
|
+
bytes,
|
|
82
|
+
lines,
|
|
83
|
+
message: `Output file consumed: ${absolutePath} (${formatByteSize(bytes)}, ${lines} ${lines === 1 ? "line" : "lines"}); ${status}.`,
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
export function findDuplicateOutputPath(items) {
|
|
87
|
+
const seen = new Map();
|
|
88
|
+
for (let index = 0; index < items.length; index++) {
|
|
89
|
+
const outputPath = items[index]?.outputPath;
|
|
90
|
+
if (!outputPath)
|
|
91
|
+
continue;
|
|
92
|
+
const previous = seen.get(outputPath);
|
|
93
|
+
if (previous) {
|
|
94
|
+
return `Parallel tasks ${previous.index + 1} (${previous.agent}) and ${index + 1} (${items[index].agent}) resolve output to the same path: ${outputPath}. Use distinct output paths.`;
|
|
95
|
+
}
|
|
96
|
+
seen.set(outputPath, { index, agent: items[index].agent });
|
|
97
|
+
}
|
|
98
|
+
return undefined;
|
|
99
|
+
}
|
|
100
|
+
export function validateFileOnlyOutputMode(outputMode, outputPath, context) {
|
|
101
|
+
if (outputMode === "file-only" && !outputPath) {
|
|
102
|
+
return `${context} sets outputMode: "file-only" but does not configure an output file. Set output to a path or use outputMode: "inline".`;
|
|
103
|
+
}
|
|
104
|
+
return undefined;
|
|
105
|
+
}
|
|
106
|
+
export function captureSingleOutputSnapshot(outputPath) {
|
|
107
|
+
if (!outputPath)
|
|
108
|
+
return undefined;
|
|
109
|
+
try {
|
|
110
|
+
const stat = fs.statSync(outputPath);
|
|
111
|
+
return { exists: true, mtimeMs: stat.mtimeMs, ctimeMs: stat.ctimeMs, size: stat.size, ino: stat.ino };
|
|
112
|
+
}
|
|
113
|
+
catch {
|
|
114
|
+
// The snapshot is advisory; resolveSingleOutput reports concrete read/write failures.
|
|
115
|
+
return { exists: false };
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
function matchesSnapshot(stat, snapshot) {
|
|
119
|
+
return snapshot?.exists === true
|
|
120
|
+
&& stat.mtimeMs === snapshot.mtimeMs
|
|
121
|
+
&& stat.ctimeMs === snapshot.ctimeMs
|
|
122
|
+
&& stat.size === snapshot.size
|
|
123
|
+
&& stat.ino === snapshot.ino;
|
|
124
|
+
}
|
|
125
|
+
function persistSingleOutput(outputPath, fullOutput) {
|
|
126
|
+
if (!outputPath)
|
|
127
|
+
return {};
|
|
128
|
+
try {
|
|
129
|
+
fs.mkdirSync(path.dirname(outputPath), { recursive: true });
|
|
130
|
+
fs.writeFileSync(outputPath, fullOutput, "utf-8");
|
|
131
|
+
return { savedPath: outputPath };
|
|
132
|
+
}
|
|
133
|
+
catch (err) {
|
|
134
|
+
return { error: err instanceof Error ? err.message : String(err) };
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
export function resolveSingleOutput(outputPath, fallbackOutput, beforeRun) {
|
|
138
|
+
if (!outputPath)
|
|
139
|
+
return { fullOutput: fallbackOutput };
|
|
140
|
+
try {
|
|
141
|
+
const stat = fs.statSync(outputPath);
|
|
142
|
+
if (!matchesSnapshot(stat, beforeRun)) {
|
|
143
|
+
// ponytail: acceptance and downstream prompts explicitly request this full
|
|
144
|
+
// individual output; it must fit their heap. Inspection uses readOutputPage.
|
|
145
|
+
return { fullOutput: fs.readFileSync(outputPath, "utf-8"), savedPath: outputPath };
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
catch (error) {
|
|
149
|
+
const code = error && typeof error === "object" && "code" in error ? error.code : undefined;
|
|
150
|
+
if (code !== "ENOENT" && code !== "ENOTDIR") {
|
|
151
|
+
return {
|
|
152
|
+
fullOutput: fallbackOutput,
|
|
153
|
+
saveError: `Failed to read changed output file: ${error instanceof Error ? error.message : String(error)}`,
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
const save = persistSingleOutput(outputPath, fallbackOutput);
|
|
158
|
+
if (save.savedPath)
|
|
159
|
+
return { fullOutput: fallbackOutput, savedPath: save.savedPath, writtenSnapshot: captureSingleOutputSnapshot(save.savedPath) };
|
|
160
|
+
return { fullOutput: fallbackOutput, saveError: save.error };
|
|
161
|
+
}
|
|
162
|
+
export function cleanupSingleOutputFile(outputPath, fullOutput, beforeRun) {
|
|
163
|
+
if (!outputPath)
|
|
164
|
+
return undefined;
|
|
165
|
+
const absolutePath = path.resolve(outputPath);
|
|
166
|
+
try {
|
|
167
|
+
const stat = fs.statSync(outputPath);
|
|
168
|
+
const fd = fs.openSync(outputPath, "r");
|
|
169
|
+
let equal = stat.size === Buffer.byteLength(fullOutput);
|
|
170
|
+
try {
|
|
171
|
+
let position = 0;
|
|
172
|
+
for (let start = 0; equal && start < fullOutput.length;) {
|
|
173
|
+
let end = Math.min(start + 16384, fullOutput.length);
|
|
174
|
+
if (end < fullOutput.length && /[\uD800-\uDBFF]/.test(fullOutput[end - 1]))
|
|
175
|
+
end--;
|
|
176
|
+
const expected = Buffer.from(fullOutput.slice(start, end));
|
|
177
|
+
const actual = Buffer.allocUnsafe(expected.length);
|
|
178
|
+
equal = fs.readSync(fd, actual, 0, actual.length, position) === actual.length && actual.equals(expected);
|
|
179
|
+
position += expected.length;
|
|
180
|
+
start = end;
|
|
181
|
+
}
|
|
182
|
+
const current = fs.fstatSync(fd), located = fs.statSync(outputPath);
|
|
183
|
+
equal &&= current.ino === stat.ino && current.size === stat.size && current.ctimeMs === stat.ctimeMs
|
|
184
|
+
&& located.ino === current.ino && located.dev === current.dev && located.ctimeMs === current.ctimeMs;
|
|
185
|
+
}
|
|
186
|
+
finally {
|
|
187
|
+
fs.closeSync(fd);
|
|
188
|
+
}
|
|
189
|
+
if (!equal) {
|
|
190
|
+
return { path: absolutePath, action: "skipped", reason: "file changed after capture" };
|
|
191
|
+
}
|
|
192
|
+
if (matchesSnapshot(stat, beforeRun)) {
|
|
193
|
+
return { path: absolutePath, action: "skipped", reason: "file preexisted and was unchanged" };
|
|
194
|
+
}
|
|
195
|
+
fs.unlinkSync(outputPath);
|
|
196
|
+
return { path: absolutePath, action: "deleted" };
|
|
197
|
+
}
|
|
198
|
+
catch (error) {
|
|
199
|
+
const code = error && typeof error === "object" && "code" in error ? error.code : undefined;
|
|
200
|
+
if (code === "ENOENT" || code === "ENOTDIR")
|
|
201
|
+
return { path: absolutePath, action: "already-missing" };
|
|
202
|
+
return { path: absolutePath, action: "skipped", error: error instanceof Error ? error.message : String(error) };
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
export function finalizeSingleOutput(params) {
|
|
206
|
+
let displayOutput = params.truncatedOutput || params.fullOutput;
|
|
207
|
+
if (params.exitCode === 0 && params.savedPath) {
|
|
208
|
+
const outputReference = params.outputReference ?? (params.cleanup && params.outputMode !== "file-only"
|
|
209
|
+
? formatConsumedOutputReference(params.savedPath, params.fullOutput, params.cleanup)
|
|
210
|
+
: formatSavedOutputReference(params.savedPath, params.fullOutput));
|
|
211
|
+
if (params.outputMode === "file-only") {
|
|
212
|
+
return { displayOutput: outputReference.message, savedPath: params.savedPath, outputReference };
|
|
213
|
+
}
|
|
214
|
+
displayOutput += `\n\n${outputReference.message}`;
|
|
215
|
+
return { displayOutput, savedPath: params.cleanup ? undefined : params.savedPath, outputReference };
|
|
216
|
+
}
|
|
217
|
+
if (params.exitCode === 0 && params.saveError && params.outputPath) {
|
|
218
|
+
displayOutput += `\n\nOutput file error: ${params.outputPath}\n${params.saveError}`;
|
|
219
|
+
return { displayOutput, saveError: params.saveError };
|
|
220
|
+
}
|
|
221
|
+
return { displayOutput };
|
|
222
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/** Native JSON stdout sends text deltas, not cumulative message/partial snapshots. */
|
|
2
|
+
export function updateStreamingText(current, event) {
|
|
3
|
+
if (event.type === "agent_start" || event.type === "message_end" && event.message?.role === "assistant")
|
|
4
|
+
return undefined;
|
|
5
|
+
if (event.type === "message_start" && event.message?.role === "assistant")
|
|
6
|
+
return "";
|
|
7
|
+
if (event.type !== "message_update")
|
|
8
|
+
return current;
|
|
9
|
+
const update = event.assistantMessageEvent;
|
|
10
|
+
if (update?.type === "text_start")
|
|
11
|
+
return current ? `${current}\n\n` : "";
|
|
12
|
+
if (update?.type === "text_delta")
|
|
13
|
+
return ((current ?? "") + update.delta).slice(-8192);
|
|
14
|
+
return current;
|
|
15
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as os from "node:os";
|
|
3
|
+
import * as path from "node:path";
|
|
4
|
+
import { Compile } from "../../shared/native-typebox.js";
|
|
5
|
+
export const STRUCTURED_OUTPUT_SCHEMA_ENV = "PI_SUBAGENT_STRUCTURED_OUTPUT_SCHEMA";
|
|
6
|
+
export const STRUCTURED_OUTPUT_CAPTURE_ENV = "PI_SUBAGENT_STRUCTURED_OUTPUT_CAPTURE";
|
|
7
|
+
export function assertJsonSchemaObject(schema, label = "outputSchema") {
|
|
8
|
+
if (!schema || typeof schema !== "object" || Array.isArray(schema)) {
|
|
9
|
+
throw new Error(`${label} must be a JSON Schema object.`);
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
export function createStructuredOutputRuntime(schema, baseDir) {
|
|
13
|
+
assertJsonSchemaObject(schema);
|
|
14
|
+
const rootDir = baseDir ?? os.tmpdir();
|
|
15
|
+
fs.mkdirSync(rootDir, { recursive: true });
|
|
16
|
+
const dir = fs.mkdtempSync(path.join(rootDir, "pi-subagent-structured-"));
|
|
17
|
+
const schemaPath = path.join(dir, "schema.json");
|
|
18
|
+
const outputPath = path.join(dir, "output.json");
|
|
19
|
+
fs.writeFileSync(schemaPath, JSON.stringify(schema), { mode: 0o600 });
|
|
20
|
+
return { schema, schemaPath, outputPath };
|
|
21
|
+
}
|
|
22
|
+
export function validateStructuredOutputValue(schema, value) {
|
|
23
|
+
let validator;
|
|
24
|
+
try {
|
|
25
|
+
validator = Compile(schema);
|
|
26
|
+
}
|
|
27
|
+
catch (error) {
|
|
28
|
+
return { status: "invalid", message: `invalid outputSchema: ${error instanceof Error ? error.message : String(error)}` };
|
|
29
|
+
}
|
|
30
|
+
if (validator.Check(value))
|
|
31
|
+
return { status: "valid" };
|
|
32
|
+
const errors = [...validator.Errors(value)]
|
|
33
|
+
.slice(0, 8)
|
|
34
|
+
.map((error) => {
|
|
35
|
+
const pathText = error.instancePath ? error.instancePath.replace(/^\//, "").replace(/\//g, ".") : "root";
|
|
36
|
+
return `${pathText}: ${error.message}`;
|
|
37
|
+
});
|
|
38
|
+
return { status: "invalid", message: errors.join("; ") || "schema validation failed" };
|
|
39
|
+
}
|
|
40
|
+
export function readStructuredOutput(runtime) {
|
|
41
|
+
if (!fs.existsSync(runtime.outputPath)) {
|
|
42
|
+
return { error: "Missing structured_output call; this step has outputSchema and must finish by calling structured_output." };
|
|
43
|
+
}
|
|
44
|
+
let value;
|
|
45
|
+
try {
|
|
46
|
+
value = JSON.parse(fs.readFileSync(runtime.outputPath, "utf-8"));
|
|
47
|
+
}
|
|
48
|
+
catch (error) {
|
|
49
|
+
return { error: `Failed to read structured output: ${error instanceof Error ? error.message : String(error)}` };
|
|
50
|
+
}
|
|
51
|
+
const validation = validateStructuredOutputValue(runtime.schema, value);
|
|
52
|
+
if (validation.status === "invalid")
|
|
53
|
+
return { error: `Structured output validation failed: ${validation.message}` };
|
|
54
|
+
return { value };
|
|
55
|
+
}
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import {} from "../../shared/types.js";
|
|
2
|
+
import { formatRunAction } from "../../shared/status-format.js";
|
|
3
|
+
import { readStatus } from "../../shared/utils.js";
|
|
4
|
+
import { getRunMetadataDir } from "./supervisor-questions.js";
|
|
5
|
+
export function isObsoleteIdleNotice(details) {
|
|
6
|
+
const event = details?.event;
|
|
7
|
+
if (!event || event.reason !== "idle" || event.supervisorQuestion)
|
|
8
|
+
return false;
|
|
9
|
+
let status;
|
|
10
|
+
try {
|
|
11
|
+
status = readStatus(details.asyncDir ?? getRunMetadataDir(event.runId));
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
// Without readable terminal evidence, retain the actionable notice.
|
|
15
|
+
return false;
|
|
16
|
+
}
|
|
17
|
+
if (!status || status.runId !== event.runId)
|
|
18
|
+
return false;
|
|
19
|
+
const child = event.index === undefined ? undefined : status.steps?.[event.index];
|
|
20
|
+
return ["complete", "failed", "blocked", "paused"].includes(status.state)
|
|
21
|
+
|| Boolean(child && ["complete", "completed", "failed", "blocked", "paused", "timed-out"].includes(child.status));
|
|
22
|
+
}
|
|
23
|
+
const CONTROL_EVENT_TYPES = ["needs_attention"];
|
|
24
|
+
const CONTROL_NOTIFICATION_CHANNELS = ["event", "async", "intercom"];
|
|
25
|
+
const DEFAULT_NOTIFY_ON = ["needs_attention"];
|
|
26
|
+
export const DEFAULT_CONTROL_CONFIG = {
|
|
27
|
+
enabled: true,
|
|
28
|
+
needsAttentionAfterMs: 10 * 60_000,
|
|
29
|
+
failedToolAttemptsBeforeAttention: 3,
|
|
30
|
+
notifyOn: DEFAULT_NOTIFY_ON,
|
|
31
|
+
notifyChannels: CONTROL_NOTIFICATION_CHANNELS,
|
|
32
|
+
};
|
|
33
|
+
function parsePositiveInt(value) {
|
|
34
|
+
if (typeof value !== "number")
|
|
35
|
+
return undefined;
|
|
36
|
+
if (!Number.isFinite(value) || !Number.isInteger(value) || value < 1)
|
|
37
|
+
return undefined;
|
|
38
|
+
return value;
|
|
39
|
+
}
|
|
40
|
+
function parseControlList(value, allowed) {
|
|
41
|
+
if (!Array.isArray(value))
|
|
42
|
+
return undefined;
|
|
43
|
+
if (value.length === 0)
|
|
44
|
+
return [];
|
|
45
|
+
const allowedSet = new Set(allowed);
|
|
46
|
+
const parsed = value.filter((entry) => typeof entry === "string" && allowedSet.has(entry));
|
|
47
|
+
return parsed.length > 0 ? Array.from(new Set(parsed)) : undefined;
|
|
48
|
+
}
|
|
49
|
+
export function resolveControlConfig(globalConfig, override) {
|
|
50
|
+
const enabled = override?.enabled ?? globalConfig?.enabled ?? DEFAULT_CONTROL_CONFIG.enabled;
|
|
51
|
+
const needsAttentionAfterMs = parsePositiveInt(override?.needsAttentionAfterMs)
|
|
52
|
+
?? parsePositiveInt(globalConfig?.needsAttentionAfterMs)
|
|
53
|
+
?? DEFAULT_CONTROL_CONFIG.needsAttentionAfterMs;
|
|
54
|
+
const failedToolAttemptsBeforeAttention = parsePositiveInt(override?.failedToolAttemptsBeforeAttention)
|
|
55
|
+
?? parsePositiveInt(globalConfig?.failedToolAttemptsBeforeAttention)
|
|
56
|
+
?? DEFAULT_CONTROL_CONFIG.failedToolAttemptsBeforeAttention;
|
|
57
|
+
const notifyOn = parseControlList(override?.notifyOn, CONTROL_EVENT_TYPES)
|
|
58
|
+
?? parseControlList(globalConfig?.notifyOn, CONTROL_EVENT_TYPES)
|
|
59
|
+
?? DEFAULT_CONTROL_CONFIG.notifyOn;
|
|
60
|
+
const notifyChannels = parseControlList(override?.notifyChannels, CONTROL_NOTIFICATION_CHANNELS)
|
|
61
|
+
?? parseControlList(globalConfig?.notifyChannels, CONTROL_NOTIFICATION_CHANNELS)
|
|
62
|
+
?? DEFAULT_CONTROL_CONFIG.notifyChannels;
|
|
63
|
+
return {
|
|
64
|
+
enabled,
|
|
65
|
+
needsAttentionAfterMs,
|
|
66
|
+
failedToolAttemptsBeforeAttention,
|
|
67
|
+
notifyOn: [...notifyOn],
|
|
68
|
+
notifyChannels: [...notifyChannels],
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
export function deriveActivityState(input) {
|
|
72
|
+
if (!input.config.enabled)
|
|
73
|
+
return undefined;
|
|
74
|
+
const now = input.now ?? Date.now();
|
|
75
|
+
const lastActivity = input.lastActivityAt ?? input.startedAt;
|
|
76
|
+
const ageMs = Math.max(0, now - lastActivity);
|
|
77
|
+
return ageMs > input.config.needsAttentionAfterMs ? "needs_attention" : undefined;
|
|
78
|
+
}
|
|
79
|
+
export function buildControlEvent(input) {
|
|
80
|
+
const ts = input.ts ?? Date.now();
|
|
81
|
+
const type = input.type ?? "needs_attention";
|
|
82
|
+
const elapsedMs = input.elapsedMs ?? (input.lastActivityAt !== undefined ? Math.max(0, ts - input.lastActivityAt) : undefined);
|
|
83
|
+
const elapsedSeconds = elapsedMs !== undefined ? Math.floor(elapsedMs / 1000) : undefined;
|
|
84
|
+
const question = input.supervisorQuestion;
|
|
85
|
+
const observation = input.currentTool
|
|
86
|
+
? `${input.currentTool} still active${input.currentToolDurationMs !== undefined ? ` for ${Math.floor(input.currentToolDurationMs / 1000)}s` : ""}${elapsedSeconds !== undefined ? `; no observed output/events for ${elapsedSeconds}s` : ""}`
|
|
87
|
+
: elapsedSeconds !== undefined ? `no observed activity for ${elapsedSeconds}s` : undefined;
|
|
88
|
+
const signal = question
|
|
89
|
+
? question.state === "awaiting_input" ? `Waiting for supervisor input (question ${question.questionId})` : `Supervisor answer saved for question ${question.questionId}; delivery unconfirmed`
|
|
90
|
+
: `${input.agent} needs attention`;
|
|
91
|
+
const message = input.message ?? `${signal}${observation ? ` (${observation})` : ""}`;
|
|
92
|
+
return {
|
|
93
|
+
type,
|
|
94
|
+
...(input.from ? { from: input.from } : {}),
|
|
95
|
+
to: input.to,
|
|
96
|
+
ts,
|
|
97
|
+
runId: input.runId,
|
|
98
|
+
agent: input.agent,
|
|
99
|
+
...(input.index !== undefined ? { index: input.index } : {}),
|
|
100
|
+
message,
|
|
101
|
+
reason: input.reason ?? "idle",
|
|
102
|
+
...(input.turns !== undefined ? { turns: input.turns } : {}),
|
|
103
|
+
...(input.tokens !== undefined ? { tokens: input.tokens } : {}),
|
|
104
|
+
...(input.toolCount !== undefined ? { toolCount: input.toolCount } : {}),
|
|
105
|
+
...(input.currentTool ? { currentTool: input.currentTool } : {}),
|
|
106
|
+
...(input.currentToolDurationMs !== undefined ? { currentToolDurationMs: input.currentToolDurationMs } : {}),
|
|
107
|
+
...(input.currentPath ? { currentPath: input.currentPath } : {}),
|
|
108
|
+
...(elapsedMs !== undefined ? { elapsedMs } : {}),
|
|
109
|
+
...(input.recentFailureSummary ? { recentFailureSummary: input.recentFailureSummary } : {}),
|
|
110
|
+
...(question ? { supervisorQuestion: question } : {}),
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
export function shouldNotifyControlEvent(config, event) {
|
|
114
|
+
return config.enabled && config.notifyOn.includes(event.type);
|
|
115
|
+
}
|
|
116
|
+
export function controlNotificationKey(event, childIntercomTarget) {
|
|
117
|
+
const childKey = childIntercomTarget ?? (event.index !== undefined ? `${event.runId}:${event.index}` : event.runId);
|
|
118
|
+
return `${childKey}:${event.type}:${event.reason ?? "idle"}`;
|
|
119
|
+
}
|
|
120
|
+
export function claimControlNotification(config, event, seenKeys, childIntercomTarget) {
|
|
121
|
+
if (!shouldNotifyControlEvent(config, event))
|
|
122
|
+
return false;
|
|
123
|
+
const key = controlNotificationKey(event, childIntercomTarget);
|
|
124
|
+
if (seenKeys.has(key))
|
|
125
|
+
return false;
|
|
126
|
+
seenKeys.add(key);
|
|
127
|
+
return true;
|
|
128
|
+
}
|
|
129
|
+
export function formatControlNoticeMessage(event, childIntercomTarget, childSafe = false) {
|
|
130
|
+
const runTarget = event.runId;
|
|
131
|
+
if (event.reason === "completion_guard") {
|
|
132
|
+
return [
|
|
133
|
+
`Subagent failed: ${event.agent}`,
|
|
134
|
+
`Run: ${runTarget}${event.index !== undefined ? ` step ${event.index + 1}` : ""}`,
|
|
135
|
+
`Signal: ${event.message}`,
|
|
136
|
+
"Next: read the output artifact or session from the subagent result, then retry with a more explicit implementation prompt or handle the fix directly.",
|
|
137
|
+
childIntercomTarget ? `Run intercom target (may be inactive): ${childIntercomTarget}` : undefined,
|
|
138
|
+
].filter((line) => Boolean(line)).join("\n");
|
|
139
|
+
}
|
|
140
|
+
const nudgeCommand = formatRunAction("nudge", runTarget, { ...(event.index !== undefined ? { index: event.index } : {}), message: "What are you blocked on? Reply with the smallest next step, or state the exact decision you need." }, childSafe);
|
|
141
|
+
const question = event.supervisorQuestion;
|
|
142
|
+
const askCommand = childIntercomTarget
|
|
143
|
+
? `intercom({ action: "ask", to: "${childIntercomTarget}", delivery: "steer", message: "What are you blocked on? Reply with the smallest next step, or state the exact decision you need." })`
|
|
144
|
+
: undefined;
|
|
145
|
+
return [
|
|
146
|
+
`Subagent needs attention: ${event.agent}`,
|
|
147
|
+
`Run: ${runTarget}${event.index !== undefined ? ` step ${event.index + 1}` : ""}`,
|
|
148
|
+
`Signal: ${event.message}`,
|
|
149
|
+
event.recentFailureSummary ? `Recent failures: ${event.recentFailureSummary}` : undefined,
|
|
150
|
+
...(question ? [
|
|
151
|
+
`Question ID: ${question.questionId}`,
|
|
152
|
+
question.state === "answer_pending" ? "The saved answer has not been confirmed delivered. Inspect the child and retry the same answer; do not assume it resumed." : "Answer the saved question so the child can continue.",
|
|
153
|
+
`Questions: ${formatRunAction("questions", runTarget, {}, childSafe)}`,
|
|
154
|
+
`Answer: ${formatRunAction("answer", runTarget, { questionId: question.questionId, message: question.answer ?? "..." }, childSafe)}`,
|
|
155
|
+
] : [
|
|
156
|
+
event.reason === "idle" && event.currentTool ? "Hint: Inspect command progress. A long-running tool may still be running or hung; elapsed time alone does not prove either." : "Hint: Inspect status first unless the run is clearly blocked.",
|
|
157
|
+
`Nudge (preferred live coordination): ${nudgeCommand}`,
|
|
158
|
+
childIntercomTarget
|
|
159
|
+
? `Ask (blocking wait only; parent must remain alive): ${askCommand}`
|
|
160
|
+
: "Ask (blocking wait only): no child message route registered",
|
|
161
|
+
]),
|
|
162
|
+
`Status: ${formatRunAction("status", runTarget, {}, childSafe)}`,
|
|
163
|
+
`${childSafe ? "Interrupt" : "Stop"}: ${formatRunAction("interrupt", runTarget, {}, childSafe)}`,
|
|
164
|
+
].filter((line) => Boolean(line)).join("\n");
|
|
165
|
+
}
|
|
166
|
+
export function formatControlIntercomMessage(event, childIntercomTarget, childSafe = false) {
|
|
167
|
+
const statusLabel = event.reason === "completion_guard"
|
|
168
|
+
? "subagent failed"
|
|
169
|
+
: "subagent needs attention";
|
|
170
|
+
return [
|
|
171
|
+
statusLabel,
|
|
172
|
+
"",
|
|
173
|
+
event.reason === "completion_guard"
|
|
174
|
+
? `${event.agent} failed in run ${event.runId}.`
|
|
175
|
+
: `${event.agent} needs attention in run ${event.runId}.`,
|
|
176
|
+
"",
|
|
177
|
+
formatControlNoticeMessage(event, childIntercomTarget, childSafe),
|
|
178
|
+
].join("\n");
|
|
179
|
+
}
|