@maheidem/pi-delegate 0.3.1 → 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 +215 -72
- package/commands.ts +12 -1
- package/config.ts +50 -5
- package/index.ts +505 -30
- package/mode.ts +2 -2
- package/package.json +1 -1
- package/run-store.ts +7 -0
- package/runner.ts +97 -4
- package/types.ts +63 -3
- package/ui/format.ts +49 -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.
|
|
@@ -289,10 +456,12 @@ export class DelegateApplicationImpl implements DelegateApplication {
|
|
|
289
456
|
// Strip the overlay's diagnostic keys so only real config fields
|
|
290
457
|
// reach the runner (a spurious key would survive into metadata).
|
|
291
458
|
const overlay = applyProjectOverlay(this.liveConfig, request.projectRoot);
|
|
292
|
-
const { projectOverrides, projectCorrupt, ...rest } = overlay as unknown as DelegateConfigV1 & {
|
|
459
|
+
const { projectOverrides, projectSetKeys, projectCorrupt, ...rest } = overlay as unknown as DelegateConfigV1 & {
|
|
293
460
|
projectOverrides: string[];
|
|
461
|
+
projectSetKeys: string[];
|
|
294
462
|
projectCorrupt?: string;
|
|
295
463
|
};
|
|
464
|
+
void projectSetKeys; // display-only; run resolution uses projectOverrides
|
|
296
465
|
projectSetsHard = projectOverrides.includes("hardTimeoutMs");
|
|
297
466
|
baseCfg = { ...(rest as unknown as DelegateConfigV1) } as DelegateConfigV1;
|
|
298
467
|
}
|
|
@@ -318,26 +487,26 @@ export class DelegateApplicationImpl implements DelegateApplication {
|
|
|
318
487
|
// 2. Validate task (line endings, blank, byte limit).
|
|
319
488
|
const taskResult = validateTask(request.task, cfg.maxTaskBytes);
|
|
320
489
|
if (typeof taskResult !== "string") {
|
|
321
|
-
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}`) };
|
|
322
491
|
}
|
|
323
492
|
const task = taskResult;
|
|
324
493
|
|
|
325
494
|
// 3. Role (closed catalogue).
|
|
326
495
|
if (!isRoleName(request.role)) {
|
|
327
|
-
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'.`) };
|
|
328
497
|
}
|
|
329
498
|
const role = resolveRole(request.role, cfg.defaultRole);
|
|
330
499
|
|
|
331
500
|
// 4. Project trust for the write-capable general role.
|
|
332
501
|
if (role.name === "general" && !request.projectTrusted) {
|
|
333
|
-
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.") };
|
|
334
503
|
}
|
|
335
504
|
|
|
336
505
|
// 5. Model resolution (R5): an explicit `model` pin wins; otherwise
|
|
337
506
|
// the parent's current model is inherited as before.
|
|
338
507
|
const model = request.model?.trim() || request.parentModel?.trim();
|
|
339
508
|
if (!model) {
|
|
340
|
-
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.") };
|
|
341
510
|
}
|
|
342
511
|
const modelNote = request.model?.trim() && request.model!.trim() !== request.parentModel?.trim()
|
|
343
512
|
? `child model pinned to ${request.model!.trim()} (parent model ${request.parentModel || "none"} not inherited)`
|
|
@@ -349,10 +518,10 @@ export class DelegateApplicationImpl implements DelegateApplication {
|
|
|
349
518
|
if (request.resumeFrom) {
|
|
350
519
|
const prior = readRunMetadata(agentDir, request.resumeFrom);
|
|
351
520
|
if (!prior) {
|
|
352
|
-
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}.`) };
|
|
353
522
|
}
|
|
354
523
|
if (!prior.sessionPath || !fs.existsSync(prior.sessionPath)) {
|
|
355
|
-
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).`) };
|
|
356
525
|
}
|
|
357
526
|
resumeOf = prior.runId;
|
|
358
527
|
sessionPath = prior.sessionPath;
|
|
@@ -360,7 +529,7 @@ export class DelegateApplicationImpl implements DelegateApplication {
|
|
|
360
529
|
|
|
361
530
|
// 6. Role prompt readability.
|
|
362
531
|
if (!rolePromptExists(role)) {
|
|
363
|
-
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}'.`) };
|
|
364
533
|
}
|
|
365
534
|
|
|
366
535
|
// 7. Open run store entry (atomic, 0700/0600).
|
|
@@ -368,7 +537,7 @@ export class DelegateApplicationImpl implements DelegateApplication {
|
|
|
368
537
|
try {
|
|
369
538
|
opened = openRun(agentDir, { ...request, task, role: role.name });
|
|
370
539
|
} catch (error) {
|
|
371
|
-
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}`) };
|
|
372
541
|
}
|
|
373
542
|
|
|
374
543
|
// R3: durable session storage for new runs (resumed runs re-enter
|
|
@@ -382,66 +551,7 @@ export class DelegateApplicationImpl implements DelegateApplication {
|
|
|
382
551
|
}
|
|
383
552
|
}
|
|
384
553
|
|
|
385
|
-
|
|
386
|
-
// Capture live state for the home dashboard while forwarding the caller's hooks.
|
|
387
|
-
this.activeStream = null;
|
|
388
|
-
this.activeRing = new FeedRing(120);
|
|
389
|
-
const captureHooks: RunHooks = {
|
|
390
|
-
...hooks,
|
|
391
|
-
onUpdate: (u: RunStreamUpdate) => {
|
|
392
|
-
this.activeStream = u;
|
|
393
|
-
hooks.onUpdate?.(u);
|
|
394
|
-
},
|
|
395
|
-
onEvent: (e: FeedEvent) => {
|
|
396
|
-
this.activeRing.push(e);
|
|
397
|
-
hooks.onEvent?.(e);
|
|
398
|
-
},
|
|
399
|
-
};
|
|
400
|
-
const runner = new DelegateRunner(
|
|
401
|
-
opened,
|
|
402
|
-
{
|
|
403
|
-
agentDir,
|
|
404
|
-
role,
|
|
405
|
-
task,
|
|
406
|
-
runId: opened.metadata.runId,
|
|
407
|
-
parentModel: model,
|
|
408
|
-
thinkingLevel: request.thinkingLevel,
|
|
409
|
-
cwd: request.cwd,
|
|
410
|
-
projectTrusted: request.projectTrusted,
|
|
411
|
-
registeredTools: this.lastRegisteredTools,
|
|
412
|
-
...(resumeOf ? { resumeOf } : {}),
|
|
413
|
-
...(sessionPath ? { sessionPath } : {}),
|
|
414
|
-
...(sessionDir ? { sessionDir } : {}),
|
|
415
|
-
},
|
|
416
|
-
cfg,
|
|
417
|
-
captureHooks,
|
|
418
|
-
this.ports.resolveInvocation ?? resolvePiInvocation,
|
|
419
|
-
);
|
|
420
|
-
const reservation: ActiveRunReservation = {
|
|
421
|
-
id: opened.metadata.runId,
|
|
422
|
-
role: role.name,
|
|
423
|
-
runner,
|
|
424
|
-
startedAt: opened.metadata.createdAt,
|
|
425
|
-
hardMs: timeouts.hardMs,
|
|
426
|
-
};
|
|
427
|
-
this.activeRun = reservation;
|
|
428
|
-
|
|
429
|
-
try {
|
|
430
|
-
const outcome = await runner.run();
|
|
431
|
-
this.activeRun = null;
|
|
432
|
-
// Retention after terminal finalization (best-effort).
|
|
433
|
-
try {
|
|
434
|
-
enforceRetention(agentDir, cfg.maxRuns, cfg.maxRunAgeDays, undefined);
|
|
435
|
-
} catch {
|
|
436
|
-
// cleanup failure is warning-only
|
|
437
|
-
}
|
|
438
|
-
return outcomeToRunResult(outcome, opened.metadata, role.name, model, request.thinkingLevel, { timeoutInfo, modelNote });
|
|
439
|
-
} catch (error) {
|
|
440
|
-
this.activeRun = null;
|
|
441
|
-
return errorResult(opened.metadata.runId, role.name, "E_CHILD_EXIT", `Delegation failed unexpectedly: ${(error as Error).message}`);
|
|
442
|
-
} finally {
|
|
443
|
-
this.startNextQueuedRun();
|
|
444
|
-
}
|
|
554
|
+
return { opened, role, task, model, cfg, timeoutInfo, modelNote, resumeOf, sessionPath, sessionDir };
|
|
445
555
|
}
|
|
446
556
|
|
|
447
557
|
/** Queued-call introspection for status views. */
|
|
@@ -453,6 +563,32 @@ export class DelegateApplicationImpl implements DelegateApplication {
|
|
|
453
563
|
return this.liveConfig.queueLimit;
|
|
454
564
|
}
|
|
455
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
|
+
|
|
456
592
|
/** Pop the next queued run (if any) into the free slot, fire-and-forget. */
|
|
457
593
|
private startNextQueuedRun(): void {
|
|
458
594
|
const next = this.runQueue.shift();
|
|
@@ -529,20 +665,27 @@ export class DelegateApplicationImpl implements DelegateApplication {
|
|
|
529
665
|
if (projectRoot) {
|
|
530
666
|
const overlay = applyProjectOverlay(cfg, projectRoot) as unknown as DelegateConfigV1 & {
|
|
531
667
|
projectOverrides: string[];
|
|
668
|
+
projectSetKeys: string[];
|
|
532
669
|
projectCorrupt?: string;
|
|
533
670
|
};
|
|
534
|
-
const { projectOverrides, projectCorrupt, ...rest } = overlay;
|
|
671
|
+
const { projectOverrides, projectSetKeys, projectCorrupt, ...rest } = overlay;
|
|
535
672
|
const eff = rest as unknown as DelegateConfigV1;
|
|
673
|
+
// Provenance (source) keeps the override semantics: the effective value
|
|
674
|
+
// only comes "from the project" when it differs. Reporting does not:
|
|
675
|
+
// projectHardMs is present whenever the key is in the project FILE, so a
|
|
676
|
+
// project value equal to the user value is still visible to the panel.
|
|
536
677
|
const projectSetsHard = projectOverrides.includes("hardTimeoutMs");
|
|
678
|
+
const hardFromFile = projectSetKeys.includes("hardTimeoutMs");
|
|
537
679
|
timeouts = {
|
|
538
680
|
hardMs: eff.hardTimeoutMs,
|
|
539
681
|
inactivityMs: eff.inactivityTimeoutMs,
|
|
540
682
|
source: projectSetsHard ? "project" : "user",
|
|
541
683
|
userHardMs: cfg.hardTimeoutMs,
|
|
542
684
|
userInactivityMs: cfg.inactivityTimeoutMs,
|
|
543
|
-
...(
|
|
685
|
+
...(hardFromFile ? { projectHardMs: eff.hardTimeoutMs } : {}),
|
|
544
686
|
projectPath: projectConfigPath(projectRoot),
|
|
545
687
|
projectOverrides,
|
|
688
|
+
projectSetKeys,
|
|
546
689
|
...(projectCorrupt ? { projectCorrupt } : {}),
|
|
547
690
|
};
|
|
548
691
|
}
|
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];
|
|
@@ -327,15 +356,24 @@ export function projectConfigPath(projectRoot: string): string {
|
|
|
327
356
|
* (a broken project file must never break delegations);
|
|
328
357
|
* - only keys PRESENT in the project file override (no default backfill);
|
|
329
358
|
* - values are clamped by the same min/max bounds as the user config.
|
|
359
|
+
* Two diagnostic arrays, deliberately different:
|
|
360
|
+
* - `projectOverrides`: keys that CHANGE the effective value (equality vs
|
|
361
|
+
* base). Resolution/provenance logic depends on this — do not widen.
|
|
362
|
+
* - `projectSetKeys`: every known key explicitly PRESENT in the file,
|
|
363
|
+
* regardless of equality with the base. Display code must use this, so a
|
|
364
|
+
* project value that happens to equal the user value never renders as
|
|
365
|
+
* "not set". A key whose value is invalid is still reported as set (it
|
|
366
|
+
* is in the file); its effective value then equals the base value.
|
|
330
367
|
* Returns a NEW config object; the base is never mutated.
|
|
331
368
|
*/
|
|
332
369
|
export function applyProjectOverlay(
|
|
333
370
|
base: DelegateConfigV1,
|
|
334
371
|
projectRoot: string,
|
|
335
|
-
): DelegateConfigV1 & { projectOverrides: string[]; projectCorrupt?: string } {
|
|
336
|
-
const result: DelegateConfigV1 & { projectOverrides: string[]; projectCorrupt?: string } = {
|
|
372
|
+
): DelegateConfigV1 & { projectOverrides: string[]; projectSetKeys: string[]; projectCorrupt?: string } {
|
|
373
|
+
const result: DelegateConfigV1 & { projectOverrides: string[]; projectSetKeys: string[]; projectCorrupt?: string } = {
|
|
337
374
|
...base,
|
|
338
375
|
projectOverrides: [],
|
|
376
|
+
projectSetKeys: [],
|
|
339
377
|
};
|
|
340
378
|
const pPath = projectConfigPath(projectRoot);
|
|
341
379
|
let raw: unknown;
|
|
@@ -351,9 +389,13 @@ export function applyProjectOverlay(
|
|
|
351
389
|
const record = raw as Record<string, unknown>;
|
|
352
390
|
const known = new Set<string>(Object.keys(DEFAULT_DELEGATE_CONFIG));
|
|
353
391
|
const overrides: string[] = [];
|
|
392
|
+
const setKeys: string[] = [];
|
|
354
393
|
for (const key of Object.keys(record)) {
|
|
355
394
|
if (key === "schemaVersion") continue;
|
|
356
395
|
if (!knownKey(key)) continue; // unknown keys in project overlay ignored
|
|
396
|
+
// File truth: present in the project file counts as set even when the
|
|
397
|
+
// normalized value equals the base value (the override list would omit it).
|
|
398
|
+
setKeys.push(key);
|
|
357
399
|
try {
|
|
358
400
|
const probe: DelegateConfigV1 = { ...DEFAULT_DELEGATE_CONFIG };
|
|
359
401
|
applyKnownField(probe, key, record[key]);
|
|
@@ -367,6 +409,7 @@ export function applyProjectOverlay(
|
|
|
367
409
|
}
|
|
368
410
|
}
|
|
369
411
|
result.projectOverrides = overrides;
|
|
412
|
+
result.projectSetKeys = setKeys;
|
|
370
413
|
return result;
|
|
371
414
|
}
|
|
372
415
|
|
|
@@ -382,14 +425,15 @@ export function loadConfigCascade(
|
|
|
382
425
|
agentDir: string,
|
|
383
426
|
projectRoot?: string,
|
|
384
427
|
configPath?: string,
|
|
385
|
-
): ConfigLoadResult & { projectOverrides: string[]; projectCorrupt?: string } {
|
|
428
|
+
): ConfigLoadResult & { projectOverrides: string[]; projectSetKeys: string[]; projectCorrupt?: string } {
|
|
386
429
|
const base = loadConfig(agentDir, configPath);
|
|
387
430
|
if (!projectRoot) {
|
|
388
|
-
return { ...base, projectOverrides: [] };
|
|
431
|
+
return { ...base, projectOverrides: [], projectSetKeys: [] };
|
|
389
432
|
}
|
|
390
433
|
const overlay = applyProjectOverlay(base.config, projectRoot);
|
|
391
|
-
const { projectOverrides, projectCorrupt, ...rest } = overlay as unknown as DelegateConfigV1 & {
|
|
434
|
+
const { projectOverrides, projectSetKeys, projectCorrupt, ...rest } = overlay as unknown as DelegateConfigV1 & {
|
|
392
435
|
projectOverrides: string[];
|
|
436
|
+
projectSetKeys: string[];
|
|
393
437
|
projectCorrupt?: string;
|
|
394
438
|
};
|
|
395
439
|
const config: DelegateConfigV1 = { ...(rest as unknown as DelegateConfigV1) };
|
|
@@ -397,6 +441,7 @@ export function loadConfigCascade(
|
|
|
397
441
|
...base,
|
|
398
442
|
config,
|
|
399
443
|
projectOverrides: overlay.projectOverrides,
|
|
444
|
+
projectSetKeys: overlay.projectSetKeys,
|
|
400
445
|
projectCorrupt: overlay.projectCorrupt,
|
|
401
446
|
};
|
|
402
447
|
}
|