@maheidem/pi-delegate 0.7.0 → 0.7.2

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
@@ -200,6 +200,24 @@ export class DelegateApplicationImpl implements DelegateApplication {
200
200
  }
201
201
  }
202
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
+
203
221
  // ── Mode ───────────────────────────────────────────────────────────────
204
222
 
205
223
  isStrict(): boolean {
@@ -244,7 +262,7 @@ export class DelegateApplicationImpl implements DelegateApplication {
244
262
  }
245
263
 
246
264
  /** Advanced knobs for the dashboard's Configure-advanced screen (§ S7). */
247
- panelConfig(): Pick<DelegateConfigV1, "queueLimit" | "killGraceMs" | "handoffGraceMs" | "handoffEnforceTimeoutMs" | "stuckToolTimeoutMs" | "maxTaskBytes" | "maxResultBytes" | "updateThrottleMs" | "defaultRole" | "defaultExecution" | "maxRuns" | "maxRunAgeDays"> {
265
+ panelConfig(): Pick<DelegateConfigV1, "queueLimit" | "killGraceMs" | "handoffGraceMs" | "handoffEnforceTimeoutMs" | "stuckToolTimeoutMs" | "maxTaskBytes" | "maxResultBytes" | "updateThrottleMs" | "defaultRole" | "defaultExecution" | "maxRuns" | "maxRunAgeDays" | "progressReports"> {
248
266
  const c = this.liveConfig;
249
267
  return {
250
268
  queueLimit: c.queueLimit,
@@ -259,6 +277,7 @@ export class DelegateApplicationImpl implements DelegateApplication {
259
277
  defaultExecution: c.defaultExecution,
260
278
  maxRuns: c.maxRuns,
261
279
  maxRunAgeDays: c.maxRunAgeDays,
280
+ progressReports: c.progressReports,
262
281
  };
263
282
  }
264
283
 
@@ -383,7 +402,7 @@ export class DelegateApplicationImpl implements DelegateApplication {
383
402
  /** R8: spawn a background run — same validation and spawn path as the
384
403
  * foreground, but no slot reservation, no queue, and the caller gets a
385
404
  * live handle instead of the terminal result. */
386
- 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 } {
387
406
  const prepared = this.prepareRun(request);
388
407
  if ("error" in prepared) return { error: prepared.error };
389
408
  const { opened, role, task, model, cfg, timeoutInfo, modelNote, resumeOf, sessionPath, sessionDir } = prepared;
@@ -413,7 +432,7 @@ export class DelegateApplicationImpl implements DelegateApplication {
413
432
  ...(sessionDir ? { sessionDir } : {}),
414
433
  ...(askDir && askTimeoutMs ? { background: true, askDir, askTimeoutMs, ...(askMaxQuestions ? { askMaxQuestions } : {}) } : {}),
415
434
  },
416
- cfg,
435
+ { ...cfg, progressReports: this.liveConfig.progressReports },
417
436
  {
418
437
  onUpdate: (u: RunStreamUpdate) => {
419
438
  streamEntry.latest = u;
@@ -422,6 +441,7 @@ export class DelegateApplicationImpl implements DelegateApplication {
422
441
  ring.push(e);
423
442
  },
424
443
  ...(hooks.onAsk ? { onAsk: hooks.onAsk } : {}),
444
+ ...(hooks.onProgress ? { onProgress: hooks.onProgress } : {}),
425
445
  },
426
446
  this.ports.resolveInvocation ?? resolvePiInvocation,
427
447
  );
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
@@ -25,6 +25,8 @@ export type DelegateIntent =
25
25
  | { kind: "resume"; runId?: string; task: string; timeoutMs?: number; execution?: "background" | "foreground" }
26
26
  | { kind: "peek"; runId?: string }
27
27
  | { kind: "run"; role: RoleName; task: string; explicit: boolean; timeoutMs?: number; execution?: "background" | "foreground" }
28
+ | { kind: "set"; field: string; value: string }
29
+ | { kind: "set-project"; field: string; value: string }
28
30
  | { kind: "invalid"; token: string; usage: string };
29
31
 
30
32
  export const DELEGATE_USAGE = [
@@ -39,6 +41,8 @@ export const DELEGATE_USAGE = [
39
41
  "/delegate peek [run-id] live/final feed of a run's child activity",
40
42
  "/delegate inspect [run-id] show run metadata (defaults to latest)",
41
43
  "/delegate run <general|research> <task...> run with an explicit role",
44
+ "/delegate set <field> <value> set a user-wide config knob (e.g. set queueLimit 4)",
45
+ "/delegate set-project <field> <value> set a knob in the project .pi/delegate/config.json overlay",
42
46
  "/delegate fg [general|research] <task...> run in the FOREGROUND (blocks until done)",
43
47
  "/delegate research <task...> research-role shorthand",
44
48
  "/delegate <task...> general-role shorthand",
@@ -63,6 +67,8 @@ export const RESERVED_FIRST_TOKENS = new Set([
63
67
  "peek",
64
68
  "run",
65
69
  "research",
70
+ "set",
71
+ "set-project",
66
72
  ]);
67
73
 
68
74
  export interface ParseOptions {
@@ -180,6 +186,24 @@ export function parseDelegateCommand(input: string, options: ParseOptions = {}):
180
186
  if (!task) return invalid("research");
181
187
  return { kind: "run", role: "research", task, explicit: true, timeoutMs, ...(execution ? { execution } : {}) };
182
188
  }
189
+ case "set": {
190
+ // Panel≡command parity: the advanced-config input rows dispatch
191
+ // through patchConfig — `set` is their command twin. Field validation
192
+ // is a runtime concern (the app method owns it), not grammar.
193
+ const rest = trimmed.slice("set".length).trim();
194
+ const field = rest.split(/\s+/)[0] ?? "";
195
+ const value = rest.slice(field.length).trim();
196
+ if (!field || !value) return { kind: "invalid", token: "set", usage: "/delegate set <field> <value>" };
197
+ return { kind: "set", field, value };
198
+ }
199
+ case "set-project": {
200
+ // Same shape as `set`, but targets the project overlay file.
201
+ const rest = trimmed.slice("set-project".length).trim();
202
+ const field = rest.split(/\s+/)[0] ?? "";
203
+ const value = rest.slice(field.length).trim();
204
+ if (!field || !value) return { kind: "invalid", token: "set-project", usage: "/delegate set-project <field> <value>" };
205
+ return { kind: "set-project", field, value };
206
+ }
183
207
  }
184
208
  return invalid(first);
185
209
  }
@@ -192,7 +216,7 @@ function invalid(token: string): DelegateIntent {
192
216
  export function delegateCompletions(prefix: string, recentRunIds: string[] = []): string[] {
193
217
  const words = (prefix ?? "").trimStart();
194
218
  const tokens = words.split(/\s+/);
195
- const base: string[] = ["on", "off", "status", "paths", "doctor", "help", "cancel ", "answer ", "bg ", "fg ", "inspect ", "resume ", "peek ", "run ", "research "];
219
+ const base: string[] = ["on", "off", "status", "paths", "doctor", "help", "cancel ", "answer ", "bg ", "fg ", "inspect ", "resume ", "peek ", "run ", "research ", "set ", "set-project "];
196
220
 
197
221
  const matches: string[] = [];
198
222
  if (tokens.length <= 1) {
@@ -213,7 +237,7 @@ export function delegateCompletions(prefix: string, recentRunIds: string[] = [])
213
237
  }
214
238
  }
215
239
  // De-duplicate, keep order, cap for the TUI (all primary verbs fit).
216
- return [...new Set(matches)].slice(0, 15);
240
+ return [...new Set(matches)].slice(0, 17);
217
241
  }
218
242
 
219
243
  /**
package/config.ts CHANGED
@@ -31,6 +31,14 @@ export interface DelegateConfigV1 {
31
31
  defaultExecution: "background" | "foreground";
32
32
  /** R9: concurrent background children (default 3, clamp 1–8). */
33
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
+ };
34
42
  /** R17/R18: ask_parent channel (background children). */
35
43
  askParent: {
36
44
  enabled: boolean;
@@ -56,6 +64,13 @@ export const DEFAULT_DELEGATE_CONFIG: DelegateConfigV1 = {
56
64
  updateThrottleMs: 100,
57
65
  defaultExecution: "background",
58
66
  maxBackgroundRuns: 3,
67
+ progressReports: {
68
+ enabled: true,
69
+ minToolMs: 60_000,
70
+ intervalMs: 300_000,
71
+ minGapMs: 120_000,
72
+ maxPerRun: 6,
73
+ },
59
74
  askParent: {
60
75
  enabled: true,
61
76
  timeoutMs: 600_000,
@@ -103,7 +118,13 @@ const MAX_VALUES: Partial<Record<keyof DelegateConfigV1, number>> = {
103
118
  export function normalizeConfig(
104
119
  raw: unknown,
105
120
  ): { config: DelegateConfigV1; unknownKeys: string[] } {
106
- 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
+ };
107
128
  const unknownKeys: string[] = [];
108
129
  const extras: Record<string, unknown> = {};
109
130
  const known = new Set<string>(Object.keys(base));
@@ -152,6 +173,24 @@ function applyKnownField(config: DelegateConfigV1, key: string, value: unknown):
152
173
  }
153
174
  return;
154
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
+ }
155
194
  if (key === "askParent") {
156
195
  if (!value || typeof value !== "object" || Array.isArray(value)) return;
157
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,
@@ -513,6 +515,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
513
515
  refreshDoctor(ctx);
514
516
  const attempt = app.runBackground(request, {
515
517
  onAsk: (ask) => background.onAsk(ask),
518
+ onProgress: (p) => background.onProgress(p),
516
519
  });
517
520
  if ("error" in attempt) {
518
521
  return {
@@ -870,6 +873,18 @@ export default function delegateExtension(pi: ExtensionAPI) {
870
873
  return new Text(`[delegate ${d.runId ?? "?"} · ${d.role ?? "?"} · ${d.state ?? "?"}]\n\n${text}`, 0, 0);
871
874
  });
872
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
+
873
888
  // ── R15: background result renderer (neutral glyph+word, no model-only text)
874
889
 
875
890
  pi.registerMessageRenderer(BACKGROUND_RESULT_TYPE, (message: { content?: string | unknown[]; details?: unknown }) => {
@@ -1035,6 +1050,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
1035
1050
  refreshDoctor(ctx);
1036
1051
  const attempt = app.runBackground(request, {
1037
1052
  onAsk: (ask) => background.onAsk(ask),
1053
+ onProgress: (p) => background.onProgress(p),
1038
1054
  });
1039
1055
  if ("error" in attempt) {
1040
1056
  say(ctx, formatRunText(attempt.error), "error");
@@ -1101,6 +1117,8 @@ export default function delegateExtension(pi: ExtensionAPI) {
1101
1117
  "/delegate status stable status text",
1102
1118
  "/delegate run general <task> run a delegation with a role",
1103
1119
  "/delegate research <task> research role",
1120
+ "/delegate set <field> <value> set a user-wide config knob (e.g. set queueLimit 4)",
1121
+ "/delegate set-project <field> <value> set a knob in the project .pi/delegate/config.json overlay",
1104
1122
  "/delegate bg [role] <task> run it in the background (report arrives later)",
1105
1123
  "/delegate fg [role] <task> run it in the foreground (blocks until done)",
1106
1124
  "/delegate <task> general-role shorthand",
@@ -1120,7 +1138,10 @@ export default function delegateExtension(pi: ExtensionAPI) {
1120
1138
 
1121
1139
  const doctorText = (): string => {
1122
1140
  const report = app.doctor();
1123
- const lines = [`[delegate doctor] ${report.ok ? "OK" : "ISSUES FOUND"}`];
1141
+ const lines = [
1142
+ `[delegate doctor] ${report.ok ? "OK" : "ISSUES FOUND"}`,
1143
+ `version: v${delegateVersion()} (loaded at session start; /reload picks up newer installs)`,
1144
+ ];
1124
1145
  for (const c of report.checks) lines.push(` ${c.status === "ok" ? "✓" : c.status === "warning" ? "!" : "✗"} ${c.name}: ${c.detail}`);
1125
1146
  return lines.join("\n");
1126
1147
  };
@@ -1257,6 +1278,19 @@ export default function delegateExtension(pi: ExtensionAPI) {
1257
1278
  }
1258
1279
  return;
1259
1280
  }
1281
+ case "set": {
1282
+ // Panel≡command parity: same app method as the advanced-config
1283
+ // input rows (cfg:user:*). patchConfig owns field validation.
1284
+ const err = app.patchConfig(intent.field, intent.value);
1285
+ say(ctx, err ? `[delegate] ${err}` : `[delegate] set ${intent.field} = ${intent.value} (user config)`, err ? "warning" : "info");
1286
+ return;
1287
+ }
1288
+ case "set-project": {
1289
+ // Same method as the cfg:project:* input rows.
1290
+ const err = app.patchProjectConfig(ctx.cwd ?? process.cwd(), intent.field, intent.value);
1291
+ say(ctx, err ? `[delegate] ${err}` : `[delegate] set ${intent.field} = ${intent.value} (project config)`, err ? "warning" : "info");
1292
+ return;
1293
+ }
1260
1294
  case "invalid":
1261
1295
  say(ctx, `[delegate] unrecognized '${intent.token}'.\n${intent.usage}\n${helpText()}`, "error");
1262
1296
  return;
@@ -1347,6 +1381,7 @@ export default function delegateExtension(pi: ExtensionAPI) {
1347
1381
  { key: "cfg:user:updateThrottleMs", label: "Update throttle", value: formatDuration(c.updateThrottleMs), rawValue: String(c.updateThrottleMs), kind: "input", inputHint: "live update cadence" },
1348
1382
  { key: "info:defaultRole", label: "Default role", value: c.defaultRole, kind: "info" },
1349
1383
  { key: "exec-default-toggle", label: "Execution default", value: c.defaultExecution, kind: "action" },
1384
+ { key: "progress-toggle", label: "Progress reports", value: c.progressReports.enabled ? "on" : "off", kind: "action" },
1350
1385
  { key: "info:retention", label: "Retention", value: `${c.maxRuns} runs · ${c.maxRunAgeDays}d`, kind: "info" },
1351
1386
  ];
1352
1387
  };
@@ -1375,6 +1410,12 @@ export default function delegateExtension(pi: ExtensionAPI) {
1375
1410
  const err = app.patchDefaultExecution(next);
1376
1411
  return err ? { kind: "error", message: err } : { kind: "updated", message: `Execution default: ${next}` };
1377
1412
  }
1413
+ // R23: the progress-reports toggle flips enabled in place.
1414
+ if (key === "progress-toggle") {
1415
+ const next = !app.panelConfig().progressReports.enabled;
1416
+ const err = app.patchProgressReportsEnabled(next);
1417
+ return err ? { kind: "error", message: err } : { kind: "updated", message: `Progress reports: ${next ? "on" : "off"}` };
1418
+ }
1378
1419
  return { kind: "close", action: "advanced-done" };
1379
1420
  },
1380
1421
  requestRender: () => tui.requestRender(),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maheidem/pi-delegate",
3
- "version": "0.7.0",
3
+ "version": "0.7.2",
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
@@ -446,6 +446,8 @@ export type RunHooks = {
446
446
  onEvent?: (event: FeedEvent) => void;
447
447
  /** R17/R18: ask_parent channel events from the child stream. */
448
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;
449
451
  abortSignal?: AbortSignal;
450
452
  };
451
453