pi-goal-delegate 0.1.0 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +147 -0
- package/README.md +409 -280
- package/package.json +2 -2
- package/skills/delegate/SKILL.md +128 -47
- package/src/command.ts +124 -32
- package/src/contract.ts +137 -11
- package/src/doctor.ts +385 -0
- package/src/events.ts +22 -1
- package/src/index.ts +466 -271
- package/src/registry.ts +108 -29
- package/src/result-schema.ts +143 -0
- package/src/retention.ts +132 -34
- package/src/run.ts +93 -21
- package/src/spawn.ts +6 -2
- package/src/supervisor.mjs +113 -4
- package/src/verify.ts +16 -1
- package/src/worker.ts +128 -59
- package/src/worktree.ts +107 -3
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-goal-delegate",
|
|
3
|
-
"version": "0.1
|
|
4
|
-
"description": "Bounded delegation for Pi: one
|
|
3
|
+
"version": "0.3.1",
|
|
4
|
+
"description": "Bounded delegation for Pi: one goal, a fresh child agent, and a return value that says verified or not. Waits inline by default; wait: false returns a live handle.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MPL-2.0",
|
|
7
7
|
"author": "Zhuocheng-Lang <2435060515@st.usst.edu.cn>",
|
package/skills/delegate/SKILL.md
CHANGED
|
@@ -1,77 +1,158 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: delegate
|
|
3
|
-
description: Hand
|
|
3
|
+
description: Hand one goal to a fresh child agent with its own context window and a verification gate, and get the verified outcome back. Use when a task splits into two or more independent workstreams, when an exploration or build loop would take more than about fifteen tool calls in the parent context, or when a mechanical job can run on a cheaper model under a verify command. Waits inline by default; wait false returns a live handle.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# Delegation
|
|
7
7
|
|
|
8
|
-
A delegation hands one goal to a fresh child
|
|
8
|
+
A delegation hands one goal to a fresh Pi child process with its own context
|
|
9
|
+
window, budget, and completion contract. `delegate_start` returns the verified
|
|
10
|
+
outcome. You run the fan-out in `codemode` and read the results in the same
|
|
11
|
+
script.
|
|
9
12
|
|
|
10
|
-
##
|
|
13
|
+
## When to delegate
|
|
11
14
|
|
|
12
|
-
Delegate
|
|
15
|
+
Delegate as soon as one of these is true. Each one is decidable from the request
|
|
16
|
+
in seconds, before any work starts:
|
|
13
17
|
|
|
14
|
-
-
|
|
15
|
-
|
|
16
|
-
|
|
18
|
+
- **Fan-out >= 2.** The task splits into two or more independent workstreams:
|
|
19
|
+
several documents or modules rewritten, separate subsystems audited, unrelated
|
|
20
|
+
test suites fixed. One workstream is not a reason to delegate.
|
|
21
|
+
- **Long loop in a clean context.** Exploration, reverse engineering,
|
|
22
|
+
build-and-fix iteration, or verification that will take more than about fifteen
|
|
23
|
+
tool calls. The child absorbs the search noise; you get the verdict.
|
|
24
|
+
- **Cheaper mechanical execution.** A well-specified rename, migration, doc
|
|
25
|
+
rewrite, or test backfill can run on a faster or cheaper `model` with a
|
|
26
|
+
`verify` command deciding whether the work counts.
|
|
17
27
|
|
|
18
|
-
|
|
28
|
+
Do the work inline when the change is a one-to-five-call edit, when it needs
|
|
29
|
+
back-and-forth with the user, or when it touches uncommitted state the child
|
|
30
|
+
would collide with.
|
|
19
31
|
|
|
20
32
|
## Write the contract
|
|
21
33
|
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
- **
|
|
26
|
-
|
|
27
|
-
- **
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
34
|
+
`goal` is the only required argument. Everything else is a sparse input or lives
|
|
35
|
+
in `options`.
|
|
36
|
+
|
|
37
|
+
- **goal**: name the artifact and the end state. "Make pnpm test pass in
|
|
38
|
+
packages/app", not "look at the tests".
|
|
39
|
+
- **doneWhen**: a falsifiable condition: a command exits 0, a test passes, a file
|
|
40
|
+
has specific content.
|
|
41
|
+
- **verify**: the one command that proves the goal. It gates
|
|
42
|
+
`delegate_complete` inside the child; a failure returns the output to the live
|
|
43
|
+
child for repair. After the child claims completion the parent re-runs the same
|
|
44
|
+
command with the same dropped environment. A parent-side failure turns the run
|
|
45
|
+
into `unverified`.
|
|
46
|
+
- **context**: only facts the child cannot discover: prior decisions, exact
|
|
47
|
+
paths, constraints, files to leave alone. No transcripts.
|
|
48
|
+
- **worktree: true** when two children would edit the same tree.
|
|
49
|
+
|
|
50
|
+
`options` carries the rest:
|
|
51
|
+
|
|
52
|
+
- `model` for a cheaper or different provider (`provider/id`). Without it the
|
|
53
|
+
parent passes its own session model explicitly.
|
|
54
|
+
- `tools` as a read-only allowlist, for example `"read,grep"`.
|
|
55
|
+
- `resultSchema` for a validated structured result, so a `codemode` fan-out can
|
|
56
|
+
aggregate JSON instead of prose.
|
|
57
|
+
- `maxTurns` when the work exceeds the 150-turn default. Split a slow goal
|
|
58
|
+
instead of raising `timeoutMinutes`.
|
|
59
|
+
- `scope: "workspace"` when the run must outlive Pi. Only a later session in the
|
|
60
|
+
same directory re-adopts it.
|
|
61
|
+
- `isolated: true` when the host cannot answer permission asks, or when ambient
|
|
62
|
+
extensions, skills, MCP servers, and context files must not reach the child.
|
|
63
|
+
- `maxDepth` (0-3) when the child must decompose its goal. A child stays inside
|
|
64
|
+
the parent's depth, spend, and deadline limits.
|
|
65
|
+
- `resumeFrom` with a previous run id to continue that child's context instead of
|
|
66
|
+
repeating it. The resumed run gets a fresh budget and, when the first run had
|
|
67
|
+
one, the same worktree.
|
|
68
|
+
- `maxCostUsd` for a per-run spend cap. A run that crosses it ends as `limit`.
|
|
69
|
+
|
|
70
|
+
A known option name written at the top level is lifted into `options`, so either
|
|
71
|
+
shape works.
|
|
72
|
+
|
|
73
|
+
## Two modes
|
|
74
|
+
|
|
75
|
+
### Inline (default)
|
|
76
|
+
|
|
77
|
+
`delegate_start` holds the call open until the child settles and returns the
|
|
78
|
+
outcome. The wait is capped by the run's own `timeoutMinutes`, so it cannot
|
|
79
|
+
outlive the delegation.
|
|
37
80
|
|
|
38
|
-
|
|
81
|
+
```js
|
|
82
|
+
// @options: {"timeout_ms": 1800000}
|
|
83
|
+
// goal: fan out two verified delegations and return their outcomes
|
|
84
|
+
const goals = [
|
|
85
|
+
{ goal: "Make pnpm test pass in packages/api", verify: "pnpm --dir packages/api test", worktree: true },
|
|
86
|
+
{ goal: "Make pnpm test pass in packages/web", verify: "pnpm --dir packages/web test", worktree: true },
|
|
87
|
+
];
|
|
88
|
+
const outcomes = await Promise.all(goals.map((g) => tools.delegate_start(g)));
|
|
89
|
+
return outcomes.map(({ runId, status, verified, summary, integration }) => ({
|
|
90
|
+
runId, status, verified, summary, patch: integration?.patchPath,
|
|
91
|
+
}));
|
|
92
|
+
```
|
|
39
93
|
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
the context.
|
|
94
|
+
Raise `timeout_ms` to cover the whole fan-out. A `codemode` script has no
|
|
95
|
+
deadline unless its header sets one, and a host default of 60 seconds cuts any
|
|
96
|
+
real delegation short.
|
|
44
97
|
|
|
45
|
-
|
|
98
|
+
If the script deadline or an abort cuts the wait, the child is **not** cancelled.
|
|
99
|
+
The call returns a live handle, and the completion is delivered later as a
|
|
100
|
+
`delegate-completion` message.
|
|
101
|
+
|
|
102
|
+
### Background handle (`wait: false`)
|
|
103
|
+
|
|
104
|
+
Use it when you want to keep working or let the session go idle.
|
|
105
|
+
|
|
106
|
+
- **Ordinary session**: start the runs, then end the turn. One coalesced
|
|
107
|
+
`delegate-completion` message wakes the session when they settle.
|
|
108
|
+
- **Active `/goal`**: do not end the turn bare. Goal mode continues
|
|
109
|
+
automatically while the child is still running. Either keep the default
|
|
110
|
+
`wait: true`, or call `goal_wait({ goal_id, reason })` alone so Goal mode
|
|
111
|
+
pauses until `delegate-completion` arrives. When `delegate_start` returns a
|
|
112
|
+
live handle under Goal mode it prints the exact `goal_wait` call with the
|
|
113
|
+
current goal id.
|
|
46
114
|
|
|
47
|
-
|
|
48
|
-
larger fan-out is refused with the live runs named. Fan out in waves, or raise the
|
|
49
|
-
limit deliberately.
|
|
115
|
+
## Collect outcomes
|
|
50
116
|
|
|
51
|
-
|
|
117
|
+
`delegate_status` inspects and optionally waits:
|
|
52
118
|
|
|
53
119
|
```js
|
|
54
|
-
const
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
const handles = await Promise.all(goals.map((goal) => tools.delegate_start(goal)));
|
|
59
|
-
return handles.map((handle) => handle.runId);
|
|
60
|
-
// End the turn. One coalesced delegate-completion message wakes you when they settle.
|
|
120
|
+
const all = await tools.delegate_status({}); // list, claims nothing
|
|
121
|
+
const one = await tools.delegate_status({ runIds: runId }); // claims that run
|
|
122
|
+
const done = await tools.delegate_status({ runIds, waitMs: 600_000 });
|
|
123
|
+
const first = await tools.delegate_status({ runIds, mode: "any", waitMs: 600_000 });
|
|
61
124
|
```
|
|
62
125
|
|
|
63
|
-
|
|
126
|
+
## Steer instead of restarting
|
|
127
|
+
|
|
128
|
+
`delegate_send(runId, text)` hands a running child one message. It reads it at its
|
|
129
|
+
next turn start, queued as a steer message before the next model call. Correcting
|
|
130
|
+
course costs one call; a restart costs the whole budget and the context.
|
|
131
|
+
|
|
132
|
+
## At most a few at once
|
|
133
|
+
|
|
134
|
+
One session keeps `PI_DELEGATE_MAX_LIVE` delegations live, four by default.
|
|
135
|
+
`delegate_start` refuses a larger fan-out and names the live runs. Fan out in
|
|
136
|
+
waves, or raise the limit deliberately.
|
|
64
137
|
|
|
65
138
|
## Handle the outcome
|
|
66
139
|
|
|
67
140
|
| Status | Meaning | Next action |
|
|
68
141
|
|---|---|---|
|
|
69
|
-
| `complete` | The child
|
|
70
|
-
| `unverified` | The child claimed completion and the parent's `verify`
|
|
71
|
-
| `blocked` | The child needs a decision, credential, or fact. It is in `needs
|
|
72
|
-
| `no_progress` | A circuit breaker fired: repeated call, repeated failure, or two identical idle turns. | Narrow the goal or change the approach
|
|
142
|
+
| `complete` | The child passed its completion gate. `verified: true` means the parent's own `verify` run also passed; `"not-run"` means no verify command was given. Structured output is in `result`. | With `verified: true`, report success and use `result` directly. With `"not-run"`, check the evidence yourself. |
|
|
143
|
+
| `unverified` | The child claimed completion and the parent's `verify` run failed. | Read `verification.output`. The work is not done, whatever the child said. |
|
|
144
|
+
| `blocked` | The child needs a decision, credential, or fact. It is in `needs`. | Start a new run with the answer in `context`, or ask the user. |
|
|
145
|
+
| `no_progress` | A circuit breaker fired: repeated call, repeated failure, or two identical idle turns. | Narrow the goal or change the approach; do not restart the same goal. |
|
|
73
146
|
| `limit` | The turn budget or the spend cap ran out before a verdict. | Raise `maxTurns`/`maxCostUsd` or split the goal. |
|
|
74
147
|
| `timeout` | The wall clock ran out and the fence stopped the child. | Split the goal into smaller parts. |
|
|
75
|
-
| `aborted` |
|
|
76
|
-
| `error` | Spawn failure, child crash, provider error, or
|
|
148
|
+
| `aborted` | Something called `delegate_cancel`. | Read `containment`: `gone` is proof, `leaked` names the survivors, `unproven` means this platform cannot prove absence. Report it as unproven. |
|
|
149
|
+
| `error` | Spawn failure, child crash, provider error, or no verdict. | Read `<runDir>/child.log` or `<runDir>/outcome.json`. |
|
|
77
150
|
| `lost` | An adopted workspace record has no exit and no provable liveness. | Inspect `<runDir>` and re-delegate the remaining work. |
|
|
151
|
+
|
|
152
|
+
## When nothing works
|
|
153
|
+
|
|
154
|
+
`delegate_status` with no runs prints the run root and the record count. If a run
|
|
155
|
+
you started is missing, compare that path with where you expected records to be.
|
|
156
|
+
A human can run `/delegate doctor` for a full installation check: run root
|
|
157
|
+
writability, the child launcher, git, retention plan, limits, and containment
|
|
158
|
+
mode.
|
package/src/command.ts
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
* /delegate read <id|prefix> one run in full
|
|
7
7
|
* /delegate log <id|prefix> the tail of the child output
|
|
8
8
|
* /delegate cancel <id|prefix|all> stop runs
|
|
9
|
+
* /delegate doctor check this installation
|
|
9
10
|
*
|
|
10
11
|
* The command is a second front end for the same registry the delegate_* tools
|
|
11
12
|
* use, so it accepts the same options and enforces the same limits. Anything the
|
|
@@ -15,8 +16,10 @@
|
|
|
15
16
|
|
|
16
17
|
import { join, resolve } from "node:path";
|
|
17
18
|
import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
18
|
-
import { MAX_MAX_TURNS, MAX_TIMEOUT_MINUTES, shortGoal } from "./contract.ts";
|
|
19
|
+
import { MAX_MAX_DEPTH, MAX_MAX_TURNS, MAX_TIMEOUT_MINUTES, shortGoal } from "./contract.ts";
|
|
20
|
+
import { formatDoctor, type DoctorReport } from "./doctor.ts";
|
|
19
21
|
import { readTail } from "./events.ts";
|
|
22
|
+
import { auditResultSchema } from "./result-schema.ts";
|
|
20
23
|
import type { RunRegistry } from "./registry.ts";
|
|
21
24
|
import { formatOutcome, type RunHandle } from "./run.ts";
|
|
22
25
|
|
|
@@ -28,7 +31,18 @@ const LOG_TAIL_BYTES = 64 * 1024;
|
|
|
28
31
|
export interface DelegateCommandOptions {
|
|
29
32
|
/** The registry of the session this command runs in. */
|
|
30
33
|
registryFor: (ctx: ExtensionCommandContext) => RunRegistry;
|
|
31
|
-
defaults: { maxTurns: number; timeoutMinutes: number; maxCostUsd?: number };
|
|
34
|
+
defaults: { maxTurns: number; timeoutMinutes: number; maxCostUsd?: number; maxDepth?: number };
|
|
35
|
+
/** The installation self-check, supplied by the extension that owns the tools. */
|
|
36
|
+
doctor?: (ctx: ExtensionCommandContext) => DoctorReport;
|
|
37
|
+
/**
|
|
38
|
+
* Where a session without a UI writes.
|
|
39
|
+
*
|
|
40
|
+
* A dependency rather than `process.stdout.write`: a test that replaces the
|
|
41
|
+
* process stream also replaces whatever protocol the host is speaking on it,
|
|
42
|
+
* and a test that silently eats the runner's own events is a test that never
|
|
43
|
+
* reports whether it passed.
|
|
44
|
+
*/
|
|
45
|
+
write?: (line: string) => void;
|
|
32
46
|
}
|
|
33
47
|
|
|
34
48
|
const USAGE = [
|
|
@@ -41,17 +55,21 @@ const USAGE = [
|
|
|
41
55
|
" --done <criteria> explicit completion criteria",
|
|
42
56
|
" --context <facts> only what the child cannot discover itself",
|
|
43
57
|
" --tools <list> child tool allowlist, e.g. read,grep",
|
|
44
|
-
" --verify <command>
|
|
45
|
-
" --cost <usd>
|
|
58
|
+
" --verify <command> gates delegate_complete, then the parent re-runs it",
|
|
59
|
+
" --cost <usd> per-run spend cap in USD, 0 disables it",
|
|
60
|
+
" --depth <n> maximum delegation-tree depth, 0-3 (default 0)",
|
|
61
|
+
" --schema <json> JSON Schema for the child's structured result",
|
|
46
62
|
" --scope <session|workspace> workspace survives Pi exiting",
|
|
47
63
|
" --isolated no ambient extensions, skills, MCP servers, or context files",
|
|
48
64
|
" --worktree give the child its own git worktree and branch",
|
|
49
65
|
" --resume <id|session> continue a previous child session",
|
|
50
66
|
" --cwd <dir> child working directory, relative to the session directory",
|
|
67
|
+
" --wait hold the turn open until the run settles (the default in print mode)",
|
|
68
|
+
" --background return as soon as the run is admitted (the default in the TUI)",
|
|
51
69
|
"",
|
|
52
70
|
"Put -- on its own to end options when the goal itself contains --words.",
|
|
53
71
|
"",
|
|
54
|
-
"Other: /delegate list · /delegate read <id> · /delegate log <id> · /delegate send <id> <text> · /delegate cancel <id|prefix|all>",
|
|
72
|
+
"Other: /delegate list · /delegate read <id> · /delegate log <id> · /delegate send <id> <text> · /delegate cancel <id|prefix|all> · /delegate doctor",
|
|
55
73
|
].join("\n");
|
|
56
74
|
|
|
57
75
|
const KNOWN_FLAGS = new Set([
|
|
@@ -59,6 +77,8 @@ const KNOWN_FLAGS = new Set([
|
|
|
59
77
|
"turns",
|
|
60
78
|
"minutes",
|
|
61
79
|
"cost",
|
|
80
|
+
"depth",
|
|
81
|
+
"schema",
|
|
62
82
|
"done",
|
|
63
83
|
"context",
|
|
64
84
|
"verify",
|
|
@@ -68,10 +88,12 @@ const KNOWN_FLAGS = new Set([
|
|
|
68
88
|
"worktree",
|
|
69
89
|
"resume",
|
|
70
90
|
"cwd",
|
|
91
|
+
"wait",
|
|
92
|
+
"background",
|
|
71
93
|
]);
|
|
72
94
|
|
|
73
95
|
/** Flags that stand alone; their value is their presence. */
|
|
74
|
-
const BOOLEAN_FLAGS = new Set(["isolated", "worktree"]);
|
|
96
|
+
const BOOLEAN_FLAGS = new Set(["isolated", "worktree", "wait", "background"]);
|
|
75
97
|
|
|
76
98
|
/** Split on whitespace, honouring single and double quotes. */
|
|
77
99
|
function tokenize(input: string): string[] {
|
|
@@ -177,7 +199,14 @@ function booleanFlag(value: string | undefined, fallback: boolean, name: string)
|
|
|
177
199
|
throw new Error(`--${name} takes true or false.`);
|
|
178
200
|
}
|
|
179
201
|
|
|
180
|
-
function emit(
|
|
202
|
+
function emit(
|
|
203
|
+
ctx: ExtensionCommandContext,
|
|
204
|
+
text: string,
|
|
205
|
+
level: "info" | "warning" | "error" = "info",
|
|
206
|
+
write: (line: string) => void = (line) => {
|
|
207
|
+
process.stdout.write(`${line}\n`);
|
|
208
|
+
},
|
|
209
|
+
) {
|
|
181
210
|
if (ctx.mode === "tui" || ctx.mode === "rpc") {
|
|
182
211
|
try {
|
|
183
212
|
ctx.ui.notify(text, level);
|
|
@@ -186,10 +215,13 @@ function emit(ctx: ExtensionCommandContext, text: string, level: "info" | "warni
|
|
|
186
215
|
}
|
|
187
216
|
return;
|
|
188
217
|
}
|
|
189
|
-
|
|
218
|
+
write(text);
|
|
190
219
|
}
|
|
191
220
|
|
|
192
221
|
export function registerDelegateCommand(pi: ExtensionAPI, options: DelegateCommandOptions) {
|
|
222
|
+
/** Every line this command prints, through the sink the host supplied. */
|
|
223
|
+
const emitTo = (ctx: ExtensionCommandContext, text: string, level: "info" | "warning" | "error" = "info"): void =>
|
|
224
|
+
emit(ctx, text, level, options.write);
|
|
193
225
|
const pane = (ctx: ExtensionCommandContext) => {
|
|
194
226
|
try {
|
|
195
227
|
const registry = options.registryFor(ctx);
|
|
@@ -222,24 +254,24 @@ export function registerDelegateCommand(pi: ExtensionAPI, options: DelegateComma
|
|
|
222
254
|
const registry = options.registryFor(ctx);
|
|
223
255
|
const lines = registry.lines();
|
|
224
256
|
if (lines.length === 0) {
|
|
225
|
-
|
|
257
|
+
emitTo(ctx, `No delegations in this session.\n\n${USAGE}`);
|
|
226
258
|
return;
|
|
227
259
|
}
|
|
228
260
|
if (ctx.mode !== "tui") {
|
|
229
|
-
|
|
261
|
+
emitTo(ctx, ["Delegations:", ...lines].join("\n"));
|
|
230
262
|
return;
|
|
231
263
|
}
|
|
232
264
|
const choice = await ctx.ui.select("Delegations", ["(close)", ...lines]);
|
|
233
265
|
if (!choice || choice === "(close)") return;
|
|
234
266
|
const runId = choice.split(" · ")[0];
|
|
235
|
-
|
|
267
|
+
emitTo(ctx, (runId ? registry.describe(runId) : undefined) ?? "No such run.");
|
|
236
268
|
};
|
|
237
269
|
|
|
238
270
|
/** /delegate read: one run in full. */
|
|
239
271
|
const describeTarget = (ctx: ExtensionCommandContext, target: string) => {
|
|
240
272
|
const registry = options.registryFor(ctx);
|
|
241
273
|
const runId = targetRun(registry, target);
|
|
242
|
-
|
|
274
|
+
emitTo(ctx, runId ? (registry.describe(runId) ?? "No such run.") : "No matching run.");
|
|
243
275
|
};
|
|
244
276
|
|
|
245
277
|
/** /delegate log: the tail of the child stderr, read from the end. */
|
|
@@ -248,14 +280,14 @@ export function registerDelegateCommand(pi: ExtensionAPI, options: DelegateComma
|
|
|
248
280
|
const runId = targetRun(registry, target);
|
|
249
281
|
const handle: RunHandle | undefined = runId ? registry.get(runId) : undefined;
|
|
250
282
|
if (!handle) {
|
|
251
|
-
|
|
283
|
+
emitTo(ctx, "No matching run.", "error");
|
|
252
284
|
return;
|
|
253
285
|
}
|
|
254
286
|
try {
|
|
255
287
|
const log = (await readTail(join(handle.runDir, "child.log"), LOG_TAIL_BYTES)).trim();
|
|
256
|
-
|
|
288
|
+
emitTo(ctx, log ? log.split("\n").slice(-40).join("\n") : "(no child stderr)");
|
|
257
289
|
} catch {
|
|
258
|
-
|
|
290
|
+
emitTo(ctx, "(no child log yet)");
|
|
259
291
|
}
|
|
260
292
|
};
|
|
261
293
|
|
|
@@ -269,7 +301,7 @@ export function registerDelegateCommand(pi: ExtensionAPI, options: DelegateComma
|
|
|
269
301
|
const registry = options.registryFor(ctx);
|
|
270
302
|
const running = registry.list().filter((handle) => !handle.outcome);
|
|
271
303
|
if (running.length === 0) {
|
|
272
|
-
|
|
304
|
+
emitTo(ctx, "No running delegations to cancel.");
|
|
273
305
|
return;
|
|
274
306
|
}
|
|
275
307
|
let runIds: string[];
|
|
@@ -281,7 +313,7 @@ export function registerDelegateCommand(pi: ExtensionAPI, options: DelegateComma
|
|
|
281
313
|
} else {
|
|
282
314
|
const runId = resolveId(registry, target);
|
|
283
315
|
if (!runId) {
|
|
284
|
-
|
|
316
|
+
emitTo(ctx, `No matching run: ${target}`, "error");
|
|
285
317
|
return;
|
|
286
318
|
}
|
|
287
319
|
runIds = [runId];
|
|
@@ -289,13 +321,13 @@ export function registerDelegateCommand(pi: ExtensionAPI, options: DelegateComma
|
|
|
289
321
|
const result = await registry.cancelRuns({ runIds });
|
|
290
322
|
pane(ctx);
|
|
291
323
|
for (const outcome of result.outcomes) {
|
|
292
|
-
|
|
324
|
+
emitTo(ctx, formatOutcome(outcome), outcome.status === "aborted" ? "warning" : "info");
|
|
293
325
|
}
|
|
294
|
-
if (result.containment === "leaked")
|
|
326
|
+
if (result.containment === "leaked") emitTo(ctx, "WARNING: some descendants survived the fence.", "error");
|
|
295
327
|
if (result.containment === "unproven") {
|
|
296
|
-
|
|
328
|
+
emitTo(ctx, "Containment unproven: this platform exposes no process table, so absence could not be verified.", "warning");
|
|
297
329
|
}
|
|
298
|
-
if (result.unknown.length > 0)
|
|
330
|
+
if (result.unknown.length > 0) emitTo(ctx, `Unknown runs: ${result.unknown.join(", ")}`, "error");
|
|
299
331
|
};
|
|
300
332
|
|
|
301
333
|
/** /delegate send <id|prefix> <text>: hand a running child one message. */
|
|
@@ -304,17 +336,17 @@ export function registerDelegateCommand(pi: ExtensionAPI, options: DelegateComma
|
|
|
304
336
|
const [target = "", ...rest] = raw.split(/\s+/u);
|
|
305
337
|
const text = rest.join(" ").trim();
|
|
306
338
|
if (!target || !text) {
|
|
307
|
-
|
|
339
|
+
emitTo(ctx, "Usage: /delegate send <id|prefix> <text>", "error");
|
|
308
340
|
return;
|
|
309
341
|
}
|
|
310
342
|
const runId = resolveId(registry, target);
|
|
311
343
|
if (!runId) {
|
|
312
|
-
|
|
344
|
+
emitTo(ctx, `No matching run: ${target}`, "error");
|
|
313
345
|
return;
|
|
314
346
|
}
|
|
315
347
|
const result = registry.send(runId, text);
|
|
316
348
|
pane(ctx);
|
|
317
|
-
|
|
349
|
+
emitTo(
|
|
318
350
|
ctx,
|
|
319
351
|
result.ok
|
|
320
352
|
? `Sent to ${runId}. The child reads it at its next turn start.`
|
|
@@ -323,6 +355,30 @@ export function registerDelegateCommand(pi: ExtensionAPI, options: DelegateComma
|
|
|
323
355
|
);
|
|
324
356
|
};
|
|
325
357
|
|
|
358
|
+
/**
|
|
359
|
+
* /delegate doctor: the installation self-check.
|
|
360
|
+
*
|
|
361
|
+
* A check that cannot run is reported as the failure it is, not as a crash:
|
|
362
|
+
* the command a user runs when nothing works must not be the command that
|
|
363
|
+
* throws.
|
|
364
|
+
*/
|
|
365
|
+
const report = (ctx: ExtensionCommandContext) => {
|
|
366
|
+
if (!options.doctor) {
|
|
367
|
+
emitTo(ctx, "This host did not register the delegate tools, so there is nothing to check.", "error");
|
|
368
|
+
return;
|
|
369
|
+
}
|
|
370
|
+
let text: string;
|
|
371
|
+
let ok = false;
|
|
372
|
+
try {
|
|
373
|
+
const result = options.doctor(ctx);
|
|
374
|
+
text = formatDoctor(result);
|
|
375
|
+
ok = result.ok;
|
|
376
|
+
} catch (error) {
|
|
377
|
+
text = "delegate doctor failed before it could check anything: " + (error as Error).message;
|
|
378
|
+
}
|
|
379
|
+
emitTo(ctx, text, ok ? "info" : "error");
|
|
380
|
+
};
|
|
381
|
+
|
|
326
382
|
/** /delegate <goal> [options]: parse, bound, admit, then report. */
|
|
327
383
|
const start = async (ctx: ExtensionCommandContext, raw: string) => {
|
|
328
384
|
const registry = options.registryFor(ctx);
|
|
@@ -330,24 +386,53 @@ export function registerDelegateCommand(pi: ExtensionAPI, options: DelegateComma
|
|
|
330
386
|
try {
|
|
331
387
|
parsed = parseInvocation(raw);
|
|
332
388
|
} catch (error) {
|
|
333
|
-
|
|
389
|
+
emitTo(ctx, `${(error as Error).message}\n\n${USAGE}`, "error");
|
|
334
390
|
return;
|
|
335
391
|
}
|
|
336
392
|
if (!parsed.goal) {
|
|
337
|
-
|
|
393
|
+
emitTo(ctx, USAGE, "error");
|
|
338
394
|
return;
|
|
339
395
|
}
|
|
340
396
|
|
|
341
397
|
let maxTurns: number;
|
|
342
398
|
let timeoutMinutes: number;
|
|
343
399
|
let maxCostUsd: number;
|
|
400
|
+
let maxDepth: number;
|
|
401
|
+
let resultSchema: Record<string, unknown> | undefined;
|
|
344
402
|
let scope: "session" | "workspace";
|
|
345
403
|
let isolated: boolean;
|
|
346
404
|
let worktree: boolean;
|
|
405
|
+
// Undefined means "whatever the session mode implies": a TUI keeps working
|
|
406
|
+
// and takes the completion message, print mode has nothing else to live for.
|
|
407
|
+
let waitMode: boolean | undefined;
|
|
347
408
|
try {
|
|
409
|
+
if (parsed.flags.background === "true") waitMode = false;
|
|
410
|
+
else if (parsed.flags.wait === "true") waitMode = true;
|
|
348
411
|
maxCostUsd = parsed.flags.cost === undefined
|
|
349
412
|
? (options.defaults.maxCostUsd ?? 0)
|
|
350
413
|
: boundedNumber(parsed.flags.cost, 0, "cost", { min: 0, max: 10_000 });
|
|
414
|
+
maxDepth = boundedNumber(parsed.flags.depth, options.defaults.maxDepth ?? 0, "depth", {
|
|
415
|
+
min: 0,
|
|
416
|
+
max: MAX_MAX_DEPTH,
|
|
417
|
+
integer: true,
|
|
418
|
+
});
|
|
419
|
+
if (parsed.flags.schema === undefined) {
|
|
420
|
+
resultSchema = undefined;
|
|
421
|
+
} else {
|
|
422
|
+
let decoded: unknown;
|
|
423
|
+
try {
|
|
424
|
+
decoded = JSON.parse(parsed.flags.schema);
|
|
425
|
+
} catch (error) {
|
|
426
|
+
throw new Error(`--schema must be valid JSON: ${String(error)}`);
|
|
427
|
+
}
|
|
428
|
+
if (typeof decoded !== "object" || decoded === null || Array.isArray(decoded)) {
|
|
429
|
+
throw new Error("--schema must be a JSON Schema object.");
|
|
430
|
+
}
|
|
431
|
+
const schema = decoded as Record<string, unknown>;
|
|
432
|
+
const problem = auditResultSchema(schema);
|
|
433
|
+
if (problem) throw new Error(problem.startsWith("resultSchema") ? problem.replace("resultSchema", "--schema") : problem);
|
|
434
|
+
resultSchema = schema;
|
|
435
|
+
}
|
|
351
436
|
worktree = booleanFlag(parsed.flags.worktree, false, "worktree");
|
|
352
437
|
maxTurns = boundedNumber(parsed.flags.turns, options.defaults.maxTurns, "turns", {
|
|
353
438
|
min: 1,
|
|
@@ -365,7 +450,7 @@ export function registerDelegateCommand(pi: ExtensionAPI, options: DelegateComma
|
|
|
365
450
|
scope = requestedScope === "workspace" ? "workspace" : "session";
|
|
366
451
|
isolated = booleanFlag(parsed.flags.isolated, false, "isolated");
|
|
367
452
|
} catch (error) {
|
|
368
|
-
|
|
453
|
+
emitTo(ctx, (error as Error).message, "error");
|
|
369
454
|
return;
|
|
370
455
|
}
|
|
371
456
|
|
|
@@ -381,6 +466,8 @@ export function registerDelegateCommand(pi: ExtensionAPI, options: DelegateComma
|
|
|
381
466
|
maxTurns,
|
|
382
467
|
timeoutMinutes,
|
|
383
468
|
maxCostUsd,
|
|
469
|
+
maxDepth,
|
|
470
|
+
resultSchema,
|
|
384
471
|
model: parsed.flags.model,
|
|
385
472
|
tools: parsed.flags.tools,
|
|
386
473
|
cwd: runCwd,
|
|
@@ -388,28 +475,31 @@ export function registerDelegateCommand(pi: ExtensionAPI, options: DelegateComma
|
|
|
388
475
|
isolated,
|
|
389
476
|
worktree,
|
|
390
477
|
resumeFrom: parsed.flags.resume,
|
|
478
|
+
// The command waits on `handle.done` when it waits at all, so the
|
|
479
|
+
// registry's own admission window would only delay the first draw.
|
|
480
|
+
inlineSettleMs: 0,
|
|
391
481
|
onProgress: () => pane(ctx),
|
|
392
482
|
});
|
|
393
483
|
pane(ctx);
|
|
394
|
-
|
|
484
|
+
emitTo(
|
|
395
485
|
ctx,
|
|
396
486
|
[
|
|
397
487
|
`delegate started · ${handle.runId}`,
|
|
398
488
|
`Goal: ${shortGoal(parsed.goal, 90)}`,
|
|
399
|
-
`Budget: ${maxTurns} turns, ${timeoutMinutes} minutes, scope ${scope}${isolated ? ", isolated" : ""}${worktree ? ", own worktree" : ""}${maxCostUsd > 0 ? `, \$${maxCostUsd} cap` : ""}`,
|
|
489
|
+
`Budget: ${maxTurns} turns, ${timeoutMinutes} minutes, depth ${maxDepth}, scope ${scope}${isolated ? ", isolated" : ""}${worktree ? ", own worktree" : ""}${maxCostUsd > 0 ? `, \$${maxCostUsd} cap` : ""}`,
|
|
400
490
|
"The result is posted into this session when the child settles.",
|
|
401
491
|
].join("\n"),
|
|
402
492
|
);
|
|
403
493
|
|
|
404
|
-
if (ctx.mode
|
|
494
|
+
if (!(waitMode ?? ctx.mode !== "tui")) {
|
|
405
495
|
// Nothing keeps a print-mode process alive for a session-scoped run, so
|
|
406
|
-
// only the interactive path returns immediately.
|
|
496
|
+
// only the interactive path returns immediately by default.
|
|
407
497
|
void handle.done.then(() => pane(ctx));
|
|
408
498
|
return;
|
|
409
499
|
}
|
|
410
500
|
const outcome = await handle.done;
|
|
411
501
|
pane(ctx);
|
|
412
|
-
|
|
502
|
+
emitTo(ctx, formatOutcome(outcome), outcome.status === "complete" ? "info" : "warning");
|
|
413
503
|
};
|
|
414
504
|
|
|
415
505
|
pi.registerCommand("delegate", {
|
|
@@ -421,6 +511,7 @@ export function registerDelegateCommand(pi: ExtensionAPI, options: DelegateComma
|
|
|
421
511
|
{ value: "log", label: "log", description: "Tail the child output of one run" },
|
|
422
512
|
{ value: "send", label: "send", description: "Send a message to a running run" },
|
|
423
513
|
{ value: "cancel", label: "cancel", description: "Cancel runs" },
|
|
514
|
+
{ value: "doctor", label: "doctor", description: "Check this installation and report what is wrong" },
|
|
424
515
|
];
|
|
425
516
|
const filtered = items.filter((item) => item.value.startsWith(prefix));
|
|
426
517
|
return filtered.length > 0 ? filtered : null;
|
|
@@ -439,6 +530,7 @@ export function registerDelegateCommand(pi: ExtensionAPI, options: DelegateComma
|
|
|
439
530
|
if (first === "log") return tailLog(ctx, raw.slice("log".length).trim());
|
|
440
531
|
if (first === "cancel") return cancelTarget(ctx, raw.slice("cancel".length).trim());
|
|
441
532
|
if (first === "send") return sendTarget(ctx, raw.slice("send".length).trim());
|
|
533
|
+
if (first === "doctor") return report(ctx);
|
|
442
534
|
return start(ctx, raw);
|
|
443
535
|
},
|
|
444
536
|
});
|