pi-durable-subagents 1.0.29 → 1.0.32

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/CHANGELOG.md CHANGED
@@ -1,5 +1,37 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.0.32
4
+
5
+ - `/subagents` lists working workflows first (newest first) and finished ones
6
+ after them (most recently ended first), so running work is never buried
7
+ under a page of finished rows. The cursor stays on its row when a workflow
8
+ moves.
9
+ - Rows name subagents the way people know them: a workflow's only subagent by
10
+ the workflow's name, a generated key (`tasks:0`, `chain:1`) by its agent,
11
+ numbered when repeated (`worker 1`, `worker 2`). Applies to the list, the
12
+ dock, the watch view and the input prompts; tools and the CLI keep the key
13
+ as the address. A name longer than the key column is clipped so columns
14
+ stay aligned.
15
+
16
+ ## 1.0.31
17
+
18
+ - A run can be shown in the pi session it was started for, not only the one
19
+ that sent it. pi exports `DSA_SESSION=<session id>` to the processes it
20
+ starts, and `run` takes `--session <id>` (default: an inherited
21
+ `$DSA_SESSION`, ignored inside a subagent). A tool or script started from a
22
+ pi session therefore has its runs listed in that session's dock and
23
+ `/subagents`, sorted first in `status`. Display and ownership only:
24
+ completion notices and attention still go to the sender, quitting pi does not
25
+ pause these runs, and `session` is not part of a request's digest. An invalid
26
+ `--session` exits 1; the engine rejects an invalid id with `invalid-session`.
27
+
28
+ ## 1.0.30
29
+
30
+ - The pi UI shows only the subagents this pi session started again: the
31
+ dock's `elsewhere: ...` count and the `Other sessions` group from 1.0.29 are
32
+ removed, and the `ui.otherSessions` setting is ignored. Other sessions' and
33
+ the CLI's work remains visible through `status` and the CLI.
34
+
3
35
  ## 1.0.29
4
36
 
5
37
  - The pi UI shows subagents that other sessions or the CLI started, kept apart
package/README.md CHANGED
@@ -205,25 +205,17 @@ lines above the editor in extension load order, so to keep the dock above
205
205
  another extension's editor bar (a powerline bar, for example), list
206
206
  pi-durable-subagents before that extension in `packages`.
207
207
 
208
- Subagents that another pi session or the CLI started never get rows in this
209
- dock; while they run, the summary line adds a count, e.g.
210
- `elsewhere: 4 running (cli 2, 1 session 2)` (dropped first when the line is
211
- tight, and shown alone when this session has nothing running).
212
-
213
208
  Press `↓` on an empty editor, or type `/subagents`, to open the list, a floating panel: this
214
- session's workflows (sessions are independent), newest first, every
215
- subagent with its model, what it is doing and for how long, and its latest
216
- line. Finished ones stay there,
217
- dimmed, with their conclusion.
218
-
219
- Live workflows of other sessions and the CLI follow in one group at the end,
220
- `Other sessions (2 workflows, 4 running)`, folded until you press `Enter` on
221
- it. Each shows its wid, name, origin (`cli:<user>@<host>` or a short session
222
- id), labels and live calls. You can watch them, but not change them here:
223
- steer, stop, model, answer and follow-up are refused with a hint to use the
224
- session or CLI that started them (or the tool's `send` with an explicit
225
- address). `"ui": { "otherSessions": false }` hides both the count and the
226
- group.
209
+ session's workflows (sessions are independent), working ones first (newest
210
+ first), every subagent with its model, what it is doing and for how long, and
211
+ its latest line. Finished ones follow, most recently ended first, dimmed, with
212
+ their conclusion. A workflow's only subagent is named after the workflow; in a
213
+ fan-out, a generated key (`tasks:0`) shows as its agent (`worker 1`,
214
+ `reviewer`). The key remains the address for `send` and the CLI. A session's workflows include runs started
215
+ through the CLI by a process this session launched (a background driver, a
216
+ script run from its bash tool): pi exports `DSA_SESSION`, and `run` names that
217
+ session (see `--session` below). Other sessions' and a terminal's runs are
218
+ not shown.
227
219
 
228
220
  The list is also where you act. The footer shows the keys for the selected
229
221
  row: `Enter` watch, `s` steer, `f` follow-up, `x` stop (asks `y` first),
@@ -313,7 +305,7 @@ pi-durable-subagents start start the orchestrator if work is pendin
313
305
  pi-durable-subagents resume [wid] continue unfinished or parked work (undoes drain / stop-all)
314
306
  pi-durable-subagents drain hold existing workflows: running calls finish, nothing new starts in them
315
307
  pi-durable-subagents stop <wid|call>
316
- pi-durable-subagents run --request <id> --spec <file|-> [--labels <json>] [--cwd <dir>] [--json] [--wait-ms <n>]
308
+ pi-durable-subagents run --request <id> --spec <file|-> [--labels <json>] [--session <id>] [--cwd <dir>] [--json] [--wait-ms <n>]
317
309
  start a run under a caller-chosen id; safe to retry (see below)
318
310
  pi-durable-subagents send --request <id> --to <run-id|wid/key> [--to ...] --kind follow-up|answer|steer|notify|model
319
311
  [--call <key>] [--qid <qid> --rev <n>] --message <text|@file> [--model <m>] [--json]
@@ -496,6 +488,17 @@ request that carries invalid ones (`invalid-labels: …`). `describe` returns
496
488
  them as `labels` (also after `prune`), and every event of the run carries
497
489
  them.
498
490
 
491
+ `--session <pi session id>` shows the run in that pi session's dock and
492
+ `/subagents` list as one of its own; without it, `run` takes `$DSA_SESSION`,
493
+ which a pi session exports to every process it starts (a subagent's
494
+ processes never pass it on). It decides where the run is listed (the dock,
495
+ `/subagents` and that session's `status`), and you act on it there like on
496
+ any row; the run still belongs to its sender: that session's main agent gets
497
+ no completion notices for it, quitting that pi does not pause it, and the
498
+ session is not part of the content, so a retry from another session gets the
499
+ first outcome. An invalid `--session` exits 1; an invalid inherited value
500
+ is ignored.
501
+
499
502
  When an unsealed call does not move, its `waiting` in `describe` adds
500
503
  `reason`, `detail` (the status line for that cause, e.g. `waiting for a slot:
501
504
  probe 1/1`) and `since` (ms: when that cause started). The event log has the
@@ -91,7 +91,8 @@ export function registerMain(pi, ui) {
91
91
  return;
92
92
  await lock.release();
93
93
  const entry = process.env.DSA_ORCHESTRATOR_ENTRY ?? fileURLToPath(new URL(import.meta.url.endsWith(".ts") ? "../orchestrator/main.ts" : "../orchestrator/main.js", import.meta.url));
94
- const child = spawn(process.execPath, [entry], { detached: true, stdio: "ignore", env: { ...process.env, DSA_HOME: home } });
94
+ const { DSA_SESSION: _session, ...env } = process.env;
95
+ const child = spawn(process.execPath, [entry], { detached: true, stdio: "ignore", env: { ...env, DSA_HOME: home } });
95
96
  await new Promise((resolve, reject) => { child.once("spawn", resolve); child.once("error", reject); });
96
97
  child.unref();
97
98
  }
@@ -156,6 +157,10 @@ export function registerMain(pi, ui) {
156
157
  ctx = context;
157
158
  sender = `main:${context.sessionManager.getSessionId()}`;
158
159
  stopped = false;
160
+ // Processes this session starts (bash, a detached CLI driver) inherit it: their CLI runs name this session, which
161
+ // then shows them as its own. A subagent's pi is not a user's session and exports nothing.
162
+ if (!process.env.DSA_EXEC)
163
+ process.env.DSA_SESSION = context.sessionManager.getSessionId();
159
164
  outbox = await Outbox.open(outboxRoot(home), sender, () => orchInbox(home));
160
165
  noteSink = sink;
161
166
  await reconcile();
@@ -21,7 +21,9 @@ export async function startOrchestrator(home, env) {
21
21
  return;
22
22
  await lock.release();
23
23
  const entry = env.DSA_ORCHESTRATOR_ENTRY ?? fileURLToPath(new URL(import.meta.url.endsWith(".ts") ? "../orchestrator/main.ts" : "../orchestrator/main.js", import.meta.url));
24
- const child = spawn(process.execPath, [entry], { detached: true, stdio: "ignore", env: { ...env, DSA_HOME: home } });
24
+ // The orchestrator serves every session: it never carries the starting pi session's $DSA_SESSION to its children.
25
+ const { DSA_SESSION: _session, ...rest } = env;
26
+ const child = spawn(process.execPath, [entry], { detached: true, stdio: "ignore", env: { ...rest, DSA_HOME: home } });
25
27
  await new Promise((resolve, reject) => { child.once("spawn", resolve); child.once("error", reject); });
26
28
  child.unref();
27
29
  }
package/dist/cli/main.js CHANGED
@@ -164,7 +164,7 @@ export function serviceEntryError(entry) {
164
164
  return `install-service refuses to run from an npx cache (${entry}); the cache can be pruned and the service would break. Install the CLI with \`npm i -g pi-durable-subagents\` and run \`pi-durable-subagents install-service\` again.`;
165
165
  return undefined;
166
166
  }
167
- export const HELP = "pi-durable-subagents: smoke | status [wid] [--json] | status <wid> [--tail <n>] [--grep <regex>] [--json] | events <wid> [--json] | events --all [--since <cursor>] [--limit <n>] [--json] [--wait-ms <n>] | tail [wid] [--json] | start | resume [wid] | drain | stop <wid|callId> | stop-all | run --request <id> --spec <file|-> [--labels <json>] [--cwd <dir>] [--json] [--wait-ms <n>] | send --request <id> --to <run-id|wid/key> [--to ...] [--call <key>] --kind follow-up|answer|steer|notify|model [--qid <qid> --rev <n>] [--message <text|@file>] [--model <m>] [--json] [--wait-ms <n>] | stop --request <id> <run-id|wid|wid/key> [--json] [--wait-ms <n>] | describe --key <id> | describe <wid> [--json] | prune [wid] [--older-than <days>] | restart [--force <token> --reason <text>] | hold <resource> [--shared | --slots <n>] [--max-wait <s> | --no-wait] [--note <text>] -- <command…> | leases [--json] | doctor [--json] | install-service [--dry-run] | uninstall-service [--dry-run] | chaos [--scenario <1-9>] [--keep] [--json] | drill failover [--keep] [--json]";
167
+ export const HELP = "pi-durable-subagents: smoke | status [wid] [--json] | status <wid> [--tail <n>] [--grep <regex>] [--json] | events <wid> [--json] | events --all [--since <cursor>] [--limit <n>] [--json] [--wait-ms <n>] | tail [wid] [--json] | start | resume [wid] | drain | stop <wid|callId> | stop-all | run --request <id> --spec <file|-> [--labels <json>] [--session <id>] [--cwd <dir>] [--json] [--wait-ms <n>] | send --request <id> --to <run-id|wid/key> [--to ...] [--call <key>] --kind follow-up|answer|steer|notify|model [--qid <qid> --rev <n>] [--message <text|@file>] [--model <m>] [--json] [--wait-ms <n>] | stop --request <id> <run-id|wid|wid/key> [--json] [--wait-ms <n>] | describe --key <id> | describe <wid> [--json] | prune [wid] [--older-than <days>] | restart [--force <token> --reason <text>] | hold <resource> [--shared | --slots <n>] [--max-wait <s> | --no-wait] [--note <text>] -- <command…> | leases [--json] | doctor [--json] | install-service [--dry-run] | uninstall-service [--dry-run] | chaos [--scenario <1-9>] [--keep] [--json] | drill failover [--keep] [--json]";
168
168
  /** Restart: the orchestrator exits when no execution runs (or `force`) and the installed version takes over. */
169
169
  async function restartCommand(home, env, write, options) {
170
170
  const body = { ...(typeof options.force === "string" ? { token: options.force } : options.force === true ? { force: true } : {}), ...(options.reason !== undefined ? { reason: options.reason } : {}), initiator: cliInitiator(env) };
@@ -7,7 +7,7 @@ import { setTimeout as delay } from "node:timers/promises";
7
7
  import { readJournalSnapshot } from "../kernel/journal.js";
8
8
  import { reduceLifecycle } from "../kernel/lifecycle.js";
9
9
  import { journalPath, orchLedger, pinnedDir } from "../paths.js";
10
- import { batchConflict, batchDigest, findRequest, manyIds, namesMany, REQUEST_ID, requestId, requestRid, RequestsBusy, specDigest } from "../requests.js";
10
+ import { batchConflict, batchDigest, findRequest, manyIds, namesMany, REQUEST_ID, requestId, requestRid, RequestsBusy, SESSION_ID, specDigest } from "../requests.js";
11
11
  import { NOTIFY_SINCE, isLive, orchestratorTooOld, slotsView, workflowSnapshot, writerWaits, writerWaitLine, WRITER_WAIT_HINT } from "../orchestrator/snapshot.js";
12
12
  import { leaseCalls, leaseState } from "../platform/lease.js";
13
13
  import { BATCH, checkAgents, outcomeLine, request, sendReceipt } from "../agent/main/tool.js";
@@ -265,16 +265,27 @@ async function refusable(args, ctx, run) {
265
265
  }
266
266
  const forks = (spec) => [spec, ...["tasks", "chain"].flatMap(k => Array.isArray(spec[k]) ? spec[k] : [])]
267
267
  .some(s => s && typeof s === "object" && s.context === "fork");
268
- /** `run --request <id> --spec <file|-> [--cwd <dir>] [--json] [--wait-ms <n>]`. The spec is the `subagents` run
268
+ /** The pi session a CLI run is shown in: --session, else $DSA_SESSION (exported by a pi session to what it starts)
269
+ * unless this process runs inside a subagent call. An unusable inherited value is ignored; a bad flag is an error. */
270
+ export function runSession(flag, env) {
271
+ if (flag !== undefined) {
272
+ if (!SESSION_ID.test(flag))
273
+ throw new Error("--session must be a pi session id ([A-Za-z0-9._:-], at most 128 characters)");
274
+ return flag;
275
+ }
276
+ const inherited = env.DSA_CALL || env.DSA_EXEC ? undefined : env.DSA_SESSION;
277
+ return inherited && SESSION_ID.test(inherited) ? inherited : undefined;
278
+ }
279
+ /** `run --request <id> --spec <file|-> [--session <id>] [--cwd <dir>] [--json] [--wait-ms <n>]`. The spec is the `subagents` run
269
280
  * form ({agent,task,…} or {tasks|chain:[…],…}); it is validated by the tool's own normalizer and agent check. */
270
281
  export const runCommand = (args, ctx) => refusable(args, ctx, runRequest);
271
282
  async function runRequest(args, ctx, seen) {
272
- const { values, positionals } = flags(args, { request: "value", spec: "value", cwd: "value", labels: "value", json: "flag", "wait-ms": "value" });
283
+ const { values, positionals } = flags(args, { request: "value", spec: "value", cwd: "value", labels: "value", session: "value", json: "flag", "wait-ms": "value" });
273
284
  const id = text(values, "request"), file = text(values, "spec"), json = values.json === true, wait = waitMs(values, ctx);
274
285
  seen.id = id;
275
286
  seen.json = json;
276
287
  if (!id || !file || positionals.length)
277
- throw new Error("usage: run --request <id> --spec <file|-> [--labels <json>] [--cwd <dir>] [--json] [--wait-ms <n>]");
288
+ throw new Error("usage: run --request <id> --spec <file|-> [--labels <json>] [--session <pi session id>] [--cwd <dir>] [--json] [--wait-ms <n>]");
278
289
  requestRid(id);
279
290
  const raw = text(values, "labels"), labels = raw !== undefined ? parseLabels(raw) : undefined;
280
291
  const bytes = file === "-" ? await (ctx.stdin ?? stdin)() : readFileSync(resolve(ctx.cwd ?? process.cwd(), file), "utf8");
@@ -299,6 +310,9 @@ async function runRequest(args, ctx, seen) {
299
310
  const base = resolve(ctx.cwd ?? process.cwd(), text(values, "cwd") ?? "."), dir = typeof spec.cwd === "string" && spec.cwd ? resolve(base, spec.cwd) : base;
300
311
  const normalized = request({ ...spec, action: "run", ...(typeof spec.cwd === "string" && spec.cwd ? { cwd: dir } : {}), ...(labels ? { labels } : {}) }, dir);
301
312
  const body = normalized.body;
313
+ const session = runSession(text(values, "session"), ctx.env);
314
+ if (session)
315
+ body.session = session;
302
316
  seen.digest = specDigest({ kind: "run", body });
303
317
  // An id already recorded is decided by that record: the same content gets its first outcome (the agents it named may
304
318
  // have changed since), other content is a request-conflict. Only a new id is checked here.
@@ -20,7 +20,7 @@ import { contentHash } from "../kernel/ids.js";
20
20
  import { planDecisions, reduceLifecycle } from "../kernel/lifecycle.js";
21
21
  import { scanInbox } from "../kernel/mailbox.js";
22
22
  import { orchInbox, pinnedDir } from "../paths.js";
23
- import { requestId, specDigest } from "../requests.js";
23
+ import { SESSION_ID, requestId, specDigest } from "../requests.js";
24
24
  import { JT, attentionEntries, isEntry } from "../types.js";
25
25
  import { isForceRestart, restartRefusal } from "./restart.js";
26
26
  import { EvaluatorClient } from "./evaluator-client.js";
@@ -409,6 +409,9 @@ export class Engine {
409
409
  const labels = req.body?.labels, invalid = !created && labels !== undefined ? labelsProblem(labels) : undefined;
410
410
  if (invalid)
411
411
  return { action: 'reject', reason: `invalid-labels: ${invalid}` };
412
+ const session = req.body?.session;
413
+ if (!created && session !== undefined && (typeof session !== 'string' || !SESSION_ID.test(session)))
414
+ return { action: 'reject', reason: 'invalid-session: a pi session id' };
412
415
  if (created && this.store.pruned().has(String(created.wid)))
413
416
  return { action: 'apply' }; // Never resurrect a pruned run.
414
417
  let wf = created ? this.store.workflows.get(created.wid) : undefined;
@@ -22,6 +22,8 @@ import { packageVersion } from "../version.js";
22
22
  /** P2, C4, K6: Acquire the single authority before opening ledgers, recover, and idle-exit. Resolves `restart` when an
23
23
  * applied restart request ended it (the caller starts the successor once the lock is released). */
24
24
  export async function main(options = {}) {
25
+ // Serves every session: whichever pi session started it, its children and their CLI runs must not name that session.
26
+ delete process.env.DSA_SESSION;
25
27
  const home = options.home ?? dsaHome();
26
28
  await mkdir(home, { recursive: true });
27
29
  const lock = await new OsLock().tryAcquire(orchLock(home));
@@ -377,7 +377,7 @@ const ledgerIndexes = new WeakMap();
377
377
  export function ledgerIndex(ledger) {
378
378
  let ix = ledgerIndexes.get(ledger);
379
379
  if (!ix || ix.length > ledger.length || (ix.length && ledger[ix.length - 1] !== ix.last)) {
380
- ix = { length: 0, created: new Map(), pruned: new Set(), labels: new Map(), runLabels: new Map(), byWid: new Map(), byOrigin: new Map() };
380
+ ix = { length: 0, created: new Map(), pruned: new Set(), labels: new Map(), runLabels: new Map(), sessions: new Map(), runSessions: new Map(), byWid: new Map(), byOrigin: new Map() };
381
381
  ledgerIndexes.set(ledger, ix);
382
382
  }
383
383
  for (let i = ix.length; i < ledger.length; i++) {
@@ -391,17 +391,29 @@ export function ledgerIndex(ledger) {
391
391
  ix.labels.set(String(e.wid), labels);
392
392
  ix.runLabels.delete(String(e.rid));
393
393
  }
394
+ const session = ix.runSessions.get(String(e.rid));
395
+ if (session) {
396
+ if (!ix.sessions.has(String(e.wid)))
397
+ ix.sessions.set(String(e.wid), session);
398
+ ix.runSessions.delete(String(e.rid));
399
+ }
394
400
  }
395
401
  else if (e.type === "request") {
396
402
  const r = e.request, labels = r?.kind === "run" ? labelsOf(r.body) : undefined;
397
403
  if (labels && typeof r?.rid === "string")
398
404
  ix.runLabels.set(r.rid, labels);
405
+ const session = r?.kind === "run" ? r.body?.session : undefined;
406
+ if (typeof session === "string" && session && typeof r?.rid === "string")
407
+ ix.runSessions.set(r.rid, session);
399
408
  }
400
- else if (e.type === JT.rejected)
409
+ else if (e.type === JT.rejected) {
401
410
  ix.runLabels.delete(String(e.rid));
411
+ ix.runSessions.delete(String(e.rid));
412
+ }
402
413
  else if (e.type === "pruned") {
403
414
  ix.pruned.add(String(e.wid));
404
415
  ix.labels.delete(String(e.wid));
416
+ ix.sessions.delete(String(e.wid));
405
417
  }
406
418
  else if (e.type === "drain" || e.type === "undrain") {
407
419
  if (e.type === "drain")
@@ -448,11 +460,16 @@ export function heldWorkflows(home) {
448
460
  const origin = (wid) => ix.created.get(wid)?.origin;
449
461
  const hold = (wid) => holdOf(ledger, wid, origin(wid));
450
462
  const since = ix.lastDrain !== undefined ? ledger[ix.lastDrain].ts : undefined;
451
- return { ...(since !== undefined ? { since } : {}), held: wid => hold(wid) !== undefined, labels: wid => ix.labels.get(wid) };
463
+ return { ...(since !== undefined ? { since } : {}), held: wid => hold(wid) !== undefined, labels: wid => ix.labels.get(wid), session: wid => ix.sessions.get(wid) };
464
+ }
465
+ /** The workflow with its run's labels and session, when it has them. */
466
+ function labelled(wf, labels, session) {
467
+ return labels || session ? { ...wf, ...(labels ? { labels } : {}), ...(session ? { session } : {}) } : wf;
452
468
  }
453
- /** The workflow with its run's labels, when it has any. */
454
- function labelled(wf, labels) {
455
- return labels ? { ...wf, labels } : wf;
469
+ /** Whether `origin` ("main:<pi session id>") shows the workflow as its own: it started it, or the run named that pi
470
+ * session (RunBody.session, e.g. a CLI driver started from that session). */
471
+ export function ownedBy(w, origin) {
472
+ return w.origin === origin || (w.session !== undefined && `main:${w.session}` === origin);
456
473
  }
457
474
  /** Labels clipped for one status line: "[k=v k2=v2]", at most `width` characters (empty without labels). */
458
475
  export function labelsText(labels, width = 60) {
@@ -463,8 +480,8 @@ export function labelsText(labels, width = 60) {
463
480
  }
464
481
  /** P25: Snapshot every workflow under DSA_HOME (newest first by wid, which is a ULID); `paused` marks work a drain holds. */
465
482
  export function allWorkflows(home) {
466
- const { held, labels } = heldWorkflows(home);
467
- return workflowIds(home).sort().reverse().map(wid => { const wf = labelled(workflowSnapshot(home, wid), labels(wid)); return isLive(wf) && held(wid) ? { ...wf, paused: true } : wf; });
483
+ const { held, labels, session } = heldWorkflows(home);
484
+ return workflowIds(home).sort().reverse().map(wid => { const wf = labelled(workflowSnapshot(home, wid), labels(wid), session(wid)); return isLive(wf) && held(wid) ? { ...wf, paused: true } : wf; });
468
485
  }
469
486
  /** P10/P11: Per-workflow script console log written by the orchestrator (bounded, human-readable). */
470
487
  export function scriptLogPath(home, wid) { return join(workflowDir(home, wid), "script.log"); }
@@ -507,10 +524,10 @@ function origins(home) {
507
524
  }
508
525
  /** Every workflow with its origin and hold, own session first, then newest first. */
509
526
  function snapshots(home, origin) {
510
- const own = (w) => Number(!!origin && w.origin === origin);
511
- const { since, held, labels } = heldWorkflows(home);
527
+ const own = (w) => Number(!!origin && ownedBy(w, origin));
528
+ const { since, held, labels, session } = heldWorkflows(home);
512
529
  const all = [...origins(home)].sort(([a], [b]) => a < b ? 1 : a > b ? -1 : 0).map(([wid, origin]) => {
513
- const wf = labelled(workflowSnapshot(home, wid), labels(wid)), withOrigin = wf.origin === undefined && origin !== undefined ? { ...wf, origin } : wf;
530
+ const wf = labelled(workflowSnapshot(home, wid), labels(wid), session(wid)), withOrigin = wf.origin === undefined && origin !== undefined ? { ...wf, origin } : wf;
514
531
  return isLive(withOrigin) && held(wid) ? { ...withOrigin, paused: true } : withOrigin;
515
532
  }).sort((a, b) => own(b) - own(a));
516
533
  return { all, ...(since !== undefined ? { since } : {}) };
@@ -641,7 +658,7 @@ export function slotsView(home, now = Date.now()) {
641
658
  export function statusBrief(home, options = {}) {
642
659
  const keep = options.keep ?? 5, now = options.now ?? Date.now(), origin = options.origin;
643
660
  const { all } = snapshots(home, origin), leases = leaseState(home), byCall = leaseCalls(leases, now);
644
- const mine = (w) => !origin || w.origin === origin;
661
+ const mine = (w) => !origin || ownedBy(w, origin);
645
662
  const line = (w) => {
646
663
  const p = progressOf(w), notOk = latestCalls(w).filter(c => c.result && !c.result.ok).length;
647
664
  const notes = latestCalls(w).reduce((n, c) => n + (c.notesPending ?? 0), 0);
@@ -775,7 +792,7 @@ export function statusDetail(home, wid) {
775
792
  const origin = origins(home);
776
793
  if (!origin.has(wid))
777
794
  throw new Error(prunedIds(home).has(wid) ? `Workflow ${wid} was pruned` : `Unknown workflow: ${wid}`);
778
- const wf = labelled(workflowSnapshot(home, wid), heldWorkflows(home).labels(wid)), log = scriptLogPath(home, wid);
795
+ const held = heldWorkflows(home), wf = labelled(workflowSnapshot(home, wid), held.labels(wid), held.session(wid)), log = scriptLogPath(home, wid);
779
796
  return { ...wf, ...(wf.origin === undefined && origin.get(wid) !== undefined ? { origin: origin.get(wid) } : {}), ...(existsSync(log) ? { scriptLog: log } : {}) };
780
797
  }
781
798
  /** P25, T10: Project a workflow journal into meaningful events (no observations, time or tracking). */
package/dist/requests.js CHANGED
@@ -48,12 +48,15 @@ export async function namesMany(home, id) {
48
48
  const first = `${id}:1`;
49
49
  return REQUEST_ID.test(first) && await findRequest(home, requestRid(first)) !== undefined;
50
50
  }
51
+ /** A pi session id as a run's `session`: what a pi session exports as $DSA_SESSION. */
52
+ export const SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
51
53
  /** Spec_digest = contentHash({kind, body, cond}) (cond omitted when absent). A run's body.origin (the pi session
52
- * branch offered for context:"fork") is delivery metadata, not spec: it differs on every turn, so it is not hashed. */
54
+ * branch offered for context:"fork") is delivery metadata, not spec: it differs on every turn, so it is not hashed;
55
+ * nor is body.session (which pi session shows the run): a retry from another session is the same request. */
53
56
  export function specDigest(req) {
54
57
  let body = req.body;
55
58
  if (req.kind === 'run' && body && typeof body === 'object' && !Array.isArray(body)) {
56
- const { origin: _, ...rest } = body;
59
+ const { origin: _, session: _s, ...rest } = body;
57
60
  body = rest;
58
61
  }
59
62
  if (req.kind === 'send' && body && typeof body === 'object' && !Array.isArray(body)) {
package/dist/ui/data.js CHANGED
@@ -51,13 +51,6 @@ const FINAL_MS = 10_000;
51
51
  /** A1, P25: Read the UI's data from durable workflow snapshots and native session tails only. */
52
52
  export class UiData {
53
53
  workflows = [];
54
- /** Every workflow read by the last refresh, before the owning session splits them (a watched call of another
55
- * origin stays watchable after its workflow settles). */
56
- all = [];
57
- /** Live workflows of other origins (other pi sessions, the CLI), split off by the session that owns this data. */
58
- others = [];
59
- /** Whether other origins' live work is shown (the dock's elsewhere count, the list's Other sessions group). */
60
- otherSessions = true;
61
54
  /** Facts and session branch per call id; a finished call's are read on first `get` (see refresh). */
62
55
  facts = new Map();
63
56
  sessions = new Map();
@@ -160,7 +153,6 @@ export class UiData {
160
153
  load();
161
154
  }
162
155
  this.workflows = workflows;
163
- this.all = workflows;
164
156
  this.facts = facts;
165
157
  this.sessions = sessions;
166
158
  // UI-only optional aliases; absence or invalid config must not break execution (P21).
@@ -169,13 +161,11 @@ export class UiData {
169
161
  this.aliases = Object.fromEntries(Object.entries(config.ui?.modelAliases ?? {}).filter(([, v]) => typeof v === "string"));
170
162
  this.dock = ["auto", "line", "off"].includes(config.ui?.dock) ? config.ui.dock : "auto";
171
163
  this.dockAt = config.ui?.dockAt === "below" ? "below" : "above";
172
- this.otherSessions = config.ui?.otherSessions !== false;
173
164
  }
174
165
  catch {
175
166
  this.aliases = {};
176
167
  this.dock = "auto";
177
168
  this.dockAt = "above";
178
- this.otherSessions = true;
179
169
  }
180
170
  }
181
171
  }
package/dist/ui/index.js CHANGED
@@ -2,7 +2,7 @@ import { matchesKey, truncateToWidth, visibleWidth } from "@earendil-works/pi-tu
2
2
  import { UiActions, UiData } from "./data.js";
3
3
  import { SubagentScreen } from "./screen.js";
4
4
  import { oneLine } from "./frame.js";
5
- import { dockLines, mainLine, modelLabel, orderWorkflows, otherWorkflows, othersLive } from "./view.js";
5
+ import { dockLines, mainLine, modelLabel, orderWorkflows } from "./view.js";
6
6
  import { registerCards } from "./cards.js";
7
7
  import { toolRenderers } from "./tool.js";
8
8
  /** UI §1–3, P16, P21: Register journal-backed list/watch surfaces only in interactive pi. */
@@ -67,19 +67,16 @@ export function registerUi(pi, deps) {
67
67
  if (stopped)
68
68
  return;
69
69
  try {
70
- // Split by origin at once: nothing between the read and the split may leave other sessions' workflows among
71
- // this session's (the screen also checks the origin itself before any change).
72
70
  data.refresh();
73
- const own = `main:${ctx.sessionManager.getSessionId()}`;
74
- data.others = data.otherSessions ? otherWorkflows(data.workflows, own) : [];
75
- data.workflows = orderWorkflows(data.workflows, own);
76
71
  actions.reconcile();
77
72
  for (const result of actions.resolutions.splice(0))
78
73
  screen?.controlResult(result);
74
+ const own = `main:${ctx.sessionManager.getSessionId()}`;
75
+ data.workflows = orderWorkflows(data.workflows, own);
79
76
  // UI §1: the dock — live rows per active agent plus a summary line ("auto"), only the summary ("line"), or nothing.
80
77
  const name = (model) => modelLabel(model, (p, id) => ctx.modelRegistry.find(p, id), data.aliases);
81
78
  const now = Date.now(), dock = data.dock;
82
- const lines = (width) => dock === "off" ? [] : dock === "line" ? [mainLine(data.workflows, data.others, width) ?? ""].filter(Boolean) : dockLines(data.workflows, data.facts, name, width, now, 3, data.others);
79
+ const lines = (width) => dock === "off" ? [] : dock === "line" ? [mainLine(data.workflows) ?? ""].filter(Boolean) : dockLines(data.workflows, data.facts, name, width, now);
83
80
  dockRows = lines;
84
81
  // The widget is installed once, at session start (and again only when its placement changes). pi stacks
85
82
  // widgets in the order they were set, so installing once keeps the dock where the extension load order puts
@@ -120,7 +117,7 @@ export function registerUi(pi, deps) {
120
117
  const open = () => {
121
118
  if (stopped || opening)
122
119
  return "busy";
123
- if (!data.workflows.length && !othersLive(data.others))
120
+ if (!data.workflows.length)
124
121
  return "empty";
125
122
  opening = true;
126
123
  void (async () => {
@@ -134,7 +131,7 @@ export function registerUi(pi, deps) {
134
131
  };
135
132
  openList = open;
136
133
  unsubscribe = ctx.ui.onTerminalInput(key => {
137
- if (stopped || opening || !matchesKey(key, "down") || ctx.ui.getEditorText() !== "" || !editorFocused() || !data.workflows.length && !othersLive(data.others))
134
+ if (stopped || opening || !matchesKey(key, "down") || ctx.ui.getEditorText() !== "" || !editorFocused() || !data.workflows.length)
138
135
  return;
139
136
  open();
140
137
  return { consume: true };
package/dist/ui/screen.js CHANGED
@@ -2,7 +2,7 @@ import { AssistantMessageComponent, UserMessageComponent, ToolExecutionComponent
2
2
  import { Input, SelectList, fuzzyFilter, matchesKey, truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
3
3
  import { CT } from "../types.js";
4
4
  import { UiActions, UiData } from "./data.js";
5
- import { doneOrder, isOpen, originText, plainReason, toggleOpen, duration, keepSelection, summaryText, label, listRows, modelLabel, pendingText, resultPhrase, rowText, toolCount } from "./view.js";
5
+ import { callName, doneOrder, isOpen, plainReason, toggleOpen, duration, keepSelection, summaryText, listRows, modelLabel, pendingText, resultPhrase, rowText, toolCount } from "./view.js";
6
6
  import { fitWidth, frame, inner } from "./frame.js";
7
7
  import { thinkingElapsed } from "./thinking.js";
8
8
  import { thoughtSummary } from "./session.js";
@@ -82,7 +82,7 @@ export class SubagentScreen {
82
82
  beginListInput(kind, row) {
83
83
  const c = row.call, w = row.workflow;
84
84
  const q = w.attention.find(a => a.kind === "question" && a.call === c.callId);
85
- this.listInput = { kind, call: c, workflow: w, editor: new Input({ prompt: `${kind} ${label(c)}: ` }), ...(kind === "answer" && q ? { qid: q.qid, rev: q.rev } : {}) };
85
+ this.listInput = { kind, call: c, workflow: w, editor: new Input({ prompt: `${kind} ${callName(w, c)}: ` }), ...(kind === "answer" && q ? { qid: q.qid, rev: q.rev } : {}) };
86
86
  this.listInput.editor.focused = this.focused;
87
87
  this.listNotice = undefined;
88
88
  }
@@ -94,24 +94,15 @@ export class SubagentScreen {
94
94
  if (!message)
95
95
  return;
96
96
  this.listInput = undefined;
97
- const { call: c, kind } = draft;
98
- this.listAction({ action: "send", to: c.callId, kind, message, ...(kind === "answer" ? { qid: draft.qid, rev: draft.rev } : {}) }, `${kind} ${label(c)}: ${JSON.stringify(message)}`);
97
+ const { call: c, workflow: w, kind } = draft;
98
+ this.listAction({ action: "send", to: c.callId, kind, message, ...(kind === "answer" ? { qid: draft.qid, rev: draft.rev } : {}) }, `${kind} ${callName(w, c)}: ${JSON.stringify(message)}`);
99
99
  }
100
100
  dispose() { this.disposed = true; }
101
101
  refresh() { if (!this.disposed)
102
102
  this.tui.requestRender(); }
103
103
  name = (model) => modelLabel(model, (p, id) => this.ctx.modelRegistry.find(p, id), this.data.aliases);
104
- /** A workflow another session or the CLI started: watchable here, never changed from here. */
105
- foreign(w) {
106
- // Decided by origin, not by list membership: a refresh interrupted before the split must not make them editable.
107
- const id = this.ctx.sessionManager?.getSessionId?.();
108
- return !!w && (id === undefined || w.origin !== `main:${id}`);
109
- }
110
- readOnly(w) {
111
- return `read-only: started by ${originText(w.origin)}; change it from that session or the CLI (or send with an explicit address)`;
112
- }
113
104
  current() {
114
- const w = this.data.workflows.find(w => w.wid === this.workflow) ?? this.data.all.find(w => w.wid === this.workflow);
105
+ const w = this.data.workflows.find(w => w.wid === this.workflow);
115
106
  let c = w?.calls.find(c => c.callId === this.watching);
116
107
  // P37: watching a key follows its newest generation (a continued call reopens on the same session).
117
108
  const newest = c && w.calls.filter(x => x.key === c.key && x.gen > c.gen).sort((a, b) => b.gen - a.gen)[0];
@@ -154,15 +145,8 @@ export class SubagentScreen {
154
145
  return;
155
146
  if (row.kind === "call")
156
147
  this.open(row.workflow, row.call);
157
- else if (row.kind === "workflow" && row.other) {
158
- const wid = row.workflow.wid;
159
- if (!this.state.folded.delete(wid))
160
- this.state.folded.add(wid);
161
- }
162
148
  else if (row.kind === "workflow")
163
149
  toggleOpen(row.workflow, this.state);
164
- else if (row.kind === "others")
165
- this.state.others = !this.state.others;
166
150
  else if (row.kind === "finished")
167
151
  this.state.finished = !this.state.finished;
168
152
  else if (row.workflow) {
@@ -190,10 +174,6 @@ export class SubagentScreen {
190
174
  const c = target ?? this.current().c;
191
175
  if (!c)
192
176
  return;
193
- if (!target && this.foreign(this.current().w)) {
194
- this.notice = this.readOnly(this.current().w);
195
- return;
196
- }
197
177
  this.menuTitle = `Model for ${c.key}`;
198
178
  const models = this.ctx.modelRegistry.getAvailable();
199
179
  this.menuItems = models.map(m => ({ value: `${m.provider}/${m.id}`, label: this.name(`${m.provider}/${m.id}`) }));
@@ -223,13 +203,9 @@ export class SubagentScreen {
223
203
  this.menu.onCancel = onCancel;
224
204
  }
225
205
  thinkingMenu() {
226
- const { c, w } = this.current();
206
+ const { c } = this.current();
227
207
  if (!c)
228
208
  return;
229
- if (this.foreign(w)) {
230
- this.notice = this.readOnly(w);
231
- return;
232
- }
233
209
  const model = this.data.facts.get(c.callId)?.model ?? c.model;
234
210
  if (!model)
235
211
  return;
@@ -245,13 +221,9 @@ export class SubagentScreen {
245
221
  };
246
222
  }
247
223
  cycleThinking() {
248
- const { c, w } = this.current();
224
+ const { c } = this.current();
249
225
  if (!c)
250
226
  return;
251
- if (this.foreign(w)) {
252
- this.notice = this.readOnly(w);
253
- return;
254
- }
255
227
  const facts = this.data.facts.get(c.callId), model = facts?.model ?? c.model;
256
228
  if (!model) {
257
229
  this.notice = "Model not yet recorded";
@@ -267,10 +239,6 @@ export class SubagentScreen {
267
239
  const message = this.input.getValue().trim();
268
240
  if (!message)
269
241
  return;
270
- if (this.foreign(w)) {
271
- this.notice = this.readOnly(w);
272
- return;
273
- }
274
242
  if (message === "/model") {
275
243
  this.modelMenu();
276
244
  this.input.setValue("");
@@ -291,7 +259,7 @@ export class SubagentScreen {
291
259
  }
292
260
  const q = w.attention.find(a => a.kind === "question" && a.call === c.callId);
293
261
  const kind = followUp ? "follow-up" : q ? "answer" : "steer";
294
- void this.send({ action: "send", to: c.callId, kind, message, ...(kind === "answer" ? { qid: q.qid, rev: q.rev } : {}) }, `${kind === "answer" ? "replied to" : followUp ? "queued follow-up for" : c.phase === "sealed" ? "continued" : "steered"} ${label(c)}: ${JSON.stringify(message)}`);
262
+ void this.send({ action: "send", to: c.callId, kind, message, ...(kind === "answer" ? { qid: q.qid, rev: q.rev } : {}) }, `${kind === "answer" ? "replied to" : followUp ? "queued follow-up for" : c.phase === "sealed" ? "continued" : "steered"} ${callName(w, c)}: ${JSON.stringify(message)}`);
295
263
  }
296
264
  handleInput(key) {
297
265
  if (this.disposed)
@@ -347,9 +315,7 @@ export class SubagentScreen {
347
315
  else if (!this.busy) {
348
316
  const row = this.selectedRow(), c = row?.kind === "call" ? row.call : undefined, w = row?.workflow;
349
317
  const asking = c && w?.attention.some(a => a.kind === "question" && a.call === c.callId);
350
- if (key.length === 1 && "sfamxr".includes(key) && (row?.other || this.foreign(w)))
351
- this.listNotice = { text: this.readOnly(w), until: Date.now() + 6000 };
352
- else if (key === "s" && c && c.phase !== "sealed")
318
+ if (key === "s" && c && c.phase !== "sealed")
353
319
  this.beginListInput("steer", row);
354
320
  else if (key === "f" && c?.phase === "sealed")
355
321
  this.beginListInput("follow-up", row);
@@ -360,7 +326,7 @@ export class SubagentScreen {
360
326
  else if (key === "r" && w?.paused)
361
327
  this.listAction({ action: "resume", wid: w.wid }, `resume ${w.name ?? w.wid}`);
362
328
  else if (key === "x" && (c && c.phase !== "sealed" || row?.kind === "workflow" && w?.status === "running")) {
363
- this.stopTarget = c ? { id: c.callId, name: label(c) } : { id: w.wid, name: w.name ?? w.wid };
329
+ this.stopTarget = c ? { id: c.callId, name: callName(w, c) } : { id: w.wid, name: w.name ?? w.wid };
364
330
  }
365
331
  // Typing that is not a list key is meant for pi (a message typed with the list still open would
366
332
  // otherwise have its Enter open a watch view): close the list and hand the text to the editor.
@@ -411,10 +377,10 @@ export class SubagentScreen {
411
377
  return;
412
378
  // Panel coordinates: row 0 is the top border, column 2 is the first content column.
413
379
  if (event.y === 2) {
414
- const { c } = this.current();
415
- if (!c)
380
+ const { c, w } = this.current();
381
+ if (!c || !w)
416
382
  return;
417
- const facts = this.data.facts.get(c.callId), model = `${label(c)} · ${this.name(facts?.model ?? c.model)} ▾ · `;
383
+ const facts = this.data.facts.get(c.callId), model = `${callName(w, c)} · ${this.name(facts?.model ?? c.model)} ▾ · `;
418
384
  const x = event.x - 2;
419
385
  if (x < visibleWidth(model))
420
386
  this.modelMenu();
@@ -563,20 +529,13 @@ export class SubagentScreen {
563
529
  // A two-column gutter carries the selection marker: a background alone is invisible in some themes and in
564
530
  // plain-text captures, and x must show which row it would stop.
565
531
  const rowWidth = Math.max(1, size.width - 2);
566
- const before = this.rows.find(r => r.id === this.selectedId), wasOther = Boolean(before?.other || before?.kind === "others");
567
532
  this.rows = this.doneTab && w ? doneOrder(w.calls).map(c => {
568
533
  const f = this.data.facts.get(c.callId);
569
- return { id: c.callId, kind: "call", workflow: w, call: c, failed: !c.result?.ok, text: rowText(" ", label(c), this.name(f?.model ?? c.model), resultPhrase(c), [toolCount(f?.tools)], rowWidth) };
570
- }) : listRows(this.data.workflows, this.state, this.data.facts, this.name, rowWidth, Date.now(), this.data.others);
534
+ return { id: c.callId, kind: "call", workflow: w, call: c, failed: !c.result?.ok, text: rowText(" ", callName(w, c), this.name(f?.model ?? c.model), resultPhrase(c), [toolCount(f?.tools)], rowWidth) };
535
+ }) : listRows(this.data.workflows, this.state, this.data.facts, this.name, rowWidth);
571
536
  height = this.height(Math.max(1, this.rows.length) + footerRows);
572
537
  size = inner(width, height); // inner width does not depend on height
573
- // A vanished row of another session (its workflow ended, or the whole group went) never hands the selection to
574
- // a different row of this session by position, where x or r would act on it: the group header takes it, or no
575
- // row is selected (-1) until ↑/↓ chooses one.
576
- if (wasOther && !this.rows.some(r => r.id === this.selectedId))
577
- this.selected = this.rows.findIndex(r => r.kind === "others");
578
- else if (this.selected >= 0 || this.selectedId !== undefined)
579
- this.selected = keepSelection(this.rows, this.selectedId, this.selected);
538
+ this.selected = keepSelection(this.rows, this.selectedId, this.selected);
580
539
  while (this.rows[this.selected]?.kind === "preview" && this.selected > 0)
581
540
  this.selected--;
582
541
  this.selectedId = this.rows[this.selected]?.id;
@@ -588,9 +547,8 @@ export class SubagentScreen {
588
547
  });
589
548
  const row = this.selectedRow(), c = row?.kind === "call" ? row.call : undefined;
590
549
  const asking = c && row?.workflow?.attention.some(a => a.kind === "question" && a.call === c.callId);
591
- const narrow = size.width < 72, readOnly = row?.other || this.foreign(row?.workflow) || this.doneTab && this.foreign(w);
592
- const keys = readOnly ? [narrow ? "↑↓" : "↑ ↓ select", row?.kind === "workflow" ? `Enter ${narrow ? "" : this.state.folded.has(row.workflow.wid) ? "expand" : "collapse"}`.trim() : row?.kind === "call" ? (narrow ? "Enter" : "Enter watch") : "",
593
- narrow ? "read-only" : `read-only: started by ${originText(row?.workflow?.origin ?? w?.origin)}; change it there`, "Esc back"].filter(Boolean).join(" · ") : [narrow ? "↑↓" : "↑ ↓ select", row && row.kind !== "preview" ? `Enter ${narrow ? "" : row.kind === "workflow" ? (isOpen(row.workflow, this.state) ? "collapse" : "expand") : row.kind === "call" ? "watch" : row.kind === "others" ? (this.state.others ? "collapse" : "expand") : "open"}`.trim() : "",
550
+ const narrow = size.width < 72;
551
+ const keys = [narrow ? "↑↓" : "↑ ↓ select", row && row.kind !== "preview" ? `Enter ${narrow ? "" : row.kind === "workflow" ? (isOpen(row.workflow, this.state) ? "collapse" : "expand") : row.kind === "call" ? "watch" : "open"}`.trim() : "",
594
552
  c && c.phase !== "sealed" ? (narrow ? "s" : "s steer") : "", c?.phase === "sealed" ? (narrow ? "f" : "f follow-up") : "",
595
553
  c && c.phase !== "sealed" || row?.kind === "workflow" && row.workflow?.status === "running" ? (narrow ? "x" : "x stop") : "",
596
554
  c ? (narrow ? "m" : "m model") : "", asking ? (narrow ? "a" : "a answer") : "", row?.workflow?.paused ? (narrow ? "r" : "r resume") : "", "Esc back"].filter(Boolean).join(" · ");
@@ -605,14 +563,13 @@ export class SubagentScreen {
605
563
  if (!c || !w)
606
564
  return panel(["Subagent is no longer in the current revision"], "Subagents", "Esc back");
607
565
  const facts = this.data.facts.get(c.callId), active = w.calls.filter(c => c.phase !== "sealed"), done = w.calls.length - active.length;
608
- const tabs = size.width < 60 ? `${c.key} ${w.calls.indexOf(c) + 1}/${w.calls.length}` : `${[...active.map(c => c.key), ...(done ? [`${done} done`] : [])].join(" · ")} ← → switch`;
566
+ const tabs = size.width < 60 ? `${callName(w, c)} ${w.calls.indexOf(c) + 1}/${w.calls.length}` : `${[...active.map(c => callName(w, c)), ...(done ? [`${done} done`] : [])].join(" · ")} ← → switch`;
609
567
  const tools = toolCount(facts?.tools), pending = pendingText(c.pending), rule = this.theme.fg("borderMuted", "─".repeat(size.width));
610
568
  const switching = c.switching ? ` → ${this.name(c.switching)} (requested)` : "";
611
- const head = [tabs, `${label(c)} · ${this.name(facts?.model ?? c.model)} ▾${switching} · ${facts?.thinking ?? "off"} ▾${tools ? ` · ${tools}` : ""}${pending ? ` · ${pending}` : ""}`,
569
+ const head = [tabs, `${callName(w, c)} · ${this.name(facts?.model ?? c.model)} ▾${switching} · ${facts?.thinking ?? "off"} ▾${tools ? ` · ${tools}` : ""}${pending ? ` · ${pending}` : ""}`,
612
570
  this.theme.fg("dim", this.spend(c, facts)), rule];
613
571
  const asking = w.attention.some(a => a.kind === "question" && a.call === c.callId);
614
- const placeholder = this.foreign(w) ? `Read-only: started by ${originText(w.origin)}`
615
- : `${c.phase === "sealed" ? "Continue" : asking ? "Reply to" : "Steer"} ${c.key}…${this.uses < 3 ? " / for commands" : ""}`;
572
+ const placeholder = `${c.phase === "sealed" ? "Continue" : asking ? "Reply to" : "Steer"} ${c.key}…${this.uses < 3 ? " / for commands" : ""}`;
616
573
  const empty = new Input({ prompt: "", placeholder, placeholderStyle: text => this.theme.fg("dim", text) });
617
574
  empty.focused = this.focused;
618
575
  const editor = this.input.getValue() ? this.input.render(size.width) : empty.render(size.width);
@@ -637,6 +594,6 @@ export class SubagentScreen {
637
594
  }
638
595
  this.inputRow = 1 + head.length + available + 1;
639
596
  // pi's own keys for the transcript, spelled out: thinking and tool output expand in place.
640
- return panel([...head, ...body, rule, ...editor, hint], `${w.name ?? w.wid} › ${label(c)}`, `${duration(Date.now() - (c.startedAt ?? Date.now()))} · ctrl+t thinking · ctrl+o tools · Esc back`);
597
+ return panel([...head, ...body, rule, ...editor, hint], new Set(w.calls.map(x => x.key)).size === 1 && w.name ? callName(w, c) : `${w.name ?? w.wid} › ${callName(w, c)}`, `${duration(Date.now() - (c.startedAt ?? Date.now()))} · ctrl+t thinking · ctrl+o tools · Esc back`);
641
598
  }
642
599
  }
package/dist/ui/view.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
2
- import { isLive, labelsText, liveCalls, progressOf } from "../orchestrator/snapshot.js";
2
+ import { isLive, labelsText, liveCalls, ownedBy, progressOf } from "../orchestrator/snapshot.js";
3
3
  import { oneLine } from "./frame.js";
4
4
  /** UI §2: Render compact wall-clock durations; never present these as charged active time. */
5
5
  export function duration(ms) {
@@ -28,55 +28,16 @@ export const toolCount = (n) => n ? `${n} tool${n === 1 ? "" : "s"}` : "";
28
28
  export const pendingText = (n) => n ? `${n} message${n === 1 ? "" : "s"} pending` : "";
29
29
  /** UI §2, P7: The list row's small pending marker (the watch header spells it out). */
30
30
  export const pendingMarker = (n) => n ? `${n} pending` : "";
31
- /** UI §2: Sessions are independent: only this session's workflows, newest first by start time. Start times never
32
- * change, so the order is stable while you read, also when a workflow finishes. */
31
+ /** UI §2: Sessions are independent: only this session's workflows (it started them, or a run started from it named it
32
+ * as its session, e.g. a CLI driver launched from this pi). Working ones come first, newest start first; finished ones
33
+ * follow, most recently ended first. A workflow moves once, when it finishes (or a follow-up reopens it); the list
34
+ * keeps the selection on the same row id, so the cursor follows it. */
33
35
  export function orderWorkflows(workflows, own) {
34
- return workflows.filter(w => own === undefined || w.origin === own)
35
- .sort((a, b) => (b.startedAt ?? 0) - (a.startedAt ?? 0) || (a.wid < b.wid ? 1 : a.wid > b.wid ? -1 : 0));
36
- }
37
- /** Live workflows started elsewhere (another pi session, the CLI or an unknown origin), newest first. A workflow of
38
- * another origin counts while it is not settled (as in the status tool's otherSessions): running, parked, or
39
- * finished with an open follow-up. */
40
- export function otherWorkflows(workflows, own) {
41
- return orderWorkflows(workflows.filter(w => w.origin !== own && (isLive(w) || w.status === "parked")));
42
- }
43
- /** Who started a workflow, short: `cli:<user>@<host>` as is, a pi session by the head of its id. */
44
- export function originText(origin) {
45
- if (!origin)
46
- return "unknown origin";
47
- return origin.startsWith("main:") ? `session ${origin.slice(5, 13)}` : origin;
48
- }
49
- const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
50
- /** Live calls of other origins in a few words, e.g. "elsewhere: 4 running (cli 2, 1 session 2)"; undefined when none. */
51
- export function elsewhereText(others) {
52
- let cli = 0, unknown = 0, inSessions = 0;
53
- const sessions = new Set();
54
- for (const w of others) {
55
- const n = liveCalls(w).length;
56
- if (!n)
57
- continue;
58
- if (w.origin?.startsWith("cli:"))
59
- cli += n;
60
- else if (w.origin?.startsWith("main:")) {
61
- inSessions += n;
62
- sessions.add(w.origin);
63
- }
64
- else
65
- unknown += n;
66
- }
67
- const total = cli + inSessions + unknown;
68
- if (!total)
69
- return undefined;
70
- const parts = [cli ? `cli ${cli}` : "", inSessions ? `${plural(sessions.size, "session")} ${inSessions}` : "", unknown ? `other ${unknown}` : ""].filter(Boolean);
71
- return `elsewhere: ${total} running (${parts.join(", ")})`;
72
- }
73
- /** Whether other origins have live calls: the one rule for the dock's elsewhere count and for opening the list. */
74
- export const othersLive = (others) => others.some(w => liveCalls(w).length > 0);
75
- /** A summary line with the elsewhere count appended when it fits; it is the first part dropped when the width is tight. */
76
- function withElsewhere(line, elsewhere, width) {
77
- const both = elsewhere ? `${line} · ${elsewhere}` : line;
78
- const fit = visibleWidth(both) <= width ? both : line;
79
- return Number.isFinite(width) ? truncateToWidth(fit, Math.max(1, width)) : fit;
36
+ const tie = (a, b) => (a.wid < b.wid ? 1 : a.wid > b.wid ? -1 : 0);
37
+ return workflows.filter(w => own === undefined || ownedBy(w, own))
38
+ .sort((a, b) => Number(isLive(b)) - Number(isLive(a))
39
+ || (isLive(a) ? (b.startedAt ?? 0) - (a.startedAt ?? 0) : (b.endedAt ?? b.startedAt ?? 0) - (a.endedAt ?? a.startedAt ?? 0))
40
+ || tie(a, b));
80
41
  }
81
42
  /** UI §2: Done rows newest result first by immutable end time; ties keep snapshot order, so rows never reshuffle. */
82
43
  export function doneOrder(calls) {
@@ -96,7 +57,7 @@ export function rowText(indent, key, model, phrase, tail, width, cols = { key: 0
96
57
  const end = tail.filter(Boolean).join(" · ");
97
58
  // A long phrase (a long command) is clipped; the tail (tools, age) stays. Under pressure the model column goes first.
98
59
  for (const showModel of width >= 40 ? [true, false] : [false]) {
99
- const head = `${indent}${pad(key, cols.key)} ${showModel ? `${pad(short, width < 70 ? 0 : cols.model)} ` : ""}`;
60
+ const head = `${indent}${pad(cols.key ? truncateToWidth(key, cols.key).replaceAll("\x1b[0m", "") : key, cols.key)} ${showModel ? `${pad(short, width < 70 ? 0 : cols.model)} ` : ""}`;
100
61
  const room = width - visibleWidth(head) - (end ? visibleWidth(end) + 2 : 0);
101
62
  // truncateToWidth closes its ellipsis with an SGR reset; drop it so a dimmed row stays dim to its end (tools, age).
102
63
  if (end && room >= 8)
@@ -184,6 +145,21 @@ export function statusPhrase(call, workflow, facts, now) {
184
145
  function failed(c) { return c.phase === "sealed" && c.result && !c.result.ok && c.result.status !== "skipped"; }
185
146
  /** UI §2, P37: Calls are named by key; later generations of a key carry their generation. */
186
147
  export const label = (c) => c.gen > 1 ? `${c.key}@${c.gen}` : c.key;
148
+ /** A key the spec did not name: generated from the launch form's position (tasks:0, chain:1). */
149
+ const GENERATED = /^(?:tasks|chain):(\d+)$/;
150
+ /** UI §2: How a person knows a call. A workflow's only agent goes by the workflow's name; a generated key (tasks:0) by
151
+ * its agent, numbered when the workflow runs that agent more than once; a named key as is. "@2" marks a later
152
+ * generation. The key stays the address for tools and the CLI; only the UI shows this name. */
153
+ export function callName(w, c) {
154
+ const keys = [...new Set(w.calls.map(x => x.key))], gen = c.gen > 1 ? `@${c.gen}` : "";
155
+ if (keys.length === 1 && w.name)
156
+ return `${w.name}${gen}`;
157
+ if (!GENERATED.test(c.key))
158
+ return `${c.key}${gen}`;
159
+ const peers = keys.filter(k => GENERATED.test(k) && w.calls.find(x => x.key === k)?.agent === c.agent)
160
+ .sort((a, b) => Number(GENERATED.exec(a)[1]) - Number(GENERATED.exec(b)[1]));
161
+ return `${c.agent}${peers.length > 1 ? ` ${peers.indexOf(c.key) + 1}` : ""}${gen}`;
162
+ }
187
163
  const WORDS = { ok: "done", stopped: "stopped", failed: "failed", "gate-failed": "failed", timeout: "timeout", budget: "budget", unknown: "unknown", skipped: "skipped", parked: "parked" };
188
164
  /** v12 §4: The result word of a sealed status — a stopped call is never called failed; timeout/budget/unknown are named as such. */
189
165
  export const resultWord = (status) => WORDS[status] ?? "failed";
@@ -206,14 +182,7 @@ export function summaryText(workflows) {
206
182
  return finished ? `${finished} finished` : "nothing running";
207
183
  return [s.asking ? `${s.asking} asking` : "", s.working ? `${s.working} working` : "", s.queued ? `${s.queued} queued` : "", s.paused ? `${s.paused} paused` : "", `${s.done}/${s.total}${s.plus ? "+" : ""} done`].filter(Boolean).join(" · ");
208
184
  }
209
- /** The one-line dock: this session's summary (or completion sentence), plus the elsewhere count of other origins. */
210
- export function mainLine(workflows, others = [], width = Infinity) {
211
- const own = ownLine(workflows), elsewhere = elsewhereText(others);
212
- if (own)
213
- return withElsewhere(own, elsewhere, width);
214
- return elsewhere ? withElsewhere(`${elsewhere} · ↓ subagents`, undefined, width) : undefined;
215
- }
216
- function ownLine(workflows) {
185
+ export function mainLine(workflows) {
217
186
  if (!workflows.length)
218
187
  return undefined;
219
188
  const s = summary(workflows);
@@ -238,10 +207,7 @@ const SPIN = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "
238
207
  /** UI §1: The dock above the editor. While agents work: one row per active agent (questions first, at most `rows`),
239
208
  * then one summary line; afterwards only the completion sentence for ten minutes; otherwise nothing. Activity spins
240
209
  * only while there is fresh evidence, so a quiet agent visibly stops moving. */
241
- /** Other origins' live calls never become rows here: they add an "elsewhere" count to the summary line (alone when this
242
- * session has nothing to show). */
243
- export function dockLines(workflows, facts, name, width, now = Date.now(), rows = 3, others = []) {
244
- const elsewhere = elsewhereText(others);
210
+ export function dockLines(workflows, facts, name, width, now = Date.now(), rows = 3) {
245
211
  const live = workflows.filter(isLive);
246
212
  const active = live.flatMap(w => {
247
213
  const latest = new Map();
@@ -252,22 +218,20 @@ export function dockLines(workflows, facts, name, width, now = Date.now(), rows
252
218
  }).sort((a, b) => Number(b.asking) - Number(a.asking));
253
219
  if (!active.length) {
254
220
  const ended = workflows.filter(w => !isLive(w)).sort((a, b) => (b.endedAt ?? 0) - (a.endedAt ?? 0))[0];
255
- const line = ended && now - (ended.endedAt ?? 0) < 10 * 60_000 ? ownLine(workflows) : undefined;
256
- if (line)
257
- return [withElsewhere(line, elsewhere, width)];
258
- return elsewhere ? [truncateToWidth(`${elsewhere} · ↓ subagents`, Math.max(1, width))] : [];
221
+ const line = ended && now - (ended.endedAt ?? 0) < 10 * 60_000 ? mainLine(workflows) : undefined;
222
+ return line ? [truncateToWidth(line, Math.max(1, width))] : [];
259
223
  }
260
- const cols = { key: Math.min(14, Math.max(...active.map(a => visibleWidth(label(a.c))))), model: Math.min(20, Math.max(...active.map(a => visibleWidth(name(facts.get(a.c.callId)?.model ?? a.c.model))))) };
224
+ const cols = { key: Math.min(20, Math.max(...active.map(a => visibleWidth(callName(a.w, a.c))))), model: Math.min(20, Math.max(...active.map(a => visibleWidth(name(facts.get(a.c.callId)?.model ?? a.c.model))))) };
261
225
  const shown = active.slice(0, rows);
262
226
  const lines = shown.map(({ w, c, asking }) => {
263
227
  // A running tool is activity; otherwise a minute without new evidence (no message, no tool) stops the spinner.
264
228
  const f = facts.get(c.callId), fresh = Boolean(f?.activity) || now - Math.max(c.lastActivity ?? 0, f?.lastActivity ?? 0, c.startedAt ?? 0) < 60_000;
265
229
  const mark = asking ? "?" : c.phase === "queued" ? "·" : fresh ? SPIN[Math.floor(now / 500) % SPIN.length] : "…";
266
230
  const phrase = asking ? `asks: ${w.attention.find(a => a.kind === "question" && a.call === c.callId).text}` : statusPhrase(c, w, f, now);
267
- return rowText(`${mark} `, label(c), name(f?.model ?? c.model), phrase, [], width, cols);
231
+ return rowText(`${mark} `, callName(w, c), name(f?.model ?? c.model), phrase, [], width, cols);
268
232
  });
269
233
  const more = active.length - shown.length;
270
- lines.push(withElsewhere(`${more ? `+${more} more · ` : ""}${summaryText(workflows)} · ↓ subagents`, elsewhere, width));
234
+ lines.push(truncateToWidth(`${more ? `+${more} more · ` : ""}${summaryText(workflows)} · ↓ subagents`, Math.max(1, width)));
271
235
  return lines;
272
236
  }
273
237
  /** UI §2, v12 §5: Group workflows (finished ones stay listed, dimmed and expandable — never hidden behind a toggle),
@@ -286,9 +250,7 @@ export function toggleOpen(w, state) {
286
250
  state.done.set(w.wid, Math.max(8, state.done.get(w.wid) ?? 0));
287
251
  }
288
252
  }
289
- /** `others` (live workflows of other origins) follow in one "Other sessions" group at the end, folded until opened;
290
- * their rows are marked `other` and never feed this session's reopen-on-failure state. */
291
- export function listRows(workflows, state, facts, name, width, now = Date.now(), others = []) {
253
+ export function listRows(workflows, state, facts, name, width, now = Date.now()) {
292
254
  const rows = [];
293
255
  state.observed ??= new Map();
294
256
  for (const w of workflows) {
@@ -305,20 +267,20 @@ export function listRows(workflows, state, facts, name, width, now = Date.now(),
305
267
  state.observed.set(w.wid, { working, failures });
306
268
  }
307
269
  const unviewed = (w) => w.calls.some(c => failed(c) && !state.viewed.has(c.callId));
308
- const visible = workflows; // caller order (newest first), unchanged when a workflow finishes
270
+ const visible = workflows; // caller order: working first, then finished (orderWorkflows)
309
271
  // Aligned columns across the whole list (UI §2): key and model start at the same column on every row.
310
- const shownCalls = [...visible.flatMap(w => w.calls), ...(state.others ? others.flatMap(liveCalls) : [])];
311
- const cols = { key: Math.min(18, Math.max(0, ...shownCalls.map(c => visibleWidth(label(c))))),
312
- model: Math.min(26, Math.max(0, ...shownCalls.map(c => visibleWidth(name(facts.get(c.callId)?.model ?? c.model))))) };
313
- const callRow = (w, c, indent, preview, dim = false, other = false) => {
272
+ const shownCalls = visible.flatMap(w => w.calls.map(c => ({ w, c })));
273
+ const cols = { key: Math.min(24, Math.max(0, ...shownCalls.map(({ w, c }) => visibleWidth(callName(w, c))))),
274
+ model: Math.min(26, Math.max(0, ...shownCalls.map(({ c }) => visibleWidth(name(facts.get(c.callId)?.model ?? c.model))))) };
275
+ const callRow = (w, c, indent, preview, dim = false) => {
314
276
  const f = facts.get(c.callId), age = c.phase === "sealed" ? `${duration(now - (c.endedAt ?? now))} ago` : c.startedAt ? duration(now - c.startedAt) : "";
315
277
  // A requested switch shows at once (it applies when the current step ends; until then it would look as if it had failed).
316
278
  const shown = c.switching ? `${name(f?.model ?? c.model)} → ${name(c.switching)}` : name(f?.model ?? c.model);
317
- const text = rowText(indent, label(c), shown, statusPhrase(c, w, f, now), [pendingMarker(c.pending), toolCount(f?.tools), age], width, cols);
318
- rows.push({ id: c.callId, kind: "call", workflow: w, call: c, failed: Boolean(failed(c)), dim, text, ...(other ? { other } : {}) });
279
+ const text = rowText(indent, callName(w, c), shown, statusPhrase(c, w, f, now), [pendingMarker(c.pending), toolCount(f?.tools), age], width, cols);
280
+ rows.push({ id: c.callId, kind: "call", workflow: w, call: c, failed: Boolean(failed(c)), dim, text });
319
281
  // Overview (UI §2): every active agent shows what it last said, thought or saw, without opening it.
320
282
  if (preview !== undefined && c.phase !== "sealed" && f?.latest)
321
- rows.push({ id: `${c.callId}:preview`, kind: "preview", workflow: w, call: c, dim, text: truncateToWidth(`${preview}${f.latest}`, Math.max(1, width)).replaceAll("\x1b[0m", ""), ...(other ? { other } : {}) });
283
+ rows.push({ id: `${c.callId}:preview`, kind: "preview", workflow: w, call: c, dim, text: truncateToWidth(`${preview}${f.latest}`, Math.max(1, width)).replaceAll("\x1b[0m", "") });
322
284
  };
323
285
  for (const v of visible) {
324
286
  // One row per key: the newest generation (key@2) stands for the agent; older ones open from its watch view (← →).
@@ -354,24 +316,5 @@ export function listRows(workflows, state, facts, name, width, now = Date.now(),
354
316
  if (more)
355
317
  rows.push({ id: `${w.wid}:more`, kind: "more", workflow: w, dim, text: ` └ … ${done.length - count} more` });
356
318
  }
357
- if (!others.length)
358
- return rows;
359
- // Other sessions: one folded group; inside, each workflow (wid, name, origin, labels) and its live calls only.
360
- const running = others.reduce((n, w) => n + liveCalls(w).length, 0);
361
- rows.push({ id: "others", kind: "others", text: `${state.others ? "▾" : "▸"} Other sessions (${plural(others.length, "workflow")}, ${running} running)` });
362
- if (!state.others)
363
- return rows;
364
- for (const w of others) {
365
- const folded = state.folded.has(w.wid), open = liveCalls(w), latest = new Map();
366
- for (const c of open)
367
- latest.set(c.key, c);
368
- const calls = [...latest.values()];
369
- const head = ` ${folded ? "▸" : "▾"} ${[w.wid, w.name, originText(w.origin)].filter(Boolean).join(" · ")}`;
370
- const room = Math.min(60, width - visibleWidth(head) - 3);
371
- rows.push({ id: w.wid, kind: "workflow", workflow: w, other: true, dim: !calls.length, text: w.labels && room >= 12 ? `${head} · ${labelsText(w.labels, room)}` : head });
372
- if (folded)
373
- continue;
374
- calls.forEach((c, i) => callRow(w, c, i === calls.length - 1 ? " └ " : " ├ ", undefined, false, true));
375
- }
376
319
  return rows;
377
320
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-durable-subagents",
3
- "version": "1.0.29",
3
+ "version": "1.0.32",
4
4
  "description": "Subagents for pi that never lose work and never do it twice. Crash-safe workflows, automatic recovery, and a live view just like the main agent.",
5
5
  "type": "module",
6
6
  "license": "MIT",