@xzzpig/pi-subagents 0.1.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 +1621 -0
- package/LICENSE +21 -0
- package/README.md +118 -0
- package/agents/delegate.md +14 -0
- package/agents/oracle.md +74 -0
- package/agents/researcher.md +52 -0
- package/agents/reviewer.md +79 -0
- package/agents/scout.md +50 -0
- package/agents/worker.md +58 -0
- package/index.ts +1 -0
- package/inspector-runner.mjs +11 -0
- package/install.mjs +93 -0
- package/package.json +105 -0
- package/prompts/gather-context-and-clarify.md +13 -0
- package/prompts/parallel-cleanup.md +59 -0
- package/prompts/parallel-research.md +50 -0
- package/prompts/parallel-review.md +54 -0
- package/prompts/review-loop.md +43 -0
- package/skills/pi-subagents/SKILL.md +41 -0
- package/skills/pi-subagents/references/constraints-and-recipes.md +251 -0
- package/skills/pi-subagents/references/execution-controls.md +428 -0
- package/skills/pi-subagents/references/management-authoring-rpc.md +161 -0
- package/skills/pi-subagents/references/prompting-and-roles.md +242 -0
- package/src/agents/agent-management.ts +1256 -0
- package/src/agents/agent-memory.ts +254 -0
- package/src/agents/agent-refinements.ts +624 -0
- package/src/agents/agent-scope.ts +6 -0
- package/src/agents/agent-selection.ts +25 -0
- package/src/agents/agent-serializer.ts +163 -0
- package/src/agents/agents.ts +1889 -0
- package/src/agents/chain-serializer.ts +280 -0
- package/src/agents/frontmatter.ts +149 -0
- package/src/agents/identity.ts +30 -0
- package/src/agents/proactive-skills.ts +194 -0
- package/src/agents/skills.ts +761 -0
- package/src/api/background-work.ts +197 -0
- package/src/api/capability-ceiling.ts +17 -0
- package/src/api/control-channel.ts +4 -0
- package/src/api/delegation.ts +119 -0
- package/src/api/external-runs.ts +129 -0
- package/src/api/intercom-bridge.ts +3 -0
- package/src/api/pi-args.ts +5 -0
- package/src/api/preflight.ts +403 -0
- package/src/api/shared-types.ts +19 -0
- package/src/extension/config.ts +76 -0
- package/src/extension/control-notices.ts +58 -0
- package/src/extension/doctor.ts +230 -0
- package/src/extension/fanout-child.ts +201 -0
- package/src/extension/index.ts +805 -0
- package/src/extension/public-execution.ts +71 -0
- package/src/extension/rpc.ts +653 -0
- package/src/extension/schemas.ts +375 -0
- package/src/extension/steering-notices.ts +35 -0
- package/src/extension/tool-description.ts +164 -0
- package/src/inspectors/herdr/actions.ts +229 -0
- package/src/inspectors/herdr/client.ts +130 -0
- package/src/inspectors/herdr/inspector-runner.ts +141 -0
- package/src/inspectors/herdr/project-panes.ts +154 -0
- package/src/integrations/herdr-status.ts +330 -0
- package/src/intercom/intercom-bridge.ts +187 -0
- package/src/intercom/native-supervisor-channel.ts +715 -0
- package/src/intercom/result-intercom.ts +421 -0
- package/src/missions/actions.ts +410 -0
- package/src/missions/goal-driver.ts +162 -0
- package/src/missions/lifecycle.ts +346 -0
- package/src/missions/store.ts +507 -0
- package/src/missions/types.ts +157 -0
- package/src/missions/workflow-state.ts +250 -0
- package/src/policy/authority.ts +46 -0
- package/src/profiles/profiles.ts +661 -0
- package/src/runs/background/async-execution.ts +1574 -0
- package/src/runs/background/async-job-tracker.ts +511 -0
- package/src/runs/background/async-resume.ts +539 -0
- package/src/runs/background/async-status.ts +542 -0
- package/src/runs/background/auto-drain.ts +67 -0
- package/src/runs/background/chain-append.ts +328 -0
- package/src/runs/background/chain-root-attachment.ts +199 -0
- package/src/runs/background/completion-batcher.ts +168 -0
- package/src/runs/background/completion-dedupe.ts +54 -0
- package/src/runs/background/control-channel.ts +692 -0
- package/src/runs/background/fleet-view.ts +540 -0
- package/src/runs/background/notify.ts +332 -0
- package/src/runs/background/parallel-groups.ts +45 -0
- package/src/runs/background/process-terminal.ts +280 -0
- package/src/runs/background/result-watcher.ts +414 -0
- package/src/runs/background/retained-children.ts +68 -0
- package/src/runs/background/run-id-resolver.ts +167 -0
- package/src/runs/background/run-status.ts +504 -0
- package/src/runs/background/scheduled-runs.ts +753 -0
- package/src/runs/background/stale-run-reconciler.ts +396 -0
- package/src/runs/background/steering.ts +239 -0
- package/src/runs/background/subagent-runner.ts +4718 -0
- package/src/runs/background/subagent-wait.ts +661 -0
- package/src/runs/background/top-level-async.ts +14 -0
- package/src/runs/background/wait-completions.ts +112 -0
- package/src/runs/background/wait-config.ts +36 -0
- package/src/runs/background/wait-subscriptions.ts +253 -0
- package/src/runs/background/wait-tool.ts +34 -0
- package/src/runs/foreground/async-steering-action.ts +256 -0
- package/src/runs/foreground/async-stop-action.ts +65 -0
- package/src/runs/foreground/chain-clarify.ts +1354 -0
- package/src/runs/foreground/chain-execution.ts +1527 -0
- package/src/runs/foreground/execution.ts +1868 -0
- package/src/runs/foreground/foreground-control.ts +132 -0
- package/src/runs/foreground/subagent-executor.ts +5532 -0
- package/src/runs/shared/acceptance.ts +1365 -0
- package/src/runs/shared/agent-contract.ts +38 -0
- package/src/runs/shared/capability-ceiling.ts +209 -0
- package/src/runs/shared/chain-outputs.ts +118 -0
- package/src/runs/shared/child-protocol.ts +401 -0
- package/src/runs/shared/completion-guard.ts +95 -0
- package/src/runs/shared/context-mode.ts +44 -0
- package/src/runs/shared/dynamic-fanout.ts +297 -0
- package/src/runs/shared/external-cli-runner.ts +130 -0
- package/src/runs/shared/long-running-guard.ts +220 -0
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +406 -0
- package/src/runs/shared/model-fallback.ts +336 -0
- package/src/runs/shared/model-scope.ts +128 -0
- package/src/runs/shared/nested-events.ts +1076 -0
- package/src/runs/shared/nested-path.ts +52 -0
- package/src/runs/shared/nested-render.ts +123 -0
- package/src/runs/shared/parallel-handoff.ts +238 -0
- package/src/runs/shared/parallel-utils.ts +256 -0
- package/src/runs/shared/permissions.ts +95 -0
- package/src/runs/shared/pi-args.ts +808 -0
- package/src/runs/shared/pi-spawn.ts +163 -0
- package/src/runs/shared/process-signal.ts +19 -0
- package/src/runs/shared/run-history.ts +181 -0
- package/src/runs/shared/runtime-acknowledged-extensions.ts +71 -0
- package/src/runs/shared/session-lease.ts +299 -0
- package/src/runs/shared/single-output.ts +235 -0
- package/src/runs/shared/spawn-budget.ts +128 -0
- package/src/runs/shared/structured-output.ts +182 -0
- package/src/runs/shared/subagent-control.ts +231 -0
- package/src/runs/shared/subagent-prompt-runtime.ts +588 -0
- package/src/runs/shared/subagent-startup-retry.ts +104 -0
- package/src/runs/shared/task-intent.ts +181 -0
- package/src/runs/shared/tool-availability.ts +83 -0
- package/src/runs/shared/tool-budget.ts +80 -0
- package/src/runs/shared/turn-budget.ts +98 -0
- package/src/runs/shared/usage-budget.ts +65 -0
- package/src/runs/shared/workflow-graph.ts +231 -0
- package/src/runs/shared/worktree.ts +759 -0
- package/src/shared/accessible-dir.ts +47 -0
- package/src/shared/artifacts.ts +285 -0
- package/src/shared/atomic-json.ts +61 -0
- package/src/shared/child-transcript.ts +264 -0
- package/src/shared/file-coalescer.ts +40 -0
- package/src/shared/file-system-retry.ts +47 -0
- package/src/shared/fork-context.ts +213 -0
- package/src/shared/formatters.ts +133 -0
- package/src/shared/jsonl-writer.ts +81 -0
- package/src/shared/launch-contract.ts +124 -0
- package/src/shared/model-info.ts +81 -0
- package/src/shared/post-exit-stdio-guard.ts +85 -0
- package/src/shared/session-identity.ts +10 -0
- package/src/shared/session-tokens.ts +44 -0
- package/src/shared/settings.ts +501 -0
- package/src/shared/status-format.ts +55 -0
- package/src/shared/types.ts +2069 -0
- package/src/shared/utils.ts +613 -0
- package/src/slash/delegation-adapters.ts +434 -0
- package/src/slash/delegation-json.ts +108 -0
- package/src/slash/delegation-request.ts +166 -0
- package/src/slash/prompt-template-bridge.ts +383 -0
- package/src/slash/prompt-workflows.ts +300 -0
- package/src/slash/selector.ts +147 -0
- package/src/slash/slash-bridge.ts +192 -0
- package/src/slash/slash-commands.ts +994 -0
- package/src/slash/slash-live-state.ts +296 -0
- package/src/slash/subagents-admin.ts +432 -0
- package/src/tui/fleet-status.ts +564 -0
- package/src/tui/fleet-transcript.ts +577 -0
- package/src/tui/fleet.ts +879 -0
- package/src/tui/render-helpers.ts +80 -0
- package/src/tui/render.ts +2029 -0
- package/src/types/pi-runtime-compat.d.ts +8 -0
- package/src/watchdog/change-signature.ts +220 -0
- package/src/watchdog/child-status.ts +205 -0
- package/src/watchdog/emission-guard.ts +123 -0
- package/src/watchdog/lsp-diagnostics.ts +537 -0
- package/src/watchdog/model-selection.ts +167 -0
- package/src/watchdog/permission-arbiter.ts +145 -0
- package/src/watchdog/register-child.ts +117 -0
- package/src/watchdog/register-main.ts +440 -0
- package/src/watchdog/render.ts +54 -0
- package/src/watchdog/review.ts +302 -0
- package/src/watchdog/runtime.ts +868 -0
- package/src/watchdog/scope.ts +62 -0
- package/src/watchdog/settings.ts +568 -0
- package/src/watchdog/tool-actions.ts +155 -0
- package/src/watchdog/turn-delta.ts +161 -0
- package/src/watchdog/types.ts +198 -0
- package/src/watchdog/warning-format.ts +73 -0
- package/src/workflows/chat-progress.ts +140 -0
- package/src/workflows/scripted-workflow.ts +506 -0
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import type { ArtifactPaths, SubagentState, WaitCompletion, WaitCompletionChild } from "../../shared/types.ts";
|
|
4
|
+
import type { AsyncRunSummary } from "./async-status.ts";
|
|
5
|
+
|
|
6
|
+
function asNonEmptyString(value: unknown): string | undefined {
|
|
7
|
+
return typeof value === "string" && value ? value : undefined;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
function errorCode(error: unknown): string | undefined {
|
|
11
|
+
return typeof error === "object" && error !== null && "code" in error
|
|
12
|
+
? (error as NodeJS.ErrnoException).code
|
|
13
|
+
: undefined;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function errorMessage(error: unknown): string {
|
|
17
|
+
return error instanceof Error ? error.message : String(error);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Project a terminal result payload into the slim shape that is safe to surface in
|
|
22
|
+
* tool_result details: run identity, per-child outcome, and the artifact trail.
|
|
23
|
+
* Output text is deliberately excluded — it already travels in the tool result
|
|
24
|
+
* content, and duplicating it in details would double the payload for every wait.
|
|
25
|
+
*/
|
|
26
|
+
export function toWaitCompletion(data: Record<string, unknown>, runId: string): WaitCompletion {
|
|
27
|
+
const results = Array.isArray(data.results)
|
|
28
|
+
? data.results.flatMap((entry): WaitCompletionChild[] => {
|
|
29
|
+
if (entry === null || typeof entry !== "object") return [];
|
|
30
|
+
const child = entry as Record<string, unknown>;
|
|
31
|
+
const outputState = child.outputState === "present" || child.outputState === "absent" || child.outputState === "unknown"
|
|
32
|
+
? child.outputState
|
|
33
|
+
: undefined;
|
|
34
|
+
const artifactPaths = child.artifactPaths !== null && typeof child.artifactPaths === "object"
|
|
35
|
+
? (child.artifactPaths as Partial<ArtifactPaths>)
|
|
36
|
+
: undefined;
|
|
37
|
+
const agent = asNonEmptyString(child.agent);
|
|
38
|
+
const childRunId = asNonEmptyString(child.runId);
|
|
39
|
+
const error = asNonEmptyString(child.error);
|
|
40
|
+
const model = asNonEmptyString(child.model);
|
|
41
|
+
return [{
|
|
42
|
+
...(agent ? { agent } : {}),
|
|
43
|
+
...(childRunId ? { runId: childRunId } : {}),
|
|
44
|
+
...(typeof child.success === "boolean" ? { success: child.success } : {}),
|
|
45
|
+
...(outputState ? { outputState } : {}),
|
|
46
|
+
...(error ? { error } : {}),
|
|
47
|
+
...(model ? { model } : {}),
|
|
48
|
+
...(artifactPaths ? { artifactPaths } : {}),
|
|
49
|
+
}];
|
|
50
|
+
})
|
|
51
|
+
: undefined;
|
|
52
|
+
const agent = asNonEmptyString(data.agent);
|
|
53
|
+
const mode = asNonEmptyString(data.mode);
|
|
54
|
+
const state = asNonEmptyString(data.state);
|
|
55
|
+
return {
|
|
56
|
+
runId,
|
|
57
|
+
...(agent ? { agent } : {}),
|
|
58
|
+
...(mode ? { mode } : {}),
|
|
59
|
+
...(state ? { state } : {}),
|
|
60
|
+
...(typeof data.success === "boolean" ? { success: data.success } : {}),
|
|
61
|
+
...(results && results.length > 0 ? { results } : {}),
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Record a consumed terminal payload for later surfacing by subagent_wait, pruning
|
|
67
|
+
* stale entries with the same TTL that dedupes completion notifications. The result
|
|
68
|
+
* file is deleted after delivery, so this record is the only in-process source once
|
|
69
|
+
* the watcher has consumed it.
|
|
70
|
+
*/
|
|
71
|
+
export function recordWaitCompletion(state: SubagentState, runId: string, data: Record<string, unknown>, now: number, ttlMs: number): void {
|
|
72
|
+
const store = state.completedResults ??= new Map();
|
|
73
|
+
for (const [key, entry] of store) {
|
|
74
|
+
if (now - entry.seenAt > ttlMs) store.delete(key);
|
|
75
|
+
}
|
|
76
|
+
store.set(runId, { seenAt: now, completion: toWaitCompletion(data, runId) });
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Terminal payloads for the runs a wait covered: the watcher's in-memory record
|
|
81
|
+
* first, then the not-yet-consumed result file. Result files are written atomically,
|
|
82
|
+
* so a direct read never observes a torn write; the read is deliberately read-only —
|
|
83
|
+
* the watcher owns notification and cleanup.
|
|
84
|
+
*/
|
|
85
|
+
export function collectWaitCompletions(terminal: AsyncRunSummary[], state: SubagentState, resultsDir: string): WaitCompletion[] | undefined {
|
|
86
|
+
if (terminal.length === 0) return undefined;
|
|
87
|
+
const completions: WaitCompletion[] = [];
|
|
88
|
+
for (const run of terminal) {
|
|
89
|
+
const recorded = state.completedResults?.get(run.id);
|
|
90
|
+
if (recorded) {
|
|
91
|
+
completions.push(recorded.completion);
|
|
92
|
+
continue;
|
|
93
|
+
}
|
|
94
|
+
const resultPath = path.join(resultsDir, `${run.id}.json`);
|
|
95
|
+
try {
|
|
96
|
+
const raw = JSON.parse(fs.readFileSync(resultPath, "utf-8")) as Record<string, unknown>;
|
|
97
|
+
completions.push(toWaitCompletion(raw, run.id));
|
|
98
|
+
} catch (error) {
|
|
99
|
+
if (errorCode(error) !== "ENOENT") {
|
|
100
|
+
throw new Error(`Failed to read subagent result '${resultPath}': ${errorMessage(error)}`, {
|
|
101
|
+
cause: error instanceof Error ? error : undefined,
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
// The watcher may have consumed the file between the store check and the
|
|
105
|
+
// read; its record is authoritative when present, otherwise the payload
|
|
106
|
+
// is gone and the text summary remains the only surface for this run.
|
|
107
|
+
const late = state.completedResults?.get(run.id);
|
|
108
|
+
if (late) completions.push(late.completion);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
return completions.length > 0 ? completions : undefined;
|
|
112
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { WaitToolConfig } from "../../shared/types.ts";
|
|
2
|
+
|
|
3
|
+
export const WAIT_TOOL_ENABLED_ENV = "PI_SUBAGENT_WAIT_TOOL_ENABLED";
|
|
4
|
+
|
|
5
|
+
export interface ResolvedWaitToolConfig {
|
|
6
|
+
enabled: boolean;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
const TRUE_VALUES = new Set(["1", "true", "yes", "on", "enabled"]);
|
|
10
|
+
const FALSE_VALUES = new Set(["0", "false", "no", "off", "disabled"]);
|
|
11
|
+
|
|
12
|
+
function environmentValue(value: string | undefined): boolean | undefined {
|
|
13
|
+
if (value === undefined) return undefined;
|
|
14
|
+
const normalized = value.trim().toLowerCase();
|
|
15
|
+
if (TRUE_VALUES.has(normalized)) return true;
|
|
16
|
+
if (FALSE_VALUES.has(normalized)) return false;
|
|
17
|
+
throw new Error(`${WAIT_TOOL_ENABLED_ENV} must be one of true/false, 1/0, yes/no, on/off, or enabled/disabled.`);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function configuredValue(config: unknown): boolean | undefined {
|
|
21
|
+
if (config === undefined) return undefined;
|
|
22
|
+
if (typeof config === "boolean") return config;
|
|
23
|
+
if (!config || typeof config !== "object" || Array.isArray(config)) {
|
|
24
|
+
throw new Error("config.waitTool must be a boolean or an object with optional enabled boolean.");
|
|
25
|
+
}
|
|
26
|
+
const enabled = (config as { enabled?: unknown }).enabled;
|
|
27
|
+
if (enabled === undefined) return undefined;
|
|
28
|
+
if (typeof enabled !== "boolean") throw new Error("config.waitTool.enabled must be a boolean.");
|
|
29
|
+
return enabled;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function resolveWaitToolConfig(config?: WaitToolConfig, env: Record<string, string | undefined> = process.env): ResolvedWaitToolConfig {
|
|
33
|
+
return {
|
|
34
|
+
enabled: environmentValue(env[WAIT_TOOL_ENABLED_ENV]) ?? configuredValue(config) ?? true,
|
|
35
|
+
};
|
|
36
|
+
}
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import { randomUUID } from "node:crypto";
|
|
4
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
5
|
+
import { listAsyncRuns } from "./async-status.ts";
|
|
6
|
+
import { writeAtomicJson } from "../../shared/atomic-json.ts";
|
|
7
|
+
import {
|
|
8
|
+
DIRS,
|
|
9
|
+
INTERCOM_DETACH_REQUEST_EVENT,
|
|
10
|
+
SUBAGENT_ASYNC_COMPLETE_EVENT,
|
|
11
|
+
SUBAGENT_CONTROL_EVENT,
|
|
12
|
+
SUBAGENT_CONTROL_INTERCOM_EVENT,
|
|
13
|
+
SUBAGENT_FOREGROUND_COMPLETE_EVENT,
|
|
14
|
+
SUBAGENT_RESULT_INTERCOM_EVENT,
|
|
15
|
+
type SubagentState,
|
|
16
|
+
type WaitSubscriptionRecord,
|
|
17
|
+
} from "../../shared/types.ts";
|
|
18
|
+
|
|
19
|
+
const SUBSCRIPTION_VERSION = 1;
|
|
20
|
+
const RECONCILE_INTERVAL_MS = 1_000;
|
|
21
|
+
|
|
22
|
+
export interface ArmWaitSubscriptionInput {
|
|
23
|
+
targetKind: "async" | "foreground";
|
|
24
|
+
runId: string;
|
|
25
|
+
requestedId: string;
|
|
26
|
+
timeoutMs: number;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface WaitSubscriptionManager {
|
|
30
|
+
arm(input: ArmWaitSubscriptionInput): WaitSubscriptionRecord;
|
|
31
|
+
restore(): void;
|
|
32
|
+
reconcile(): void;
|
|
33
|
+
dispose(): void;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
interface WaitSubscriptionManagerOptions {
|
|
37
|
+
asyncDirRoot?: string;
|
|
38
|
+
resultsDir?: string;
|
|
39
|
+
subscriptionsDir?: string;
|
|
40
|
+
now?: () => number;
|
|
41
|
+
pollIntervalMs?: number;
|
|
42
|
+
kill?: (pid: number, signal?: NodeJS.Signals | 0) => boolean;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function isNotFound(error: unknown): boolean {
|
|
46
|
+
return typeof error === "object" && error !== null && "code" in error && (error as NodeJS.ErrnoException).code === "ENOENT";
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function parseRecord(value: unknown): WaitSubscriptionRecord | undefined {
|
|
50
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
|
|
51
|
+
const record = value as Partial<WaitSubscriptionRecord>;
|
|
52
|
+
if (record.version !== SUBSCRIPTION_VERSION
|
|
53
|
+
|| typeof record.token !== "string"
|
|
54
|
+
|| !/^[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)
|
|
55
|
+
|| typeof record.sessionId !== "string"
|
|
56
|
+
|| (record.targetKind !== "async" && record.targetKind !== "foreground")
|
|
57
|
+
|| typeof record.runId !== "string"
|
|
58
|
+
|| typeof record.requestedId !== "string"
|
|
59
|
+
|| typeof record.createdAt !== "number"
|
|
60
|
+
|| typeof record.expiresAt !== "number") return undefined;
|
|
61
|
+
return record as WaitSubscriptionRecord;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function needsAttention(run: ReturnType<typeof listAsyncRuns>[number]): boolean {
|
|
65
|
+
return run.activityState === "needs_attention" || run.steps.some((step) => step.activityState === "needs_attention");
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function subscriptionFile(dir: string, token: string): string {
|
|
69
|
+
return path.join(dir, `${token}.json`);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function formatWaitSubscriptions(state: Pick<SubagentState, "waitSubscriptions">, now = Date.now()): string | undefined {
|
|
73
|
+
const subscriptions = [...(state.waitSubscriptions?.values() ?? [])].sort((left, right) => left.createdAt - right.createdAt);
|
|
74
|
+
if (subscriptions.length === 0) return undefined;
|
|
75
|
+
const lines = [`Armed wait subscriptions (${subscriptions.length}):`];
|
|
76
|
+
for (const record of subscriptions) {
|
|
77
|
+
lines.push(`- ${record.token}: ${record.targetKind} run ${record.runId}, timeout in ${Math.max(0, record.expiresAt - now)}ms`);
|
|
78
|
+
}
|
|
79
|
+
return lines.join("\n");
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function createWaitSubscriptionManager(
|
|
83
|
+
pi: Pick<ExtensionAPI, "events" | "sendMessage">,
|
|
84
|
+
state: SubagentState,
|
|
85
|
+
options: WaitSubscriptionManagerOptions = {},
|
|
86
|
+
): WaitSubscriptionManager {
|
|
87
|
+
const asyncDirRoot = options.asyncDirRoot ?? DIRS.async;
|
|
88
|
+
const resultsDir = options.resultsDir ?? DIRS.results;
|
|
89
|
+
const subscriptionsDir = options.subscriptionsDir ?? path.join(path.dirname(asyncDirRoot), "wait-subscriptions");
|
|
90
|
+
const now = options.now ?? Date.now;
|
|
91
|
+
const subscriptions = state.waitSubscriptions ?? new Map<string, WaitSubscriptionRecord>();
|
|
92
|
+
state.waitSubscriptions = subscriptions;
|
|
93
|
+
const unresolvedRestoredForegroundTokens = new Set<string>();
|
|
94
|
+
let disposed = false;
|
|
95
|
+
|
|
96
|
+
const remove = (record: WaitSubscriptionRecord) => {
|
|
97
|
+
try {
|
|
98
|
+
fs.unlinkSync(subscriptionFile(subscriptionsDir, record.token));
|
|
99
|
+
} catch (error) {
|
|
100
|
+
if (!isNotFound(error)) throw error;
|
|
101
|
+
}
|
|
102
|
+
subscriptions.delete(record.token);
|
|
103
|
+
unresolvedRestoredForegroundTokens.delete(record.token);
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
const settle = (record: WaitSubscriptionRecord, outcome: string, detail: string) => {
|
|
107
|
+
if (disposed || state.currentSessionId !== record.sessionId) return;
|
|
108
|
+
try {
|
|
109
|
+
remove(record);
|
|
110
|
+
} catch (error) {
|
|
111
|
+
console.error(`Failed to clear wait subscription '${record.token}'; it remains armed:`, error);
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
try {
|
|
115
|
+
pi.sendMessage({
|
|
116
|
+
customType: "subagent-wait-subscription",
|
|
117
|
+
content: `Wait subscription ${record.token} fired for run ${record.runId}: ${outcome}. ${detail}`,
|
|
118
|
+
display: true,
|
|
119
|
+
details: { token: record.token, runId: record.runId, outcome },
|
|
120
|
+
}, { triggerTurn: true });
|
|
121
|
+
} catch (error) {
|
|
122
|
+
console.error(`Failed to deliver wait subscription '${record.token}' after clearing it:`, error);
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
const reconcileRecord = (record: WaitSubscriptionRecord) => {
|
|
127
|
+
if (record.sessionId !== state.currentSessionId) return;
|
|
128
|
+
if (now() >= record.expiresAt) {
|
|
129
|
+
settle(record, "timed out", "The targeted run may still be active; inspect its status before taking follow-up action.");
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
if (record.targetKind === "foreground") {
|
|
133
|
+
const run = state.foregroundRuns?.get(record.runId);
|
|
134
|
+
if (!run && unresolvedRestoredForegroundTokens.has(record.token)) return;
|
|
135
|
+
if (run) unresolvedRestoredForegroundTokens.delete(record.token);
|
|
136
|
+
if (!run || run.sessionId !== record.sessionId) {
|
|
137
|
+
settle(record, "could not be reconciled", "The remembered foreground run disappeared before completion was confirmed.");
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
const detached = run.children.filter((child) => child.status === "detached");
|
|
141
|
+
if (detached.some((child) => child.activityState === "needs_attention")) {
|
|
142
|
+
settle(record, "needs attention", "Reply to the pending supervisor request or inspect the run status.");
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
if (detached.length === 0) {
|
|
146
|
+
const failed = run.children.some((child) => child.status === "failed");
|
|
147
|
+
settle(record, failed ? "failed" : "completed", "Inspect the run status for its final output.");
|
|
148
|
+
}
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const runs = listAsyncRuns(asyncDirRoot, {
|
|
153
|
+
sessionId: record.sessionId,
|
|
154
|
+
runId: record.runId,
|
|
155
|
+
resultsDir,
|
|
156
|
+
kill: options.kill,
|
|
157
|
+
now,
|
|
158
|
+
});
|
|
159
|
+
const run = runs.find((candidate) => candidate.id === record.runId);
|
|
160
|
+
if (!run) {
|
|
161
|
+
settle(record, "could not be reconciled", "The exact async run disappeared before a terminal result was confirmed.");
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
if (needsAttention(run)) {
|
|
165
|
+
settle(record, "needs attention", "Inspect the run status and answer any pending supervisor request.");
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
if (run.state !== "queued" && run.state !== "running") {
|
|
169
|
+
settle(record, run.state === "complete" ? "completed" : run.state, "Inspect the run status for its final output.");
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
const reconcile = () => {
|
|
174
|
+
if (disposed || !state.currentSessionId) return;
|
|
175
|
+
for (const record of [...subscriptions.values()]) {
|
|
176
|
+
try {
|
|
177
|
+
reconcileRecord(record);
|
|
178
|
+
} catch (error) {
|
|
179
|
+
console.error(`Failed to reconcile wait subscription '${record.token}':`, error);
|
|
180
|
+
settle(record, "reconciliation failed", "The targeted run could not be reconciled. Inspect its status before taking follow-up action.");
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
};
|
|
184
|
+
|
|
185
|
+
const wakeChannels = [
|
|
186
|
+
INTERCOM_DETACH_REQUEST_EVENT,
|
|
187
|
+
SUBAGENT_ASYNC_COMPLETE_EVENT,
|
|
188
|
+
SUBAGENT_FOREGROUND_COMPLETE_EVENT,
|
|
189
|
+
SUBAGENT_CONTROL_EVENT,
|
|
190
|
+
SUBAGENT_CONTROL_INTERCOM_EVENT,
|
|
191
|
+
SUBAGENT_RESULT_INTERCOM_EVENT,
|
|
192
|
+
];
|
|
193
|
+
const unsubscribes = wakeChannels.map((channel) => pi.events.on(channel, reconcile));
|
|
194
|
+
const interval = setInterval(reconcile, options.pollIntervalMs ?? RECONCILE_INTERVAL_MS);
|
|
195
|
+
interval.unref?.();
|
|
196
|
+
|
|
197
|
+
return {
|
|
198
|
+
arm(input) {
|
|
199
|
+
const sessionId = state.currentSessionId;
|
|
200
|
+
if (!sessionId) throw new Error("A wait subscription requires an active session identity.");
|
|
201
|
+
const createdAt = now();
|
|
202
|
+
const record: WaitSubscriptionRecord = {
|
|
203
|
+
version: SUBSCRIPTION_VERSION,
|
|
204
|
+
token: randomUUID(),
|
|
205
|
+
sessionId,
|
|
206
|
+
targetKind: input.targetKind,
|
|
207
|
+
runId: input.runId,
|
|
208
|
+
requestedId: input.requestedId,
|
|
209
|
+
createdAt,
|
|
210
|
+
expiresAt: createdAt + input.timeoutMs,
|
|
211
|
+
};
|
|
212
|
+
fs.mkdirSync(subscriptionsDir, { recursive: true });
|
|
213
|
+
writeAtomicJson(subscriptionFile(subscriptionsDir, record.token), record);
|
|
214
|
+
subscriptions.set(record.token, record);
|
|
215
|
+
return record;
|
|
216
|
+
},
|
|
217
|
+
restore() {
|
|
218
|
+
subscriptions.clear();
|
|
219
|
+
unresolvedRestoredForegroundTokens.clear();
|
|
220
|
+
if (!state.currentSessionId) return;
|
|
221
|
+
let files: string[];
|
|
222
|
+
try {
|
|
223
|
+
files = fs.readdirSync(subscriptionsDir).filter((file) => file.endsWith(".json"));
|
|
224
|
+
} catch (error) {
|
|
225
|
+
if (isNotFound(error)) return;
|
|
226
|
+
throw error;
|
|
227
|
+
}
|
|
228
|
+
for (const file of files) {
|
|
229
|
+
try {
|
|
230
|
+
const record = parseRecord(JSON.parse(fs.readFileSync(path.join(subscriptionsDir, file), "utf-8")));
|
|
231
|
+
if (!record || file !== `${record.token}.json`) continue;
|
|
232
|
+
if (record.sessionId === state.currentSessionId) {
|
|
233
|
+
subscriptions.set(record.token, record);
|
|
234
|
+
if (record.targetKind === "foreground" && !state.foregroundRuns?.has(record.runId)) unresolvedRestoredForegroundTokens.add(record.token);
|
|
235
|
+
}
|
|
236
|
+
} catch (error) {
|
|
237
|
+
console.error(`Ignoring invalid wait subscription '${path.join(subscriptionsDir, file)}':`, error);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
reconcile();
|
|
241
|
+
},
|
|
242
|
+
reconcile,
|
|
243
|
+
dispose() {
|
|
244
|
+
if (disposed) return;
|
|
245
|
+
disposed = true;
|
|
246
|
+
clearInterval(interval);
|
|
247
|
+
for (const unsubscribe of unsubscribes) {
|
|
248
|
+
try { unsubscribe(); } catch { /* best effort */ }
|
|
249
|
+
}
|
|
250
|
+
subscriptions.clear();
|
|
251
|
+
},
|
|
252
|
+
};
|
|
253
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { ExtensionAPI, ToolDefinition } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { SubagentWaitParams } from "../../extension/schemas.ts";
|
|
3
|
+
import type { Details, SubagentState } from "../../shared/types.ts";
|
|
4
|
+
import { resolveWaitToolConfig, waitForSubagents } from "./subagent-wait.ts";
|
|
5
|
+
import type { WaitSubscriptionManager } from "./wait-subscriptions.ts";
|
|
6
|
+
|
|
7
|
+
export function registerWaitTool(pi: ExtensionAPI, state: SubagentState, enabled = resolveWaitToolConfig().enabled, subscriptions?: Pick<WaitSubscriptionManager, "arm">): void {
|
|
8
|
+
const tool: ToolDefinition<typeof SubagentWaitParams, Details> = {
|
|
9
|
+
name: "subagent_wait",
|
|
10
|
+
label: "Subagent Wait",
|
|
11
|
+
description: `Block until background work owned by this session changes, then return.
|
|
12
|
+
|
|
13
|
+
In an interactive chat, do not call this merely to wait: return control to the user and let Pi wake the session on completion. Override that default and call it when the current request is run-to-completion — for example, the user asked you to report results back before continuing or a skill cannot return before its work finishes. Headless runs auto-drain current-session work at agent_end; call this when the current turn must receive results before it ends.
|
|
14
|
+
|
|
15
|
+
• { } — return when the first initially active async run or registered provider item finishes, or when a subagent needs attention.
|
|
16
|
+
• { all: true } — wait for every async run and provider item that was active when the call began.
|
|
17
|
+
• { id: "..." } — wait for one async or remembered detached foreground subagent run (id or prefix).
|
|
18
|
+
• { id: "...", nonBlocking: true } — resolve the prefix once, persist an exact-run wake subscription, and return immediately. The originating interactive session wakes on completion, failure, attention, reconciliation failure, or timeout.
|
|
19
|
+
• { timeoutMs: 600000 } — stop waiting after N ms; active work keeps running.
|
|
20
|
+
|
|
21
|
+
Non-blocking subscriptions are visible in subagent status and differ from disabling waitTool: waitTool.enabled=false returns immediately without registering any future wake. Provider jobs are session-scoped and identified exactly, so replacing one job with another cannot hide a completion. Provider extensions must be explicitly loaded in this process. In a child agent, keep \`subagent_wait\` in the child tool allowlist and load each provider through the agent's extensions or subagentOnlyExtensions; this tool never loads providers or grants tools itself.${enabled ? "" : "\n\nConfigured behavior: subagent_wait is disabled by config.waitTool or PI_SUBAGENT_WAIT_TOOL_ENABLED and returns immediately without blocking."}`,
|
|
22
|
+
parameters: SubagentWaitParams,
|
|
23
|
+
execute(_id, params, signal, onUpdate, ctx) {
|
|
24
|
+
return waitForSubagents(params, signal, {
|
|
25
|
+
state,
|
|
26
|
+
events: pi.events,
|
|
27
|
+
enabled,
|
|
28
|
+
onUpdate,
|
|
29
|
+
...(subscriptions && ctx?.hasUI ? { subscribe: (input) => subscriptions.arm(input) } : {}),
|
|
30
|
+
});
|
|
31
|
+
},
|
|
32
|
+
};
|
|
33
|
+
pi.registerTool(tool);
|
|
34
|
+
}
|