@maheidem/pi-delegate 0.3.2 → 0.6.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/README.md +63 -0
- package/application.ts +203 -69
- package/commands.ts +12 -1
- package/config.ts +29 -0
- package/index.ts +503 -28
- package/mode.ts +2 -2
- package/package.json +1 -1
- package/run-store.ts +7 -0
- package/runner.ts +97 -4
- package/types.ts +59 -1
- package/ui/format.ts +36 -8
- package/ui/panel-frame.ts +126 -0
- package/ui/peek-view.ts +34 -5
- package/ui/running-view.ts +55 -10
- package/ui/tool-card.ts +129 -0
- package/ui/version.ts +69 -0
- package/version.ts +9 -13
package/README.md
CHANGED
|
@@ -150,6 +150,69 @@ Consequences worth internalizing:
|
|
|
150
150
|
than blamed on the provider, and the stderr tail is no longer presented as
|
|
151
151
|
the cause.
|
|
152
152
|
|
|
153
|
+
### Background delegation (v0.5.0, R8–R15)
|
|
154
|
+
|
|
155
|
+
`delegate({ background: true, description: "…" })` runs the delegation
|
|
156
|
+
**asynchronously**: the tool call returns a runId immediately, the parent turn
|
|
157
|
+
continues, and the terminal report is delivered later as a message that wakes
|
|
158
|
+
an idle parent (`deliverAs: "steer"`, `triggerTurn: true`) or steers a busy
|
|
159
|
+
one. The envelope explicitly tells the parent model to treat reports as
|
|
160
|
+
internal work events.
|
|
161
|
+
|
|
162
|
+
- **Concurrency**: up to `maxBackgroundRuns` (default 3, clamp 1–8, dashboard +
|
|
163
|
+
project overlay) children run **in parallel**, separate from the foreground
|
|
164
|
+
one-child queue. Overflow fails fast with `E_BACKGROUND_FULL` — background
|
|
165
|
+
calls are never queued.
|
|
166
|
+
- **`description`** is required (3–6 words, single line) and rides every header.
|
|
167
|
+
- **Model surface**: the `delegate_status` tool lists live background runs
|
|
168
|
+
(slots, phase, elapsed, in-flight tool) and per-run detail with the activity
|
|
169
|
+
tail, handoff preview, and the `resumeFrom` hint for interrupted runs.
|
|
170
|
+
`/delegate status` prints the same inventory; the dashboard gains a
|
|
171
|
+
**Background runs** section and the footer shows `▴Nbg`.
|
|
172
|
+
- **Ownership + delivery** (pi-async-fork pattern, no daemon): `delegate.background`
|
|
173
|
+
custom entries in the session JSONL are the branch-scoped ledger; terminal
|
|
174
|
+
delivery is at-least-once with details-scan dedup; a restart reconciles the
|
|
175
|
+
branch, re-delivers undelivered terminals exactly once, reports runs owned
|
|
176
|
+
by other live sessions, and turns dead-pid orphans into resumable
|
|
177
|
+
interrupted reports. Branch switches pause delivery; the extension never
|
|
178
|
+
delivers into a session the run's branch doesn't own.
|
|
179
|
+
- **Rendered results**: delivered reports render as neutral glyph+word cards
|
|
180
|
+
(`✓ completed / ⚠ failed / ⏱ timed out / ⊘ cancelled`) with the model-only
|
|
181
|
+
classification sentence stripped from display.
|
|
182
|
+
- Headless note: background works, but a `pi -p` process exit kills in-flight
|
|
183
|
+
children — receipts finalize interrupted/resumable. Prefer foreground for
|
|
184
|
+
one-shot headless flows.
|
|
185
|
+
|
|
186
|
+
### Bidirectional channels (v0.6.0, R16–R19)
|
|
187
|
+
|
|
188
|
+
Background children are a team, not batch jobs — three channels, all auditable
|
|
189
|
+
from the session JSONL:
|
|
190
|
+
|
|
191
|
+
- **`delegate_send({ runId, message })`** — steer a live background run. The
|
|
192
|
+
message is written to the child as an RPC `follow_up` record (pi steering
|
|
193
|
+
semantics: queued before the child's next model call, never interrupts).
|
|
194
|
+
Steering re-arms the idle watchdog; terminal runs point at `resumeFrom`.
|
|
195
|
+
- **`ask_parent(kind: "question")`** (child-side tool, background children
|
|
196
|
+
ONLY — a foreground child asking would deadlock the parent turn by
|
|
197
|
+
construction, enforced at tool registration). The child's tool call IS the
|
|
198
|
+
blocking primitive: it polls `$PI_DELEGATE_ASK_DIR/<toolCallId>.json` until
|
|
199
|
+
the parent answers via **`delegate_answer({ runId, answer })`** — which any
|
|
200
|
+
model turn can call, and the question's `triggerTurn` wake makes the parent
|
|
201
|
+
answer autonomously. While a question is open, the runner suspends the
|
|
202
|
+
idle/stuck watchdogs (the hard cap still applies). On timeout (config
|
|
203
|
+
`askParent.timeoutMs`, default 10 m) the tool returns the exact fallback
|
|
204
|
+
“proceed with your best judgment and state the assumption” — the child is
|
|
205
|
+
never wedged. `askParent.maxPerRun` (default 5) bounds round-trips.
|
|
206
|
+
- **`ask_parent(kind: "note")`** — non-blocking notes (risk/observation/
|
|
207
|
+
concern) delivered as `delegate-child-note` messages with
|
|
208
|
+
`triggerTurn: false`: notes NEVER wake an idle parent. Capped at 20/run.
|
|
209
|
+
|
|
210
|
+
Questions render as `? … asks` cards, notes as `ℹ … note`; `/delegate status`
|
|
211
|
+
lists pending questions. In strict mode the active set is
|
|
212
|
+
`delegate, delegate_status, delegate_send, delegate_answer` — answering your
|
|
213
|
+
own children is coordination, not substantive work (a strict session that
|
|
214
|
+
cannot answer is a deadlock farm).
|
|
215
|
+
|
|
153
216
|
### Concurrent calls queue (fan-out just works)
|
|
154
217
|
|
|
155
218
|
Models naturally issue several `delegate` calls in one turn. Pi executes
|
package/application.ts
CHANGED
|
@@ -33,12 +33,16 @@ import type {
|
|
|
33
33
|
RunStreamUpdate,
|
|
34
34
|
TranscriptRecordV1,
|
|
35
35
|
SessionEntryLike,
|
|
36
|
+
BackgroundRunHandle,
|
|
37
|
+
RunState,
|
|
38
|
+
RunTerminalState,
|
|
36
39
|
} from "./types.ts";
|
|
37
40
|
import { FeedRing, type FeedEvent } from "./transcript-feed.ts";
|
|
38
|
-
import { decodeTranscriptRecord } from "./types.ts";
|
|
41
|
+
import { decodeTranscriptRecord, isTerminalRunState } from "./types.ts";
|
|
39
42
|
import { applyProjectOverlay, clampConfigField, formatDuration, normalizeConfig, parseDuration, projectConfigPath, resolveRunTimeouts, saveConfig, saveProjectConfig, type DelegateConfigV1 } from "./config.ts";
|
|
40
43
|
import { EMPTY_USAGE } from "./types.ts";
|
|
41
44
|
import { isRoleName, resolveRole, rolePromptExists, DELEGATE_ROLES } from "./roles.ts";
|
|
45
|
+
import type { DelegateRole } from "./types.ts";
|
|
42
46
|
import {
|
|
43
47
|
replayModeEntries,
|
|
44
48
|
applyReplayToRuntime,
|
|
@@ -55,6 +59,7 @@ import {
|
|
|
55
59
|
enforceRetention,
|
|
56
60
|
runPaths,
|
|
57
61
|
pathsForAgentDir,
|
|
62
|
+
type OpenedRun,
|
|
58
63
|
} from "./run-store.ts";
|
|
59
64
|
import { DelegateRunner, resolvePiInvocation, type PiInvocationResolver } from "./runner.ts";
|
|
60
65
|
import { validateTask } from "./commands.ts";
|
|
@@ -118,6 +123,8 @@ export class DelegateApplicationImpl implements DelegateApplication {
|
|
|
118
123
|
private activeStream: RunStreamUpdate | null = null;
|
|
119
124
|
private activeRing: FeedRing = new FeedRing(120);
|
|
120
125
|
private runQueue: QueuedRun[] = [];
|
|
126
|
+
/** R14: live stream capture for background runs spawned by this process. */
|
|
127
|
+
private backgroundStreams = new Map<string, { ring: FeedRing; latest: RunStreamUpdate | null }>();
|
|
121
128
|
private readonly modeRuntime: ModeRuntime;
|
|
122
129
|
private readonly ports: DelegateApplicationPorts;
|
|
123
130
|
private liveConfig: DelegateConfigV1;
|
|
@@ -279,7 +286,167 @@ export class DelegateApplicationImpl implements DelegateApplication {
|
|
|
279
286
|
|
|
280
287
|
/** Execute one run in the free slot (reservation stays synchronous). */
|
|
281
288
|
private async startRun(request: DelegateRequest, hooks: RunHooks = {}): Promise<RunAttemptResult> {
|
|
289
|
+
const prepared = this.prepareRun(request);
|
|
290
|
+
if ("error" in prepared) return prepared.error;
|
|
291
|
+
const { opened, role, task, model, cfg, timeoutInfo, modelNote, resumeOf, sessionPath, sessionDir } = prepared;
|
|
292
|
+
const agentDir = this.ports.agentDir;
|
|
293
|
+
|
|
294
|
+
// 8. Reservation NOW covers the child lifecycle.
|
|
295
|
+
// Capture live state for the home dashboard while forwarding the caller's hooks.
|
|
296
|
+
this.activeStream = null;
|
|
297
|
+
this.activeRing = new FeedRing(120);
|
|
298
|
+
const captureHooks: RunHooks = {
|
|
299
|
+
...hooks,
|
|
300
|
+
onUpdate: (u: RunStreamUpdate) => {
|
|
301
|
+
this.activeStream = u;
|
|
302
|
+
hooks.onUpdate?.(u);
|
|
303
|
+
},
|
|
304
|
+
onEvent: (e: FeedEvent) => {
|
|
305
|
+
this.activeRing.push(e);
|
|
306
|
+
hooks.onEvent?.(e);
|
|
307
|
+
},
|
|
308
|
+
};
|
|
309
|
+
const runner = new DelegateRunner(
|
|
310
|
+
opened,
|
|
311
|
+
{
|
|
312
|
+
agentDir,
|
|
313
|
+
role,
|
|
314
|
+
task,
|
|
315
|
+
runId: opened.metadata.runId,
|
|
316
|
+
parentModel: model,
|
|
317
|
+
thinkingLevel: request.thinkingLevel,
|
|
318
|
+
cwd: request.cwd,
|
|
319
|
+
projectTrusted: request.projectTrusted,
|
|
320
|
+
registeredTools: this.lastRegisteredTools,
|
|
321
|
+
...(resumeOf ? { resumeOf } : {}),
|
|
322
|
+
...(sessionPath ? { sessionPath } : {}),
|
|
323
|
+
...(sessionDir ? { sessionDir } : {}),
|
|
324
|
+
},
|
|
325
|
+
cfg,
|
|
326
|
+
captureHooks,
|
|
327
|
+
this.ports.resolveInvocation ?? resolvePiInvocation,
|
|
328
|
+
);
|
|
329
|
+
const reservation: ActiveRunReservation = {
|
|
330
|
+
id: opened.metadata.runId,
|
|
331
|
+
role: role.name,
|
|
332
|
+
runner,
|
|
333
|
+
startedAt: opened.metadata.createdAt,
|
|
334
|
+
hardMs: cfg.hardTimeoutMs,
|
|
335
|
+
};
|
|
336
|
+
this.activeRun = reservation;
|
|
337
|
+
|
|
338
|
+
try {
|
|
339
|
+
const outcome = await runner.run();
|
|
340
|
+
this.activeRun = null;
|
|
341
|
+
// Retention after terminal finalization (best-effort).
|
|
342
|
+
try {
|
|
343
|
+
enforceRetention(agentDir, cfg.maxRuns, cfg.maxRunAgeDays, undefined);
|
|
344
|
+
} catch {
|
|
345
|
+
// cleanup failure is warning-only
|
|
346
|
+
}
|
|
347
|
+
return outcomeToRunResult(outcome, opened.metadata, role.name, model, request.thinkingLevel, { timeoutInfo, modelNote });
|
|
348
|
+
} catch (error) {
|
|
349
|
+
this.activeRun = null;
|
|
350
|
+
return errorResult(opened.metadata.runId, role.name, "E_CHILD_EXIT", `Delegation failed unexpectedly: ${(error as Error).message}`);
|
|
351
|
+
} finally {
|
|
352
|
+
this.startNextQueuedRun();
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
/** R8: spawn a background run — same validation and spawn path as the
|
|
356
|
+
* foreground, but no slot reservation, no queue, and the caller gets a
|
|
357
|
+
* live handle instead of the terminal result. */
|
|
358
|
+
runBackground(request: DelegateRequest, hooks: { onAsk?: RunHooks["onAsk"] } = {}): { error: DelegateRunResult } | { handle: BackgroundRunHandle } {
|
|
359
|
+
const prepared = this.prepareRun(request);
|
|
360
|
+
if ("error" in prepared) return { error: prepared.error };
|
|
361
|
+
const { opened, role, task, model, cfg, timeoutInfo, modelNote, resumeOf, sessionPath, sessionDir } = prepared;
|
|
362
|
+
const agentDir = this.ports.agentDir;
|
|
363
|
+
// R17: ask channel plumbing — answers dir + budget env for the child.
|
|
364
|
+
const askEnabled = this.liveConfig.askParent?.enabled !== false;
|
|
365
|
+
const askDir = askEnabled ? path.join(opened.paths.runsDir, "answers", opened.metadata.runId) : undefined;
|
|
366
|
+
const askTimeoutMs = askEnabled ? (this.liveConfig.askParent?.timeoutMs ?? 600_000) : undefined;
|
|
367
|
+
const askMaxQuestions = askEnabled ? (this.liveConfig.askParent?.maxPerRun ?? 5) : undefined;
|
|
368
|
+
// R14: capture the live stream for status/dashboard surfaces.
|
|
369
|
+
const ring = new FeedRing(120);
|
|
370
|
+
const streamEntry = { ring, latest: null as RunStreamUpdate | null };
|
|
371
|
+
const runner = new DelegateRunner(
|
|
372
|
+
opened,
|
|
373
|
+
{
|
|
374
|
+
agentDir,
|
|
375
|
+
role,
|
|
376
|
+
task,
|
|
377
|
+
runId: opened.metadata.runId,
|
|
378
|
+
parentModel: model,
|
|
379
|
+
thinkingLevel: request.thinkingLevel,
|
|
380
|
+
cwd: request.cwd,
|
|
381
|
+
projectTrusted: request.projectTrusted,
|
|
382
|
+
registeredTools: this.lastRegisteredTools,
|
|
383
|
+
...(resumeOf ? { resumeOf } : {}),
|
|
384
|
+
...(sessionPath ? { sessionPath } : {}),
|
|
385
|
+
...(sessionDir ? { sessionDir } : {}),
|
|
386
|
+
...(askDir && askTimeoutMs ? { background: true, askDir, askTimeoutMs, ...(askMaxQuestions ? { askMaxQuestions } : {}) } : {}),
|
|
387
|
+
},
|
|
388
|
+
cfg,
|
|
389
|
+
{
|
|
390
|
+
onUpdate: (u: RunStreamUpdate) => {
|
|
391
|
+
streamEntry.latest = u;
|
|
392
|
+
},
|
|
393
|
+
onEvent: (e: FeedEvent) => {
|
|
394
|
+
ring.push(e);
|
|
395
|
+
},
|
|
396
|
+
...(hooks.onAsk ? { onAsk: hooks.onAsk } : {}),
|
|
397
|
+
},
|
|
398
|
+
this.ports.resolveInvocation ?? resolvePiInvocation,
|
|
399
|
+
);
|
|
400
|
+
this.backgroundStreams.set(opened.metadata.runId, streamEntry);
|
|
401
|
+
const completion = runner.run().then(
|
|
402
|
+
(outcome) => {
|
|
403
|
+
this.backgroundStreams.delete(opened.metadata.runId);
|
|
404
|
+
try {
|
|
405
|
+
enforceRetention(agentDir, cfg.maxRuns, cfg.maxRunAgeDays, undefined);
|
|
406
|
+
} catch {
|
|
407
|
+
// cleanup failure is warning-only
|
|
408
|
+
}
|
|
409
|
+
return outcomeToRunResult(outcome, opened.metadata, role.name, model, request.thinkingLevel, { timeoutInfo, modelNote });
|
|
410
|
+
},
|
|
411
|
+
(error: unknown) => {
|
|
412
|
+
this.backgroundStreams.delete(opened.metadata.runId);
|
|
413
|
+
return errorResult(opened.metadata.runId, role.name, "E_CHILD_EXIT", `Delegation failed unexpectedly: ${(error as Error).message}`);
|
|
414
|
+
},
|
|
415
|
+
);
|
|
416
|
+
return {
|
|
417
|
+
handle: {
|
|
418
|
+
runId: opened.metadata.runId,
|
|
419
|
+
role: role.name,
|
|
420
|
+
description: request.description ?? "",
|
|
421
|
+
cancel: (reason?: string) => runner.cancel((reason ?? "cancelled") as "cancelled"),
|
|
422
|
+
steer: (message: string) => runner.steer(message),
|
|
423
|
+
...(askDir
|
|
424
|
+
? {
|
|
425
|
+
writeAnswer: (toolCallId: string, payload: { answeredBy: "model" | "user"; answeredAt: string; answer: string }) =>
|
|
426
|
+
runner.writeAskAnswer(toolCallId, payload),
|
|
427
|
+
}
|
|
428
|
+
: {}),
|
|
429
|
+
completion,
|
|
430
|
+
},
|
|
431
|
+
};
|
|
432
|
+
}
|
|
282
433
|
|
|
434
|
+
/** Validation + open (steps 1–7) shared by the foreground and background
|
|
435
|
+
* spawn paths. Returns a terminal error result or the prepared context. */
|
|
436
|
+
private prepareRun(request: DelegateRequest):
|
|
437
|
+
| { error: DelegateRunResult }
|
|
438
|
+
| {
|
|
439
|
+
opened: OpenedRun;
|
|
440
|
+
role: DelegateRole;
|
|
441
|
+
task: string;
|
|
442
|
+
model: string;
|
|
443
|
+
cfg: DelegateConfigV1;
|
|
444
|
+
timeoutInfo: string;
|
|
445
|
+
modelNote: string | undefined;
|
|
446
|
+
resumeOf: string | undefined;
|
|
447
|
+
sessionPath: string | undefined;
|
|
448
|
+
sessionDir: string | undefined;
|
|
449
|
+
} {
|
|
283
450
|
const agentDir = this.ports.agentDir;
|
|
284
451
|
// Config cascade: project .pi/delegate/config.json overlays the
|
|
285
452
|
// user-wide (live) config per run; missing file = live config.
|
|
@@ -320,26 +487,26 @@ export class DelegateApplicationImpl implements DelegateApplication {
|
|
|
320
487
|
// 2. Validate task (line endings, blank, byte limit).
|
|
321
488
|
const taskResult = validateTask(request.task, cfg.maxTaskBytes);
|
|
322
489
|
if (typeof taskResult !== "string") {
|
|
323
|
-
return errorResult("", isRoleName(request.role) ? request.role : "general", "E_INVALID_TASK", `Task invalid: ${taskResult.error}`);
|
|
490
|
+
return { error: errorResult("", isRoleName(request.role) ? request.role : "general", "E_INVALID_TASK", `Task invalid: ${taskResult.error}`) };
|
|
324
491
|
}
|
|
325
492
|
const task = taskResult;
|
|
326
493
|
|
|
327
494
|
// 3. Role (closed catalogue).
|
|
328
495
|
if (!isRoleName(request.role)) {
|
|
329
|
-
return errorResult("", "general", "E_INVALID_ROLE", `Unknown role '${String(request.role)}'. Use 'general' or 'research'.`);
|
|
496
|
+
return { error: errorResult("", "general", "E_INVALID_ROLE", `Unknown role '${String(request.role)}'. Use 'general' or 'research'.`) };
|
|
330
497
|
}
|
|
331
498
|
const role = resolveRole(request.role, cfg.defaultRole);
|
|
332
499
|
|
|
333
500
|
// 4. Project trust for the write-capable general role.
|
|
334
501
|
if (role.name === "general" && !request.projectTrusted) {
|
|
335
|
-
return errorResult("", role.name, "E_PROJECT_UNTRUSTED", "Project is not trusted; a write-capable child cannot run. Approve trust or use the research role.");
|
|
502
|
+
return { error: errorResult("", role.name, "E_PROJECT_UNTRUSTED", "Project is not trusted; a write-capable child cannot run. Approve trust or use the research role.") };
|
|
336
503
|
}
|
|
337
504
|
|
|
338
505
|
// 5. Model resolution (R5): an explicit `model` pin wins; otherwise
|
|
339
506
|
// the parent's current model is inherited as before.
|
|
340
507
|
const model = request.model?.trim() || request.parentModel?.trim();
|
|
341
508
|
if (!model) {
|
|
342
|
-
return errorResult("", role.name, "E_MODEL_UNAVAILABLE", "No parent model available to inherit. Select or configure a model, or pass an explicit child model.");
|
|
509
|
+
return { error: errorResult("", role.name, "E_MODEL_UNAVAILABLE", "No parent model available to inherit. Select or configure a model, or pass an explicit child model.") };
|
|
343
510
|
}
|
|
344
511
|
const modelNote = request.model?.trim() && request.model!.trim() !== request.parentModel?.trim()
|
|
345
512
|
? `child model pinned to ${request.model!.trim()} (parent model ${request.parentModel || "none"} not inherited)`
|
|
@@ -351,10 +518,10 @@ export class DelegateApplicationImpl implements DelegateApplication {
|
|
|
351
518
|
if (request.resumeFrom) {
|
|
352
519
|
const prior = readRunMetadata(agentDir, request.resumeFrom);
|
|
353
520
|
if (!prior) {
|
|
354
|
-
return errorResult("", role.name, "E_STORE", `resumeFrom: no receipt for run ${request.resumeFrom}.`);
|
|
521
|
+
return { error: errorResult("", role.name, "E_STORE", `resumeFrom: no receipt for run ${request.resumeFrom}.`) };
|
|
355
522
|
}
|
|
356
523
|
if (!prior.sessionPath || !fs.existsSync(prior.sessionPath)) {
|
|
357
|
-
return errorResult("", role.name, "E_STORE", `resumeFrom: run ${request.resumeFrom} has no durable child session on disk (pre-0.2.0 runs are not resumable).`);
|
|
524
|
+
return { error: errorResult("", role.name, "E_STORE", `resumeFrom: run ${request.resumeFrom} has no durable child session on disk (pre-0.2.0 runs are not resumable).`) };
|
|
358
525
|
}
|
|
359
526
|
resumeOf = prior.runId;
|
|
360
527
|
sessionPath = prior.sessionPath;
|
|
@@ -362,7 +529,7 @@ export class DelegateApplicationImpl implements DelegateApplication {
|
|
|
362
529
|
|
|
363
530
|
// 6. Role prompt readability.
|
|
364
531
|
if (!rolePromptExists(role)) {
|
|
365
|
-
return errorResult("", role.name, "E_STORE", `Role prompt asset is unreadable for role '${role.name}'.`);
|
|
532
|
+
return { error: errorResult("", role.name, "E_STORE", `Role prompt asset is unreadable for role '${role.name}'.`) };
|
|
366
533
|
}
|
|
367
534
|
|
|
368
535
|
// 7. Open run store entry (atomic, 0700/0600).
|
|
@@ -370,7 +537,7 @@ export class DelegateApplicationImpl implements DelegateApplication {
|
|
|
370
537
|
try {
|
|
371
538
|
opened = openRun(agentDir, { ...request, task, role: role.name });
|
|
372
539
|
} catch (error) {
|
|
373
|
-
return errorResult("", role.name, "E_STORE", `Run store could not initialize: ${(error as Error).message}`);
|
|
540
|
+
return { error: errorResult("", role.name, "E_STORE", `Run store could not initialize: ${(error as Error).message}`) };
|
|
374
541
|
}
|
|
375
542
|
|
|
376
543
|
// R3: durable session storage for new runs (resumed runs re-enter
|
|
@@ -384,66 +551,7 @@ export class DelegateApplicationImpl implements DelegateApplication {
|
|
|
384
551
|
}
|
|
385
552
|
}
|
|
386
553
|
|
|
387
|
-
|
|
388
|
-
// Capture live state for the home dashboard while forwarding the caller's hooks.
|
|
389
|
-
this.activeStream = null;
|
|
390
|
-
this.activeRing = new FeedRing(120);
|
|
391
|
-
const captureHooks: RunHooks = {
|
|
392
|
-
...hooks,
|
|
393
|
-
onUpdate: (u: RunStreamUpdate) => {
|
|
394
|
-
this.activeStream = u;
|
|
395
|
-
hooks.onUpdate?.(u);
|
|
396
|
-
},
|
|
397
|
-
onEvent: (e: FeedEvent) => {
|
|
398
|
-
this.activeRing.push(e);
|
|
399
|
-
hooks.onEvent?.(e);
|
|
400
|
-
},
|
|
401
|
-
};
|
|
402
|
-
const runner = new DelegateRunner(
|
|
403
|
-
opened,
|
|
404
|
-
{
|
|
405
|
-
agentDir,
|
|
406
|
-
role,
|
|
407
|
-
task,
|
|
408
|
-
runId: opened.metadata.runId,
|
|
409
|
-
parentModel: model,
|
|
410
|
-
thinkingLevel: request.thinkingLevel,
|
|
411
|
-
cwd: request.cwd,
|
|
412
|
-
projectTrusted: request.projectTrusted,
|
|
413
|
-
registeredTools: this.lastRegisteredTools,
|
|
414
|
-
...(resumeOf ? { resumeOf } : {}),
|
|
415
|
-
...(sessionPath ? { sessionPath } : {}),
|
|
416
|
-
...(sessionDir ? { sessionDir } : {}),
|
|
417
|
-
},
|
|
418
|
-
cfg,
|
|
419
|
-
captureHooks,
|
|
420
|
-
this.ports.resolveInvocation ?? resolvePiInvocation,
|
|
421
|
-
);
|
|
422
|
-
const reservation: ActiveRunReservation = {
|
|
423
|
-
id: opened.metadata.runId,
|
|
424
|
-
role: role.name,
|
|
425
|
-
runner,
|
|
426
|
-
startedAt: opened.metadata.createdAt,
|
|
427
|
-
hardMs: timeouts.hardMs,
|
|
428
|
-
};
|
|
429
|
-
this.activeRun = reservation;
|
|
430
|
-
|
|
431
|
-
try {
|
|
432
|
-
const outcome = await runner.run();
|
|
433
|
-
this.activeRun = null;
|
|
434
|
-
// Retention after terminal finalization (best-effort).
|
|
435
|
-
try {
|
|
436
|
-
enforceRetention(agentDir, cfg.maxRuns, cfg.maxRunAgeDays, undefined);
|
|
437
|
-
} catch {
|
|
438
|
-
// cleanup failure is warning-only
|
|
439
|
-
}
|
|
440
|
-
return outcomeToRunResult(outcome, opened.metadata, role.name, model, request.thinkingLevel, { timeoutInfo, modelNote });
|
|
441
|
-
} catch (error) {
|
|
442
|
-
this.activeRun = null;
|
|
443
|
-
return errorResult(opened.metadata.runId, role.name, "E_CHILD_EXIT", `Delegation failed unexpectedly: ${(error as Error).message}`);
|
|
444
|
-
} finally {
|
|
445
|
-
this.startNextQueuedRun();
|
|
446
|
-
}
|
|
554
|
+
return { opened, role, task, model, cfg, timeoutInfo, modelNote, resumeOf, sessionPath, sessionDir };
|
|
447
555
|
}
|
|
448
556
|
|
|
449
557
|
/** Queued-call introspection for status views. */
|
|
@@ -455,6 +563,32 @@ export class DelegateApplicationImpl implements DelegateApplication {
|
|
|
455
563
|
return this.liveConfig.queueLimit;
|
|
456
564
|
}
|
|
457
565
|
|
|
566
|
+
/** R9: live background slot limit. */
|
|
567
|
+
backgroundLimit(): number {
|
|
568
|
+
return this.liveConfig.maxBackgroundRuns;
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
/** R14: live stream of a background run spawned by this process. */
|
|
572
|
+
getBackgroundStream(runId: string): { update: RunStreamUpdate | null; events: readonly FeedEvent[] } | null {
|
|
573
|
+
const s = this.backgroundStreams.get(runId);
|
|
574
|
+
if (!s) return null;
|
|
575
|
+
return { update: s.latest, events: s.ring.all() };
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
/** R14: recent background runs (terminal, newest-first). */
|
|
579
|
+
backgroundRecentRuns(limit = 3): Array<{ runId: string; role: RoleName; description?: string; state: RunTerminalState; durationMs?: number }> {
|
|
580
|
+
return listRuns(this.ports.agentDir, 20)
|
|
581
|
+
.filter((r) => r.background && isTerminalRunState(r.state))
|
|
582
|
+
.slice(0, limit)
|
|
583
|
+
.map((r) => ({
|
|
584
|
+
runId: r.runId,
|
|
585
|
+
role: r.role,
|
|
586
|
+
...(r.description ? { description: r.description } : {}),
|
|
587
|
+
state: r.state as RunTerminalState,
|
|
588
|
+
...(r.durationMs !== undefined ? { durationMs: r.durationMs } : {}),
|
|
589
|
+
}));
|
|
590
|
+
}
|
|
591
|
+
|
|
458
592
|
/** Pop the next queued run (if any) into the free slot, fire-and-forget. */
|
|
459
593
|
private startNextQueuedRun(): void {
|
|
460
594
|
const next = this.runQueue.shift();
|
package/commands.ts
CHANGED
|
@@ -18,6 +18,7 @@ export type DelegateIntent =
|
|
|
18
18
|
| { kind: "doctor" }
|
|
19
19
|
| { kind: "help" }
|
|
20
20
|
| { kind: "cancel"; runId?: string }
|
|
21
|
+
| { kind: "answer"; runId: string; text: string }
|
|
21
22
|
| { kind: "inspect"; runId?: string }
|
|
22
23
|
| { kind: "resume"; runId?: string; task: string; timeoutMs?: number }
|
|
23
24
|
| { kind: "peek"; runId?: string }
|
|
@@ -51,6 +52,7 @@ export const RESERVED_FIRST_TOKENS = new Set([
|
|
|
51
52
|
"doctor",
|
|
52
53
|
"help",
|
|
53
54
|
"cancel",
|
|
55
|
+
"answer",
|
|
54
56
|
"inspect",
|
|
55
57
|
"resume",
|
|
56
58
|
"peek",
|
|
@@ -93,6 +95,15 @@ export function parseDelegateCommand(input: string, options: ParseOptions = {}):
|
|
|
93
95
|
const rest = trimmed.slice("cancel".length).trim();
|
|
94
96
|
return { kind: "cancel", runId: rest || undefined };
|
|
95
97
|
}
|
|
98
|
+
case "answer": {
|
|
99
|
+
// R19: /delegate answer <run-id> <answer text...>
|
|
100
|
+
const rest = trimmed.slice("answer".length).trim();
|
|
101
|
+
const space = rest.indexOf(" ");
|
|
102
|
+
if (space <= 0 || !rest.slice(space + 1).trim()) {
|
|
103
|
+
return { kind: "invalid", token: "answer", usage: "/delegate answer <run-id> <answer text…>" };
|
|
104
|
+
}
|
|
105
|
+
return { kind: "answer", runId: rest.slice(0, space), text: rest.slice(space + 1).trim() };
|
|
106
|
+
}
|
|
96
107
|
case "inspect": {
|
|
97
108
|
const rest = trimmed.slice("inspect".length).trim();
|
|
98
109
|
return { kind: "inspect", runId: rest || undefined };
|
|
@@ -143,7 +154,7 @@ function invalid(token: string): DelegateIntent {
|
|
|
143
154
|
export function delegateCompletions(prefix: string, recentRunIds: string[] = []): string[] {
|
|
144
155
|
const words = (prefix ?? "").trimStart();
|
|
145
156
|
const tokens = words.split(/\s+/);
|
|
146
|
-
const base: string[] = ["on", "off", "status", "paths", "doctor", "help", "cancel ", "inspect ", "resume ", "peek ", "run ", "research "];
|
|
157
|
+
const base: string[] = ["on", "off", "status", "paths", "doctor", "help", "cancel ", "answer ", "inspect ", "resume ", "peek ", "run ", "research "];
|
|
147
158
|
|
|
148
159
|
const matches: string[] = [];
|
|
149
160
|
if (tokens.length <= 1) {
|
package/config.ts
CHANGED
|
@@ -27,6 +27,14 @@ export interface DelegateConfigV1 {
|
|
|
27
27
|
maxRuns: number;
|
|
28
28
|
maxRunAgeDays: number;
|
|
29
29
|
updateThrottleMs: number;
|
|
30
|
+
/** R9: concurrent background children (default 3, clamp 1–8). */
|
|
31
|
+
maxBackgroundRuns: number;
|
|
32
|
+
/** R17/R18: ask_parent channel (background children). */
|
|
33
|
+
askParent: {
|
|
34
|
+
enabled: boolean;
|
|
35
|
+
timeoutMs: number;
|
|
36
|
+
maxPerRun: number;
|
|
37
|
+
};
|
|
30
38
|
}
|
|
31
39
|
|
|
32
40
|
export const DEFAULT_DELEGATE_CONFIG: DelegateConfigV1 = {
|
|
@@ -44,6 +52,12 @@ export const DEFAULT_DELEGATE_CONFIG: DelegateConfigV1 = {
|
|
|
44
52
|
maxRuns: 50,
|
|
45
53
|
maxRunAgeDays: 30,
|
|
46
54
|
updateThrottleMs: 100,
|
|
55
|
+
maxBackgroundRuns: 3,
|
|
56
|
+
askParent: {
|
|
57
|
+
enabled: true,
|
|
58
|
+
timeoutMs: 600_000,
|
|
59
|
+
maxPerRun: 5,
|
|
60
|
+
},
|
|
47
61
|
};
|
|
48
62
|
|
|
49
63
|
const MIN_VALUES: Partial<Record<keyof DelegateConfigV1, number>> = {
|
|
@@ -59,6 +73,7 @@ const MIN_VALUES: Partial<Record<keyof DelegateConfigV1, number>> = {
|
|
|
59
73
|
maxRuns: 1,
|
|
60
74
|
maxRunAgeDays: 1,
|
|
61
75
|
updateThrottleMs: 0,
|
|
76
|
+
maxBackgroundRuns: 1,
|
|
62
77
|
};
|
|
63
78
|
|
|
64
79
|
const MAX_VALUES: Partial<Record<keyof DelegateConfigV1, number>> = {
|
|
@@ -74,6 +89,7 @@ const MAX_VALUES: Partial<Record<keyof DelegateConfigV1, number>> = {
|
|
|
74
89
|
maxRuns: 10_000,
|
|
75
90
|
maxRunAgeDays: 3650,
|
|
76
91
|
updateThrottleMs: 5_000,
|
|
92
|
+
maxBackgroundRuns: 8,
|
|
77
93
|
};
|
|
78
94
|
|
|
79
95
|
/**
|
|
@@ -125,6 +141,19 @@ function applyKnownField(config: DelegateConfigV1, key: string, value: unknown):
|
|
|
125
141
|
}
|
|
126
142
|
return;
|
|
127
143
|
}
|
|
144
|
+
// R17: nested askParent block — merge field-by-field with clamps.
|
|
145
|
+
if (key === "askParent") {
|
|
146
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return;
|
|
147
|
+
const raw = value as Record<string, unknown>;
|
|
148
|
+
if (typeof raw.enabled === "boolean") config.askParent.enabled = raw.enabled;
|
|
149
|
+
if (Number.isFinite(Number(raw.timeoutMs))) {
|
|
150
|
+
config.askParent.timeoutMs = Math.min(3_600_000, Math.max(5_000, Number(raw.timeoutMs)));
|
|
151
|
+
}
|
|
152
|
+
if (Number.isFinite(Number(raw.maxPerRun))) {
|
|
153
|
+
config.askParent.maxPerRun = Math.min(20, Math.max(1, Math.trunc(Number(raw.maxPerRun))));
|
|
154
|
+
}
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
128
157
|
const numeric = typeof value === "number" ? value : Number(value);
|
|
129
158
|
if (!Number.isFinite(numeric)) return;
|
|
130
159
|
const min = MIN_VALUES[key as keyof DelegateConfigV1];
|