@maheidem/pi-delegate 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +32 -0
- package/README.md +86 -0
- package/application.ts +507 -0
- package/commands.ts +159 -0
- package/config.ts +216 -0
- package/index.ts +669 -0
- package/mode.ts +327 -0
- package/package.json +68 -0
- package/roles/general.md +41 -0
- package/roles/research.md +46 -0
- package/roles.ts +93 -0
- package/rpc-jsonl.ts +172 -0
- package/run-store.ts +326 -0
- package/runner.ts +771 -0
- package/types.ts +365 -0
- package/ui/running-view.ts +85 -0
- package/ui/settings-panel.ts +393 -0
package/index.ts
ADDED
|
@@ -0,0 +1,669 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* delegate — Pi adapter (the ONLY file that imports Pi).
|
|
3
|
+
*
|
|
4
|
+
* Wiring order (§11.1):
|
|
5
|
+
* 1. inert in children (PI_DELEGATE_CHILD=1)
|
|
6
|
+
* 2. construct config/store/roles/application (no child, no timers)
|
|
7
|
+
* 3. register the `delegate` tool
|
|
8
|
+
* 4. register `/delegate` + completion
|
|
9
|
+
* 5. register the `delegate-handoff` renderer
|
|
10
|
+
* 6. register the strict `tool_call` gate (same factory as the tool)
|
|
11
|
+
* 7. lifecycle: session_start / session_tree / before_agent_start /
|
|
12
|
+
* turn_start / session_shutdown
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { Type } from "typebox";
|
|
16
|
+
import {
|
|
17
|
+
getAgentDir,
|
|
18
|
+
type ExtensionAPI,
|
|
19
|
+
type ExtensionCommandContext,
|
|
20
|
+
type ExtensionContext,
|
|
21
|
+
} from "@earendil-works/pi-coding-agent";
|
|
22
|
+
import { Text } from "@earendil-works/pi-tui";
|
|
23
|
+
|
|
24
|
+
import { loadConfig, saveConfig } from "./config.ts";
|
|
25
|
+
import { parseDelegateCommand, delegateCompletions, type DelegateIntent } from "./commands.ts";
|
|
26
|
+
import { DELEGATE_ROLES, isRoleName, resolveRole } from "./roles.ts";
|
|
27
|
+
import { STRICT_OVERLAY, syncStrictToolSet, resetBlockedCounters } from "./mode.ts";
|
|
28
|
+
import { DelegateApplicationImpl } from "./application.ts";
|
|
29
|
+
import { DELEGATE_MODE_CUSTOM_TYPE } from "./types.ts";
|
|
30
|
+
import type {
|
|
31
|
+
DelegateDetails,
|
|
32
|
+
DelegateRequest,
|
|
33
|
+
DelegateRunResult,
|
|
34
|
+
RunAttemptResult,
|
|
35
|
+
RunStreamUpdate,
|
|
36
|
+
SessionEntryLike,
|
|
37
|
+
} from "./types.ts";
|
|
38
|
+
import { SettingsPanel, type PanelSnapshot, type PanelActionResult } from "./ui/settings-panel.ts";
|
|
39
|
+
import { RunningView, type RunningViewState } from "./ui/running-view.ts";
|
|
40
|
+
|
|
41
|
+
/** Stable command-driven handoff custom message type (§6.4). */
|
|
42
|
+
const HANDOFF_CUSTOM_TYPE = "delegate-handoff";
|
|
43
|
+
|
|
44
|
+
export default function delegateExtension(pi: ExtensionAPI) {
|
|
45
|
+
// 1. The child never reactivates this extension (POL: no recursion).
|
|
46
|
+
if (process.env.PI_DELEGATE_CHILD === "1") return;
|
|
47
|
+
// 2. Construct state — no child, no timers at load time.
|
|
48
|
+
// PI_DELEGATE_AGENT_DIR is a test override; production uses getAgentDir().
|
|
49
|
+
const agentDir = process.env.PI_DELEGATE_AGENT_DIR || getAgentDir();
|
|
50
|
+
const { config, unknownKeys, recoveredFromCorrupt, corruptEvidencePath } = loadConfig(agentDir);
|
|
51
|
+
const app = new DelegateApplicationImpl({ agentDir, config });
|
|
52
|
+
// Startup orphan recovery (§10.6): receipts only; never kills PIDs.
|
|
53
|
+
app.markOrphansOnStartup();
|
|
54
|
+
|
|
55
|
+
const say = (ctx: { hasUI: boolean; ui: { notify(message: string, level?: "info" | "warning" | "error"): void } }, text: string, level: "info" | "warning" | "error" = "info") => {
|
|
56
|
+
// Essential output uses stdout (§6.1); notify is supplemental only.
|
|
57
|
+
// In headless RPC, console.log is captured by the host — surface the
|
|
58
|
+
// full text on the message channel so clients can observe it.
|
|
59
|
+
console.log(text);
|
|
60
|
+
// notify is protocol-visible (TUI toast + RPC extension_ui_request).
|
|
61
|
+
try {
|
|
62
|
+
ctx.ui.notify(text, level);
|
|
63
|
+
} catch {
|
|
64
|
+
// ignore
|
|
65
|
+
}
|
|
66
|
+
if (!ctx.hasUI) {
|
|
67
|
+
try {
|
|
68
|
+
pi.sendMessage(
|
|
69
|
+
{ customType: "delegate-message", content: text, display: true, details: {} },
|
|
70
|
+
{ triggerTurn: false },
|
|
71
|
+
);
|
|
72
|
+
} catch {
|
|
73
|
+
// last resort: nothing else available
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
const lastLine = (text: string): string => text.split("\n").filter(Boolean).pop() ?? text;
|
|
78
|
+
|
|
79
|
+
const modelString = (ctx: ExtensionContext): string => {
|
|
80
|
+
const m = ctx.model as { provider?: string; id?: string } | undefined;
|
|
81
|
+
if (!m?.provider || !m.id) return "";
|
|
82
|
+
return `${m.provider}/${m.id}`;
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
const thinkingOf = (ctx: ExtensionContext): string | undefined => {
|
|
86
|
+
try {
|
|
87
|
+
return (ctx as unknown as { thinkingLevel?: string }).thinkingLevel ?? pi.getThinkingLevel() ?? undefined;
|
|
88
|
+
} catch {
|
|
89
|
+
return undefined;
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
const buildRequest = (task: string, role: "general" | "research", source: "tool" | "command", ctx: ExtensionContext): DelegateRequest => ({
|
|
94
|
+
task,
|
|
95
|
+
role,
|
|
96
|
+
source,
|
|
97
|
+
cwd: ctx.cwd ?? process.cwd(),
|
|
98
|
+
parentModel: modelString(ctx),
|
|
99
|
+
thinkingLevel: thinkingOf(ctx),
|
|
100
|
+
projectTrusted: ctx.isProjectTrusted(),
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
const refreshDoctor = (ctx: ExtensionContext) => {
|
|
104
|
+
try {
|
|
105
|
+
app.refreshDoctorContext({
|
|
106
|
+
model: modelString(ctx) || undefined,
|
|
107
|
+
activeTools: pi.getActiveTools(),
|
|
108
|
+
registeredTools: pi.getAllTools().map((t: { name: string }) => t.name),
|
|
109
|
+
});
|
|
110
|
+
} catch {
|
|
111
|
+
// doctor context is best-effort
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
// ── Mode transition context ─────────────────────────────────────────────
|
|
116
|
+
|
|
117
|
+
const modeCtx = (ctx: ExtensionCommandContext) => ({
|
|
118
|
+
isBusy: () => !ctx.isIdle(),
|
|
119
|
+
requestAbortConfirmation: async (): Promise<boolean> => {
|
|
120
|
+
if (!ctx.hasUI) return false; // headless fails E_PARENT_BUSY (§8.4)
|
|
121
|
+
return ctx.ui.confirm(
|
|
122
|
+
"Enable strict delegation mode?",
|
|
123
|
+
"The parent turn is running. Abort it now and switch the parent to coordinator-only?",
|
|
124
|
+
);
|
|
125
|
+
},
|
|
126
|
+
abort: () => {
|
|
127
|
+
try {
|
|
128
|
+
ctx.abort();
|
|
129
|
+
} catch {
|
|
130
|
+
// ignore
|
|
131
|
+
}
|
|
132
|
+
},
|
|
133
|
+
waitForIdle: async () => {
|
|
134
|
+
const deadline = Date.now() + 20_000;
|
|
135
|
+
while (!ctx.isIdle() && Date.now() < deadline) {
|
|
136
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
137
|
+
}
|
|
138
|
+
if (!ctx.isIdle()) throw new Error("parent did not reach idle");
|
|
139
|
+
},
|
|
140
|
+
getActiveTools: () => pi.getActiveTools(),
|
|
141
|
+
setActiveTools: (names: string[]) => pi.setActiveTools(names),
|
|
142
|
+
persistModeEntry: (entry: { schemaVersion: 1; enabled: boolean; changedAt: string; source: "command" }) => {
|
|
143
|
+
pi.appendEntry(DELEGATE_MODE_CUSTOM_TYPE, entry);
|
|
144
|
+
},
|
|
145
|
+
setFooterStatus: (text: string | undefined) => ctx.ui.setStatus("delegate", text),
|
|
146
|
+
notify: (message: string, level: "info" | "warning" | "error") => ctx.ui.notify(message, level),
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
// ── Result rendering helpers ────────────────────────────────────────────
|
|
150
|
+
|
|
151
|
+
const formatRunText = (res: DelegateRunResult): string => {
|
|
152
|
+
const d = res.details;
|
|
153
|
+
const stateLabel =
|
|
154
|
+
d.state === "succeeded" ? "completed"
|
|
155
|
+
: d.state === "cancelled" ? "cancelled"
|
|
156
|
+
: d.state.startsWith("timed_out") ? d.state.replace("_", " ")
|
|
157
|
+
: d.state;
|
|
158
|
+
const secs = Math.round(d.durationMs / 1000);
|
|
159
|
+
const head = `[delegate ${d.runId} · ${d.role} · ${stateLabel} in ${secs}s]`;
|
|
160
|
+
if (!res.ok) {
|
|
161
|
+
const err = res.error ? `${res.error.code}: ${res.error.message}` : "unknown failure";
|
|
162
|
+
return `${head}\nerror: ${err}\ntranscript: ${d.transcriptPath}`;
|
|
163
|
+
}
|
|
164
|
+
const parts = [head, "", res.handoff];
|
|
165
|
+
if (d.outputTruncated || d.stderrPath) {
|
|
166
|
+
parts.push("", `[Full transcript: ${d.transcriptPath}]`);
|
|
167
|
+
}
|
|
168
|
+
return parts.join("\n");
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
const usageField = (res: DelegateRunResult) => {
|
|
172
|
+
const u = res.details.usage;
|
|
173
|
+
return {
|
|
174
|
+
input: u.input,
|
|
175
|
+
output: u.output,
|
|
176
|
+
cacheRead: u.cacheRead,
|
|
177
|
+
cacheWrite: u.cacheWrite,
|
|
178
|
+
totalTokens: u.contextTokens || u.input + u.output + u.cacheRead + u.cacheWrite,
|
|
179
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: u.cost },
|
|
180
|
+
};
|
|
181
|
+
};
|
|
182
|
+
|
|
183
|
+
// ── 3. Model tool ───────────────────────────────────────────────────────
|
|
184
|
+
|
|
185
|
+
const DelegateParams = Type.Object({
|
|
186
|
+
task: Type.String({ minLength: 1 }),
|
|
187
|
+
role: Type.Optional(Type.Union([Type.Literal("general"), Type.Literal("research")])),
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
pi.registerTool({
|
|
191
|
+
name: "delegate",
|
|
192
|
+
label: "Delegate",
|
|
193
|
+
description:
|
|
194
|
+
"Delegate a self-contained subtask to an isolated child Pi session with a bounded final handoff. " +
|
|
195
|
+
"Roles: general (implementation, write-capable) and research (read-only web research via Firecrawl, optionally supplemented by Reddit). " +
|
|
196
|
+
"The child does not see parent history; include all objective, relevant paths, constraints, and acceptance criteria in the task.",
|
|
197
|
+
promptSnippet: "Delegate a bounded subtask (implementation or research) to an isolated child session",
|
|
198
|
+
promptGuidelines: [
|
|
199
|
+
"Use delegate autonomously when a bounded subtask would consume substantial parent context, benefits from a specialist tool ceiling, or needs independent verification.",
|
|
200
|
+
"Pass the objective, relevant paths, constraints, and acceptance criteria in the delegate task text; the child cannot see parent history.",
|
|
201
|
+
"Do not use delegate for trivial one-step work, or when most of the parent history would have to be copied into the task.",
|
|
202
|
+
"While delegation mode is active, all substantive work and verification must use delegate; the parent is coordination-only.",
|
|
203
|
+
],
|
|
204
|
+
parameters: DelegateParams,
|
|
205
|
+
async execute(_toolCallId, params, signal, onUpdate, ctx) {
|
|
206
|
+
// Strict mode invariant also holds here: only delegate runs anyway.
|
|
207
|
+
const request = buildRequest(params.task, params.role ?? config.defaultRole, "tool", ctx);
|
|
208
|
+
refreshDoctor(ctx);
|
|
209
|
+
const hooks = {
|
|
210
|
+
abortSignal: signal ?? undefined,
|
|
211
|
+
onUpdate: (u: RunStreamUpdate) => {
|
|
212
|
+
onUpdate?.({
|
|
213
|
+
content: [{ type: "text", text: `[delegate ${u.runId} · ${u.role} · ${u.phase} · ${Math.round(u.elapsedMs / 1000)}s]` }],
|
|
214
|
+
details: { runId: u.runId, phase: u.phase },
|
|
215
|
+
});
|
|
216
|
+
},
|
|
217
|
+
};
|
|
218
|
+
const attempt = await app.run(request, hooks);
|
|
219
|
+
if ("busy" in attempt && attempt.busy) {
|
|
220
|
+
return {
|
|
221
|
+
content: [{ type: "text" as const, text: attempt.error.message }],
|
|
222
|
+
details: { busy: true, runId: attempt.runId, role: attempt.role } satisfies Record<string, unknown>,
|
|
223
|
+
isError: true,
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
const res = attempt as DelegateRunResult;
|
|
227
|
+
return {
|
|
228
|
+
content: [{ type: "text" as const, text: formatRunText(res) }],
|
|
229
|
+
details: res.details satisfies DelegateDetails,
|
|
230
|
+
...(res.ok ? {} : { isError: true }),
|
|
231
|
+
usage: usageField(res),
|
|
232
|
+
};
|
|
233
|
+
},
|
|
234
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
235
|
+
renderCall(args: any, theme: any) {
|
|
236
|
+
const role = typeof args.role === "string" ? args.role : config.defaultRole;
|
|
237
|
+
const task = typeof args.task === "string" ? args.task : "";
|
|
238
|
+
const text = `delegate(${role}): ${task.length > 70 ? `${task.slice(0, 67)}…` : task}`;
|
|
239
|
+
return new Text(theme?.fg ? theme.fg("accent", text) : text, 0, 0);
|
|
240
|
+
},
|
|
241
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
242
|
+
renderResult(result: any, _options: any, theme: any) {
|
|
243
|
+
const d = result.details as { runId?: string; role?: string; state?: string; usage?: { input?: number; output?: number; cost?: number }; outputTruncated?: boolean; transcriptPath?: string } | undefined;
|
|
244
|
+
if (!d?.runId) {
|
|
245
|
+
const text = (result.content ?? []).map((c: { text?: string }) => c.text ?? "").filter(Boolean).join("\n");
|
|
246
|
+
return new Text(text || "(no output)", 0, 0);
|
|
247
|
+
}
|
|
248
|
+
const u = d.usage ?? {};
|
|
249
|
+
const bits: string[] = [`${d.role ?? "?"} · ${d.state ?? "?"}`];
|
|
250
|
+
if (u.input) bits.push(`↑${u.input}`);
|
|
251
|
+
if (u.output) bits.push(`↓${u.output}`);
|
|
252
|
+
if (u.cost) bits.push(`$${u.cost.toFixed(4)}`);
|
|
253
|
+
const header = `→ ${d.runId}`;
|
|
254
|
+
const body = bits.join(" ") + (d.outputTruncated && d.transcriptPath ? `\ntranscript: ${d.transcriptPath}` : "");
|
|
255
|
+
return new Text(theme?.fg ? `${theme.fg("accent", header)}\n${body}` : `${header}\n${body}`, 0, 0);
|
|
256
|
+
},
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
// ── Handoff custom message renderer (§6.4) ─────────────────────────────
|
|
260
|
+
|
|
261
|
+
pi.registerMessageRenderer(HANDOFF_CUSTOM_TYPE, (message: { content?: string | unknown[]; details?: unknown }) => {
|
|
262
|
+
const d = (message.details ?? {}) as { runId?: string; role?: string; state?: string };
|
|
263
|
+
const raw = message.content;
|
|
264
|
+
const text =
|
|
265
|
+
typeof raw === "string" ? raw
|
|
266
|
+
: Array.isArray(raw) ? raw.map((b) => (b as { text?: string })?.text ?? "").join("\n")
|
|
267
|
+
: "";
|
|
268
|
+
return new Text(`[delegate ${d.runId ?? "?"} · ${d.role ?? "?"} · ${d.state ?? "?"}]\n\n${text}`, 0, 0);
|
|
269
|
+
});
|
|
270
|
+
|
|
271
|
+
// ── Command execution ───────────────────────────────────────────────────
|
|
272
|
+
|
|
273
|
+
const sendHandoffMessage = (res: DelegateRunResult) => {
|
|
274
|
+
// Command-run handoff: display only, never triggers a parent turn.
|
|
275
|
+
try {
|
|
276
|
+
pi.sendMessage(
|
|
277
|
+
{
|
|
278
|
+
customType: HANDOFF_CUSTOM_TYPE,
|
|
279
|
+
content: res.handoff || res.error?.message || "",
|
|
280
|
+
display: true,
|
|
281
|
+
details: { runId: res.details.runId, role: res.details.role, state: res.details.state },
|
|
282
|
+
},
|
|
283
|
+
{ triggerTurn: false },
|
|
284
|
+
);
|
|
285
|
+
} catch {
|
|
286
|
+
// headless modes simply console.log the same text
|
|
287
|
+
}
|
|
288
|
+
};
|
|
289
|
+
|
|
290
|
+
const runCommandForeground = async (task: string, role: "general" | "research", ctx: ExtensionCommandContext): Promise<void> => {
|
|
291
|
+
const request = buildRequest(task, role, "command", ctx);
|
|
292
|
+
refreshDoctor(ctx);
|
|
293
|
+
let lastText = `[delegate] starting ${role} run…`;
|
|
294
|
+
const hooks = {
|
|
295
|
+
onUpdate: (u: RunStreamUpdate) => {
|
|
296
|
+
lastText = `[delegate ${u.runId} · ${u.role} · ${u.phase} · ${Math.round(u.elapsedMs / 1000)}s] ${u.lastActions.slice(-1)[0] ?? ""}`.trim();
|
|
297
|
+
},
|
|
298
|
+
};
|
|
299
|
+
if (ctx.mode === "tui") {
|
|
300
|
+
let res: RunAttemptResult | undefined;
|
|
301
|
+
const viewState: RunningViewState = {
|
|
302
|
+
runId: "",
|
|
303
|
+
role: request.role,
|
|
304
|
+
phase: "starting",
|
|
305
|
+
elapsedMs: 0,
|
|
306
|
+
lastActions: [],
|
|
307
|
+
};
|
|
308
|
+
const runPromise = app.run(request, {
|
|
309
|
+
...hooks,
|
|
310
|
+
onUpdate: (u: RunStreamUpdate) => {
|
|
311
|
+
hooks.onUpdate?.(u);
|
|
312
|
+
viewState.runId = u.runId;
|
|
313
|
+
viewState.role = u.role;
|
|
314
|
+
viewState.phase = u.phase;
|
|
315
|
+
viewState.elapsedMs = u.elapsedMs;
|
|
316
|
+
viewState.lastActions = u.lastActions;
|
|
317
|
+
},
|
|
318
|
+
});
|
|
319
|
+
const outcome = await ctx.ui.custom<{ cancelled?: boolean } | undefined>(
|
|
320
|
+
(tui, theme, keybindings, done) =>
|
|
321
|
+
new RunningView({
|
|
322
|
+
theme,
|
|
323
|
+
keybindings,
|
|
324
|
+
state: () => viewState,
|
|
325
|
+
done,
|
|
326
|
+
}),
|
|
327
|
+
);
|
|
328
|
+
if (outcome?.cancelled) {
|
|
329
|
+
await app.cancel();
|
|
330
|
+
say(ctx, `[delegate] cancellation requested; the run finalizes with its terminal receipt.`);
|
|
331
|
+
// Let the run settle so its receipt finalizes (bounded wait).
|
|
332
|
+
try {
|
|
333
|
+
const bounded = await Promise.race([
|
|
334
|
+
runPromise,
|
|
335
|
+
new Promise<null>((r) => setTimeout(() => r(null), (config.killGraceMs ?? 5000) + 6000)),
|
|
336
|
+
]);
|
|
337
|
+
if (bounded) res = bounded;
|
|
338
|
+
} catch {
|
|
339
|
+
// ignore
|
|
340
|
+
}
|
|
341
|
+
} else {
|
|
342
|
+
res = await runPromise;
|
|
343
|
+
}
|
|
344
|
+
if (res && !("busy" in res && res.busy)) {
|
|
345
|
+
const r = res as DelegateRunResult;
|
|
346
|
+
say(ctx, formatRunText(r));
|
|
347
|
+
sendHandoffMessage(r);
|
|
348
|
+
} else if (res && "busy" in res) {
|
|
349
|
+
say(ctx, `[delegate] busy — active run ${res.runId} (${res.role}). Use /delegate cancel.`, "warning");
|
|
350
|
+
}
|
|
351
|
+
return;
|
|
352
|
+
}
|
|
353
|
+
const res = await app.run(request, hooks);
|
|
354
|
+
if ("busy" in res && res.busy) {
|
|
355
|
+
say(ctx, `[delegate] busy — active run ${res.runId} (${res.role}). Use /delegate cancel.`, "warning");
|
|
356
|
+
return;
|
|
357
|
+
}
|
|
358
|
+
const r = res as DelegateRunResult;
|
|
359
|
+
say(ctx, formatRunText(r));
|
|
360
|
+
sendHandoffMessage(r);
|
|
361
|
+
};
|
|
362
|
+
|
|
363
|
+
const statusText = (ctx: ExtensionContext): string => {
|
|
364
|
+
const s = app.getStatus(pi.getActiveTools());
|
|
365
|
+
const lines = ["[delegate]", `mode: ${s.modeEnabled ? "strict" : "normal"}`];
|
|
366
|
+
lines.push(`parent tools: ${s.modeEnabled ? "delegate only" : "normal active set"}`);
|
|
367
|
+
lines.push(`active run: ${s.activeRun ? `${s.activeRun.runId} (${s.activeRun.role})` : "none"}`);
|
|
368
|
+
if (s.lastRun) {
|
|
369
|
+
const dur = s.lastRun.durationMs != null ? `${Math.round(s.lastRun.durationMs / 1000)}s` : "";
|
|
370
|
+
lines.push(`last run: ${s.lastRun.runId} ${s.lastRun.role} ${s.lastRun.state} ${dur}`.trimEnd());
|
|
371
|
+
} else {
|
|
372
|
+
lines.push("last run: none");
|
|
373
|
+
}
|
|
374
|
+
lines.push(`default role: ${s.defaultRole}`);
|
|
375
|
+
lines.push(`store: ${s.store.runsDir}`);
|
|
376
|
+
if (app.getModeRuntime().persistenceDegraded) lines.push("warning: mode persistence is degraded");
|
|
377
|
+
if (!s.modeEnabled) {
|
|
378
|
+
const registered = pi.getAllTools().map((t: { name: string }) => t.name);
|
|
379
|
+
if (!registered.includes("delegate")) lines.push("warning: delegate tool is not registered");
|
|
380
|
+
}
|
|
381
|
+
void ctx;
|
|
382
|
+
return lines.join("\n");
|
|
383
|
+
};
|
|
384
|
+
|
|
385
|
+
const helpText = (): string =>
|
|
386
|
+
[
|
|
387
|
+
"/delegate dashboard (TUI) / status (headless)",
|
|
388
|
+
"/delegate on | off strict delegation mode (session/branch scoped)",
|
|
389
|
+
"/delegate status stable status text",
|
|
390
|
+
"/delegate run general <task> run a delegation with a role",
|
|
391
|
+
"/delegate research <task> research role",
|
|
392
|
+
"/delegate <task> general-role shorthand",
|
|
393
|
+
"/delegate cancel [run-id] cancel the active run",
|
|
394
|
+
"/delegate inspect [run-id] inspect a run (default: recent/active)",
|
|
395
|
+
"/delegate paths config + run store paths",
|
|
396
|
+
"/delegate doctor diagnostics",
|
|
397
|
+
"/delegate help this help",
|
|
398
|
+
].join("\n");
|
|
399
|
+
|
|
400
|
+
const doctorText = (): string => {
|
|
401
|
+
const report = app.doctor();
|
|
402
|
+
const lines = [`[delegate doctor] ${report.ok ? "OK" : "ISSUES FOUND"}`];
|
|
403
|
+
for (const c of report.checks) lines.push(` ${c.status === "ok" ? "✓" : c.status === "warning" ? "!" : "✗"} ${c.name}: ${c.detail}`);
|
|
404
|
+
return lines.join("\n");
|
|
405
|
+
};
|
|
406
|
+
|
|
407
|
+
const inspectText = (runId?: string): string => {
|
|
408
|
+
try {
|
|
409
|
+
const { metadata: m } = app.inspect(runId, false);
|
|
410
|
+
const lines = [
|
|
411
|
+
`[delegate inspect] ${m.runId}`,
|
|
412
|
+
`state: ${m.state} · role: ${m.role} · source: ${m.source}`,
|
|
413
|
+
`model: ${m.model}${m.thinkingLevel ? ` · thinking: ${m.thinkingLevel}` : ""}`,
|
|
414
|
+
`created: ${m.createdAt}${m.startedAt ? ` · started: ${m.startedAt}` : ""}${m.finishedAt ? ` · finished: ${m.finishedAt}` : ""}`,
|
|
415
|
+
m.exitCode != null ? `exit: ${m.exitCode}` : "",
|
|
416
|
+
m.stopReason ? `stopReason: ${m.stopReason}` : "",
|
|
417
|
+
m.errorCode ? `error: ${m.errorCode}: ${m.errorMessage ?? ""}` : "",
|
|
418
|
+
`usage: in ${m.usage.input} / out ${m.usage.output} / cost ${m.usage.cost.toFixed(4)}${m.usage.turns ? ` / turns ${m.usage.turns}` : ""}`,
|
|
419
|
+
`task: ${m.task.length > 120 ? `${m.task.slice(0, 117)}…` : m.task}`,
|
|
420
|
+
`transcript: ${m.transcriptPath}`,
|
|
421
|
+
`stderr: ${m.stderrPath}`,
|
|
422
|
+
].filter(Boolean);
|
|
423
|
+
if (m.finalHandoff) lines.push("", "final handoff (first 40 lines):", ...m.finalHandoff.split("\n").slice(0, 40));
|
|
424
|
+
return lines.join("\n");
|
|
425
|
+
} catch (error) {
|
|
426
|
+
return `[delegate inspect] ${(error as Error).message}`;
|
|
427
|
+
}
|
|
428
|
+
};
|
|
429
|
+
|
|
430
|
+
// ── 4. /delegate command ───────────────────────────────────────────────
|
|
431
|
+
|
|
432
|
+
pi.registerCommand("delegate", {
|
|
433
|
+
description: "Delegate tasks to isolated child Pi sessions; strict delegation mode gate.",
|
|
434
|
+
getArgumentCompletions: (prefix: string) => {
|
|
435
|
+
const items = delegateCompletions(prefix, app.recentRunIds(6)).map((v) => ({ value: v, label: v }));
|
|
436
|
+
return items.length ? items : null;
|
|
437
|
+
},
|
|
438
|
+
handler: async (args: string, ctx: ExtensionCommandContext) => {
|
|
439
|
+
const intent: DelegateIntent = parseDelegateCommand(args ?? "");
|
|
440
|
+
switch (intent.kind) {
|
|
441
|
+
case "help":
|
|
442
|
+
say(ctx, helpText());
|
|
443
|
+
return;
|
|
444
|
+
case "paths": {
|
|
445
|
+
const p = app.paths();
|
|
446
|
+
say(ctx, ["[delegate paths]", `config: ${p.configPath}`, `runs: ${p.runsDir}`, `agent: ${p.agentDir}`].join("\n"));
|
|
447
|
+
return;
|
|
448
|
+
}
|
|
449
|
+
case "doctor":
|
|
450
|
+
say(ctx, doctorText());
|
|
451
|
+
return;
|
|
452
|
+
case "status":
|
|
453
|
+
say(ctx, statusText(ctx));
|
|
454
|
+
return;
|
|
455
|
+
case "enable": {
|
|
456
|
+
const res = await app.enableStrict(modeCtx(ctx));
|
|
457
|
+
say(ctx, `[delegate] ${res.message}`, res.ok ? "info" : "warning");
|
|
458
|
+
return;
|
|
459
|
+
}
|
|
460
|
+
case "disable": {
|
|
461
|
+
const res = await app.disableStrict(modeCtx(ctx));
|
|
462
|
+
say(ctx, `[delegate] ${res.message}`, res.ok ? "info" : "warning");
|
|
463
|
+
return;
|
|
464
|
+
}
|
|
465
|
+
case "cancel": {
|
|
466
|
+
const res = await app.cancel(intent.runId);
|
|
467
|
+
say(ctx, `[delegate] ${res.message}`, res.ok ? "info" : "warning");
|
|
468
|
+
return;
|
|
469
|
+
}
|
|
470
|
+
case "inspect":
|
|
471
|
+
say(ctx, inspectText(intent.runId));
|
|
472
|
+
return;
|
|
473
|
+
case "run":
|
|
474
|
+
if (!isRoleName(intent.role)) {
|
|
475
|
+
say(ctx, `[delegate] invalid role '${intent.role}'. Use general or research.`, "error");
|
|
476
|
+
return;
|
|
477
|
+
}
|
|
478
|
+
await runCommandForeground(intent.task, intent.role, ctx);
|
|
479
|
+
return;
|
|
480
|
+
case "invalid":
|
|
481
|
+
say(ctx, `[delegate] unrecognized '${intent.token}'.\n${intent.usage}\n${helpText()}`, "error");
|
|
482
|
+
return;
|
|
483
|
+
case "dashboard":
|
|
484
|
+
default:
|
|
485
|
+
if (ctx.mode === "tui") {
|
|
486
|
+
await openDashboard(ctx);
|
|
487
|
+
} else {
|
|
488
|
+
say(ctx, statusText(ctx));
|
|
489
|
+
}
|
|
490
|
+
return;
|
|
491
|
+
}
|
|
492
|
+
},
|
|
493
|
+
});
|
|
494
|
+
|
|
495
|
+
// ── Dashboard (§12.2) ───────────────────────────────────────────────────
|
|
496
|
+
|
|
497
|
+
const dashboardSnapshot = (): PanelSnapshot => {
|
|
498
|
+
const s = app.getStatus(pi.getActiveTools());
|
|
499
|
+
const active = s.activeRun;
|
|
500
|
+
const last = s.lastRun;
|
|
501
|
+
return {
|
|
502
|
+
title: "Delegation",
|
|
503
|
+
summaryLines: [
|
|
504
|
+
`Parent mode ${s.modeEnabled ? "strict" : "normal"}`,
|
|
505
|
+
`Parent tools ${s.modeEnabled ? "delegate only" : "normal active set"}`,
|
|
506
|
+
`Active run ${active ? `${active.runId.slice(0, 24)} (${active.role})` : "none"}`,
|
|
507
|
+
`Last run ${last ? `${last.role} · ${last.state}${last.durationMs != null ? ` · ${Math.round(last.durationMs / 1000)}s` : ""}` : "none"}`,
|
|
508
|
+
`Default role ${s.defaultRole}`,
|
|
509
|
+
],
|
|
510
|
+
sections: [
|
|
511
|
+
{
|
|
512
|
+
title: "Actions",
|
|
513
|
+
rows: [
|
|
514
|
+
{ key: "run-general", label: "Run general", value: "", kind: "action" },
|
|
515
|
+
{ key: "run-research", label: "Run research", value: "", kind: "action" },
|
|
516
|
+
{ key: "strict-toggle", label: s.modeEnabled ? "Disable strict mode" : "Enable strict mode", value: "", kind: "action" },
|
|
517
|
+
{ key: "inspect-last", label: "Inspect last run", value: "", kind: "action", disabled: !last && !active },
|
|
518
|
+
{ key: "paths", label: "Paths / diagnostics", value: "", kind: "action" },
|
|
519
|
+
{ key: "doctor", label: "Doctor", value: "", kind: "action" },
|
|
520
|
+
],
|
|
521
|
+
},
|
|
522
|
+
],
|
|
523
|
+
detailLines: active ? [`elapsed updates refresh every 1s while a run is active`] : undefined,
|
|
524
|
+
};
|
|
525
|
+
};
|
|
526
|
+
|
|
527
|
+
const openDashboard = async (ctx: ExtensionCommandContext): Promise<void> => {
|
|
528
|
+
let initialKey = app.isStrict() ? "strict-toggle" : "run-general";
|
|
529
|
+
for (;;) {
|
|
530
|
+
let refreshTimer: ReturnType<typeof setInterval> | undefined;
|
|
531
|
+
let result: { action?: string } | undefined;
|
|
532
|
+
try {
|
|
533
|
+
result = await ctx.ui.custom<{ action?: string }>(
|
|
534
|
+
(tui, theme, keybindings, done) => {
|
|
535
|
+
const panel = new SettingsPanel({
|
|
536
|
+
theme,
|
|
537
|
+
keybindings,
|
|
538
|
+
initialKey,
|
|
539
|
+
snapshot: dashboardSnapshot,
|
|
540
|
+
apply: () => null,
|
|
541
|
+
activate: (key): PanelActionResult => ({ kind: "close", action: key }),
|
|
542
|
+
requestRender: () => tui.requestRender(),
|
|
543
|
+
done,
|
|
544
|
+
});
|
|
545
|
+
refreshTimer = setInterval(() => {
|
|
546
|
+
panel.refresh();
|
|
547
|
+
tui.requestRender();
|
|
548
|
+
}, 1000);
|
|
549
|
+
return panel;
|
|
550
|
+
},
|
|
551
|
+
{
|
|
552
|
+
onCancel: () => ({ /* esc closes */ }),
|
|
553
|
+
} as unknown as Record<string, never>,
|
|
554
|
+
);
|
|
555
|
+
} catch {
|
|
556
|
+
return; // esc / cancel
|
|
557
|
+
} finally {
|
|
558
|
+
if (refreshTimer) clearInterval(refreshTimer);
|
|
559
|
+
}
|
|
560
|
+
const action = result?.action;
|
|
561
|
+
if (!action) return;
|
|
562
|
+
initialKey = action;
|
|
563
|
+
if (action === "run-general" || action === "run-research") {
|
|
564
|
+
const role = action === "run-research" ? ("research" as const) : ("general" as const);
|
|
565
|
+
const task = await ctx.ui.editor(`Delegated task (${role})`, "");
|
|
566
|
+
if (!task || !task.trim()) continue;
|
|
567
|
+
await runCommandForeground(task, role, ctx);
|
|
568
|
+
continue;
|
|
569
|
+
}
|
|
570
|
+
if (action === "strict-toggle") {
|
|
571
|
+
if (app.isStrict()) {
|
|
572
|
+
const res = await app.disableStrict(modeCtx(ctx));
|
|
573
|
+
say(ctx, `[delegate] ${res.message}`, res.ok ? "info" : "warning");
|
|
574
|
+
} else {
|
|
575
|
+
const res = await app.enableStrict(modeCtx(ctx));
|
|
576
|
+
say(ctx, `[delegate] ${res.message}`, res.ok ? "info" : "warning");
|
|
577
|
+
}
|
|
578
|
+
continue;
|
|
579
|
+
}
|
|
580
|
+
if (action === "inspect-last") {
|
|
581
|
+
say(ctx, inspectText());
|
|
582
|
+
continue;
|
|
583
|
+
}
|
|
584
|
+
if (action === "paths") {
|
|
585
|
+
const p = app.paths();
|
|
586
|
+
say(ctx, [`[delegate paths]`, `config: ${p.configPath}`, `runs: ${p.runsDir}`].join("\n"));
|
|
587
|
+
continue;
|
|
588
|
+
}
|
|
589
|
+
if (action === "doctor") {
|
|
590
|
+
say(ctx, doctorText());
|
|
591
|
+
continue;
|
|
592
|
+
}
|
|
593
|
+
return;
|
|
594
|
+
}
|
|
595
|
+
};
|
|
596
|
+
|
|
597
|
+
// ── 6. Strict tool_call gate — authoritative allowlist ──────────────────
|
|
598
|
+
|
|
599
|
+
pi.on("tool_call", async (event: { toolName: string }) => {
|
|
600
|
+
const decision = app.gate(event.toolName);
|
|
601
|
+
if (decision.block) return { block: true, reason: decision.reason };
|
|
602
|
+
return undefined;
|
|
603
|
+
});
|
|
604
|
+
|
|
605
|
+
// ── 7. Lifecycle ────────────────────────────────────────────────────────
|
|
606
|
+
|
|
607
|
+
const hydrateFromSession = (ctx: ExtensionContext) => {
|
|
608
|
+
try {
|
|
609
|
+
const branch = ctx.sessionManager.getBranch() as SessionEntryLike[];
|
|
610
|
+
app.hydrateFromBranch(branch);
|
|
611
|
+
} catch (error) {
|
|
612
|
+
// Replay failure keeps the stricter of both states (§8.2).
|
|
613
|
+
console.log(`[delegate] mode replay failed: ${(error as Error).message}`);
|
|
614
|
+
}
|
|
615
|
+
if (app.isStrict()) {
|
|
616
|
+
ctx.ui.setStatus("delegate", "delegate: strict");
|
|
617
|
+
// Repair visibility immediately in case the session had drifted.
|
|
618
|
+
try {
|
|
619
|
+
syncStrictToolSet(app.getModeRuntime(), pi.getActiveTools(), () => pi.setActiveTools(["delegate"]));
|
|
620
|
+
} catch {
|
|
621
|
+
// gate remains authoritative
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
refreshDoctor(ctx);
|
|
625
|
+
};
|
|
626
|
+
|
|
627
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
628
|
+
hydrateFromSession(ctx);
|
|
629
|
+
if ((unknownKeys.length > 0 || recoveredFromCorrupt) && ctx.hasUI) {
|
|
630
|
+
const parts: string[] = [];
|
|
631
|
+
if (unknownKeys.length > 0) parts.push(`unknown config keys ignored: ${unknownKeys.join(", ")}`);
|
|
632
|
+
if (recoveredFromCorrupt) parts.push(`corrupt config preserved at ${corruptEvidencePath ?? "?"}`);
|
|
633
|
+
ctx.ui.notify(`delegate: ${parts.join("; ")}`, "warning");
|
|
634
|
+
}
|
|
635
|
+
});
|
|
636
|
+
|
|
637
|
+
pi.on("session_tree", async (_event, ctx) => {
|
|
638
|
+
// Branch navigation: mode follows the new leaf (§8.2, E2E-03).
|
|
639
|
+
hydrateFromSession(ctx);
|
|
640
|
+
});
|
|
641
|
+
|
|
642
|
+
pi.on("before_agent_start", async (event: { systemPrompt?: string }, ctx) => {
|
|
643
|
+
if (!app.isStrict()) return undefined;
|
|
644
|
+
// Drift repair before provider call; keep advertised set to ['delegate'].
|
|
645
|
+
try {
|
|
646
|
+
syncStrictToolSet(app.getModeRuntime(), pi.getActiveTools(), () => pi.setActiveTools(["delegate"]));
|
|
647
|
+
} catch {
|
|
648
|
+
// gate remains authoritative
|
|
649
|
+
}
|
|
650
|
+
resetBlockedCounters(app.getModeRuntime());
|
|
651
|
+
const prompt = event.systemPrompt ?? "";
|
|
652
|
+
if (prompt.includes("[DELEGATION-MODE OVERLAY")) return undefined;
|
|
653
|
+
return { systemPrompt: `${prompt}\n\n${STRICT_OVERLAY}` };
|
|
654
|
+
});
|
|
655
|
+
|
|
656
|
+
pi.on("turn_start", async () => {
|
|
657
|
+
resetBlockedCounters(app.getModeRuntime());
|
|
658
|
+
});
|
|
659
|
+
|
|
660
|
+
pi.on("session_shutdown", async (_event, ctx) => {
|
|
661
|
+
// Owned child gets cancelled; UI indicators cleared.
|
|
662
|
+
app.cancelActiveOnShutdown();
|
|
663
|
+
try {
|
|
664
|
+
ctx.ui.setStatus("delegate", undefined);
|
|
665
|
+
} catch {
|
|
666
|
+
// ignore
|
|
667
|
+
}
|
|
668
|
+
});
|
|
669
|
+
}
|