@awebai/oats 0.50.0 → 0.52.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/bin/oats.mjs +153 -51
- package/docs/capabilities.md +11 -3
- package/docs/configuration.md +134 -88
- package/docs/desktop-cli-api.md +994 -71
- package/docs/desktop-instance-start.md +56 -0
- package/docs/desktop.md +10 -7
- package/docs/execution-targets.md +230 -59
- package/docs/first-team.md +3 -1
- package/docs/harness-trust.md +50 -2
- package/docs/implementation.md +73 -8
- package/docs/integrations.md +9 -8
- package/docs/knowledge-reference/acceptance.md +1 -0
- package/docs/knowledge-reference/harvester.md +5 -3
- package/docs/knowledge-reference/model.md +5 -3
- package/docs/knowledge-theory.md +1 -1
- package/docs/knowledge.md +43 -7
- package/docs/launch-prompt-completion.md +50 -48
- package/docs/oats-local.schema.json +4 -3
- package/docs/official-catalog.md +4 -4
- package/docs/packages.md +14 -14
- package/docs/release-lane.md +15 -5
- package/docs/release-notes/v0.44.0.md +1 -1
- package/docs/release-notes/v0.51.0.md +156 -0
- package/docs/release-notes/v0.52.0.md +933 -0
- package/docs/schedules.md +91 -4
- package/docs/servers.md +21 -2
- package/docs/souls-and-instances.md +113 -21
- package/docs/tui.md +152 -0
- package/docs/workspaces.md +2 -2
- package/lib/claim.mjs +266 -0
- package/lib/core.mjs +845 -166
- package/lib/errors.mjs +170 -0
- package/lib/harness-trust-write.mjs +68 -27
- package/lib/harness-trust.mjs +34 -16
- package/lib/instance-inspect.mjs +40 -11
- package/lib/instance-lifecycle.mjs +169 -47
- package/lib/launch-preference.mjs +16 -0
- package/lib/launch-prompt-completion.mjs +7 -43
- package/lib/launch-prompt-evidence.mjs +14 -7
- package/lib/launch-prompt-fixtures/README.md +86 -152
- package/lib/launch-prompt-fixtures/dev-channel-confirmation.json +50 -0
- package/lib/launch-prompt-fixtures.mjs +122 -109
- package/lib/launch-prompt-transport.mjs +2 -56
- package/lib/launch-prompts.mjs +102 -100
- package/lib/schedule-host.mjs +154 -22
- package/lib/schedule.mjs +73 -24
- package/lib/servers.mjs +20 -4
- package/lib/session-viewer.mjs +87 -10
- package/lib/system-tools.mjs +39 -0
- package/lib/tmux-server-scope.mjs +62 -0
- package/lib/triggers.mjs +4 -4
- package/lib/workspace.mjs +5 -11
- package/lib/worktree-hooks.mjs +116 -23
- package/lib/worktree.mjs +89 -102
- package/package-catalog.json +3 -3
- package/package.json +7 -2
- package/packages/client/capability-show-contract.mjs +230 -0
- package/packages/client/capability-warnings-contract.mjs +57 -0
- package/packages/client/cli-adapter.mjs +548 -0
- package/packages/client/cli-environment.mjs +53 -0
- package/packages/client/cli-locator.mjs +253 -0
- package/packages/client/cli-probe-contract.mjs +47 -0
- package/packages/client/client-terms.mjs +60 -0
- package/packages/client/deployment-contract.mjs +68 -0
- package/packages/client/deployment-data.mjs +483 -0
- package/packages/client/deployment-facts.mjs +34 -0
- package/packages/client/deployment-label.mjs +76 -0
- package/packages/client/deployment-observer.mjs +89 -0
- package/packages/client/deployment-panel.mjs +142 -0
- package/packages/client/deployment-read-cli.mjs +53 -0
- package/packages/client/display-text.mjs +44 -0
- package/packages/client/harness-names.mjs +30 -0
- package/packages/client/inspect-contract.mjs +62 -0
- package/packages/client/instance-acts.mjs +54 -0
- package/packages/client/instance-admission.mjs +45 -0
- package/packages/client/instance-events-contract.mjs +74 -0
- package/packages/client/instance-git-contract.mjs +80 -0
- package/packages/client/instance-presentation.mjs +22 -0
- package/packages/client/instance-tree.mjs +453 -0
- package/packages/client/kernel-environment.mjs +11 -0
- package/packages/client/launch-contract.mjs +51 -0
- package/packages/client/launch-prompt-outcome.mjs +165 -0
- package/packages/client/lifecycle-cli.mjs +61 -0
- package/packages/client/lifecycle-contract.mjs +372 -0
- package/packages/client/liveness-main.mjs +10 -0
- package/packages/client/liveness.mjs +35 -0
- package/packages/client/machine-contract.mjs +123 -0
- package/packages/client/own-environment.mjs +22 -0
- package/packages/client/panel-views.mjs +286 -0
- package/packages/client/readiness-contract.mjs +172 -0
- package/packages/client/refresh-loop.mjs +52 -0
- package/packages/client/remote-address.mjs +126 -0
- package/packages/client/remote-roster.mjs +67 -0
- package/packages/client/roster-sections.mjs +80 -0
- package/packages/client/spawn-apply-cli.mjs +104 -0
- package/packages/client/spawn-apply-contract.mjs +183 -0
- package/packages/client/spawn-decision.mjs +46 -0
- package/packages/client/spawn-messages.mjs +119 -0
- package/packages/client/spawn-preview-cli.mjs +32 -0
- package/packages/client/spawn-preview-contract.mjs +314 -0
- package/packages/client/team-members.mjs +41 -0
- package/packages/client/team-rows.mjs +45 -0
- package/packages/client/terminal-contract.mjs +57 -0
- package/packages/client/tmux-status.mjs +66 -0
- package/packages/client/waiting-on-you.mjs +88 -0
- package/packages/client/workspace-admission.mjs +45 -0
- package/packages/client/workspace-cli.mjs +142 -0
- package/packages/client/workspace-views.mjs +147 -0
- package/packages/tui/README.md +46 -0
- package/packages/tui/bin/tui.mjs +7 -0
- package/packages/tui/lib/actions.mjs +29 -0
- package/packages/tui/lib/client.mjs +4 -0
- package/packages/tui/lib/main.mjs +105 -0
- package/packages/tui/lib/term/keys.mjs +323 -0
- package/packages/tui/lib/term/screen.mjs +122 -0
- package/packages/tui/lib/term/style.mjs +43 -0
- package/packages/tui/lib/term/text.mjs +49 -0
- package/packages/tui/lib/term/tty.mjs +168 -0
- package/packages/tui/lib/term/width.mjs +124 -0
- package/packages/tui/lib/views/frame.mjs +62 -0
- package/packages/tui/lib/views/help.mjs +28 -0
- package/packages/tui/package.json +8 -0
- package/skills/oats-getting-started/SKILL.md +29 -22
- package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-05-channel-seeded.txt +0 -35
- package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-06-first-after-channel.txt +0 -35
- package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-07-after-channel-200ms.txt +0 -35
- package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-08-installed-after-channel-200ms.txt +0 -35
- package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/manifest.json +0 -77
- package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/max-bypass-source.json +0 -88
- package/lib/launch-prompt-fixtures/structural-completion.json +0 -205
- package/lib/launch-prompt-policy.mjs +0 -87
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/** Whether a directory is an OATS deployment, and which deployments a directory holds: the rule a
|
|
2
|
+
* client applies before it serves or offers a directory. Existence only: the deployment's content is
|
|
3
|
+
* the kernel's to read (`oats workspace status`), and nothing here parses it. The filesystem is the
|
|
4
|
+
* caller's: every function takes its `io`. */
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
|
|
7
|
+
/** The most directory entries one look inside a folder reads. */
|
|
8
|
+
export const PICK_SCAN_LIMIT = 200;
|
|
9
|
+
|
|
10
|
+
/** `io.isDeployment` as a predicate that never throws: a path it cannot answer for is not a deployment. */
|
|
11
|
+
export const deploymentCheck = (io) => (p) => { try { return io.isDeployment(p) === true; } catch { return false; } };
|
|
12
|
+
|
|
13
|
+
/** The deployments directly inside `dir`, sorted by name: at most PICK_SCAN_LIMIT entries read, a
|
|
14
|
+
* link never followed, nothing parsed. An unreadable or missing `dir` holds none. Used for a picked
|
|
15
|
+
* parent folder, and for ~/Agents, whose deployments the switcher offers unasked (#518).
|
|
16
|
+
* @param {string} dir
|
|
17
|
+
* @param {object} io
|
|
18
|
+
* @param {(dir: string, limit: number) => { entries: Array<{ name: string, isDirectory: boolean }>, limited: boolean }} io.list
|
|
19
|
+
* at most `limit` entries, `isDirectory` from the entry itself (a link is not a directory)
|
|
20
|
+
* @param {(p: string) => boolean} io.isDeployment a regular oats-local.yaml (lstat)
|
|
21
|
+
* @returns {{ paths: string[], limited: boolean }} */
|
|
22
|
+
export function deploymentsInside(dir, io) {
|
|
23
|
+
let listed = { entries: [], limited: false };
|
|
24
|
+
try { listed = io.list(dir, PICK_SCAN_LIMIT) || listed; } catch { /* unreadable: no children offered */ }
|
|
25
|
+
const paths = listed.entries.filter((e) => e?.isDirectory && typeof e.name === "string" && !e.name.includes("/"))
|
|
26
|
+
.map((e) => e.name).sort((a, b) => a.localeCompare(b)).map((name) => join(dir, name)).filter(deploymentCheck(io));
|
|
27
|
+
return { paths, limited: !!listed.limited };
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Validate a directory as a workspace-model v2 deployment and derive its
|
|
32
|
+
* identity: the canonical deployment directory itself.
|
|
33
|
+
* @param {string} path canonicalized absolute path
|
|
34
|
+
* @param {object} io
|
|
35
|
+
* @param {(p: string) => boolean} io.isDeployment the directory holds its
|
|
36
|
+
* deployment file (a regular, non-symlink oats-local.yaml); existence
|
|
37
|
+
* only — the kernel reads and validates it
|
|
38
|
+
* @returns {{ id: string, name: string, team: null, path: string } | null}
|
|
39
|
+
*/
|
|
40
|
+
export function validateWorkspace(path, io) {
|
|
41
|
+
if (typeof path !== "string" || !path.startsWith("/")) return null;
|
|
42
|
+
let deployment = false;
|
|
43
|
+
try { deployment = io.isDeployment(path) === true; } catch { return null; }
|
|
44
|
+
return deployment ? { id: path, name: path.split("/").pop() || path, team: null, path } : null;
|
|
45
|
+
}
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
/** Workspace model v2 verbs the Desktop drives: fixed argv, bounded output,
|
|
2
|
+
* scrubbed instance environment. Only the kernel's JSON crosses back; a
|
|
3
|
+
* refusal is its bounded error envelope (code + message, plus onboarding's
|
|
4
|
+
* rolledBack flag), never stderr, argv, stacks or details objects.
|
|
5
|
+
* capabilities → `oats capabilities --dir D [--max-age S] --json` (capabilitiesApi 1)
|
|
6
|
+
* souls → `oats souls --dir D [--max-age S] --json` (soulsApi 1, the spawn catalog)
|
|
7
|
+
* capability-show → `oats capabilities show NAME (--member KEY | --package ID) [--file PATH]
|
|
8
|
+
* --dir D [--max-age S] --json` (capabilityShowApi 1, feature capability-show:
|
|
9
|
+
* what one capability ships, read at the commit the catalog reports)
|
|
10
|
+
* sync → `oats sync --dir D --json` (syncApi 1)
|
|
11
|
+
* onboard → `oats onboard DIR --workspace REF --json` (onboardApi 2)
|
|
12
|
+
* There is no package approval (packages-no-approval): declaring a package
|
|
13
|
+
* is the trust decision, so every success exits 0. `--max-age` (feature
|
|
14
|
+
* observe-max-age) belongs to the three reads only and reaches argv only when
|
|
15
|
+
* the probe declares the feature; cliWorkspace drops it otherwise. */
|
|
16
|
+
import { execFile } from 'node:child_process';
|
|
17
|
+
import { isAbsolute, resolve } from 'node:path';
|
|
18
|
+
import { OBSERVE_MAX_AGE_FEATURE, validMaxAge } from './deployment-contract.mjs';
|
|
19
|
+
import { capabilityShowSupported, validCapabilityName, validPackageId, validRelativePath, validRepoKey } from './capability-show-contract.mjs';
|
|
20
|
+
import { cliEnvironment } from './cli-environment.mjs';
|
|
21
|
+
import { withoutInstanceVariables } from './kernel-environment.mjs';
|
|
22
|
+
import { requireTerms } from './client-terms.mjs';
|
|
23
|
+
|
|
24
|
+
export const WORKSPACE_READ_TIMEOUT = 60_000;
|
|
25
|
+
export const WORKSPACE_WRITE_TIMEOUT = 300_000; // discovery reads every member remote
|
|
26
|
+
export const WORKSPACE_MAX_BUFFER = 4 * 1024 * 1024;
|
|
27
|
+
export const WORKSPACE_ACTIONS = Object.freeze(['capabilities', 'souls', 'sync', 'onboard', 'capability-show']);
|
|
28
|
+
/** The read-only verbs: the ones `--max-age` may reach. */
|
|
29
|
+
const READS = ['capabilities', 'souls', 'capability-show'];
|
|
30
|
+
/** The kernel line this Desktop drives: workspace model v2 without package approval. */
|
|
31
|
+
export const WORKSPACE_FEATURES = Object.freeze(['workspace-v2', 'packages-no-approval']);
|
|
32
|
+
const absolute = path => typeof path === 'string' && !path.includes('\0') && isAbsolute(path) && resolve(path) === path;
|
|
33
|
+
const record = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
34
|
+
/** A repository reference is the kernel's to parse (E_REPO_REF); the Desktop
|
|
35
|
+
* only refuses what could not be one argv value: empty, huge, control
|
|
36
|
+
* characters or an option-looking token. */
|
|
37
|
+
export const validWorkspaceRef = ref => typeof ref === 'string' && ref.length > 0 && ref.length <= 2048
|
|
38
|
+
&& ref.trim() === ref && !/[\u0000-\u001f\u007f]/.test(ref) && !ref.startsWith('-');
|
|
39
|
+
|
|
40
|
+
/** The sentence for each failure this adapter raises itself; one names the client, in its terms (client-terms.mjs). */
|
|
41
|
+
const messages = Object.freeze({
|
|
42
|
+
E_CLI_UNAVAILABLE: 'Choose a compatible installed OATS CLI first.',
|
|
43
|
+
E_WORKSPACE_FEATURE: terms => `The installed OATS CLI is older than ${terms.self} (it does not advertise workspace-v2 and packages-no-approval). Update OATS and retry.`,
|
|
44
|
+
E_BAD_ARGS: 'The workspace request was not valid.',
|
|
45
|
+
E_CLI_FAILED: 'The installed OATS CLI could not complete this workspace command.',
|
|
46
|
+
E_CLI_PROTOCOL: 'The installed OATS CLI returned an invalid workspace result.',
|
|
47
|
+
E_CLI_TIMEOUT: 'The workspace command exceeded its time limit.',
|
|
48
|
+
E_CLI_OUTPUT_LIMIT: 'The workspace command exceeded its size limit.',
|
|
49
|
+
E_CAPABILITY_SHOW_FEATURE: "The installed OATS CLI can't show what a capability ships. Update OATS and retry.",
|
|
50
|
+
});
|
|
51
|
+
/** Every code workspaceFailure has a sentence for. */
|
|
52
|
+
export const WORKSPACE_FAILURE_CODES = Object.freeze(Object.keys(messages));
|
|
53
|
+
|
|
54
|
+
export function workspaceFailure(code, terms, message) {
|
|
55
|
+
requireTerms(terms, 'workspaceFailure');
|
|
56
|
+
const known = Object.hasOwn(messages, code) ? code : 'E_CLI_FAILED', fixed = messages[known];
|
|
57
|
+
return { ok: false, reason: { code: known, message: message || (typeof fixed === 'function' ? fixed(terms) : fixed) } };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Probe facts only (version --json): the API integer and the feature. */
|
|
61
|
+
export function workspaceGate(cli, terms) {
|
|
62
|
+
requireTerms(terms, 'workspaceGate');
|
|
63
|
+
if (cli?.ok !== true || !absolute(cli.bin)) return workspaceFailure('E_CLI_UNAVAILABLE', terms);
|
|
64
|
+
if (cli.workspaceApi !== 2 || !Array.isArray(cli.features) || !WORKSPACE_FEATURES.every(name => cli.features.includes(name))) return workspaceFailure('E_WORKSPACE_FEATURE', terms);
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function workspaceArgv(options) {
|
|
69
|
+
if (!record(options) || !WORKSPACE_ACTIONS.includes(options.action)) return null;
|
|
70
|
+
const { action } = options;
|
|
71
|
+
const allowed = { capabilities: ['action', 'context', 'maxAge'], souls: ['action', 'context', 'maxAge'], sync: ['action', 'context'], onboard: ['action', 'dir', 'workspace'],
|
|
72
|
+
'capability-show': ['action', 'context', 'name', 'member', 'package', 'path', 'maxAge'] }[action];
|
|
73
|
+
if (Object.keys(options).some(key => !allowed.includes(key))) return null;
|
|
74
|
+
if (action === 'onboard') {
|
|
75
|
+
if (!absolute(options.dir) || !validWorkspaceRef(options.workspace)) return null;
|
|
76
|
+
return { argv: ['onboard', options.dir, '--workspace', options.workspace, '--json'], cwd: options.dir, timeout: WORKSPACE_WRITE_TIMEOUT };
|
|
77
|
+
}
|
|
78
|
+
if (!absolute(options.context)) return null;
|
|
79
|
+
if (action === 'capability-show') {
|
|
80
|
+
// Exactly one selector, each value one argv token the kernel parses (never option-looking);
|
|
81
|
+
// the file path is plain, relative and inside the capability (no `..`, no leading `/` or `-`).
|
|
82
|
+
const member = Object.hasOwn(options, 'member'), pkg = Object.hasOwn(options, 'package');
|
|
83
|
+
if (!validCapabilityName(options.name) || member === pkg || !validMaxAge(options.maxAge)) return null;
|
|
84
|
+
if (member ? !validRepoKey(options.member) : !validPackageId(options.package)) return null;
|
|
85
|
+
if (Object.hasOwn(options, 'path') && !validRelativePath(options.path)) return null;
|
|
86
|
+
return { argv: ['capabilities', 'show', options.name, ...(member ? ['--member', options.member] : ['--package', options.package]),
|
|
87
|
+
...(Object.hasOwn(options, 'path') ? ['--file', options.path] : []), '--dir', options.context,
|
|
88
|
+
...(options.maxAge === undefined ? [] : ['--max-age', String(options.maxAge)]), '--json'], cwd: options.context, timeout: WORKSPACE_READ_TIMEOUT };
|
|
89
|
+
}
|
|
90
|
+
if (action === 'capabilities' || action === 'souls') {
|
|
91
|
+
if (!validMaxAge(options.maxAge)) return null;
|
|
92
|
+
const maxAge = options.maxAge === undefined ? [] : ['--max-age', String(options.maxAge)];
|
|
93
|
+
return { argv: [action, '--dir', options.context, ...maxAge, '--json'], cwd: options.context, timeout: WORKSPACE_READ_TIMEOUT };
|
|
94
|
+
}
|
|
95
|
+
return { argv: ['sync', '--dir', options.context, '--json'], cwd: options.context, timeout: WORKSPACE_WRITE_TIMEOUT };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** `io.exec` is a client's own `execFile` (the rule is at cli-adapter.mjs `runJson`). */
|
|
99
|
+
export function cliWorkspace(cli, options, terms, io = {}) {
|
|
100
|
+
requireTerms(terms, 'cliWorkspace');
|
|
101
|
+
const gate = workspaceGate(cli, terms);
|
|
102
|
+
if (gate) return Promise.resolve(gate);
|
|
103
|
+
// `capabilities show` is its own feature on top of the workspace line (the feature AND the API integer).
|
|
104
|
+
if (record(options) && options.action === 'capability-show' && !capabilityShowSupported(cli)) return Promise.resolve(workspaceFailure('E_CAPABILITY_SHOW_FEATURE', terms));
|
|
105
|
+
// An invalid value is a bad request whatever the kernel. A valid one on a kernel without
|
|
106
|
+
// observe-max-age names a flag that does not exist there: drop it (on a copy; the caller's
|
|
107
|
+
// request is not ours to edit) so the read runs flagless. Only the reads take it, so the
|
|
108
|
+
// drop never lets a mutating verb past workspaceArgv's allowlist.
|
|
109
|
+
if (record(options) && Object.hasOwn(options, 'maxAge')) {
|
|
110
|
+
if (!validMaxAge(options.maxAge)) return Promise.resolve(workspaceFailure('E_BAD_ARGS', terms));
|
|
111
|
+
if (!cli.features.includes(OBSERVE_MAX_AGE_FEATURE) && READS.includes(options.action)) { const { maxAge, ...rest } = options; options = rest; }
|
|
112
|
+
}
|
|
113
|
+
const plan = workspaceArgv(options);
|
|
114
|
+
if (!plan) return Promise.resolve(workspaceFailure('E_BAD_ARGS', terms));
|
|
115
|
+
const env = withoutInstanceVariables(cliEnvironment(io.env ?? process.env)); // main's own environment is not cleaned; in the backend this changes nothing
|
|
116
|
+
return new Promise(done => {
|
|
117
|
+
const fail = code => done(workspaceFailure(code, terms));
|
|
118
|
+
try {
|
|
119
|
+
(io.exec ?? execFile)(cli.bin, plan.argv, { cwd: plan.cwd, env, shell: false, encoding: 'utf8', timeout: plan.timeout, maxBuffer: WORKSPACE_MAX_BUFFER }, (error, stdout) => {
|
|
120
|
+
if (error?.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER') return fail('E_CLI_OUTPUT_LIMIT');
|
|
121
|
+
if (error?.killed) return fail('E_CLI_TIMEOUT');
|
|
122
|
+
if (typeof stdout !== 'string') return fail(error ? 'E_CLI_FAILED' : 'E_CLI_PROTOCOL');
|
|
123
|
+
if (Buffer.byteLength(stdout, 'utf8') > WORKSPACE_MAX_BUFFER) return fail('E_CLI_OUTPUT_LIMIT');
|
|
124
|
+
let document;
|
|
125
|
+
try { document = JSON.parse(stdout); } catch { return fail(error ? 'E_CLI_FAILED' : 'E_CLI_PROTOCOL'); }
|
|
126
|
+
if (!record(document) || document.schemaVersion !== 1 || typeof document.ok !== 'boolean') return fail('E_CLI_PROTOCOL');
|
|
127
|
+
if (document.ok === false) {
|
|
128
|
+
const reason = document.error;
|
|
129
|
+
if (!record(reason) || typeof reason.code !== 'string' || !/^[A-Z][A-Z0-9_]{0,63}$/.test(reason.code)
|
|
130
|
+
|| typeof reason.message !== 'string' || reason.message.length > 8192) return fail('E_CLI_PROTOCOL');
|
|
131
|
+
// A refusal cannot become success, and a success exit cannot carry one.
|
|
132
|
+
if (!error) return fail('E_CLI_PROTOCOL');
|
|
133
|
+
const out = { code: reason.code, message: reason.message };
|
|
134
|
+
if (options.action === 'onboard' && reason.details?.rolledBack === true) out.rolledBack = true;
|
|
135
|
+
return done({ ok: false, reason: out });
|
|
136
|
+
}
|
|
137
|
+
if (error) return fail('E_CLI_FAILED'); // success is exit 0 only
|
|
138
|
+
done({ ok: true, document });
|
|
139
|
+
});
|
|
140
|
+
} catch { fail('E_CLI_FAILED'); }
|
|
141
|
+
});
|
|
142
|
+
}
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
/** Workspace views (#482): what the switcher lists and a window shows. One view per workspace
|
|
2
|
+
* identity `(key, default team)` its deployments report, matched by the kernel's rules
|
|
3
|
+
* (docs/desktop-cli-api.md, "Matching workspaces across machines" and "Matching teams across
|
|
4
|
+
* machines"), plus one view per deployment that cannot be matched, under that deployment's own id.
|
|
5
|
+
* Pure: no I/O. The identity is the kernel's `workspace` object, read as reported; nothing is
|
|
6
|
+
* derived from a path, a ref or a host name, and `ref` is never compared. */
|
|
7
|
+
import { createHash } from 'node:crypto';
|
|
8
|
+
import { requireTerms } from './client-terms.mjs';
|
|
9
|
+
|
|
10
|
+
const TEXT_MAX = 2048;
|
|
11
|
+
const text = v => typeof v === 'string' && v.length > 0 && v.length <= TEXT_MAX && !v.includes('\0');
|
|
12
|
+
const record = v => !!v && typeof v === 'object' && !Array.isArray(v);
|
|
13
|
+
|
|
14
|
+
/** The identity fields of a reported `workspace` object, validated and copied, or a classification:
|
|
15
|
+
* `{ status: 'none' }` when nothing was reported (null, absent, not an object), `{ status: 'old' }`
|
|
16
|
+
* for a host before 0.36.0 (the reachability-only object has no `key` field), `{ status: 'invalid' }`
|
|
17
|
+
* for a shape the contract does not allow, else `{ status: 'identity', identity }`. */
|
|
18
|
+
export function readIdentity(workspace) {
|
|
19
|
+
if (!record(workspace)) return { status: 'none' };
|
|
20
|
+
if (!Object.hasOwn(workspace, 'key')) return { status: 'old' };
|
|
21
|
+
const { key, ref = null, keyFrom = null, standalone, defaultTeam = null, teams = {}, teamsFrom } = workspace;
|
|
22
|
+
const team = v => v === null || text(v);
|
|
23
|
+
const ok = (key === null || text(key)) && (ref === null || text(ref)) && [null, 'workspace', 'member'].includes(keyFrom)
|
|
24
|
+
&& typeof standalone === 'boolean' && ['observed', 'cache', 'local'].includes(teamsFrom)
|
|
25
|
+
&& (defaultTeam === null || record(defaultTeam) && text(defaultTeam.label) && team(defaultTeam.team))
|
|
26
|
+
&& record(teams) && Object.keys(teams).length <= 256 && Object.entries(teams).every(([label, id]) => text(label) && team(id));
|
|
27
|
+
if (!ok) return { status: 'invalid' };
|
|
28
|
+
return { status: 'identity', identity: { key, ref, keyFrom, standalone, teamsFrom,
|
|
29
|
+
defaultTeam: defaultTeam && { label: defaultTeam.label, team: defaultTeam.team }, teams: { ...teams } } };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** How one identity attaches, by the kernel's rules: `{ key, team, unmapped, note? }` (team null and
|
|
33
|
+
* unmapped true for an unmapped default team, which matches only unmapped), or `{ unattached }` with
|
|
34
|
+
* the reason's key. `note` is information, not a failure (a standalone deployment's local teams). */
|
|
35
|
+
export function attachment(identity) {
|
|
36
|
+
if (!identity) return { unattached: 'no-report' };
|
|
37
|
+
if (identity.keyFrom === 'member') return { unattached: 'member' };
|
|
38
|
+
if (identity.key === null || identity.keyFrom !== 'workspace') return { unattached: 'invalid-ref' };
|
|
39
|
+
const team = identity.defaultTeam?.team ?? null;
|
|
40
|
+
if (identity.teamsFrom === 'local' && !identity.standalone && team === null) return { unattached: 'unknown-team' };
|
|
41
|
+
return { key: identity.key, team, unmapped: team === null,
|
|
42
|
+
...(identity.teamsFrom === 'local' && identity.standalone && team === null ? { note: 'standalone' } : {}) };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** A stable view id for one `(key, team)`: never a path, so it cannot collide with a deployment id. */
|
|
46
|
+
export function viewId(key, team) {
|
|
47
|
+
return `ws:${createHash('sha256').update(JSON.stringify([key, team])).digest('hex').slice(0, 20)}`;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** The kernel's own reason texts where docs/desktop-cli-api.md gives them, else the spec's: the full
|
|
51
|
+
* sentence, the short label (headings, the switcher) and the fix as plain steps. `there` names where
|
|
52
|
+
* the fix runs ("there" for a remote, "in this deployment" for a local one). */
|
|
53
|
+
const REASONS = {
|
|
54
|
+
member: ({ there }) => ({ short: 'Workspace not known yet', detail: 'This deployment\'s workspace reference names a member whose workspace isn\'t known yet; run oats sync there.', fix: [`Run \`oats sync\` ${there}.`] }),
|
|
55
|
+
'invalid-ref': ({ ref }) => ({ short: 'Invalid workspace reference', detail: `This deployment's workspace reference${ref ? ` (${ref})` : ''} isn't valid; fix oats-local.yaml.`,
|
|
56
|
+
fix: [`Fix the workspace reference${ref ? ` (\`${ref}\`)` : ''} in its oats-local.yaml.`] }),
|
|
57
|
+
'unknown-team': ({ there }) => ({ short: 'Workspace not observed yet', detail: 'This host hasn\'t observed its workspace yet; run oats sync there.', fix: [`Run \`oats sync\` ${there}.`] }),
|
|
58
|
+
standalone: () => ({ short: 'Local teams only', detail: 'Teams are local only on this host (standalone).', fix: [] }),
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
/** True when a failed probe's message is ssh's own timeout: the kernel reports an ssh that timed out
|
|
62
|
+
* as E_SSH with ssh's stderr and no code of its own, so ssh's text is the only signal (a documented limit). */
|
|
63
|
+
const TIMED_OUT = /timed out|timeout/i;
|
|
64
|
+
|
|
65
|
+
/** Why a deployment is not live or not matched, or null: `{ short, detail, fix }`. `short` is a few
|
|
66
|
+
* words for a heading or the switcher ("OATS too old to report its workspace"); `detail` the one full
|
|
67
|
+
* sentence; `fix` the plain steps (possibly none: the detail then says what happens next). The steps
|
|
68
|
+
* carry every fact the sentence has (a host, a reference): with steps, a heading shows only them.
|
|
69
|
+
* `d`: `{ local, machine, sshHost?, probe?, identityStatus, attach, ref, cliReadsRemotes, rosterError?, unavailable?, readError? }`.
|
|
70
|
+
* `terms`: the client's own (client-terms.mjs): its name where a sentence names it, and the label of its
|
|
71
|
+
* machine where `d` names none. */
|
|
72
|
+
export function deploymentReasonParts(d, terms) {
|
|
73
|
+
requireTerms(terms, 'deploymentReasonParts');
|
|
74
|
+
const machine = d.machine || terms.thisMachine;
|
|
75
|
+
const updateHere = ['Update OATS on this computer.'];
|
|
76
|
+
if (d.local) {
|
|
77
|
+
if (d.unavailable) return { short: 'Not observed', detail: d.unavailable, fix: [] };
|
|
78
|
+
// A re-read failed and the last observation was kept (packages/desktop/server/oats-web.mjs observeDeployment): the kernel's message.
|
|
79
|
+
if (d.readError) return { short: 'Last read failed', detail: `This deployment's last read failed: ${d.readError}. It shows what was last observed.`, fix: [] };
|
|
80
|
+
if (d.identityStatus === 'feature') return { short: 'OATS here too old to report workspaces', detail: 'This computer\'s OATS is too old to report its workspace; update OATS here.', fix: updateHere };
|
|
81
|
+
if (d.identityStatus === 'old' || d.identityStatus === 'none') return { short: 'Reports no workspace', detail: 'This deployment reports no workspace identity.', fix: [] };
|
|
82
|
+
} else {
|
|
83
|
+
if (d.cliReadsRemotes === false) return { short: 'OATS here can\'t read other machines', detail: 'This computer\'s OATS can\'t read other machines; update OATS here.', fix: updateHere };
|
|
84
|
+
if (d.identityStatus === 'feature' && d.probe?.ok === true) return { short: 'OATS here too old to read workspaces', detail: 'This computer\'s OATS is too old to read other machines\' workspaces; update OATS here.', fix: updateHere };
|
|
85
|
+
if (d.rosterError) return { short: 'Not reached', detail: `${machine} was not reached: ${d.rosterError}`, fix: [] };
|
|
86
|
+
if (d.probe && d.probe.ok !== true) {
|
|
87
|
+
const code = d.probe.error?.code, message = typeof d.probe.error?.message === 'string' ? d.probe.error.message : '';
|
|
88
|
+
if (code === 'E_ROSTER_BUDGET' || code === 'E_CLI_TIMEOUT' || TIMED_OUT.test(message)) return { short: 'Timed out', detail: `${machine} timed out; it is tried again on the next read.`, fix: [] };
|
|
89
|
+
if (code === 'E_SSH') {
|
|
90
|
+
const host = d.sshHost || machine;
|
|
91
|
+
return { short: 'ssh needs a prompt', detail: `${machine} needs ssh to connect without a prompt; run \`ssh ${host}\` once in a terminal.`,
|
|
92
|
+
fix: [`Run \`ssh ${host}\` once in a terminal and answer its prompt (a host key or a password).`, `${terms.name} tries again on its next read.`] };
|
|
93
|
+
}
|
|
94
|
+
return { short: 'Not reached', detail: `${machine} was not reached${code ? ` (${code})` : ''}.`, fix: [] };
|
|
95
|
+
}
|
|
96
|
+
if (d.identityStatus === 'old') return { short: 'OATS too old to report its workspace', detail: `${machine}'s OATS is too old to report its workspace; update OATS there.`, fix: [`Update OATS on ${machine}.`] };
|
|
97
|
+
if (d.identityStatus === 'none') return { short: 'Reports no workspace', detail: `${machine} reports no workspace for this deployment.`, fix: [] };
|
|
98
|
+
}
|
|
99
|
+
if (d.identityStatus === 'invalid') return { short: 'Unreadable workspace report', detail: `${machine} reported a workspace ${terms.self} can't read.`, fix: [] };
|
|
100
|
+
const reason = d.attach?.unattached && REASONS[d.attach.unattached];
|
|
101
|
+
return reason ? reason({ ref: d.ref, there: d.local ? 'in this deployment' : `on ${machine}` }) : null;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** The one plain sentence for a deployment that is not live or not matched, or null. */
|
|
105
|
+
export function deploymentReason(d, terms) {
|
|
106
|
+
requireTerms(terms, 'deploymentReason');
|
|
107
|
+
return deploymentReasonParts(d, terms)?.detail ?? null;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** The last segment of a canonical key: github.com/GreaterSkies/tsm → tsm. */
|
|
111
|
+
const keyTail = key => String(key).split('/').filter(Boolean).pop() || String(key);
|
|
112
|
+
|
|
113
|
+
/** Build the views from the served deployments, in their served order (locals first, as given).
|
|
114
|
+
* `deployments`: `[{ id, local, name, attach }]` where `attach` comes from attachment().
|
|
115
|
+
* Returns `[{ id, name, key, team, teamLabel, unattached, deployments: [id…], primary }]`: attached
|
|
116
|
+
* views first in order of their first deployment, then one view per unattached deployment, under
|
|
117
|
+
* its deployment id (today's id, so nothing saved breaks). */
|
|
118
|
+
export function buildViews(deployments) {
|
|
119
|
+
const attached = new Map(), loose = [];
|
|
120
|
+
for (const d of deployments) {
|
|
121
|
+
if (!d.attach || d.attach.unattached) { loose.push(d); continue; }
|
|
122
|
+
const id = viewId(d.attach.key, d.attach.team);
|
|
123
|
+
if (!attached.has(id)) attached.set(id, { id, key: d.attach.key, team: d.attach.team, teamLabel: d.teamLabel ?? null, members: [] });
|
|
124
|
+
attached.get(id).members.push(d);
|
|
125
|
+
}
|
|
126
|
+
const views = [...attached.values()].map(v => {
|
|
127
|
+
const primary = v.members.find(d => d.local) || v.members[0];
|
|
128
|
+
const localName = v.members.find(d => d.local && d.name)?.name;
|
|
129
|
+
return { id: v.id, name: localName || keyTail(v.key), key: v.key, team: v.team, teamLabel: v.teamLabel,
|
|
130
|
+
unattached: false, deployments: v.members.map(d => d.id), primary: primary.id };
|
|
131
|
+
});
|
|
132
|
+
// The same key with another team is another workspace: both names say which team.
|
|
133
|
+
const byKey = new Map();
|
|
134
|
+
for (const v of views) byKey.set(v.key, [...(byKey.get(v.key) || []), v]);
|
|
135
|
+
for (const same of byKey.values()) {
|
|
136
|
+
if (same.length < 2) continue;
|
|
137
|
+
const labels = same.map(v => v.teamLabel);
|
|
138
|
+
for (const v of same) {
|
|
139
|
+
const label = v.team === null ? 'unmapped'
|
|
140
|
+
: v.teamLabel && labels.filter(l => l === v.teamLabel).length === 1 ? v.teamLabel : v.team;
|
|
141
|
+
v.name = `${v.name} · ${label}`;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
for (const v of views) delete v.teamLabel;
|
|
145
|
+
for (const d of loose) views.push({ id: d.id, name: d.name || d.id, key: null, team: null, unattached: true, deployments: [d.id], primary: d.id });
|
|
146
|
+
return views;
|
|
147
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
# OATS TUI (preview)
|
|
2
|
+
|
|
3
|
+
`oats tui` is the OATS terminal client: one full-screen, keyboard-only program
|
|
4
|
+
for people who work in terminals and on machines with no display. It ships
|
|
5
|
+
inside `@awebai/oats` and is never published on its own.
|
|
6
|
+
|
|
7
|
+
**It is a preview.** This version draws the frame, answers `?` (help) and `q`
|
|
8
|
+
(quit), and reads nothing from the kernel yet; the views arrive in later
|
|
9
|
+
releases. While it is a preview its screens may change without notice.
|
|
10
|
+
|
|
11
|
+
[`docs/tui.md`](../../docs/tui.md) is the reference: how to start it, the keys,
|
|
12
|
+
the complete list of what it changes in the terminal and restores, and what it
|
|
13
|
+
never does.
|
|
14
|
+
|
|
15
|
+
## For developers
|
|
16
|
+
|
|
17
|
+
| path | contents |
|
|
18
|
+
|---|---|
|
|
19
|
+
| `bin/tui.mjs` | the entry `bin/oats.mjs` loads: it imports the whole module graph, then runs `main()` |
|
|
20
|
+
| `lib/main.mjs` | the loop: state, a pure `reduce(state, event)`, render, write |
|
|
21
|
+
| `lib/actions.mjs` | the action table: the reducer and the help both read it |
|
|
22
|
+
| `lib/client.mjs` | the one module that imports the shared readers (`packages/client/`) |
|
|
23
|
+
| `lib/term/keys.mjs` | bytes to key events: a pure parser with an injected clock |
|
|
24
|
+
| `lib/term/width.mjs` | the cells a grapheme takes |
|
|
25
|
+
| `lib/term/text.mjs` | safe text, the only thing the screen draws: `lit()` and `shown()` |
|
|
26
|
+
| `lib/term/style.mjs` | style values: the sixteen ANSI colours and four attributes |
|
|
27
|
+
| `lib/term/screen.mjs` | the cell buffer and the bytes of a frame |
|
|
28
|
+
| `lib/term/tty.mjs` | the guard: enter, leave, signals, suspend, resize, one write per frame |
|
|
29
|
+
| `lib/views/` | pure functions from state and size to rows of safe text |
|
|
30
|
+
|
|
31
|
+
Rules the tests pin (`test/tui-boundary.test.mjs` reads the files):
|
|
32
|
+
|
|
33
|
+
- No dependency, and no import outside `node:` modules, this package and the
|
|
34
|
+
one path in `lib/client.mjs`. No dynamic `import()`.
|
|
35
|
+
- Nothing in `lib/` or `bin/` of the kernel imports this package, except the
|
|
36
|
+
one dynamic import where `bin/oats.mjs` dispatches the word.
|
|
37
|
+
- Only `term/screen.mjs` and `term/tty.mjs` produce an ESC byte. Views are
|
|
38
|
+
pure: no IO, no clock, no escape bytes.
|
|
39
|
+
- The screen takes safe text only. Text the TUI did not write goes through
|
|
40
|
+
`shown()`; `lit()` is for the TUI's own words and refuses anything the
|
|
41
|
+
display filter would change, a run of spaces included, so a row is spans
|
|
42
|
+
placed by column, never one padded string.
|
|
43
|
+
|
|
44
|
+
Tests: `node --test packages/tui/test/*.test.mjs` (no dependency needed), the
|
|
45
|
+
root tests `test/tui-*.test.mjs`, and the end-to-end tests in a real tmux on a
|
|
46
|
+
private socket (`test/tui-terminal.test.mjs`).
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// The entry of `oats tui`, loaded by bin/oats.mjs with one dynamic import.
|
|
2
|
+
// The import below loads every module of packages/tui/lib/ statically, BEFORE the terminal is
|
|
3
|
+
// looked at: `oats tui` with no terminal therefore proves that the installed package holds the
|
|
4
|
+
// whole module graph (scripts/clean-room-smoke.mjs runs exactly that).
|
|
5
|
+
import { main } from "../lib/main.mjs";
|
|
6
|
+
|
|
7
|
+
process.exitCode = await main({ argv: process.argv.slice(2), stdin: process.stdin, stdout: process.stdout, stderr: process.stderr, env: process.env });
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// The action table: what the TUI can do and the keys that do it. The reducer and the help view
|
|
2
|
+
// both read it, so the help cannot name a key the program does not act on. `keys` are key ids
|
|
3
|
+
// (term/keys.mjs keyId); they are the part a user's tui.json will replace.
|
|
4
|
+
export const ACTIONS = Object.freeze([
|
|
5
|
+
{ id: "help", keys: ["?"], label: "help" },
|
|
6
|
+
{ id: "close", keys: ["escape"], label: "close" },
|
|
7
|
+
{ id: "quit", keys: ["q", "ctrl+c"], label: "quit" },
|
|
8
|
+
{ id: "suspend", keys: ["ctrl+z"], label: "suspend" },
|
|
9
|
+
{ id: "redraw", keys: ["ctrl+l"], label: "redraw" },
|
|
10
|
+
].map((action) => Object.freeze({ ...action, keys: Object.freeze([...action.keys]) })));
|
|
11
|
+
|
|
12
|
+
/** key id -> action id. A key bound twice is a defect of the table, refused when it is read. */
|
|
13
|
+
export function bindings(actions = ACTIONS) {
|
|
14
|
+
const map = new Map();
|
|
15
|
+
for (const action of actions) for (const key of action.keys) {
|
|
16
|
+
if (map.has(key)) throw new Error(`key ${key} is bound to ${map.get(key)} and to ${action.id}`);
|
|
17
|
+
map.set(key, action.id);
|
|
18
|
+
}
|
|
19
|
+
return map;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const NAMES = Object.freeze({ escape: "Esc", enter: "Enter", tab: "Tab", backspace: "Backspace", space: "Space", up: "Up", down: "Down", left: "Left", right: "Right", home: "Home", end: "End", pageup: "PageUp", pagedown: "PageDown", insert: "Insert", delete: "Delete", ctrl: "Ctrl", alt: "Alt", shift: "Shift" });
|
|
23
|
+
/** A key id as a person reads it: `ctrl+c` is `Ctrl+C`, `escape` is `Esc`, `?` is `?`. */
|
|
24
|
+
export function keyLabel(key) {
|
|
25
|
+
if (key.length === 1) return key;
|
|
26
|
+
const parts = key.split("+"), last = parts.pop();
|
|
27
|
+
const name = NAMES[last] ?? (/^f\d+$/.test(last) ? last.toUpperCase() : parts.length && last.length === 1 ? last.toUpperCase() : last);
|
|
28
|
+
return [...parts.map((part) => NAMES[part] ?? part), name].join("+");
|
|
29
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
// The ONE module of packages/tui/ that imports the shared client home (packages/client/): the rest
|
|
2
|
+
// of the TUI names no reader path, so what the TUI takes from the shared readers is this list
|
|
3
|
+
// (test/tui-boundary.test.mjs pins it). The filter is the Desktop's own, never a copy.
|
|
4
|
+
export { displayLine, DETAIL_WITHHELD } from "../../client/display-text.mjs";
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
// `oats tui` (preview): the loop. State, a pure reduce(state, event), render, write.
|
|
2
|
+
// This version draws the frame, answers help and quit, and reads nothing from the kernel:
|
|
3
|
+
// what it delivers is the terminal layer the views will stand on (docs/tui.md).
|
|
4
|
+
import { ACTIONS, bindings } from "./actions.mjs";
|
|
5
|
+
import { displayLine } from "./client.mjs";
|
|
6
|
+
import { createKeyParser, keyId } from "./term/keys.mjs";
|
|
7
|
+
import { createScreen, glyphs } from "./term/screen.mjs";
|
|
8
|
+
import { colorEnabled } from "./term/style.mjs";
|
|
9
|
+
import { createGuard, isTerminal } from "./term/tty.mjs";
|
|
10
|
+
import { frame } from "./views/frame.mjs";
|
|
11
|
+
|
|
12
|
+
export const USAGE = "oats tui [--ascii]";
|
|
13
|
+
const HELP = `Usage:
|
|
14
|
+
${USAGE}
|
|
15
|
+
|
|
16
|
+
The OATS terminal client (preview): a full-screen view of a deployment's agents.
|
|
17
|
+
This version draws the frame only. Keys: ? help, q quit. docs/tui.md has the rest.
|
|
18
|
+
|
|
19
|
+
--ascii draw rules and marks in ASCII, whatever the locale
|
|
20
|
+
`;
|
|
21
|
+
export const NO_TERMINAL = "oats: `oats tui` needs a terminal on stdin and stdout (E_NO_TERMINAL); `oats status` prints the instances once";
|
|
22
|
+
|
|
23
|
+
/** The arguments of this version: `--ascii`, `--help`/`-h`. Everything else is refused, `--dir`
|
|
24
|
+
* and `--server` included: it reads no deployment yet. */
|
|
25
|
+
export function parseArgs(argv) {
|
|
26
|
+
const options = { ascii: false, help: false };
|
|
27
|
+
for (const arg of argv) {
|
|
28
|
+
if (arg === "--ascii") options.ascii = true;
|
|
29
|
+
else if (arg === "--help" || arg === "-h") options.help = true;
|
|
30
|
+
// The argument is echoed only when it is plain: this line goes to a terminal.
|
|
31
|
+
else return { error: `oats: \`oats tui\` takes no argument ${/^[\x21-\x7e]{1,40}$/.test(arg) ? arg : "like that one"} (E_BAD_ARGS); usage: ${USAGE}` };
|
|
32
|
+
}
|
|
33
|
+
return { options };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export const initialState = ({ ascii = false, actions = ACTIONS } = {}) => Object.freeze({ view: "frame", ascii, actions });
|
|
37
|
+
|
|
38
|
+
/** (state, event) -> { state, effect }. Pure. An event is `{ key: <key id> }` or `{ paste }`;
|
|
39
|
+
* an effect is something only the loop can do: "quit", "suspend", "redraw", or null.
|
|
40
|
+
* A paste is dropped whole: nothing in it is a key. */
|
|
41
|
+
export function reduce(state, event, keymap = bindings(state.actions)) {
|
|
42
|
+
const stay = { state, effect: null };
|
|
43
|
+
if (typeof event.key !== "string") return stay;
|
|
44
|
+
switch (keymap.get(event.key)) {
|
|
45
|
+
case "help": return { state: Object.freeze({ ...state, view: state.view === "help" ? "frame" : "help" }), effect: null };
|
|
46
|
+
case "close": return state.view === "help" ? { state: Object.freeze({ ...state, view: "frame" }), effect: null } : stay;
|
|
47
|
+
case "quit": return { state, effect: "quit" };
|
|
48
|
+
case "suspend": return { state, effect: "suspend" };
|
|
49
|
+
case "redraw": return { state, effect: "redraw" };
|
|
50
|
+
default: return stay;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** An error as lines fit for a terminal: its stack, each line through the display filter. */
|
|
55
|
+
function errorLines(error) {
|
|
56
|
+
const text = error instanceof Error ? error.stack || error.message : String(error);
|
|
57
|
+
return String(text).split("\n", 12).map((line) => displayLine(line)).filter(Boolean);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Run. Resolves with the exit status; never calls process.exit, so what was written drains. */
|
|
61
|
+
export async function main({ argv, stdin, stdout, stderr, env, proc = process, now = Date.now, setTimer = setTimeout, clearTimer = clearTimeout }) {
|
|
62
|
+
const { options, error } = parseArgs(argv);
|
|
63
|
+
if (error) { stderr.write(`${error}\n`); return 1; }
|
|
64
|
+
if (options.help) { stdout.write(HELP); return 0; }
|
|
65
|
+
if (!isTerminal({ stdin, stdout, env })) { stderr.write(`${NO_TERMINAL}\n`); return 1; }
|
|
66
|
+
|
|
67
|
+
const look = glyphs(env, { ascii: options.ascii });
|
|
68
|
+
const screen = createScreen({ ...look, color: colorEnabled(env) });
|
|
69
|
+
const parser = createKeyParser({ now });
|
|
70
|
+
let state = initialState({ ascii: look.ascii });
|
|
71
|
+
const keymap = bindings(state.actions);
|
|
72
|
+
let full = true, escTimer = null;
|
|
73
|
+
|
|
74
|
+
const guard = createGuard({
|
|
75
|
+
stdin, stdout, proc, setTimer, clearTimer,
|
|
76
|
+
frame() { const bytes = screen.render(frame(state, guard.size()), guard.size(), { full }); full = false; return bytes; },
|
|
77
|
+
onInput(bytes) { act(parser.feed(bytes)); watchEscape(); },
|
|
78
|
+
onResize() { full = true; guard.draw(); },
|
|
79
|
+
onRedraw() { full = true; guard.draw(); },
|
|
80
|
+
});
|
|
81
|
+
function act(events) {
|
|
82
|
+
for (const event of events) {
|
|
83
|
+
const next = reduce(state, "paste" in event ? { paste: true } : { key: keyId(event) }, keymap);
|
|
84
|
+
state = next.state;
|
|
85
|
+
if (next.effect === "quit") return guard.finish(0);
|
|
86
|
+
if (next.effect === "suspend") guard.suspend();
|
|
87
|
+
if (next.effect === "redraw") guard.reassert(); // the modes again, then the whole screen
|
|
88
|
+
}
|
|
89
|
+
guard.draw();
|
|
90
|
+
}
|
|
91
|
+
/** A lone ESC is the Esc key once nothing has followed it for the parser's timeout. */
|
|
92
|
+
function watchEscape() {
|
|
93
|
+
if (escTimer !== null) { clearTimer(escTimer); escTimer = null; }
|
|
94
|
+
const due = parser.timeoutAt();
|
|
95
|
+
if (due !== null) escTimer = setTimer(() => { escTimer = null; guard.attempt(() => { act(parser.expire()); watchEscape(); }); }, Math.max(0, due - now()));
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
guard.start();
|
|
99
|
+
guard.attempt(() => guard.draw());
|
|
100
|
+
const end = await guard.done;
|
|
101
|
+
if (escTimer !== null) clearTimer(escTimer);
|
|
102
|
+
// After the alternate screen is left, so the message stays on the screen the user returns to.
|
|
103
|
+
if (end.error !== undefined) stderr.write(`oats: \`oats tui\` stopped on an internal error; the terminal was restored\n${errorLines(end.error).map((line) => ` ${line}\n`).join("")}`);
|
|
104
|
+
return end.status;
|
|
105
|
+
}
|