pi-cohort 2.0.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 +1151 -0
- package/LICENSE +22 -0
- package/README.md +1220 -0
- package/agents/context-builder.md +45 -0
- package/agents/delegate.md +12 -0
- package/agents/oracle.md +73 -0
- package/agents/planner.md +55 -0
- package/agents/reviewer.md +91 -0
- package/agents/scout.md +50 -0
- package/agents/worker.md +67 -0
- package/package.json +87 -0
- package/prompts/gather-context-and-clarify.md +13 -0
- package/prompts/parallel-cleanup.md +59 -0
- package/prompts/parallel-context-build.md +55 -0
- package/prompts/parallel-handoff-plan.md +61 -0
- package/prompts/parallel-review.md +54 -0
- package/prompts/review-loop.md +41 -0
- package/skills/pi-cohort/SKILL.md +818 -0
- package/src/agents/agent-management.ts +685 -0
- package/src/agents/agent-scope.ts +6 -0
- package/src/agents/agent-selection.ts +23 -0
- package/src/agents/agent-serializer.ts +83 -0
- package/src/agents/agents.ts +1141 -0
- package/src/agents/chain-serializer.ts +251 -0
- package/src/agents/frontmatter.ts +29 -0
- package/src/agents/identity.ts +30 -0
- package/src/agents/skills.ts +632 -0
- package/src/extension/config.ts +16 -0
- package/src/extension/control-notices.ts +92 -0
- package/src/extension/doctor.ts +236 -0
- package/src/extension/fanout-child.ts +170 -0
- package/src/extension/grand-total.ts +109 -0
- package/src/extension/index.ts +630 -0
- package/src/extension/schemas.ts +306 -0
- package/src/intercom/intercom-bridge.ts +379 -0
- package/src/intercom/result-intercom.ts +377 -0
- package/src/runs/background/async-execution.ts +796 -0
- package/src/runs/background/async-job-tracker.ts +320 -0
- package/src/runs/background/async-resume.ts +345 -0
- package/src/runs/background/async-status.ts +335 -0
- package/src/runs/background/completion-dedupe.ts +63 -0
- package/src/runs/background/notify.ts +108 -0
- package/src/runs/background/parallel-groups.ts +45 -0
- package/src/runs/background/result-watcher.ts +307 -0
- package/src/runs/background/run-id-resolver.ts +83 -0
- package/src/runs/background/run-status.ts +272 -0
- package/src/runs/background/stale-run-reconciler.ts +336 -0
- package/src/runs/background/subagent-runner.ts +2326 -0
- package/src/runs/background/top-level-async.ts +13 -0
- package/src/runs/foreground/chain-clarify.ts +1333 -0
- package/src/runs/foreground/chain-execution.ts +1187 -0
- package/src/runs/foreground/execution.ts +1028 -0
- package/src/runs/foreground/subagent-executor.ts +2580 -0
- package/src/runs/shared/acceptance.ts +605 -0
- package/src/runs/shared/chain-outputs.ts +101 -0
- package/src/runs/shared/completion-guard.ts +143 -0
- package/src/runs/shared/dynamic-fanout.ts +293 -0
- package/src/runs/shared/long-running-guard.ts +175 -0
- package/src/runs/shared/model-fallback.ts +103 -0
- package/src/runs/shared/nested-events.ts +822 -0
- package/src/runs/shared/nested-path.ts +52 -0
- package/src/runs/shared/nested-render.ts +115 -0
- package/src/runs/shared/parallel-utils.ts +136 -0
- package/src/runs/shared/pi-args.ts +221 -0
- package/src/runs/shared/pi-spawn.ts +115 -0
- package/src/runs/shared/run-history.ts +60 -0
- package/src/runs/shared/single-output.ts +164 -0
- package/src/runs/shared/structured-output.ts +77 -0
- package/src/runs/shared/subagent-control.ts +287 -0
- package/src/runs/shared/subagent-prompt-runtime.ts +220 -0
- package/src/runs/shared/workflow-graph.ts +206 -0
- package/src/runs/shared/worktree.ts +577 -0
- package/src/shared/artifacts.ts +98 -0
- package/src/shared/atomic-json.ts +16 -0
- package/src/shared/file-coalescer.ts +40 -0
- package/src/shared/fork-context.ts +76 -0
- package/src/shared/formatters.ts +133 -0
- package/src/shared/jsonl-writer.ts +81 -0
- package/src/shared/model-info.ts +78 -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 +46 -0
- package/src/shared/settings.ts +447 -0
- package/src/shared/status-format.ts +59 -0
- package/src/shared/types.ts +1072 -0
- package/src/shared/utils.ts +451 -0
- package/src/slash/prompt-template-bridge.ts +397 -0
- package/src/slash/slash-bridge.ts +174 -0
- package/src/slash/slash-commands.ts +567 -0
- package/src/slash/slash-live-state.ts +292 -0
- package/src/tui/render-helpers.ts +80 -0
- package/src/tui/render.ts +1476 -0
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import { getAgentDir } from "../../shared/utils.ts";
|
|
4
|
+
|
|
5
|
+
export interface RunEntry {
|
|
6
|
+
agent: string;
|
|
7
|
+
task: string;
|
|
8
|
+
ts: number;
|
|
9
|
+
status: "ok" | "error";
|
|
10
|
+
duration: number;
|
|
11
|
+
exit?: number;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const ROTATE_READ_THRESHOLD = 1200;
|
|
15
|
+
const ROTATE_KEEP = 1000;
|
|
16
|
+
|
|
17
|
+
function getHistoryPath(): string {
|
|
18
|
+
return path.join(getAgentDir(), "run-history.jsonl");
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function recordRun(agent: string, task: string, exitCode: number, durationMs: number): void {
|
|
22
|
+
try {
|
|
23
|
+
const entry: RunEntry = {
|
|
24
|
+
agent,
|
|
25
|
+
task: task.slice(0, 200),
|
|
26
|
+
ts: Math.floor(Date.now() / 1000),
|
|
27
|
+
status: exitCode === 0 ? "ok" : "error",
|
|
28
|
+
duration: durationMs,
|
|
29
|
+
...(exitCode !== 0 ? { exit: exitCode } : {}),
|
|
30
|
+
};
|
|
31
|
+
const historyPath = getHistoryPath();
|
|
32
|
+
fs.mkdirSync(path.dirname(historyPath), { recursive: true });
|
|
33
|
+
fs.appendFileSync(historyPath, `${JSON.stringify(entry)}\n`);
|
|
34
|
+
} catch {
|
|
35
|
+
// Best-effort — never crash the execution flow for history recording
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function loadRunsForAgent(agent: string): RunEntry[] {
|
|
40
|
+
const historyPath = getHistoryPath();
|
|
41
|
+
if (!fs.existsSync(historyPath)) return [];
|
|
42
|
+
let raw: string;
|
|
43
|
+
try {
|
|
44
|
+
raw = fs.readFileSync(historyPath, "utf-8");
|
|
45
|
+
} catch {
|
|
46
|
+
return [];
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
let lines = raw.split("\n").map((line) => line.trim()).filter((line) => line.length > 0);
|
|
50
|
+
|
|
51
|
+
if (lines.length > ROTATE_READ_THRESHOLD) {
|
|
52
|
+
lines = lines.slice(-ROTATE_KEEP);
|
|
53
|
+
try { fs.writeFileSync(historyPath, `${lines.join("\n")}\n`, "utf-8"); } catch {}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
return lines
|
|
57
|
+
.map((line) => { try { return JSON.parse(line) as RunEntry; } catch { return undefined; } })
|
|
58
|
+
.filter((entry): entry is RunEntry => Boolean(entry) && entry.agent === agent)
|
|
59
|
+
.reverse();
|
|
60
|
+
}
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import type { OutputMode, SavedOutputReference } from "../../shared/types.ts";
|
|
4
|
+
|
|
5
|
+
export interface SingleOutputSnapshot {
|
|
6
|
+
exists: boolean;
|
|
7
|
+
mtimeMs?: number;
|
|
8
|
+
size?: number;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function normalizeSingleOutputOverride(
|
|
12
|
+
output: string | boolean | undefined,
|
|
13
|
+
defaultOutput: string | undefined,
|
|
14
|
+
): string | false | undefined {
|
|
15
|
+
if (output === false || output === "false") return false;
|
|
16
|
+
if (output === true || output === "true") return defaultOutput;
|
|
17
|
+
if (typeof output === "string" && output.length > 0) return output;
|
|
18
|
+
return undefined;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function resolveSingleOutputPath(
|
|
22
|
+
output: string | boolean | undefined,
|
|
23
|
+
runtimeCwd: string,
|
|
24
|
+
requestedCwd?: string,
|
|
25
|
+
): string | undefined {
|
|
26
|
+
if (typeof output !== "string" || !output || output === "false" || output === "true") return undefined;
|
|
27
|
+
if (path.isAbsolute(output)) return output;
|
|
28
|
+
const baseCwd = requestedCwd
|
|
29
|
+
? (path.isAbsolute(requestedCwd) ? requestedCwd : path.resolve(runtimeCwd, requestedCwd))
|
|
30
|
+
: runtimeCwd;
|
|
31
|
+
return path.resolve(baseCwd, output);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function injectSingleOutputInstruction(task: string, outputPath: string | undefined): string {
|
|
35
|
+
if (!outputPath) return task;
|
|
36
|
+
return `${task}\n\n---\n**Output:** Write your findings to: ${outputPath}`;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function countLines(text: string): number {
|
|
40
|
+
if (!text) return 0;
|
|
41
|
+
const newlineMatches = text.match(/\r\n|\r|\n/g);
|
|
42
|
+
return (newlineMatches?.length ?? 0) + (/[\r\n]$/.test(text) ? 0 : 1);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function formatByteSize(bytes: number): string {
|
|
46
|
+
if (bytes < 1024) return `${bytes} B`;
|
|
47
|
+
const units = ["KB", "MB", "GB", "TB"];
|
|
48
|
+
let value = bytes / 1024;
|
|
49
|
+
let unitIndex = 0;
|
|
50
|
+
while (value >= 1024 && unitIndex < units.length - 1) {
|
|
51
|
+
value /= 1024;
|
|
52
|
+
unitIndex++;
|
|
53
|
+
}
|
|
54
|
+
return `${value.toFixed(1)} ${units[unitIndex]}`;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function formatSavedOutputReference(savedPath: string, fullOutput: string): SavedOutputReference {
|
|
58
|
+
const absolutePath = path.resolve(savedPath);
|
|
59
|
+
const bytes = Buffer.byteLength(fullOutput, "utf-8");
|
|
60
|
+
const lines = countLines(fullOutput);
|
|
61
|
+
return {
|
|
62
|
+
path: absolutePath,
|
|
63
|
+
bytes,
|
|
64
|
+
lines,
|
|
65
|
+
message: `Output saved to: ${absolutePath} (${formatByteSize(bytes)}, ${lines} ${lines === 1 ? "line" : "lines"}). Read this file if needed.`,
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function validateFileOnlyOutputMode(outputMode: OutputMode | undefined, outputPath: string | undefined, context: string): string | undefined {
|
|
70
|
+
if (outputMode === "file-only" && !outputPath) {
|
|
71
|
+
return `${context} sets outputMode: "file-only" but does not configure an output file. Set output to a path or use outputMode: "inline".`;
|
|
72
|
+
}
|
|
73
|
+
return undefined;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function captureSingleOutputSnapshot(outputPath: string | undefined): SingleOutputSnapshot | undefined {
|
|
77
|
+
if (!outputPath) return undefined;
|
|
78
|
+
try {
|
|
79
|
+
const stat = fs.statSync(outputPath);
|
|
80
|
+
return { exists: true, mtimeMs: stat.mtimeMs, size: stat.size };
|
|
81
|
+
} catch {
|
|
82
|
+
// The snapshot is advisory; resolveSingleOutput reports concrete read/write failures.
|
|
83
|
+
return { exists: false };
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function persistSingleOutput(
|
|
88
|
+
outputPath: string | undefined,
|
|
89
|
+
fullOutput: string,
|
|
90
|
+
): { savedPath?: string; error?: string } {
|
|
91
|
+
if (!outputPath) return {};
|
|
92
|
+
try {
|
|
93
|
+
fs.mkdirSync(path.dirname(outputPath), { recursive: true });
|
|
94
|
+
fs.writeFileSync(outputPath, fullOutput, "utf-8");
|
|
95
|
+
return { savedPath: outputPath };
|
|
96
|
+
} catch (err) {
|
|
97
|
+
return { error: err instanceof Error ? err.message : String(err) };
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function resolveSingleOutput(
|
|
102
|
+
outputPath: string | undefined,
|
|
103
|
+
fallbackOutput: string,
|
|
104
|
+
beforeRun: SingleOutputSnapshot | undefined,
|
|
105
|
+
): { fullOutput: string; savedPath?: string; saveError?: string } {
|
|
106
|
+
if (!outputPath) return { fullOutput: fallbackOutput };
|
|
107
|
+
|
|
108
|
+
let changedSinceStart = false;
|
|
109
|
+
try {
|
|
110
|
+
const stat = fs.statSync(outputPath);
|
|
111
|
+
changedSinceStart = !beforeRun?.exists
|
|
112
|
+
|| stat.mtimeMs !== beforeRun.mtimeMs
|
|
113
|
+
|| stat.size !== beforeRun.size;
|
|
114
|
+
} catch (error) {
|
|
115
|
+
const code = error && typeof error === "object" && "code" in error ? (error as { code?: unknown }).code : undefined;
|
|
116
|
+
if (code !== "ENOENT" && code !== "ENOTDIR") {
|
|
117
|
+
return {
|
|
118
|
+
fullOutput: fallbackOutput,
|
|
119
|
+
saveError: `Failed to inspect output file: ${error instanceof Error ? error.message : String(error)}`,
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
if (changedSinceStart) {
|
|
125
|
+
try {
|
|
126
|
+
return { fullOutput: fs.readFileSync(outputPath, "utf-8"), savedPath: outputPath };
|
|
127
|
+
} catch (error) {
|
|
128
|
+
return {
|
|
129
|
+
fullOutput: fallbackOutput,
|
|
130
|
+
saveError: `Failed to read changed output file: ${error instanceof Error ? error.message : String(error)}`,
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const save = persistSingleOutput(outputPath, fallbackOutput);
|
|
136
|
+
if (save.savedPath) return { fullOutput: fallbackOutput, savedPath: save.savedPath };
|
|
137
|
+
return { fullOutput: fallbackOutput, saveError: save.error };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export function finalizeSingleOutput(params: {
|
|
141
|
+
fullOutput: string;
|
|
142
|
+
truncatedOutput?: string;
|
|
143
|
+
outputPath?: string;
|
|
144
|
+
outputMode?: OutputMode;
|
|
145
|
+
exitCode: number;
|
|
146
|
+
savedPath?: string;
|
|
147
|
+
outputReference?: SavedOutputReference;
|
|
148
|
+
saveError?: string;
|
|
149
|
+
}): { displayOutput: string; savedPath?: string; outputReference?: SavedOutputReference; saveError?: string } {
|
|
150
|
+
let displayOutput = params.truncatedOutput || params.fullOutput;
|
|
151
|
+
if (params.exitCode === 0 && params.savedPath) {
|
|
152
|
+
const outputReference = params.outputReference ?? formatSavedOutputReference(params.savedPath, params.fullOutput);
|
|
153
|
+
if (params.outputMode === "file-only") {
|
|
154
|
+
return { displayOutput: outputReference.message, savedPath: params.savedPath, outputReference };
|
|
155
|
+
}
|
|
156
|
+
displayOutput += `\n\n${outputReference.message}`;
|
|
157
|
+
return { displayOutput, savedPath: params.savedPath, outputReference };
|
|
158
|
+
}
|
|
159
|
+
if (params.exitCode === 0 && params.saveError && params.outputPath) {
|
|
160
|
+
displayOutput += `\n\nOutput file error: ${params.outputPath}\n${params.saveError}`;
|
|
161
|
+
return { displayOutput, saveError: params.saveError };
|
|
162
|
+
}
|
|
163
|
+
return { displayOutput };
|
|
164
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
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 "typebox/compile";
|
|
5
|
+
import type { JsonSchemaObject } from "../../shared/types.ts";
|
|
6
|
+
|
|
7
|
+
export const STRUCTURED_OUTPUT_SCHEMA_ENV = "PI_SUBAGENT_STRUCTURED_OUTPUT_SCHEMA";
|
|
8
|
+
export const STRUCTURED_OUTPUT_CAPTURE_ENV = "PI_SUBAGENT_STRUCTURED_OUTPUT_CAPTURE";
|
|
9
|
+
|
|
10
|
+
export interface StructuredOutputRuntime {
|
|
11
|
+
schema: JsonSchemaObject;
|
|
12
|
+
schemaPath: string;
|
|
13
|
+
outputPath: string;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
interface CompiledJsonSchema {
|
|
17
|
+
Check(value: unknown): boolean;
|
|
18
|
+
Errors(value: unknown): Iterable<{ instancePath?: string; message?: string }>;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function assertJsonSchemaObject(schema: unknown, label = "outputSchema"): asserts schema is JsonSchemaObject {
|
|
22
|
+
if (!schema || typeof schema !== "object" || Array.isArray(schema)) {
|
|
23
|
+
throw new Error(`${label} must be a JSON Schema object.`);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function createStructuredOutputRuntime(schema: JsonSchemaObject, baseDir?: string): StructuredOutputRuntime {
|
|
28
|
+
assertJsonSchemaObject(schema);
|
|
29
|
+
const rootDir = baseDir ?? os.tmpdir();
|
|
30
|
+
fs.mkdirSync(rootDir, { recursive: true });
|
|
31
|
+
const dir = fs.mkdtempSync(path.join(rootDir, "pi-subagent-structured-"));
|
|
32
|
+
const schemaPath = path.join(dir, "schema.json");
|
|
33
|
+
const outputPath = path.join(dir, "output.json");
|
|
34
|
+
fs.writeFileSync(schemaPath, JSON.stringify(schema), { mode: 0o600 });
|
|
35
|
+
return { schema, schemaPath, outputPath };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function validateStructuredOutputValue(schema: JsonSchemaObject, value: unknown): { status: "valid" } | { status: "invalid"; message: string } {
|
|
39
|
+
let validator: CompiledJsonSchema;
|
|
40
|
+
try {
|
|
41
|
+
validator = (Compile as (schema: unknown) => CompiledJsonSchema)(schema);
|
|
42
|
+
} catch (error) {
|
|
43
|
+
return { status: "invalid", message: `invalid outputSchema: ${error instanceof Error ? error.message : String(error)}` };
|
|
44
|
+
}
|
|
45
|
+
if (validator.Check(value)) return { status: "valid" };
|
|
46
|
+
const errors = [...validator.Errors(value)]
|
|
47
|
+
.slice(0, 8)
|
|
48
|
+
.map((error) => {
|
|
49
|
+
const pathText = error.instancePath ? error.instancePath.replace(/^\//, "").replace(/\//g, ".") : "root";
|
|
50
|
+
return `${pathText}: ${error.message}`;
|
|
51
|
+
});
|
|
52
|
+
return { status: "invalid", message: errors.join("; ") || "schema validation failed" };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function readStructuredOutput(runtime: StructuredOutputRuntime): { value?: unknown; error?: string } {
|
|
56
|
+
if (!fs.existsSync(runtime.outputPath)) {
|
|
57
|
+
return { error: "Missing structured_output call; this step has outputSchema and must finish by calling structured_output." };
|
|
58
|
+
}
|
|
59
|
+
let value: unknown;
|
|
60
|
+
try {
|
|
61
|
+
value = JSON.parse(fs.readFileSync(runtime.outputPath, "utf-8"));
|
|
62
|
+
} catch (error) {
|
|
63
|
+
return { error: `Failed to read structured output: ${error instanceof Error ? error.message : String(error)}` };
|
|
64
|
+
}
|
|
65
|
+
const validation = validateStructuredOutputValue(runtime.schema, value);
|
|
66
|
+
if (validation.status === "invalid") return { error: `Structured output validation failed: ${validation.message}` };
|
|
67
|
+
return { value };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function cleanupStructuredOutputRuntime(runtime: StructuredOutputRuntime | undefined): void {
|
|
71
|
+
if (!runtime) return;
|
|
72
|
+
try {
|
|
73
|
+
fs.rmSync(path.dirname(runtime.schemaPath), { recursive: true, force: true });
|
|
74
|
+
} catch {
|
|
75
|
+
// Best-effort temp cleanup.
|
|
76
|
+
}
|
|
77
|
+
}
|
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type ActivityState,
|
|
3
|
+
type ControlConfig,
|
|
4
|
+
type ControlEvent,
|
|
5
|
+
type ControlEventType,
|
|
6
|
+
type ControlNotificationChannel,
|
|
7
|
+
type ResolvedControlConfig,
|
|
8
|
+
} from "../../shared/types.ts";
|
|
9
|
+
|
|
10
|
+
const CONTROL_EVENT_TYPES: ControlEventType[] = ["active_long_running", "needs_attention"];
|
|
11
|
+
const CONTROL_NOTIFICATION_CHANNELS: ControlNotificationChannel[] = ["event", "async", "intercom"];
|
|
12
|
+
const DEFAULT_NOTIFY_ON: ControlEventType[] = ["active_long_running", "needs_attention"];
|
|
13
|
+
|
|
14
|
+
export const DEFAULT_CONTROL_CONFIG: ResolvedControlConfig = {
|
|
15
|
+
enabled: true,
|
|
16
|
+
needsAttentionAfterMs: 60_000,
|
|
17
|
+
activeNoticeAfterMs: 240_000,
|
|
18
|
+
inFlightSilenceCeilingMs: 600_000,
|
|
19
|
+
inFlightSilenceKillMs: 1_800_000,
|
|
20
|
+
failedToolAttemptsBeforeAttention: 3,
|
|
21
|
+
notifyOn: DEFAULT_NOTIFY_ON,
|
|
22
|
+
notifyChannels: CONTROL_NOTIFICATION_CHANNELS,
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
function parsePositiveInt(value: unknown): number | undefined {
|
|
26
|
+
if (typeof value !== "number") return undefined;
|
|
27
|
+
if (!Number.isFinite(value) || !Number.isInteger(value) || value < 1) return undefined;
|
|
28
|
+
return value;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function parseControlList<T extends string>(value: unknown, allowed: readonly T[]): T[] | undefined {
|
|
32
|
+
if (!Array.isArray(value)) return undefined;
|
|
33
|
+
if (value.length === 0) return [];
|
|
34
|
+
const allowedSet = new Set(allowed);
|
|
35
|
+
const parsed = value.filter((entry): entry is T => typeof entry === "string" && allowedSet.has(entry as T));
|
|
36
|
+
return parsed.length > 0 ? Array.from(new Set(parsed)) : undefined;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function resolveControlConfig(
|
|
40
|
+
globalConfig?: ControlConfig,
|
|
41
|
+
override?: ControlConfig,
|
|
42
|
+
): ResolvedControlConfig {
|
|
43
|
+
const enabled = override?.enabled ?? globalConfig?.enabled ?? DEFAULT_CONTROL_CONFIG.enabled;
|
|
44
|
+
const needsAttentionAfterMs = parsePositiveInt(override?.needsAttentionAfterMs)
|
|
45
|
+
?? parsePositiveInt(globalConfig?.needsAttentionAfterMs)
|
|
46
|
+
?? DEFAULT_CONTROL_CONFIG.needsAttentionAfterMs;
|
|
47
|
+
const activeNoticeAfterMs = parsePositiveInt(override?.activeNoticeAfterMs)
|
|
48
|
+
?? parsePositiveInt(globalConfig?.activeNoticeAfterMs)
|
|
49
|
+
?? DEFAULT_CONTROL_CONFIG.activeNoticeAfterMs;
|
|
50
|
+
const inFlightSilenceCeilingMs = parsePositiveInt(override?.inFlightSilenceCeilingMs)
|
|
51
|
+
?? parsePositiveInt(globalConfig?.inFlightSilenceCeilingMs)
|
|
52
|
+
?? DEFAULT_CONTROL_CONFIG.inFlightSilenceCeilingMs;
|
|
53
|
+
const resolvedInFlightSilenceKillMs = parsePositiveInt(override?.inFlightSilenceKillMs)
|
|
54
|
+
?? parsePositiveInt(globalConfig?.inFlightSilenceKillMs)
|
|
55
|
+
?? DEFAULT_CONTROL_CONFIG.inFlightSilenceKillMs;
|
|
56
|
+
const inFlightSilenceKillMs = Math.max(
|
|
57
|
+
resolvedInFlightSilenceKillMs,
|
|
58
|
+
inFlightSilenceCeilingMs + needsAttentionAfterMs,
|
|
59
|
+
);
|
|
60
|
+
const activeNoticeAfterTurns = parsePositiveInt(override?.activeNoticeAfterTurns)
|
|
61
|
+
?? parsePositiveInt(globalConfig?.activeNoticeAfterTurns);
|
|
62
|
+
const activeNoticeAfterTokens = parsePositiveInt(override?.activeNoticeAfterTokens)
|
|
63
|
+
?? parsePositiveInt(globalConfig?.activeNoticeAfterTokens);
|
|
64
|
+
const failedToolAttemptsBeforeAttention = parsePositiveInt(override?.failedToolAttemptsBeforeAttention)
|
|
65
|
+
?? parsePositiveInt(globalConfig?.failedToolAttemptsBeforeAttention)
|
|
66
|
+
?? DEFAULT_CONTROL_CONFIG.failedToolAttemptsBeforeAttention;
|
|
67
|
+
const notifyOn = parseControlList(override?.notifyOn, CONTROL_EVENT_TYPES)
|
|
68
|
+
?? parseControlList(globalConfig?.notifyOn, CONTROL_EVENT_TYPES)
|
|
69
|
+
?? DEFAULT_CONTROL_CONFIG.notifyOn;
|
|
70
|
+
const notifyChannels = parseControlList(override?.notifyChannels, CONTROL_NOTIFICATION_CHANNELS)
|
|
71
|
+
?? parseControlList(globalConfig?.notifyChannels, CONTROL_NOTIFICATION_CHANNELS)
|
|
72
|
+
?? DEFAULT_CONTROL_CONFIG.notifyChannels;
|
|
73
|
+
return {
|
|
74
|
+
enabled,
|
|
75
|
+
needsAttentionAfterMs,
|
|
76
|
+
activeNoticeAfterMs,
|
|
77
|
+
inFlightSilenceCeilingMs,
|
|
78
|
+
inFlightSilenceKillMs,
|
|
79
|
+
activeNoticeAfterTurns,
|
|
80
|
+
activeNoticeAfterTokens,
|
|
81
|
+
failedToolAttemptsBeforeAttention,
|
|
82
|
+
notifyOn: [...notifyOn],
|
|
83
|
+
notifyChannels: [...notifyChannels],
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export interface TurnLifecycleState {
|
|
88
|
+
turnOpen?: boolean;
|
|
89
|
+
lastProductiveSignalAt?: number;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function applyChildEventToLifecycle(
|
|
93
|
+
state: TurnLifecycleState,
|
|
94
|
+
event: { type?: string; hasToolCall?: boolean },
|
|
95
|
+
now: number,
|
|
96
|
+
): TurnLifecycleState {
|
|
97
|
+
switch (event.type) {
|
|
98
|
+
case "turn_start":
|
|
99
|
+
case "message_start":
|
|
100
|
+
return { turnOpen: true, lastProductiveSignalAt: state.lastProductiveSignalAt };
|
|
101
|
+
case "message_update":
|
|
102
|
+
case "tool_execution_start":
|
|
103
|
+
case "tool_execution_end":
|
|
104
|
+
case "tool_result_end":
|
|
105
|
+
return { turnOpen: state.turnOpen, lastProductiveSignalAt: now };
|
|
106
|
+
case "message_end":
|
|
107
|
+
return { turnOpen: event.hasToolCall ? state.turnOpen : false, lastProductiveSignalAt: now };
|
|
108
|
+
case "turn_end":
|
|
109
|
+
return { turnOpen: false, lastProductiveSignalAt: now };
|
|
110
|
+
default:
|
|
111
|
+
return state;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export function deriveActivityState(input: {
|
|
116
|
+
config: ResolvedControlConfig;
|
|
117
|
+
startedAt: number;
|
|
118
|
+
lastActivityAt?: number;
|
|
119
|
+
now?: number;
|
|
120
|
+
inFlightTurn?: boolean;
|
|
121
|
+
lastProductiveSignalAt?: number;
|
|
122
|
+
}): ActivityState | undefined {
|
|
123
|
+
if (!input.config.enabled) return undefined;
|
|
124
|
+
const now = input.now ?? Date.now();
|
|
125
|
+
const lastActivity = input.lastActivityAt ?? input.startedAt;
|
|
126
|
+
const ageMs = Math.max(0, now - lastActivity);
|
|
127
|
+
if (ageMs <= input.config.needsAttentionAfterMs) return undefined;
|
|
128
|
+
if (input.inFlightTurn) {
|
|
129
|
+
const silenceMs = Math.max(0, now - (input.lastProductiveSignalAt ?? input.startedAt));
|
|
130
|
+
return silenceMs > input.config.inFlightSilenceCeilingMs ? "needs_attention" : "active_long_running";
|
|
131
|
+
}
|
|
132
|
+
return "needs_attention";
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export function shouldSilenceKill(input: {
|
|
136
|
+
turnOpen?: boolean;
|
|
137
|
+
lastProductiveSignalAt?: number;
|
|
138
|
+
startedAt: number;
|
|
139
|
+
now: number;
|
|
140
|
+
killMs: number;
|
|
141
|
+
}): boolean {
|
|
142
|
+
if (!input.turnOpen) return false;
|
|
143
|
+
const silenceMs = input.now - (input.lastProductiveSignalAt ?? input.startedAt);
|
|
144
|
+
return silenceMs > input.killMs;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export function buildControlEvent(input: {
|
|
148
|
+
type?: ControlEventType;
|
|
149
|
+
from?: ActivityState;
|
|
150
|
+
to: ActivityState;
|
|
151
|
+
runId: string;
|
|
152
|
+
agent: string;
|
|
153
|
+
index?: number;
|
|
154
|
+
ts?: number;
|
|
155
|
+
lastActivityAt?: number;
|
|
156
|
+
message?: string;
|
|
157
|
+
reason?: ControlEvent["reason"];
|
|
158
|
+
turns?: number;
|
|
159
|
+
tokens?: number;
|
|
160
|
+
toolCount?: number;
|
|
161
|
+
currentTool?: string;
|
|
162
|
+
currentToolDurationMs?: number;
|
|
163
|
+
currentPath?: string;
|
|
164
|
+
elapsedMs?: number;
|
|
165
|
+
recentFailureSummary?: string;
|
|
166
|
+
}): ControlEvent {
|
|
167
|
+
const ts = input.ts ?? Date.now();
|
|
168
|
+
const type = input.type ?? (input.to === "active_long_running" ? "active_long_running" : "needs_attention");
|
|
169
|
+
const elapsedMs = input.elapsedMs ?? (input.lastActivityAt ? Math.max(0, ts - input.lastActivityAt) : undefined);
|
|
170
|
+
const elapsedSeconds = elapsedMs !== undefined ? Math.floor(elapsedMs / 1000) : undefined;
|
|
171
|
+
const message = input.message ?? (type === "active_long_running"
|
|
172
|
+
? `${input.agent} is still active but long-running`
|
|
173
|
+
: elapsedSeconds !== undefined
|
|
174
|
+
? `${input.agent} needs attention (no observed activity for ${elapsedSeconds}s)`
|
|
175
|
+
: `${input.agent} needs attention`);
|
|
176
|
+
return {
|
|
177
|
+
type,
|
|
178
|
+
...(input.from ? { from: input.from } : {}),
|
|
179
|
+
to: input.to,
|
|
180
|
+
ts,
|
|
181
|
+
runId: input.runId,
|
|
182
|
+
agent: input.agent,
|
|
183
|
+
...(input.index !== undefined ? { index: input.index } : {}),
|
|
184
|
+
message,
|
|
185
|
+
reason: input.reason ?? (type === "active_long_running" ? "active_long_running" : "idle"),
|
|
186
|
+
...(input.turns !== undefined ? { turns: input.turns } : {}),
|
|
187
|
+
...(input.tokens !== undefined ? { tokens: input.tokens } : {}),
|
|
188
|
+
...(input.toolCount !== undefined ? { toolCount: input.toolCount } : {}),
|
|
189
|
+
...(input.currentTool ? { currentTool: input.currentTool } : {}),
|
|
190
|
+
...(input.currentToolDurationMs !== undefined ? { currentToolDurationMs: input.currentToolDurationMs } : {}),
|
|
191
|
+
...(input.currentPath ? { currentPath: input.currentPath } : {}),
|
|
192
|
+
...(elapsedMs !== undefined ? { elapsedMs } : {}),
|
|
193
|
+
...(input.recentFailureSummary ? { recentFailureSummary: input.recentFailureSummary } : {}),
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
export function shouldNotifyControlEvent(config: ResolvedControlConfig, event: ControlEvent): boolean {
|
|
198
|
+
return config.enabled && config.notifyOn.includes(event.type);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
export function controlNotificationKey(event: ControlEvent, childIntercomTarget?: string): string {
|
|
202
|
+
const childKey = childIntercomTarget ?? (event.index !== undefined ? `${event.runId}:${event.index}` : event.runId);
|
|
203
|
+
return `${childKey}:${event.type}:${event.reason ?? "idle"}`;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export function claimControlNotification(config: ResolvedControlConfig, event: ControlEvent, seenKeys: Set<string>, childIntercomTarget?: string): boolean {
|
|
207
|
+
if (!shouldNotifyControlEvent(config, event)) return false;
|
|
208
|
+
const key = controlNotificationKey(event, childIntercomTarget);
|
|
209
|
+
if (seenKeys.has(key)) return false;
|
|
210
|
+
seenKeys.add(key);
|
|
211
|
+
return true;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
function formatLongRunningFacts(event: ControlEvent): string | undefined {
|
|
215
|
+
const facts: string[] = [];
|
|
216
|
+
if (event.elapsedMs !== undefined) facts.push(`elapsed ${Math.floor(Math.max(0, event.elapsedMs) / 1000)}s`);
|
|
217
|
+
if (event.turns !== undefined) facts.push(`${event.turns} turns`);
|
|
218
|
+
if (event.tokens !== undefined) facts.push(`${event.tokens} tokens`);
|
|
219
|
+
if (event.toolCount !== undefined) facts.push(`${event.toolCount} tools`);
|
|
220
|
+
if (event.currentTool) facts.push(`tool ${event.currentTool}${event.currentToolDurationMs !== undefined ? ` ${Math.floor(Math.max(0, event.currentToolDurationMs) / 1000)}s` : ""}`);
|
|
221
|
+
if (event.currentPath) facts.push(`path ${event.currentPath}`);
|
|
222
|
+
return facts.length > 0 ? facts.join(" | ") : undefined;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
export function formatControlNoticeMessage(event: ControlEvent, childIntercomTarget?: string): string {
|
|
226
|
+
const runTarget = event.runId;
|
|
227
|
+
if (event.reason === "completion_guard") {
|
|
228
|
+
return [
|
|
229
|
+
`Subagent failed: ${event.agent}`,
|
|
230
|
+
`Run: ${runTarget}${event.index !== undefined ? ` step ${event.index + 1}` : ""}`,
|
|
231
|
+
`Signal: ${event.message}`,
|
|
232
|
+
"Next: read the output artifact or session from the subagent result, then retry with a more explicit implementation prompt or handle the fix directly.",
|
|
233
|
+
childIntercomTarget ? `Run intercom target (may be inactive): ${childIntercomTarget}` : undefined,
|
|
234
|
+
].filter((line): line is string => Boolean(line)).join("\n");
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
const nudgeCommand = childIntercomTarget
|
|
238
|
+
? `intercom({ action: "send", to: "${childIntercomTarget}", message: "What are you blocked on? Reply with the smallest next step or ask for a decision." })`
|
|
239
|
+
: undefined;
|
|
240
|
+
if (event.type === "active_long_running") {
|
|
241
|
+
const facts = formatLongRunningFacts(event);
|
|
242
|
+
return [
|
|
243
|
+
`Subagent active but long-running: ${event.agent}`,
|
|
244
|
+
`Run: ${runTarget}${event.index !== undefined ? ` step ${event.index + 1}` : ""}`,
|
|
245
|
+
`Signal: ${event.message}`,
|
|
246
|
+
facts ? `Facts: ${facts}` : undefined,
|
|
247
|
+
"Hint: Inspect status, then nudge if the work seems stuck.",
|
|
248
|
+
childIntercomTarget
|
|
249
|
+
? `Nudge: ${nudgeCommand}`
|
|
250
|
+
: "Nudge: no child message route registered",
|
|
251
|
+
`Status: subagent({ action: "status", id: "${runTarget}" })`,
|
|
252
|
+
`Interrupt: subagent({ action: "interrupt", id: "${runTarget}" })`,
|
|
253
|
+
].filter((line): line is string => Boolean(line)).join("\n");
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
return [
|
|
257
|
+
`Subagent needs attention: ${event.agent}`,
|
|
258
|
+
`Run: ${runTarget}${event.index !== undefined ? ` step ${event.index + 1}` : ""}`,
|
|
259
|
+
`Signal: ${event.message}`,
|
|
260
|
+
event.recentFailureSummary ? `Recent failures: ${event.recentFailureSummary}` : undefined,
|
|
261
|
+
"Hint: Inspect status first unless the run is clearly blocked.",
|
|
262
|
+
childIntercomTarget
|
|
263
|
+
? `Nudge: ${nudgeCommand}`
|
|
264
|
+
: "Nudge: no child message route registered",
|
|
265
|
+
`Status: subagent({ action: "status", id: "${runTarget}" })`,
|
|
266
|
+
`Interrupt: subagent({ action: "interrupt", id: "${runTarget}" })`,
|
|
267
|
+
].filter((line): line is string => Boolean(line)).join("\n");
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
export function formatControlIntercomMessage(event: ControlEvent, childIntercomTarget?: string): string {
|
|
271
|
+
const statusLabel = event.reason === "completion_guard"
|
|
272
|
+
? "subagent failed"
|
|
273
|
+
: event.type === "active_long_running"
|
|
274
|
+
? "subagent active but long-running"
|
|
275
|
+
: "subagent needs attention";
|
|
276
|
+
return [
|
|
277
|
+
statusLabel,
|
|
278
|
+
"",
|
|
279
|
+
event.reason === "completion_guard"
|
|
280
|
+
? `${event.agent} failed in run ${event.runId}.`
|
|
281
|
+
: event.type === "active_long_running"
|
|
282
|
+
? `${event.agent} is still active but long-running in run ${event.runId}.`
|
|
283
|
+
: `${event.agent} needs attention in run ${event.runId}.`,
|
|
284
|
+
"",
|
|
285
|
+
formatControlNoticeMessage(event, childIntercomTarget),
|
|
286
|
+
].join("\n");
|
|
287
|
+
}
|