@maheidem/pi-delegate 0.6.4 → 0.7.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/application.ts CHANGED
@@ -173,6 +173,51 @@ export class DelegateApplicationImpl implements DelegateApplication {
173
173
  }
174
174
  }
175
175
 
176
+ /**
177
+ * R22: the configured default execution mode for delegations without
178
+ * an explicit override (absent `background` parameter / no flag).
179
+ */
180
+ defaultExecution(): "background" | "foreground" {
181
+ return this.liveConfig.defaultExecution;
182
+ }
183
+
184
+ /**
185
+ * R22: toggle the default execution mode (dashboard Advanced screen).
186
+ * Persists through the same saveConfig path as patchConfig; unlike
187
+ * patchConfig it is NOT numeric. Returns an error string or null.
188
+ */
189
+ patchDefaultExecution(value: "background" | "foreground"): string | null {
190
+ if (value !== "background" && value !== "foreground") {
191
+ return `Unknown execution mode '${value}'.`;
192
+ }
193
+ try {
194
+ const { config } = normalizeConfig({ ...(this.liveConfig as unknown as Record<string, unknown>), defaultExecution: value });
195
+ saveConfig(this.ports.agentDir, config);
196
+ this.liveConfig = config;
197
+ return null;
198
+ } catch (error) {
199
+ return `Save failed: ${(error as Error).message}`;
200
+ }
201
+ }
202
+
203
+ /**
204
+ * R23: toggle progress reports (dashboard Advanced screen). Persists
205
+ * through the same saveConfig path as patchDefaultExecution.
206
+ */
207
+ patchProgressReportsEnabled(value: boolean): string | null {
208
+ try {
209
+ const { config } = normalizeConfig({
210
+ ...(this.liveConfig as unknown as Record<string, unknown>),
211
+ progressReports: { ...this.liveConfig.progressReports, enabled: value },
212
+ });
213
+ saveConfig(this.ports.agentDir, config);
214
+ this.liveConfig = config;
215
+ return null;
216
+ } catch (error) {
217
+ return `Save failed: ${(error as Error).message}`;
218
+ }
219
+ }
220
+
176
221
  // ── Mode ───────────────────────────────────────────────────────────────
177
222
 
178
223
  isStrict(): boolean {
@@ -217,7 +262,7 @@ export class DelegateApplicationImpl implements DelegateApplication {
217
262
  }
218
263
 
219
264
  /** Advanced knobs for the dashboard's Configure-advanced screen (§ S7). */
220
- panelConfig(): Pick<DelegateConfigV1, "queueLimit" | "killGraceMs" | "handoffGraceMs" | "handoffEnforceTimeoutMs" | "stuckToolTimeoutMs" | "maxTaskBytes" | "maxResultBytes" | "updateThrottleMs" | "defaultRole" | "maxRuns" | "maxRunAgeDays"> {
265
+ panelConfig(): Pick<DelegateConfigV1, "queueLimit" | "killGraceMs" | "handoffGraceMs" | "handoffEnforceTimeoutMs" | "stuckToolTimeoutMs" | "maxTaskBytes" | "maxResultBytes" | "updateThrottleMs" | "defaultRole" | "defaultExecution" | "maxRuns" | "maxRunAgeDays" | "progressReports"> {
221
266
  const c = this.liveConfig;
222
267
  return {
223
268
  queueLimit: c.queueLimit,
@@ -229,8 +274,10 @@ export class DelegateApplicationImpl implements DelegateApplication {
229
274
  maxResultBytes: c.maxResultBytes,
230
275
  updateThrottleMs: c.updateThrottleMs,
231
276
  defaultRole: c.defaultRole,
277
+ defaultExecution: c.defaultExecution,
232
278
  maxRuns: c.maxRuns,
233
279
  maxRunAgeDays: c.maxRunAgeDays,
280
+ progressReports: c.progressReports,
234
281
  };
235
282
  }
236
283
 
@@ -344,7 +391,7 @@ export class DelegateApplicationImpl implements DelegateApplication {
344
391
  } catch {
345
392
  // cleanup failure is warning-only
346
393
  }
347
- return outcomeToRunResult(outcome, opened.metadata, role.name, model, request.thinkingLevel, { timeoutInfo, modelNote });
394
+ return outcomeToRunResult(outcome, opened.metadata, role.name, model, request.thinkingLevel, { timeoutInfo, modelNote, ...(request.description ? { description: request.description } : {}) });
348
395
  } catch (error) {
349
396
  this.activeRun = null;
350
397
  return errorResult(opened.metadata.runId, role.name, "E_CHILD_EXIT", `Delegation failed unexpectedly: ${(error as Error).message}`);
@@ -355,7 +402,7 @@ export class DelegateApplicationImpl implements DelegateApplication {
355
402
  /** R8: spawn a background run — same validation and spawn path as the
356
403
  * foreground, but no slot reservation, no queue, and the caller gets a
357
404
  * live handle instead of the terminal result. */
358
- runBackground(request: DelegateRequest, hooks: { onAsk?: RunHooks["onAsk"] } = {}): { error: DelegateRunResult } | { handle: BackgroundRunHandle } {
405
+ runBackground(request: DelegateRequest, hooks: { onAsk?: RunHooks["onAsk"]; onProgress?: RunHooks["onProgress"] } = {}): { error: DelegateRunResult } | { handle: BackgroundRunHandle } {
359
406
  const prepared = this.prepareRun(request);
360
407
  if ("error" in prepared) return { error: prepared.error };
361
408
  const { opened, role, task, model, cfg, timeoutInfo, modelNote, resumeOf, sessionPath, sessionDir } = prepared;
@@ -385,7 +432,7 @@ export class DelegateApplicationImpl implements DelegateApplication {
385
432
  ...(sessionDir ? { sessionDir } : {}),
386
433
  ...(askDir && askTimeoutMs ? { background: true, askDir, askTimeoutMs, ...(askMaxQuestions ? { askMaxQuestions } : {}) } : {}),
387
434
  },
388
- cfg,
435
+ { ...cfg, progressReports: this.liveConfig.progressReports },
389
436
  {
390
437
  onUpdate: (u: RunStreamUpdate) => {
391
438
  streamEntry.latest = u;
@@ -394,6 +441,7 @@ export class DelegateApplicationImpl implements DelegateApplication {
394
441
  ring.push(e);
395
442
  },
396
443
  ...(hooks.onAsk ? { onAsk: hooks.onAsk } : {}),
444
+ ...(hooks.onProgress ? { onProgress: hooks.onProgress } : {}),
397
445
  },
398
446
  this.ports.resolveInvocation ?? resolvePiInvocation,
399
447
  );
@@ -908,7 +956,7 @@ function outcomeToRunResult(
908
956
  role: RoleName,
909
957
  model: string,
910
958
  thinkingLevel?: string,
911
- provenance?: { timeoutInfo?: string; modelNote?: string },
959
+ provenance?: { timeoutInfo?: string; modelNote?: string; description?: string },
912
960
  ): DelegateRunResult {
913
961
  const ok = outcome.state === "succeeded";
914
962
  const details: DelegateDetails = {
@@ -928,6 +976,8 @@ function outcomeToRunResult(
928
976
  outputTruncated: outcome.outputTruncated,
929
977
  ...(outcome.partialHandoff ? { partialHandoff: outcome.partialHandoff } : {}),
930
978
  ...(provenance?.timeoutInfo ? { timeoutInfo: provenance.timeoutInfo } : {}),
979
+ // R22: foreground results return the validated description inline.
980
+ ...(provenance?.description ? { description: provenance.description } : {}),
931
981
  transcriptPath: outcome.transcriptPath,
932
982
  stderrPath: outcome.stderrPath,
933
983
  displayItems: outcome.displayItems,
package/background.ts CHANGED
@@ -27,6 +27,7 @@ import type {
27
27
  } from "./types.ts";
28
28
  import { isTerminalRunState } from "./types.ts";
29
29
  import { isPidAlive, readRunMetadata } from "./run-store.ts";
30
+ import { formatDuration } from "./config.ts";
30
31
  import { CHILD_NOTE_TYPE, CHILD_QUESTION_TYPE } from "./ask.ts";
31
32
  export { CHILD_NOTE_TYPE, CHILD_QUESTION_TYPE };
32
33
 
@@ -34,6 +35,8 @@ export { CHILD_NOTE_TYPE, CHILD_QUESTION_TYPE };
34
35
  export const BACKGROUND_LEDGER_TYPE = "delegate.background";
35
36
  /** R10: terminal-result custom-message type. */
36
37
  export const BACKGROUND_RESULT_TYPE = "delegate-background-result";
38
+ /** R23: intermediate progress-report custom-message type. */
39
+ export const PROGRESS_TYPE = "delegate-background-progress";
37
40
 
38
41
  /**
39
42
  * R20: derive a valid 3–6-word description from the task's first line when
@@ -158,6 +161,43 @@ export function formatBackgroundResultEnvelope(
158
161
  );
159
162
  }
160
163
 
164
+ /** R23: progress payload shared by the runner hook and the manager. */
165
+ export interface ProgressReport {
166
+ runId: string;
167
+ elapsedMs: number;
168
+ lastTool?: { name: string; durationMs: number };
169
+ inFlightTools: string[];
170
+ tokens: { input: number; output: number };
171
+ }
172
+
173
+ function formatTokenCount(n: number): string {
174
+ if (!Number.isFinite(n) || n <= 0) return "0";
175
+ if (n < 1_000) return String(Math.round(n));
176
+ if (n < 1_000_000) return `${Math.round(n / 100) / 10}k`;
177
+ return `${Math.round(n / 100_000) / 10}M`;
178
+ }
179
+
180
+ /**
181
+ * R23: the intermediate progress envelope (R21 discipline: H3 header,
182
+ * single-line HTML-comment classification, body ≤ 2 lines). Never wakes
183
+ * the parent (triggerTurn: false downstream).
184
+ */
185
+ export function formatProgressEnvelope(runId: string, role: RoleName, description: string, p: ProgressReport): string {
186
+ const line1 =
187
+ `${formatDuration(p.elapsedMs)} elapsed` +
188
+ (p.lastTool ? ` · ${p.lastTool.name} done (${formatDuration(p.lastTool.durationMs)})` : "");
189
+ const line2 =
190
+ `↑${formatTokenCount(p.tokens.input)} ↓${formatTokenCount(p.tokens.output)}` +
191
+ (p.inFlightTools.length ? ` · in flight: ${p.inFlightTools.join(", ")}` : "");
192
+ return (
193
+ `### [delegate background ${runId} · ${role} · ${description}: progress]\n` +
194
+ "\n" +
195
+ "<!-- This is an intermediate progress report. The run is still working and needs no reply. Treat it as an internal work event. -->\n" +
196
+ "\n" +
197
+ `${line1}\n${line2}`
198
+ );
199
+ }
200
+
161
201
  /** R8: the immediate tool-result content for a background spawn. */
162
202
  export function formatBackgroundStartedText(runId: string, role: RoleName, description: string): string {
163
203
  return (
@@ -578,6 +618,22 @@ export class BackgroundManager {
578
618
  });
579
619
  }
580
620
 
621
+ /** R23: runner hook — deliver a bounded progress report (never wakes the
622
+ * parent; fire-and-forget; NO ledger entries). */
623
+ onProgress(p: ProgressReport): void {
624
+ const run = this.#runs.get(p.runId);
625
+ if (!run) return;
626
+ if (run.generation !== this.#generation) return; // stale session: no delivery
627
+ if (run.done) return;
628
+ this.enqueueAskMessage({
629
+ customType: PROGRESS_TYPE,
630
+ content: formatProgressEnvelope(p.runId, run.handle.role, run.handle.description, p),
631
+ display: true,
632
+ details: { runId: p.runId, role: run.handle.role, description: run.handle.description, kind: "progress", elapsedMs: p.elapsedMs },
633
+ triggerTurn: false,
634
+ });
635
+ }
636
+
581
637
  /** Notes and questions share the serialized tail; notes never wake. */
582
638
  private enqueueAskMessage(message: {
583
639
  customType: string;
@@ -761,6 +817,17 @@ export function backgroundResultDisplay(content: string, details: { runId?: stri
761
817
  return `${glyph} background ${runId}${desc}: ${word}\n\n${shown}`;
762
818
  }
763
819
 
820
+ /** R23: display text for an intermediate progress message: neutral ●
821
+ * glyph header + body, with the model-only classification comment
822
+ * stripped (same split discipline as backgroundResultDisplay). */
823
+ export function progressDisplay(content: string, details: { runId?: string; description?: string }): string {
824
+ const parts = content.split("\n\n");
825
+ const body = parts.length > 2 ? parts.slice(2).join("\n\n") : content;
826
+ const runId = (details.runId ?? "?").slice(-12);
827
+ const desc = details.description ? ` · ${details.description}` : "";
828
+ return `● background ${runId}${desc}: progress\n\n${body}`;
829
+ }
830
+
764
831
  /** Default receipt reader bound to an agentDir (used by the adapter). */
765
832
  export function makeReceiptReader(agentDir: string): (runId: string) => RunMetadataV1 | null {
766
833
  return (runId) => {
package/commands.ts CHANGED
@@ -19,11 +19,12 @@ export type DelegateIntent =
19
19
  | { kind: "help" }
20
20
  | { kind: "cancel"; runId?: string }
21
21
  | { kind: "answer"; runId: string; text: string }
22
- | { kind: "bg"; role: RoleName; task: string; timeoutMs?: number }
22
+ | { kind: "bg"; role: RoleName; task: string; timeoutMs?: number; execution?: "background" | "foreground" }
23
+ | { kind: "fg"; role: RoleName; task: string; timeoutMs?: number; execution?: "background" | "foreground" }
23
24
  | { kind: "inspect"; runId?: string }
24
- | { kind: "resume"; runId?: string; task: string; timeoutMs?: number }
25
+ | { kind: "resume"; runId?: string; task: string; timeoutMs?: number; execution?: "background" | "foreground" }
25
26
  | { kind: "peek"; runId?: string }
26
- | { kind: "run"; role: RoleName; task: string; explicit: boolean; timeoutMs?: number }
27
+ | { kind: "run"; role: RoleName; task: string; explicit: boolean; timeoutMs?: number; execution?: "background" | "foreground" }
27
28
  | { kind: "invalid"; token: string; usage: string };
28
29
 
29
30
  export const DELEGATE_USAGE = [
@@ -38,9 +39,10 @@ export const DELEGATE_USAGE = [
38
39
  "/delegate peek [run-id] live/final feed of a run's child activity",
39
40
  "/delegate inspect [run-id] show run metadata (defaults to latest)",
40
41
  "/delegate run <general|research> <task...> run with an explicit role",
42
+ "/delegate fg [general|research] <task...> run in the FOREGROUND (blocks until done)",
41
43
  "/delegate research <task...> research-role shorthand",
42
44
  "/delegate <task...> general-role shorthand",
43
- "flags (run/research/<task>): --timeout <90s|10m|2h|1d|ms>",
45
+ "flags (run/research/<task>): --timeout <90s|10m|2h|1d|ms> --background --foreground (mutually exclusive)",
44
46
  "timeout priority: per-invocation > project .pi/delegate/config.json > user ~/.pi/agent/delegate/config.json",
45
47
  "/delegate help this help",
46
48
  ].join("\n");
@@ -55,6 +57,7 @@ export const RESERVED_FIRST_TOKENS = new Set([
55
57
  "cancel",
56
58
  "answer",
57
59
  "bg",
60
+ "fg",
58
61
  "inspect",
59
62
  "resume",
60
63
  "peek",
@@ -75,9 +78,9 @@ export function parseDelegateCommand(input: string, options: ParseOptions = {}):
75
78
  if (!RESERVED_FIRST_TOKENS.has(first)) {
76
79
  // General-role shorthand. `research` is reserved, so a general task
77
80
  // that starts with that word must use `run general ...`.
78
- const { task, timeoutMs } = extractFlags(trimmed);
81
+ const { task, timeoutMs, execution } = extractFlags(trimmed);
79
82
  if (!task) return invalid(first);
80
- return { kind: "run", role: "general", task, explicit: false, timeoutMs };
83
+ return { kind: "run", role: "general", task, explicit: false, timeoutMs, ...(execution ? { execution } : {}) };
81
84
  }
82
85
 
83
86
  switch (first) {
@@ -117,47 +120,65 @@ export function parseDelegateCommand(input: string, options: ParseOptions = {}):
117
120
  case "resume": {
118
121
  const rest = trimmed.slice("resume".length).trim();
119
122
  if (!rest) return invalid("resume");
120
- const { task, timeoutMs } = extractFlags(rest);
123
+ const { task, timeoutMs, execution } = extractFlags(rest);
121
124
  const runId = task.split(/\s+/)[0] ?? "";
122
125
  const body = task.slice(runId.length).trim();
123
126
  if (!runId || !body) return invalid("resume");
124
- return { kind: "resume", runId, task: body, timeoutMs };
127
+ return { kind: "resume", runId, task: body, timeoutMs, ...(execution ? { execution } : {}) };
125
128
  }
126
129
  case "bg": {
127
130
  // R20: user-facing background launch — /delegate bg [general|research] <task>
128
131
  const rest = trimmed.slice("bg".length).trim();
129
132
  if (!rest) return invalid("bg");
130
- const { task, timeoutMs } = extractFlags(rest);
133
+ const { task, timeoutMs, execution } = extractFlags(rest);
131
134
  if (!task) return invalid("bg");
132
135
  const parts = task.split(/\s+/);
133
136
  const roleToken = parts[0]!;
134
137
  if (roleToken === "general" || roleToken === "research") {
135
138
  const body = parts.slice(1).join(" ").trim();
136
139
  if (!body) return invalid("bg");
137
- return { kind: "bg", role: roleToken, task: body, timeoutMs };
140
+ return { kind: "bg", role: roleToken, task: body, timeoutMs, ...(execution ? { execution } : {}) };
138
141
  }
139
- return { kind: "bg", role: "general", task, timeoutMs };
142
+ return { kind: "bg", role: "general", task, timeoutMs, ...(execution ? { execution } : {}) };
143
+ }
144
+ case "fg": {
145
+ // R22: explicit foreground shorthand — mirrors `bg` (role prefix
146
+ // optional, defaults to general), but means FOREGROUND.
147
+ const rest = trimmed.slice("fg".length).trim();
148
+ if (!rest) return invalid("fg");
149
+ const { task, timeoutMs, execution } = extractFlags(rest);
150
+ if (!task) return invalid("fg");
151
+ const parts = task.split(/\s+/);
152
+ const roleToken = parts[0]!;
153
+ if (roleToken === "general" || roleToken === "research") {
154
+ const body = parts.slice(1).join(" ").trim();
155
+ if (!body) return invalid("fg");
156
+ return { kind: "fg", role: roleToken, task: body, timeoutMs, ...(execution ? { execution } : {}) };
157
+ }
158
+ return { kind: "fg", role: "general", task, timeoutMs, ...(execution ? { execution } : {}) };
140
159
  }
141
160
  case "run": {
142
161
  const rest = trimmed.slice("run".length).trim();
143
162
  if (!rest) return invalid("run");
144
- const { task, timeoutMs } = extractFlags(rest);
163
+ const { task, timeoutMs, execution } = extractFlags(rest);
145
164
  const parts = task.split(/\s+/);
146
165
  const roleToken = parts[0]!;
147
166
  if (roleToken === "general" || roleToken === "research") {
148
167
  const body = parts.slice(1).join(" ").trim();
149
- if (!body) return invalid("run");
150
- return { kind: "run", role: roleToken, task: body, explicit: true, timeoutMs };
168
+ if (!body) return invalid("run");
169
+ return { kind: "run", role: roleToken, task: body, explicit: true, timeoutMs, ...(execution ? { execution } : {}) };
151
170
  }
152
- // `run <task...>` — role defaults to general.
153
- return { kind: "run", role: "general", task, explicit: true, timeoutMs };
171
+ // `run <task...>` — role defaults to general. A flag error (e.g.
172
+ // --background + --foreground) also lands here with an empty task.
173
+ if (!task) return invalid("run");
174
+ return { kind: "run", role: "general", task, explicit: true, timeoutMs, ...(execution ? { execution } : {}) };
154
175
  }
155
176
  case "research": {
156
177
  const rest = trimmed.slice("research".length).trim();
157
178
  if (!rest) return invalid("research");
158
- const { task, timeoutMs } = extractFlags(rest);
179
+ const { task, timeoutMs, execution } = extractFlags(rest);
159
180
  if (!task) return invalid("research");
160
- return { kind: "run", role: "research", task, explicit: true, timeoutMs };
181
+ return { kind: "run", role: "research", task, explicit: true, timeoutMs, ...(execution ? { execution } : {}) };
161
182
  }
162
183
  }
163
184
  return invalid(first);
@@ -171,7 +192,7 @@ function invalid(token: string): DelegateIntent {
171
192
  export function delegateCompletions(prefix: string, recentRunIds: string[] = []): string[] {
172
193
  const words = (prefix ?? "").trimStart();
173
194
  const tokens = words.split(/\s+/);
174
- const base: string[] = ["on", "off", "status", "paths", "doctor", "help", "cancel ", "answer ", "bg ", "inspect ", "resume ", "peek ", "run ", "research "];
195
+ const base: string[] = ["on", "off", "status", "paths", "doctor", "help", "cancel ", "answer ", "bg ", "fg ", "inspect ", "resume ", "peek ", "run ", "research "];
175
196
 
176
197
  const matches: string[] = [];
177
198
  if (tokens.length <= 1) {
@@ -192,7 +213,7 @@ export function delegateCompletions(prefix: string, recentRunIds: string[] = [])
192
213
  }
193
214
  }
194
215
  // De-duplicate, keep order, cap for the TUI (all primary verbs fit).
195
- return [...new Set(matches)].slice(0, 14);
216
+ return [...new Set(matches)].slice(0, 15);
196
217
  }
197
218
 
198
219
  /**
@@ -200,10 +221,13 @@ export function delegateCompletions(prefix: string, recentRunIds: string[] = [])
200
221
  * Unknown flags are kept in the task text; a malformed duration yields a
201
222
  * stable error message.
202
223
  */
203
- export function extractFlags(input: string): { task: string; timeoutMs?: number; error?: string } {
224
+ export function extractFlags(input: string): { task: string; timeoutMs?: number; execution?: "background" | "foreground"; error?: string } {
204
225
  const tokens = input.split(/\s+/).filter(Boolean);
205
226
  const kept: string[] = [];
206
227
  let timeoutMs: number | undefined;
228
+ let execution: "background" | "foreground" | undefined;
229
+ let bg = 0;
230
+ let fg = 0;
207
231
  for (let i = 0; i < tokens.length; i++) {
208
232
  const t = tokens[i]!;
209
233
  if (t === "--timeout") {
@@ -219,9 +243,22 @@ export function extractFlags(input: string): { task: string; timeoutMs?: number;
219
243
  }
220
244
  continue;
221
245
  }
246
+ if (t === "--background") {
247
+ bg += 1;
248
+ execution = "background";
249
+ continue;
250
+ }
251
+ if (t === "--foreground") {
252
+ fg += 1;
253
+ execution = "foreground";
254
+ continue;
255
+ }
222
256
  kept.push(t);
223
257
  }
224
- return { task: kept.join(" "), timeoutMs };
258
+ if (bg > 0 && fg > 0) {
259
+ return { task: "", error: "--background and --foreground are mutually exclusive" };
260
+ }
261
+ return { task: kept.join(" "), timeoutMs, ...(execution ? { execution } : {}) };
225
262
  }
226
263
 
227
264
  /**
package/config.ts CHANGED
@@ -27,8 +27,18 @@ export interface DelegateConfigV1 {
27
27
  maxRuns: number;
28
28
  maxRunAgeDays: number;
29
29
  updateThrottleMs: number;
30
+ /** R22: default execution mode for delegations without an explicit override. */
31
+ defaultExecution: "background" | "foreground";
30
32
  /** R9: concurrent background children (default 3, clamp 1–8). */
31
33
  maxBackgroundRuns: number;
34
+ /** R23: automatic progress reports for background runs. */
35
+ progressReports: {
36
+ enabled: boolean;
37
+ minToolMs: number;
38
+ intervalMs: number;
39
+ minGapMs: number;
40
+ maxPerRun: number;
41
+ };
32
42
  /** R17/R18: ask_parent channel (background children). */
33
43
  askParent: {
34
44
  enabled: boolean;
@@ -52,7 +62,15 @@ export const DEFAULT_DELEGATE_CONFIG: DelegateConfigV1 = {
52
62
  maxRuns: 50,
53
63
  maxRunAgeDays: 30,
54
64
  updateThrottleMs: 100,
65
+ defaultExecution: "background",
55
66
  maxBackgroundRuns: 3,
67
+ progressReports: {
68
+ enabled: true,
69
+ minToolMs: 60_000,
70
+ intervalMs: 300_000,
71
+ minGapMs: 120_000,
72
+ maxPerRun: 6,
73
+ },
56
74
  askParent: {
57
75
  enabled: true,
58
76
  timeoutMs: 600_000,
@@ -100,7 +118,13 @@ const MAX_VALUES: Partial<Record<keyof DelegateConfigV1, number>> = {
100
118
  export function normalizeConfig(
101
119
  raw: unknown,
102
120
  ): { config: DelegateConfigV1; unknownKeys: string[] } {
103
- const base: DelegateConfigV1 = { ...DEFAULT_DELEGATE_CONFIG };
121
+ const base: DelegateConfigV1 = {
122
+ ...DEFAULT_DELEGATE_CONFIG,
123
+ // nested blocks are shared references in the default — copy so a
124
+ // normalize never mutates DEFAULT_DELEGATE_CONFIG
125
+ askParent: { ...DEFAULT_DELEGATE_CONFIG.askParent },
126
+ progressReports: { ...DEFAULT_DELEGATE_CONFIG.progressReports },
127
+ };
104
128
  const unknownKeys: string[] = [];
105
129
  const extras: Record<string, unknown> = {};
106
130
  const known = new Set<string>(Object.keys(base));
@@ -142,6 +166,31 @@ function applyKnownField(config: DelegateConfigV1, key: string, value: unknown):
142
166
  return;
143
167
  }
144
168
  // R17: nested askParent block — merge field-by-field with clamps.
169
+ if (key === "defaultExecution") {
170
+ // R22: accept exactly the two enum words; anything else keeps the default.
171
+ if (value === "background" || value === "foreground") {
172
+ config.defaultExecution = value;
173
+ }
174
+ return;
175
+ }
176
+ if (key === "progressReports") {
177
+ if (!value || typeof value !== "object" || Array.isArray(value)) return;
178
+ const raw = value as Record<string, unknown>;
179
+ if (typeof raw.enabled === "boolean") config.progressReports.enabled = raw.enabled;
180
+ if (Number.isFinite(Number(raw.minToolMs))) {
181
+ config.progressReports.minToolMs = Math.min(3_600_000, Math.max(5_000, Number(raw.minToolMs)));
182
+ }
183
+ if (Number.isFinite(Number(raw.intervalMs))) {
184
+ config.progressReports.intervalMs = Math.min(3_600_000, Math.max(60_000, Number(raw.intervalMs)));
185
+ }
186
+ if (Number.isFinite(Number(raw.minGapMs))) {
187
+ config.progressReports.minGapMs = Math.min(1_800_000, Math.max(30_000, Number(raw.minGapMs)));
188
+ }
189
+ if (Number.isFinite(Number(raw.maxPerRun))) {
190
+ config.progressReports.maxPerRun = Math.min(20, Math.max(1, Math.trunc(Number(raw.maxPerRun))));
191
+ }
192
+ return;
193
+ }
145
194
  if (key === "askParent") {
146
195
  if (!value || typeof value !== "object" || Array.isArray(value)) return;
147
196
  const raw = value as Record<string, unknown>;
package/index.ts CHANGED
@@ -54,6 +54,8 @@ import {
54
54
  formatBackgroundInventoryText,
55
55
  formatBackgroundStartedText,
56
56
  makeReceiptReader,
57
+ PROGRESS_TYPE,
58
+ progressDisplay,
57
59
  validateBackgroundDescription,
58
60
  type BackgroundDetailView,
59
61
  type BackgroundLiveView,
@@ -361,7 +363,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
361
363
  const secs = Math.round(d.durationMs / 1000);
362
364
  const head =
363
365
  `[delegate v${delegateVersion()} · ${d.runId} · ${d.role} · ${stateLabel} in ${secs}s` +
364
- `${d.model ? ` · ${d.model}` : ""}${d.timeoutInfo ? ` · ${d.timeoutInfo}` : ""}]`;
366
+ `${d.model ? ` · ${d.model}` : ""}${d.timeoutInfo ? ` · ${d.timeoutInfo}` : ""}${d.description ? ` · ${d.description}` : ""}]`;
365
367
  if (!res.ok) {
366
368
  const parts = [head];
367
369
  const err = res.error ? `${res.error.code}: ${res.error.message}` : "unknown failure";
@@ -429,15 +431,13 @@ export default function delegateExtension(pi: ExtensionAPI) {
429
431
  })),
430
432
  background: Type.Optional(Type.Boolean({
431
433
  description:
432
- "Run this delegation in the background: the call returns a runId immediately and the terminal report " +
433
- "arrives later as a message. Use it for long builds, test matrices, or research that should not block " +
434
- "this turn. Requires 'description'. Poll with the delegate_status pattern or wait for the report message.",
435
- })),
436
- description: Type.Optional(Type.String({
437
- description:
438
- "Required with background=true: a 3-to-6-word purpose summary for the user, e.g. 'Run full test matrix'. " +
439
- "Describes the work, not the mechanism. Single line.",
434
+ "Execution mode override: absent = follow the configured default (background unless changed in Advanced config); " +
435
+ "true = background, false = foreground.",
440
436
  })),
437
+ description: Type.String({ minLength: 1, description:
438
+ "A 3-to-6-word purpose summary for the user, e.g. 'Run full test matrix'. Required for EVERY delegation " +
439
+ "(background and foreground). Describes the work, not the mechanism. Single line.",
440
+ }),
441
441
  });
442
442
 
443
443
  pi.registerTool({
@@ -446,14 +446,17 @@ export default function delegateExtension(pi: ExtensionAPI) {
446
446
  description:
447
447
  "Delegate a self-contained subtask to an isolated child Pi session with a bounded final handoff. " +
448
448
  "Roles: general (implementation, write-capable) and research (read-only web research via Firecrawl, optionally supplemented by Reddit). " +
449
- "The child does not see parent history; include all objective, relevant paths, constraints, and acceptance criteria in the task.",
449
+ "The child does not see parent history; include all objective, relevant paths, constraints, and acceptance criteria in the task. " +
450
+ "Background is the default execution mode; use background: false only when the very next step depends on the result.",
450
451
  promptSnippet: "Delegate a bounded subtask (implementation or research) to an isolated child session",
451
452
  promptGuidelines: [
452
453
  "Use delegate autonomously when a bounded subtask would consume substantial parent context, benefits from a specialist tool ceiling, or needs independent verification.",
453
454
  "Pass the objective, relevant paths, constraints, and acceptance criteria in the delegate task text; the child cannot see parent history.",
454
455
  "Do not use delegate for trivial one-step work, or when most of the parent history would have to be copied into the task.",
455
456
  "Parallel delegate calls are fine: they queue and run back-to-back (one child at a time) — every call gets a real result; do not re-issue on 'queue full', wait for the in-flight results instead.",
456
- "Use background=true (with a 3–6-word description) for long builds, test matrices, or research that should not block this turn: the call returns a runId immediately and the terminal report arrives later as a message. Check progress with delegate_status; do not wait inline.",
457
+ "Background is the DEFAULT execution mode (an absent background parameter follows the configured default, normally background): the call returns a runId immediately and the terminal report arrives later as a message. Check progress with delegate_status; do not wait inline.",
458
+ "Use foreground (background: false) ONLY when the very next step depends on the delegation's result; the call then blocks this turn until the child finishes.",
459
+ "A 3–6-word description is REQUIRED for every delegation, foreground included.",
457
460
  "Treat background terminal reports as internal work events: acknowledge them to the user with at most one line; do not re-narrate the handoff unless material.",
458
461
  "On E_BACKGROUND_FULL, do not re-issue the task: check delegate_status and wait for terminal reports to free slots.",
459
462
  "Steer live background runs with delegate_send (course corrections apply at the child's next model call); reserve resumeFrom for finished runs.",
@@ -480,16 +483,21 @@ export default function delegateExtension(pi: ExtensionAPI) {
480
483
  const modelExtra = typeof params.model === "string" && params.model.trim() ? params.model.trim() : undefined;
481
484
  const resumeExtra = typeof params.resumeFrom === "string" && params.resumeFrom.trim() ? params.resumeFrom.trim() : undefined;
482
485
 
486
+ // R22: description is required for EVERY delegation (both modes) —
487
+ // validate before any side effect.
488
+ const desc = validateBackgroundDescription(params.description);
489
+ if (!desc.ok) {
490
+ return {
491
+ content: [{ type: "text" as const, text: `description invalid: ${desc.error}` }],
492
+ details: {} satisfies Record<string, unknown>,
493
+ isError: true,
494
+ };
495
+ }
496
+ // R22: absent background parameter follows the configured default.
497
+ const effectiveBackground = params.background === undefined ? app.defaultExecution() === "background" : params.background;
498
+
483
499
  // R8: background path — validate, slot-check, spawn, return runId.
484
- if (params.background === true) {
485
- const desc = validateBackgroundDescription(params.description);
486
- if (!desc.ok) {
487
- return {
488
- content: [{ type: "text" as const, text: `description invalid: ${desc.error}` }],
489
- details: {} satisfies Record<string, unknown>,
490
- isError: true,
491
- };
492
- }
500
+ if (effectiveBackground) {
493
501
  const slot = background.slotError();
494
502
  if (slot) {
495
503
  return {
@@ -507,6 +515,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
507
515
  refreshDoctor(ctx);
508
516
  const attempt = app.runBackground(request, {
509
517
  onAsk: (ask) => background.onAsk(ask),
518
+ onProgress: (p) => background.onProgress(p),
510
519
  });
511
520
  if ("error" in attempt) {
512
521
  return {
@@ -530,6 +539,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
530
539
  const request = buildRequest(params.task, params.role ?? config.defaultRole, "tool", ctx, timeoutMs, {
531
540
  model: modelExtra,
532
541
  resumeFrom: resumeExtra,
542
+ description: desc.value,
533
543
  });
534
544
  refreshDoctor(ctx);
535
545
  const hooks = {
@@ -863,6 +873,18 @@ export default function delegateExtension(pi: ExtensionAPI) {
863
873
  return new Text(`[delegate ${d.runId ?? "?"} · ${d.role ?? "?"} · ${d.state ?? "?"}]\n\n${text}`, 0, 0);
864
874
  });
865
875
 
876
+ // ── R23: progress renderer (neutral ● glyph, classification stripped) ───
877
+
878
+ pi.registerMessageRenderer(PROGRESS_TYPE, (message: { content?: string | unknown[]; details?: unknown }) => {
879
+ const d = (message.details ?? {}) as { runId?: string; description?: string };
880
+ const raw = message.content;
881
+ const text =
882
+ typeof raw === "string" ? raw
883
+ : Array.isArray(raw) ? raw.map((b) => (b as { text?: string })?.text ?? "").join("\n")
884
+ : "";
885
+ return new Text(progressDisplay(text, d), 0, 0);
886
+ });
887
+
866
888
  // ── R15: background result renderer (neutral glyph+word, no model-only text)
867
889
 
868
890
  pi.registerMessageRenderer(BACKGROUND_RESULT_TYPE, (message: { content?: string | unknown[]; details?: unknown }) => {
@@ -894,7 +916,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
894
916
  }
895
917
  };
896
918
 
897
- const runCommandForeground = async (task: string, role: "general" | "research", ctx: ExtensionCommandContext, timeoutMs?: number, extras?: { resumeFrom?: string }): Promise<void> => {
919
+ const runCommandForeground = async (task: string, role: "general" | "research", ctx: ExtensionCommandContext, timeoutMs?: number, extras?: { resumeFrom?: string; description?: string }): Promise<void> => {
898
920
  const request = buildRequest(task, role, "command", ctx, timeoutMs, extras);
899
921
  refreshDoctor(ctx);
900
922
  let lastText = `[delegate] starting ${role} run…`;
@@ -1009,7 +1031,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
1009
1031
  // R20: user-facing background launch — /delegate bg and the dashboard
1010
1032
  // action spawn a background run (description derived from the task's
1011
1033
  // first line) and return immediately; the report arrives later.
1012
- const runCommandBackground = async (task: string, role: "general" | "research", ctx: ExtensionCommandContext, timeoutMs?: number): Promise<void> => {
1034
+ const runCommandBackground = async (task: string, role: "general" | "research", ctx: ExtensionCommandContext, timeoutMs?: number, extras?: { resumeFrom?: string }): Promise<void> => {
1013
1035
  const desc = deriveBackgroundDescription(task);
1014
1036
  if (!desc.ok) {
1015
1037
  say(ctx, `[delegate] ${desc.error}`, "error");
@@ -1023,10 +1045,12 @@ export default function delegateExtension(pi: ExtensionAPI) {
1023
1045
  const request = buildRequest(task, role, "command", ctx, timeoutMs, {
1024
1046
  background: true,
1025
1047
  description: desc.value,
1048
+ ...(extras?.resumeFrom ? { resumeFrom: extras.resumeFrom } : {}),
1026
1049
  });
1027
1050
  refreshDoctor(ctx);
1028
1051
  const attempt = app.runBackground(request, {
1029
1052
  onAsk: (ask) => background.onAsk(ask),
1053
+ onProgress: (p) => background.onProgress(p),
1030
1054
  });
1031
1055
  if ("error" in attempt) {
1032
1056
  say(ctx, formatRunText(attempt.error), "error");
@@ -1036,6 +1060,21 @@ export default function delegateExtension(pi: ExtensionAPI) {
1036
1060
  say(ctx, formatBackgroundStartedText(attempt.handle.runId, attempt.handle.role, attempt.handle.description));
1037
1061
  };
1038
1062
 
1063
+ // R22: a foreground launch from the user surface (slash/panel) also needs
1064
+ // a description — derive it from the task's first line exactly like the
1065
+ // background path (R20) and pass it to the foreground run.
1066
+ const launchForeground = async (task: string, role: "general" | "research", ctx: ExtensionCommandContext, timeoutMs?: number, extras?: { resumeFrom?: string }): Promise<void> => {
1067
+ const desc = deriveBackgroundDescription(task);
1068
+ if (!desc.ok) {
1069
+ say(ctx, `[delegate] ${desc.error}`, "error");
1070
+ return;
1071
+ }
1072
+ await runCommandForeground(task, role, ctx, timeoutMs, {
1073
+ ...(extras?.resumeFrom ? { resumeFrom: extras.resumeFrom } : {}),
1074
+ description: desc.value,
1075
+ });
1076
+ };
1077
+
1039
1078
  const statusText = (ctx: ExtensionContext): string => {
1040
1079
  const s = app.getStatus(pi.getActiveTools(), ctx.cwd ?? process.cwd());
1041
1080
  const lines = ["[delegate]", `version: v${delegateVersion()} (loaded at session start; /reload picks up newer installs)`, `mode: ${s.modeEnabled ? "strict" : "normal"}`];
@@ -1079,7 +1118,9 @@ export default function delegateExtension(pi: ExtensionAPI) {
1079
1118
  "/delegate run general <task> run a delegation with a role",
1080
1119
  "/delegate research <task> research role",
1081
1120
  "/delegate bg [role] <task> run it in the background (report arrives later)",
1121
+ "/delegate fg [role] <task> run it in the foreground (blocks until done)",
1082
1122
  "/delegate <task> general-role shorthand",
1123
+ "flags (run/research/<task>): --timeout <90s|10m|2h|1d> --background --foreground",
1083
1124
  "/delegate cancel [run-id] cancel the active run",
1084
1125
  "/delegate answer <run-id> <text> answer a blocked background child's question",
1085
1126
  "/delegate resume <run-id> <task> resume a prior run's child session",
@@ -1195,11 +1236,19 @@ export default function delegateExtension(pi: ExtensionAPI) {
1195
1236
  say(ctx, `[delegate] invalid role '${intent.role}'. Use general or research.`, "error");
1196
1237
  return;
1197
1238
  }
1198
- await runCommandForeground(intent.task, intent.role, ctx, intent.timeoutMs);
1239
+ // R22: run follows the configured default unless a flag overrides.
1240
+ if ((intent.execution ?? app.defaultExecution()) === "foreground") {
1241
+ await launchForeground(intent.task, intent.role, ctx, intent.timeoutMs);
1242
+ } else {
1243
+ await runCommandBackground(intent.task, intent.role, ctx, intent.timeoutMs);
1244
+ }
1199
1245
  return;
1200
1246
  case "bg":
1201
1247
  await runCommandBackground(intent.task, isRoleName(intent.role) ? intent.role : "general", ctx, intent.timeoutMs);
1202
1248
  return;
1249
+ case "fg":
1250
+ await launchForeground(intent.task, isRoleName(intent.role) ? intent.role : "general", ctx, intent.timeoutMs);
1251
+ return;
1203
1252
  case "peek": {
1204
1253
  const id = intent.runId?.trim() || app.mostRecentRunId();
1205
1254
  if (!id) {
@@ -1216,7 +1265,12 @@ export default function delegateExtension(pi: ExtensionAPI) {
1216
1265
  say(ctx, `[delegate] usage: /delegate resume <run-id> <continuation task...>`, "error");
1217
1266
  return;
1218
1267
  }
1219
- await runCommandForeground(intent.task, "general", ctx, intent.timeoutMs, { resumeFrom: runId });
1268
+ // R22: resume follows the configured default unless a flag overrides.
1269
+ if ((intent.execution ?? app.defaultExecution()) === "foreground") {
1270
+ await launchForeground(intent.task, "general", ctx, intent.timeoutMs, { resumeFrom: runId });
1271
+ } else {
1272
+ await runCommandBackground(intent.task, "general", ctx, intent.timeoutMs, { resumeFrom: runId });
1273
+ }
1220
1274
  return;
1221
1275
  }
1222
1276
  case "invalid":
@@ -1308,6 +1362,8 @@ export default function delegateExtension(pi: ExtensionAPI) {
1308
1362
  { key: "cfg:user:maxResultBytes", label: "Max result bytes", value: String(c.maxResultBytes), rawValue: String(c.maxResultBytes), kind: "input" },
1309
1363
  { key: "cfg:user:updateThrottleMs", label: "Update throttle", value: formatDuration(c.updateThrottleMs), rawValue: String(c.updateThrottleMs), kind: "input", inputHint: "live update cadence" },
1310
1364
  { key: "info:defaultRole", label: "Default role", value: c.defaultRole, kind: "info" },
1365
+ { key: "exec-default-toggle", label: "Execution default", value: c.defaultExecution, kind: "action" },
1366
+ { key: "progress-toggle", label: "Progress reports", value: c.progressReports.enabled ? "on" : "off", kind: "action" },
1311
1367
  { key: "info:retention", label: "Retention", value: `${c.maxRuns} runs · ${c.maxRunAgeDays}d`, kind: "info" },
1312
1368
  ];
1313
1369
  };
@@ -1328,7 +1384,22 @@ export default function delegateExtension(pi: ExtensionAPI) {
1328
1384
  if (!m) return `Unknown setting '${key}'.`;
1329
1385
  return app.patchConfig(m[1]!, raw);
1330
1386
  },
1331
- activate: (): PanelActionResult => ({ kind: "close", action: "advanced-done" }),
1387
+ activate: (key): PanelActionResult => {
1388
+ // R22: the execution-default toggle cycles background ⇄ foreground
1389
+ // in place (action row, no editor input).
1390
+ if (key === "exec-default-toggle") {
1391
+ const next = app.panelConfig().defaultExecution === "background" ? "foreground" : "background";
1392
+ const err = app.patchDefaultExecution(next);
1393
+ return err ? { kind: "error", message: err } : { kind: "updated", message: `Execution default: ${next}` };
1394
+ }
1395
+ // R23: the progress-reports toggle flips enabled in place.
1396
+ if (key === "progress-toggle") {
1397
+ const next = !app.panelConfig().progressReports.enabled;
1398
+ const err = app.patchProgressReportsEnabled(next);
1399
+ return err ? { kind: "error", message: err } : { kind: "updated", message: `Progress reports: ${next ? "on" : "off"}` };
1400
+ }
1401
+ return { kind: "close", action: "advanced-done" };
1402
+ },
1332
1403
  requestRender: () => tui.requestRender(),
1333
1404
  done,
1334
1405
  }),
@@ -1415,7 +1486,6 @@ export default function delegateExtension(pi: ExtensionAPI) {
1415
1486
  rows: [
1416
1487
  { key: "run-general", label: "Run general task…", value: "", kind: "action" },
1417
1488
  { key: "run-research", label: "Run research task…", value: "", kind: "action" },
1418
- { key: "run-background", label: "Run background task…", value: "", kind: "action" },
1419
1489
  { key: "peek", label: "Peek live / final detail", value: "", kind: "action", disabled: !active && !last },
1420
1490
  { key: "cancel", label: "Cancel active run", value: "", kind: "action", disabled: !active },
1421
1491
  { key: "resume", label: "Resume last run…", value: "", kind: "action", disabled: !last },
@@ -1504,14 +1574,12 @@ export default function delegateExtension(pi: ExtensionAPI) {
1504
1574
  const role = action === "run-research" ? ("research" as const) : ("general" as const);
1505
1575
  const task = await ctx.ui.editor(`Delegated task (${role})`, "");
1506
1576
  if (!task || !task.trim()) continue;
1507
- await runCommandForeground(task, role, ctx);
1508
- continue;
1509
- }
1510
- // R20: user-facing background launch — spawn, return immediately.
1511
- if (action === "run-background") {
1512
- const task = await ctx.ui.editor("Background task (returns immediately)", "");
1513
- if (!task || !task.trim()) continue;
1514
- await runCommandBackground(task.trim(), "general", ctx);
1577
+ // R22: role-based actions honor the effective (default) mode.
1578
+ if (app.defaultExecution() === "foreground") {
1579
+ await launchForeground(task, role, ctx);
1580
+ } else {
1581
+ await runCommandBackground(task, role, ctx);
1582
+ }
1515
1583
  continue;
1516
1584
  }
1517
1585
  if (action === "peek") {
@@ -1544,7 +1612,12 @@ export default function delegateExtension(pi: ExtensionAPI) {
1544
1612
  }
1545
1613
  const task = await ctx.ui.editor(`Resume ${target.runId.slice(-12)} (${target.role})`, "");
1546
1614
  if (!task || !task.trim()) continue;
1547
- await runCommandForeground(task, target.role === "research" ? "research" : "general", ctx, undefined, { resumeFrom: target.runId });
1615
+ const role = target.role === "research" ? ("research" as const) : ("general" as const);
1616
+ if (app.defaultExecution() === "foreground") {
1617
+ await launchForeground(task, role, ctx, undefined, { resumeFrom: target.runId });
1618
+ } else {
1619
+ await runCommandBackground(task, role, ctx, undefined, { resumeFrom: target.runId });
1620
+ }
1548
1621
  continue;
1549
1622
  }
1550
1623
  if (action === "strict-toggle") {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maheidem/pi-delegate",
3
- "version": "0.6.4",
3
+ "version": "0.7.1",
4
4
  "type": "module",
5
5
  "description": "Foreground isolated delegation and strict coordinator mode for the Pi coding agent.",
6
6
  "license": "MIT",
package/runner.ts CHANGED
@@ -44,6 +44,14 @@ export interface RunnerConfig {
44
44
  /** R1: watchdog budget while a tool call is in flight (default: hard). */
45
45
  stuckToolTimeoutMs?: number;
46
46
  updateThrottleMs: number;
47
+ /** R23: progress-report policy (background runs; absent = no reports). */
48
+ progressReports?: {
49
+ enabled: boolean;
50
+ minToolMs: number;
51
+ intervalMs: number;
52
+ minGapMs: number;
53
+ maxPerRun: number;
54
+ };
47
55
  maxRecordBytes?: number;
48
56
  malformedThreshold?: number;
49
57
  }
@@ -53,6 +61,41 @@ export type PiInvocationResolver = (piPath?: string) => {
53
61
  args: string[];
54
62
  };
55
63
 
64
+ /**
65
+ * R23: the pure per-run progress throttle decision. `reason` is the fire
66
+ * point ("tool" for a long tool end, "heartbeat" for the interval timer);
67
+ * the minToolMs gate is applied by the caller before invoking this.
68
+ * Returns true when a report should be emitted (the caller then updates
69
+ * its state: reportsSent + 1, lastReportAt = now).
70
+ */
71
+ export interface ProgressThrottleState {
72
+ reportsSent: number;
73
+ lastReportAt: number;
74
+ startedMs: number;
75
+ }
76
+
77
+ export type ProgressReportConfig = {
78
+ enabled: boolean;
79
+ minToolMs: number;
80
+ intervalMs: number;
81
+ minGapMs: number;
82
+ maxPerRun: number;
83
+ };
84
+
85
+ export function shouldEmitProgress(
86
+ state: ProgressThrottleState,
87
+ now: number,
88
+ cfg: ProgressReportConfig,
89
+ reason: "tool" | "heartbeat",
90
+ ): boolean {
91
+ if (!cfg.enabled) return false;
92
+ if (state.reportsSent >= cfg.maxPerRun) return false;
93
+ const since = now - state.lastReportAt;
94
+ if (state.reportsSent > 0 && since < cfg.minGapMs) return false;
95
+ if (reason === "heartbeat" && now - state.startedMs < cfg.intervalMs) return false;
96
+ return true;
97
+ }
98
+
56
99
  /**
57
100
  * Robust Pi executable resolution (official example pattern, §9.4):
58
101
  * 1. current Pi script path (argv[1]) exists → node/bun + that script;
@@ -308,6 +351,9 @@ export class DelegateRunner {
308
351
  private readonly promptId: string;
309
352
  /** R16: steering sequence (follow_up record ids). */
310
353
  private steerSeq = 0;
354
+ /** R23: progress-report throttle state + heartbeat timer. */
355
+ private progressState: ProgressThrottleState = { reportsSent: 0, lastReportAt: 0, startedMs: 0 };
356
+ private progressTimer: NodeJS.Timeout | null = null;
311
357
 
312
358
  constructor(opened: OpenedRun, req: RunnerSpawnRequest, cfg: RunnerConfig, hooks: RunHooks = {}, resolveInvocation?: PiInvocationResolver) {
313
359
  this.opened = opened;
@@ -431,6 +477,14 @@ export class DelegateRunner {
431
477
  this.hardTimer = setTimeout(() => this.cancel("timed_out_hard"), this.cfg.hardTimeoutMs);
432
478
  this.hardTimer.unref();
433
479
 
480
+ // R23: progress-report heartbeat (background runs only — the hook is
481
+ // wired solely by the background spawn path).
482
+ this.progressState = { reportsSent: 0, lastReportAt: Date.now(), startedMs: this.startedAtMs };
483
+ if (this.hooks.onProgress && this.cfg.progressReports?.enabled && this.cfg.progressReports.intervalMs > 0) {
484
+ this.progressTimer = setInterval(() => this.maybeEmitProgress("heartbeat"), this.cfg.progressReports.intervalMs);
485
+ this.progressTimer.unref();
486
+ }
487
+
434
488
  // A fast-exiting child closes stdin before/as the prompt is written;
435
489
  // the resulting EPIPE must never escape as an unhandled stream error
436
490
  // (the exit handler already finalizes the run).
@@ -574,6 +628,14 @@ export class DelegateRunner {
574
628
  if (cls.toolName) this.toolNames.set(cls.id, cls.toolName);
575
629
  this.toolDetails.set(cls.id, feedDetailFor(cls.toolName ?? "", cls.args));
576
630
  } else if (cls.phase === "end") {
631
+ // R23: a long tool completion is a progress fire point —
632
+ // read the duration BEFORE the bookkeeping deletes it.
633
+ const toolStart = this.toolStartedAt.get(cls.id);
634
+ const toolDuration = toolStart != null ? Date.now() - toolStart : undefined;
635
+ const toolName = this.toolNames.get(cls.id);
636
+ if (toolName && toolDuration != null && toolDuration >= (this.cfg.progressReports?.minToolMs ?? Number.POSITIVE_INFINITY)) {
637
+ this.maybeEmitProgress("tool", { name: toolName, durationMs: toolDuration });
638
+ }
577
639
  this.openToolCalls.delete(cls.id);
578
640
  this.toolStartedAt.delete(cls.id);
579
641
  this.toolNames.delete(cls.id);
@@ -1234,6 +1296,27 @@ export class DelegateRunner {
1234
1296
  }
1235
1297
  }
1236
1298
 
1299
+ /** R23: shared throttle gate for both fire points; updates state on emit. */
1300
+ private maybeEmitProgress(reason: "tool" | "heartbeat", lastTool?: { name: string; durationMs: number }): void {
1301
+ const cfg = this.cfg.progressReports;
1302
+ const hook = this.hooks.onProgress;
1303
+ if (!cfg || !hook) return;
1304
+ const now = Date.now();
1305
+ if (!shouldEmitProgress(this.progressState, now, cfg, reason)) return;
1306
+ this.progressState = { ...this.progressState, reportsSent: this.progressState.reportsSent + 1, lastReportAt: now };
1307
+ try {
1308
+ hook({
1309
+ runId: this.runId,
1310
+ elapsedMs: this.startedAtMs ? now - this.startedAtMs : 0,
1311
+ ...(lastTool ? { lastTool } : {}),
1312
+ inFlightTools: this.openToolNames(),
1313
+ tokens: { input: this.usage.input, output: this.usage.output },
1314
+ });
1315
+ } catch {
1316
+ // progress failures never affect the run
1317
+ }
1318
+ }
1319
+
1237
1320
  private pushUpdate(phase: "starting" | "running" | `tool:${string}` | "finalizing"): void {
1238
1321
  if (!this.hooks.onUpdate) return;
1239
1322
  const now = Date.now();
@@ -1311,6 +1394,8 @@ export class DelegateRunner {
1311
1394
  // completion to guarantee the child is killed (short-lived refs).
1312
1395
  if (this.inactivityTimer) clearTimeout(this.inactivityTimer);
1313
1396
  if (this.hardTimer) clearTimeout(this.hardTimer);
1397
+ if (this.progressTimer) clearInterval(this.progressTimer);
1398
+ this.progressTimer = null;
1314
1399
  if (this.killGraceTimer) clearTimeout(this.killGraceTimer);
1315
1400
  if (this.settleExitTimer) clearTimeout(this.settleExitTimer);
1316
1401
  if (this.handoffGraceTimer) clearTimeout(this.handoffGraceTimer);
package/types.ts CHANGED
@@ -149,6 +149,9 @@ export interface DelegateDetails {
149
149
  sessionPath?: string;
150
150
  /** R7: resolved timeout provenance, e.g. "hard 45m (per-run) · idle 22m30s". */
151
151
  timeoutInfo?: string;
152
+ /** R22: validated 3–6-word purpose summary (required for every delegation;
153
+ * returned inline in the foreground result header). */
154
+ description?: string;
152
155
  transcriptPath: string;
153
156
  stderrPath: string;
154
157
  displayItems: DelegateDisplayItem[];
@@ -443,6 +446,8 @@ export type RunHooks = {
443
446
  onEvent?: (event: FeedEvent) => void;
444
447
  /** R17/R18: ask_parent channel events from the child stream. */
445
448
  onAsk?: (ask: { runId: string; phase: "start" | "end"; kind: "question" | "note"; topic: string; text: string; toolCallId: string }) => void;
449
+ /** R23: automatic progress report (background runs only). */
450
+ onProgress?: (p: { runId: string; elapsedMs: number; lastTool?: { name: string; durationMs: number }; inFlightTools: string[]; tokens: { input: number; output: number } }) => void;
446
451
  abortSignal?: AbortSignal;
447
452
  };
448
453