@awebai/oats 0.66.0 → 0.68.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.
Files changed (81) hide show
  1. package/bin/oats.mjs +166 -17
  2. package/docs/capabilities.md +58 -9
  3. package/docs/capability-manifest.schema.json +5 -1
  4. package/docs/design/2026-10-22-module-upgrade.md +192 -0
  5. package/docs/design/README.md +4 -0
  6. package/docs/desktop-cli-api.md +463 -13
  7. package/docs/desktop.md +363 -67
  8. package/docs/first-team.md +5 -3
  9. package/docs/implementation.md +46 -6
  10. package/docs/integrations.md +16 -4
  11. package/docs/knowledge.md +44 -27
  12. package/docs/layers.md +2 -2
  13. package/docs/official-catalog.md +5 -5
  14. package/docs/packages.md +14 -14
  15. package/docs/release-lane.md +16 -0
  16. package/docs/release-notes/v0.67.0.md +366 -0
  17. package/docs/release-notes/v0.67.1.md +64 -0
  18. package/docs/release-notes/v0.68.0.md +504 -0
  19. package/docs/servers.md +8 -2
  20. package/docs/souls-and-instances.md +58 -6
  21. package/docs/tui.md +1033 -237
  22. package/docs/upgrading.md +164 -26
  23. package/docs/workspaces.md +2 -2
  24. package/lib/capability-contract.mjs +8 -7
  25. package/lib/core.mjs +331 -75
  26. package/lib/instance-color.mjs +58 -0
  27. package/lib/instance-events.mjs +1 -1
  28. package/lib/instance-inspect.mjs +107 -23
  29. package/lib/instance-lifecycle.mjs +21 -1
  30. package/lib/instance-naming.mjs +187 -0
  31. package/lib/instance-resolution.mjs +10 -6
  32. package/lib/instance-upgrade.mjs +1445 -0
  33. package/lib/materialize.mjs +287 -89
  34. package/lib/servers.mjs +24 -11
  35. package/lib/soul-composition.mjs +7 -3
  36. package/lib/upgrade-state.mjs +101 -0
  37. package/lib/workspace.mjs +4 -1
  38. package/lib/worktree.mjs +103 -12
  39. package/package-catalog.json +5 -4
  40. package/package.json +1 -1
  41. package/packages/client/cli-adapter.mjs +52 -6
  42. package/packages/client/cli-locator.mjs +2 -2
  43. package/packages/client/composed-gate.mjs +10 -2
  44. package/packages/client/deployment-data.mjs +5 -0
  45. package/packages/client/deployment-identity.mjs +40 -0
  46. package/packages/client/deployment-panel.mjs +9 -3
  47. package/packages/client/inspect-boundary.mjs +11 -7
  48. package/packages/client/inspect-cache.mjs +2 -2
  49. package/packages/client/instance-name.mjs +28 -0
  50. package/packages/client/instance-presentation.mjs +11 -0
  51. package/packages/client/keymap.mjs +133 -28
  52. package/packages/client/keys-file.mjs +126 -0
  53. package/packages/client/own-codes.mjs +4 -2
  54. package/packages/client/panel-views.mjs +78 -12
  55. package/packages/client/spawn-naming.mjs +32 -0
  56. package/packages/client/spawn-preview-cli.mjs +58 -7
  57. package/packages/client/spawn-preview-contract.mjs +59 -0
  58. package/packages/client/spawn-preview-facts.mjs +8 -4
  59. package/packages/client/spawn-preview.mjs +81 -3
  60. package/packages/client/team-members.mjs +4 -1
  61. package/packages/client/workspace-step.mjs +25 -0
  62. package/packages/tui/README.md +7 -7
  63. package/packages/tui/lib/actions.mjs +92 -25
  64. package/packages/tui/lib/client.mjs +9 -4
  65. package/packages/tui/lib/config.mjs +50 -9
  66. package/packages/tui/lib/main.mjs +65 -24
  67. package/packages/tui/lib/model.mjs +292 -75
  68. package/packages/tui/lib/read.mjs +53 -1
  69. package/packages/tui/lib/store.mjs +469 -100
  70. package/packages/tui/lib/term/keys.mjs +22 -6
  71. package/packages/tui/lib/term/kitty.mjs +54 -11
  72. package/packages/tui/lib/term/screen.mjs +15 -6
  73. package/packages/tui/lib/term/through.mjs +66 -28
  74. package/packages/tui/lib/views/frame.mjs +223 -165
  75. package/packages/tui/lib/views/help.mjs +134 -29
  76. package/packages/tui/lib/views/instances.mjs +63 -22
  77. package/packages/tui/lib/views/palette.mjs +14 -4
  78. package/packages/tui/lib/views/souls.mjs +2 -2
  79. package/packages/tui/lib/views/switcher.mjs +6 -1
  80. package/packages/tui/lib/views/workspaces.mjs +55 -0
  81. package/skills/oats-getting-started/SKILL.md +96 -42
@@ -7,16 +7,16 @@
7
7
  // in. What it adds is the TUI's: the window, the clock times, and which fact stands on which line.
8
8
  import {
9
9
  TERMS, panelData, displayLine, DETAIL_WITHHELD, originLead, instanceId, instanceVisibleInTree, waitingRollup, collapseKey, filterInstanceTree,
10
- hasInstanceChildren, heldHome, instanceSiblings, siblingText, rosterSections, deploymentState, rowStale, primaryDeployment, isMultiDeployment, runtimeState, runtimeCounts,
10
+ hasInstanceChildren, heldHome, instanceSiblings, siblingText, rosterSections, deploymentState, rowStale, primaryDeployment, isMultiDeployment, runtimeState, runtimeCounts, instanceColor,
11
11
  waitingClaim, waitingLabel, waitedText, waitingClock, waitingBelowText, instanceActs, rowReason,
12
- identityMemory, viewModel, workspaceChoices, workspaceChoiceRows, choiceMatches, UNMATCHED_SECTION, shortPath,
12
+ identityMemory, viewModel, listedViews, workspaceChoices, workspaceChoiceRows, choiceMatches, UNMATCHED_SECTION, shortPath, machineLabels,
13
13
  openAct, deployments as heldDeployments, attachExit, preflightFailure, kernelLines,
14
14
  startGate, launchFlagIgnored, flagIgnoredNotice, retainedStartMessage, retiringRows, soulRows, soulFacts, spawnRefusal,
15
15
  defaultSpawnChoices, spawnProblem, outcomeWords, previewFacts, deploymentLabel, subsequenceScore, soulMatches, soulCatalogFailure, catalogFailure,
16
16
  memberNames, capabilitySource, groupCapabilities, hostKeyOf, capabilitySections, matchCapabilities, soulsComposition, rosterAgentName, layerLabel, capabilityUsers,
17
- capabilityFacts, CAPABILITY_COPY,
17
+ capabilityFacts, CAPABILITY_COPY, CHORD_FAMILY_LABELS, DEFAULT_CHORD_FAMILY, chordFamilyNote,
18
18
  } from "./client.mjs";
19
- import { LEADER, keyLabel } from "./actions.mjs";
19
+ import { LEADER, chordsRead, keyLabel } from "./actions.mjs";
20
20
  import { ownEllipsis, shownLines } from "./term/text.mjs";
21
21
  import { textWidth } from "./term/width.mjs";
22
22
  import { windowOf } from "./views/scroll.mjs";
@@ -44,6 +44,9 @@ export function heldOf(state, at) {
44
44
  remembered: identityMemory({ memory: state.memory, notes: state.notes }),
45
45
  rosterAnswered: state.remote.rosterAnswered, rosterFailure: state.remote.rosterFailure, cli: state.cli,
46
46
  observing: new Set(), remoteCollecting: state.collecting, home: state.home, at: state.rosterAt ?? at,
47
+ // What the identity reads learned of this computer's listed deployments (lib/main.mjs): a listed one is
48
+ // matched to its workspace in the switcher, and one opened from there is in its view before its first read.
49
+ learned: state.identities,
47
50
  };
48
51
  }
49
52
 
@@ -55,6 +58,27 @@ export function panelOf(state, at) {
55
58
  return state.open === null ? null : panelData(heldOf(state, at), state.open, TERMS);
56
59
  }
57
60
 
61
+ /** The workspace (the shared view's id: panel-views.mjs viewModel) that holds deployment `id` in `state`,
62
+ * or null: what the tabs belong to, so a change of `state.open` within one workspace (its deployment of
63
+ * this machine opened beside another machine's) is not taken for opening another. */
64
+ export function workspaceOf(state, id, at) {
65
+ if (id === null) return null;
66
+ return viewModel(heldOf(state, at), TERMS).views.find((v) => v.id === id || v.deployments.includes(id))?.id ?? null;
67
+ }
68
+ /** What a workspace's memory for the run is kept under (docs/tui.md, "Tabs"): the workspace that
69
+ * holds deployment `id` (workspaceOf), so another of its deployments finds the same memory; a
70
+ * deployment that reports no workspace, by its own id. Null for no deployment. */
71
+ export const memoryKey = (state, id, at) => (id === null ? null : workspaceOf(state, id, at) ?? id);
72
+ /** The palette's recency of the open workspace (`recent`, per memoryKey): its instances opened or
73
+ * shown in this run, the latest first. */
74
+ export const recentOf = (state, at) => state.recent.get(memoryKey(state, state.open, at)) ?? [];
75
+ /** The memoryKeys the views hold now (each view's id, and its deployments'), and the one each
76
+ * deployment whose read failed with nothing kept was in when it was last read (`unreadKeys`): it is
77
+ * in no view but its own until it is read again, so that view may only seem gone. */
78
+ export function memoryKeys(state, at) {
79
+ return new Set([...viewModel(heldOf(state, at), TERMS).views.flatMap((v) => [v.id, ...v.deployments]), ...state.unreadKeys.values()]);
80
+ }
81
+
58
82
  const text = (value) => typeof value === "string" && value !== "";
59
83
  const pad = (n) => String(n).padStart(2, "0");
60
84
  /** An ISO time as a local clock time, `14:03:27`, or null. */
@@ -104,6 +128,10 @@ function markOf(row) {
104
128
  return word === "stopped" && row.runtimeState === "shell" ? "shell" : word;
105
129
  }
106
130
 
131
+ /** An instance row's colour (feature instance-color) as one of the terminal's sixteen, through the souls'
132
+ * map (views/souls.mjs SOUL_COLOURS), or null: which colour a row shows is the shared rule (instanceColor). */
133
+ const rowColour = (row) => SOUL_COLOURS[instanceColor(row)] ?? null;
134
+
107
135
  /** The key prefix of each run of instances related to no other, as the shared grouping names it
108
136
  * (`independent:<id>`). Read by key, not by label: a cluster whose root is named `independent` has that
109
137
  * label too, and its key is `cluster:<n>:independent`. */
@@ -225,8 +253,8 @@ function build(state, at) {
225
253
  status,
226
254
  workspace: text(panel?.workspace?.name) ? panel.workspace.name : "",
227
255
  machines, here,
228
- // The one machine of a view that holds no deployment of this machine: nothing else names it,
229
- // since a view of one deployment has no heading.
256
+ // The one machine of a view that holds no deployment of this machine: a view of one deployment
257
+ // has no heading, so the detail names it (detailOf).
230
258
  machine: !here && away.length === 1 ? away[0] : null,
231
259
  // The counts in the order they are drawn. `shared`: the word is the shared home's.
232
260
  counts: [
@@ -305,12 +333,15 @@ export function disclosure(state, r, item) {
305
333
  /** One row of the list: its mark, its name, the word its mark cannot say (or null), whether it
306
334
  * waits, and on a folded row only, how many instances are folded away under it (`folded`) and how
307
335
  * many of those wait (`below`). A row that is not folded says nothing of its children: they
308
- * stand under it, indented. */
336
+ * stand under it, indented. `selected` the selected row, `cursor` whether it carries `>`. */
309
337
  function listRow(state, r, item) {
310
338
  const closed = disclosure(state, r, item) === "closed";
311
339
  return {
312
340
  id: item.id, name: item.row.instance, depth: item.depth, selected: item.id === state.selected,
313
- mark: markOf(item.row), word: wordOf(item.row, state.ascii),
341
+ // The selected row keeps its reverse video while the list of workspaces has the focus, but not the
342
+ // cursor: only the region with the focus draws `>`.
343
+ cursor: item.id === state.selected && state.focus !== "workspaces",
344
+ mark: markOf(item.row), color: rowColour(item.row), word: wordOf(item.row, state.ascii),
314
345
  waiting: waitingClaim(item.row, { stale: r.stale(item.row) }) !== null,
315
346
  folded: closed ? r.folded.get(item.id) ?? 0 : 0,
316
347
  below: closed ? r.below.get(item.id)?.length ?? 0 : 0,
@@ -357,6 +388,11 @@ const LEADER_CLOSE = LEADER.find((entry) => entry.does === "close-terminal").key
357
388
  export const TAB_WORDS = Object.freeze({
358
389
  full: (limit, leader) => [{ own: `${limit} terminals are open; close one with ` }, { own: `${leader} ${keyLabel(LEADER_CLOSE)}`, whole: true }, { own: "." }],
359
390
  });
391
+ /** The line of a leader whose key came in its own read (docs/tui.md, "The leader"): dropped, and
392
+ * why. */
393
+ export const LEADER_WORDS = Object.freeze({
394
+ merged: (leader) => [{ own: leader, whole: true }, { own: " and the next key came in one read, so nothing ran: press them one after the other." }],
395
+ });
360
396
  /** The lines of a split that is not made (docs/tui.md, "Splits"): a second split, and a panel too
361
397
  * small for two groups (`min` views/split.mjs SPLIT_MIN). */
362
398
  export const SPLIT_WORDS = Object.freeze({
@@ -458,10 +494,12 @@ function detailOf(state, r, item, now, acts) {
458
494
  const row = item.row, facts = [];
459
495
  const add = (label, value, form = "line") => { if (text(value)) facts.push({ label, value, form }); };
460
496
  add("soul", row.agent);
497
+ // Which machine the instance is on: in a view of two or more deployments, and in one whose only
498
+ // deployment is another machine's, where no heading and no row of the list of workspaces names it.
499
+ if (r.multi || r.machine !== null) add("machine", row.deployment?.machine);
461
500
  if (r.multi) {
462
- // Which machine the instance is on, and, when that deployment is not live, the whole
463
- // sentence that says why: a heading has room for the short reason only.
464
- add("machine", row.deployment?.machine);
501
+ // When that deployment is not live, the whole sentence that says why: a heading has room for
502
+ // the short reason only.
465
503
  const of = r.deployments.find((d) => d.id === row.deployment?.id);
466
504
  const said = of ? deploymentState(of) : null;
467
505
  if (said && said.key !== "live") add("", said.detail, "wrap");
@@ -516,6 +554,20 @@ export const LIST_WORDS = Object.freeze({
516
554
  leaving: "oats: a change to this computer's list of deployments is still running; `oats deployments` shows the list.",
517
555
  });
518
556
 
557
+ /** The lines of the list of workspaces (docs/tui.md, "The list of workspaces"): the leader's Up or
558
+ * Down at an end of it, and a row picked there that is not a deployment any more. */
559
+ export const WORKSPACE_WORDS = Object.freeze({
560
+ above: () => [{ own: "No workspace above this one." }],
561
+ below: () => [{ own: "No workspace below this one." }],
562
+ refused: (name) => [{ shown: name }, { own: ": not an OATS deployment any more." }],
563
+ });
564
+ /** The switcher's choices with no filter, in its order (workspaceList's rows are their keys). */
565
+ export const listChoices = (state, at = new Date(0).toISOString()) => switcherOf(state, at, "").made.items.filter((item) => item.key !== undefined);
566
+ /** The switcher's choice of key `key`, with no filter, or null. */
567
+ export const listChoice = (state, key, at) => listChoices(state, at).find((item) => item.key === key) ?? null;
568
+
569
+ /** The help's `keys` on macOS (views/help.mjs chordFamilyLines): no family, no file's note. */
570
+ const MAC_KEYS = Object.freeze({ family: null, label: null, note: null, mac: true });
519
571
  /** What the switcher says above its rows, as views/switcher.mjs leadRows reads it. */
520
572
  const leadOf = (state) => ({ said: state.switcher.line, failure: state.listed.failure?.message ?? null, removing: state.switcher.removing !== null });
521
573
  /** How many rows stand above the switcher's choices in an area `cols` wide (the switcher's is the
@@ -526,42 +578,156 @@ export function switcherLead(state, cols) {
526
578
  return leadRows(leadOf(state), Number.isInteger(cols) && cols > 0 ? cols : 80, { ascii: state.ascii }).length;
527
579
  }
528
580
 
529
- /** The switcher's rows for a state, top to bottom: the workspaces this run can show, as the
530
- * shared home lists and words them; then the ones matched to no workspace under the shared
531
- * heading; then the rows of this computer's deployments list that this run does not serve, in
532
- * the kernel's order, under the TUI's own. A served deployment's id and a row's path are both
533
- * canonical, so a deployment opened in this run is never offered again.
534
- * An item is `{ heading, shared }`, or a choice: `{ key, label, place, notLiveText, open,
535
- * primary }` for a view (`primary` is the deployment Enter opens) and `{ key, label, place,
536
- * path, state, refused }` for a row of the list (`state` the kernel's: views/switcher.mjs says a
537
- * stale one in words). `keys` are the choices in order; `selected` is the key the selection
538
- * stands on (the first choice when the state's own is not listed). */
539
- export function switcher(state, at = new Date(0).toISOString()) {
540
- const held = heldOf(state, at), views = viewModel(held, TERMS);
541
- const rows = workspaceChoiceRows(workspaceChoices(held, TERMS, views));
542
- const query = state.switcher.query;
543
- const openView = state.open === null ? null : views.views.find((v) => v.id === state.open || v.deployments.includes(state.open))?.id ?? null;
544
- const choice = (row) => ({
545
- key: `view\u0000${row.id}`, label: row.label, place: row.place, notLiveText: row.notLiveText, open: row.id === openView,
546
- primary: views.views.find((v) => v.id === row.id)?.primary ?? null,
547
- });
548
- const shown = rows.filter((row) => choiceMatches(row, query));
549
- const matched = shown.filter((row) => !row.unattached).map(choice), unmatched = shown.filter((row) => row.unattached).map(choice);
581
+ /** The word an indicator line says of a deployment of a workspace in the switcher, or null for a live
582
+ * one: "not opened" for a deployment of this computer's list that this run does not serve (the TUI's
583
+ * own), else the shared word for its state (roster-sections.mjs deploymentState: not observed, not
584
+ * reached, stale, remembered). */
585
+ export const NOT_OPENED = "not opened";
586
+ function indicatorState(info) {
587
+ if (info.listed) return NOT_OPENED;
588
+ const said = deploymentState(info);
589
+ return said.key === "live" ? null : said.text;
590
+ }
591
+
592
+ /** The switcher's rows for a state, top to bottom: the workspaces, each a choice followed by one
593
+ * indicator line per deployment of it; then the views matched to no workspace under the shared
594
+ * heading; then the rows of this computer's deployments list that this run does not serve and that
595
+ * no workspace took, in the kernel's order, under the TUI's own.
596
+ * A workspace is what the shared rule (panel-views.mjs listedViews, buildViews underneath) makes of
597
+ * the deployments this run serves, the machines' groups and the listed deployments whose identity a
598
+ * read learned (`state.identities`, lib/main.mjs): a listed deployment that reports the same
599
+ * workspace as another is in its row. A served deployment's id and a row's path are both canonical,
600
+ * so a deployment opened in this run is never offered again.
601
+ * An item is `{ heading, shared }`; `{ indicator }`, a line under a workspace (its deployment's
602
+ * machine label, with a path tail where the shared label adds one, then its state word when it is
603
+ * not live: indicatorState), never a choice; or a choice: `{ key, label, open, primary, join, opens }`
604
+ * for a workspace (`primary` the deployment Enter opens when every local one is served; `join` the
605
+ * listed deployments Enter opens first, and `opens` the deployments it may then open, in order),
606
+ * `{ key, label, place, notLiveText, open, primary }` for a view matched to no workspace, and
607
+ * `{ key, label, place, path, state, refused }` for a row of the list (`state` the kernel's:
608
+ * views/switcher.mjs says a stale one in words; `place` why no workspace took it, when a read said, then its path: the reason first, so a narrow row
609
+ * cuts the path and keeps it).
610
+ * `keys` are the choices in order; `selected` is the key the selection stands on (the first choice
611
+ * when the state's own is not listed). */
612
+ export const switcher = (state, at = new Date(0).toISOString()) => switcherOf(state, at, state.switcher.query).made;
613
+ /** The switcher's rows for `query` (`made`), and of each workspace's key whether some instance of it
614
+ * needs input (`waits`), which the list of workspaces says (workspaceList). */
615
+ function switcherOf(state, at, query) {
616
+ const held = heldOf(state, at);
550
617
  const unserved = state.listed.rows.filter((row) => !state.ctxs.includes(row.path));
551
- const offered = unserved
552
- .map(({ path, name, state: listedState }) => ({ key: `path\u0000${path}`, label: name, place: shortPath(path, { home: state.home }), path, state: listedState, refused: state.switcher.refused === path }))
618
+ // Only a row the kernel says is a deployment is matched: a stale one (missing, not one any more) says so instead.
619
+ const views = listedViews(held, unserved.filter((row) => row.state === "ok"), TERMS);
620
+ const choices = workspaceChoices(held, TERMS, views), rows = workspaceChoiceRows(choices);
621
+ // Whether some instance of a workspace needs input: what this run observes of it alone, the shared
622
+ // choice's `waiting` (its served deployments' reads; unknown or stale is not).
623
+ const waits = new Map(choices.map((choice) => [`view\u0000${choice.id}`, choice.waiting === true]));
624
+ const viewOf = (id) => views.views.find((v) => v.id === id);
625
+ const openView = state.open === null ? null : views.views.find((v) => v.id === state.open || v.deployments.includes(state.open))?.id ?? null;
626
+ const items = [];
627
+ for (const row of rows.filter((each) => !each.unattached)) {
628
+ // This machine's deployments first (the served, then the listed), then the other machines', each in the shared order.
629
+ const all = viewOf(row.id).deployments.map((id) => views.infos.get(id)).filter(Boolean);
630
+ const infos = [...all.filter((info) => info.local), ...all.filter((info) => !info.local)], view = viewOf(row.id);
631
+ const labels = machineLabels(infos, TERMS);
632
+ const lines = infos.map((info) => [labels.get(info.id), indicatorState(info)].filter(Boolean).join(" · "));
633
+ if (!choiceMatches({ label: row.label, place: lines.join(" ") }, query)) continue;
634
+ const join = infos.filter((info) => info.listed).map((info) => info.id);
635
+ items.push({ key: `view\u0000${row.id}`, label: row.label, open: row.id === openView, primary: view.primary, join,
636
+ opens: infos.map((info) => info.id) });
637
+ for (const line of lines) items.push({ indicator: line });
638
+ }
639
+ const unmatched = rows.filter((row) => row.unattached && choiceMatches(row, query)).map((row) => ({
640
+ key: `view\u0000${row.id}`, label: row.label, place: row.place, notLiveText: row.notLiveText, open: row.id === openView, primary: viewOf(row.id)?.primary ?? null,
641
+ }));
642
+ const why = new Map(views.unmatched.map((info) => [info.id, info.short]));
643
+ const taken = new Set([...views.infos.keys()]);
644
+ const offered = unserved.filter((row) => !taken.has(row.path))
645
+ .map(({ path, name, state: listedState }) => ({
646
+ key: `path\u0000${path}`, label: name, place: [why.get(path), shortPath(path, { home: state.home })].filter(Boolean).join(" · "), path, state: listedState, refused: state.switcher.refused === path,
647
+ }))
553
648
  .filter((item) => choiceMatches(item, query));
554
- const items = [
555
- ...matched,
649
+ items.push(
556
650
  ...(unmatched.length ? [{ heading: UNMATCHED_SECTION, shared: true }, ...unmatched] : []),
557
651
  ...(offered.length ? [{ heading: OFFERED_SECTION, shared: false }, ...offered] : []),
558
- ];
652
+ );
559
653
  const keys = items.filter((item) => item.key !== undefined).map((item) => item.key);
560
- const total = rows.length + unserved.length;
561
- return {
654
+ const total = rows.length + unserved.filter((row) => !taken.has(row.path)).length;
655
+ const made = {
562
656
  items, keys, selected: keys.includes(state.switcher.selected) ? state.switcher.selected : keys[0] ?? null,
563
657
  empty: keys.length ? null : total ? "nomatch" : "none",
564
658
  };
659
+ return { made, waits };
660
+ }
661
+ /** THE LIST OF WORKSPACES (docs/tui.md, "The list of workspaces"): one row per workspace the switcher
662
+ * offers, by its name, whatever machines it is on, in the switcher's order, at the top of the
663
+ * sidebar. A workspace only this machine's deployments not opened make is not one of them, nor a
664
+ * view with nothing to open, nor a row of this computer's list: the switcher keeps those (`w` `w`).
665
+ * `lines`: a row `{ key, label, current, waiting }`: `current` the open workspace's row; `waiting`
666
+ * whether some instance of it needs input, as far as this run observes it (an unknown never says
667
+ * so). `rows`: the rows as `{ key, openable }`, for workspaceStep (every row opens). `current`: the
668
+ * open row's key, or null. Kept while what it is made from (LIST_MADE_FROM) is the same: every
669
+ * frame and every key asks for it, and the shared home walks every machine to make it, so it is
670
+ * not asked again for a key or a paint that changed none of that (as `roster` is kept). */
671
+ const LIST_MADE_FROM = ["entries", "remote", "memory", "notes", "rosterAt", "collecting", "ctxs", "open", "cli", "home", "identities", "listed"];
672
+ let listKept = null;
673
+ export function workspaceList(state, at) {
674
+ if (listKept !== null && LIST_MADE_FROM.every((name) => listKept.state[name] === state[name])) return listKept.list;
675
+ const lines = [], { made, waits } = switcherOf(state, at, "");
676
+ for (const item of made.items) {
677
+ if (item.key === undefined || item.path !== undefined) continue;
678
+ const notOpened = item.join?.length > 0 && item.join.length === item.opens.length;
679
+ const opens = item.join?.length > 0 || item.primary !== null;
680
+ if (notOpened || !opens) continue;
681
+ lines.push(Object.freeze({ key: item.key, label: item.label, current: item.open === true, waiting: waits.get(item.key) === true }));
682
+ }
683
+ const list = Object.freeze({ lines: Object.freeze(lines), rows: Object.freeze(lines.map(({ key }) => Object.freeze({ key, openable: true }))), current: lines.find((line) => line.current)?.key ?? null });
684
+ listKept = { state, list };
685
+ return list;
686
+ }
687
+ /** The most lines the list stands on; more are windowed, and the last line says how many are not
688
+ * shown (`+N`), with the dot when an instance of one of them needs input. */
689
+ export const LIST_LINES = 5;
690
+ /** How many rows stand at the top of the sidebar (views/frame.mjs layout's `list`): the list's,
691
+ * LIST_LINES at most, while a workspace is open and the switcher is not shown; else the title's
692
+ * one. */
693
+ export function listRowsOf(state, at) {
694
+ const under = state.view === "help" || state.view === "act" ? state.back : state.view;
695
+ const list = listModel(state, under, at);
696
+ return list === null ? 1 : list.lines.length + (list.more > 0 ? 1 : 0);
697
+ }
698
+ /** The list as the sidebar draws it (views/workspaces.mjs): its lines windowed around the cursor
699
+ * while the list has the focus, else around the open workspace's row; `more` how many are not
700
+ * shown, and `moreWaiting` whether one of those is waiting; `focused`; `cursor` the cursor's row
701
+ * key, null without the focus. Null while nothing is listed (no workspace open, or the switcher
702
+ * shown): the title stands there. */
703
+ function listModel(state, under, at) {
704
+ if (under === "switcher" || state.open === null) return null;
705
+ const list = workspaceList(state, at);
706
+ if (!list.lines.length) return null;
707
+ const focused = state.view === "instances" && state.focus === "workspaces";
708
+ const cursor = focused ? (list.rows.some((row) => row.key === state.workspaceCursor) ? state.workspaceCursor : list.current) : null;
709
+ return { ...listWindow(list.lines, cursor ?? list.current), focused, cursor };
710
+ }
711
+ /** The lines the list draws, windowed around `keep` (the focused row, else the open one): all of
712
+ * them when they fit, else LIST_LINES - 1 of them, and `more`, how many are not shown, and
713
+ * `moreWaiting`, whether one of those is `waiting`. */
714
+ export function listWindow(lines, keep) {
715
+ if (lines.length <= LIST_LINES) return { lines, more: 0, moreWaiting: false };
716
+ const height = LIST_LINES - 1, at = Math.max(0, lines.findIndex((line) => line.key === keep));
717
+ const top = Math.min(Math.max(0, at - Math.floor(height / 2)), lines.length - height);
718
+ const shown = lines.slice(top, top + height);
719
+ const moreWaiting = lines.some((line, i) => (i < top || i >= top + height) && line.waiting);
720
+ return { lines: shown, more: lines.length - shown.length, moreWaiting };
721
+ }
722
+ /** The window of the switcher's `items` in a pane `height` rows tall, from `top`, that holds the choice
723
+ * `key` and, while they fit, the indicator lines under it (scroll.mjs windowOf, asked to keep the last
724
+ * of them and then the choice). No key (-1 kept): the window as `top` gives it. */
725
+ export function switcherWindow(items, key, { top, height }) {
726
+ const at = key === null ? -1 : items.findIndex((item) => item.key === key);
727
+ let last = at;
728
+ while (last >= 0 && items[last + 1]?.indicator !== undefined) last++;
729
+ const after = windowOf({ top, count: items.length, height, keep: last });
730
+ return windowOf({ top: after.top, count: items.length, height, keep: at });
565
731
  }
566
732
 
567
733
  /** The palette's views and commands, each a row's label and the action it runs. */
@@ -574,51 +740,75 @@ const PALETTE_SPLIT = Object.freeze({
574
740
  });
575
741
  const PALETTE_ACTS = Object.freeze({ stop: "Stop", restart: "Restart", retire: "Retire", start: "Start" });
576
742
 
743
+ /** Which way each of the palette's own keys (its `does`, lib/actions.mjs paletteKeys) moves the
744
+ * selection among the palette's runs: to the next, or to the one before. */
745
+ const PALETTE_STEPS = Object.freeze({ "palette-next-group": 1, "palette-previous-group": -1 });
746
+
577
747
  /** THE PALETTE'S ROWS (docs/tui.md, "The palette"), in this order: the instances that can be
578
- * opened (the most recently opened in this run first, then the shared order), the souls of the
579
- * open workspace once its catalog was read, its capabilities once theirs was, the views, the acts
580
- * the palette's instance offers (the open terminal's, when the palette came from its focus; else
581
- * the selected one) and, once the catalog lists its soul, another of that soul, then spawning an
582
- * agent, workspaces, refresh and help, and the split's that apply. With a query, each group keeps the rows the
583
- * Desktop's subsequence score matches, the best first (a prefix first); a tie keeps that order.
584
- * A row: `{ key, kind, label, does?, id?, name?, machine?, mark?, sibling?, capability?, source? }`; `selected` is the key the
585
- * selection stands on (the first row when the palette's own is not listed). */
748
+ * opened, grouped and ordered as the sidebar's tree but by recency (the shared rosterSections
749
+ * with `lastFocus`, the Desktop's palette's: the group, the cluster, the root and the child opened
750
+ * most recently in this run first, then the shared order; one section per deployment where the
751
+ * view has several, as the sidebar's), each group led by a row of its label (`kind: "group"`: its
752
+ * name, the deployment's before it where there are several, never selected), then the souls of
753
+ * the open workspace once its catalog was read, its capabilities once theirs was, the views, the
754
+ * acts the palette's instance offers (the open terminal's, when the palette came from its focus;
755
+ * else the selected one) and, once the catalog lists its soul, another of that soul, then
756
+ * spawning an agent, workspaces, refresh and help, and the split's that apply. With a query, an
757
+ * instance group keeps the rows the Desktop's subsequence score matches, in its own order, and a
758
+ * group with none has no label row; each kind after them keeps its matches the best first (a
759
+ * prefix first), a tie in that order. A row: `{ key, kind, label, does?, id?, name?, machine?, mark?, sibling?, capability?, source? }`.
760
+ * `runs`: the keys of the rows that can be selected, run by run (each instance group, then each
761
+ * kind), which the palette's own keys move between (paletteStep). `selected` is the key the
762
+ * selection stands on (the first row that can be selected when the palette's own is not listed). */
586
763
  export function paletteItems(state, at = new Date(0).toISOString()) {
587
764
  const p = state.palette;
588
- if (p === null) return { items: [], selected: null };
589
- const groups = [];
765
+ if (p === null) return { items: [], runs: [], selected: null };
766
+ const query = p.query.trim();
767
+ // An instance group keeps its order under a query; a kind is ranked by the score.
768
+ const matched = (item) => query === "" || subsequenceScore(item.text, query) !== null;
769
+ const ranked = (group) => (query === "" ? group
770
+ : group.map((item, i) => ({ item, i, score: subsequenceScore(item.text, query) })).filter((each) => each.score !== null).sort((a, b) => a.score - b.score || a.i - b.i).map(({ item }) => item));
771
+ const runs = [];
590
772
  if (state.open !== null) {
591
773
  const r = roster(state, at);
592
- const recent = new Map(state.recent.map((id, i) => [id, i]));
593
- const rank = (row) => recent.get(instanceId(row)) ?? Infinity;
594
- const openable = r.ordered.filter((row) => openDecision(state, row, instanceActs(row)).open);
595
- groups.push(openable.map((row, i) => ({ row, i })).sort((a, b) => rank(a.row) - rank(b.row) || a.i - b.i).map(({ row }) => {
774
+ const openable = r.instances.filter((row) => openDecision(state, row, instanceActs(row)).open);
775
+ // The record of focus the shared order reads: larger is more recent, `recent` is the latest first.
776
+ const recent = recentOf(state, at), lastFocus = new Map(recent.map((id, i) => [id, recent.length - i]));
777
+ const item = (row) => {
596
778
  const machine = elsewhere(row) ? row.deployment?.machine ?? row.server : null;
597
779
  // `sibling`: the shared words for its siblings, or null; never part of what a query matches.
598
780
  return {
599
781
  key: `instance\u0000${instanceId(row)}`, kind: "instance", label: row.instance, id: instanceId(row), name: row.instance, machine, mark: markOf(row),
600
782
  sibling: siblingText(r.siblings.get(instanceId(row))), text: `${row.instance} ${machine ?? ""}`,
601
783
  };
602
- }));
784
+ };
785
+ for (const section of rosterSections(r.instances, openable, r.deployments, TERMS, { lastFocus })) for (const group of section.groups) {
786
+ const rows = group.clusters.flatMap((cluster) => cluster.instances).map(item).filter(matched);
787
+ if (!rows.length) continue;
788
+ // A group is named, and kept apart, by its deployment where there are several (the Desktop's palette.mjs).
789
+ const key = section.deployment ? `${section.deployment.id}|${group.key}` : group.key;
790
+ runs.push([{ key: `group\u0000${key}`, kind: "group", label: section.deployment ? `${section.label} · ${group.label}` : group.label }, ...rows]);
791
+ }
603
792
  }
793
+ const kinds = [];
604
794
  // The souls of the open workspace, once its catalog was read (the Souls view opened): choosing
605
795
  // one shows the Souls view with it selected. A palette never reads the catalog.
606
- groups.push(soulsOf(state).all.map((row) => ({ key: `soul\u0000${row.name}`, kind: "soul", label: row.name, name: row.name, text: row.name })));
796
+ kinds.push(soulsOf(state).all.map((row) => ({ key: `soul\u0000${row.name}`, kind: "soul", label: row.name, name: row.name, text: row.name })));
607
797
  // The capabilities of the open workspace, once its catalog was read (the Capabilities view opened):
608
798
  // choosing one shows that view with it selected. Each says where it comes from (a package's and a
609
799
  // member's may share a name).
610
800
  const c = capabilitiesOf(state), names = memberNames(c.status);
611
- groups.push(c.all.map((row) => {
801
+ kinds.push(c.all.map((row) => {
612
802
  const capability = capabilityKey(row, names);
613
803
  return { key: `capability\u0000${capability}`, kind: "capability", label: row.name, name: row.name, capability, source: capabilitySource(row, names).label, text: row.name };
614
804
  }));
615
- groups.push(PALETTE_VIEWS.map(([does, label]) => ({ key: `view\u0000${does}`, kind: "view", label, does, text: label })));
805
+ kinds.push(PALETTE_VIEWS.map(([does, label]) => ({ key: `view\u0000${does}`, kind: "view", label, does, text: label })));
616
806
  const id = p.from === "terminal" && state.terminal !== null ? state.terminal.id : state.selected;
617
807
  const row = id === null || state.open === null ? null : roster(state, at).instances.find((each) => instanceId(each) === id) ?? null;
618
808
  if (row !== null && state.opening === null) {
619
809
  const acts = instanceActs(row);
620
810
  const another = !elsewhere(row) && state.ctxs.includes(state.open) ? soulOfAgent(state, state.open, row.agent) : null;
621
- groups.push([
811
+ kinds.push([
622
812
  ...ACT_VERBS.filter((verb) => actDecision(state, row, acts, verb).open)
623
813
  .map((verb) => ({ key: `act\u0000${verb}`, kind: "act", label: PALETTE_ACTS[verb], does: verb, id: instanceId(row), name: row.instance, text: `${PALETTE_ACTS[verb]} ${row.instance}` })),
624
814
  // Another of its soul (N), once the catalog lists that soul: the row names the soul.
@@ -630,16 +820,28 @@ export function paletteItems(state, at = new Date(0).toISOString()) {
630
820
  // empty. A split there is no room for says so when it is run.
631
821
  const splitting = state.tabs.length > 0 && state.opening === null && !state.tabs.some((tab) => tab.status === "starting");
632
822
  const SPLIT = splitting ? (state.split === null ? PALETTE_SPLIT.one : state.terminal !== null ? PALETTE_SPLIT.shown : PALETTE_SPLIT.empty) : [];
633
- groups.push([...PALETTE_COMMANDS, ...SPLIT].map(([does, label]) => ({ key: `command\u0000${does}`, kind: "command", label, does, text: label })));
634
- const query = p.query.trim();
635
- const items = groups.flatMap((group) => (query === ""
636
- ? group
637
- : group.map((item, i) => ({ item, i, score: subsequenceScore(item.text, query) })).filter((each) => each.score !== null).sort((a, b) => a.score - b.score || a.i - b.i).map(({ item }) => item)));
638
- // With nothing chosen yet, the first row; but in the palette as it opens (no query), when the
639
- // first row is the shown tab's instance (the most recent), the second instance: the palette and
640
- // Enter go back to the terminal before it, as the Desktop's recent group does.
641
- const first = p.query === "" && items[0]?.kind === "instance" && items[0].id === state.terminal?.id && items[1]?.kind === "instance" ? items[1] : items[0];
642
- return { items, selected: items.some((item) => item.key === p.selected) ? p.selected : first?.key ?? null };
823
+ kinds.push([...PALETTE_COMMANDS, ...SPLIT].map(([does, label]) => ({ key: `command\u0000${does}`, kind: "command", label, does, text: label })));
824
+ for (const kind of kinds) { const rows = ranked(kind); if (rows.length) runs.push(rows); }
825
+ const items = runs.flat(), selectable = items.filter((each) => each.kind !== "group"), instances = selectable.filter((each) => each.kind === "instance");
826
+ // With nothing chosen yet, the first row that can be selected; but in the palette as it opens (no
827
+ // query), when that is the shown tab's instance (the most recent), the instance shown before it
828
+ // (the second of this workspace's recency, wherever its group puts it), else the second instance:
829
+ // the palette and Enter go back to the terminal before it, as the Desktop's recent group did.
830
+ const before = instances.find((each) => each.id === recentOf(state, at)[1]) ?? instances[1];
831
+ const first = p.query === "" && instances.length > 1 && selectable[0] === instances[0] && instances[0].id === state.terminal?.id ? before : selectable[0];
832
+ return {
833
+ items, runs: runs.map((run) => run.filter((each) => each.kind !== "group").map((each) => each.key)),
834
+ selected: selectable.some((each) => each.key === p.selected) ? p.selected : first?.key ?? null,
835
+ };
836
+ }
837
+ /** Where the palette's own key `does` (lib/actions.mjs paletteKeys) takes the selection of `list`
838
+ * (paletteItems): the first row of the next run, or of the one before, wrapping past either end;
839
+ * with one run, its first row. Null with no row, or for a `does` that is not the palette's. */
840
+ export function paletteStep(list, does) {
841
+ const step = PALETTE_STEPS[does], n = list.runs.length;
842
+ if (step === undefined || n === 0) return null;
843
+ const at = list.runs.findIndex((run) => run.includes(list.selected));
844
+ return list.runs[(((at < 0 ? 0 : at + step) % n) + n) % n][0];
643
845
  }
644
846
  /** The palette as the view draws it, in a body `page` rows tall: its query on the first row, and
645
847
  * under it the window of its rows that holds the selection (whose last row says what is cut off,
@@ -678,8 +880,22 @@ export function model(state, { page, body = page, now, at, cols, area = cols })
678
880
  workspace: r.workspace, machines: r.machines, here: r.here, machine: r.machine, counts: r.counts, readAt: r.readAt, notice: r.notice, note: r.note, empty: r.empty, observed: r.observed,
679
881
  detailTop: state.detailTop, helpTop: state.helpTop, open: state.open !== null,
680
882
  detachKey: state.detachKey, opening: state.opening, openable: false,
681
- // The chords, `[key id, does]`, while the terminal confirms the kitty keyboard protocol; else null.
682
- chords: state.keyboard === null ? null : [...state.chords],
883
+ // The chords read now, `[key id, does]` (actions.mjs chordsRead), whether the terminal confirms
884
+ // the kitty keyboard protocol, and whether every chord bound is read now (under the protocol, or
885
+ // the Alt family, whose keys all come without it): then the help and a terminal's cheat sheet
886
+ // lead with them.
887
+ chords: [...chordsRead(state.chords, state.keyboard !== null)], kitty: state.keyboard !== null,
888
+ chordsLead: state.chords.size > 0 && chordsRead(state.chords, state.keyboard !== null).size === state.chords.size,
889
+ // Whether a chord shows the Nth tab (tab-1 to tab-9): the tabs carry their numbers only then
890
+ // (views/frame.mjs stripRow). On macOS none does: ⌥⌘N never reaches a terminal.
891
+ tabNumbers: [...state.chords.values()].some((does) => /^tab-[1-9]$/.test(does)),
892
+ // The family the chords are bound in (keys.json, lib/config.mjs loadKeys), its name, and the line that says
893
+ // why the file was not taken, or null (the shared chordFamilyNote): the help's chords section names both.
894
+ // macOS has no family (`mac`): its chords are the arrows, whatever keys.json says.
895
+ keys: state.mac === true ? MAC_KEYS : state.keysRead ? Object.freeze({ family: state.keysRead.family, label: CHORD_FAMILY_LABELS[state.keysRead.family] ?? CHORD_FAMILY_LABELS[DEFAULT_CHORD_FAMILY], note: chordFamilyNote(state.keysRead) }) : null,
896
+ // The palette's own keys, `[key id, does]` (actions.mjs paletteKeys; none on macOS): its cheat
897
+ // sheet and the help name them.
898
+ paletteKeys: [...state.paletteKeys],
683
899
  terminal: state.terminal, onTerminal: false,
684
900
  // The panel's groups (views/frame.mjs), the split and the focused group; the panel stands while
685
901
  // any tab is open. `tabs` is the focused group's strip: each tab in order, the shown one marked,
@@ -687,20 +903,21 @@ export function model(state, { page, body = page, now, at, cols, area = cols })
687
903
  split: state.split, group: state.group, panelOpen: state.tabs.length > 0, groups: groupsOf(state),
688
904
  tabs: groupsOf(state)[state.group].tabs,
689
905
  act: state.view === "act" && state.act ? actView(state) : null,
690
- // The leader waits for its key (the cheat sheet is its hint), and the palette, while it is open.
691
- leader: state.leader?.waiting === true, palette: state.palette === null ? null : paletteView(state, body, at),
906
+ // The palette, while it is open.
907
+ palette: state.palette === null ? null : paletteView(state, body, at),
692
908
  souls: under === "souls" ? soulsView(state, page, at) : null,
693
909
  capabilities: under === "capabilities" ? capabilitiesView(state, page, at) : null,
694
910
  spawn: state.spawn === null ? null : spawnView(state, body, at),
695
911
  // The line under the sidebar's title: the last outcome, else a spawn under way (outcomeOf).
696
912
  outcome: outcomeOf(state),
913
+ // The list of workspaces at the top of the sidebar, and whether colour may say the dot.
914
+ workspaces: listModel(state, under, at), colour: state.colour !== false,
697
915
  };
698
916
  if (under === "switcher") {
699
917
  const s = switcher(state, at);
700
- const at_ = s.selected === null ? -1 : s.items.findIndex((item) => item.key === s.selected);
701
918
  // The lines above the rows take the pane's rows, and so does the filter field while it is
702
919
  // typed or kept: the window is that much shorter, so no choice is hidden for them (switcherHeight).
703
- const win = windowOf({ top: state.switcher.top, count: s.items.length, height: switcherHeight(state, body, area), keep: state.switcher.loose ? -1 : at_ });
920
+ const win = switcherWindow(s.items, state.switcher.loose ? null : s.selected, { top: state.switcher.top, height: switcherHeight(state, body, area) });
704
921
  return {
705
922
  ...common, under, list: [], above: 0, below: 0, wordWidth: 0, detail: null,
706
923
  // Nothing of a workspace stands in the sidebar while the switcher is shown.
@@ -983,7 +1200,7 @@ function soulDetail(state, at, row) {
983
1200
  name: row.name, description: row.description ?? "", from: soulFrom(row), works: facts.work, refusal: facts.refusalLine,
984
1201
  harness: { rows: facts.rows, notes: facts.notes, problem: facts.problem },
985
1202
  teams, capabilities,
986
- instances: { shown: here.slice(0, INSTANCES_NAMED).map((each) => ({ name: each.instance, mark: markOf(each) })), more: Math.max(0, here.length - INSTANCES_NAMED) },
1203
+ instances: { shown: here.slice(0, INSTANCES_NAMED).map((each) => ({ name: each.instance, mark: markOf(each), color: rowColour(each) })), more: Math.max(0, here.length - INSTANCES_NAMED) },
987
1204
  };
988
1205
  }
989
1206
 
@@ -15,7 +15,7 @@ import { closeSync, fstatSync, lstatSync, mkdtempSync, openSync, readSync, realp
15
15
  import { tmpdir } from "node:os";
16
16
  import { dirname, join } from "node:path";
17
17
  import { fileURLToPath } from "node:url";
18
- import { COLLECTOR, INSTANCE_VARIABLES, MAX_DEPLOYMENT_OBSERVATIONS, acceptProbe, cliDeploymentRead, cliReadsRemotes, cliRecord, cliRemoteRoster, createDeploymentObserver, createRefreshLoop, failedEntry, livenessAnswers, livenessInput, mapBounded, observeIdentities, observedEntry, panelInstances, parseProbeStdout, remoteRosterState, rosterRows, validateWorkspace } from "./client.mjs";
18
+ import { COLLECTOR, INSTANCE_VARIABLES, MAX_DEPLOYMENT_OBSERVATIONS, acceptProbe, cliDeploymentIdentity, cliDeploymentRead, cliReadsRemotes, cliRecord, cliRemoteRoster, createDeploymentObserver, createRefreshLoop, failedEntry, identityReadable, identityTimedOut, livenessAnswers, livenessInput, mapBounded, observeIdentities, observedEntry, panelInstances, parseProbeStdout, remoteRosterState, rosterRows, validateWorkspace } from "./client.mjs";
19
19
 
20
20
  /** A path made canonical: what the shared start rule checks a local home with (session-start.mjs
21
21
  * verifiedLocalHome). Throws for a path that cannot be resolved; the rule answers that as no home. */
@@ -613,3 +613,55 @@ export function createReader({ cli, getServed, getEntry, getRoster, onEntry, onR
613
613
  children() { return [...remembered.keys()].map((child) => child.pid).filter((pid) => Number.isInteger(pid)); },
614
614
  };
615
615
  }
616
+
617
+ /** The most time the identity reads of one run take together, in ms: two reads at their own limit
618
+ * (packages/client deployment-read-cli.mjs DEPLOYMENT_READ_TIMEOUT, 30 s each). */
619
+ export const IDENTITY_BUDGET_MS = 60_000;
620
+
621
+ /** THE IDENTITY READS (docs/tui.md, "The switcher"): what the switcher learns of the deployments of this
622
+ * computer's list that the run does not serve, so that one of them is matched to its workspace before it
623
+ * is opened (#482). -> { start(paths), stop() }
624
+ * `start(paths)` reads each path's identity through the shared cliDeploymentIdentity (`oats status --dir
625
+ * <path> --json`, the read an opened deployment gets, with its own time limit, `--max-age` as a background
626
+ * cycle's), ONE AT A TIME, in order, and calls `onRead({ path, read })` with each answer as it comes:
627
+ * nothing waits for them, and the screen is drawn before the first. They take IDENTITY_BUDGET_MS at most
628
+ * together: when it runs out the read in flight is ended, and it and every read not begun answer the
629
+ * shared timed-out failure (identityTimedOut). A new `start` ends the run before it, whose answers are
630
+ * then dropped, and so does `stop()`. With a kernel that reports no workspace identities
631
+ * (identityReadable), or no path, nothing is read.
632
+ * Nothing here runs on a timer: a run starts only when its caller says, and the caller says so at the
633
+ * start and when the switcher is opened or refreshed (lib/main.mjs), never from the refresh loop.
634
+ * `exec` is the reader's asked exec (createReader `exec`): every read is a child of kind "read" in a
635
+ * session of its own, ended on every way out, and ended through the run's signal here. */
636
+ export function createIdentityReads({ cli, exec, env, onRead, timers = globalThis, budgetMs = IDENTITY_BUDGET_MS, read = cliDeploymentIdentity }) {
637
+ let run = null;
638
+ function stop() {
639
+ if (run === null) return;
640
+ run.gone = true;
641
+ run.controller.abort();
642
+ run = null;
643
+ }
644
+ async function start(paths) {
645
+ stop();
646
+ // No exec of the reader's, nothing is read: the shared reader would start its own child otherwise.
647
+ if (typeof exec !== "function" || !identityReadable(cli) || !Array.isArray(paths) || !paths.length) return;
648
+ const mine = run = { controller: new AbortController(), gone: false, spent: false };
649
+ const timer = timers.setTimeout(() => { mine.spent = true; mine.controller.abort(); }, budgetMs);
650
+ timer?.unref?.();
651
+ const own = (bin, argv, options, callback) => exec(bin, argv, { ...options, signal: mine.controller.signal }, callback);
652
+ try {
653
+ for (const path of paths) {
654
+ if (mine.gone) return;
655
+ let answer = mine.spent ? identityTimedOut() : await read(cli, path, { maxAge: BACKGROUND_MAX_AGE }, { exec: own, env });
656
+ if (mine.gone) return;
657
+ // A read the budget ended answers whatever its ending made of it: it timed out.
658
+ if (mine.spent && !answer?.ok) answer = identityTimedOut();
659
+ onRead({ path, read: answer });
660
+ }
661
+ } finally {
662
+ timers.clearTimeout(timer);
663
+ if (run === mine) run = null;
664
+ }
665
+ }
666
+ return { start: (paths) => start(paths).catch(() => {}), stop };
667
+ }