@awebai/oats 0.68.0 → 0.69.1
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/bin/oats.mjs +102 -22
- package/docs/capabilities.md +49 -5
- package/docs/configuration.md +68 -2
- package/docs/desktop-cli-api.md +355 -12
- package/docs/desktop-instance-start.md +88 -3
- package/docs/desktop.md +147 -13
- package/docs/execution-targets.md +514 -62
- package/docs/harness-trust.md +3 -1
- package/docs/implementation.md +28 -11
- package/docs/integrations.md +1 -1
- package/docs/oats-local.schema.json +2 -2
- package/docs/official-catalog.md +4 -3
- package/docs/packages.md +7 -7
- package/docs/release-notes/v0.68.1.md +102 -0
- package/docs/release-notes/v0.69.0.md +658 -0
- package/docs/release-notes/v0.69.1.md +25 -0
- package/docs/servers.md +44 -5
- package/docs/souls-and-instances.md +11 -7
- package/docs/tui.md +114 -31
- package/docs/upgrading.md +14 -5
- package/docs/workspaces.md +1 -1
- package/lib/core.mjs +345 -89
- package/lib/file-pieces.mjs +49 -0
- package/lib/instance-events.mjs +25 -4
- package/lib/launch-prompt-fixtures/README.md +62 -0
- package/lib/launch-prompt-fixtures/resume-confirmation.json +32 -0
- package/lib/launch-prompt-fixtures.mjs +49 -0
- package/lib/launch-prompt-resume.mjs +55 -0
- package/lib/login-environment.mjs +27 -9
- package/lib/schedule.mjs +3 -3
- package/lib/servers.mjs +117 -23
- package/lib/session-end.mjs +82 -0
- package/lib/session-input.mjs +43 -9
- package/lib/session-resume-contract.mjs +32 -0
- package/lib/session-resume.mjs +310 -0
- package/lib/session-seen.mjs +163 -0
- package/lib/session-viewer.mjs +147 -44
- package/lib/soul-composition.mjs +2 -1
- package/lib/start-env.mjs +110 -0
- package/lib/tmux-server-scope.mjs +139 -14
- package/lib/workspace.mjs +38 -4
- package/package-catalog.json +10 -4
- package/package.json +1 -1
- package/packages/client/cli-adapter.mjs +9 -0
- package/packages/client/cli-locator.mjs +3 -2
- package/packages/client/deployment-data.mjs +7 -0
- package/packages/client/deployment-panel.mjs +3 -0
- package/packages/client/file-output-exec.mjs +98 -0
- package/packages/client/instance-display-name.mjs +18 -0
- package/packages/client/launch-prompt-outcome.mjs +25 -13
- package/packages/client/own-codes.mjs +2 -0
- package/packages/client/session-attach.mjs +35 -5
- package/packages/client/session-resume-cli.mjs +64 -0
- package/packages/client/session-resume-trigger.mjs +167 -0
- package/packages/client/session-resume.mjs +332 -0
- package/packages/client/tmux-status.mjs +30 -7
- package/packages/client/waiting-on-you.mjs +11 -4
- package/packages/client/workspace-step.mjs +17 -5
- package/packages/record/lib/last-conversation.mjs +123 -0
- package/packages/record/lib/session-roots.mjs +10 -1
- package/packages/tui/README.md +1 -1
- package/packages/tui/lib/client.mjs +2 -1
- package/packages/tui/lib/main.mjs +5 -3
- package/packages/tui/lib/model.mjs +57 -15
- package/packages/tui/lib/store.mjs +8 -7
- package/packages/tui/lib/term/text.mjs +12 -9
- package/packages/tui/lib/views/capabilities.mjs +6 -6
- package/packages/tui/lib/views/frame.mjs +72 -7
- package/packages/tui/lib/views/help.mjs +9 -4
- package/packages/tui/lib/views/instances.mjs +46 -29
- package/packages/tui/lib/views/souls.mjs +9 -8
- package/skills/oats-getting-started/SKILL.md +117 -4
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
/** When a client runs the machine sweep (`oats session resume --json`, session-resume-cli.mjs): once at its launch,
|
|
2
|
+
* then whenever a roster read shows a lost session of a local deployment. Shared by the Desktop (main) and the TUI;
|
|
3
|
+
* no DOM, no clock or IO of its own: the caller gives the probe, the run, the read and the time.
|
|
4
|
+
*
|
|
5
|
+
* Locality is the roster's, by deployment id: a row is this machine's only when its `deployment.id` is one of the
|
|
6
|
+
* read's local deployments (`localDeploymentIds`, from the panel's `deployments[].local`). A row of a remote
|
|
7
|
+
* deployment, or with no deployment tag, is never local: a client never acts on another host's loss.
|
|
8
|
+
*
|
|
9
|
+
* The rule. `launch()` arms the trigger and runs the launch sweep, with no floor. After it, `observed(rows,
|
|
10
|
+
* {localDeploymentIds})` (each accepted roster read's instance rows) starts a sweep when all hold: armed and not
|
|
11
|
+
* disposed; no sweep in flight (single flight); at least RESUME_MIN_INTERVAL_MS since the last sweep that ran
|
|
12
|
+
* STARTED (the floor counts from the moment its slot was taken, the launch sweep's and a busy one's too); and
|
|
13
|
+
* lostLocalHomes names a home that is not settled. Otherwise nothing: no queue, no timer; the next read asks again.
|
|
14
|
+
* Each would-be start takes the slot, then asks `cli()`: only a probe with the feature (session-resume-cli.mjs
|
|
15
|
+
* resumeSupported) runs. Without one nothing runs, nothing is read, the floor does not move and the slot is let go.
|
|
16
|
+
*
|
|
17
|
+
* Settled homes keep a home that cannot be resumed from starting a sweep on every read. A sweep `observed()` started
|
|
18
|
+
* keeps the lost homes it was started for (its snapshot); when it completes as a sweep (its reading is quiet or a
|
|
19
|
+
* notice of an answer that ran: session-resume.mjs sweepCompleted), every one of them is settled, whatever the answer said of it (left out
|
|
20
|
+
* because its deployment is not ready, or named busy or unknown), so a home that cannot be resumed costs at most
|
|
21
|
+
* one observed sweep. Then the answer's rows settle and release homes (session-resume.mjs sweepSettlement: a
|
|
22
|
+
* refusal, or a home skipped as not lost or not seen running recently, settles it; a session started or running
|
|
23
|
+
* releases it; anything else changes nothing; the launch sweep has no snapshot, so a busy or unknown home there
|
|
24
|
+
* stays news for one observed sweep). A later read also releases a local home it shows that lostLocalHomes does not
|
|
25
|
+
* name: no longer lost, or running.
|
|
26
|
+
*
|
|
27
|
+
* News, not repeats. The kernel reports a refusal again in every sweep: before `read`, the refusals an earlier
|
|
28
|
+
* sweep of this trigger reported are left out of a copy of the envelope (session-resume.mjs withoutReported; the
|
|
29
|
+
* run's own is never changed). Every other row is this sweep's event and kept. A home released (above) forgets the
|
|
30
|
+
* refusals reported for it, so a refusal after it recovered is news again. A host warning (the result's own
|
|
31
|
+
* `warnings`, about this computer) is left out the same way once a notice of this trigger showed it: once per run,
|
|
32
|
+
* never forgotten (it is no home's); one a quiet sweep carried was never shown, so it stays news. This module reads
|
|
33
|
+
* nothing of the answer itself: its shape is session-resume.mjs's alone.
|
|
34
|
+
*
|
|
35
|
+
* `onReading` gets the reading of every finished sweep, whatever its kind (the caller ignores what it does not
|
|
36
|
+
* show). A run that rejects reads as failed, E_CLI_FAILED; a `read` that throws, as failed, E_CLI_PROTOCOL.
|
|
37
|
+
*
|
|
38
|
+
* `dispose()` stops the trigger and never cancels a sweep: a sweep in flight runs on (a kernel change outlives
|
|
39
|
+
* its client), and its reading is dropped. Nothing here throws out of `launch` or `observed`. */
|
|
40
|
+
import { resumeSupported, runResumeSweep } from './session-resume-cli.mjs';
|
|
41
|
+
import { readResumeSweep, shownHostKeys, sweepCompleted, sweepSettlement, withoutReported } from './session-resume.mjs';
|
|
42
|
+
import { SESSION_ENDS } from './deployment-data.mjs';
|
|
43
|
+
|
|
44
|
+
export const RESUME_MIN_INTERVAL_MS = 30_000;
|
|
45
|
+
|
|
46
|
+
const record = v => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
47
|
+
const absolute = v => typeof v === 'string' && v.startsWith('/') && !v.includes('\0');
|
|
48
|
+
/** The local deployment ids as a set of strings: an iterable's string entries; anything else, none. */
|
|
49
|
+
const idSet = ids => new Set(typeof ids !== 'string' && typeof ids?.[Symbol.iterator] === 'function'
|
|
50
|
+
? [...ids].filter(id => typeof id === 'string') : []);
|
|
51
|
+
/** A row of a local deployment with a home to name: a record with an absolute `home`, its `deployment.id` in `local`. */
|
|
52
|
+
const localRow = (row, local) => record(row) && absolute(row.home) && record(row.deployment) && local.has(row.deployment.id);
|
|
53
|
+
const done = Promise.resolve();
|
|
54
|
+
|
|
55
|
+
/** The ids of a panel reply's local deployments (`/api/panel`: `deployments[]` entries with `local: true`,
|
|
56
|
+
* panel-views.mjs deploymentEntry), in order; anything else, none. What `observed` and lostLocalHomes take. */
|
|
57
|
+
export function localDeploymentIds(panel) {
|
|
58
|
+
const entries = record(panel) && Array.isArray(panel.deployments) ? panel.deployments : [];
|
|
59
|
+
return entries.filter(d => record(d) && d.local === true && typeof d.id === 'string').map(d => d.id);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** The homes of `rows` (instance rows as a roster read serves them; anything else: none) whose session was lost
|
|
63
|
+
* in a local deployment: a row whose `deployment.id` is in `localDeploymentIds` (an iterable of ids; missing or
|
|
64
|
+
* empty: no row is local), with an absolute `home`, `sessionEnd` SESSION_ENDS.lost and `running` not true. Each
|
|
65
|
+
* once, in the rows' order. The one place a client reads `sessionEnd`. */
|
|
66
|
+
export function lostLocalHomes(rows, localDeploymentIds) {
|
|
67
|
+
if (!Array.isArray(rows)) return [];
|
|
68
|
+
const local = idSet(localDeploymentIds), homes = new Set();
|
|
69
|
+
for (const row of rows) if (localRow(row, local) && row.sessionEnd === SESSION_ENDS.lost && row.running !== true) homes.add(row.home);
|
|
70
|
+
return [...homes];
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* @param {{cli: () => unknown, run?: (cli: unknown) => Promise<unknown>, read?: (envelope: unknown) => unknown,
|
|
75
|
+
* now?: () => number, onReading?: (reading: unknown) => void}} options
|
|
76
|
+
* `cli()`: the accepted probe, or null, or a promise of either, asked at each would-be start. `run(cli)`: the
|
|
77
|
+
* sweep's envelope (runResumeSweep). `read(envelope)`: its reading (readResumeSweep). `now()`: milliseconds.
|
|
78
|
+
* @returns {{launch: () => Promise<void>,
|
|
79
|
+
* observed: (rows: unknown, options?: {localDeploymentIds?: Iterable<string>}) => Promise<void>, dispose: () => void}}
|
|
80
|
+
* `launch()` arms and runs the launch sweep; a second call answers the first's promise. It settles once that
|
|
81
|
+
* sweep's onReading ran, or at once when nothing ran. `observed(rows, {localDeploymentIds})` releases, then
|
|
82
|
+
* applies the rule; it settles when the sweep it started was read, or at once. Neither rejects. `dispose()`:
|
|
83
|
+
* later calls do nothing.
|
|
84
|
+
*/
|
|
85
|
+
export function createResumeTrigger({ cli, run = runResumeSweep, read = readResumeSweep, now = Date.now, onReading }) {
|
|
86
|
+
let launched = null, disposed = false, flying = false, lastStart = null;
|
|
87
|
+
const settled = new Set(), reported = new Set(), reportedFor = new Map(); // reportedFor: home → its reported keys
|
|
88
|
+
const reportedHost = new Set(); // host warnings a notice showed
|
|
89
|
+
let releasedDuring = null; // homes a read released while the sweep in flight ran: newer than its answer
|
|
90
|
+
|
|
91
|
+
/** A home no longer settled, and the refusals reported for it forgotten. */
|
|
92
|
+
function release(home) {
|
|
93
|
+
releasedDuring?.add(home);
|
|
94
|
+
settled.delete(home);
|
|
95
|
+
for (const key of reportedFor.get(home) ?? []) reported.delete(key);
|
|
96
|
+
reportedFor.delete(home);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** The envelope `read` is given, without the refusals an earlier answer reported and the host warnings a
|
|
100
|
+
* notice showed (withoutReported), with this answer's host keys and settlement (sweepSettlement) for after
|
|
101
|
+
* the read. Its refusal keys are added at once. */
|
|
102
|
+
function digest(envelope) {
|
|
103
|
+
const news = { ...withoutReported(envelope, reported, reportedHost), settlement: sweepSettlement(envelope) };
|
|
104
|
+
for (const { home, key } of news.keys) {
|
|
105
|
+
reported.add(key);
|
|
106
|
+
if (!reportedFor.has(home)) reportedFor.set(home, new Set());
|
|
107
|
+
reportedFor.get(home).add(key);
|
|
108
|
+
}
|
|
109
|
+
return news;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** After the read: a completed sweep settles every home of its snapshot; then the answer's own rows settle and
|
|
113
|
+
* release (a home it resumed, started, left waiting or found running is released again). A home a read released
|
|
114
|
+
* while the sweep ran is settled by neither: that read is newer than the sweep's answer. */
|
|
115
|
+
function settle(envelope, reading, snapshot, { settlement: { settle: settles, release: released } }, newer) {
|
|
116
|
+
const settleIfNotNewer = home => { if (!newer.has(home)) settled.add(home); };
|
|
117
|
+
if (sweepCompleted(envelope, reading)) for (const home of snapshot) settleIfNotNewer(home);
|
|
118
|
+
for (const home of settles) settleIfNotNewer(home);
|
|
119
|
+
for (const home of released) release(home);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** `snapshot`: the lost homes not yet settled that started this sweep (none for the launch sweep). */
|
|
123
|
+
async function sweep(snapshot = []) {
|
|
124
|
+
flying = true;
|
|
125
|
+
const newer = releasedDuring = new Set();
|
|
126
|
+
const startedAt = now();
|
|
127
|
+
try {
|
|
128
|
+
// A sync answer is used at once (the run starts in this call); a promise is awaited, the slot held meanwhile.
|
|
129
|
+
let probe;
|
|
130
|
+
try { probe = cli(); if (typeof probe?.then === 'function') probe = await probe; } catch { probe = null; }
|
|
131
|
+
if (!resumeSupported(probe)) return;
|
|
132
|
+
lastStart = startedAt;
|
|
133
|
+
let reading;
|
|
134
|
+
try {
|
|
135
|
+
const envelope = await run(probe);
|
|
136
|
+
try {
|
|
137
|
+
const news = digest(envelope);
|
|
138
|
+
reading = read(news.envelope);
|
|
139
|
+
releasedDuring = null;
|
|
140
|
+
settle(envelope, reading, snapshot, news, newer);
|
|
141
|
+
for (const key of shownHostKeys(reading, news.hostKeys)) reportedHost.add(key);
|
|
142
|
+
} catch { reading = { kind: 'failed', code: 'E_CLI_PROTOCOL' }; }
|
|
143
|
+
} catch { reading = { kind: 'failed', code: 'E_CLI_FAILED' }; }
|
|
144
|
+
if (!disposed && typeof onReading === 'function') { try { onReading(reading); } catch { /* the caller's */ } }
|
|
145
|
+
} catch { /* never out of launch or observed */ } finally { flying = false; releasedDuring = null; }
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
return {
|
|
149
|
+
launch() {
|
|
150
|
+
if (launched) return launched;
|
|
151
|
+
if (disposed) return done;
|
|
152
|
+
launched = sweep();
|
|
153
|
+
return launched;
|
|
154
|
+
},
|
|
155
|
+
observed(rows, options) {
|
|
156
|
+
if (!launched || disposed) return done;
|
|
157
|
+
// A local home this read shows and lostLocalHomes does not name is no longer lost, or runs: released.
|
|
158
|
+
const local = idSet(record(options) ? options.localDeploymentIds : undefined), lostNow = new Set(lostLocalHomes(rows, local));
|
|
159
|
+
if (Array.isArray(rows)) for (const row of rows) if (localRow(row, local) && !lostNow.has(row.home)) release(row.home);
|
|
160
|
+
if (flying || lastStart !== null && now() - lastStart < RESUME_MIN_INTERVAL_MS) return done;
|
|
161
|
+
const snapshot = [...lostNow].filter(home => !settled.has(home));
|
|
162
|
+
if (!snapshot.length) return done;
|
|
163
|
+
return sweep(snapshot);
|
|
164
|
+
},
|
|
165
|
+
dispose() { disposed = true; },
|
|
166
|
+
};
|
|
167
|
+
}
|
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
/** The machine sweep's answer (`oats session resume --json`, feature `session-resume`), read into a summary of
|
|
2
|
+
* facts and put into the clients' words. session-resume-cli.mjs runs it; this module reads what came back.
|
|
3
|
+
* Shared by the Desktop and the TUI: pure, no IO, no DOM, never throws on data (only resumeNotice throws, on
|
|
4
|
+
* a caller's missing `label`). No sentence names a client's control, so no client terms are needed.
|
|
5
|
+
*
|
|
6
|
+
* The answer: `{schemaVersion: 1, plan, deployments: [{deployment, state, swept, reason?, …}], rows:
|
|
7
|
+
* [{deployment, instance, outcome, reason?, code?, message?, warnings?, …}], warnings?}`; the result's own
|
|
8
|
+
* `warnings` are about the host, not one home. The summary:
|
|
9
|
+
* { resumed: [{instance, deployment, warnings, omitted}],
|
|
10
|
+
* fresh: [{instance, deployment, reason, warnings, omitted}], reason: FRESH_REASONS or null
|
|
11
|
+
* waiting: [{instance, deployment, reason}], a `blocked` row; reason: WAITING_REASONS or null
|
|
12
|
+
* refused: [{instance, deployment, reason, code, message}], reason: REFUSED_REASONS or null
|
|
13
|
+
* unswept: [{deployment, reason}], not swept; reason: UNSWEPT_REASONS or null
|
|
14
|
+
* host: {warnings, omitted}, the result's warnings, bounded as a row's
|
|
15
|
+
* omitted, totals: {resumed, fresh, waiting, refused} }
|
|
16
|
+
* `refused` carries `reason` beside the four fields the spec lists: the words say when a refusal was this
|
|
17
|
+
* boot's, and when the home keeps losing its session. There is no opt-out: an older kernel's `opted-out`
|
|
18
|
+
* deployment is unswept with reason null. Nothing is read from the kernel's words: no sentence, warning or
|
|
19
|
+
* message is matched. Names, paths, warnings and messages are display lines (display-text.mjs): labels and
|
|
20
|
+
* quotes, never used to address anything. A refused `message` is kernel prose, shown only after `OATS says:`,
|
|
21
|
+
* never alone with its `code`.
|
|
22
|
+
*
|
|
23
|
+
* Tolerant per entry: a row or deployment that does not decode (not a record, a name or path that is not a
|
|
24
|
+
* string, empty or withheld, an unknown outcome) is dropped alone; an unknown reason under a known outcome is
|
|
25
|
+
* null and worded generically; a code not of the kernel's form is null. `already-running` and `skipped` rows
|
|
26
|
+
* are counted nowhere and shown nowhere. The answer around them is closed: one that is not the document (no
|
|
27
|
+
* schemaVersion 1, `plan` not a boolean, `deployments` or `rows` not an array, or either longer than
|
|
28
|
+
* RESUME_ANSWER_ENTRIES) is a protocol failure, never read in part. */
|
|
29
|
+
import { displayLine, cleanLine, DETAIL_WITHHELD } from './display-text.mjs';
|
|
30
|
+
import { boundedWarnings, boundedWarningsValid } from './launch-prompt-outcome.mjs';
|
|
31
|
+
|
|
32
|
+
/** At most this many rows (over resumed, fresh, waiting and refused, in the answer's order) and, apart, this
|
|
33
|
+
* many unswept deployment lines (in the answer's order) are kept. What is left out is counted in `omitted`;
|
|
34
|
+
* `totals` keeps the real counts of the rows, which the headline uses. */
|
|
35
|
+
export const RESUME_SUMMARY_ROWS = 100;
|
|
36
|
+
export const RESUME_SUMMARY_DEPLOYMENTS = 100;
|
|
37
|
+
/** The longest `rows` or `deployments` this reader reads: more is a protocol failure, not a summary. */
|
|
38
|
+
export const RESUME_ANSWER_ENTRIES = 100_000;
|
|
39
|
+
/** A row's `outcome`, by name: the one place a client spells them. */
|
|
40
|
+
export const RESUME_OUTCOMES = Object.freeze({ resumed: 'resumed', fresh: 'fresh', blocked: 'blocked', refused: 'refused',
|
|
41
|
+
alreadyRunning: 'already-running', skipped: 'skipped' });
|
|
42
|
+
/** A `skipped` row's reasons, by name. A skipped row is counted and shown nowhere, whatever its reason. */
|
|
43
|
+
export const SKIPPED_REASONS = Object.freeze({ notLost: 'not-lost', notSeenRecently: 'not-seen-recently', startBusy: 'start-busy',
|
|
44
|
+
unknown: 'unknown' });
|
|
45
|
+
/** The skipped reasons that settle a home (sweepSettlement): it is not lost, or the kernel did not recently see it
|
|
46
|
+
* running (its status still reads lost, and every sweep would skip it again). */
|
|
47
|
+
export const SETTLING_SKIPPED_REASONS = Object.freeze([SKIPPED_REASONS.notLost, SKIPPED_REASONS.notSeenRecently]);
|
|
48
|
+
export const FRESH_REASONS = Object.freeze(['no-conversation', 'no-receipts', 'resume-unproven']);
|
|
49
|
+
export const WAITING_REASONS = Object.freeze(['resume-confirmation', 'launch-prompt']);
|
|
50
|
+
export const REFUSED_REASONS = Object.freeze(['start-refused', 'refused-this-boot', 'keeps-getting-lost']);
|
|
51
|
+
export const UNSWEPT_REASONS = Object.freeze(['not-ok', 'unreadable']);
|
|
52
|
+
/** The ok:false codes that mean nothing ran: no compatible CLI, or one without the feature. */
|
|
53
|
+
const UNSUPPORTED = new Set(['E_CLI_UNAVAILABLE', 'E_RESUME_FEATURE']);
|
|
54
|
+
const CODE = /^E_[A-Z0-9_]{1,64}$/;
|
|
55
|
+
const KINDS = ['resumed', 'fresh', 'waiting', 'refused'];
|
|
56
|
+
const SUMMARY_KEYS = [...KINDS, 'unswept', 'host', 'omitted', 'totals'];
|
|
57
|
+
|
|
58
|
+
const record = v => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
59
|
+
const exactKeys = (v, keys) => record(v) && Object.keys(v).length === keys.length && keys.every(k => Object.hasOwn(v, k));
|
|
60
|
+
const known = (list, v) => list.includes(v) ? v : null;
|
|
61
|
+
const code = v => typeof v === 'string' && CODE.test(v) ? v : null;
|
|
62
|
+
/** A name or a path as a label: one display line, null when it is withheld or there is nothing to show. */
|
|
63
|
+
const label = v => { const line = displayLine(v); return line === DETAIL_WITHHELD ? null : line; };
|
|
64
|
+
const named = v => cleanLine(v) && v !== DETAIL_WITHHELD;
|
|
65
|
+
const count = v => Number.isSafeInteger(v) && v >= 0;
|
|
66
|
+
const sum = totals => KINDS.reduce((n, k) => n + totals[k], 0);
|
|
67
|
+
|
|
68
|
+
/** One counted row as its kind and fact, or null (dropped, or counted nowhere). */
|
|
69
|
+
function decodeRow(row) {
|
|
70
|
+
if (!record(row)) return null;
|
|
71
|
+
const instance = label(row.instance), deployment = label(row.deployment);
|
|
72
|
+
if (instance === null || deployment === null) return null;
|
|
73
|
+
switch (row.outcome) {
|
|
74
|
+
case RESUME_OUTCOMES.resumed: return ['resumed', { instance, deployment, ...boundedWarnings(row.warnings) }];
|
|
75
|
+
case RESUME_OUTCOMES.fresh: return ['fresh', { instance, deployment, reason: known(FRESH_REASONS, row.reason), ...boundedWarnings(row.warnings) }];
|
|
76
|
+
case RESUME_OUTCOMES.blocked: return ['waiting', { instance, deployment, reason: known(WAITING_REASONS, row.reason) }];
|
|
77
|
+
case RESUME_OUTCOMES.refused: return ['refused', { instance, deployment, reason: known(REFUSED_REASONS, row.reason), code: code(row.code), message: displayLine(row.message) }];
|
|
78
|
+
default: return null;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** One unswept deployment line, `{deployment, reason}`, or null (swept, or dropped). */
|
|
83
|
+
function decodeDeployment(d) {
|
|
84
|
+
if (!record(d)) return null;
|
|
85
|
+
const deployment = label(d.deployment);
|
|
86
|
+
if (deployment === null) return null;
|
|
87
|
+
return d.swept === true ? null : { deployment, reason: known(UNSWEPT_REASONS, d.reason) };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const empty = () => ({ resumed: [], fresh: [], waiting: [], refused: [], unswept: [], host: { warnings: [], omitted: 0 }, omitted: 0,
|
|
91
|
+
totals: { resumed: 0, fresh: 0, waiting: 0, refused: 0 } });
|
|
92
|
+
|
|
93
|
+
/** Whether `result` is the sweep's document: the one check the summary and the trigger's helpers share. */
|
|
94
|
+
const sweepDocument = result => record(result) && result.schemaVersion === 1 && typeof result.plan === 'boolean'
|
|
95
|
+
&& Array.isArray(result.deployments) && Array.isArray(result.rows)
|
|
96
|
+
&& result.deployments.length <= RESUME_ANSWER_ENTRIES && result.rows.length <= RESUME_ANSWER_ENTRIES;
|
|
97
|
+
|
|
98
|
+
/** The sweep's `result` as a summary, or null when it is not the document. A plan (`plan: true`) started
|
|
99
|
+
* nothing, so it is the empty summary: none of its rows, deployments or warnings is read. The result's own
|
|
100
|
+
* `warnings` (about the host) are kept as a row's are (boundedWarnings): a host warning alone is no row, so
|
|
101
|
+
* it never makes a notice. */
|
|
102
|
+
function summarize(result) {
|
|
103
|
+
if (!sweepDocument(result)) return null;
|
|
104
|
+
const s = empty();
|
|
105
|
+
if (result.plan) return s;
|
|
106
|
+
let rows = 0, lines = 0;
|
|
107
|
+
for (const row of result.rows) {
|
|
108
|
+
const decoded = decodeRow(row);
|
|
109
|
+
if (!decoded) continue;
|
|
110
|
+
const [kind, fact] = decoded;
|
|
111
|
+
s.totals[kind] += 1;
|
|
112
|
+
if (rows < RESUME_SUMMARY_ROWS) { s[kind].push(fact); rows += 1; } else s.omitted += 1;
|
|
113
|
+
}
|
|
114
|
+
for (const d of result.deployments) {
|
|
115
|
+
const decoded = decodeDeployment(d);
|
|
116
|
+
if (!decoded) continue;
|
|
117
|
+
if (lines < RESUME_SUMMARY_DEPLOYMENTS) { s.unswept.push(decoded); lines += 1; } else s.omitted += 1;
|
|
118
|
+
}
|
|
119
|
+
s.host = boundedWarnings(result.warnings);
|
|
120
|
+
return s;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* @param {unknown} envelope what runResumeSweep resolved: the kernel's envelope or a client read error
|
|
125
|
+
* @returns {{kind: 'unsupported'} | {kind: 'busy'} | {kind: 'failed', code: string}
|
|
126
|
+
* | {kind: 'quiet', summary} | {kind: 'notice', summary}}
|
|
127
|
+
* `unsupported`: nothing ran (no compatible CLI, or no feature). `busy`: another sweep holds the machine's
|
|
128
|
+
* lock and nothing started. `failed`: any other refusal, with its code when it has the kernel's form, else
|
|
129
|
+
* E_CLI_PROTOCOL, as is an answer that does not decode. `notice` when a row was resumed, fresh, blocked
|
|
130
|
+
* or refused; `quiet` otherwise, also when only unswept deployments are left to say.
|
|
131
|
+
*/
|
|
132
|
+
export function readResumeSweep(envelope) {
|
|
133
|
+
if (record(envelope) && envelope.ok === false) {
|
|
134
|
+
const c = record(envelope.error) ? envelope.error.code : undefined;
|
|
135
|
+
if (UNSUPPORTED.has(c)) return { kind: 'unsupported' };
|
|
136
|
+
if (c === 'E_RESUME_BUSY') return { kind: 'busy' };
|
|
137
|
+
return { kind: 'failed', code: code(c) ?? 'E_CLI_PROTOCOL' };
|
|
138
|
+
}
|
|
139
|
+
const summary = record(envelope) && envelope.ok === true ? summarize(envelope.result) : null;
|
|
140
|
+
if (!summary) return { kind: 'failed', code: 'E_CLI_PROTOCOL' };
|
|
141
|
+
return { kind: sum(summary.totals) > 0 ? 'notice' : 'quiet', summary };
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** The rows of an answer the trigger reads (session-resume-trigger.mjs): the rows of an `ok: true` envelope
|
|
145
|
+
* whose result is the sweep's document (sweepDocument, as readResumeSweep reads it) and not a plan, else null:
|
|
146
|
+
* an answer the reader fails or reads as nothing settles nothing and leaves nothing out. */
|
|
147
|
+
function answerRows(envelope) {
|
|
148
|
+
const result = record(envelope) && envelope.ok === true ? envelope.result : undefined;
|
|
149
|
+
return sweepDocument(result) && result.plan === false ? result.rows : null;
|
|
150
|
+
}
|
|
151
|
+
/** A row's home as the trigger keys it: a non-empty string, else null. */
|
|
152
|
+
const homeOf = row => record(row) && typeof row.home === 'string' && row.home !== '' ? row.home : null;
|
|
153
|
+
const settles = row => row.outcome === RESUME_OUTCOMES.refused
|
|
154
|
+
|| row.outcome === RESUME_OUTCOMES.skipped && SETTLING_SKIPPED_REASONS.includes(row.reason);
|
|
155
|
+
const RELEASES = new Set([RESUME_OUTCOMES.resumed, RESUME_OUTCOMES.fresh, RESUME_OUTCOMES.blocked, RESUME_OUTCOMES.alreadyRunning]);
|
|
156
|
+
/** A refused row's (home, reason, code), as one string; the format is this module's alone. */
|
|
157
|
+
const reportedKey = (home, row) => JSON.stringify([home, row.reason ?? null, row.code ?? null]);
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* The homes a sweep's answer settles and releases, for the trigger's settled homes. A row `refused` (any
|
|
161
|
+
* reason) or `skipped` with a reason of SETTLING_SKIPPED_REASONS settles its home; `resumed`, `fresh`, `blocked` and
|
|
162
|
+
* `already-running` release it; any other row (`start-busy`, `unknown`, an outcome not known) does neither.
|
|
163
|
+
* When a home has several rows, its last decides. Rows that are not records, or have no string home, are
|
|
164
|
+
* ignored. Both lists are empty for an envelope that is not `ok: true` with a rows array.
|
|
165
|
+
* @param {unknown} envelope what runResumeSweep resolved
|
|
166
|
+
* @returns {{settle: string[], release: string[]}}
|
|
167
|
+
*/
|
|
168
|
+
export function sweepSettlement(envelope) {
|
|
169
|
+
const last = new Map();
|
|
170
|
+
for (const row of answerRows(envelope) ?? []) {
|
|
171
|
+
const home = homeOf(row);
|
|
172
|
+
if (home === null) continue;
|
|
173
|
+
if (settles(row)) { last.delete(home); last.set(home, true); } else if (RELEASES.has(row.outcome)) { last.delete(home); last.set(home, false); }
|
|
174
|
+
}
|
|
175
|
+
const settle = [], release = [];
|
|
176
|
+
for (const [home, settles] of last) (settles ? settle : release).push(home);
|
|
177
|
+
return { settle, release };
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* News, not repeats: the answer without what an earlier answer already reported, and this answer's keys.
|
|
182
|
+
* `envelope` is a copy (the given one is never changed) that leaves out each `refused` row with a string home
|
|
183
|
+
* whose (home, reason, code) key is in `reported`, and each host warning (the result's `warnings`) whose
|
|
184
|
+
* exact string is in `reportedHost`; everything else is kept, in order (`warnings` absent when none is left).
|
|
185
|
+
* `keys` are the keys of every such refused row of this answer, those left out too, each with its home, for
|
|
186
|
+
* the caller to add to `reported` after (and to forget by home). `hostKeys` are the host warnings kept, each
|
|
187
|
+
* that becomes a line, in order: shownHostKeys says which of them a reading showed. Keys are opaque outside
|
|
188
|
+
* this module. An envelope that is not the sweep's document (answerRows) is given back as it came, with no keys.
|
|
189
|
+
* @param {unknown} envelope
|
|
190
|
+
* @param {Set<string>} reported refusal keys an earlier answer gave
|
|
191
|
+
* @param {Set<string>} [reportedHost] host keys an earlier notice showed
|
|
192
|
+
* @returns {{envelope: unknown, keys: {home: string, key: string}[], hostKeys: string[]}}
|
|
193
|
+
*/
|
|
194
|
+
export function withoutReported(envelope, reported, reportedHost = new Set()) {
|
|
195
|
+
const rows = answerRows(envelope);
|
|
196
|
+
if (!rows) return { envelope, keys: [], hostKeys: [] };
|
|
197
|
+
const keys = [];
|
|
198
|
+
const kept = rows.filter(row => {
|
|
199
|
+
const home = homeOf(row);
|
|
200
|
+
if (home === null || row.outcome !== RESUME_OUTCOMES.refused) return true;
|
|
201
|
+
const key = reportedKey(home, row);
|
|
202
|
+
keys.push({ home, key });
|
|
203
|
+
return !reported.has(key);
|
|
204
|
+
});
|
|
205
|
+
// Host warnings: a reported one left out by its exact string; a `warnings` that is not an array passes as it is.
|
|
206
|
+
const { warnings: given, ...result } = envelope.result;
|
|
207
|
+
if (!Array.isArray(given)) return { envelope: { ...envelope, result: { ...envelope.result, rows: kept } }, keys, hostKeys: [] };
|
|
208
|
+
const host = given.filter(w => typeof w !== 'string' || !reportedHost.has(w));
|
|
209
|
+
const hostKeys = host.filter(w => typeof w === 'string' && displayLine(w) !== null);
|
|
210
|
+
return { envelope: { ...envelope, result: { ...result, rows: kept, ...(host.length ? { warnings: host } : {}) } }, keys, hostKeys };
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** Whether a sweep completed: its answer is the sweep's document and not a plan (answerRows: it ran), and its
|
|
214
|
+
* reading is `quiet` or `notice`. Busy, failed, unsupported and a plan are not: nothing can be concluded about a
|
|
215
|
+
* home from them. `envelope` is the run's answer, `reading` what was read of it. */
|
|
216
|
+
export const sweepCompleted = (envelope, reading) => answerRows(envelope) !== null
|
|
217
|
+
&& record(reading) && (reading.kind === 'quiet' || reading.kind === 'notice');
|
|
218
|
+
|
|
219
|
+
/** The host keys of `hostKeys` (withoutReported's, for the envelope `reading` was read from) that the reading
|
|
220
|
+
* showed: none unless it is a notice, else those its summary kept, in order (the cut is by position). A host
|
|
221
|
+
* warning a quiet sweep carried was never shown, so it stays news. */
|
|
222
|
+
export function shownHostKeys(reading, hostKeys) {
|
|
223
|
+
if (!record(reading) || reading.kind !== 'notice' || !record(reading.summary) || !record(reading.summary.host)
|
|
224
|
+
|| !Array.isArray(reading.summary.host.warnings) || !Array.isArray(hostKeys)) return [];
|
|
225
|
+
return hostKeys.slice(0, reading.summary.host.warnings.length);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** Whether each kept fact has its kind's exact shape. */
|
|
229
|
+
const rowShape = {
|
|
230
|
+
resumed: r => exactKeys(r, ['instance', 'deployment', 'warnings', 'omitted']) && boundedWarningsValid(r.warnings, r.omitted),
|
|
231
|
+
fresh: r => exactKeys(r, ['instance', 'deployment', 'reason', 'warnings', 'omitted']) && (r.reason === null || FRESH_REASONS.includes(r.reason))
|
|
232
|
+
&& boundedWarningsValid(r.warnings, r.omitted),
|
|
233
|
+
waiting: r => exactKeys(r, ['instance', 'deployment', 'reason']) && (r.reason === null || WAITING_REASONS.includes(r.reason)),
|
|
234
|
+
refused: r => exactKeys(r, ['instance', 'deployment', 'reason', 'code', 'message']) && (r.reason === null || REFUSED_REASONS.includes(r.reason))
|
|
235
|
+
&& (r.code === null || code(r.code) !== null) && (r.message === null || cleanLine(r.message)),
|
|
236
|
+
};
|
|
237
|
+
const copyRow = r => Object.hasOwn(r, 'warnings') ? { ...r, warnings: [...r.warnings] } : { ...r };
|
|
238
|
+
|
|
239
|
+
/** The summary as it crossed a boundary (main to a renderer over IPC): the same summary, a fresh copy, or
|
|
240
|
+
* undefined. Exactly the keys above, everywhere; names and paths display lines, never withheld or empty;
|
|
241
|
+
* reasons one of their kind's or null; codes of the kernel's form or null; each row's warnings within both
|
|
242
|
+
* bounds with `omitted` consistent (boundedWarningsValid); at most RESUME_SUMMARY_ROWS rows and
|
|
243
|
+
* RESUME_SUMMARY_DEPLOYMENTS deployment lines; `host` the host warnings within both bounds (boundedWarningsValid);
|
|
244
|
+
* `totals` non-negative safe integers, each at least its kind's
|
|
245
|
+
* kept rows. `omitted` is the rows over the bound (the totals' sum less the kept rows: above 0 only beside
|
|
246
|
+
* a full set of rows) plus the deployment lines over theirs (above 0 only beside a full set of lines).
|
|
247
|
+
* Idempotent: readResumeSweep's summary decodes to itself, and so does this function's answer. */
|
|
248
|
+
export function resumeSummaryFact(v) {
|
|
249
|
+
if (!exactKeys(v, SUMMARY_KEYS) || !exactKeys(v.totals, KINDS) || !KINDS.every(k => count(v.totals[k]))
|
|
250
|
+
|| !count(v.omitted) || !Array.isArray(v.unswept)
|
|
251
|
+
|| !exactKeys(v.host, ['warnings', 'omitted']) || !boundedWarningsValid(v.host.warnings, v.host.omitted)) return undefined;
|
|
252
|
+
let kept = 0;
|
|
253
|
+
for (const k of KINDS) {
|
|
254
|
+
const rows = v[k];
|
|
255
|
+
if (!Array.isArray(rows) || rows.length > v.totals[k]
|
|
256
|
+
|| !rows.every(r => rowShape[k](r) && named(r.instance) && named(r.deployment))) return undefined;
|
|
257
|
+
kept += rows.length;
|
|
258
|
+
}
|
|
259
|
+
const lines = v.unswept.length, total = sum(v.totals);
|
|
260
|
+
if (kept > RESUME_SUMMARY_ROWS || lines > RESUME_SUMMARY_DEPLOYMENTS || !Number.isSafeInteger(total)
|
|
261
|
+
|| !v.unswept.every(u => exactKeys(u, ['deployment', 'reason']) && named(u.deployment) && (u.reason === null || UNSWEPT_REASONS.includes(u.reason)))) return undefined;
|
|
262
|
+
const overRows = total - kept, overLines = v.omitted - overRows;
|
|
263
|
+
if (overRows > 0 && kept < RESUME_SUMMARY_ROWS || overLines < 0 || overLines > 0 && lines < RESUME_SUMMARY_DEPLOYMENTS) return undefined;
|
|
264
|
+
const out = {};
|
|
265
|
+
for (const k of KINDS) out[k] = v[k].map(copyRow);
|
|
266
|
+
return { ...out, unswept: v.unswept.map(u => ({ ...u })), host: { warnings: [...v.host.warnings], omitted: v.host.omitted },
|
|
267
|
+
omitted: v.omitted, totals: { ...v.totals } };
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
const FRESH_WHY = {
|
|
271
|
+
'no-conversation': 'no saved conversation was found.',
|
|
272
|
+
'no-receipts': 'OATS has no record of where its conversations are kept.',
|
|
273
|
+
'resume-unproven': "resuming this harness's conversations isn't supported yet.",
|
|
274
|
+
};
|
|
275
|
+
const UNSWEPT_WHY = { 'not-ok': "its deployment isn't ready.", unreadable: 'it could not be read.' };
|
|
276
|
+
const THIS_BOOT = ' It was refused earlier since this computer started, so OATS did not try again.';
|
|
277
|
+
const KEEPS_LOST = "keeps losing its session, so OATS stopped resuming it: start it yourself once it's fixed.";
|
|
278
|
+
/** A refused row's line: `keeps-getting-lost` says why in place of "could not be resumed.". */
|
|
279
|
+
const refusedLine = r => r.reason === 'keeps-getting-lost' ? KEEPS_LOST
|
|
280
|
+
: `could not be resumed.${r.reason === 'refused-this-boot' ? THIS_BOOT : ''}`;
|
|
281
|
+
|
|
282
|
+
/** The headline's sentences, each only when its count is above 0. A blocked row's session runs, so it counts
|
|
283
|
+
* among the resumed: N = resumed + fresh + waiting. "1 of them" takes "its"; "It" when the one is all of N. */
|
|
284
|
+
function headline({ resumed, fresh: f, waiting: w, refused: r }) {
|
|
285
|
+
const n = resumed + f + w, out = [];
|
|
286
|
+
if (n > 0) out.push(n === 1 ? 'OATS resumed 1 instance whose session was lost.' : `OATS resumed ${n} instances whose sessions were lost.`);
|
|
287
|
+
if (f > 0) out.push(f === n && n === 1 ? 'It started fresh from its briefing.'
|
|
288
|
+
: f === 1 ? '1 of them started fresh from its briefing.' : `${f} of them started fresh from their briefing.`);
|
|
289
|
+
if (w > 0) out.push(w === n && n === 1 ? 'It is waiting for you: open its terminal.'
|
|
290
|
+
: w === 1 ? '1 of them is waiting for you: open its terminal.' : `${w} of them are waiting for you: open their terminals.`);
|
|
291
|
+
if (r > 0) out.push(n > 0 ? `${r} could not be resumed.` : r === 1 ? 'OATS could not resume 1 lost session.' : `OATS could not resume ${r} lost sessions.`);
|
|
292
|
+
return out.join(' ');
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** A row's warnings under `OATS says:`, in order, then how many more the cut left out; nothing without one. */
|
|
296
|
+
const said = r => r.warnings.length ? ['OATS says:', ...r.warnings, ...(r.omitted > 0 ? [`${r.omitted} more not shown.`] : [])] : [];
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* The notice for a summary in the clients' words: `{headline, detail}`, or null when `summary` does not
|
|
300
|
+
* decode (resumeSummaryFact) or has no row to tell of. Kernel text appears only after `OATS says:`.
|
|
301
|
+
* @param {unknown} summary
|
|
302
|
+
* @param {{label: (deployment: string) => string}} options `label` is the caller's display label for a
|
|
303
|
+
* deployment path (required: a TypeError without it); a non-string or empty label shows the path itself.
|
|
304
|
+
* Detail: a line per kept row, waiting, refused, fresh, resumed; then the unswept deployments; then the host
|
|
305
|
+
* warnings under `OATS says about this computer:` (and how many more the cut left out); then
|
|
306
|
+
* `M more not shown.` when anything was left out. A row line names its deployment (` in {d}`) only when the
|
|
307
|
+
* kept rows name more than one; a deployment line always does. A refused row's kernel message follows it on
|
|
308
|
+
* its own line, as `OATS says: …`. `detail` is the lines joined with '\n', absent when there are none.
|
|
309
|
+
*/
|
|
310
|
+
export function resumeNotice(summary, options) {
|
|
311
|
+
const labelOf = options?.label;
|
|
312
|
+
if (typeof labelOf !== 'function') throw new TypeError('resumeNotice needs a label function');
|
|
313
|
+
const s = resumeSummaryFact(summary);
|
|
314
|
+
if (!s || sum(s.totals) === 0) return null;
|
|
315
|
+
const shown = d => { const l = labelOf(d); return typeof l === 'string' && l ? l : d; };
|
|
316
|
+
const several = new Set(KINDS.flatMap(k => s[k].map(r => r.deployment))).size > 1;
|
|
317
|
+
const who = r => several ? `${r.instance} in ${shown(r.deployment)}` : r.instance;
|
|
318
|
+
const lines = [
|
|
319
|
+
...s.waiting.map(r => r.reason === 'resume-confirmation'
|
|
320
|
+
? `${who(r)}: waiting for you to choose how to resume it. Open its terminal.`
|
|
321
|
+
: `${who(r)}: waiting at a launch prompt. Open its terminal.`),
|
|
322
|
+
...s.refused.flatMap(r => [`${who(r)}: ${refusedLine(r)}`,
|
|
323
|
+
...(r.message !== null ? [`OATS says: ${r.message}`] : [])]),
|
|
324
|
+
...s.fresh.flatMap(r => [`${who(r)}: started fresh from its briefing, ${FRESH_WHY[r.reason] ?? 'its conversation could not be resumed.'}`, ...said(r)]),
|
|
325
|
+
...s.resumed.flatMap(r => [`${who(r)}: resumed in its own conversation.`, ...said(r)]),
|
|
326
|
+
...s.unswept.map(u => `Not checked in ${shown(u.deployment)}: ${UNSWEPT_WHY[u.reason] ?? 'it could not be checked.'}`),
|
|
327
|
+
...(s.host.warnings.length ? ['OATS says about this computer:', ...s.host.warnings,
|
|
328
|
+
...(s.host.omitted > 0 ? [`${s.host.omitted} more not shown.`] : [])] : []),
|
|
329
|
+
...(s.omitted > 0 ? [`${s.omitted} more not shown.`] : []),
|
|
330
|
+
];
|
|
331
|
+
return lines.length ? { headline: headline(s.totals), detail: lines.join('\n') } : { headline: headline(s.totals) };
|
|
332
|
+
}
|
|
@@ -7,6 +7,29 @@ export const DEFAULT_TMUX_SESSION = process.env.OATS_TMUX_SESSION || process.env
|
|
|
7
7
|
|
|
8
8
|
const shells = new Set(["sh", "bash", "zsh", "fish", "dash", "ksh", "login"]);
|
|
9
9
|
|
|
10
|
+
const paneNumber = (paneId) => Number(paneId.slice(1));
|
|
11
|
+
|
|
12
|
+
/** The agent's pane of one window's panes, [{ paneId: "%N", mark, ...rest }] (`mark`: the pane's
|
|
13
|
+
* `@oats-agent`, "" when unset): the kernel's rule, lib/session-input.mjs `resolveAgentPane`, which
|
|
14
|
+
* a client cannot import. This copy is for this computer's tmux only (the status reader below and
|
|
15
|
+
* the Desktop's terminal open, packages/desktop/tmux-target.mjs), and test/desktop-tmux-status.test.mjs
|
|
16
|
+
* pins it to the kernel's, sentences included. `name` is the window's recorded name, which is what
|
|
17
|
+
* OATS marks the agent's pane with. One pane is the agent's, mark or not. Of several: the one marked
|
|
18
|
+
* `name`; else the lowest pane id of those with no mark (the window's own: an OATS split comes
|
|
19
|
+
* later), as another instance's mark is never this one's; two or more marked `name`, or no
|
|
20
|
+
* candidate, it can't tell. { pane } (the element, null for no pane) or { error }. */
|
|
21
|
+
export function agentPane(panes, name) {
|
|
22
|
+
if (panes.length <= 1) return { pane: panes[0] ?? null };
|
|
23
|
+
const byId = [...panes].sort((a, b) => paneNumber(a.paneId) - paneNumber(b.paneId));
|
|
24
|
+
const ids = (list) => list.map((p) => p.paneId).join(", ");
|
|
25
|
+
const ours = byId.filter((p) => p.mark === name);
|
|
26
|
+
if (ours.length === 1) return { pane: ours[0] };
|
|
27
|
+
if (ours.length > 1) return { error: `the window has ${ours.length} panes marked as ${name}'s agent pane (${ids(ours)}); close all but the agent's with tmux kill-pane -t <id>, or close the window and start the instance` };
|
|
28
|
+
const unmarked = byId.find((p) => !p.mark);
|
|
29
|
+
if (unmarked) return { pane: unmarked };
|
|
30
|
+
return { error: `the window has ${byId.length} panes and none is ${name}'s agent pane (${ids(byId)}); close the panes that aren't, or close the window and start the instance` };
|
|
31
|
+
}
|
|
32
|
+
|
|
10
33
|
/** One read per socket, and at most one process snapshot per roster collection. */
|
|
11
34
|
export function createTmuxStatusReader({ exec = execFileSync } = {}) {
|
|
12
35
|
const sockets = new Map();
|
|
@@ -18,11 +41,12 @@ export function createTmuxStatusReader({ exec = execFileSync } = {}) {
|
|
|
18
41
|
if (!sockets.has(socket)) {
|
|
19
42
|
try {
|
|
20
43
|
const text = run("tmux", ["-u", ...(socket ? ["-S", socket] : []), "list-panes", "-a", "-F",
|
|
21
|
-
"#{session_name}\t#{window_name}\t#{window_id}\t#{pane_dead}\t#{pane_current_command}\t#{pane_pid}"]);
|
|
44
|
+
"#{session_name}\t#{window_name}\t#{window_id}\t#{pane_id}\t#{pane_dead}\t#{pane_current_command}\t#{pane_pid}\t#{@oats-agent}"]);
|
|
22
45
|
const panes = text.trim().split("\n").filter(Boolean).map((line) => {
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
46
|
+
// The mark is last: whatever it holds, the fields before it are where they should be.
|
|
47
|
+
const [session, window, id, paneId, dead, command, pid, ...mark] = line.split("\t");
|
|
48
|
+
if (!session || !window || !/^@\d+$/.test(id) || !/^%\d+$/.test(paneId) || !/^[01]$/.test(dead) || !/^\d+$/.test(pid)) throw new Error("Invalid tmux status response");
|
|
49
|
+
return { session, window, id, paneId, dead: dead === "1", command, pid, mark: mark.join("\t") };
|
|
26
50
|
});
|
|
27
51
|
sockets.set(socket, { panes });
|
|
28
52
|
} catch (e) {
|
|
@@ -53,9 +77,8 @@ export function createTmuxStatusReader({ exec = execFileSync } = {}) {
|
|
|
53
77
|
const status = readSocket(tmux.socket || "");
|
|
54
78
|
const unknown = (error) => ({ tmux, running: null, runtimeState: "unreachable", runtimeError: error });
|
|
55
79
|
if (status.error) return unknown(status.error);
|
|
56
|
-
const
|
|
57
|
-
if (
|
|
58
|
-
const pane = panes[0];
|
|
80
|
+
const { pane, error } = agentPane(status.panes.filter((p) => p.session === tmux.session && p.window === tmux.window), tmux.window);
|
|
81
|
+
if (error) return unknown(error);
|
|
59
82
|
if (!pane || pane.dead) return { tmux, running: false, runtimeState: "stopped" };
|
|
60
83
|
tmux.id = pane.id;
|
|
61
84
|
try {
|
|
@@ -20,13 +20,14 @@ export function waitingMessage(v) {
|
|
|
20
20
|
|
|
21
21
|
/** The sidebar's claim: `{ since, producer, reason, message }` or null. Only `since` and `producer` can
|
|
22
22
|
* drop a claim: a missing or malformed reason (never rendered) is null, a malformed message is null, and
|
|
23
|
-
* so is a withheld one (#584)
|
|
24
|
-
* never the withheld marker
|
|
23
|
+
* so is a withheld one (#584) or one with no character but white space (#1502): the row, the card and the
|
|
24
|
+
* tab then show the reason in words (waitingLabel), never the withheld marker or a blank line. Extra keys
|
|
25
|
+
* are ignored (forward compatible). */
|
|
25
26
|
export function waitingOnYouData(v) {
|
|
26
27
|
if (!record(v) || !eventsTimestamp(v.since) || !eventsId(v.producer)) return null;
|
|
27
28
|
const reason = typeof v.reason === 'string' && v.reason.length <= 64 ? v.reason : null;
|
|
28
29
|
const message = waitingMessage(v.message);
|
|
29
|
-
return { since: v.since, producer: v.producer, reason, message: message === EVENTS_WITHHELD ? null : message };
|
|
30
|
+
return { since: v.since, producer: v.producer, reason, message: message === EVENTS_WITHHELD || !message?.trim() ? null : message };
|
|
30
31
|
}
|
|
31
32
|
|
|
32
33
|
/** The claim a row may show, or null. The only gate: liveness says running (`running === true`, and no
|
|
@@ -45,6 +46,9 @@ export function waitingClaim(row, { stale = false } = {}) {
|
|
|
45
46
|
const LABELS = Object.freeze({ permission: 'Waiting for a tool approval', question: 'Asked you a question', attention: 'Asked for your attention' });
|
|
46
47
|
/** The reason in words. The raw reason is never rendered: an unknown one reads "Needs input". */
|
|
47
48
|
export const waitingLabel = claim => Object.hasOwn(LABELS, claim?.reason ?? '') ? LABELS[claim.reason] : 'Needs input';
|
|
49
|
+
/** What a surface that already says "Needs input" adds after it: the message, else the reason in words,
|
|
50
|
+
* else null, when the claim names no reason of its own and the tag's words say it all (#1502). */
|
|
51
|
+
export const waitingDetail = claim => claim?.message ?? (Object.hasOwn(LABELS, claim?.reason ?? '') ? LABELS[claim.reason] : null);
|
|
48
52
|
|
|
49
53
|
/** How long it has waited (floor): "under a minute", "N min", "N h", "N d". A future `since` (clock skew)
|
|
50
54
|
* reads "under a minute". Computed when shown, never painted into the row. */
|
|
@@ -82,7 +86,10 @@ export const waitingBelowText = rows => `${rows.length} ${rows.length === 1 ? 'n
|
|
|
82
86
|
* the sentence is painted once; `now` is the paint time (it decides whether the start needs a date). */
|
|
83
87
|
export function waitingSentence(claim, below = [], now = Date.now()) {
|
|
84
88
|
const parts = [];
|
|
85
|
-
if (claim)
|
|
89
|
+
if (claim) {
|
|
90
|
+
const detail = waitingDetail(claim);
|
|
91
|
+
parts.push(`Needs input${detail ? `: ${detail}` : ''} since ${waitingClock(claim.since, now)}`);
|
|
92
|
+
}
|
|
86
93
|
if (below.length) parts.push(`${below.length} below need input: ${waitingNames(below)}`);
|
|
87
94
|
return parts.map(p => ` · ${p}`).join('');
|
|
88
95
|
}
|