@maheidem/pi-delegate 0.2.3 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -45,6 +45,38 @@ is performed by this package.
45
45
 
46
46
  Any unrecognized first word is shorthand for `run general …`.
47
47
 
48
+ ### Terminal UI (v0.3.0)
49
+
50
+ One centralized experience built on the vendored canonical `SettingsPanel`
51
+ (never a bespoke panel). Everything reachable from the panel is also reachable
52
+ as a nested command and from headless stdout — the same application method.
53
+
54
+ - **Home dashboard** (`/delegate`, TUI) — health summary (version · mode,
55
+ active/idle, last run) + **Actions** (Run general/research, Peek, Cancel,
56
+ Resume, strict toggle, `Configure advanced… ›`, Doctor, Paths) + base
57
+ **Timeouts** (user & project). Keys: `↑↓/jk` move, `enter` select, `esc/q`
58
+ close; shortcuts `r run · p peek · x cancel · c configure · d doctor · s status`.
59
+ - **Live dashboard** — while a run is active the home panel mirrors it live
60
+ (`refresh` 1 s): phase · short model · fixed progress bar · tokens
61
+ `↑in ↓out` (primary) · `$cost` (secondary, dim) · in-flight tools · tail.
62
+ - **Inline execution (both paths).** Slash path shows a fixed-height strip
63
+ above the composer (`RunningView`) with progress, in-flight and a feed; the
64
+ model path renders the same liveness through the tool's `renderCall` /
65
+ `renderResult`. Terminal results render as a neutral card — `✓ done`,
66
+ `⊘ cancelled`, `⏱ timeout · idle/hard`, `✗ failed` — glyph+word (never a
67
+ bare `error:`), tokens primary, with a partial-handoff tail + resume hint
68
+ on cancel/timeout.
69
+ - **Peek** (`/delegate peek [runId]`) — detailed fixed-height overlay
70
+ (`PeekView`, full model id, relative-stamped event feed); `q` returns home.
71
+ - **Advanced config** (`Configure advanced… ›`) — queue limit, stuck-tool
72
+ watchdog, kill/handoff grace/enforce, max task/result bytes, default role —
73
+ edited through the same generic `patchConfig`; `esc` returns home.
74
+ - **Destructive actions** (cancel, strict on/off) require confirmation.
75
+
76
+ Headless (`pi -p` / child mode) prints the same status/doctor/paths text, so
77
+ panel ≡ command ≡ headless. Screens with pixel evidence live in
78
+ `.planning/ui-redesign-2026-09-04/evidence/` (see `manifest.json`).
79
+
48
80
  ### Timeouts
49
81
 
50
82
  Three levels, highest priority first:
package/application.ts CHANGED
@@ -30,9 +30,11 @@ import type {
30
30
  RunInspection,
31
31
  RunMetadataV1,
32
32
  RunnerOutcome,
33
+ RunStreamUpdate,
33
34
  TranscriptRecordV1,
34
35
  SessionEntryLike,
35
36
  } from "./types.ts";
37
+ import { FeedRing, type FeedEvent } from "./transcript-feed.ts";
36
38
  import { decodeTranscriptRecord } from "./types.ts";
37
39
  import { applyProjectOverlay, clampConfigField, formatDuration, normalizeConfig, parseDuration, projectConfigPath, resolveRunTimeouts, saveConfig, saveProjectConfig, type DelegateConfigV1 } from "./config.ts";
38
40
  import { EMPTY_USAGE } from "./types.ts";
@@ -62,6 +64,8 @@ interface ActiveRunReservation {
62
64
  role: RoleName;
63
65
  runner: DelegateRunner;
64
66
  startedAt: string;
67
+ /** Effective hard cap for the live progress bar (§ S2). */
68
+ hardMs: number;
65
69
  }
66
70
 
67
71
  /**
@@ -110,6 +114,9 @@ function errorResult(
110
114
 
111
115
  export class DelegateApplicationImpl implements DelegateApplication {
112
116
  private activeRun: ActiveRunReservation | null = null;
117
+ /** Live state of the active run, captured for the home dashboard (§ S2). */
118
+ private activeStream: RunStreamUpdate | null = null;
119
+ private activeRing: FeedRing = new FeedRing(120);
113
120
  private runQueue: QueuedRun[] = [];
114
121
  private readonly modeRuntime: ModeRuntime;
115
122
  private readonly ports: DelegateApplicationPorts;
@@ -195,6 +202,31 @@ export class DelegateApplicationImpl implements DelegateApplication {
195
202
  return { runId: this.activeRun.id, role: this.activeRun.role, startedAt: this.activeRun.startedAt };
196
203
  }
197
204
 
205
+ /** Live state of the active run (identity update + feed events + queue),
206
+ * for the home dashboard's Live block. Null when nothing is running. */
207
+ getActiveRunStream(): { update: RunStreamUpdate; events: readonly FeedEvent[]; queue: number; hardMs: number } | null {
208
+ if (!this.activeRun || !this.activeStream) return null;
209
+ return { update: this.activeStream, events: this.activeRing.all(), queue: this.runQueue.length, hardMs: this.activeRun.hardMs };
210
+ }
211
+
212
+ /** Advanced knobs for the dashboard's Configure-advanced screen (§ S7). */
213
+ panelConfig(): Pick<DelegateConfigV1, "queueLimit" | "killGraceMs" | "handoffGraceMs" | "handoffEnforceTimeoutMs" | "stuckToolTimeoutMs" | "maxTaskBytes" | "maxResultBytes" | "updateThrottleMs" | "defaultRole" | "maxRuns" | "maxRunAgeDays"> {
214
+ const c = this.liveConfig;
215
+ return {
216
+ queueLimit: c.queueLimit,
217
+ killGraceMs: c.killGraceMs,
218
+ handoffGraceMs: c.handoffGraceMs,
219
+ handoffEnforceTimeoutMs: c.handoffEnforceTimeoutMs,
220
+ stuckToolTimeoutMs: c.stuckToolTimeoutMs,
221
+ maxTaskBytes: c.maxTaskBytes,
222
+ maxResultBytes: c.maxResultBytes,
223
+ updateThrottleMs: c.updateThrottleMs,
224
+ defaultRole: c.defaultRole,
225
+ maxRuns: c.maxRuns,
226
+ maxRunAgeDays: c.maxRunAgeDays,
227
+ };
228
+ }
229
+
198
230
  /**
199
231
  * Canonical entry point shared by tool and command. ONE child executes at
200
232
  * a time (POL-005): concurrent calls queue (bounded by `queueLimit`) and
@@ -351,6 +383,20 @@ export class DelegateApplicationImpl implements DelegateApplication {
351
383
  }
352
384
 
353
385
  // 8. Reservation NOW covers the child lifecycle.
386
+ // Capture live state for the home dashboard while forwarding the caller's hooks.
387
+ this.activeStream = null;
388
+ this.activeRing = new FeedRing(120);
389
+ const captureHooks: RunHooks = {
390
+ ...hooks,
391
+ onUpdate: (u: RunStreamUpdate) => {
392
+ this.activeStream = u;
393
+ hooks.onUpdate?.(u);
394
+ },
395
+ onEvent: (e: FeedEvent) => {
396
+ this.activeRing.push(e);
397
+ hooks.onEvent?.(e);
398
+ },
399
+ };
354
400
  const runner = new DelegateRunner(
355
401
  opened,
356
402
  {
@@ -368,7 +414,7 @@ export class DelegateApplicationImpl implements DelegateApplication {
368
414
  ...(sessionDir ? { sessionDir } : {}),
369
415
  },
370
416
  cfg,
371
- hooks,
417
+ captureHooks,
372
418
  this.ports.resolveInvocation ?? resolvePiInvocation,
373
419
  );
374
420
  const reservation: ActiveRunReservation = {
@@ -376,6 +422,7 @@ export class DelegateApplicationImpl implements DelegateApplication {
376
422
  role: role.name,
377
423
  runner,
378
424
  startedAt: opened.metadata.createdAt,
425
+ hardMs: timeouts.hardMs,
379
426
  };
380
427
  this.activeRun = reservation;
381
428
 
package/commands.ts CHANGED
@@ -43,7 +43,7 @@ export const DELEGATE_USAGE = [
43
43
  "/delegate help this help",
44
44
  ].join("\n");
45
45
 
46
- const RESERVED_FIRST_TOKENS = new Set([
46
+ export const RESERVED_FIRST_TOKENS = new Set([
47
47
  "on",
48
48
  "off",
49
49
  "status",
@@ -163,8 +163,8 @@ export function delegateCompletions(prefix: string, recentRunIds: string[] = [])
163
163
  if (id.startsWith(p)) matches.push(`${id} `);
164
164
  }
165
165
  }
166
- // De-duplicate, keep order, cap for the TUI.
167
- return [...new Set(matches)].slice(0, 10);
166
+ // De-duplicate, keep order, cap for the TUI (all primary verbs fit).
167
+ return [...new Set(matches)].slice(0, 14);
168
168
  }
169
169
 
170
170
  /**
package/index.ts CHANGED
@@ -38,7 +38,8 @@ import type {
38
38
  RunStreamUpdate,
39
39
  SessionEntryLike,
40
40
  } from "./types.ts";
41
- import { SettingsPanel, type PanelSnapshot, type PanelActionResult } from "./ui/settings-panel.ts";
41
+ import { SettingsPanel, type PanelSnapshot, type PanelActionResult, type PanelSection, type PanelRow } from "./ui/settings-panel.ts";
42
+ import { shortModel, formatTokens, formatCost, stateGlyph, progressBar } from "./ui/format.ts";
42
43
  import { RunningView, type RunningViewState } from "./ui/running-view.ts";
43
44
  import { PeekView } from "./ui/peek-view.ts";
44
45
  import { FeedRing, feedEventsFromTranscript, renderFeedEvents } from "./transcript-feed.ts";
@@ -408,9 +409,10 @@ export default function delegateExtension(pi: ExtensionAPI) {
408
409
  const hooks = {
409
410
  abortSignal: signal ?? undefined,
410
411
  onUpdate: (u: RunStreamUpdate) => {
411
- const modelBit = u.model ? ` · ${u.model}` : "";
412
+ const head = `[delegate v${delegateVersion()} ${shortModel(u.model) || u.role} · ${u.phase} · ${Math.round(u.elapsedMs / 1000)}s]`;
413
+ const tail = (u.lastActions ?? []).slice(-2).map((l) => ` ${l}`);
412
414
  onUpdate?.({
413
- content: [{ type: "text", text: `[delegate v${delegateVersion()} ${u.runId} · ${u.role}${modelBit} · ${u.phase} · ${Math.round(u.elapsedMs / 1000)}s]` }],
415
+ content: [{ type: "text", text: tail.length ? `${head}\n${tail.join("\n")}` : head }],
414
416
  details: { runId: u.runId, phase: u.phase },
415
417
  });
416
418
  },
@@ -435,7 +437,8 @@ export default function delegateExtension(pi: ExtensionAPI) {
435
437
  renderCall(args: any, theme: any) {
436
438
  const role = typeof args.role === "string" ? args.role : config.defaultRole;
437
439
  const task = typeof args.task === "string" ? args.task : "";
438
- const text = `delegate(${role}): ${task.length > 70 ? `${task.slice(0, 67)}…` : task}`;
440
+ const modelBit = typeof args.model === "string" && args.model ? ` · ${shortModel(args.model)}` : "";
441
+ const text = `→ delegate · ${role}${modelBit}: ${task.length > 64 ? `${task.slice(0, 61)}…` : task}`;
439
442
  return new Text(theme?.fg ? theme.fg("accent", text) : text, 0, 0);
440
443
  },
441
444
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -446,22 +449,31 @@ export default function delegateExtension(pi: ExtensionAPI) {
446
449
  return new Text(text || "(no output)", 0, 0);
447
450
  }
448
451
  const fg = (kind: string, s: string) => (theme?.fg ? theme.fg(kind, s) : s);
449
- const u = d.usage ?? {};
450
- const bits: string[] = [`${d.role ?? "?"} · ${d.state ?? "?"}`];
451
- if (u.input) bits.push(`↑${u.input}`);
452
- if (u.output) bits.push(`↓${u.output}`);
453
- if (u.cost) bits.push(`$${u.cost.toFixed(4)}`);
454
- const header = `→ ${d.runId}`;
452
+ const u = d.usage ?? ({} as DelegateDetails["usage"]);
453
+ // Neutral, non-color-alone state word (cancelled ≠ failed ≠ timeout).
454
+ const g = stateGlyph(d.state);
455
+ const bits: string[] = [`${d.role} ${g.glyph} ${g.word}`, `${Math.round(d.durationMs / 1000)}s`];
456
+ if (d.model) bits.push(shortModel(d.model));
457
+ bits.push(`↑${formatTokens(u.input)} ↓${formatTokens(u.output)}`);
458
+ if (u.cost) bits.push(formatCost(u.cost));
459
+ const header = `→ ${d.runId.slice(-16)}`;
460
+ const color = g.color;
455
461
  if (!options?.expanded) {
456
- const body = bits.join(" ") + (d.outputTruncated && d.transcriptPath ? `\ntranscript: ${d.transcriptPath}` : "");
457
- return new Text(`${fg("accent", header)}\n${body}`, 0, 0);
462
+ const lines = [fg("accent", header), fg(color, bits.join(" "))];
463
+ // Inline tail ≤5 — partial handoff (timeout/cancel) or reason, never bare.
464
+ const tailSrc: string = d.partialHandoff ?? (d.state === "succeeded" ? "" : (result.content ?? []).map((c: { text?: string }) => c.text ?? "").join(" ").split("\n")[0] ?? "");
465
+ const tail = tailSrc ? tailSrc.split("\n").map((l: string) => l.trim()).filter(Boolean).slice(0, 5) : [];
466
+ for (const t of tail) lines.push(fg("muted", ` ${t}`));
467
+ if (d.outputTruncated && d.transcriptPath) lines.push(fg("muted", ` transcript: ${d.transcriptPath}`));
468
+ return new Text(lines.join("\n"), 0, 0);
458
469
  }
459
- // Expanded: compact summary — Outcome + key lines + last actions.
460
- const res = result as unknown as DelegateRunResult;
461
- const summary = formatRunSummary(res);
462
- const stateColor = d.state === "succeeded" ? "success" : d.state === "cancelled" ? "muted" : "warning";
463
- const body = bits.join(" ") + (summary ? `\n${summary}` : "");
464
- return new Text(`${fg("accent", header)}\n${fg(stateColor, body)}`, 0, 0);
470
+ // Expanded: identity + canonical summary + resume hint.
471
+ const summary = formatRunSummary(result as unknown as DelegateRunResult);
472
+ const lines = [fg("accent", header), fg(color, bits.join(" "))];
473
+ if (summary) for (const l of summary.split("\n")) lines.push(l);
474
+ if (d.sessionPath && d.state !== "succeeded") lines.push(fg("muted", ` resume: resumeFrom ${d.runId}`));
475
+ if (d.transcriptPath) lines.push(fg("muted", ` transcript: ${d.transcriptPath}`));
476
+ return new Text(lines.join("\n"), 0, 0);
465
477
  },
466
478
  });
467
479
 
@@ -741,63 +753,10 @@ export default function delegateExtension(pi: ExtensionAPI) {
741
753
  say(ctx, "[delegate] no runs to peek at.", "warning");
742
754
  return;
743
755
  }
744
- let meta;
745
- try {
746
- meta = app.inspect(id).metadata;
747
- } catch {
748
- say(ctx, `[delegate] unknown run '${id}'.`, "error");
749
- return;
750
- }
751
- if (!fsSync.existsSync(meta.transcriptPath)) {
752
- say(ctx, `[delegate] no transcript captured for ${id}.`, "warning");
753
- return;
754
- }
755
- if (ctx.mode === "tui") {
756
- await ctx.ui.custom<{ closed?: boolean } | undefined>((tui, theme, keybindings, done) => {
757
- const state = () => {
758
- let live = false;
759
- try {
760
- live = !["succeeded", "failed", "cancelled", "timed_out_idle", "timed_out_hard", "crashed"].includes(app.inspect(id).metadata.state);
761
- } catch {
762
- live = false;
763
- }
764
- const { startMs, events } = feedEventsFromTranscript(meta.transcriptPath, { maxEvents: 400 });
765
- return {
766
- title: `${id.slice(-16)} · ${meta.role}${meta.model ? ` · ${meta.model}` : ""} · ${meta.state}`,
767
- summary: meta.transcriptPath,
768
- lines: renderFeedEvents(events, { startMs: startMs || Date.now(), maxChars: 150 }),
769
- live,
770
- };
771
- };
772
- // Live-follow refresh timer; cleared the moment the
773
- // overlay closes (done wrapper) — never leaks.
774
- let timer: ReturnType<typeof setInterval> | undefined;
775
- const wrappedDone = (result: { closed?: boolean }) => {
776
- if (timer) clearInterval(timer);
777
- done(result);
778
- };
779
- const view = new PeekView({ theme, keybindings, state, done: wrappedDone });
780
- timer = setInterval(() => tui.requestRender(), 1000);
781
- return view;
782
- }, {
783
- overlay: true,
784
- overlayOptions: {
785
- width: "92%",
786
- minWidth: 60,
787
- maxHeight: "80%",
788
- anchor: "center",
789
- },
790
- });
791
- } else {
792
- const { startMs, events } = feedEventsFromTranscript(meta.transcriptPath, { maxEvents: 400 });
793
- const lines = renderFeedEvents(events, { startMs: startMs || Date.now(), maxChars: 200 });
794
- say(
795
- ctx,
796
- `[delegate peek ${id} · ${meta.role} · ${meta.state}]\n${meta.transcriptPath}\n${lines.slice(-40).join("\n")}`,
797
- );
798
- }
756
+ await openPeek(ctx, id);
799
757
  return;
800
758
  }
759
+
801
760
  case "resume": {
802
761
  const runId = intent.runId?.trim();
803
762
  if (!runId || !intent.task) {
@@ -824,72 +783,200 @@ export default function delegateExtension(pi: ExtensionAPI) {
824
783
 
825
784
  // ── Dashboard (§12.2) ───────────────────────────────────────────────────
826
785
 
786
+ // ── 5b. Unified peek (shared by slash `peek` + dashboard `peek`) ────────
787
+
788
+ const openPeek = async (ctx: ExtensionCommandContext, runId?: string): Promise<void> => {
789
+ const id = runId?.trim() || app.mostRecentRunId();
790
+ if (!id) {
791
+ say(ctx, "[delegate] no runs to peek at.", "warning");
792
+ return;
793
+ }
794
+ let meta;
795
+ try {
796
+ meta = app.inspect(id).metadata;
797
+ } catch {
798
+ say(ctx, `[delegate] unknown run '${id}'.`, "error");
799
+ return;
800
+ }
801
+ if (!fsSync.existsSync(meta.transcriptPath)) {
802
+ say(ctx, `[delegate] no transcript captured for ${id}.`, "warning");
803
+ return;
804
+ }
805
+ if (ctx.mode === "tui") {
806
+ await ctx.ui.custom<{ closed?: boolean } | undefined>((tui, theme, keybindings, done) => {
807
+ const state = () => {
808
+ let live = false;
809
+ try {
810
+ live = !["succeeded", "failed", "cancelled", "timed_out_idle", "timed_out_hard", "crashed"].includes(app.inspect(id).metadata.state);
811
+ } catch {
812
+ live = false;
813
+ }
814
+ const { startMs, events } = feedEventsFromTranscript(meta.transcriptPath, { maxEvents: 400 });
815
+ return {
816
+ title: `${id.slice(-16)} · ${meta.role}${meta.model ? ` · ${shortModel(meta.model)}` : ""} · ${meta.state}`,
817
+ summary: meta.transcriptPath,
818
+ lines: renderFeedEvents(events, { startMs: startMs || Date.now(), maxChars: 150 }),
819
+ live,
820
+ };
821
+ };
822
+ // Live-follow refresh timer; cleared the moment the overlay
823
+ // closes (done wrapper) — never leaks past `q`/esc.
824
+ let timer: ReturnType<typeof setInterval> | undefined;
825
+ const wrappedDone = (result: { closed?: boolean }) => {
826
+ if (timer) clearInterval(timer);
827
+ done(result);
828
+ };
829
+ const view = new PeekView({ theme, keybindings, state, done: wrappedDone });
830
+ timer = setInterval(() => tui.requestRender(), 1000);
831
+ return view;
832
+ }, {
833
+ overlay: true,
834
+ overlayOptions: { width: "92%", minWidth: 60, maxHeight: "80%", anchor: "center" },
835
+ });
836
+ } else {
837
+ const { startMs, events } = feedEventsFromTranscript(meta.transcriptPath, { maxEvents: 400 });
838
+ const lines = renderFeedEvents(events, { startMs: startMs || Date.now(), maxChars: 200 });
839
+ say(ctx, `[delegate peek ${id} · ${meta.role} · ${meta.state}]\n${meta.transcriptPath}\n${lines.slice(-40).join("\n")}`);
840
+ }
841
+ };
842
+
843
+ // ── 5c. Advanced configuration (secondary screen, opened from home) ──────
844
+
845
+ const openAdvanced = async (ctx: ExtensionCommandContext, projectRoot: string): Promise<void> => {
846
+ const buildRows = (): PanelRow[] => {
847
+ const c = app.panelConfig();
848
+ return [
849
+ { key: "cfg:user:queueLimit", label: "Queue limit", value: String(c.queueLimit), rawValue: String(c.queueLimit), kind: "input", inputHint: "concurrent calls that wait (1–10)" },
850
+ { key: "cfg:user:stuckToolTimeoutMs", label: "Stuck-tool watchdog", value: c.stuckToolTimeoutMs != null ? formatDuration(c.stuckToolTimeoutMs) : "hard (default)", rawValue: c.stuckToolTimeoutMs != null ? String(c.stuckToolTimeoutMs) : "", kind: "input", inputHint: "idle budget while a tool runs; leave hard blank to inherit" },
851
+ { key: "cfg:user:killGraceMs", label: "Kill grace", value: formatDuration(c.killGraceMs), rawValue: String(c.killGraceMs), kind: "input", inputHint: "SIGTERM→SIGKILL grace" },
852
+ { key: "cfg:user:handoffGraceMs", label: "Handoff grace", value: formatDuration(c.handoffGraceMs), rawValue: String(c.handoffGraceMs), kind: "input", inputHint: "wait for final handoff after a kill" },
853
+ { key: "cfg:user:handoffEnforceTimeoutMs", label: "Handoff enforce", value: formatDuration(c.handoffEnforceTimeoutMs), rawValue: String(c.handoffEnforceTimeoutMs), kind: "input", inputHint: "re-prompt until a schema handoff lands" },
854
+ { key: "cfg:user:maxTaskBytes", label: "Max task bytes", value: String(c.maxTaskBytes), rawValue: String(c.maxTaskBytes), kind: "input" },
855
+ { key: "cfg:user:maxResultBytes", label: "Max result bytes", value: String(c.maxResultBytes), rawValue: String(c.maxResultBytes), kind: "input" },
856
+ { key: "cfg:user:updateThrottleMs", label: "Update throttle", value: formatDuration(c.updateThrottleMs), rawValue: String(c.updateThrottleMs), kind: "input", inputHint: "live update cadence" },
857
+ { key: "info:defaultRole", label: "Default role", value: c.defaultRole, kind: "info" },
858
+ { key: "info:retention", label: "Retention", value: `${c.maxRuns} runs · ${c.maxRunAgeDays}d`, kind: "info" },
859
+ ];
860
+ };
861
+ try {
862
+ await ctx.ui.custom(
863
+ (tui, theme, keybindings, done) =>
864
+ new SettingsPanel({
865
+ theme,
866
+ keybindings,
867
+ initialKey: "cfg:user:queueLimit",
868
+ snapshot: () => ({
869
+ title: "Advanced configuration",
870
+ summaryLines: ["User-wide · ~/.pi/agent/delegate/config.json", "Esc or any action returns to Delegation"],
871
+ sections: [{ title: "Knobs", rows: buildRows() }],
872
+ }),
873
+ apply: (key: string, raw: string): string | null => {
874
+ const m = /^cfg:user:([A-Za-z0-9]+)$/.exec(key);
875
+ if (!m) return `Unknown setting '${key}'.`;
876
+ return app.patchConfig(m[1]!, raw);
877
+ },
878
+ activate: (): PanelActionResult => ({ kind: "close", action: "advanced-done" }),
879
+ requestRender: () => tui.requestRender(),
880
+ done,
881
+ }),
882
+ { onCancel: () => ({}) } as unknown as Record<string, never>,
883
+ );
884
+ } catch {
885
+ /* esc → back to home */
886
+ }
887
+ };
888
+
889
+ // ── 5d. Home dashboard snapshot (centralized live window) ───────────────
890
+
827
891
  const dashboardSnapshot = (projectRoot?: string): PanelSnapshot => {
828
892
  const s = app.getStatus(pi.getActiveTools(), projectRoot);
829
893
  const active = s.activeRun;
830
894
  const last = s.lastRun;
831
895
  const t = s.timeouts;
896
+ const live = app.getActiveRunStream();
897
+ const queued = app.queuedRunCount();
898
+
899
+ const summaryLines: string[] = [];
900
+ summaryLines.push(`Delegate v${delegateVersion()} · mode ${s.modeEnabled ? "strict (delegate-only)" : "normal"}`);
901
+ if (active && live) {
902
+ const phaseState = live.update.phase.startsWith("tool:") ? "running" : live.update.phase;
903
+ const g = stateGlyph(phaseState);
904
+ summaryLines.push(`Active ${shortModel(live.update.model) || live.update.role} ${g.glyph} ${Math.round(live.update.elapsedMs / 1000)}s / ${formatDuration(live.hardMs)}`);
905
+ } else if (active) {
906
+ summaryLines.push(`Active ${active.role} · ${active.runId.slice(-12)} · starting`);
907
+ } else {
908
+ summaryLines.push(`Idle no active run`);
909
+ }
910
+ if (queued > 0) summaryLines.push(`Queue ${queued} waiting (limit ${app.queueLimit()})`);
911
+ if (last) {
912
+ const g = stateGlyph(last.state);
913
+ summaryLines.push(`Last ${last.role} ${g.glyph} ${g.word}${last.durationMs != null ? ` in ${formatDuration(last.durationMs)}` : ""}`);
914
+ }
915
+
916
+ const sections: PanelSection[] = [];
917
+
918
+ if (live) {
919
+ const inflight = (live.update.openTools ?? []).slice(0, 3).join(", ");
920
+ const frac = live.hardMs ? Math.min(1, live.update.elapsedMs / live.hardMs) : 0;
921
+ const tail = renderFeedEvents([...live.events], { startMs: Date.now() - live.update.elapsedMs, maxChars: 96 }).slice(-3);
922
+ const rows: PanelRow[] = [
923
+ { key: "live-phase", label: "Phase", value: `${live.update.phase}${live.update.model ? ` · ${shortModel(live.update.model)}` : ""}`, kind: "info", valueStyle: "accent" },
924
+ { key: "live-progress", label: "Progress", value: progressBar(frac, 24), kind: "info" },
925
+ { key: "live-tokens", label: "Tokens", value: `↑${formatTokens(live.update.usage?.input)} ↓${formatTokens(live.update.usage?.output)} · ${formatCost(live.update.usage?.cost)}`, kind: "info", valueStyle: "muted" },
926
+ { key: "live-inflight", label: "In flight", value: inflight || "—", kind: "info" },
927
+ ];
928
+ tail.forEach((line, i) => rows.push({ key: `live-tail-${i}`, label: "", value: line, kind: "info", valueStyle: "muted" }));
929
+ sections.push({ title: "Live", rows });
930
+ }
931
+
932
+ sections.push({
933
+ title: "Actions",
934
+ rows: [
935
+ { key: "run-general", label: "Run general task…", value: "", kind: "action" },
936
+ { key: "run-research", label: "Run research task…", value: "", kind: "action" },
937
+ { key: "peek", label: "Peek live / final detail", value: "", kind: "action", disabled: !active && !last },
938
+ { key: "cancel", label: "Cancel active run", value: "", kind: "action", disabled: !active },
939
+ { key: "resume", label: "Resume last run…", value: "", kind: "action", disabled: !last },
940
+ { key: "strict-toggle", label: s.modeEnabled ? "Disable strict mode" : "Enable strict mode", value: "", kind: "action" },
941
+ { key: "configure-advanced", label: "Configure advanced…", value: "›", kind: "action" },
942
+ { key: "doctor", label: "Doctor", value: "", kind: "action" },
943
+ { key: "paths", label: "Paths", value: "", kind: "action" },
944
+ ],
945
+ });
946
+
947
+ sections.push({
948
+ title: "Timeouts (base)",
949
+ rows: [
950
+ { key: "cfg:user:hardTimeoutMs", label: "Hard · user-wide", value: formatDuration(t.userHardMs), rawValue: String(t.userHardMs), kind: "input", inputHint: "e.g. 30m / 2h / 1d — user config" },
951
+ { key: "cfg:user:inactivityTimeoutMs", label: "Idle · user-wide", value: formatDuration(t.userInactivityMs), rawValue: String(t.userInactivityMs), kind: "input", inputHint: "no-output watchdog; capped at ½ hard" },
952
+ { key: "cfg:project:hardTimeoutMs", label: "Hard · project", value: t.projectHardMs !== undefined ? formatDuration(t.projectHardMs) : "not set", rawValue: t.projectHardMs !== undefined ? String(t.projectHardMs) : "", kind: "input", inputHint: `merges into ${t.projectPath ?? ".pi/delegate/config.json"}` },
953
+ ...(t.projectCorrupt
954
+ ? [{ key: "project-corrupt", label: "Project config", value: "corrupt — user values used", kind: "info" as const, valueStyle: "warning" as const }]
955
+ : []),
956
+ ],
957
+ });
958
+
832
959
  return {
833
960
  title: "Delegation",
834
- summaryLines: [
835
- `Parent mode ${s.modeEnabled ? "strict" : "normal"}`,
836
- `Parent tools ${s.modeEnabled ? "delegate only" : "normal active set"}`,
837
- `Active run ${active ? `${active.runId.slice(0, 24)} (${active.role})` : "none"}`,
838
- `Last run ${last ? `${last.role} · ${last.state}${last.durationMs != null ? ` · ${Math.round(last.durationMs / 1000)}s` : ""}` : "none"}`,
839
- `Default role ${s.defaultRole}`,
840
- `Base timeout ${formatDuration(t.hardMs)} hard · ${formatDuration(t.inactivityMs)} idle (${t.source === "project" ? "project" : "user-wide"})`,
961
+ summaryLines,
962
+ sections,
963
+ shortcuts: [
964
+ { key: "r", label: "run", action: "run-general" },
965
+ { key: "p", label: "peek", action: "peek" },
966
+ { key: "x", label: "cancel", action: "cancel" },
967
+ { key: "c", label: "configure", action: "configure-advanced" },
968
+ { key: "d", label: "doctor", action: "doctor" },
969
+ { key: "s", label: "status", action: "status" },
841
970
  ],
842
- sections: [
843
- {
844
- title: "Actions",
845
- rows: [
846
- { key: "run-general", label: "Run general", value: "", kind: "action" },
847
- { key: "run-research", label: "Run research", value: "", kind: "action" },
848
- { key: "strict-toggle", label: s.modeEnabled ? "Disable strict mode" : "Enable strict mode", value: "", kind: "action" },
849
- { key: "inspect-last", label: "Inspect last run", value: "", kind: "action", disabled: !last && !active },
850
- { key: "paths", label: "Paths / diagnostics", value: "", kind: "action" },
851
- { key: "doctor", label: "Doctor", value: "", kind: "action" },
852
- ],
853
- },
854
- {
855
- title: "Timeouts (base)",
856
- rows: [
857
- {
858
- key: "timeout-user",
859
- label: "Hard · user-wide",
860
- value: formatDuration(t.userHardMs),
861
- rawValue: formatDuration(t.userHardMs),
862
- kind: "input",
863
- inputHint: "e.g. 30m / 2h / 1d — saves ~/.pi/agent/delegate/config.json",
864
- },
865
- {
866
- key: "timeout-project",
867
- label: "Hard · project",
868
- value: t.projectHardMs !== undefined ? formatDuration(t.projectHardMs) : "not set",
869
- rawValue: t.projectHardMs !== undefined ? formatDuration(t.projectHardMs) : "",
870
- kind: "input",
871
- inputHint: `merges into ${t.projectPath ?? ".pi/delegate/config.json"} (this key only)`,
872
- },
873
- {
874
- key: "idle-user",
875
- label: "Idle · user-wide",
876
- value: formatDuration(t.userInactivityMs),
877
- rawValue: formatDuration(t.userInactivityMs),
878
- kind: "input",
879
- inputHint: "no-output watchdog; capped at ½ of the hard timeout",
880
- },
881
- ...(t.projectCorrupt
882
- ? [{ key: "project-corrupt", label: "Project config", value: "corrupt — user values used", kind: "info" as const, valueStyle: "warning" as const }]
883
- : []),
884
- ],
885
- },
886
- ],
887
- detailLines: active ? [`elapsed updates refresh every 1s while a run is active`] : undefined,
971
+ detailLines: active
972
+ ? ["live refresh 1s · enter selects · peek / cancel in Actions"]
973
+ : ["enter selects · edit a timeout, or run a task"],
888
974
  };
889
975
  };
890
976
 
891
977
  const openDashboard = async (ctx: ExtensionCommandContext): Promise<void> => {
892
- let initialKey = app.isStrict() ? "strict-toggle" : "run-general";
978
+ const projectRoot = ctx.cwd ?? process.cwd();
979
+ let initialKey = app.isStrict() ? "run-general" : "run-general";
893
980
  for (;;) {
894
981
  let refreshTimer: ReturnType<typeof setInterval> | undefined;
895
982
  let result: { action?: string } | undefined;
@@ -900,18 +987,14 @@ export default function delegateExtension(pi: ExtensionAPI) {
900
987
  theme,
901
988
  keybindings,
902
989
  initialKey,
903
- snapshot: () => dashboardSnapshot(ctx.cwd ?? process.cwd()),
990
+ snapshot: () => dashboardSnapshot(projectRoot),
904
991
  apply: (key: string, raw: string): string | null => {
905
- switch (key) {
906
- case "timeout-user":
907
- return app.patchConfig("hardTimeoutMs", raw);
908
- case "idle-user":
909
- return app.patchConfig("inactivityTimeoutMs", raw);
910
- case "timeout-project":
911
- return app.patchProjectConfig(ctx.cwd ?? process.cwd(), "hardTimeoutMs", raw);
912
- default:
913
- return `Unknown setting '${key}'.`;
914
- }
992
+ const m = /^cfg:(user|project):([A-Za-z0-9]+)$/.exec(key);
993
+ if (!m) return `Unknown setting '${key}'.`;
994
+ const [, target, field] = m;
995
+ return target === "project"
996
+ ? app.patchProjectConfig(projectRoot, field, raw)
997
+ : app.patchConfig(field, raw);
915
998
  },
916
999
  activate: (key): PanelActionResult => ({ kind: "close", action: key }),
917
1000
  requestRender: () => tui.requestRender(),
@@ -942,18 +1025,44 @@ export default function delegateExtension(pi: ExtensionAPI) {
942
1025
  await runCommandForeground(task, role, ctx);
943
1026
  continue;
944
1027
  }
945
- if (action === "strict-toggle") {
946
- if (app.isStrict()) {
947
- const res = await app.disableStrict(modeCtx(ctx));
948
- say(ctx, `[delegate] ${res.message}`, res.ok ? "info" : "warning");
949
- } else {
950
- const res = await app.enableStrict(modeCtx(ctx));
1028
+ if (action === "peek") {
1029
+ await openPeek(ctx);
1030
+ continue;
1031
+ }
1032
+ if (action === "cancel") {
1033
+ const ok = await ctx.ui.confirm("Cancel active run?", "SIGTERM then SIGKILL; a partial handoff is returned if the child produced one.");
1034
+ if (ok) {
1035
+ const res = await app.cancel();
951
1036
  say(ctx, `[delegate] ${res.message}`, res.ok ? "info" : "warning");
952
1037
  }
953
1038
  continue;
954
1039
  }
955
- if (action === "inspect-last") {
956
- say(ctx, inspectText());
1040
+ if (action === "resume") {
1041
+ const target = app.getStatus(pi.getActiveTools(), projectRoot).lastRun;
1042
+ if (!target) {
1043
+ say(ctx, "[delegate] nothing to resume.", "warning");
1044
+ continue;
1045
+ }
1046
+ const task = await ctx.ui.editor(`Resume ${target.runId.slice(-12)} (${target.role})`, "");
1047
+ if (!task || !task.trim()) continue;
1048
+ await runCommandForeground(task, target.role === "research" ? "research" : "general", ctx, undefined, { resumeFrom: target.runId });
1049
+ continue;
1050
+ }
1051
+ if (action === "strict-toggle") {
1052
+ const res = app.isStrict() ? await app.disableStrict(modeCtx(ctx)) : await app.enableStrict(modeCtx(ctx));
1053
+ say(ctx, `[delegate] ${res.message}`, res.ok ? "info" : "warning");
1054
+ continue;
1055
+ }
1056
+ if (action === "configure-advanced") {
1057
+ await openAdvanced(ctx, projectRoot);
1058
+ continue;
1059
+ }
1060
+ if (action === "doctor") {
1061
+ say(ctx, doctorText());
1062
+ continue;
1063
+ }
1064
+ if (action === "status") {
1065
+ say(ctx, statusText(ctx));
957
1066
  continue;
958
1067
  }
959
1068
  if (action === "paths") {
@@ -961,8 +1070,8 @@ export default function delegateExtension(pi: ExtensionAPI) {
961
1070
  say(ctx, [`[delegate paths]`, `config: ${p.configPath}`, `runs: ${p.runsDir}`].join("\n"));
962
1071
  continue;
963
1072
  }
964
- if (action === "doctor") {
965
- say(ctx, doctorText());
1073
+ if (action === "inspect-last") {
1074
+ say(ctx, inspectText());
966
1075
  continue;
967
1076
  }
968
1077
  return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maheidem/pi-delegate",
3
- "version": "0.2.3",
3
+ "version": "0.3.0",
4
4
  "type": "module",
5
5
  "description": "Foreground isolated delegation and strict coordinator mode for the Pi coding agent.",
6
6
  "license": "MIT",
package/ui/format.ts ADDED
@@ -0,0 +1,79 @@
1
+ /**
2
+ * delegate — shared formatting (reuse mandate, FIELDS.md §2).
3
+ *
4
+ * ONE module all views import so tokens/durations/sizes/model render
5
+ * identically across home, live strip, inline tool card, and peek. Wraps the
6
+ * canonical `formatDuration` (config.ts) rather than re-rolling it. Replaces
7
+ * the duplicate `fmtDuration`/`fmtTokens` that used to live in running-view.
8
+ */
9
+
10
+ import { formatDuration } from "../config.ts";
11
+
12
+ /** Canonical duration (ms → "41s"/"30m 22s"/"2h"). */
13
+ export { formatDuration };
14
+
15
+ /** Token count: 0 if falsy; raw <1000; else `X.Yk`; else `X.YM`. */
16
+ export function formatTokens(n: number | undefined): string {
17
+ if (!n || n < 0) return "0";
18
+ if (n < 1000) return String(n);
19
+ if (n < 1_000_000) return `${Math.round(n / 100) / 10}k`;
20
+ return `${Math.round(n / 100_000) / 10}M`;
21
+ }
22
+
23
+ /** Cost as `$X.YZ` (2 dp) or `$0.00`. Never emoji. */
24
+ export function formatCost(cost: number | undefined): string {
25
+ return `$${(cost ?? 0).toFixed(2)}`;
26
+ }
27
+
28
+ /** Bytes → binary size, 0–1 decimal ("51200"→"50 KB"). */
29
+ export function formatSize(bytes: number | undefined): string {
30
+ const b = bytes ?? 0;
31
+ if (b < 1024) return `${b} B`;
32
+ const kb = b / 1024;
33
+ if (kb < 1024) return `${kb < 10 ? Math.round(kb * 10) / 10 : Math.round(kb)} KB`;
34
+ const mb = kb / 1024;
35
+ if (mb < 1024) return `${mb < 10 ? Math.round(mb * 10) / 10 : Math.round(mb)} MB`;
36
+ const gb = mb / 1024;
37
+ return `${gb < 10 ? Math.round(gb * 10) / 10 : Math.round(gb)} GB`;
38
+ }
39
+
40
+ /** "zai/glm-5.3" → "glm-5.3" for compact rows; full id for peek headers. */
41
+ export function shortModel(model: string | undefined): string {
42
+ if (!model) return "";
43
+ const slash = model.lastIndexOf("/");
44
+ return slash >= 0 ? model.slice(slash + 1) : model;
45
+ }
46
+
47
+ /**
48
+ * State glyph + word (never color-alone, FIELDS §3.6). Returns the glyph and
49
+ * the word separately so the caller colors them together.
50
+ */
51
+ export function stateGlyph(state: string): { glyph: string; word: string; color: "success" | "warning" | "error" | "muted" } {
52
+ switch (state) {
53
+ case "created":
54
+ case "starting":
55
+ return { glyph: "◐", word: "starting", color: "muted" };
56
+ case "running":
57
+ return { glyph: "●", word: "running", color: "success" };
58
+ case "succeeded":
59
+ return { glyph: "✓", word: "done", color: "success" };
60
+ case "cancelled":
61
+ return { glyph: "⊘", word: "cancelled", color: "muted" };
62
+ case "timed_out_idle":
63
+ return { glyph: "⏱", word: "timeout · idle", color: "warning" };
64
+ case "timed_out_hard":
65
+ return { glyph: "⏱", word: "timeout · hard", color: "warning" };
66
+ case "queued":
67
+ return { glyph: "○", word: "queued", color: "muted" };
68
+ default:
69
+ return { glyph: "✗", word: state || "unknown", color: "error" };
70
+ }
71
+ }
72
+
73
+ /** Progress bar: `filled(█) + empty(░)` + "NN%" text (never shape-alone). */
74
+ export function progressBar(frac: number, width: number): string {
75
+ const f = Math.max(0, Math.min(1, frac));
76
+ const w = Math.max(4, Math.floor(width));
77
+ const filled = Math.round(f * w);
78
+ return `${"█".repeat(filled)}${"░".repeat(Math.max(0, w - filled))} ${Math.round(f * 100)}%`;
79
+ }
@@ -16,6 +16,7 @@
16
16
 
17
17
  import { truncateToWidth, visibleWidth, matchesKey, type Component } from "@earendil-works/pi-tui";
18
18
  import type { Theme, KeybindingsManager, ThemeColor } from "@earendil-works/pi-coding-agent";
19
+ import { formatDuration, formatTokens, shortModel } from "./format.ts";
19
20
 
20
21
  export interface RunningViewState {
21
22
  runId: string;
@@ -47,19 +48,6 @@ const PANEL_ROWS = 9;
47
48
  /** Feed rows inside the fixed frame; the rest are the fixed scaffold. */
48
49
  const FEED_ROWS = PANEL_ROWS - 5;
49
50
 
50
- function fmtDuration(ms: number): string {
51
- const s = Math.max(0, Math.round(ms / 1000));
52
- if (s < 60) return `${s}s`;
53
- return `${Math.floor(s / 60)}m${String(s % 60).padStart(2, "0")}s`;
54
- }
55
-
56
- function fmtTokens(n?: number): string {
57
- if (!n) return "0";
58
- if (n < 1000) return String(n);
59
- if (n < 1_000_000) return `${Math.round(n / 100) / 10}k`;
60
- return `${Math.round(n / 100_000) / 10}M`;
61
- }
62
-
63
51
  export class RunningView implements Component {
64
52
  private readonly host: RunningViewHost;
65
53
  private cancelArmed = false;
@@ -110,10 +98,10 @@ export class RunningView implements Component {
110
98
  // Fixed scaffold rows — always exactly PANEL_ROWS - 2 inner rows.
111
99
  const head = [
112
100
  s.role,
113
- s.model,
114
- fmtDuration(s.elapsedMs),
101
+ s.model ? shortModel(s.model) : undefined,
102
+ formatDuration(s.elapsedMs),
115
103
  ...(s.turns !== undefined ? [`turn ${s.turns}`] : []),
116
- ...(s.tokens ? [`↑${fmtTokens(s.tokens.input)} ↓${fmtTokens(s.tokens.output)}`] : []),
104
+ ...(s.tokens ? [`↑${formatTokens(s.tokens.input)} ↓${formatTokens(s.tokens.output)}`] : []),
117
105
  ]
118
106
  .filter(Boolean)
119
107
  .join(" · ");
@@ -123,7 +111,7 @@ export class RunningView implements Component {
123
111
  const frac = Math.min(1, s.elapsedMs / s.hardMs);
124
112
  const barWidth = Math.max(4, Math.min(inner - 14, 24));
125
113
  const filled = Math.round(frac * barWidth);
126
- progress = `${"█".repeat(filled)}${"░".repeat(Math.max(0, barWidth - filled))} ${Math.round(frac * 100)}% of ${fmtDuration(s.hardMs)} hard`;
114
+ progress = `${"█".repeat(filled)}${"░".repeat(Math.max(0, barWidth - filled))} ${Math.round(frac * 100)}% of ${formatDuration(s.hardMs)} hard`;
127
115
  }
128
116
 
129
117
  const openTools = s.openTools ?? [];