@loka1/pi-orchestra 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -74,6 +74,7 @@ export function loadState(root: string): OrchestraState {
74
74
  parsed.dispatches ??= {};
75
75
  parsed.gates ??= {};
76
76
  parsed.seq ??= 0;
77
+ parsed.ui ??= {};
77
78
  return parsed;
78
79
  } catch {
79
80
  return emptyState();
@@ -96,14 +97,85 @@ export function nowIso(): string {
96
97
  return new Date().toISOString();
97
98
  }
98
99
 
99
- export function activeRun(state: OrchestraState): Run | undefined {
100
- if (state.activeRunId && state.runs[state.activeRunId]) return state.runs[state.activeRunId];
100
+ export interface ActiveRunOptions {
101
+ /**
102
+ * Hide a run whose work is finished once nothing in it has moved for this long
103
+ * (0 = never; every finished run stays current). See `staleRunHours`.
104
+ */
105
+ staleAfterMs?: number;
106
+ /** Clock override for tests. */
107
+ now?: number;
108
+ }
109
+
110
+ /** The newest timestamp anything in `run` *did* (creation alone does not count). */
111
+ export function runLastActivity(state: OrchestraState, run: Run): number {
112
+ const stamps: Array<string | undefined> = [run.updatedAt];
113
+ for (const dispatch of listDispatches(state, run.id)) {
114
+ // A finished dispatch last did something when it ended; only a live one moves.
115
+ const ended = dispatch.endedAt ?? dispatch.settledAt;
116
+ if (ended) stamps.push(ended);
117
+ else stamps.push(dispatch.startedAt, dispatch.lastEventAt);
118
+ }
119
+ for (const task of listTasks(state, run.id)) stamps.push(task.updatedAt);
120
+ let newest = 0;
121
+ for (const stamp of stamps) {
122
+ if (!stamp) continue;
123
+ const value = Date.parse(stamp);
124
+ if (Number.isFinite(value) && value > newest) newest = value;
125
+ }
126
+ return newest;
127
+ }
128
+
129
+ /**
130
+ * A run is stale when it can no longer make progress on its own — every worker is
131
+ * terminal (note: `orphaned` is not, its process may still be alive) and no task
132
+ * is waiting to run — and its last activity is older than the window.
133
+ *
134
+ * Staleness only affects *visibility*: the run and its history stay in the state
135
+ * and in `/orchestra runs`; it is simply not treated as this session's work.
136
+ */
137
+ export function isRunStale(
138
+ state: OrchestraState,
139
+ run: Run,
140
+ staleAfterMs: number,
141
+ now = Date.now(),
142
+ ): boolean {
143
+ if (!(staleAfterMs > 0)) return false;
144
+ const live = listDispatches(state, run.id).some((dispatch) => !isTerminalStatus(dispatch.status));
145
+ if (live) return false;
146
+ const waiting = listTasks(state, run.id).some(
147
+ (task) => task.status === "pending" || task.status === "ready" || task.status === "running" || task.status === "blocked",
148
+ );
149
+ if (waiting) return false;
150
+ const last = runLastActivity(state, run);
151
+ return last > 0 && now - last >= staleAfterMs;
152
+ }
153
+
154
+ /**
155
+ * The run a session should treat as current.
156
+ *
157
+ * Explicit wins: `state.activeRunId` is honoured even when the run is stale if it
158
+ * was pinned by `/orchestra use`, so an old run can be reopened on purpose. Otherwise
159
+ * stale runs are skipped and a fresh session starts with no run at all.
160
+ */
161
+ export function activeRun(state: OrchestraState, options: ActiveRunOptions = {}): Run | undefined {
162
+ const staleAfterMs = options.staleAfterMs ?? 0;
163
+ const now = options.now ?? Date.now();
164
+ const pinned = state.ui?.pinnedRunId;
165
+ const usable = (run: Run): boolean => run.id === pinned || !isRunStale(state, run, staleAfterMs, now);
166
+
167
+ const explicit = state.activeRunId ? state.runs[state.activeRunId] : undefined;
168
+ if (explicit && usable(explicit)) return explicit;
169
+
101
170
  const runs = Object.values(state.runs).sort((a, b) => a.createdAt.localeCompare(b.createdAt));
102
- return runs.length > 0 ? runs[runs.length - 1] : undefined;
171
+ for (let index = runs.length - 1; index >= 0; index -= 1) {
172
+ if (usable(runs[index])) return runs[index];
173
+ }
174
+ return undefined;
103
175
  }
104
176
 
105
- export function runOf(state: OrchestraState): Run {
106
- const run = activeRun(state);
177
+ export function runOf(state: OrchestraState, options: ActiveRunOptions = {}): Run {
178
+ const run = activeRun(state, options);
107
179
  if (!run) {
108
180
  const created = createRun(state, { name: "main" });
109
181
  state.activeRunId = created.id;
@@ -130,6 +202,8 @@ export function createRun(
130
202
  };
131
203
  state.runs[run.id] = run;
132
204
  state.activeRunId = run.id;
205
+ // A new run is the current one; drop the `/orchestra use` pin of an older run.
206
+ state.ui = { ...state.ui, pinnedRunId: undefined };
133
207
  return run;
134
208
  }
135
209
 
@@ -512,6 +586,35 @@ export function pruneStore(root: string, state: OrchestraState, options: PruneOp
512
586
  // archiving: keep state.json small without losing history
513
587
  // ---------------------------------------------------------------------------
514
588
 
589
+ /**
590
+ * The blunt instrument behind `action=reset` and `/orchestra reset`: copy the whole
591
+ * store aside, then empty the live state in place so the coordinator keeps its reference.
592
+ *
593
+ * Logs, prompts, mail and the archive stay on disk (use `prune` to reclaim them).
594
+ * The project's *UI preference* survives — hiding the widget is a choice about the
595
+ * terminal, not about the data — while the `/orchestra use` pin does not.
596
+ */
597
+ export function archiveAndClearState(root: string, state: OrchestraState): { archive?: string } {
598
+ const paths = storePaths(root);
599
+ let archive: string | undefined;
600
+ if (existsSync(paths.stateFile)) {
601
+ archive = join(root, `state.${Date.now()}.bak.json`);
602
+ try {
603
+ writeFileSync(archive, readFileSync(paths.stateFile));
604
+ } catch {
605
+ // Archiving is best effort: a reset must still clear the state.
606
+ archive = undefined;
607
+ }
608
+ }
609
+ for (const bucket of [state.runs, state.tasks, state.dispatches, state.gates] as Array<Record<string, unknown>>) {
610
+ for (const key of Object.keys(bucket)) delete bucket[key];
611
+ }
612
+ state.seq = 0;
613
+ state.activeRunId = undefined;
614
+ state.ui = { widget: state.ui?.widget };
615
+ return { archive };
616
+ }
617
+
515
618
  export interface ArchiveResult {
516
619
  /** Runs moved out of the live state. */
517
620
  archived: string[];
@@ -133,6 +133,20 @@ export interface Gate {
133
133
  answeredAt?: string;
134
134
  }
135
135
 
136
+ /** How much of the always-on UI this project wants. */
137
+ export type WidgetMode = "auto" | "always" | "off";
138
+
139
+ /**
140
+ * Per-project UI preferences, persisted in `state.json` so they survive sessions:
141
+ * what `/orchestra hide` / `/orchestra show` and `/orchestra use` set.
142
+ */
143
+ export interface UiState {
144
+ /** Overrides the `widget` config key for this project. */
145
+ widget?: WidgetMode;
146
+ /** Run reopened with `/orchestra use`; it stays current even when a stale run would be hidden. */
147
+ pinnedRunId?: string;
148
+ }
149
+
136
150
  export interface OrchestraState {
137
151
  version: 1;
138
152
  activeRunId?: string;
@@ -141,10 +155,11 @@ export interface OrchestraState {
141
155
  tasks: Record<string, Task>;
142
156
  dispatches: Record<string, Dispatch>;
143
157
  gates: Record<string, Gate>;
158
+ ui?: UiState;
144
159
  }
145
160
 
146
161
  export function emptyState(): OrchestraState {
147
- return { version: 1, seq: 0, runs: {}, tasks: {}, dispatches: {}, gates: {} };
162
+ return { version: 1, seq: 0, runs: {}, tasks: {}, dispatches: {}, gates: {}, ui: {} };
148
163
  }
149
164
 
150
165
  export function emptyUsage(): DispatchUsage {
@@ -22,13 +22,13 @@ import { StringEnum } from "@earendil-works/pi-ai";
22
22
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
23
23
  import { Text, truncateToWidth } from "@earendil-works/pi-tui";
24
24
  import { Type } from "typebox";
25
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
25
+ import { mkdirSync, writeFileSync } from "node:fs";
26
26
  import { join } from "node:path";
27
27
  import { fileURLToPath } from "node:url";
28
28
 
29
29
  import { type AgentScope, discoverAgents, findAgent } from "./lib/agents.ts";
30
30
  import { type OrchestraConfig, DEFAULT_CONFIG, loadConfig, resolveStateDir } from "./lib/config.ts";
31
- import { type Dispatch, type Gate, type OrchestraState, type Run, type Task, activeRun, archiveRuns, pidAlive, pruneStore, createDispatch, createRun, createTask, ensureStore, isTerminalStatus, killPid, listDispatches, listTasks, loadState, newId,
31
+ import { type Dispatch, type Gate, type OrchestraState, type Run, type Task, activeRun, archiveAndClearState, archiveRuns, pidAlive, pruneStore, createDispatch, createRun, createTask, ensureStore, isTerminalStatus, killPid, listDispatches, listTasks, loadState, newId,
32
32
  reconcileOrphans, setTaskDeps, nowIso, refreshTaskReadiness, runOf, saveState, storePaths, totalUsage } from "./lib/state.ts";
33
33
  import { pendingQuestions, postQuestion, waitForAnswer, writeAnswer } from "./lib/mail.ts";
34
34
  import { readRecords, readTranscript, searchLogs, transcriptText } from "./lib/log.ts";
@@ -44,6 +44,7 @@ import {
44
44
  fit,
45
45
  formatCost,
46
46
  formatTokens,
47
+ hasLiveWork,
47
48
  liveDispatches,
48
49
  questionReport,
49
50
  runSummary,
@@ -366,18 +367,70 @@ function registerCoordinator(pi: ExtensionAPI): void {
366
367
  runtime.uiDirty = true;
367
368
  }
368
369
 
370
+ /** The staleness window for `activeRun`, from `staleRunHours` (0 = keep every finished run current). */
371
+ function staleAfterMs(): number {
372
+ return Math.max(0, runtime.config.staleRunHours) * 60 * 60 * 1000;
373
+ }
374
+
375
+ /**
376
+ * The run this session works on: the active (or `/orchestra use` pinned) run, otherwise
377
+ * the newest run that is not stale. `undefined` in a fresh session whose previous runs
378
+ * finished hours ago — that is what keeps yesterday's run off today's screen.
379
+ */
380
+ function currentRun(): Run | undefined {
381
+ return activeRun(runtime.state, { staleAfterMs: staleAfterMs() });
382
+ }
383
+
384
+ /** `ui.widget` (set by `/orchestra hide|show`) wins over the `widget` config key. */
385
+ function widgetMode(): "auto" | "always" | "off" {
386
+ return runtime.state.ui?.widget ?? runtime.config.widget;
387
+ }
388
+
389
+ /** Drop the widget body: used when nothing is live, when switched off, and on shutdown. */
390
+ function unmountWidget(ctx: ExtensionContext): void {
391
+ runtime.widgetMounted = false;
392
+ runtime.widgetTui = undefined;
393
+ runtime.lastWidget = undefined;
394
+ try {
395
+ ctx.ui.setWidget("orchestra", undefined);
396
+ } catch {
397
+ // Best effort: print/rpc modes have no widget surface.
398
+ }
399
+ }
400
+
369
401
  function refreshUI(ctx: ExtensionContext | undefined): void {
370
402
  if (!ctx?.hasUI) return;
371
403
  try {
372
- ctx.ui.setStatus("orchestra", statusLine(runtime.state, activeRun(runtime.state)));
373
- if (ctx.mode === "tui") {
404
+ const mode = widgetMode();
405
+ const run = currentRun();
406
+ if (mode === "off") {
407
+ ctx.ui.setStatus("orchestra", undefined);
408
+ unmountWidget(ctx);
409
+ runtime.browseRepaint?.();
410
+ return;
411
+ }
412
+ // No current run (nothing here yet, or only older sessions' runs): leave both
413
+ // surfaces empty instead of summarising history that is not this session's work.
414
+ if (!run && !runtime.watchId) {
415
+ ctx.ui.setStatus("orchestra", undefined);
416
+ unmountWidget(ctx);
417
+ runtime.browseRepaint?.();
418
+ return;
419
+ }
420
+
421
+ ctx.ui.setStatus("orchestra", statusLine(runtime.state, run));
422
+ const lines = widgetText(run);
423
+ // `auto` mounts only while work is live; a watched transcript always shows.
424
+ const mounted = mode === "always" || Boolean(runtime.watchId) || hasLiveWork(runtime.state, run);
425
+ if (!mounted || lines.length === 0) {
426
+ unmountWidget(ctx);
427
+ } else if (ctx.mode === "tui") {
374
428
  installWidget(ctx);
375
429
  } else {
376
- const lines = widgetText();
377
430
  const key = lines.join("\n");
378
431
  if (key !== runtime.lastWidget) {
379
432
  runtime.lastWidget = key;
380
- ctx.ui.setWidget("orchestra", lines.length > 0 ? lines : undefined);
433
+ ctx.ui.setWidget("orchestra", lines);
381
434
  }
382
435
  }
383
436
  runtime.browseRepaint?.();
@@ -387,9 +440,10 @@ function registerCoordinator(pi: ExtensionAPI): void {
387
440
  }
388
441
 
389
442
  /** The widget body: prioritised, capped and width-fitted by the render callback below. */
390
- function widgetText(): string[] {
443
+ function widgetText(run: Run | undefined): string[] {
391
444
  if (runtime.watchId) return watchLines(runtime.watchId);
392
- return widgetRows(runtime.state, activeRun(runtime.state), {
445
+ if (!run) return [];
446
+ return widgetRows(runtime.state, run, {
393
447
  maxLines: runtime.config.widgetMaxLines,
394
448
  showSettled: runtime.config.widgetShowSettled,
395
449
  });
@@ -409,7 +463,7 @@ function registerCoordinator(pi: ExtensionAPI): void {
409
463
  runtime.widgetTui = tui;
410
464
  return {
411
465
  render(width: number) {
412
- return widgetText().map((line) => colorizeWidget(theme, truncateToWidth(line, width)));
466
+ return widgetText(currentRun()).map((line) => colorizeWidget(theme, truncateToWidth(line, width)));
413
467
  },
414
468
  invalidate() {},
415
469
  };
@@ -623,6 +677,12 @@ function registerCoordinator(pi: ExtensionAPI): void {
623
677
 
624
678
  /** Stop a worker from the browser or the command: kill it, free the task, persist. */
625
679
  async function stopDispatchNow(dispatch: Dispatch, note = "Stopped from the browser."): Promise<void> {
680
+ // Record the reason before the process dies: finalize() runs from the exit
681
+ // handler and would otherwise classify this as a normal settle and report it
682
+ // that way in the wake-up.
683
+ dispatch.stopReason ??= "user";
684
+ dispatch.stopNote ??= note;
685
+ dispatch.endedAt ??= nowIso();
626
686
  const worker = runtime.workers.get(dispatch.id);
627
687
  if (worker) {
628
688
  await worker.abort().catch(() => undefined);
@@ -631,8 +691,6 @@ function registerCoordinator(pi: ExtensionAPI): void {
631
691
  }
632
692
  clearBudgetTimers(dispatch.id);
633
693
  runtime.stalled.delete(dispatch.id);
634
- dispatch.stopReason ??= "user";
635
- dispatch.stopNote ??= note;
636
694
  dispatch.status = "stopped";
637
695
  dispatch.endedAt = nowIso();
638
696
  const task = dispatch.taskId ? runtime.state.tasks[dispatch.taskId] : undefined;
@@ -806,14 +864,14 @@ function registerCoordinator(pi: ExtensionAPI): void {
806
864
  retries?: number;
807
865
  }): Promise<{ dispatch: Dispatch; worker: WorkerProcess }> {
808
866
  const cwd = runtime.cwd;
809
- const live = liveDispatches(runtime.state, activeRun(runtime.state)?.id);
867
+ const live = liveDispatches(runtime.state, currentRun()?.id);
810
868
  if (live.length >= runtime.config.maxConcurrency) {
811
869
  throw new Error(
812
870
  `Concurrency limit reached (${runtime.config.maxConcurrency} workers running). Wait for one to settle or raise maxConcurrency in .pi/orchestra.json.`,
813
871
  );
814
872
  }
815
873
 
816
- const run = runOf(runtime.state);
874
+ const run = runOf(runtime.state, { staleAfterMs: staleAfterMs() });
817
875
  if (checkRunBudget(run)) {
818
876
  throw new Error(
819
877
  run.budgetPaused
@@ -1294,7 +1352,7 @@ function registerCoordinator(pi: ExtensionAPI): void {
1294
1352
 
1295
1353
  switch (params.action) {
1296
1354
  case "status": {
1297
- const run = activeRun(runtime.state);
1355
+ const run = currentRun();
1298
1356
  if (!run) {
1299
1357
  return textResult(
1300
1358
  `orchestra: no run yet. Create one with action=run_create, then add tasks with action=task_create. Agents: ${agentNames(ctx.cwd)}.`,
@@ -1368,13 +1426,16 @@ function registerCoordinator(pi: ExtensionAPI): void {
1368
1426
  throw new Error(`Unknown run. Use action=run_list to see runs.`);
1369
1427
  }
1370
1428
  runtime.state.activeRunId = params.runId;
1429
+ // Pin it: an explicitly reopened run stays current even when it is old enough
1430
+ // for the staleness window (see `staleRunHours`).
1431
+ runtime.state.ui = { ...runtime.state.ui, pinnedRunId: params.runId };
1371
1432
  persist();
1372
1433
  return textResult(`Active run is now ${params.runId}.`);
1373
1434
  }
1374
1435
 
1375
1436
  case "task_create": {
1376
1437
  if (!params.title) throw new Error("task_create requires `title`.");
1377
- const run = params.runId ? runtime.state.runs[params.runId] : runOf(runtime.state);
1438
+ const run = params.runId ? runtime.state.runs[params.runId] : runOf(runtime.state, { staleAfterMs: staleAfterMs() });
1378
1439
  if (!run) throw new Error(`Unknown run ${params.runId}.`);
1379
1440
  const task = createTask(runtime.state, {
1380
1441
  runId: run.id,
@@ -1597,7 +1658,7 @@ function registerCoordinator(pi: ExtensionAPI): void {
1597
1658
  case "search": {
1598
1659
  const query = (params.filter ?? "").trim();
1599
1660
  if (!query) throw new Error("search requires `filter` (the text to look for in worker transcripts).");
1600
- const scoped = params.runId ? [params.runId] : activeRun(runtime.state) ? [activeRun(runtime.state)?.id as string] : [];
1661
+ const scoped = params.runId ? [params.runId] : currentRun() ? [currentRun()?.id as string] : [];
1601
1662
  const dispatchIds =
1602
1663
  params.runId || scoped.length
1603
1664
  ? Object.values(runtime.state.dispatches)
@@ -1636,7 +1697,7 @@ function registerCoordinator(pi: ExtensionAPI): void {
1636
1697
  case "metrics": {
1637
1698
  const run = params.runId
1638
1699
  ? runtime.state.runs[params.runId]
1639
- : (activeRun(runtime.state) ?? undefined);
1700
+ : (currentRun() ?? undefined);
1640
1701
  if (!run) throw new Error("No run to measure. Pass runId or create a run first.");
1641
1702
  const metrics = runMetrics(runtime.state, run.id);
1642
1703
  return textResult(metricsTable(metrics), {
@@ -1666,7 +1727,7 @@ function registerCoordinator(pi: ExtensionAPI): void {
1666
1727
  }
1667
1728
 
1668
1729
  case "report": {
1669
- const run = params.runId ? runtime.state.runs[params.runId] : (activeRun(runtime.state) ?? undefined);
1730
+ const run = params.runId ? runtime.state.runs[params.runId] : (currentRun() ?? undefined);
1670
1731
  if (!run) throw new Error("No run to report on. Pass runId or create a run first.");
1671
1732
  const metrics = runMetrics(runtime.state, run.id);
1672
1733
  const changes: Record<string, string> = {};
@@ -1687,7 +1748,7 @@ function registerCoordinator(pi: ExtensionAPI): void {
1687
1748
  }
1688
1749
 
1689
1750
  case "budget": {
1690
- const run = params.runId ? runtime.state.runs[params.runId] : (activeRun(runtime.state) ?? undefined);
1751
+ const run = params.runId ? runtime.state.runs[params.runId] : (currentRun() ?? undefined);
1691
1752
  if (!run) throw new Error("No run to budget. Pass runId or create a run first.");
1692
1753
  const usage = totalUsage(runtime.state, run.id);
1693
1754
  if (params.budgetUsd === undefined) {
@@ -1732,7 +1793,7 @@ function registerCoordinator(pi: ExtensionAPI): void {
1732
1793
  case "export": {
1733
1794
  const run = params.runId
1734
1795
  ? runtime.state.runs[params.runId]
1735
- : (activeRun(runtime.state) ?? undefined);
1796
+ : (currentRun() ?? undefined);
1736
1797
  if (!run) throw new Error("No run to export. Pass runId or create a run first.");
1737
1798
  const metrics = runMetrics(runtime.state, run.id);
1738
1799
  const format = (params.format ?? "jsonl").toLowerCase();
@@ -1776,18 +1837,15 @@ function registerCoordinator(pi: ExtensionAPI): void {
1776
1837
  );
1777
1838
  runtime.workers.clear();
1778
1839
  runtime.finalized.clear();
1779
- const archive = join(runtime.root, `state.${Date.now()}.bak.json`);
1780
- try {
1781
- if (existsSync(storePaths(runtime.root).stateFile)) {
1782
- writeFileSync(archive, readFileSync(storePaths(runtime.root).stateFile));
1783
- }
1784
- } catch {
1785
- // Archiving is best effort.
1786
- }
1787
- runtime.state = { version: 1, seq: 0, runs: {}, tasks: {}, dispatches: {}, gates: {} };
1840
+ const { archive } = archiveAndClearState(runtime.root, runtime.state);
1788
1841
  persist();
1789
1842
  runtime.watchId = undefined;
1790
- return textResult(`Reset orchestration state (archived to ${archive}).`);
1843
+ refreshUI(ctx);
1844
+ return textResult(
1845
+ archive
1846
+ ? `Reset orchestration state (archived to ${archive}).`
1847
+ : "Reset orchestration state (there was no state file to archive).",
1848
+ );
1791
1849
  }
1792
1850
 
1793
1851
  default:
@@ -1833,7 +1891,7 @@ function registerCoordinator(pi: ExtensionAPI): void {
1833
1891
  lastCtx = ctx;
1834
1892
  ready(ctx.cwd);
1835
1893
  if (params.dispatch.trim() === "*") {
1836
- const targets = liveDispatches(runtime.state, activeRun(runtime.state)?.id);
1894
+ const targets = liveDispatches(runtime.state, currentRun()?.id);
1837
1895
  if (targets.length === 0) return textResult("No live workers to broadcast to.");
1838
1896
  const lines: string[] = [];
1839
1897
  for (const target of targets) {
@@ -1879,8 +1937,11 @@ function registerCoordinator(pi: ExtensionAPI): void {
1879
1937
  ) {
1880
1938
  const worker = runtime.workers.get(dispatch.id);
1881
1939
  if (!worker || worker.exited) {
1940
+ const options = dispatch.sessionId
1941
+ ? `Resume it to keep its context: orchestra action=worker_resume dispatch=${dispatch.id}.`
1942
+ : `Set sessionMode: "session" to make settled workers resumable.`;
1882
1943
  throw new Error(
1883
- `Worker ${dispatch.id} has no live process (status ${dispatch.status}). Start a new worker with the previous result as context, or set keepOpen=true in .pi/orchestra.json so settled workers stay reachable.`,
1944
+ `Worker ${dispatch.id} has no live process (status ${dispatch.status}). ${options} Or start a new dispatch with the previous result as context, and keepOpen=true in .pi/orchestra.json so settled workers stay reachable.`,
1884
1945
  );
1885
1946
  }
1886
1947
  dispatch.status = worker.settled ? "running" : dispatch.status;
@@ -1922,7 +1983,7 @@ function registerCoordinator(pi: ExtensionAPI): void {
1922
1983
 
1923
1984
  function resolveWaitTargets(id?: string): string[] {
1924
1985
  if (id) return [requireDispatch(id).id];
1925
- return liveDispatches(runtime.state, activeRun(runtime.state)?.id).map((dispatch) => dispatch.id);
1986
+ return liveDispatches(runtime.state, currentRun()?.id).map((dispatch) => dispatch.id);
1926
1987
  }
1927
1988
 
1928
1989
  async function waitForSettled(ids: string[], timeoutMs: number, signal?: AbortSignal): Promise<string> {
@@ -2270,9 +2331,9 @@ function registerCoordinator(pi: ExtensionAPI): void {
2270
2331
  done,
2271
2332
  {
2272
2333
  items: (scope, filter, sort) =>
2273
- browseItems(runtime.state, activeRun(runtime.state), scope, filter, sort),
2334
+ browseItems(runtime.state, currentRun(), scope, filter, sort),
2274
2335
  title: () => {
2275
- const run = activeRun(runtime.state);
2336
+ const run = currentRun();
2276
2337
  return run ? `orchestra — ${run.name} (${shortId(run.id)})` : "orchestra — no run";
2277
2338
  },
2278
2339
  initial: session,
@@ -2378,7 +2439,9 @@ function registerCoordinator(pi: ExtensionAPI): void {
2378
2439
  session.selectedId = result.item.id;
2379
2440
  if (result.kind === "useRun") {
2380
2441
  runtime.state.activeRunId = result.item.runId;
2442
+ runtime.state.ui = { ...runtime.state.ui, pinnedRunId: result.item.runId };
2381
2443
  persist();
2444
+ refreshUI(ctx);
2382
2445
  notify(ctx, `Active run is now ${result.item.title}.`, "info");
2383
2446
  continue;
2384
2447
  }
@@ -2441,7 +2504,7 @@ function registerCoordinator(pi: ExtensionAPI): void {
2441
2504
  switch (sub) {
2442
2505
  case undefined:
2443
2506
  case "status": {
2444
- const run = activeRun(runtime.state);
2507
+ const run = currentRun();
2445
2508
  const body = run
2446
2509
  ? [
2447
2510
  runSummary(runtime.state, run),
@@ -2452,6 +2515,14 @@ function registerCoordinator(pi: ExtensionAPI): void {
2452
2515
  ].join("\n")
2453
2516
  : "No run yet. Ask the model to start one, or use /orchestra workers after a dispatch.";
2454
2517
  notify(ctx, body);
2518
+ const earlier = Object.values(runtime.state.runs).length;
2519
+ if (!run && earlier > 0) {
2520
+ notify(
2521
+ ctx,
2522
+ `${earlier} earlier run(s) are kept from previous sessions but are not current (/orchestra runs, then /orchestra use <id>).`,
2523
+ "info",
2524
+ );
2525
+ }
2455
2526
  return;
2456
2527
  }
2457
2528
  case "browse":
@@ -2462,7 +2533,7 @@ function registerCoordinator(pi: ExtensionAPI): void {
2462
2533
  return;
2463
2534
  case "open": {
2464
2535
  const needle = arg.trim();
2465
- const run = activeRun(runtime.state);
2536
+ const run = currentRun();
2466
2537
  const candidates = [
2467
2538
  ...browseItems(runtime.state, run, "tasks"),
2468
2539
  ...browseItems(runtime.state, run, "workers"),
@@ -2504,6 +2575,71 @@ function registerCoordinator(pi: ExtensionAPI): void {
2504
2575
  refreshUI(ctx);
2505
2576
  notify(ctx, "Stopped watching.", "info");
2506
2577
  return;
2578
+ case "hide":
2579
+ case "show": {
2580
+ const requested = arg.trim().toLowerCase();
2581
+ if (sub === "hide") {
2582
+ runtime.state.ui = { ...runtime.state.ui, widget: "off" };
2583
+ persist();
2584
+ refreshUI(ctx);
2585
+ notify(
2586
+ ctx,
2587
+ "Orchestra UI hidden for this project. `/orchestra show` brings the widget back; `/orchestra status` always works.",
2588
+ "info",
2589
+ );
2590
+ return;
2591
+ }
2592
+ if (requested && requested !== "auto" && requested !== "always" && requested !== "off") {
2593
+ notify(ctx, "Usage: /orchestra show [auto|always|off]", "error");
2594
+ return;
2595
+ }
2596
+ const mode = (requested || "auto") as "auto" | "always" | "off";
2597
+ runtime.state.ui = { ...runtime.state.ui, widget: mode };
2598
+ persist();
2599
+ refreshUI(ctx);
2600
+ notify(
2601
+ ctx,
2602
+ mode === "off"
2603
+ ? "Orchestra UI off for this project."
2604
+ : mode === "always"
2605
+ ? "Widget pinned on for this project, even when nothing is running."
2606
+ : "Widget back to auto: it appears while workers are live and clears when they settle.",
2607
+ "info",
2608
+ );
2609
+ return;
2610
+ }
2611
+ case "reset":
2612
+ case "clean": {
2613
+ const live = [...runtime.workers.keys()];
2614
+ if (ctx.mode === "tui" || ctx.mode === "rpc") {
2615
+ const counts = `${Object.keys(runtime.state.runs).length} run(s), ${Object.keys(runtime.state.tasks).length} task(s), ${live.length} live worker(s)`;
2616
+ const ok = await ctx.ui.confirm(
2617
+ "Reset orchestra state",
2618
+ `Archive this project's state (${counts}) and start clean? Logs stay on disk.`,
2619
+ );
2620
+ if (!ok) return;
2621
+ }
2622
+ await Promise.all(
2623
+ [...runtime.workers.values()].map(async (worker) => {
2624
+ await worker.abort().catch(() => undefined);
2625
+ await worker.stop().catch(() => undefined);
2626
+ }),
2627
+ );
2628
+ runtime.workers.clear();
2629
+ runtime.finalized.clear();
2630
+ runtime.watchId = undefined;
2631
+ const { archive } = archiveAndClearState(runtime.root, runtime.state);
2632
+ persist();
2633
+ refreshUI(ctx);
2634
+ notify(
2635
+ ctx,
2636
+ archive
2637
+ ? `Reset. Previous state archived to ${archive}.`
2638
+ : "Reset. There was no state file to archive.",
2639
+ "info",
2640
+ );
2641
+ return;
2642
+ }
2507
2643
  case "stop": {
2508
2644
  const dispatch = requireDispatch(arg.trim());
2509
2645
  const worker = runtime.workers.get(dispatch.id);
@@ -2598,6 +2734,7 @@ function registerCoordinator(pi: ExtensionAPI): void {
2598
2734
  return;
2599
2735
  }
2600
2736
  runtime.state.activeRunId = run.id;
2737
+ runtime.state.ui = { ...runtime.state.ui, pinnedRunId: run.id };
2601
2738
  persist();
2602
2739
  refreshUI(ctx);
2603
2740
  notify(ctx, `Active run is now ${run.id}${run.name ? ` — ${run.name}` : ""}.`);
@@ -2640,7 +2777,7 @@ function registerCoordinator(pi: ExtensionAPI): void {
2640
2777
  return;
2641
2778
  }
2642
2779
  case "export": {
2643
- const run = activeRun(runtime.state);
2780
+ const run = currentRun();
2644
2781
  if (!run) {
2645
2782
  notify(ctx, "No active run to export.", "warning");
2646
2783
  return;
@@ -2659,7 +2796,7 @@ function registerCoordinator(pi: ExtensionAPI): void {
2659
2796
  return;
2660
2797
  }
2661
2798
  case "metrics": {
2662
- const run = activeRun(runtime.state);
2799
+ const run = currentRun();
2663
2800
  if (!run) {
2664
2801
  notify(ctx, "No active run to measure.", "warning");
2665
2802
  return;
@@ -2673,7 +2810,7 @@ function registerCoordinator(pi: ExtensionAPI): void {
2673
2810
  notify(ctx, "Usage: /orchestra broadcast <message>", "error");
2674
2811
  return;
2675
2812
  }
2676
- const targets = liveDispatches(runtime.state, activeRun(runtime.state)?.id);
2813
+ const targets = liveDispatches(runtime.state, currentRun()?.id);
2677
2814
  if (targets.length === 0) {
2678
2815
  notify(ctx, "No live workers to broadcast to.", "warning");
2679
2816
  return;
@@ -2748,7 +2885,7 @@ function registerCoordinator(pi: ExtensionAPI): void {
2748
2885
  }
2749
2886
 
2750
2887
  case "report": {
2751
- const run = activeRun(runtime.state);
2888
+ const run = currentRun();
2752
2889
  if (!run) {
2753
2890
  notify(ctx, "No active run to report on.", "warning");
2754
2891
  return;
@@ -2770,7 +2907,7 @@ function registerCoordinator(pi: ExtensionAPI): void {
2770
2907
  return;
2771
2908
  }
2772
2909
  case "budget": {
2773
- const run = activeRun(runtime.state);
2910
+ const run = currentRun();
2774
2911
  if (!run) {
2775
2912
  notify(ctx, "No active run to budget.", "warning");
2776
2913
  return;
@@ -2886,7 +3023,7 @@ function registerCoordinator(pi: ExtensionAPI): void {
2886
3023
  });
2887
3024
 
2888
3025
  pi.on("before_agent_start", async (event) => {
2889
- const run = activeRun(runtime.state);
3026
+ const run = currentRun();
2890
3027
  if (!run) return;
2891
3028
  const live = liveDispatches(runtime.state, run.id);
2892
3029
  if (live.length === 0) return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@loka1/pi-orchestra",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "type": "module",
5
5
  "description": "Orchestrate pi worker agents from inside pi: runs, tasks, dispatches, wake-ups, questions and gates. No external runtime.",
6
6
  "keywords": [
@@ -61,6 +61,8 @@ Each spec must contain: the target (paths), the change, constraints, what the wo
61
61
  "notifyOnSettle": true,
62
62
  "widgetMaxLines": 8,
63
63
  "widgetShowSettled": false,
64
+ "widget": "auto",
65
+ "staleRunHours": 12,
64
66
  "providerExtensions": [],
65
67
  "sessionMode": "session",
66
68
  "budgetUsdPerWorker": 2,
@@ -71,13 +73,13 @@ Each spec must contain: the target (paths), the change, constraints, what the wo
71
73
  "budgetAction": "stop",
72
74
  "retries": 0,
73
75
  "retryBackoffMs": 2000,
74
- "agents": { "reviewer": { "provider": "commandcode", "model": "deepseek/deepseek-v4.1-flash", "thinking": "high", "tools": "read,grep,ls,bash" } }
76
+ "agents": { "reviewer": { "provider": "anthropic", "model": "claude-sonnet-4-5", "thinking": "high", "tools": "read,grep,ls,bash" } }
75
77
  }
76
78
  ```
77
79
 
78
80
  Agents are markdown files with frontmatter in `~/.pi/agent/agents/` and `.pi/agents/` (same format as pi's subagent example). A worker inherits your model when the agent names none and `inheritModel` is true.
79
81
 
80
- State, logs and prompts live in `.pi/orchestra/` (git-ignored by the extension itself); exports land in `exports/`, archived runs in `archive/`.
82
+ State, logs and prompts live in `.pi/orchestra/` (git-ignored by the extension itself); exports land in `exports/`, archived runs in `archive/`. The state is per directory and outlives sessions, so a run that finished more than `staleRunHours` ago is no longer treated as current — new work creates a new run. `/orchestra reset` archives the whole store and starts clean, `/orchestra hide` / `/orchestra show` toggle the widget for this project.
81
83
 
82
84
  Run templates (`/orchestra templates`) can create a whole run from a markdown plan instead of eight `task_create` calls.
83
85