@maheidem/pi-delegate 0.6.0 → 0.6.2
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/README.md +11 -0
- package/ask.ts +183 -0
- package/background.ts +780 -0
- package/commands.ts +18 -1
- package/index.ts +43 -0
- package/package.json +72 -70
package/README.md
CHANGED
|
@@ -28,6 +28,7 @@ is performed by this package.
|
|
|
28
28
|
/delegate dashboard (TUI) / status (headless)
|
|
29
29
|
/delegate run general <task> foreground delegation (impl specialist)
|
|
30
30
|
/delegate research <task> foreground web research (read-only tools)
|
|
31
|
+
/delegate bg [role] <task> run it in the background (report arrives later)
|
|
31
32
|
/delegate on enable strict coordinator mode (session,
|
|
32
33
|
tree-stable; active tool set becomes
|
|
33
34
|
['delegate'])
|
|
@@ -183,6 +184,16 @@ internal work events.
|
|
|
183
184
|
children — receipts finalize interrupted/resumable. Prefer foreground for
|
|
184
185
|
one-shot headless flows.
|
|
185
186
|
|
|
187
|
+
**User-facing launch (v0.6.2, R20).** `/delegate bg [general|research] <task>`
|
|
188
|
+
runs the same background run from the command line with no description to
|
|
189
|
+
write: one is derived from the task's first line (edge punctuation stripped,
|
|
190
|
+
first 3–6 words), validated by the same 3–6-word rule — a first line too
|
|
191
|
+
short to yield 3 words is an instructive error — echoed in the started line,
|
|
192
|
+
and stored on the receipt/ledger like an explicit one. The dashboard's
|
|
193
|
+
**Run background task…** action (task editor) takes the same path. Explicit
|
|
194
|
+
descriptions remain available to the model via `delegate({ background: true,
|
|
195
|
+
description: "…" })`; foreground `/delegate run` is unchanged.
|
|
196
|
+
|
|
186
197
|
### Bidirectional channels (v0.6.0, R16–R19)
|
|
187
198
|
|
|
188
199
|
Background children are a team, not batch jobs — three channels, all auditable
|
package/ask.ts
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* delegate — ask_parent channel (R17/R18): background children can ask the
|
|
3
|
+
* parent blocking questions (answered via delegate_answer) and file
|
|
4
|
+
* non-blocking notes. Child-side tool + shared validation; the parent-side
|
|
5
|
+
* delivery lives in background.ts and the runner.
|
|
6
|
+
*
|
|
7
|
+
* Mechanism (SPEC §3): the tool call IS the blocking primitive. The child's
|
|
8
|
+
* execute() polls $PI_DELEGATE_ASK_DIR/<toolCallId>.json until the parent's
|
|
9
|
+
* answer lands or the budget expires. The runner watches the toolCall records
|
|
10
|
+
* on the child stream and delivers the question/note message to the parent.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { Type } from "typebox";
|
|
14
|
+
import * as fs from "node:fs";
|
|
15
|
+
import * as path from "node:path";
|
|
16
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
17
|
+
|
|
18
|
+
export const CHILD_QUESTION_TYPE = "delegate-child-question";
|
|
19
|
+
export const CHILD_NOTE_TYPE = "delegate-child-note";
|
|
20
|
+
|
|
21
|
+
/** R17: the exact timeout fallback (byte-exact per SPEC §5 discipline). */
|
|
22
|
+
export const ASK_FALLBACK_TEXT =
|
|
23
|
+
"No answer arrived within the budget. Proceed with your best judgment and state the assumption in your handoff.";
|
|
24
|
+
|
|
25
|
+
/** R18: notes are capped to bound spam (never blocks, never wakes). */
|
|
26
|
+
export const MAX_NOTES_PER_RUN = 20;
|
|
27
|
+
|
|
28
|
+
const QUESTION_TOPICS = ["blocked", "guidance", "approval", "opinion"] as const;
|
|
29
|
+
const NOTE_TOPICS = ["risk", "observation", "concern"] as const;
|
|
30
|
+
|
|
31
|
+
export const AskParentParams = Type.Object({
|
|
32
|
+
kind: Type.Union([Type.Literal("question"), Type.Literal("note")], {
|
|
33
|
+
description: "question = you are blocked and wait for the parent's answer; note = non-blocking FYI for the parent (no answer will come).",
|
|
34
|
+
}),
|
|
35
|
+
topic: Type.String({
|
|
36
|
+
description: "question: blocked | guidance | approval | opinion. note: risk | observation | concern.",
|
|
37
|
+
}),
|
|
38
|
+
text: Type.String({
|
|
39
|
+
minLength: 1,
|
|
40
|
+
maxLength: 2000,
|
|
41
|
+
description: "The question or note, ≤2000 chars. For questions: be specific and self-contained; the parent answers from its own context only.",
|
|
42
|
+
}),
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
export type AskSubmission = {
|
|
46
|
+
kind: "question" | "note";
|
|
47
|
+
topic: string;
|
|
48
|
+
text: string;
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
export function validateAskSubmission(params: unknown): { ok: true; value: AskSubmission } | { ok: false; errors: string[] } {
|
|
52
|
+
if (!params || typeof params !== "object") return { ok: false, errors: ["ask_parent params must be an object."] };
|
|
53
|
+
const raw = params as Record<string, unknown>;
|
|
54
|
+
const errors: string[] = [];
|
|
55
|
+
if (raw.kind !== "question" && raw.kind !== "note") errors.push("kind must be 'question' or 'note'.");
|
|
56
|
+
const topic = typeof raw.topic === "string" ? raw.topic.trim() : "";
|
|
57
|
+
if (!topic) errors.push("topic is required.");
|
|
58
|
+
else if (raw.kind === "question" && !(QUESTION_TOPICS as readonly string[]).includes(topic)) {
|
|
59
|
+
errors.push(`question topic must be one of: ${QUESTION_TOPICS.join(", ")}.`);
|
|
60
|
+
} else if (raw.kind === "note" && !(NOTE_TOPICS as readonly string[]).includes(topic)) {
|
|
61
|
+
errors.push(`note topic must be one of: ${NOTE_TOPICS.join(", ")}.`);
|
|
62
|
+
}
|
|
63
|
+
const text = typeof raw.text === "string" ? raw.text : "";
|
|
64
|
+
if (!text.trim()) errors.push("text is required.");
|
|
65
|
+
if (text.length > 2000) errors.push(`text must be ≤2000 chars (got ${text.length}).`);
|
|
66
|
+
if (errors.length > 0) return { ok: false, errors };
|
|
67
|
+
return { ok: true, value: { kind: raw.kind as "question" | "note", topic, text } };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export interface AskEnv {
|
|
71
|
+
askDir?: string;
|
|
72
|
+
timeoutMs: number;
|
|
73
|
+
maxQuestions: number;
|
|
74
|
+
/** Test seam: sleep between polls. */
|
|
75
|
+
sleep?: (ms: number) => Promise<void>;
|
|
76
|
+
/** Test seam: inject the answer instead of reading the file. */
|
|
77
|
+
readAnswer?: (toolCallId: string) => { answeredBy: string; answer: string } | null;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
type AskToolResult = {
|
|
81
|
+
content: Array<{ type: "text"; text: string }>;
|
|
82
|
+
details: {
|
|
83
|
+
rejected?: boolean;
|
|
84
|
+
errors?: string[];
|
|
85
|
+
askNote?: AskSubmission;
|
|
86
|
+
askAnswered?: boolean;
|
|
87
|
+
answeredBy?: string;
|
|
88
|
+
askTimedOut?: boolean;
|
|
89
|
+
};
|
|
90
|
+
isError?: boolean;
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Child-side registration. The tool exists ONLY in background children
|
|
95
|
+
* (PI_DELEGATE_ASK_DIR set by the runner when askParent is enabled):
|
|
96
|
+
* a foreground child asking would deadlock the parent turn by construction.
|
|
97
|
+
*/
|
|
98
|
+
export function registerAskParentTool(pi: ExtensionAPI, env: AskEnv): void {
|
|
99
|
+
const questionsAsked = { count: 0 };
|
|
100
|
+
const notesFiled = { count: 0 };
|
|
101
|
+
const sleep = env.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));
|
|
102
|
+
const readAnswer = env.readAnswer ?? ((toolCallId: string) => {
|
|
103
|
+
const file = path.join(env.askDir ?? "", `${toolCallId}.json`);
|
|
104
|
+
try {
|
|
105
|
+
const raw = JSON.parse(fs.readFileSync(file, "utf8")) as { answeredBy?: string; answer?: string };
|
|
106
|
+
if (typeof raw.answer === "string") return { answeredBy: raw.answeredBy ?? "model", answer: raw.answer };
|
|
107
|
+
return null;
|
|
108
|
+
} catch {
|
|
109
|
+
return null;
|
|
110
|
+
}
|
|
111
|
+
});
|
|
112
|
+
pi.registerTool({
|
|
113
|
+
name: "ask_parent",
|
|
114
|
+
label: "Ask the parent",
|
|
115
|
+
description:
|
|
116
|
+
"Ask the delegating parent agent a question (you block until it answers or the budget expires) or file a non-blocking note. " +
|
|
117
|
+
"Ask only when you are genuinely blocked or a wrong guess is expensive; for cheap decisions proceed with a stated assumption instead. " +
|
|
118
|
+
"Prefer notes for risks and observations — they never stall your run.",
|
|
119
|
+
parameters: AskParentParams,
|
|
120
|
+
async execute(toolCallId: string, params): Promise<AskToolResult> {
|
|
121
|
+
const validation = validateAskSubmission(params);
|
|
122
|
+
if (!validation.ok) {
|
|
123
|
+
return {
|
|
124
|
+
content: [{ type: "text" as const, text: `ask_parent REJECTED — fix and call again:\n${validation.errors.map((e) => `- ${e}`).join("\n")}` }],
|
|
125
|
+
details: { rejected: true, errors: validation.errors },
|
|
126
|
+
isError: true,
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
const ask = validation.value;
|
|
130
|
+
if (ask.kind === "note") {
|
|
131
|
+
if (notesFiled.count >= MAX_NOTES_PER_RUN) {
|
|
132
|
+
return {
|
|
133
|
+
content: [{ type: "text" as const, text: `Note cap reached (${MAX_NOTES_PER_RUN}). Continue your work; include remaining observations in your handoff.` }],
|
|
134
|
+
details: { rejected: true },
|
|
135
|
+
isError: true,
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
notesFiled.count += 1;
|
|
139
|
+
return {
|
|
140
|
+
content: [{ type: "text" as const, text: `Note delivered to the parent (topic: ${ask.topic}). No answer will arrive — continue your work.` }],
|
|
141
|
+
details: { askNote: ask },
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
questionsAsked.count += 1;
|
|
145
|
+
if (questionsAsked.count > env.maxQuestions) {
|
|
146
|
+
return {
|
|
147
|
+
content: [{ type: "text" as const, text: `Question budget exhausted (${env.maxQuestions} per run). ${ASK_FALLBACK_TEXT}` }],
|
|
148
|
+
details: { rejected: true },
|
|
149
|
+
isError: true,
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
const deadline = Date.now() + env.timeoutMs;
|
|
153
|
+
for (;;) {
|
|
154
|
+
const answer = readAnswer(toolCallId);
|
|
155
|
+
if (answer) {
|
|
156
|
+
return {
|
|
157
|
+
content: [{ type: "text" as const, text: `[parent answered · by ${answer.answeredBy}]\n${answer.answer}` }],
|
|
158
|
+
details: { askAnswered: true, answeredBy: answer.answeredBy },
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
if (Date.now() >= deadline) {
|
|
162
|
+
return {
|
|
163
|
+
content: [{ type: "text" as const, text: ASK_FALLBACK_TEXT }],
|
|
164
|
+
details: { askTimedOut: true },
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
await sleep(Math.min(400, Math.max(50, deadline - Date.now())));
|
|
168
|
+
}
|
|
169
|
+
},
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** R17: answer payload written by the parent runner. */
|
|
174
|
+
export interface AskAnswerFile {
|
|
175
|
+
answeredBy: "model" | "user";
|
|
176
|
+
answeredAt: string;
|
|
177
|
+
answer: string;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
export function writeAskAnswerFile(askDir: string, toolCallId: string, payload: AskAnswerFile): void {
|
|
181
|
+
fs.mkdirSync(askDir, { recursive: true, mode: 0o700 });
|
|
182
|
+
fs.writeFileSync(path.join(askDir, `${toolCallId}.json`), JSON.stringify(payload), { mode: 0o600 });
|
|
183
|
+
}
|
package/background.ts
ADDED
|
@@ -0,0 +1,780 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* delegate — background run manager (R8–R13).
|
|
3
|
+
*
|
|
4
|
+
* Pi-free: delivery and ledger writes are injected ports (wired in
|
|
5
|
+
* index.ts), so every behavior here is unit-testable with fakes. The
|
|
6
|
+
* session JSONL is the source of truth for background-run ownership
|
|
7
|
+
* (`delegate.background` custom entries, schema v1); receipts remain the
|
|
8
|
+
* detailed durable record. Semantics ported from pi-async-fork
|
|
9
|
+
* (SPEC §1): serialized at-least-once delivery with branch-scan dedup,
|
|
10
|
+
* generation guard across session replacement, delivery pause across
|
|
11
|
+
* tree switches, and reconcile-on-activation for runs that finished
|
|
12
|
+
* while their owning branch was inactive.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import type {
|
|
16
|
+
BackgroundCreatedEntry,
|
|
17
|
+
BackgroundFinishedEntry,
|
|
18
|
+
BackgroundRunHandle,
|
|
19
|
+
BackgroundRunRecord,
|
|
20
|
+
DelegateError,
|
|
21
|
+
DelegateRunResult,
|
|
22
|
+
RoleName,
|
|
23
|
+
RunMetadataV1,
|
|
24
|
+
RunState,
|
|
25
|
+
RunTerminalState,
|
|
26
|
+
SessionEntryLike,
|
|
27
|
+
} from "./types.ts";
|
|
28
|
+
import { isTerminalRunState } from "./types.ts";
|
|
29
|
+
import { isPidAlive, readRunMetadata } from "./run-store.ts";
|
|
30
|
+
import { CHILD_NOTE_TYPE, CHILD_QUESTION_TYPE } from "./ask.ts";
|
|
31
|
+
export { CHILD_NOTE_TYPE, CHILD_QUESTION_TYPE };
|
|
32
|
+
|
|
33
|
+
/** R11: ledger custom-entry type (session JSONL). */
|
|
34
|
+
export const BACKGROUND_LEDGER_TYPE = "delegate.background";
|
|
35
|
+
/** R10: terminal-result custom-message type. */
|
|
36
|
+
export const BACKGROUND_RESULT_TYPE = "delegate-background-result";
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* R20: derive a valid 3–6-word description from the task's first line when
|
|
40
|
+
* the user launches via `/delegate bg` (which takes no description). Takes
|
|
41
|
+
* the first line, strips edge punctuation, and uses its first words.
|
|
42
|
+
*/
|
|
43
|
+
export function deriveBackgroundDescription(task: string): { ok: true; value: string } | { ok: false; error: string } {
|
|
44
|
+
const firstLine = task.split("\n")[0]?.trim() ?? "";
|
|
45
|
+
const cleaned = firstLine.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g, " ").trim();
|
|
46
|
+
const words = cleaned.split(/\s+/).filter(Boolean).map((w) => w.replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, "")).filter(Boolean);
|
|
47
|
+
if (words.length < 3) {
|
|
48
|
+
return { ok: false, error: "could not derive a 3–6-word description from the task's first line; give a longer task or use the delegate tool with an explicit description." };
|
|
49
|
+
}
|
|
50
|
+
const value = words.slice(0, 6).join(" ");
|
|
51
|
+
return validateBackgroundDescription(value);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** R12: was a terminal result for this run already delivered on the branch? */
|
|
55
|
+
export function wasResultDelivered(branch: readonly SessionEntryLike[], runId: string): boolean {
|
|
56
|
+
return branch.some((entry) => {
|
|
57
|
+
if (entry?.type !== "custom_message") return false;
|
|
58
|
+
if (entry.customType !== BACKGROUND_RESULT_TYPE) return false;
|
|
59
|
+
const details = (entry as { details?: unknown }).details;
|
|
60
|
+
return Boolean(details && typeof details === "object" &&
|
|
61
|
+
(details as { runId?: unknown }).runId === runId);
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function isBackgroundLedgerEntry(data: unknown): data is BackgroundCreatedEntry | BackgroundFinishedEntry {
|
|
66
|
+
if (!data || typeof data !== "object") return false;
|
|
67
|
+
const raw = data as Record<string, unknown>;
|
|
68
|
+
if (raw.v !== 1) return false;
|
|
69
|
+
if (raw.type === "created") {
|
|
70
|
+
return typeof raw.runId === "string"
|
|
71
|
+
&& (raw.role === "general" || raw.role === "research")
|
|
72
|
+
&& typeof raw.description === "string"
|
|
73
|
+
&& typeof raw.createdAt === "string";
|
|
74
|
+
}
|
|
75
|
+
if (raw.type === "finished") {
|
|
76
|
+
return typeof raw.runId === "string" && typeof raw.finishedAt === "string"
|
|
77
|
+
&& typeof raw.state === "string" && isTerminalRunState(raw.state as RunTerminalState);
|
|
78
|
+
}
|
|
79
|
+
return false;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** R11: project the branch root-to-tip into background-run records.
|
|
83
|
+
* Malformed entries are skipped and counted — never fatal. */
|
|
84
|
+
export function projectBackgroundRuns(branch: readonly SessionEntryLike[]): {
|
|
85
|
+
records: Map<string, BackgroundRunRecord>;
|
|
86
|
+
skipped: number;
|
|
87
|
+
} {
|
|
88
|
+
const records = new Map<string, BackgroundRunRecord>();
|
|
89
|
+
let skipped = 0;
|
|
90
|
+
for (const entry of branch) {
|
|
91
|
+
if (entry?.type !== "custom" || entry.customType !== BACKGROUND_LEDGER_TYPE) continue;
|
|
92
|
+
if (!isBackgroundLedgerEntry(entry.data)) {
|
|
93
|
+
skipped += 1;
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
const data = entry.data;
|
|
97
|
+
if (data.type === "created") {
|
|
98
|
+
records.set(data.runId, { created: data });
|
|
99
|
+
} else {
|
|
100
|
+
const existing = records.get(data.runId);
|
|
101
|
+
if (existing && !existing.finished) {
|
|
102
|
+
records.set(data.runId, { ...existing, finished: data });
|
|
103
|
+
} else if (!existing) {
|
|
104
|
+
// finished without created on this branch: unowned, skip
|
|
105
|
+
skipped += 1;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return { records, skipped };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* R8: background `description` validation (pi-async-fork rule, SPEC §1):
|
|
114
|
+
* trimmed outer whitespace, 3–6 whitespace-separated words, single line —
|
|
115
|
+
* C0/C1 controls and U+2028/U+2029 rejected. Returns the normalized value
|
|
116
|
+
* or an error message.
|
|
117
|
+
*/
|
|
118
|
+
export function validateBackgroundDescription(raw: unknown): { ok: true; value: string } | { ok: false; error: string } {
|
|
119
|
+
if (typeof raw !== "string") return { ok: false, error: "description must be a string." };
|
|
120
|
+
const value = raw.trim();
|
|
121
|
+
if (!value) return { ok: false, error: "description is required for background runs." };
|
|
122
|
+
if (/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/.test(value)) {
|
|
123
|
+
return { ok: false, error: "description must be a single line (control characters rejected)." };
|
|
124
|
+
}
|
|
125
|
+
const words = value.split(/\s+/).filter(Boolean);
|
|
126
|
+
if (words.length < 3 || words.length > 6) {
|
|
127
|
+
return { ok: false, error: `description must be 3 to 6 words (got ${words.length}).` };
|
|
128
|
+
}
|
|
129
|
+
return { ok: true, value };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** State word for headers (same mapping as the foreground result header). */
|
|
133
|
+
export function backgroundStateWord(state: RunTerminalState): string {
|
|
134
|
+
if (state === "succeeded") return "completed";
|
|
135
|
+
if (state === "cancelled") return "cancelled";
|
|
136
|
+
if (state.startsWith("timed_out")) return state.replace("_", " ");
|
|
137
|
+
return state;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* R10: the model-visible terminal envelope (SPEC §5, byte-exact).
|
|
142
|
+
* `runText` is the deterministic foreground-style result rendering
|
|
143
|
+
* (formatRunText) reused verbatim.
|
|
144
|
+
*/
|
|
145
|
+
export function formatBackgroundResultEnvelope(
|
|
146
|
+
runId: string,
|
|
147
|
+
role: RoleName,
|
|
148
|
+
description: string,
|
|
149
|
+
state: RunTerminalState,
|
|
150
|
+
runText: string,
|
|
151
|
+
): string {
|
|
152
|
+
return (
|
|
153
|
+
`[delegate background ${runId} · ${role} · ${description}: ${backgroundStateWord(state)}]\n` +
|
|
154
|
+
"\n" +
|
|
155
|
+
"This is the terminal report of a background delegation. The run has finished and\n" +
|
|
156
|
+
"cannot receive steering. Treat it as an internal work event: write user-visible\n" +
|
|
157
|
+
"text only if material, and do not re-narrate the handoff.\n" +
|
|
158
|
+
"\n" +
|
|
159
|
+
runText
|
|
160
|
+
);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** R8: the immediate tool-result content for a background spawn. */
|
|
164
|
+
export function formatBackgroundStartedText(runId: string, role: RoleName, description: string): string {
|
|
165
|
+
return (
|
|
166
|
+
`[delegate background started · ${runId} · ${role} · ${description}]\n` +
|
|
167
|
+
"The run executes outside this turn. Poll it with the delegate_status tool\n" +
|
|
168
|
+
"(delegate_status({ runId: \"" + runId + "\" })). The terminal report arrives as a\n" +
|
|
169
|
+
"message when the run finishes — do not wait inline for it."
|
|
170
|
+
);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** R17: the question envelope (SPEC §5, byte-exact; wakes the parent). */
|
|
174
|
+
export function formatChildQuestionEnvelope(runId: string, role: RoleName, description: string, topic: string, question: string): string {
|
|
175
|
+
return (
|
|
176
|
+
`[delegate background ${runId} · ${role} · ${description}: asks]\n` +
|
|
177
|
+
"\n" +
|
|
178
|
+
`A delegated child is blocked waiting for your answer (topic: ${topic}). Answer\n` +
|
|
179
|
+
`with the delegate_answer tool: delegate_answer({ runId: "${runId}", answer: "…" }).\n` +
|
|
180
|
+
"Be terse and directive; the child resumes the moment your answer lands. Do not\n" +
|
|
181
|
+
"narrate this exchange to the user unless it is material. If you cannot answer,\n" +
|
|
182
|
+
"say so — the child proceeds with its best judgment after the ask budget expires.\n" +
|
|
183
|
+
"\n" +
|
|
184
|
+
question
|
|
185
|
+
);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** R18: the note envelope (SPEC §5, byte-exact; NEVER wakes the parent). */
|
|
189
|
+
export function formatChildNoteEnvelope(runId: string, role: RoleName, description: string, topic: string, note: string): string {
|
|
190
|
+
return (
|
|
191
|
+
`[delegate background ${runId} · ${role} · ${description}: note]\n` +
|
|
192
|
+
"\n" +
|
|
193
|
+
`A delegated child filed a non-blocking note (topic: ${topic}). No answer is\n` +
|
|
194
|
+
"expected or possible. Treat it as an internal work event.\n" +
|
|
195
|
+
"\n" +
|
|
196
|
+
note
|
|
197
|
+
);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** R12: rebuild a DelegateRunResult from a receipt (replay/reconcile path). */
|
|
201
|
+
export function receiptToRunResult(metadata: RunMetadataV1): DelegateRunResult {
|
|
202
|
+
const ok = metadata.state === "succeeded";
|
|
203
|
+
const durationMs = metadata.startedAt && metadata.finishedAt
|
|
204
|
+
? Math.max(0, Date.parse(metadata.finishedAt) - Date.parse(metadata.startedAt))
|
|
205
|
+
: 0;
|
|
206
|
+
return {
|
|
207
|
+
ok,
|
|
208
|
+
handoff: metadata.finalHandoff ?? "",
|
|
209
|
+
details: {
|
|
210
|
+
schemaVersion: 1,
|
|
211
|
+
runId: metadata.runId,
|
|
212
|
+
role: metadata.role,
|
|
213
|
+
state: metadata.state as RunTerminalState,
|
|
214
|
+
startedAt: metadata.startedAt ?? metadata.createdAt,
|
|
215
|
+
finishedAt: metadata.finishedAt ?? metadata.createdAt,
|
|
216
|
+
durationMs,
|
|
217
|
+
model: metadata.model,
|
|
218
|
+
...(metadata.thinkingLevel ? { thinkingLevel: metadata.thinkingLevel } : {}),
|
|
219
|
+
exitCode: metadata.exitCode,
|
|
220
|
+
stopReason: metadata.stopReason,
|
|
221
|
+
usage: metadata.usage,
|
|
222
|
+
outputBytes: metadata.outputBytes ?? 0,
|
|
223
|
+
outputTruncated: metadata.outputTruncated ?? false,
|
|
224
|
+
...(metadata.partialHandoff ? { partialHandoff: metadata.partialHandoff } : {}),
|
|
225
|
+
...(metadata.sessionPath ? { sessionPath: metadata.sessionPath } : {}),
|
|
226
|
+
transcriptPath: metadata.transcriptPath,
|
|
227
|
+
stderrPath: metadata.stderrPath,
|
|
228
|
+
displayItems: [],
|
|
229
|
+
},
|
|
230
|
+
...(metadata.errorCode
|
|
231
|
+
? { error: { code: metadata.errorCode, message: metadata.errorMessage ?? "" } }
|
|
232
|
+
: {}),
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
export interface BackgroundManagerPorts {
|
|
237
|
+
/** pi.sendMessage(message, options) — wired by the adapter. */
|
|
238
|
+
sendMessage(message: {
|
|
239
|
+
customType: string;
|
|
240
|
+
content: string;
|
|
241
|
+
display: true;
|
|
242
|
+
details: Record<string, unknown>;
|
|
243
|
+
}, options: { deliverAs: "steer"; triggerTurn: boolean }): unknown;
|
|
244
|
+
/** pi.appendEntry(customType, data) — wired by the adapter. */
|
|
245
|
+
appendEntry(customType: string, data: unknown): unknown;
|
|
246
|
+
/** Live config accessor (slot limit). */
|
|
247
|
+
maxBackgroundRuns(): number;
|
|
248
|
+
/** Renders a terminal DelegateRunResult to text (formatRunText). */
|
|
249
|
+
formatRun: (res: DelegateRunResult) => string;
|
|
250
|
+
/** Receipt lookup for reconcile (run store). */
|
|
251
|
+
readReceipt(runId: string): RunMetadataV1 | null;
|
|
252
|
+
/** Injected for testability (defaults to run-store isPidAlive). */
|
|
253
|
+
isPidAlive?: (pid: number) => boolean;
|
|
254
|
+
/** R15: optional footer hook — live background count changes. */
|
|
255
|
+
onInventoryChange?: (liveCount: number) => void;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
interface ManagedRun {
|
|
259
|
+
handle: BackgroundRunHandle;
|
|
260
|
+
generation: number;
|
|
261
|
+
/** Set when the owning branch is not the active one (delivery deferred). */
|
|
262
|
+
detached: boolean;
|
|
263
|
+
done: boolean;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* R9/R10/R12/R13: slot accounting, ledger writes, serialized delivery,
|
|
268
|
+
* generation guard, tree pause, reconcile.
|
|
269
|
+
*/
|
|
270
|
+
export class BackgroundManager {
|
|
271
|
+
readonly #ports: BackgroundManagerPorts;
|
|
272
|
+
readonly #runs = new Map<string, ManagedRun>();
|
|
273
|
+
#generation = 0;
|
|
274
|
+
#paused = false;
|
|
275
|
+
#deliveryTail: Promise<void> = Promise.resolve();
|
|
276
|
+
#pendingFlush: Array<() => void> = [];
|
|
277
|
+
/** R17: runId → pending ask (one live question per run). */
|
|
278
|
+
readonly #pendingAsks = new Map<string, { toolCallId: string; topic: string; askedAt: string }>();
|
|
279
|
+
/** runIds with a created entry on the currently active branch. */
|
|
280
|
+
#branchOwned = new Set<string>();
|
|
281
|
+
/** Latest branch snapshot (for dedup scans between refreshes). */
|
|
282
|
+
#branchSnapshot: readonly SessionEntryLike[] = [];
|
|
283
|
+
/** Delivered during this manager lifetime (in-memory dedup supplement). */
|
|
284
|
+
#delivered = new Set<string>();
|
|
285
|
+
readonly #isPidAlive: (pid: number) => boolean;
|
|
286
|
+
|
|
287
|
+
constructor(ports: BackgroundManagerPorts) {
|
|
288
|
+
this.#ports = ports;
|
|
289
|
+
this.#isPidAlive = ports.isPidAlive ?? isPidAlive;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
// ── Slots (R9) ────────────────────────────────────────────────────────
|
|
293
|
+
|
|
294
|
+
private liveCount(): number {
|
|
295
|
+
let n = 0;
|
|
296
|
+
for (const run of this.#runs.values()) if (!run.done) n += 1;
|
|
297
|
+
return n;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** Sync pre-spawn slot check; null = a slot is free. */
|
|
301
|
+
slotError(): DelegateError | null {
|
|
302
|
+
const live = this.liveCount();
|
|
303
|
+
if (live >= this.#ports.maxBackgroundRuns()) {
|
|
304
|
+
return {
|
|
305
|
+
code: "E_BACKGROUND_FULL",
|
|
306
|
+
message: `${live} background runs active (limit ${this.#ports.maxBackgroundRuns()}); wait for terminal reports or check delegate_status.`,
|
|
307
|
+
};
|
|
308
|
+
}
|
|
309
|
+
return null;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
// ── Registration + terminal path (R8/R10/R11) ─────────────────────────
|
|
313
|
+
|
|
314
|
+
/** Register a spawned handle: ledger `created`, completion wiring. */
|
|
315
|
+
register(handle: BackgroundRunHandle): void {
|
|
316
|
+
const generation = this.#generation;
|
|
317
|
+
this.#runs.set(handle.runId, { handle, generation, detached: false, done: false });
|
|
318
|
+
this.#branchOwned.add(handle.runId);
|
|
319
|
+
this.appendLedger({
|
|
320
|
+
v: 1,
|
|
321
|
+
type: "created",
|
|
322
|
+
runId: handle.runId,
|
|
323
|
+
role: handle.role,
|
|
324
|
+
description: handle.description,
|
|
325
|
+
createdAt: new Date().toISOString(),
|
|
326
|
+
});
|
|
327
|
+
void handle.completion.then((result) => {
|
|
328
|
+
this.onTerminal(handle.runId, result);
|
|
329
|
+
});
|
|
330
|
+
this.#ports.onInventoryChange?.(this.liveCount());
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
private onTerminal(runId: string, result: DelegateRunResult): void {
|
|
334
|
+
const run = this.#runs.get(runId);
|
|
335
|
+
if (!run) return; // unknown run: reconcile owns it
|
|
336
|
+
run.done = true;
|
|
337
|
+
this.#ports.onInventoryChange?.(this.liveCount());
|
|
338
|
+
if (run.generation !== this.#generation) return; // stale session: receipt only
|
|
339
|
+
if (!this.#branchOwned.has(runId) || run.detached) {
|
|
340
|
+
// Owning branch inactive: no entry write, no delivery here.
|
|
341
|
+
// R12 reconcile delivers when the branch re-activates.
|
|
342
|
+
return;
|
|
343
|
+
}
|
|
344
|
+
this.finalizeAndDeliver(runId, run.handle.role, run.handle.description, result);
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/** R10/R11: finished entry first, then exactly one result message. */
|
|
348
|
+
private finalizeAndDeliver(runId: string, role: RoleName, description: string, result: DelegateRunResult): void {
|
|
349
|
+
if (this.wasDelivered(runId)) return;
|
|
350
|
+
this.appendLedger({
|
|
351
|
+
v: 1,
|
|
352
|
+
type: "finished",
|
|
353
|
+
runId,
|
|
354
|
+
state: result.details.state,
|
|
355
|
+
finishedAt: result.details.finishedAt,
|
|
356
|
+
});
|
|
357
|
+
this.deliver({
|
|
358
|
+
customType: BACKGROUND_RESULT_TYPE,
|
|
359
|
+
content: formatBackgroundResultEnvelope(
|
|
360
|
+
runId,
|
|
361
|
+
role,
|
|
362
|
+
description,
|
|
363
|
+
result.details.state,
|
|
364
|
+
this.#ports.formatRun(result),
|
|
365
|
+
),
|
|
366
|
+
display: true,
|
|
367
|
+
details: { runId, role, state: result.details.state, description, kind: "result" },
|
|
368
|
+
});
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
// ── Delivery (serialized, pausable; R10/R13) ──────────────────────────
|
|
372
|
+
|
|
373
|
+
private deliver(message: {
|
|
374
|
+
customType: string;
|
|
375
|
+
content: string;
|
|
376
|
+
display: true;
|
|
377
|
+
details: Record<string, unknown>;
|
|
378
|
+
}): void {
|
|
379
|
+
const send = () => {
|
|
380
|
+
this.#deliveryTail = this.#deliveryTail
|
|
381
|
+
.catch(() => undefined)
|
|
382
|
+
.then(() => {
|
|
383
|
+
this.#ports.sendMessage(message, { deliverAs: "steer", triggerTurn: true });
|
|
384
|
+
this.#delivered.add(String(message.details.runId));
|
|
385
|
+
});
|
|
386
|
+
};
|
|
387
|
+
if (this.#paused) this.#pendingFlush.push(send);
|
|
388
|
+
else send();
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
private appendLedger(entry: BackgroundCreatedEntry | BackgroundFinishedEntry): void {
|
|
392
|
+
try {
|
|
393
|
+
this.#ports.appendEntry(BACKGROUND_LEDGER_TYPE, entry);
|
|
394
|
+
} catch {
|
|
395
|
+
// ledger write failure is diagnostic-only; the receipt remains
|
|
396
|
+
// the durable record and reconcile re-derives the state.
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
private wasDelivered(runId: string): boolean {
|
|
401
|
+
return this.#delivered.has(runId) || wasResultDelivered(this.#branchSnapshot, runId);
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
// ── Lifecycle (R12/R13) ───────────────────────────────────────────────
|
|
405
|
+
|
|
406
|
+
/** session_start: new generation, adopt the projected branch. */
|
|
407
|
+
start(branch: readonly SessionEntryLike[]): { resent: string[]; notes: string[] } {
|
|
408
|
+
this.#generation += 1;
|
|
409
|
+
this.#paused = false;
|
|
410
|
+
for (const run of this.#runs.values()) {
|
|
411
|
+
// Runs from a previous session of this process are stale for
|
|
412
|
+
// direct delivery; reconcile re-adopts those the new branch owns.
|
|
413
|
+
run.generation = -1;
|
|
414
|
+
run.detached = true;
|
|
415
|
+
}
|
|
416
|
+
return this.reconcile(branch);
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/** session_before_tree: pause delivery (buffered until afterTree). */
|
|
420
|
+
beforeTree(): void {
|
|
421
|
+
this.#paused = true;
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/** session_tree: re-adopt the new branch, resume delivery. */
|
|
425
|
+
afterTree(branch: readonly SessionEntryLike[]): { resent: string[]; notes: string[] } {
|
|
426
|
+
this.#paused = false;
|
|
427
|
+
const result = this.reconcile(branch);
|
|
428
|
+
const pending = this.#pendingFlush;
|
|
429
|
+
this.#pendingFlush = [];
|
|
430
|
+
for (const flush of pending) flush();
|
|
431
|
+
return result;
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
/** session_shutdown (R13): cancel every live child; no ledger writes. */
|
|
435
|
+
shutdown(): void {
|
|
436
|
+
this.#generation += 1;
|
|
437
|
+
this.#paused = true;
|
|
438
|
+
for (const run of this.#runs.values()) {
|
|
439
|
+
if (!run.done) run.handle.cancel("cancelled");
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
/**
|
|
444
|
+
* R12: rebuild ownership from the branch, deliver undelivered terminals
|
|
445
|
+
* exactly once, report foreign/live runs without touching them.
|
|
446
|
+
*/
|
|
447
|
+
reconcile(branch: readonly SessionEntryLike[]): { resent: string[]; notes: string[] } {
|
|
448
|
+
this.#branchSnapshot = branch;
|
|
449
|
+
const { records, skipped } = projectBackgroundRuns(branch);
|
|
450
|
+
this.#branchOwned = new Set(records.keys());
|
|
451
|
+
const resent: string[] = [];
|
|
452
|
+
const notes: string[] = [];
|
|
453
|
+
if (skipped > 0) notes.push(`${skipped} malformed delegate.background entr${skipped === 1 ? "y" : "ies"} skipped`);
|
|
454
|
+
|
|
455
|
+
for (const [runId, record] of records) {
|
|
456
|
+
const managed = this.#runs.get(runId);
|
|
457
|
+
if (managed && !managed.done) {
|
|
458
|
+
// Live child of this process: re-adopt for the new branch.
|
|
459
|
+
managed.generation = this.#generation;
|
|
460
|
+
managed.detached = false;
|
|
461
|
+
continue;
|
|
462
|
+
}
|
|
463
|
+
if (record.finished) {
|
|
464
|
+
if (!this.wasDelivered(runId)) {
|
|
465
|
+
const receipt = this.#ports.readReceipt(runId);
|
|
466
|
+
if (receipt) {
|
|
467
|
+
this.deliverResultFromReceipt(runId, record, receipt);
|
|
468
|
+
resent.push(runId);
|
|
469
|
+
} else {
|
|
470
|
+
notes.push(`run ${runId}: finished entry but receipt purged; session JSONL is the record`);
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
continue;
|
|
474
|
+
}
|
|
475
|
+
// created, not finished: check the receipt.
|
|
476
|
+
const receipt = this.#ports.readReceipt(runId);
|
|
477
|
+
if (!receipt) {
|
|
478
|
+
notes.push(`run ${runId}: no receipt (purged); nothing to reconcile`);
|
|
479
|
+
continue;
|
|
480
|
+
}
|
|
481
|
+
if (isTerminalRunState(receipt.state)) {
|
|
482
|
+
// Finished while its branch was inactive (or crash between
|
|
483
|
+
// receipt finalization and the ledger write): append the
|
|
484
|
+
// missing finished entry, then deliver once.
|
|
485
|
+
if (!this.wasDelivered(runId)) {
|
|
486
|
+
this.appendLedger({
|
|
487
|
+
v: 1,
|
|
488
|
+
type: "finished",
|
|
489
|
+
runId,
|
|
490
|
+
state: receipt.state,
|
|
491
|
+
finishedAt: receipt.finishedAt ?? new Date().toISOString(),
|
|
492
|
+
});
|
|
493
|
+
this.deliverResultFromReceipt(runId, record, receipt);
|
|
494
|
+
resent.push(runId);
|
|
495
|
+
}
|
|
496
|
+
continue;
|
|
497
|
+
}
|
|
498
|
+
if (typeof receipt.pid === "number" && this.#isPidAlive(receipt.pid)) {
|
|
499
|
+
notes.push(`run ${runId}: nonterminal, owned by another live session (pid ${receipt.pid}) — not touched`);
|
|
500
|
+
continue;
|
|
501
|
+
}
|
|
502
|
+
// Nonterminal, dead pid: children die with the parent process;
|
|
503
|
+
// markOrphanedRuns (startup) finalized the receipt as crashed.
|
|
504
|
+
const refreshed = this.#ports.readReceipt(runId);
|
|
505
|
+
if (refreshed && isTerminalRunState(refreshed.state) && !this.wasDelivered(runId)) {
|
|
506
|
+
this.appendLedger({
|
|
507
|
+
v: 1,
|
|
508
|
+
type: "finished",
|
|
509
|
+
runId,
|
|
510
|
+
state: refreshed.state,
|
|
511
|
+
finishedAt: refreshed.finishedAt ?? new Date().toISOString(),
|
|
512
|
+
});
|
|
513
|
+
this.deliverResultFromReceipt(runId, record, refreshed);
|
|
514
|
+
resent.push(runId);
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
return { resent, notes };
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
private deliverResultFromReceipt(
|
|
521
|
+
runId: string,
|
|
522
|
+
record: BackgroundRunRecord,
|
|
523
|
+
receipt: RunMetadataV1,
|
|
524
|
+
): void {
|
|
525
|
+
const role = record.created.role;
|
|
526
|
+
const description = record.created.description;
|
|
527
|
+
const result = receiptToRunResult(receipt);
|
|
528
|
+
this.deliver({
|
|
529
|
+
customType: BACKGROUND_RESULT_TYPE,
|
|
530
|
+
content: formatBackgroundResultEnvelope(
|
|
531
|
+
runId,
|
|
532
|
+
role,
|
|
533
|
+
description,
|
|
534
|
+
result.details.state,
|
|
535
|
+
this.#ports.formatRun(result),
|
|
536
|
+
),
|
|
537
|
+
display: true,
|
|
538
|
+
details: { runId, role, state: result.details.state, description, kind: "result" },
|
|
539
|
+
});
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
// ── R17/R18: ask channel ─────────────────────────────────────────────
|
|
543
|
+
|
|
544
|
+
/** Fired by the runner hook for every ask_parent start/end (M4). */
|
|
545
|
+
onAsk(ask: {
|
|
546
|
+
runId: string;
|
|
547
|
+
phase: "start" | "end";
|
|
548
|
+
kind: "question" | "note";
|
|
549
|
+
topic: string;
|
|
550
|
+
text: string;
|
|
551
|
+
toolCallId: string;
|
|
552
|
+
}): void {
|
|
553
|
+
const run = this.#runs.get(ask.runId);
|
|
554
|
+
if (!run) return;
|
|
555
|
+
if (run.generation !== this.#generation) return; // stale session: no delivery
|
|
556
|
+
if (ask.phase === "end") {
|
|
557
|
+
const pending = this.#pendingAsks.get(ask.runId);
|
|
558
|
+
if (pending?.toolCallId === ask.toolCallId) this.#pendingAsks.delete(ask.runId);
|
|
559
|
+
return;
|
|
560
|
+
}
|
|
561
|
+
if (ask.kind === "note") {
|
|
562
|
+
this.deliverNote(run, ask);
|
|
563
|
+
return;
|
|
564
|
+
}
|
|
565
|
+
// question: wake the parent (a blocked child is material); register pending.
|
|
566
|
+
const superseded = this.#pendingAsks.get(ask.runId);
|
|
567
|
+
if (superseded) this.#pendingAsks.delete(ask.runId);
|
|
568
|
+
this.#pendingAsks.set(ask.runId, { toolCallId: ask.toolCallId, topic: ask.topic, askedAt: new Date().toISOString() });
|
|
569
|
+
this.enqueueAskMessage({
|
|
570
|
+
customType: CHILD_QUESTION_TYPE,
|
|
571
|
+
content: formatChildQuestionEnvelope(ask.runId, run.handle.role, run.handle.description, ask.topic, ask.text),
|
|
572
|
+
display: true,
|
|
573
|
+
details: { runId: ask.runId, toolCallId: ask.toolCallId, role: run.handle.role, description: run.handle.description, topic: ask.topic, kind: "question" },
|
|
574
|
+
triggerTurn: true,
|
|
575
|
+
});
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
private deliverNote(run: ManagedRun, ask: { topic: string; text: string; toolCallId: string }): void {
|
|
579
|
+
this.enqueueAskMessage({
|
|
580
|
+
customType: CHILD_NOTE_TYPE,
|
|
581
|
+
content: formatChildNoteEnvelope(run.handle.runId, run.handle.role, run.handle.description, ask.topic, ask.text),
|
|
582
|
+
display: true,
|
|
583
|
+
details: { runId: run.handle.runId, role: run.handle.role, description: run.handle.description, topic: ask.topic, kind: "note" },
|
|
584
|
+
triggerTurn: false,
|
|
585
|
+
});
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
/** Notes and questions share the serialized tail; notes never wake. */
|
|
589
|
+
private enqueueAskMessage(message: {
|
|
590
|
+
customType: string;
|
|
591
|
+
content: string;
|
|
592
|
+
display: true;
|
|
593
|
+
details: Record<string, unknown>;
|
|
594
|
+
triggerTurn: boolean;
|
|
595
|
+
}): void {
|
|
596
|
+
const send = () => {
|
|
597
|
+
this.#deliveryTail = this.#deliveryTail.catch(() => undefined).then(() => {
|
|
598
|
+
this.#ports.sendMessage(message, { deliverAs: "steer", triggerTurn: message.triggerTurn });
|
|
599
|
+
});
|
|
600
|
+
};
|
|
601
|
+
if (this.#paused) this.#pendingFlush.push(send);
|
|
602
|
+
else send();
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
/** R17: route a delegate_answer call to the blocked child. */
|
|
606
|
+
answer(runId: string, answerText: string, answeredBy: "model" | "user"): { ok: true } | { ok: false; error: string } {
|
|
607
|
+
const run = this.#runs.get(runId);
|
|
608
|
+
if (!run) {
|
|
609
|
+
return { ok: false, error: `unknown or expired background run ${runId}.` };
|
|
610
|
+
}
|
|
611
|
+
const pending = this.#pendingAsks.get(runId);
|
|
612
|
+
if (!pending) {
|
|
613
|
+
return { ok: false, error: `background run ${runId} has no pending question (it may have timed out or already been answered).` };
|
|
614
|
+
}
|
|
615
|
+
if (!run.handle.writeAnswer) {
|
|
616
|
+
return { ok: false, error: `background run ${runId} does not support answering.` };
|
|
617
|
+
}
|
|
618
|
+
try {
|
|
619
|
+
run.handle.writeAnswer(pending.toolCallId, { answeredBy, answeredAt: new Date().toISOString(), answer: answerText });
|
|
620
|
+
this.#pendingAsks.delete(runId);
|
|
621
|
+
return { ok: true };
|
|
622
|
+
} catch (error) {
|
|
623
|
+
return { ok: false, error: `could not deliver the answer: ${(error as Error).message}` };
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
/** R14/R19: pending questions for status surfaces. */
|
|
628
|
+
pendingQuestions(): Array<{ runId: string; topic: string; askedAt: string }> {
|
|
629
|
+
return [...this.#pendingAsks.entries()].map(([runId, p]) => ({ runId, topic: p.topic, askedAt: p.askedAt }));
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
// ── Introspection (status surface, R14 lands in M2) ───────────────────
|
|
633
|
+
|
|
634
|
+
liveRuns(): Array<{ runId: string; role: RoleName; description: string; detached: boolean }> {
|
|
635
|
+
return [...this.#runs.values()]
|
|
636
|
+
.filter((r) => !r.done)
|
|
637
|
+
.map((r) => ({ runId: r.handle.runId, role: r.handle.role, description: r.handle.description, detached: r.detached }));
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
/** Cancel one background run (user path). */
|
|
641
|
+
cancel(runId: string): boolean {
|
|
642
|
+
const run = this.#runs.get(runId);
|
|
643
|
+
if (!run || run.done) return false;
|
|
644
|
+
run.handle.cancel("cancelled");
|
|
645
|
+
return true;
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
/** R16: steer one live background run (RPC follow_up). */
|
|
649
|
+
send(runId: string, message: string): { ok: true } | { ok: false; error: string } {
|
|
650
|
+
const run = this.#runs.get(runId);
|
|
651
|
+
if (!run) {
|
|
652
|
+
return {
|
|
653
|
+
ok: false,
|
|
654
|
+
error: `unknown or expired background run ${runId}. It is not a live background run of this session (foreground runs cannot be steered — the parent turn is blocked on them; finished runs continue via delegate({ resumeFrom: … })).`,
|
|
655
|
+
};
|
|
656
|
+
}
|
|
657
|
+
if (run.done) {
|
|
658
|
+
return { ok: false, error: `background run ${runId} already finished; continue it with delegate({ resumeFrom: "${runId}", … }) instead.` };
|
|
659
|
+
}
|
|
660
|
+
if (!run.handle.steer) {
|
|
661
|
+
return { ok: false, error: `background run ${runId} does not support steering.` };
|
|
662
|
+
}
|
|
663
|
+
return run.handle.steer(message);
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
// ── R14: status text builders (pure; the adapter feeds data in) ────────
|
|
668
|
+
|
|
669
|
+
export interface BackgroundLiveView {
|
|
670
|
+
runId: string;
|
|
671
|
+
role: RoleName;
|
|
672
|
+
description: string;
|
|
673
|
+
phase?: string;
|
|
674
|
+
elapsedMs?: number;
|
|
675
|
+
openTools?: string[];
|
|
676
|
+
model?: string;
|
|
677
|
+
detached?: boolean;
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
export interface BackgroundRecentView {
|
|
681
|
+
runId: string;
|
|
682
|
+
role: RoleName;
|
|
683
|
+
description?: string;
|
|
684
|
+
state: RunTerminalState;
|
|
685
|
+
durationMs?: number;
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
export function formatBackgroundInventoryText(data: {
|
|
689
|
+
limit: number;
|
|
690
|
+
live: BackgroundLiveView[];
|
|
691
|
+
queue: number;
|
|
692
|
+
recent: BackgroundRecentView[];
|
|
693
|
+
}): string {
|
|
694
|
+
const lines: string[] = [];
|
|
695
|
+
const live = data.live;
|
|
696
|
+
lines.push(`background: ${live.length}/${data.limit} slots active${data.queue > 0 ? ` · queue ${data.queue}` : ""}`);
|
|
697
|
+
for (const r of live) {
|
|
698
|
+
const bits = [r.runId, r.role, r.description];
|
|
699
|
+
if (r.phase) bits.push(r.phase);
|
|
700
|
+
if (r.elapsedMs !== undefined) bits.push(`${Math.round(r.elapsedMs / 1000)}s`);
|
|
701
|
+
if (r.openTools?.length) bits.push(`⏳ ${r.openTools.slice(0, 2).join(",")}`);
|
|
702
|
+
if (r.detached) bits.push("(branch inactive)");
|
|
703
|
+
lines.push(` · ${bits.join(" · ")}`);
|
|
704
|
+
}
|
|
705
|
+
if (live.length === 0) lines.push(" · none");
|
|
706
|
+
for (const r of data.recent.slice(0, 3)) {
|
|
707
|
+
lines.push(` last: ${r.runId} ${r.role} ${backgroundStateWord(r.state)}${r.durationMs != null ? ` in ${Math.round(r.durationMs / 1000)}s` : ""}`);
|
|
708
|
+
}
|
|
709
|
+
return lines.join("\n");
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
export interface BackgroundDetailView {
|
|
713
|
+
runId: string;
|
|
714
|
+
role: RoleName;
|
|
715
|
+
description?: string;
|
|
716
|
+
state: RunState | RunTerminalState;
|
|
717
|
+
model?: string;
|
|
718
|
+
startedAt?: string;
|
|
719
|
+
finishedAt?: string;
|
|
720
|
+
durationMs?: number;
|
|
721
|
+
live?: { phase: string; elapsedMs: number; openTools?: string[] };
|
|
722
|
+
activityTail: string[];
|
|
723
|
+
handoffPreview?: string;
|
|
724
|
+
sessionPath?: string;
|
|
725
|
+
background: boolean;
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
export function formatBackgroundDetailText(d: BackgroundDetailView): string {
|
|
729
|
+
const lines = [`[delegate background ${d.runId}]`];
|
|
730
|
+
const state = isTerminalRunState(d.state as RunTerminalState)
|
|
731
|
+
? backgroundStateWord(d.state as RunTerminalState)
|
|
732
|
+
: String(d.state);
|
|
733
|
+
lines.push(`state: ${state} · role: ${d.role}${d.description ? ` · ${d.description}` : ""}`);
|
|
734
|
+
if (d.model) lines.push(`model: ${d.model}`);
|
|
735
|
+
if (d.live) {
|
|
736
|
+
lines.push(`live: ${d.live.phase} · ${Math.round(d.live.elapsedMs / 1000)}s elapsed${d.live.openTools?.length ? ` · in flight: ${d.live.openTools.join(", ")}` : ""}`);
|
|
737
|
+
} else if (d.durationMs != null) {
|
|
738
|
+
lines.push(`duration: ${Math.round(d.durationMs / 1000)}s${d.finishedAt ? ` · finished ${d.finishedAt}` : ""}`);
|
|
739
|
+
}
|
|
740
|
+
if (d.activityTail.length > 0) {
|
|
741
|
+
lines.push("", "recent activity:");
|
|
742
|
+
for (const a of d.activityTail) lines.push(` ${a}`);
|
|
743
|
+
}
|
|
744
|
+
if (d.handoffPreview) {
|
|
745
|
+
lines.push("", "handoff (first lines):");
|
|
746
|
+
for (const h of d.handoffPreview.split("\n").slice(0, 12)) lines.push(` ${h}`);
|
|
747
|
+
}
|
|
748
|
+
if (isTerminalRunState(d.state as RunTerminalState) && d.state !== "succeeded" && d.sessionPath) {
|
|
749
|
+
lines.push("", `resume: delegate({ resumeFrom: "${d.runId}" }) continues this run's child session.`);
|
|
750
|
+
}
|
|
751
|
+
return lines.join("\n");
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
/** R15: display text for a delivered background result message: neutral
|
|
755
|
+
* glyph header + report body, with the model-only classification paragraph
|
|
756
|
+
* stripped (never shown to the user). */
|
|
757
|
+
export function backgroundResultDisplay(content: string, details: { runId?: string; state?: string; description?: string }): string {
|
|
758
|
+
const parts = content.split("\n\n");
|
|
759
|
+
const body = parts.length > 2 ? parts.slice(2).join("\n\n") : content;
|
|
760
|
+
const state = (details.state ?? "?") as RunTerminalState;
|
|
761
|
+
const word = backgroundStateWord(state);
|
|
762
|
+
const glyph = state === "succeeded" ? "✓" : state === "cancelled" ? "⊘" : state.startsWith("timed_out") ? "⏱" : "⚠";
|
|
763
|
+
const runId = details.runId ?? "?";
|
|
764
|
+
const desc = details.description ? ` · ${details.description}` : "";
|
|
765
|
+
const bodyLines = body.split("\n");
|
|
766
|
+
const head = bodyLines[0] ?? "";
|
|
767
|
+
const shown = [head.split("\n")[0], ...bodyLines.slice(1)].join("\n").split("\n").slice(0, 14).join("\n");
|
|
768
|
+
return `${glyph} background ${runId}${desc}: ${word}\n\n${shown}`;
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
/** Default receipt reader bound to an agentDir (used by the adapter). */
|
|
772
|
+
export function makeReceiptReader(agentDir: string): (runId: string) => RunMetadataV1 | null {
|
|
773
|
+
return (runId) => {
|
|
774
|
+
try {
|
|
775
|
+
return readRunMetadata(agentDir, runId);
|
|
776
|
+
} catch {
|
|
777
|
+
return null;
|
|
778
|
+
}
|
|
779
|
+
};
|
|
780
|
+
}
|
package/commands.ts
CHANGED
|
@@ -19,6 +19,7 @@ export type DelegateIntent =
|
|
|
19
19
|
| { kind: "help" }
|
|
20
20
|
| { kind: "cancel"; runId?: string }
|
|
21
21
|
| { kind: "answer"; runId: string; text: string }
|
|
22
|
+
| { kind: "bg"; role: RoleName; task: string; timeoutMs?: number }
|
|
22
23
|
| { kind: "inspect"; runId?: string }
|
|
23
24
|
| { kind: "resume"; runId?: string; task: string; timeoutMs?: number }
|
|
24
25
|
| { kind: "peek"; runId?: string }
|
|
@@ -53,6 +54,7 @@ export const RESERVED_FIRST_TOKENS = new Set([
|
|
|
53
54
|
"help",
|
|
54
55
|
"cancel",
|
|
55
56
|
"answer",
|
|
57
|
+
"bg",
|
|
56
58
|
"inspect",
|
|
57
59
|
"resume",
|
|
58
60
|
"peek",
|
|
@@ -121,6 +123,21 @@ export function parseDelegateCommand(input: string, options: ParseOptions = {}):
|
|
|
121
123
|
if (!runId || !body) return invalid("resume");
|
|
122
124
|
return { kind: "resume", runId, task: body, timeoutMs };
|
|
123
125
|
}
|
|
126
|
+
case "bg": {
|
|
127
|
+
// R20: user-facing background launch — /delegate bg [general|research] <task>
|
|
128
|
+
const rest = trimmed.slice("bg".length).trim();
|
|
129
|
+
if (!rest) return invalid("bg");
|
|
130
|
+
const { task, timeoutMs } = extractFlags(rest);
|
|
131
|
+
if (!task) return invalid("bg");
|
|
132
|
+
const parts = task.split(/\s+/);
|
|
133
|
+
const roleToken = parts[0]!;
|
|
134
|
+
if (roleToken === "general" || roleToken === "research") {
|
|
135
|
+
const body = parts.slice(1).join(" ").trim();
|
|
136
|
+
if (!body) return invalid("bg");
|
|
137
|
+
return { kind: "bg", role: roleToken, task: body, timeoutMs };
|
|
138
|
+
}
|
|
139
|
+
return { kind: "bg", role: "general", task, timeoutMs };
|
|
140
|
+
}
|
|
124
141
|
case "run": {
|
|
125
142
|
const rest = trimmed.slice("run".length).trim();
|
|
126
143
|
if (!rest) return invalid("run");
|
|
@@ -154,7 +171,7 @@ function invalid(token: string): DelegateIntent {
|
|
|
154
171
|
export function delegateCompletions(prefix: string, recentRunIds: string[] = []): string[] {
|
|
155
172
|
const words = (prefix ?? "").trimStart();
|
|
156
173
|
const tokens = words.split(/\s+/);
|
|
157
|
-
const base: string[] = ["on", "off", "status", "paths", "doctor", "help", "cancel ", "answer ", "inspect ", "resume ", "peek ", "run ", "research "];
|
|
174
|
+
const base: string[] = ["on", "off", "status", "paths", "doctor", "help", "cancel ", "answer ", "bg ", "inspect ", "resume ", "peek ", "run ", "research "];
|
|
158
175
|
|
|
159
176
|
const matches: string[] = [];
|
|
160
177
|
if (tokens.length <= 1) {
|
package/index.ts
CHANGED
|
@@ -49,6 +49,7 @@ import {
|
|
|
49
49
|
BackgroundManager,
|
|
50
50
|
BACKGROUND_RESULT_TYPE,
|
|
51
51
|
backgroundResultDisplay,
|
|
52
|
+
deriveBackgroundDescription,
|
|
52
53
|
formatBackgroundDetailText,
|
|
53
54
|
formatBackgroundInventoryText,
|
|
54
55
|
formatBackgroundStartedText,
|
|
@@ -992,6 +993,36 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
992
993
|
sendHandoffMessage(r);
|
|
993
994
|
};
|
|
994
995
|
|
|
996
|
+
// R20: user-facing background launch — /delegate bg and the dashboard
|
|
997
|
+
// action spawn a background run (description derived from the task's
|
|
998
|
+
// first line) and return immediately; the report arrives later.
|
|
999
|
+
const runCommandBackground = async (task: string, role: "general" | "research", ctx: ExtensionCommandContext, timeoutMs?: number): Promise<void> => {
|
|
1000
|
+
const desc = deriveBackgroundDescription(task);
|
|
1001
|
+
if (!desc.ok) {
|
|
1002
|
+
say(ctx, `[delegate] ${desc.error}`, "error");
|
|
1003
|
+
return;
|
|
1004
|
+
}
|
|
1005
|
+
const slot = background.slotError();
|
|
1006
|
+
if (slot) {
|
|
1007
|
+
say(ctx, `[delegate] ${slot.code}: ${slot.message}`, "warning");
|
|
1008
|
+
return;
|
|
1009
|
+
}
|
|
1010
|
+
const request = buildRequest(task, role, "command", ctx, timeoutMs, {
|
|
1011
|
+
background: true,
|
|
1012
|
+
description: desc.value,
|
|
1013
|
+
});
|
|
1014
|
+
refreshDoctor(ctx);
|
|
1015
|
+
const attempt = app.runBackground(request, {
|
|
1016
|
+
onAsk: (ask) => background.onAsk(ask),
|
|
1017
|
+
});
|
|
1018
|
+
if ("error" in attempt) {
|
|
1019
|
+
say(ctx, formatRunText(attempt.error), "error");
|
|
1020
|
+
return;
|
|
1021
|
+
}
|
|
1022
|
+
background.register(attempt.handle);
|
|
1023
|
+
say(ctx, formatBackgroundStartedText(attempt.handle.runId, attempt.handle.role, attempt.handle.description));
|
|
1024
|
+
};
|
|
1025
|
+
|
|
995
1026
|
const statusText = (ctx: ExtensionContext): string => {
|
|
996
1027
|
const s = app.getStatus(pi.getActiveTools(), ctx.cwd ?? process.cwd());
|
|
997
1028
|
const lines = ["[delegate]", `version: v${delegateVersion()} (loaded at session start; /reload picks up newer installs)`, `mode: ${s.modeEnabled ? "strict" : "normal"}`];
|
|
@@ -1034,6 +1065,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
1034
1065
|
"/delegate status stable status text",
|
|
1035
1066
|
"/delegate run general <task> run a delegation with a role",
|
|
1036
1067
|
"/delegate research <task> research role",
|
|
1068
|
+
"/delegate bg [role] <task> run it in the background (report arrives later)",
|
|
1037
1069
|
"/delegate <task> general-role shorthand",
|
|
1038
1070
|
"/delegate cancel [run-id] cancel the active run",
|
|
1039
1071
|
"/delegate answer <run-id> <text> answer a blocked background child's question",
|
|
@@ -1152,6 +1184,9 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
1152
1184
|
}
|
|
1153
1185
|
await runCommandForeground(intent.task, intent.role, ctx, intent.timeoutMs);
|
|
1154
1186
|
return;
|
|
1187
|
+
case "bg":
|
|
1188
|
+
await runCommandBackground(intent.task, isRoleName(intent.role) ? intent.role : "general", ctx, intent.timeoutMs);
|
|
1189
|
+
return;
|
|
1155
1190
|
case "peek": {
|
|
1156
1191
|
const id = intent.runId?.trim() || app.mostRecentRunId();
|
|
1157
1192
|
if (!id) {
|
|
@@ -1367,6 +1402,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
1367
1402
|
rows: [
|
|
1368
1403
|
{ key: "run-general", label: "Run general task…", value: "", kind: "action" },
|
|
1369
1404
|
{ key: "run-research", label: "Run research task…", value: "", kind: "action" },
|
|
1405
|
+
{ key: "run-background", label: "Run background task…", value: "", kind: "action" },
|
|
1370
1406
|
{ key: "peek", label: "Peek live / final detail", value: "", kind: "action", disabled: !active && !last },
|
|
1371
1407
|
{ key: "cancel", label: "Cancel active run", value: "", kind: "action", disabled: !active },
|
|
1372
1408
|
{ key: "resume", label: "Resume last run…", value: "", kind: "action", disabled: !last },
|
|
@@ -1458,6 +1494,13 @@ export default function delegateExtension(pi: ExtensionAPI) {
|
|
|
1458
1494
|
await runCommandForeground(task, role, ctx);
|
|
1459
1495
|
continue;
|
|
1460
1496
|
}
|
|
1497
|
+
// R20: user-facing background launch — spawn, return immediately.
|
|
1498
|
+
if (action === "run-background") {
|
|
1499
|
+
const task = await ctx.ui.editor("Background task (returns immediately)", "");
|
|
1500
|
+
if (!task || !task.trim()) continue;
|
|
1501
|
+
await runCommandBackground(task.trim(), "general", ctx);
|
|
1502
|
+
continue;
|
|
1503
|
+
}
|
|
1461
1504
|
if (action === "peek") {
|
|
1462
1505
|
await openPeek(ctx);
|
|
1463
1506
|
continue;
|
package/package.json
CHANGED
|
@@ -1,71 +1,73 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
2
|
+
"name": "@maheidem/pi-delegate",
|
|
3
|
+
"version": "0.6.2",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Foreground isolated delegation and strict coordinator mode for the Pi coding agent.",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"author": "maheidem",
|
|
8
|
+
"keywords": [
|
|
9
|
+
"pi",
|
|
10
|
+
"pi-coding-agent",
|
|
11
|
+
"pi-extension",
|
|
12
|
+
"delegate",
|
|
13
|
+
"subagent",
|
|
14
|
+
"orchestration",
|
|
15
|
+
"coordinator"
|
|
16
|
+
],
|
|
17
|
+
"repository": {
|
|
18
|
+
"type": "git",
|
|
19
|
+
"url": "git+https://github.com/Maheidem/pi-delegate.git"
|
|
20
|
+
},
|
|
21
|
+
"bugs": {
|
|
22
|
+
"url": "https://github.com/Maheidem/pi-delegate/issues"
|
|
23
|
+
},
|
|
24
|
+
"homepage": "https://github.com/Maheidem/pi-delegate#readme",
|
|
25
|
+
"publishConfig": {
|
|
26
|
+
"access": "public"
|
|
27
|
+
},
|
|
28
|
+
"files": [
|
|
29
|
+
"index.ts",
|
|
30
|
+
"application.ts",
|
|
31
|
+
"background.ts",
|
|
32
|
+
"ask.ts",
|
|
33
|
+
"commands.ts",
|
|
34
|
+
"config.ts",
|
|
35
|
+
"mode.ts",
|
|
36
|
+
"roles.ts",
|
|
37
|
+
"runner.ts",
|
|
38
|
+
"rpc-jsonl.ts",
|
|
39
|
+
"run-store.ts",
|
|
40
|
+
"types.ts",
|
|
41
|
+
"version.ts",
|
|
42
|
+
"handoff.ts",
|
|
43
|
+
"transcript-feed.ts",
|
|
44
|
+
"roles/",
|
|
45
|
+
"ui/",
|
|
46
|
+
"README.md",
|
|
47
|
+
"LICENSE"
|
|
48
|
+
],
|
|
49
|
+
"scripts": {
|
|
50
|
+
"typecheck": "tsc -p tsconfig.json",
|
|
51
|
+
"test": "node tests/run.mjs",
|
|
52
|
+
"test:unit": "node tests/run.mjs",
|
|
53
|
+
"test:e2e": "node tests/e2e.mjs",
|
|
54
|
+
"prepack": "npm run typecheck && npm test"
|
|
55
|
+
},
|
|
56
|
+
"peerDependencies": {
|
|
57
|
+
"@earendil-works/pi-coding-agent": ">=0.84.4",
|
|
58
|
+
"@earendil-works/pi-tui": "*",
|
|
59
|
+
"typebox": "*"
|
|
60
|
+
},
|
|
61
|
+
"devDependencies": {
|
|
62
|
+
"@earendil-works/pi-coding-agent": "^0.84.4",
|
|
63
|
+
"@earendil-works/pi-tui": "^0.84.4",
|
|
64
|
+
"@types/node": "^22.0.0",
|
|
65
|
+
"typebox": "^1.0.17",
|
|
66
|
+
"typescript": "^5.9.3"
|
|
67
|
+
},
|
|
68
|
+
"pi": {
|
|
69
|
+
"extensions": [
|
|
70
|
+
"./index.ts"
|
|
71
|
+
]
|
|
72
|
+
}
|
|
73
|
+
}
|