@maheidem/pi-delegate 0.3.2 → 0.6.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/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
- // 8. Reservation NOW covers the child lifecycle.
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/ask.ts ADDED
@@ -0,0 +1,183 @@
1
+ /**
2
+ * delegate — ask_parent channel (R17/R18): background children can ask the
3
+ * parent blocking questions (answered via delegate_answer) and file
4
+ * non-blocking notes. Child-side tool + shared validation; the parent-side
5
+ * delivery lives in background.ts and the runner.
6
+ *
7
+ * Mechanism (SPEC §3): the tool call IS the blocking primitive. The child's
8
+ * execute() polls $PI_DELEGATE_ASK_DIR/<toolCallId>.json until the parent's
9
+ * answer lands or the budget expires. The runner watches the toolCall records
10
+ * on the child stream and delivers the question/note message to the parent.
11
+ */
12
+
13
+ import { Type } from "typebox";
14
+ import * as fs from "node:fs";
15
+ import * as path from "node:path";
16
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
17
+
18
+ export const CHILD_QUESTION_TYPE = "delegate-child-question";
19
+ export const CHILD_NOTE_TYPE = "delegate-child-note";
20
+
21
+ /** R17: the exact timeout fallback (byte-exact per SPEC §5 discipline). */
22
+ export const ASK_FALLBACK_TEXT =
23
+ "No answer arrived within the budget. Proceed with your best judgment and state the assumption in your handoff.";
24
+
25
+ /** R18: notes are capped to bound spam (never blocks, never wakes). */
26
+ export const MAX_NOTES_PER_RUN = 20;
27
+
28
+ const QUESTION_TOPICS = ["blocked", "guidance", "approval", "opinion"] as const;
29
+ const NOTE_TOPICS = ["risk", "observation", "concern"] as const;
30
+
31
+ export const AskParentParams = Type.Object({
32
+ kind: Type.Union([Type.Literal("question"), Type.Literal("note")], {
33
+ description: "question = you are blocked and wait for the parent's answer; note = non-blocking FYI for the parent (no answer will come).",
34
+ }),
35
+ topic: Type.String({
36
+ description: "question: blocked | guidance | approval | opinion. note: risk | observation | concern.",
37
+ }),
38
+ text: Type.String({
39
+ minLength: 1,
40
+ maxLength: 2000,
41
+ description: "The question or note, ≤2000 chars. For questions: be specific and self-contained; the parent answers from its own context only.",
42
+ }),
43
+ });
44
+
45
+ export type AskSubmission = {
46
+ kind: "question" | "note";
47
+ topic: string;
48
+ text: string;
49
+ };
50
+
51
+ export function validateAskSubmission(params: unknown): { ok: true; value: AskSubmission } | { ok: false; errors: string[] } {
52
+ if (!params || typeof params !== "object") return { ok: false, errors: ["ask_parent params must be an object."] };
53
+ const raw = params as Record<string, unknown>;
54
+ const errors: string[] = [];
55
+ if (raw.kind !== "question" && raw.kind !== "note") errors.push("kind must be 'question' or 'note'.");
56
+ const topic = typeof raw.topic === "string" ? raw.topic.trim() : "";
57
+ if (!topic) errors.push("topic is required.");
58
+ else if (raw.kind === "question" && !(QUESTION_TOPICS as readonly string[]).includes(topic)) {
59
+ errors.push(`question topic must be one of: ${QUESTION_TOPICS.join(", ")}.`);
60
+ } else if (raw.kind === "note" && !(NOTE_TOPICS as readonly string[]).includes(topic)) {
61
+ errors.push(`note topic must be one of: ${NOTE_TOPICS.join(", ")}.`);
62
+ }
63
+ const text = typeof raw.text === "string" ? raw.text : "";
64
+ if (!text.trim()) errors.push("text is required.");
65
+ if (text.length > 2000) errors.push(`text must be ≤2000 chars (got ${text.length}).`);
66
+ if (errors.length > 0) return { ok: false, errors };
67
+ return { ok: true, value: { kind: raw.kind as "question" | "note", topic, text } };
68
+ }
69
+
70
+ export interface AskEnv {
71
+ askDir?: string;
72
+ timeoutMs: number;
73
+ maxQuestions: number;
74
+ /** Test seam: sleep between polls. */
75
+ sleep?: (ms: number) => Promise<void>;
76
+ /** Test seam: inject the answer instead of reading the file. */
77
+ readAnswer?: (toolCallId: string) => { answeredBy: string; answer: string } | null;
78
+ }
79
+
80
+ type AskToolResult = {
81
+ content: Array<{ type: "text"; text: string }>;
82
+ details: {
83
+ rejected?: boolean;
84
+ errors?: string[];
85
+ askNote?: AskSubmission;
86
+ askAnswered?: boolean;
87
+ answeredBy?: string;
88
+ askTimedOut?: boolean;
89
+ };
90
+ isError?: boolean;
91
+ };
92
+
93
+ /**
94
+ * Child-side registration. The tool exists ONLY in background children
95
+ * (PI_DELEGATE_ASK_DIR set by the runner when askParent is enabled):
96
+ * a foreground child asking would deadlock the parent turn by construction.
97
+ */
98
+ export function registerAskParentTool(pi: ExtensionAPI, env: AskEnv): void {
99
+ const questionsAsked = { count: 0 };
100
+ const notesFiled = { count: 0 };
101
+ const sleep = env.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));
102
+ const readAnswer = env.readAnswer ?? ((toolCallId: string) => {
103
+ const file = path.join(env.askDir ?? "", `${toolCallId}.json`);
104
+ try {
105
+ const raw = JSON.parse(fs.readFileSync(file, "utf8")) as { answeredBy?: string; answer?: string };
106
+ if (typeof raw.answer === "string") return { answeredBy: raw.answeredBy ?? "model", answer: raw.answer };
107
+ return null;
108
+ } catch {
109
+ return null;
110
+ }
111
+ });
112
+ pi.registerTool({
113
+ name: "ask_parent",
114
+ label: "Ask the parent",
115
+ description:
116
+ "Ask the delegating parent agent a question (you block until it answers or the budget expires) or file a non-blocking note. " +
117
+ "Ask only when you are genuinely blocked or a wrong guess is expensive; for cheap decisions proceed with a stated assumption instead. " +
118
+ "Prefer notes for risks and observations — they never stall your run.",
119
+ parameters: AskParentParams,
120
+ async execute(toolCallId: string, params): Promise<AskToolResult> {
121
+ const validation = validateAskSubmission(params);
122
+ if (!validation.ok) {
123
+ return {
124
+ content: [{ type: "text" as const, text: `ask_parent REJECTED — fix and call again:\n${validation.errors.map((e) => `- ${e}`).join("\n")}` }],
125
+ details: { rejected: true, errors: validation.errors },
126
+ isError: true,
127
+ };
128
+ }
129
+ const ask = validation.value;
130
+ if (ask.kind === "note") {
131
+ if (notesFiled.count >= MAX_NOTES_PER_RUN) {
132
+ return {
133
+ content: [{ type: "text" as const, text: `Note cap reached (${MAX_NOTES_PER_RUN}). Continue your work; include remaining observations in your handoff.` }],
134
+ details: { rejected: true },
135
+ isError: true,
136
+ };
137
+ }
138
+ notesFiled.count += 1;
139
+ return {
140
+ content: [{ type: "text" as const, text: `Note delivered to the parent (topic: ${ask.topic}). No answer will arrive — continue your work.` }],
141
+ details: { askNote: ask },
142
+ };
143
+ }
144
+ questionsAsked.count += 1;
145
+ if (questionsAsked.count > env.maxQuestions) {
146
+ return {
147
+ content: [{ type: "text" as const, text: `Question budget exhausted (${env.maxQuestions} per run). ${ASK_FALLBACK_TEXT}` }],
148
+ details: { rejected: true },
149
+ isError: true,
150
+ };
151
+ }
152
+ const deadline = Date.now() + env.timeoutMs;
153
+ for (;;) {
154
+ const answer = readAnswer(toolCallId);
155
+ if (answer) {
156
+ return {
157
+ content: [{ type: "text" as const, text: `[parent answered · by ${answer.answeredBy}]\n${answer.answer}` }],
158
+ details: { askAnswered: true, answeredBy: answer.answeredBy },
159
+ };
160
+ }
161
+ if (Date.now() >= deadline) {
162
+ return {
163
+ content: [{ type: "text" as const, text: ASK_FALLBACK_TEXT }],
164
+ details: { askTimedOut: true },
165
+ };
166
+ }
167
+ await sleep(Math.min(400, Math.max(50, deadline - Date.now())));
168
+ }
169
+ },
170
+ });
171
+ }
172
+
173
+ /** R17: answer payload written by the parent runner. */
174
+ export interface AskAnswerFile {
175
+ answeredBy: "model" | "user";
176
+ answeredAt: string;
177
+ answer: string;
178
+ }
179
+
180
+ export function writeAskAnswerFile(askDir: string, toolCallId: string, payload: AskAnswerFile): void {
181
+ fs.mkdirSync(askDir, { recursive: true, mode: 0o700 });
182
+ fs.writeFileSync(path.join(askDir, `${toolCallId}.json`), JSON.stringify(payload), { mode: 0o600 });
183
+ }