@deathbeam/pi-delegate 0.0.43 → 0.0.45
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 +13 -11
- package/index.ts +70 -60
- package/package.json +1 -4
- package/src/agents.ts +19 -13
- package/src/child.ts +14 -14
- package/src/format.ts +20 -16
- package/src/inspector.ts +25 -16
- package/src/isolation.ts +3 -1
- package/src/store.ts +17 -13
package/README.md
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
# [@deathbeam/pi-delegate](https://www.npmjs.com/package/@deathbeam/pi-delegate)
|
|
2
2
|
|
|
3
|
-
Run subagents with `delegate`, `delegate_list`, `delegate_steer`, `delegate_cancel`, `delegate_apply`, and
|
|
4
|
-
`
|
|
5
|
-
Use `/delegate` command to inspect jobs in a full-screen TUI.
|
|
3
|
+
Run subagents in the background with `delegate`, and manage them with `delegate_list`, `delegate_steer`, `delegate_cancel`, `delegate_apply`, and `delegate_discard`.
|
|
4
|
+
`/delegate` opens a fullscreen inspector for live and recent jobs.
|
|
6
5
|
|
|
7
6
|
## Installation
|
|
8
7
|
|
|
@@ -29,7 +28,10 @@ Optional `delegate` settings live in `~/.pi/agent/settings.json` or `.pi/setting
|
|
|
29
28
|
}
|
|
30
29
|
```
|
|
31
30
|
|
|
32
|
-
|
|
31
|
+
- `agentDirs` adds directories to search for agents. The bundled agents and `~/.agents/agents` are always loaded.
|
|
32
|
+
- `models` maps the `cheap`, `balanced`, and `strong` tiers to a `provider/model-id` with an optional `:<thinking>` suffix. A tier without an entry uses the session model.
|
|
33
|
+
|
|
34
|
+
Agents are Markdown files with frontmatter. The body becomes the delegate's system prompt.
|
|
33
35
|
|
|
34
36
|
```markdown
|
|
35
37
|
---
|
|
@@ -43,16 +45,16 @@ isolated: false
|
|
|
43
45
|
Explore the codebase and report relevant paths.
|
|
44
46
|
```
|
|
45
47
|
|
|
46
|
-
- `name` is required and must be unique
|
|
47
|
-
- `description` is required
|
|
48
|
+
- `name` is required and must be unique.
|
|
49
|
+
- `description` is required.
|
|
48
50
|
- `tools` is optional, a comma-separated list of tool names. Defaults to the session tools.
|
|
49
51
|
- `model` is optional, a tier name or `provider/model[:thinking]`. Defaults to the session model.
|
|
50
|
-
- `isolated` is optional
|
|
52
|
+
- `isolated` is optional and defaults to `false`. See [Isolation](#isolation).
|
|
51
53
|
|
|
52
54
|
## Isolation
|
|
53
55
|
|
|
54
56
|
`isolated: true` (on a `delegate` call or in agent frontmatter) runs the delegate in its own git clone at
|
|
55
|
-
`.pi/worktrees/<id>`, starting from your current working tree including uncommitted changes.
|
|
57
|
+
`.pi/worktrees/<job id>`, starting from your current working tree including uncommitted changes.
|
|
56
58
|
|
|
57
59
|
`delegate_apply` merges the result into your working tree as uncommitted changes.
|
|
58
60
|
`delegate_discard` discards the clone and its changes.
|
|
@@ -61,10 +63,10 @@ Any later delegate can share that clone with `clone: <job id>`, for review, test
|
|
|
61
63
|
|
|
62
64
|
## Development
|
|
63
65
|
|
|
64
|
-
From
|
|
66
|
+
From the repo root:
|
|
65
67
|
|
|
66
68
|
```sh
|
|
67
69
|
npm install
|
|
68
|
-
npm test
|
|
69
|
-
pi install
|
|
70
|
+
npm test -- packages/pi-delegate
|
|
71
|
+
pi install ./packages/pi-delegate
|
|
70
72
|
```
|
package/index.ts
CHANGED
|
@@ -89,13 +89,6 @@ function resultText(result: { content: unknown }): string {
|
|
|
89
89
|
return textParts(result.content).join("\n");
|
|
90
90
|
}
|
|
91
91
|
|
|
92
|
-
/** One resolution path for launches and swaps; the error names the requested model. */
|
|
93
|
-
function mustResolveModel(request: string | undefined, ctx: ExtensionContext, fallback?: string) {
|
|
94
|
-
const { model, thinking } = resolveModel(request ?? fallback, configFor(ctx.cwd).models ?? {}, ctx);
|
|
95
|
-
if (!model) throw new Error(`No model found for "${request ?? fallback}".`);
|
|
96
|
-
return { model, thinking };
|
|
97
|
-
}
|
|
98
|
-
|
|
99
92
|
/** Isolated jobs append the clone location and a change stat so the orchestrator can apply the work. */
|
|
100
93
|
function withIsolation(output: string, isolation: IsolationState | undefined): string {
|
|
101
94
|
return isolation ? [output, isolationSummary(isolation)].filter(Boolean).join("\n\n") : output;
|
|
@@ -110,9 +103,11 @@ export default function (pi: ExtensionAPI) {
|
|
|
110
103
|
const store = createJobStore(pi.appendEntry);
|
|
111
104
|
// A cancelled child can outlive its job row; a revive waits for it so two children never share a pinned session.
|
|
112
105
|
const exiting = new Map<string, Promise<void>>();
|
|
106
|
+
// A clone an apply or discard owns: a revive that waited on the same exiting child must not spawn into it.
|
|
107
|
+
const closing = new Set<string>();
|
|
113
108
|
|
|
114
|
-
/** Waits for a cancelled child to exit; a child that never closes must not block
|
|
115
|
-
|
|
109
|
+
/** Waits for a cancelled child to exit; a child that never closes must not block its successor forever. */
|
|
110
|
+
async function waitForExit(id: string) {
|
|
116
111
|
const closed = exiting.get(id);
|
|
117
112
|
if (!closed) return;
|
|
118
113
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
@@ -122,42 +117,41 @@ export default function (pi: ExtensionAPI) {
|
|
|
122
117
|
});
|
|
123
118
|
const result = await Promise.race([closed.then(() => "closed" as const), timeout]);
|
|
124
119
|
clearTimeout(timer);
|
|
125
|
-
if (result === "timeout") throw new Error(`Delegate job "${id}" is still exiting;
|
|
126
|
-
}
|
|
120
|
+
if (result === "timeout") throw new Error(`Delegate job "${id}" is still exiting; try again.`);
|
|
121
|
+
}
|
|
127
122
|
|
|
128
123
|
let ticker: ReturnType<typeof setInterval> | undefined;
|
|
129
124
|
// Prompts are read once; drift happens one quick search at a time, so count it and nudge at 5, 10, 20, ...
|
|
130
125
|
let directCalls = 0;
|
|
131
126
|
let nextReminder = FIRST_REMINDER_AT;
|
|
132
127
|
|
|
133
|
-
|
|
128
|
+
function jobTarget(rawId: unknown, theme: Theme): string {
|
|
134
129
|
const id = jobId(rawId);
|
|
135
130
|
const job = store.find(id);
|
|
136
131
|
return job ? jobIdentity(theme, job) : theme.fg("muted", id || "…");
|
|
137
|
-
}
|
|
132
|
+
}
|
|
138
133
|
|
|
139
134
|
/** The renderCall shared by every delegate tool: identity plus an optional payload. */
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
(args: any, theme: Theme
|
|
135
|
+
function callRenderer(
|
|
136
|
+
toolName: string,
|
|
137
|
+
identity: (args: any, theme: Theme) => string,
|
|
138
|
+
payload: (args: any) => string = () => "",
|
|
139
|
+
) {
|
|
140
|
+
return (args: any, theme: Theme, context: RenderContext) =>
|
|
143
141
|
toolLayout(toolName, identity(args, theme), payload(args), theme, context.expanded, context.keyHint);
|
|
142
|
+
}
|
|
144
143
|
|
|
145
144
|
/** The job-id tools all identify the job the same way. */
|
|
146
|
-
|
|
147
|
-
callRenderer(toolName, (args, theme) => jobTarget(args?.id, theme), payload);
|
|
148
|
-
|
|
149
|
-
/** The mark is the call's outcome, not the job's status; a one-line header covers the simple tools. */
|
|
150
|
-
const headerResult = (tail: string) => (result: any, _options: any, theme: Theme, context: RenderContext) => {
|
|
151
|
-
const details = result.details as { id: string; agent: string } | undefined;
|
|
152
|
-
const body = resultText(result);
|
|
153
|
-
if (context.isError || !details?.agent) return resultFallback(body, theme, context.isError);
|
|
154
|
-
return new Text(`\n${resultHeader(theme, details, tail)}`, 0, 0);
|
|
155
|
-
};
|
|
145
|
+
function idCall(toolName: string, payload: (args: any) => string = () => "") {
|
|
146
|
+
return callRenderer(toolName, (args, theme) => jobTarget(args?.id, theme), payload);
|
|
147
|
+
}
|
|
156
148
|
|
|
157
149
|
/** The clone is the unit: every job id that ran in it is only a handle, so state changes reach all of them. */
|
|
158
|
-
|
|
150
|
+
function jobsInClone(clone: string) {
|
|
151
|
+
return store.all().filter((job) => job.isolation?.clone === clone);
|
|
152
|
+
}
|
|
159
153
|
|
|
160
|
-
|
|
154
|
+
function clonedJob(id: string) {
|
|
161
155
|
const job = store.findOrThrow(id);
|
|
162
156
|
const isolation = job.isolation;
|
|
163
157
|
if (!isolation)
|
|
@@ -167,26 +161,41 @@ export default function (pi: ExtensionAPI) {
|
|
|
167
161
|
: `Delegate job "${id}" did not run in an isolated clone.`,
|
|
168
162
|
);
|
|
169
163
|
return { job, isolation };
|
|
170
|
-
}
|
|
164
|
+
}
|
|
171
165
|
|
|
172
166
|
/** Closing a clone is a clone-wide operation: every job id that ran in it stops pointing at it. */
|
|
173
|
-
|
|
167
|
+
function closeClone(isolation: IsolationState) {
|
|
174
168
|
removeClone(isolation);
|
|
175
169
|
for (const shared of jobsInClone(isolation.clone)) {
|
|
176
170
|
shared.isolation = undefined;
|
|
177
171
|
shared.cloneClosed = true;
|
|
178
172
|
store.save(shared);
|
|
179
173
|
}
|
|
180
|
-
}
|
|
174
|
+
}
|
|
181
175
|
|
|
182
176
|
/** One job at a time per clone: a shared clone is a shared working directory. */
|
|
183
|
-
|
|
177
|
+
async function requireIdleClone(isolation: IsolationState) {
|
|
184
178
|
const busy = store.live().find((job) => job.isolation?.clone === isolation.clone);
|
|
185
179
|
if (busy)
|
|
186
180
|
throw new Error(`Delegate job "${busy.id}" is running in this clone; wait for it or cancel it first.`);
|
|
187
|
-
|
|
181
|
+
// A cancelled child leaves the live set at once but can keep writing in its clone until SIGKILL.
|
|
182
|
+
for (const job of jobsInClone(isolation.clone)) await waitForExit(job.id);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** Claims the clone before waiting; on success the mark stays as the tombstone a waiting revive checks. */
|
|
186
|
+
async function claimClone<T>(isolation: IsolationState, run: () => T): Promise<T> {
|
|
187
|
+
closing.add(isolation.clone);
|
|
188
|
+
try {
|
|
189
|
+
await requireIdleClone(isolation);
|
|
190
|
+
return run();
|
|
191
|
+
} catch (error) {
|
|
192
|
+
// A failed operation keeps the clone, so children may still spawn in it.
|
|
193
|
+
closing.delete(isolation.clone);
|
|
194
|
+
throw error;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
188
197
|
|
|
189
|
-
|
|
198
|
+
function refreshWidget(ctx: ExtensionContext) {
|
|
190
199
|
if (!ctx.hasUI) return;
|
|
191
200
|
const jobs = store.live();
|
|
192
201
|
if (jobs.length === 0) {
|
|
@@ -216,17 +225,17 @@ export default function (pi: ExtensionAPI) {
|
|
|
216
225
|
for (const line of lines) container.addChild(new Text(line, 1, 0));
|
|
217
226
|
return container;
|
|
218
227
|
});
|
|
219
|
-
}
|
|
228
|
+
}
|
|
220
229
|
|
|
221
|
-
|
|
230
|
+
function syncTicker(ctx: ExtensionContext) {
|
|
222
231
|
if (store.live().length > 0) ticker ??= setInterval(() => refreshWidget(ctx), SPINNER_INTERVAL_MS);
|
|
223
232
|
else if (ticker) {
|
|
224
233
|
clearInterval(ticker);
|
|
225
234
|
ticker = undefined;
|
|
226
235
|
}
|
|
227
|
-
}
|
|
236
|
+
}
|
|
228
237
|
|
|
229
|
-
|
|
238
|
+
function finishJob(ctx: ExtensionContext, job: DelegateJob, output?: string, error?: string) {
|
|
230
239
|
if (!store.finish(job, error ? "failed" : "done", error ? `Error: ${error}` : undefined)) return;
|
|
231
240
|
syncTicker(ctx);
|
|
232
241
|
refreshWidget(ctx);
|
|
@@ -248,10 +257,10 @@ export default function (pi: ExtensionAPI) {
|
|
|
248
257
|
{ customType: RESULT_MESSAGE, content: reportText(report), display: true, details: report },
|
|
249
258
|
{ triggerTurn: true, deliverAs: "steer" },
|
|
250
259
|
);
|
|
251
|
-
}
|
|
260
|
+
}
|
|
252
261
|
|
|
253
262
|
/** Runs one delegate child: foreground runs return their output, background ones report on completion. */
|
|
254
|
-
|
|
263
|
+
async function runDelegate(
|
|
255
264
|
ctx: ExtensionContext,
|
|
256
265
|
agent: AgentFile,
|
|
257
266
|
prior: InspectJob | undefined,
|
|
@@ -259,10 +268,12 @@ export default function (pi: ExtensionAPI) {
|
|
|
259
268
|
task: string,
|
|
260
269
|
signal: AbortSignal | undefined,
|
|
261
270
|
prompt = task,
|
|
262
|
-
)
|
|
271
|
+
) {
|
|
263
272
|
const entrypoint = process.argv[1];
|
|
264
273
|
if (!entrypoint) throw new Error("Pi CLI entrypoint missing; start Pi from its CLI to delegate.");
|
|
265
|
-
const
|
|
274
|
+
const requested = fields.model ?? agent.model;
|
|
275
|
+
const { model, thinking } = resolveModel(requested, configFor(ctx.cwd).models ?? {}, ctx);
|
|
276
|
+
if (!model) throw new Error(`No model found for "${requested}".`);
|
|
266
277
|
const tools = (agent.tools?.length ? agent.tools : pi.getActiveTools()).filter(
|
|
267
278
|
(tool) => !DELEGATION_TOOLS.has(tool),
|
|
268
279
|
);
|
|
@@ -270,7 +281,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
270
281
|
const id = prior?.id ?? randomUUID().slice(0, 8);
|
|
271
282
|
const isolation =
|
|
272
283
|
prior?.isolation ?? fields.clone ?? (fields.isolated ? createIsolation(ctx.cwd, id) : undefined);
|
|
273
|
-
if (isolation) requireIdleClone(isolation);
|
|
284
|
+
if (isolation) await requireIdleClone(isolation);
|
|
274
285
|
|
|
275
286
|
const job: DelegateJob = {
|
|
276
287
|
// A revived job keeps its id: the pinned child session id reopens the old transcript.
|
|
@@ -314,6 +325,9 @@ export default function (pi: ExtensionAPI) {
|
|
|
314
325
|
"--append-system-prompt",
|
|
315
326
|
`You are working in an isolated git clone at ${isolation.clone}. Your working directory is ${cwd}; run every command from it with relative paths. Any path under ${ctx.cwd} means the same file under ${cwd}. Your edits stay in this clone until the orchestrator applies them.${tools.includes("bash") ? " Git commands that write, such as commit and rebase, work here and change only this clone. `git diff main-snapshot` shows every change made in it." : ""}`,
|
|
316
327
|
);
|
|
328
|
+
// Same tick as the spawn: a claim that landed while we waited would delete the clone under a fresh child.
|
|
329
|
+
if (isolation && closing.has(isolation.clone))
|
|
330
|
+
throw new Error(`The clone at ${isolation.clone} is being applied or discarded; wait for it to finish.`);
|
|
317
331
|
const child = spawn(process.execPath, [entrypoint, "--mode", "rpc", ...args], {
|
|
318
332
|
cwd,
|
|
319
333
|
shell: false,
|
|
@@ -370,23 +384,23 @@ export default function (pi: ExtensionAPI) {
|
|
|
370
384
|
],
|
|
371
385
|
details,
|
|
372
386
|
};
|
|
373
|
-
}
|
|
387
|
+
}
|
|
374
388
|
|
|
375
389
|
/** Swaps a running child's model over the RPC; the child confirms or rejects it, and never restarts. */
|
|
376
|
-
|
|
390
|
+
async function swapModel(job: DelegateJob, request: string, ctx: ExtensionContext) {
|
|
377
391
|
if (!job.swapModel) throw new Error(`Delegate job "${job.id}" cannot switch models.`);
|
|
378
|
-
const { model } =
|
|
392
|
+
const { model, explicit: level } = resolveModel(request, configFor(ctx.cwd).models ?? {}, ctx);
|
|
393
|
+
if (!model) throw new Error(`No model found for "${request}".`);
|
|
379
394
|
const [provider, ...rest] = model.split("/");
|
|
380
395
|
if (!rest.length) throw new Error(`Model "${model}" has no provider prefix.`);
|
|
381
|
-
// Only an explicit :thinking suffix changes the level; an inherited one must not silently reset it.
|
|
382
|
-
const level = /:(off|minimal|low|medium|high|xhigh|max)$/.exec(request)?.[1];
|
|
396
|
+
// Only an explicit :thinking suffix, on the request or its tier, changes the level; an inherited one must not silently reset it.
|
|
383
397
|
// The display lands on the set_model ack, so a thinking-level failure cannot leave it stale.
|
|
384
398
|
await job.swapModel(provider, rest.join("/"), level, () => {
|
|
385
399
|
job.model = model;
|
|
386
400
|
job.contextWindow = contextWindowFor(ctx, model);
|
|
387
401
|
});
|
|
388
402
|
if (level) job.model = `${model}:${level}`;
|
|
389
|
-
}
|
|
403
|
+
}
|
|
390
404
|
|
|
391
405
|
pi.on("session_shutdown", () => {
|
|
392
406
|
if (ticker) clearInterval(ticker);
|
|
@@ -395,7 +409,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
395
409
|
});
|
|
396
410
|
|
|
397
411
|
// Rebuilt from the active branch: abandoned branches are alternative histories.
|
|
398
|
-
|
|
412
|
+
function restoreSession(ctx: ExtensionContext) {
|
|
399
413
|
const interrupted = store.restore(ctx.sessionManager.getBranch());
|
|
400
414
|
// Custom entries never reach the model, so announce the interrupted jobs as a steered message.
|
|
401
415
|
if (interrupted.length)
|
|
@@ -412,7 +426,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
412
426
|
},
|
|
413
427
|
{ deliverAs: "steer" },
|
|
414
428
|
);
|
|
415
|
-
}
|
|
429
|
+
}
|
|
416
430
|
|
|
417
431
|
pi.on("session_start", (_event, ctx) => restoreSession(ctx));
|
|
418
432
|
pi.on("session_tree", (_event, ctx) => restoreSession(ctx));
|
|
@@ -682,8 +696,6 @@ export default function (pi: ExtensionAPI) {
|
|
|
682
696
|
};
|
|
683
697
|
},
|
|
684
698
|
renderCall: idCall("delegate_cancel"),
|
|
685
|
-
|
|
686
|
-
renderResult: headerResult("cancellation requested"),
|
|
687
699
|
});
|
|
688
700
|
|
|
689
701
|
pi.registerTool({
|
|
@@ -698,9 +710,9 @@ export default function (pi: ExtensionAPI) {
|
|
|
698
710
|
async execute(_toolCallId, rawParams, _signal, _onUpdate, _ctx) {
|
|
699
711
|
const id = jobId(rawParams.id);
|
|
700
712
|
const { job, isolation } = clonedJob(id);
|
|
701
|
-
|
|
702
|
-
const result = applyClone(isolation);
|
|
713
|
+
const result = await claimClone(isolation, () => applyClone(isolation));
|
|
703
714
|
if (result.kind === "conflict") {
|
|
715
|
+
closing.delete(isolation.clone);
|
|
704
716
|
// Base rule: base tracks the newest snapshot, so the next apply works whether or not the delegate rebased yet.
|
|
705
717
|
for (const shared of jobsInClone(isolation.clone)) {
|
|
706
718
|
shared.isolation = { ...isolation, base: result.snapshot };
|
|
@@ -760,8 +772,7 @@ export default function (pi: ExtensionAPI) {
|
|
|
760
772
|
async execute(_toolCallId, rawParams, _signal, _onUpdate, _ctx) {
|
|
761
773
|
const id = jobId(rawParams.id);
|
|
762
774
|
const { job, isolation } = clonedJob(id);
|
|
763
|
-
|
|
764
|
-
closeClone(isolation);
|
|
775
|
+
await claimClone(isolation, () => closeClone(isolation));
|
|
765
776
|
return {
|
|
766
777
|
content: [
|
|
767
778
|
{
|
|
@@ -773,7 +784,6 @@ export default function (pi: ExtensionAPI) {
|
|
|
773
784
|
};
|
|
774
785
|
},
|
|
775
786
|
renderCall: idCall("delegate_discard"),
|
|
776
|
-
renderResult: headerResult("clone discarded"),
|
|
777
787
|
});
|
|
778
788
|
|
|
779
789
|
pi.registerTool({
|
|
@@ -787,10 +797,10 @@ export default function (pi: ExtensionAPI) {
|
|
|
787
797
|
const jobs = store.all();
|
|
788
798
|
if (!jobs.length) return { content: [{ type: "text", text: "No delegates yet." }], details: undefined };
|
|
789
799
|
const running = jobs.filter((job) => job.status === "running").length;
|
|
790
|
-
|
|
800
|
+
function lastActivity(job: InspectJob) {
|
|
791
801
|
const { tool } = lastToolCall(job);
|
|
792
802
|
return job.status === "running" && tool ? ` · ${tool.name}${tool.detail ? ` ${tool.detail}` : ""}` : "";
|
|
793
|
-
}
|
|
803
|
+
}
|
|
794
804
|
const lines = jobs.map((job) => {
|
|
795
805
|
const tag = isolationWords(job);
|
|
796
806
|
return `- ${job.id} ${job.agent} · ${job.status}${tag ? ` · ${tag}` : ""} · ${jobLine(job, elapsedMs(job, now))}${lastActivity(job)}`;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@deathbeam/pi-delegate",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.45",
|
|
4
4
|
"description": "Minimal extension for delegating tasks to subagents.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -28,9 +28,6 @@
|
|
|
28
28
|
"./index.ts"
|
|
29
29
|
]
|
|
30
30
|
},
|
|
31
|
-
"scripts": {
|
|
32
|
-
"test": "node check.mjs"
|
|
33
|
-
},
|
|
34
31
|
"peerDependencies": {
|
|
35
32
|
"@earendil-works/pi-coding-agent": "*",
|
|
36
33
|
"@earendil-works/pi-tui": "*"
|
package/src/agents.ts
CHANGED
|
@@ -46,15 +46,6 @@ function readConfig(path: string): DelegateConfig {
|
|
|
46
46
|
}
|
|
47
47
|
}
|
|
48
48
|
|
|
49
|
-
export function configFor(cwd: string): DelegateConfig {
|
|
50
|
-
const global = readConfig(join(getAgentDir(), "settings.json"));
|
|
51
|
-
const project = readConfig(join(cwd, CONFIG_DIR_NAME, "settings.json"));
|
|
52
|
-
return {
|
|
53
|
-
agentDirs: [...stringList(global.agentDirs), ...stringList(project.agentDirs)],
|
|
54
|
-
models: { ...(global.models ?? {}), ...(project.models ?? {}) },
|
|
55
|
-
};
|
|
56
|
-
}
|
|
57
|
-
|
|
58
49
|
function loadAgents(dir: string): AgentFile[] {
|
|
59
50
|
if (!existsSync(dir)) return [];
|
|
60
51
|
const agents: AgentFile[] = [];
|
|
@@ -105,6 +96,15 @@ export function agentByName(cwd: string, name: string): AgentFile {
|
|
|
105
96
|
return agent;
|
|
106
97
|
}
|
|
107
98
|
|
|
99
|
+
export function configFor(cwd: string): DelegateConfig {
|
|
100
|
+
const global = readConfig(join(getAgentDir(), "settings.json"));
|
|
101
|
+
const project = readConfig(join(cwd, CONFIG_DIR_NAME, "settings.json"));
|
|
102
|
+
return {
|
|
103
|
+
agentDirs: [...stringList(global.agentDirs), ...stringList(project.agentDirs)],
|
|
104
|
+
models: { ...(global.models ?? {}), ...(project.models ?? {}) },
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
108
|
// Same `:<thinking>` suffix pi's --model takes; only known levels split, so ids like `llama3:8b` stay whole.
|
|
109
109
|
function splitThinking(value: string): { model: string; thinking?: string } {
|
|
110
110
|
const match = /^(.*):(off|minimal|low|medium|high|xhigh|max)$/.exec(value);
|
|
@@ -112,20 +112,26 @@ function splitThinking(value: string): { model: string; thinking?: string } {
|
|
|
112
112
|
}
|
|
113
113
|
|
|
114
114
|
// Precedence: requested `:<thinking>` suffix, then the tier suffix, then the session level.
|
|
115
|
+
// `explicit` is the level the request names outright; undefined means it only inherits the session level.
|
|
115
116
|
export function resolveModel(
|
|
116
117
|
value: string | undefined,
|
|
117
118
|
models: Record<string, unknown>,
|
|
118
119
|
ctx: Pick<ExtensionContext, "model" | "thinkingLevel">,
|
|
119
|
-
): { model?: string; thinking?: string } {
|
|
120
|
+
): { model?: string; thinking?: string; explicit?: string } {
|
|
120
121
|
const split = splitThinking(value ?? "");
|
|
121
122
|
const thinking = split.thinking ?? ctx.thinkingLevel;
|
|
122
|
-
if (split.model && !MODEL_TIERS.has(split.model)) return { model: split.model, thinking };
|
|
123
|
+
if (split.model && !MODEL_TIERS.has(split.model)) return { model: split.model, thinking, explicit: split.thinking };
|
|
123
124
|
const configured = models[split.model];
|
|
124
125
|
if (typeof configured === "string" && configured) {
|
|
125
126
|
const tier = splitThinking(configured);
|
|
126
|
-
|
|
127
|
+
const explicit = split.thinking ?? tier.thinking;
|
|
128
|
+
return { model: tier.model, thinking: explicit ?? ctx.thinkingLevel, explicit };
|
|
127
129
|
}
|
|
128
|
-
return {
|
|
130
|
+
return {
|
|
131
|
+
model: ctx.model ? `${ctx.model.provider}/${ctx.model.id}` : undefined,
|
|
132
|
+
thinking,
|
|
133
|
+
explicit: split.thinking,
|
|
134
|
+
};
|
|
129
135
|
}
|
|
130
136
|
|
|
131
137
|
export function contextWindowFor(ctx: ExtensionContext, model: string | undefined): number | undefined {
|
package/src/child.ts
CHANGED
|
@@ -59,14 +59,14 @@ export function runChild(
|
|
|
59
59
|
let send!: (command: Record<string, unknown>) => Promise<any>;
|
|
60
60
|
|
|
61
61
|
const done = new Promise<string>((resolveChild, reject) => {
|
|
62
|
-
|
|
62
|
+
function rejectPending(error: Error) {
|
|
63
63
|
for (const request of pending.values()) {
|
|
64
64
|
clearTimeout(request.timer);
|
|
65
65
|
request.reject(error);
|
|
66
66
|
}
|
|
67
67
|
pending.clear();
|
|
68
|
-
}
|
|
69
|
-
|
|
68
|
+
}
|
|
69
|
+
function finish(code: number | null, error?: Error) {
|
|
70
70
|
if (settled || finishing) return;
|
|
71
71
|
finishing = true;
|
|
72
72
|
if (buffer) {
|
|
@@ -94,14 +94,14 @@ export function runChild(
|
|
|
94
94
|
rejectPending(new Error("Delegate finished before acknowledging command"));
|
|
95
95
|
resolveChild(limitOutput(liveText.trim() || "(no output)"));
|
|
96
96
|
}
|
|
97
|
-
}
|
|
98
|
-
|
|
97
|
+
}
|
|
98
|
+
function fail(error: Error) {
|
|
99
99
|
if (settled || finishing) return;
|
|
100
100
|
childFailure = error;
|
|
101
101
|
child.kill("SIGTERM");
|
|
102
102
|
finish(null, error);
|
|
103
|
-
}
|
|
104
|
-
|
|
103
|
+
}
|
|
104
|
+
function parse(line: string) {
|
|
105
105
|
if (!line.trim()) return;
|
|
106
106
|
try {
|
|
107
107
|
const event = JSON.parse(line) as any;
|
|
@@ -161,8 +161,8 @@ export function runChild(
|
|
|
161
161
|
} catch {
|
|
162
162
|
// Diagnostics on stdout that are not JSON events; ignore those lines.
|
|
163
163
|
}
|
|
164
|
-
}
|
|
165
|
-
|
|
164
|
+
}
|
|
165
|
+
function enqueue(command: Record<string, unknown>) {
|
|
166
166
|
const line = `${JSON.stringify(command)}\n`;
|
|
167
167
|
const write = writeQueue.then(
|
|
168
168
|
() =>
|
|
@@ -176,7 +176,7 @@ export function runChild(
|
|
|
176
176
|
);
|
|
177
177
|
writeQueue = write.catch(() => {});
|
|
178
178
|
return write;
|
|
179
|
-
}
|
|
179
|
+
}
|
|
180
180
|
send = (command: Record<string, unknown>) => {
|
|
181
181
|
const id = `delegate_${++requestId}`;
|
|
182
182
|
const response = new Promise<any>((resolveResponse, rejectResponse) => {
|
|
@@ -202,14 +202,14 @@ export function runChild(
|
|
|
202
202
|
});
|
|
203
203
|
return response;
|
|
204
204
|
};
|
|
205
|
-
|
|
205
|
+
function abort() {
|
|
206
206
|
if (settled || aborted) return;
|
|
207
207
|
aborted = true;
|
|
208
208
|
void send({ type: "abort" }).catch(() => {});
|
|
209
209
|
setTimeout(() => {
|
|
210
210
|
if (!settled) child.kill("SIGKILL");
|
|
211
211
|
}, 5000).unref();
|
|
212
|
-
}
|
|
212
|
+
}
|
|
213
213
|
|
|
214
214
|
child.stdout.setEncoding("utf8");
|
|
215
215
|
child.stdout.on("data", (chunk: string) => {
|
|
@@ -232,11 +232,11 @@ export function runChild(
|
|
|
232
232
|
finish(null);
|
|
233
233
|
} else {
|
|
234
234
|
signal?.addEventListener("abort", abort, { once: true });
|
|
235
|
-
|
|
235
|
+
function prompt() {
|
|
236
236
|
void send({ type: "prompt", message: task }).catch((error) => {
|
|
237
237
|
if (!settled) fail(error);
|
|
238
238
|
});
|
|
239
|
-
}
|
|
239
|
+
}
|
|
240
240
|
if (revive) {
|
|
241
241
|
// An empty transcript means the pinned session was recreated (e.g. a different cwd); prompting would lose the task.
|
|
242
242
|
void send({ type: "get_state" })
|
package/src/format.ts
CHANGED
|
@@ -30,7 +30,7 @@ export type DelegateReport = {
|
|
|
30
30
|
};
|
|
31
31
|
|
|
32
32
|
/** The isolation state to show for a job: pending means its clone still holds unapplied work. */
|
|
33
|
-
|
|
33
|
+
type IsolationMark = "isolated" | "pending";
|
|
34
34
|
|
|
35
35
|
type IsolationStateFields = {
|
|
36
36
|
isolation?: unknown;
|
|
@@ -61,19 +61,17 @@ const WIDGET_MAX_JOBS = 5;
|
|
|
61
61
|
export const COLLAPSED_OUTPUT_LINES = 10;
|
|
62
62
|
const MAX_OUTPUT_BYTES = 50 * 1024;
|
|
63
63
|
|
|
64
|
-
/** Terminal statuses have static icons; running jobs use statusIcon's clock-driven frame. */
|
|
65
|
-
function statusIcon(status: JobStatus, now = Date.now()): string {
|
|
66
|
-
return status === "running"
|
|
67
|
-
? SPINNER_FRAMES[Math.floor(now / SPINNER_INTERVAL_MS) % SPINNER_FRAMES.length]!
|
|
68
|
-
: STATUS_ICONS[status];
|
|
69
|
-
}
|
|
70
|
-
|
|
71
64
|
export function statusText(theme: Theme, status: JobStatus, now = Date.now()): string {
|
|
72
|
-
|
|
65
|
+
// Terminal statuses have static icons; running jobs use a clock-driven spinner frame.
|
|
66
|
+
const icon =
|
|
67
|
+
status === "running"
|
|
68
|
+
? SPINNER_FRAMES[Math.floor(now / SPINNER_INTERVAL_MS) % SPINNER_FRAMES.length]!
|
|
69
|
+
: STATUS_ICONS[status];
|
|
70
|
+
return theme.fg(STATUS_COLORS[status], icon);
|
|
73
71
|
}
|
|
74
72
|
|
|
75
73
|
/** Derives the mark from a job: an isolation with no clone left, or a still-running one, is not pending. */
|
|
76
|
-
|
|
74
|
+
function isolationMarkOf(job: IsolationStateFields): IsolationMark | undefined {
|
|
77
75
|
if (!job.isolation) return undefined;
|
|
78
76
|
return job.status === "running" ? "isolated" : "pending";
|
|
79
77
|
}
|
|
@@ -103,7 +101,7 @@ function formatTokens(count: number): string {
|
|
|
103
101
|
return `${Math.round(count / 1000000)}M`;
|
|
104
102
|
}
|
|
105
103
|
|
|
106
|
-
|
|
104
|
+
function formatDuration(ms: number): string {
|
|
107
105
|
const seconds = Math.max(0, Math.floor(ms / 1000));
|
|
108
106
|
if (seconds < 60) return `${seconds}s`;
|
|
109
107
|
const minutes = Math.floor(seconds / 60);
|
|
@@ -137,7 +135,9 @@ export function toolLines(theme: Theme, name: string, detail: string, result?: s
|
|
|
137
135
|
|
|
138
136
|
export function toolCallDetail(toolName: string, args: unknown): string {
|
|
139
137
|
const input = (args ?? {}) as Record<string, unknown>;
|
|
140
|
-
|
|
138
|
+
function value(key: string): string {
|
|
139
|
+
return typeof input[key] === "string" ? (input[key] as string).trim() : "";
|
|
140
|
+
}
|
|
141
141
|
const path = value("path") || ".";
|
|
142
142
|
switch (toolName) {
|
|
143
143
|
case "bash":
|
|
@@ -157,6 +157,7 @@ export function toolCallDetail(toolName: string, args: unknown): string {
|
|
|
157
157
|
return "";
|
|
158
158
|
}
|
|
159
159
|
}
|
|
160
|
+
|
|
160
161
|
/** Caps a preview at `maxLines`; callers report the hidden count their own way. */
|
|
161
162
|
export function capLines<T>(lines: T[], maxLines: number): { shown: T[]; hidden: number } {
|
|
162
163
|
if (lines.length <= maxLines) return { shown: lines, hidden: 0 };
|
|
@@ -228,12 +229,15 @@ export function piDiff(unified: string): string {
|
|
|
228
229
|
([, os, oc, ns, nc]) => String(Math.max(+os! + (+oc! || 1), +ns! + (+nc! || 1)) - 1).length,
|
|
229
230
|
),
|
|
230
231
|
);
|
|
231
|
-
|
|
232
|
+
function header() {
|
|
232
233
|
if (!pathShown) {
|
|
233
234
|
out.push(path);
|
|
234
235
|
pathShown = true;
|
|
235
236
|
}
|
|
236
|
-
}
|
|
237
|
+
}
|
|
238
|
+
function num(prefix: string): string {
|
|
239
|
+
return String(prefix === "-" ? oldNum++ : newNum++).padStart(width, " ");
|
|
240
|
+
}
|
|
237
241
|
for (const line of unified.split("\n")) {
|
|
238
242
|
const file = /^diff --git a\/\S+ b\/(.+)$/.exec(line);
|
|
239
243
|
if (file) {
|
|
@@ -258,7 +262,6 @@ export function piDiff(unified: string): string {
|
|
|
258
262
|
continue;
|
|
259
263
|
}
|
|
260
264
|
const content = line.slice(1);
|
|
261
|
-
const num = (prefix: string) => String(prefix === "-" ? oldNum++ : newNum++).padStart(width, " ");
|
|
262
265
|
if (line.startsWith("+")) out.push(`+${num("+")} ${content}`);
|
|
263
266
|
else if (line.startsWith("-")) out.push(`-${num("-")} ${content}`);
|
|
264
267
|
else {
|
|
@@ -296,8 +299,9 @@ export function resultFallback(body: string, theme: Theme, isError: boolean): Te
|
|
|
296
299
|
return new Text(`\n${mark} ${theme.fg(isError ? "error" : "toolOutput", body || "(no output)")}`, 0, 0);
|
|
297
300
|
}
|
|
298
301
|
|
|
302
|
+
/** pi's built-in expand hint; callers place it on its own row, so it carries no leading newline. */
|
|
299
303
|
export function moreLines(theme: Theme, hidden: number, keyHint: KeybindingHints["keyHint"]): string {
|
|
300
|
-
return theme.fg("muted",
|
|
304
|
+
return `${theme.fg("muted", `... (${hidden} more lines,`)} ${keyHint("app.tools.expand", "to expand")}${theme.fg("muted", ")")}`;
|
|
301
305
|
}
|
|
302
306
|
|
|
303
307
|
export function appendOutput(
|
package/src/inspector.ts
CHANGED
|
@@ -197,35 +197,44 @@ export function registerInspector(pi: ExtensionAPI, store: JobStore, sessionDir:
|
|
|
197
197
|
let lastWindow = { height: 0, total: 0 };
|
|
198
198
|
const transcripts = new Map<string, Transcript>();
|
|
199
199
|
const loaded = new Set<string>();
|
|
200
|
-
|
|
200
|
+
function jobs() {
|
|
201
|
+
return store.all();
|
|
202
|
+
}
|
|
201
203
|
// Format hints from the injected manager; an imported copy would not see the user's keybindings.
|
|
202
|
-
|
|
203
|
-
rawKeyHint(keys.getKeys(id).join("/"), description);
|
|
204
|
+
function hint(id: Keybinding, description: string) {
|
|
205
|
+
return rawKeyHint(keys.getKeys(id).join("/"), description);
|
|
206
|
+
}
|
|
204
207
|
// Fixed rows: title, top rule, bottom rule, footer.
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
+
function bodyHeight() {
|
|
209
|
+
return Math.max(0, tui.terminal.rows - 4);
|
|
210
|
+
}
|
|
211
|
+
function toolsLines(job: InspectJob, width: number) {
|
|
212
|
+
return wrapTextWithAnsi(formatTools(job.tools), Math.max(1, width)).map((line) =>
|
|
208
213
|
theme.fg("dim", line),
|
|
209
214
|
);
|
|
210
|
-
|
|
215
|
+
}
|
|
216
|
+
function transcript(job: InspectJob) {
|
|
211
217
|
let value = transcripts.get(job.id);
|
|
212
218
|
if (!value) {
|
|
213
219
|
value = new Transcript(theme);
|
|
214
220
|
transcripts.set(job.id, value);
|
|
215
221
|
}
|
|
216
222
|
return value;
|
|
217
|
-
}
|
|
223
|
+
}
|
|
218
224
|
// Restored jobs carry no messages: the child's session file is their history.
|
|
219
|
-
|
|
225
|
+
function messagesOf(job: InspectJob) {
|
|
220
226
|
if (!job.messages.length && job.status !== "running" && !loaded.has(job.id)) {
|
|
221
227
|
loaded.add(job.id);
|
|
222
228
|
job.messages = sessionMessages(sessionDir, job.id);
|
|
223
229
|
}
|
|
224
230
|
return job.messages;
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
231
|
+
}
|
|
232
|
+
function renderJobs(width: number, items: InspectJob[], selectedIndex: number): string[] {
|
|
233
|
+
function row(text: string) {
|
|
234
|
+
return (
|
|
235
|
+
truncateToWidth(text, Math.max(0, width - 1), "…", true) + theme.fg("borderMuted", "│")
|
|
236
|
+
);
|
|
237
|
+
}
|
|
229
238
|
const visible = Math.max(1, Math.floor((bodyHeight() - 1) / 3));
|
|
230
239
|
const start = Math.max(
|
|
231
240
|
0,
|
|
@@ -245,8 +254,8 @@ export function registerInspector(pi: ExtensionAPI, store: JobStore, sessionDir:
|
|
|
245
254
|
...Array(Math.max(0, bodyHeight() - 1 - lines.length)).fill(row("")),
|
|
246
255
|
row(theme.fg("dim", `${selectedIndex + 1}/${items.length}`)),
|
|
247
256
|
].slice(0, bodyHeight());
|
|
248
|
-
}
|
|
249
|
-
|
|
257
|
+
}
|
|
258
|
+
function renderHistory(width: number, job: InspectJob): string[] {
|
|
250
259
|
const tools = toolsLines(job, width);
|
|
251
260
|
// Fixed rows: header, model, description, rule, counter, plus the failure detail.
|
|
252
261
|
const height = Math.max(0, bodyHeight() - 5 - tools.length - (job.detail ? 1 : 0));
|
|
@@ -290,7 +299,7 @@ export function registerInspector(pi: ExtensionAPI, store: JobStore, sessionDir:
|
|
|
290
299
|
// Pad every row so the pane's right edge holds still while the transcript scrolls.
|
|
291
300
|
.map((line) => truncateToWidth(line, width, "…", true))
|
|
292
301
|
);
|
|
293
|
-
}
|
|
302
|
+
}
|
|
294
303
|
stopRedraw = store.subscribe(() => tui.requestRender());
|
|
295
304
|
return {
|
|
296
305
|
render(width: number) {
|
package/src/isolation.ts
CHANGED
|
@@ -137,7 +137,9 @@ export function removeClone(iso: IsolationState): void {
|
|
|
137
137
|
*/
|
|
138
138
|
export function applyClone(iso: IsolationState): ApplyResult {
|
|
139
139
|
const root = rootOf(iso);
|
|
140
|
-
|
|
140
|
+
function run(args: string[]): string {
|
|
141
|
+
return git(args, { cwd: iso.clone });
|
|
142
|
+
}
|
|
141
143
|
// Commit uncommitted delegate work so the rebase carries it.
|
|
142
144
|
run(["add", "-A"]);
|
|
143
145
|
if (run(["status", "--porcelain"]).trim()) run([...IDENTITY, "commit", "--no-verify", "-m", "delegate work"]);
|
package/src/store.ts
CHANGED
|
@@ -53,30 +53,34 @@ export function createJobStore(append: (customType: string, data: InspectJob) =>
|
|
|
53
53
|
const running = new Map<string, DelegateJob>();
|
|
54
54
|
const history: InspectJob[] = [];
|
|
55
55
|
const listeners = new Set<() => void>();
|
|
56
|
-
|
|
56
|
+
function notify() {
|
|
57
57
|
for (const redraw of listeners) redraw();
|
|
58
|
-
}
|
|
58
|
+
}
|
|
59
59
|
// A session_tree rebuild restores old entries; the history keeps one row per id across finish and relaunch.
|
|
60
|
-
|
|
60
|
+
function drop(id: string) {
|
|
61
61
|
const stale = history.findIndex((item) => item.id === id);
|
|
62
62
|
if (stale >= 0) history.splice(stale, 1);
|
|
63
|
-
}
|
|
64
|
-
|
|
63
|
+
}
|
|
64
|
+
function commit(entry: InspectJob) {
|
|
65
65
|
drop(entry.id);
|
|
66
66
|
history.unshift(entry);
|
|
67
67
|
append(JOB_ENTRY, snapshot(entry));
|
|
68
68
|
notify();
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
|
|
69
|
+
}
|
|
70
|
+
function find(id: string) {
|
|
71
|
+
return running.get(id) ?? history.find((item) => item.id === id);
|
|
72
|
+
}
|
|
73
|
+
function plain(job: InspectJob) {
|
|
72
74
|
const { controller, steer, swapModel, ...rest } = job as InspectJob & Partial<DelegateJob>;
|
|
73
75
|
return rest;
|
|
74
|
-
}
|
|
76
|
+
}
|
|
75
77
|
/** The serializable form of a job: runtime handles and the transcript stay out. */
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
78
|
+
function snapshot(job: InspectJob): InspectJob {
|
|
79
|
+
return {
|
|
80
|
+
...plain(job),
|
|
81
|
+
messages: [],
|
|
82
|
+
};
|
|
83
|
+
}
|
|
80
84
|
|
|
81
85
|
return {
|
|
82
86
|
/** Every job a view can show: live first, then history. */
|