@awebai/oats 0.51.0 → 0.53.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 +3 -1
- package/bin/oats.mjs +407 -123
- package/docs/capabilities.md +75 -6
- package/docs/configuration.md +200 -91
- package/docs/desktop-cli-api.md +1563 -113
- package/docs/desktop-instance-start.md +69 -0
- package/docs/desktop.md +10 -7
- package/docs/execution-targets.md +145 -58
- package/docs/first-team.md +3 -1
- package/docs/harness-trust.md +50 -2
- package/docs/implementation.md +238 -17
- package/docs/integrations.md +13 -9
- 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 +25 -2
- package/docs/launch-prompt-completion.md +50 -48
- package/docs/macos-test-runs.md +246 -0
- package/docs/oats-local.schema.json +4 -3
- package/docs/official-catalog.md +5 -5
- package/docs/packages.md +14 -14
- package/docs/release-lane.md +225 -11
- package/docs/release-notes/v0.44.0.md +1 -1
- package/docs/release-notes/v0.52.0.md +933 -0
- package/docs/release-notes/v0.53.0.md +1274 -0
- package/docs/schedules.md +97 -4
- package/docs/souls-and-instances.md +332 -40
- package/docs/tui.md +584 -0
- package/docs/upgrading.md +298 -0
- package/docs/workspaces.md +3 -3
- package/lib/automations.mjs +22 -22
- package/lib/claim.mjs +278 -49
- package/lib/config-data.mjs +4 -1
- package/lib/core.mjs +1282 -289
- package/lib/errors.mjs +170 -0
- package/lib/harness-trust-write.mjs +68 -27
- package/lib/harness-trust.mjs +34 -16
- package/lib/instance-events.mjs +19 -1
- package/lib/instance-git.mjs +39 -3
- package/lib/instance-inspect.mjs +45 -17
- package/lib/instance-lifecycle.mjs +306 -57
- package/lib/instance-resolution.mjs +59 -6
- package/lib/launch-preference.mjs +236 -9
- 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/local-edit.mjs +118 -0
- package/lib/packages.mjs +13 -4
- package/lib/pi-bridge.mjs +308 -0
- package/lib/refused-text.mjs +11 -0
- package/lib/remote.mjs +190 -25
- package/lib/resolve.mjs +2 -1
- package/lib/retained-after-retire.mjs +2 -2
- package/lib/retire-output.mjs +12 -1
- package/lib/schedule-host.mjs +125 -22
- package/lib/schedule.mjs +73 -24
- package/lib/shell-word.mjs +13 -0
- package/lib/soul-launch-verbs.mjs +153 -0
- package/lib/stable-node.mjs +62 -0
- package/lib/system-tools.mjs +39 -0
- package/lib/teams-verbs.mjs +18 -46
- package/lib/tmux-server-scope.mjs +62 -0
- package/lib/triggers.mjs +4 -4
- package/lib/workspace.mjs +54 -30
- package/lib/worktree-hooks.mjs +98 -20
- package/lib/worktree.mjs +83 -24
- package/package-catalog.json +4 -4
- package/package.json +8 -2
- package/packages/client/attach-exit.mjs +25 -0
- package/packages/client/capability-show-contract.mjs +230 -0
- package/packages/client/capability-warnings-contract.mjs +57 -0
- package/packages/client/cli-adapter.mjs +561 -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 +72 -0
- package/packages/client/deployment-data.mjs +483 -0
- package/packages/client/deployment-facts.mjs +95 -0
- package/packages/client/deployment-label.mjs +76 -0
- package/packages/client/deployment-observer.mjs +89 -0
- package/packages/client/deployment-panel.mjs +180 -0
- package/packages/client/deployment-read-cli.mjs +57 -0
- package/packages/client/display-text.mjs +50 -0
- package/packages/client/harness-names.mjs +30 -0
- package/packages/client/inspect-contract.mjs +62 -0
- package/packages/client/instance-acts.mjs +90 -0
- package/packages/client/instance-admission.mjs +45 -0
- package/packages/client/instance-events-contract.mjs +76 -0
- package/packages/client/instance-git-contract.mjs +80 -0
- package/packages/client/instance-presentation.mjs +86 -0
- package/packages/client/instance-tree.mjs +462 -0
- package/packages/client/kernel-environment.mjs +11 -0
- package/packages/client/kernel-lines.mjs +31 -0
- package/packages/client/kernel-made.mjs +23 -0
- package/packages/client/launch-contract.mjs +51 -0
- package/packages/client/launch-prompt-outcome.mjs +200 -0
- package/packages/client/lifecycle-cli.mjs +61 -0
- package/packages/client/lifecycle-contract.mjs +413 -0
- package/packages/client/liveness-main.mjs +10 -0
- package/packages/client/liveness.mjs +48 -0
- package/packages/client/machine-contract.mjs +123 -0
- package/packages/client/own-codes.mjs +31 -0
- package/packages/client/own-environment.mjs +22 -0
- package/packages/client/panel-views.mjs +293 -0
- package/packages/client/readiness-contract.mjs +174 -0
- package/packages/client/refresh-loop.mjs +52 -0
- package/packages/client/remote-address.mjs +151 -0
- package/packages/client/remote-identity-memory.mjs +94 -0
- package/packages/client/remote-roster.mjs +153 -0
- package/packages/client/roster-sections.mjs +80 -0
- package/packages/client/session-attach.mjs +175 -0
- package/packages/client/spawn-apply-cli.mjs +104 -0
- package/packages/client/spawn-apply-contract.mjs +195 -0
- package/packages/client/spawn-decision.mjs +46 -0
- package/packages/client/spawn-messages.mjs +142 -0
- package/packages/client/spawn-preview-cli.mjs +38 -0
- package/packages/client/spawn-preview-contract.mjs +318 -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/terminal-exec.mjs +21 -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-choices.mjs +95 -0
- package/packages/client/workspace-cli.mjs +142 -0
- package/packages/client/workspace-views.mjs +183 -0
- package/packages/record/README.md +21 -0
- package/packages/record/bin/setup.mjs +108 -15
- package/packages/tui/README.md +64 -0
- package/packages/tui/bin/tui.mjs +7 -0
- package/packages/tui/lib/actions.mjs +44 -0
- package/packages/tui/lib/client.mjs +35 -0
- package/packages/tui/lib/config.mjs +151 -0
- package/packages/tui/lib/main.mjs +176 -0
- package/packages/tui/lib/model.mjs +392 -0
- package/packages/tui/lib/read.mjs +473 -0
- package/packages/tui/lib/store.mjs +364 -0
- package/packages/tui/lib/term/keys.mjs +367 -0
- package/packages/tui/lib/term/screen.mjs +134 -0
- package/packages/tui/lib/term/style.mjs +43 -0
- package/packages/tui/lib/term/text.mjs +109 -0
- package/packages/tui/lib/term/tty.mjs +178 -0
- package/packages/tui/lib/term/width.mjs +124 -0
- package/packages/tui/lib/views/detail.mjs +46 -0
- package/packages/tui/lib/views/frame.mjs +256 -0
- package/packages/tui/lib/views/help.mjs +140 -0
- package/packages/tui/lib/views/instances.mjs +137 -0
- package/packages/tui/lib/views/scroll.mjs +19 -0
- package/packages/tui/lib/views/switcher.mjs +97 -0
- package/packages/tui/package.json +8 -0
- package/skills/oats-getting-started/SKILL.md +30 -23
- 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,561 @@
|
|
|
1
|
+
// OATS desktop — CLI JSON v1 adapter (the ONLY mutation path).
|
|
2
|
+
// Read-only K1 Git reads also use this adapter, with strict read exits.
|
|
3
|
+
//
|
|
4
|
+
// Runs the two Desktop v1 mutations through a discovered absolute `oats`
|
|
5
|
+
// binary via execFile/argv — never a shell, never kernel imports:
|
|
6
|
+
//
|
|
7
|
+
// 1. oats spawn <agent> --dir <workspace> --task-file <0600-temp>
|
|
8
|
+
// [allowlisted purpose/repo/work/harness/model args] --json
|
|
9
|
+
// 2. oats operation run <layer>:<operation> --home <resolved home> --json
|
|
10
|
+
//
|
|
11
|
+
// JSON mode emits exactly one stdout object (progress goes to stderr):
|
|
12
|
+
// success: {"schemaVersion":1,"ok":true,"result":{...}}
|
|
13
|
+
// failure: {"schemaVersion":1,"ok":false,"error":{"code","message"}}
|
|
14
|
+
//
|
|
15
|
+
// SECURITY:
|
|
16
|
+
// * The task text is user input destined for a file the spawned agent
|
|
17
|
+
// reads. It is written to a mkdtemp-owned file created 0600 (mode set at
|
|
18
|
+
// open, not chmod-after) so no other local user can read a task that may
|
|
19
|
+
// contain secrets; the temp dir is removed after the CLI returns.
|
|
20
|
+
// * Spawn argv is an ALLOWLIST — purpose/repo/work/harness/model only,
|
|
21
|
+
// values passed as separate argv entries (no interpolation). Anything
|
|
22
|
+
// else the renderer sends is dropped, never forwarded.
|
|
23
|
+
// * A provider operation names its instance by --home: the home of
|
|
24
|
+
// exactly one row the server reports (packages/desktop/server/capabilities.mjs), never
|
|
25
|
+
// a caller path.
|
|
26
|
+
import { execFile } from "node:child_process";
|
|
27
|
+
import { mkdtempSync, openSync, writeSync, closeSync, rmSync } from "node:fs";
|
|
28
|
+
import { tmpdir } from "node:os";
|
|
29
|
+
import { isAbsolute, join } from "node:path";
|
|
30
|
+
import { gitFileId, gitRevision, gitIndexRevision, gitObservation } from './instance-git-contract.mjs';
|
|
31
|
+
import { validMaxAge, maxAgeArgv } from './deployment-contract.mjs';
|
|
32
|
+
import { MACHINE_ID, machineFieldProblem } from './machine-contract.mjs';
|
|
33
|
+
import { kernelMade } from './kernel-made.mjs';
|
|
34
|
+
|
|
35
|
+
const ENVELOPE_TIMEOUT_MS = 60_000;
|
|
36
|
+
|
|
37
|
+
/** Parse the single-JSON-object stdout contract; null when contaminated.
|
|
38
|
+
* The error of an `ok: false` envelope is marked the kernel's here (kernel-made.mjs), where the CLI's
|
|
39
|
+
* answer is parsed and nowhere else: an envelope a reader writes itself (a timeout, a protocol failure,
|
|
40
|
+
* `parseRetireEnvelope`'s incomplete cleanup) is never parsed, so its error carries no mark. */
|
|
41
|
+
export function parseEnvelope(stdout) {
|
|
42
|
+
try {
|
|
43
|
+
const doc = JSON.parse(String(stdout));
|
|
44
|
+
if (!doc || typeof doc !== "object" || doc.schemaVersion !== 1) return null;
|
|
45
|
+
if (doc.ok === true && doc.result && typeof doc.result === "object") return doc;
|
|
46
|
+
if (doc.ok === false && doc.error && typeof doc.error === "object") { kernelMade(doc.error); return doc; }
|
|
47
|
+
return null;
|
|
48
|
+
} catch { return null; }
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Allowlisted optional spawn args → argv pairs. Unknown keys are DROPPED.
|
|
52
|
+
* SECURITY (review 53a20c7): values are also SHAPE-VALIDATED — the CLI
|
|
53
|
+
* parser scans raw argv with includes()/indexOf(), so an option-shaped
|
|
54
|
+
* value like purpose="--no-launch" would inject a real non-allowlisted
|
|
55
|
+
* token. Reject any value with a leading '-'; constrain each field to its
|
|
56
|
+
* domain. Rejection THROWS (E_BAD_ARGS shape) so a hostile value can never
|
|
57
|
+
* silently degrade into different spawn behavior. */
|
|
58
|
+
const SPAWN_ARG_RULES = {
|
|
59
|
+
purpose: { flag: "--purpose", re: /^[a-z0-9][a-z0-9-]*$/i }, // instance-name slug
|
|
60
|
+
repo: { flag: "--repo", re: /^[^-][^\0]*$/ }, // path — anything not option-shaped
|
|
61
|
+
work: { flag: "--work", re: /^(worktree|checkout|attached|workspace|directory)$/ },
|
|
62
|
+
backend: { flag: "--backend", re: /^tmux$/ },
|
|
63
|
+
// The flag is the kernel's (harness-names.mjs harnessFlag): the caller names it, never guessed.
|
|
64
|
+
harness: { flag: null, re: /^(pi|claude|codex)$/ },
|
|
65
|
+
launchConfig: { flag: "--launch-config", re: /^[a-z0-9][a-z0-9._-]*$/i },
|
|
66
|
+
server: { flag: "--server", re: /^[a-z0-9][a-z0-9-]{0,63}$/ }, // registered server id (remote route)
|
|
67
|
+
model: { flag: "--model", re: /^[^-][^\0]*$/ }, // model pattern — not option-shaped
|
|
68
|
+
// Spawn-time agent relations (feature/agent-relations): the kernel links
|
|
69
|
+
// the new instance to an existing one. "unrelated" is the default and is
|
|
70
|
+
// NEVER forwarded — the CLI treats absence as unrelated.
|
|
71
|
+
relation: { flag: "--relation", re: /^(child|sibling|parent)$/ },
|
|
72
|
+
relativeTo: { flag: "--relative-to", re: /^[a-z0-9][a-z0-9._-]*$/i }, // instance-name slug
|
|
73
|
+
// Anchor disambiguation (kernel contract addition): the agents root the
|
|
74
|
+
// anchor homes in. Names shadow across roots, so the desktop ALWAYS sends
|
|
75
|
+
// the pair when it spawns related — path-shaped, never option-shaped.
|
|
76
|
+
relativeRoot: { flag: "--relative-root", re: /^[^-][^\0]*$/ },
|
|
77
|
+
};
|
|
78
|
+
export function spawnArgv(agent, workspaceDir, taskFile, opts = {}) {
|
|
79
|
+
const agentName = String(agent);
|
|
80
|
+
if (agentName.startsWith("-")) { const e = new Error(`invalid agent name "${agentName}"`); e.code = "E_BAD_ARGS"; throw e; }
|
|
81
|
+
// Relation flags travel as a PAIR: a relation needs a reference instance
|
|
82
|
+
// and a reference instance is meaningless without a relation. "unrelated"
|
|
83
|
+
// normalizes to absence before the pairing check.
|
|
84
|
+
if (opts.relation === "unrelated" || opts.relation === "") opts = { ...opts, relation: undefined };
|
|
85
|
+
const hasRelation = opts.relation !== undefined && opts.relation !== null;
|
|
86
|
+
const hasRef = opts.relativeTo !== undefined && opts.relativeTo !== null && opts.relativeTo !== "";
|
|
87
|
+
if (hasRelation !== hasRef) {
|
|
88
|
+
const e = new Error(hasRelation
|
|
89
|
+
? "a relation requires --relative-to <instance>"
|
|
90
|
+
: "--relative-to requires a relation (child|sibling|parent)");
|
|
91
|
+
e.code = "E_BAD_ARGS"; throw e;
|
|
92
|
+
}
|
|
93
|
+
// relativeRoot rides along with the pair only — alone it is meaningless
|
|
94
|
+
if (!hasRef && opts.relativeRoot !== undefined && opts.relativeRoot !== null && opts.relativeRoot !== "") {
|
|
95
|
+
const e = new Error("--relative-root requires --relation and --relative-to");
|
|
96
|
+
e.code = "E_BAD_ARGS"; throw e;
|
|
97
|
+
}
|
|
98
|
+
// A remote route takes its workspace from the server registration; the
|
|
99
|
+
// kernel refuses --dir with --server, so it is omitted here.
|
|
100
|
+
const argv = opts.server
|
|
101
|
+
? ["spawn", agentName, "--task-file", String(taskFile)]
|
|
102
|
+
: ["spawn", agentName, "--dir", String(workspaceDir), "--task-file", String(taskFile)];
|
|
103
|
+
for (const [key, rule] of Object.entries(SPAWN_ARG_RULES)) {
|
|
104
|
+
const v = opts[key];
|
|
105
|
+
if (v === undefined || v === null || v === "") continue;
|
|
106
|
+
const s = String(v);
|
|
107
|
+
if (!rule.re.test(s)) { const e = new Error(`invalid ${key} value`); e.code = "E_BAD_ARGS"; throw e; }
|
|
108
|
+
argv.push(key === "harness" ? flagFor(opts.harnessFlag) : rule.flag, s);
|
|
109
|
+
}
|
|
110
|
+
if (opts.yolo !== undefined) {
|
|
111
|
+
if (typeof opts.yolo !== "boolean") throw Object.assign(new Error("yolo must be a boolean"), { code: "E_BAD_ARGS" });
|
|
112
|
+
argv.push(opts.yolo ? "--yolo" : "--no-yolo");
|
|
113
|
+
}
|
|
114
|
+
argv.push("--json");
|
|
115
|
+
return argv;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Write task text to a fresh 0600 file inside a private mkdtemp dir.
|
|
119
|
+
* Returns { file, cleanup } — callers MUST call cleanup() when done. */
|
|
120
|
+
export function writeTaskFile(taskText, io = {}) {
|
|
121
|
+
const mkdtemp = io.mkdtempSync || mkdtempSync;
|
|
122
|
+
const open = io.openSync || openSync;
|
|
123
|
+
const write = io.writeSync || writeSync;
|
|
124
|
+
const close = io.closeSync || closeSync;
|
|
125
|
+
const rm = io.rmSync || rmSync;
|
|
126
|
+
const dir = mkdtemp(join(io.tmpdir ? io.tmpdir() : tmpdir(), "oats-desktop-task-"));
|
|
127
|
+
const file = join(dir, "TASK.md");
|
|
128
|
+
const cleanup = () => { try { rm(dir, { recursive: true, force: true }); } catch { /* best-effort */ } };
|
|
129
|
+
try {
|
|
130
|
+
const fd = open(file, "wx", 0o600); // create-exclusive, owner-only from birth
|
|
131
|
+
try {
|
|
132
|
+
const text = String(taskText ?? "");
|
|
133
|
+
if (write(fd, text) !== Buffer.byteLength(text)) throw Object.assign(new Error('Could not write the complete private instruction file'), { code: 'E_INPUT_PREPARATION' });
|
|
134
|
+
} finally { close(fd); }
|
|
135
|
+
} catch (error) { cleanup(); throw error; } // construction failure must not orphan private input
|
|
136
|
+
return { file, cleanup };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** A client's own `exec`: `io.exec` on every kernel caller of this home (`exec` in the third argument
|
|
140
|
+
* of lifecycle-cli.mjs `cliLifecycle`), in place of `execFile`. It has `execFile`'s signature,
|
|
141
|
+
* `(bin, argv, options, callback)`, and its return, the child (spawn-apply-cli.mjs ends a spawn it
|
|
142
|
+
* owns through it). It passes the options through as given (cwd, env, timeout, maxBuffer, no shell)
|
|
143
|
+
* and calls back with `execFile`'s own error: every caller tells a timeout by `error.killed` and an
|
|
144
|
+
* overflow by `error.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER'`, so an `exec` that wraps or
|
|
145
|
+
* replaces that error turns both into a plain failure. */
|
|
146
|
+
function runJson(bin, argv, { cwd, exec = execFile, timeout = ENVELOPE_TIMEOUT_MS, parse = parseEnvelope, strictExit = false } = {}) {
|
|
147
|
+
return new Promise((resolveP, rejectP) => {
|
|
148
|
+
try {
|
|
149
|
+
exec(bin, argv, { cwd, encoding: "utf8", timeout, maxBuffer: 4 * 1024 * 1024, shell: false },
|
|
150
|
+
(err, stdout) => {
|
|
151
|
+
// New reads require a clean exit for success. Keep the historical
|
|
152
|
+
// envelope-wins policy for existing mutations unless opted in.
|
|
153
|
+
if (strictExit && err?.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER") return resolveP(readError("E_CLI_OUTPUT_LIMIT"));
|
|
154
|
+
if (strictExit && err?.killed) return resolveP(readError("E_CLI_TIMEOUT"));
|
|
155
|
+
const doc = parse(stdout);
|
|
156
|
+
if (strictExit && err && doc?.ok !== false) return resolveP(readError("E_CLI_FAILED"));
|
|
157
|
+
if (doc) return resolveP(doc); // a nonzero exit may still carry ok:false
|
|
158
|
+
if (err && err.killed) {
|
|
159
|
+
return resolveP({ schemaVersion: 1, ok: false, error: { code: "E_CLI_TIMEOUT", message: `oats did not answer within ${timeout / 1000}s` } });
|
|
160
|
+
}
|
|
161
|
+
return resolveP({
|
|
162
|
+
schemaVersion: 1, ok: false,
|
|
163
|
+
error: { code: "E_CLI_PROTOCOL", message: "oats did not print a valid JSON envelope on stdout" },
|
|
164
|
+
});
|
|
165
|
+
});
|
|
166
|
+
} catch (e) {
|
|
167
|
+
if (strictExit) resolveP(readError("E_CLI_FAILED"));
|
|
168
|
+
else rejectP(e);
|
|
169
|
+
}
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// Only these diagnostics cross the new read boundary. Neither stderr, thrown
|
|
174
|
+
// exception text nor free-form CLI error messages are suitable UI diagnostics.
|
|
175
|
+
const READ_ERRORS = {
|
|
176
|
+
E_BAD_ARGS: "Invalid CLI read arguments",
|
|
177
|
+
E_CLI_FAILED: "The installed OATS CLI could not complete this read",
|
|
178
|
+
E_CLI_PROTOCOL: "The installed OATS CLI returned an invalid read response",
|
|
179
|
+
E_CLI_TIMEOUT: "The installed OATS CLI read timed out",
|
|
180
|
+
E_CLI_OUTPUT_LIMIT: "The installed OATS CLI read exceeded the output limit",
|
|
181
|
+
E_USAGE: "The installed OATS CLI does not support this read command",
|
|
182
|
+
};
|
|
183
|
+
function readError(code) {
|
|
184
|
+
if (!Object.hasOwn(READ_ERRORS, code)) code = "E_CLI_FAILED";
|
|
185
|
+
return { schemaVersion: 1, ok: false, error: { code, message: READ_ERRORS[code] } };
|
|
186
|
+
}
|
|
187
|
+
const readObject = value => !!value && typeof value === "object" && !Array.isArray(value);
|
|
188
|
+
const absoluteReadPath = value => typeof value === "string" && isAbsolute(value) && !value.includes("\0");
|
|
189
|
+
|
|
190
|
+
const GIT_READ_ERRORS = {
|
|
191
|
+
E_BAD_ARGS: 'Invalid instance Git read arguments',
|
|
192
|
+
E_GIT_FAILED: 'The installed OATS CLI could not read this Git worktree',
|
|
193
|
+
E_NO_WORKTREE: 'This instance has no available Git worktree',
|
|
194
|
+
E_SESSION_UNKNOWN: 'The instance is no longer available; refresh the roster',
|
|
195
|
+
E_AMBIGUOUS_INSTANCE: 'The instance is ambiguous; select a uniquely reported instance',
|
|
196
|
+
E_HOME_MISMATCH: 'The selected instance address no longer matches',
|
|
197
|
+
E_STALE_OBSERVATION: 'The worktree observation changed; re-observe before selecting a diff',
|
|
198
|
+
'unsupported-action': 'This CLI does not support Git inspection for this captured target',
|
|
199
|
+
};
|
|
200
|
+
export function gitReadFailure(code, details) {
|
|
201
|
+
const error = Object.hasOwn(GIT_READ_ERRORS, code) ? { code, message: GIT_READ_ERRORS[code] } : readError(code).error;
|
|
202
|
+
const observation = code === 'E_STALE_OBSERVATION' && gitObservation(details?.observation);
|
|
203
|
+
return { schemaVersion: 1, ok: false, error: { ...error, ...(observation ? { details: { observation } } : {}) } };
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** K1 read adapter. Not a roster resolver: only the server boundary may supply
|
|
207
|
+
* the instance/home/context triple. The boundary requires the hardened K1
|
|
208
|
+
* contract. No direct Git command or renderer path arguments. */
|
|
209
|
+
/** A remote read's CLI deadline: ssh's ConnectTimeout (15 s) plus the command. */
|
|
210
|
+
export const REMOTE_GIT_TIMEOUT = 45_000;
|
|
211
|
+
export async function cliInstanceGit(bin, options = {}, io = {}) {
|
|
212
|
+
try {
|
|
213
|
+
// `server`: a remote row, sent as `--server S --home H` (no --dir); `context` is then this machine's cwd.
|
|
214
|
+
const base = ['action', 'instance', 'context', 'home', 'server'];
|
|
215
|
+
const diff = options?.action === 'diff';
|
|
216
|
+
const allowed = diff ? [...base, 'fileId', 'revision', 'indexRevision'] : base;
|
|
217
|
+
if (!absoluteReadPath(bin) || !readObject(options) || !['git', 'diff'].includes(options.action)
|
|
218
|
+
|| Object.keys(options).some(k => !allowed.includes(k))
|
|
219
|
+
|| typeof options.instance !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(options.instance)
|
|
220
|
+
|| !absoluteReadPath(options.context) || !absoluteReadPath(options.home)
|
|
221
|
+
|| (Object.hasOwn(options, 'server') && (typeof options.server !== 'string' || !/^[a-z0-9][a-z0-9-]{0,63}$/.test(options.server)))
|
|
222
|
+
|| (diff && (!gitFileId(options.fileId) || !gitRevision(options.revision) || !gitIndexRevision(options.indexRevision)))) return gitReadFailure('E_BAD_ARGS');
|
|
223
|
+
const remote = Object.hasOwn(options, 'server');
|
|
224
|
+
const argv = ['instance', options.action, options.instance, ...(remote ? ['--server', options.server] : ['--dir', options.context]), '--home', options.home];
|
|
225
|
+
if (diff) argv.push('--file', options.fileId, '--revision', options.revision, '--index-revision', options.indexRevision);
|
|
226
|
+
argv.push('--json');
|
|
227
|
+
const limit = remote ? REMOTE_GIT_TIMEOUT : 15_000;
|
|
228
|
+
const timeout = Number.isFinite(io.timeout) && io.timeout > 0 ? Math.min(io.timeout, limit) : limit;
|
|
229
|
+
const result = await runJson(bin, argv, { cwd: options.context, exec: io.exec, timeout, strictExit: true });
|
|
230
|
+
if (result.ok) return result;
|
|
231
|
+
// A host's refusal keeps its own code and message (the boundary bounds and shows them); this machine's own failures do not.
|
|
232
|
+
if (remote && !Object.hasOwn(READ_ERRORS, result.error?.code) && result.error?.code !== 'E_STALE_OBSERVATION') return { schemaVersion: 1, ok: false, error: { code: result.error?.code, message: result.error?.message } };
|
|
233
|
+
return gitReadFailure(result.error?.code, result.error?.details);
|
|
234
|
+
} catch { return gitReadFailure('E_CLI_FAILED'); }
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* Desktop v1 spawn. `bin` is the discovered absolute CLI; `workspaceDir` the
|
|
239
|
+
* validated workspace context (--dir); `opts` allowlisted extras.
|
|
240
|
+
* Domain results RESOLVE (never reject) with the envelope — stable codes.
|
|
241
|
+
*/
|
|
242
|
+
export async function cliSpawn(bin, { agent, workspaceDir, task, ...opts }, io = {}) {
|
|
243
|
+
let argv;
|
|
244
|
+
let wake;
|
|
245
|
+
try {
|
|
246
|
+
argv = spawnArgv(agent, workspaceDir, "__TASKFILE__", opts);
|
|
247
|
+
if (opts.wake !== undefined) {
|
|
248
|
+
const value = opts.wake;
|
|
249
|
+
if (!value || typeof value !== "object" || Array.isArray(value)
|
|
250
|
+
|| !["cron", "tz", "message"].every(k => typeof value[k] === "string" && value[k].trim() && !value[k].includes("\0"))
|
|
251
|
+
|| (value.enabled !== undefined && typeof value.enabled !== "boolean")) {
|
|
252
|
+
throw Object.assign(new Error("Specify the wake cron, time zone, and message"), { code: "E_BAD_ARGS" });
|
|
253
|
+
}
|
|
254
|
+
wake = { cron: value.cron, tz: value.tz, message: value.message, enabled: value.enabled ?? true };
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
catch (e) {
|
|
258
|
+
// Validation failures resolve as domain errors (stable codes), never throw
|
|
259
|
+
// — the endpoint maps them like CLI envelope failures.
|
|
260
|
+
return { schemaVersion: 1, ok: false, error: { code: e.code || "E_BAD_ARGS", message: e.message } };
|
|
261
|
+
}
|
|
262
|
+
// An empty opening instruction on a server spawn travels as no task at all: the routed spawn
|
|
263
|
+
// refuses an empty task file, and no task is what a local empty spawn amounts to.
|
|
264
|
+
let cleanup = () => {};
|
|
265
|
+
if (opts.server && !String(task ?? "").trim()) argv.splice(argv.indexOf("--task-file"), 2);
|
|
266
|
+
else {
|
|
267
|
+
const written = writeTaskFile(task ?? "", io); cleanup = written.cleanup;
|
|
268
|
+
// Replace the placeholder POSITIONALLY — the slot after --task-file —
|
|
269
|
+
// never by value search: an agent literally named "__TASKFILE__" would
|
|
270
|
+
// occupy an earlier argv slot and indexOf would clobber the agent name
|
|
271
|
+
// instead (review 0b83988).
|
|
272
|
+
argv[argv.indexOf("--task-file") + 1] = written.file;
|
|
273
|
+
}
|
|
274
|
+
let wakeFile;
|
|
275
|
+
try {
|
|
276
|
+
if (wake) { wakeFile = writeTaskFile(JSON.stringify(wake), io); argv.push("--wake-file", wakeFile.file); }
|
|
277
|
+
return await runJson(bin, argv, { cwd: workspaceDir, exec: io.exec, timeout: io.timeout });
|
|
278
|
+
} finally { wakeFile?.cleanup(); cleanup(); }
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/** Registered servers, from the CLI's registry (`oats server list --json`). */
|
|
282
|
+
export function cliServers(bin, io = {}) {
|
|
283
|
+
return runJson(bin, ["server", "list", "--json"], { cwd: io.cwd || process.cwd(), exec: io.exec, timeout: io.timeout });
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/* A workspace's own machines (#517): check, remove, connect and the messaging step, argv only.
|
|
287
|
+
* Every value is held to the kernel's own rules first; nothing option-shaped reaches the CLI. */
|
|
288
|
+
const MACHINE_CHECK_TIMEOUT_MS = 60_000;
|
|
289
|
+
const SERVER_CONNECT_TIMEOUT_MS = 15 * 60_000; // may install OATS and clone on the host
|
|
290
|
+
const AWEB_CONNECT_TIMEOUT_MS = 5 * 60_000;
|
|
291
|
+
const badMachineArgs = () => ({ schemaVersion: 1, ok: false, error: { code: "E_BAD_ARGS", message: "Invalid machine arguments" } });
|
|
292
|
+
|
|
293
|
+
/** `oats server check <id> --json`: reachability, the host's version and (servers-per-workspace) its key. */
|
|
294
|
+
export function cliServerCheck(bin, id, io = {}) {
|
|
295
|
+
if (typeof id !== "string" || !MACHINE_ID.test(id)) return Promise.resolve(badMachineArgs());
|
|
296
|
+
return runJson(bin, ["server", "check", id, "--json"], { cwd: io.cwd || process.cwd(), exec: io.exec, timeout: io.timeout || MACHINE_CHECK_TIMEOUT_MS });
|
|
297
|
+
}
|
|
298
|
+
/** `oats server remove <id> --json`. */
|
|
299
|
+
export function cliServerRemove(bin, id, io = {}) {
|
|
300
|
+
if (typeof id !== "string" || !MACHINE_ID.test(id)) return Promise.resolve(badMachineArgs());
|
|
301
|
+
return runJson(bin, ["server", "remove", id, "--json"], { cwd: io.cwd || process.cwd(), exec: io.exec, timeout: io.timeout });
|
|
302
|
+
}
|
|
303
|
+
/** `oats server connect <id> --ssh <host> --dir <folder on the host> [--install-oats] --json`, in the deployment's scope. */
|
|
304
|
+
export function cliServerConnect(bin, { id, host, folder, installOats, workspaceDir }, io = {}) {
|
|
305
|
+
if (machineFieldProblem({ id, host, folder }) || !absoluteReadPath(workspaceDir)) return Promise.resolve(badMachineArgs());
|
|
306
|
+
const argv = ["server", "connect", id, "--ssh", host, "--dir", folder, ...(installOats === true ? ["--install-oats"] : []), "--json"];
|
|
307
|
+
return runJson(bin, argv, { cwd: workspaceDir, exec: io.exec, timeout: io.timeout || SERVER_CONNECT_TIMEOUT_MS });
|
|
308
|
+
}
|
|
309
|
+
/** `oats aweb connect <id> --install-aw --json` (oats.aweb), in the deployment's scope. */
|
|
310
|
+
export function cliAwebConnect(bin, { id, workspaceDir }, io = {}) {
|
|
311
|
+
if (typeof id !== "string" || !MACHINE_ID.test(id) || !absoluteReadPath(workspaceDir)) return Promise.resolve(badMachineArgs());
|
|
312
|
+
return runJson(bin, ["aweb", "connect", id, "--install-aw", "--json"], { cwd: workspaceDir, exec: io.exec, timeout: io.timeout || AWEB_CONNECT_TIMEOUT_MS });
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/** Schedule definitions travel as private JSON files, never shell text. */
|
|
316
|
+
export async function cliSchedule(bin, { operation, id, spec, workspaceDir, server }, io = {}) {
|
|
317
|
+
// Reading, enable/disable and run are cliAutomation's (the kernel's automations verbs).
|
|
318
|
+
const actions = new Set(["add", "update", "remove", "reconcile", "host-install", "host-uninstall", "host-status"]);
|
|
319
|
+
const writes = operation === "add" || operation === "update";
|
|
320
|
+
const needsId = actions.has(operation) && !operation.startsWith("host-");
|
|
321
|
+
if (!actions.has(operation) || (needsId && (typeof id !== "string" || !/^[a-z0-9][a-z0-9-]{0,99}$/.test(id)))
|
|
322
|
+
|| (server !== undefined && (typeof server !== "string" || !/^[a-z0-9][a-z0-9-]{0,63}$/.test(server)))
|
|
323
|
+
|| typeof workspaceDir !== "string" || !workspaceDir.startsWith("/") || workspaceDir.includes("\0")
|
|
324
|
+
|| (writes && (!spec || typeof spec !== "object" || Array.isArray(spec)))) {
|
|
325
|
+
return { schemaVersion: 1, ok: false, error: { code: "E_BAD_ARGS", message: "Invalid schedule operation or definition" } };
|
|
326
|
+
}
|
|
327
|
+
const argv = ["schedule", ...operation.split("-")];
|
|
328
|
+
if (needsId) argv.push(id);
|
|
329
|
+
const temporary = writes ? writeTaskFile(JSON.stringify({ ...spec, id }), io) : null;
|
|
330
|
+
if (temporary) argv.push("--file", temporary.file);
|
|
331
|
+
argv.push(...(server ? ["--server", server] : ["--dir", workspaceDir]), "--json");
|
|
332
|
+
try { return await runJson(bin, argv, { cwd: workspaceDir, exec: io.exec, timeout: io.timeout }); }
|
|
333
|
+
finally { temporary?.cleanup(); }
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
/** Workspace + local triggers and schedules (feature automations, automationsApi 1): the
|
|
337
|
+
* kernel's own lists and verbs, argv only. `id` is a qualified id (`local/<id>`,
|
|
338
|
+
* `<member>/<id>`) or a bare local id; nothing option-shaped reaches the CLI. `describe`
|
|
339
|
+
* (feature automation-descriptions) is `<kind> update <local id> --description=<text>`: a
|
|
340
|
+
* local item only, the summary as ONE `=` token so a `-`-led value never becomes a flag. */
|
|
341
|
+
// `list` takes no id; `status` takes an optional one (a trigger's fire history); the rest need one.
|
|
342
|
+
export const AUTOMATION_VERBS = Object.freeze({ trigger: ["list", "status", "enable", "disable", "test", "describe"], schedule: ["list", "enable", "disable", "test", "run", "reconcile", "describe"] });
|
|
343
|
+
const ID_OPTIONAL = new Set(["status"]);
|
|
344
|
+
export const AUTOMATION_ID = /^(?:[A-Za-z0-9][A-Za-z0-9._-]{0,63}\/)?[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
|
345
|
+
// The member component and trigger admission retain their existing bounds.
|
|
346
|
+
const SCHEDULE_AUTOMATION_ID = /^(?:[A-Za-z0-9][A-Za-z0-9._-]{0,63}\/)?[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;
|
|
347
|
+
export const automationIdValid = (kind, id) => typeof id === "string" && (kind === "schedule" ? SCHEDULE_AUTOMATION_ID : AUTOMATION_ID).test(id);
|
|
348
|
+
// A local item's key: bare or `local/`; a member's (workspace) item is edited in Git, never here.
|
|
349
|
+
export const automationKeyLocal = id => typeof id === "string" && (!id.includes("/") || id.startsWith("local/"));
|
|
350
|
+
// The kernel's summary rule (and packages/desktop/renderer/schedule-read-data.mjs's): "" clears, else one line of 1-200 code points.
|
|
351
|
+
export const automationDescriptionValid = v => typeof v === "string" && [...v].length <= 200 && !/[\p{Cc}\u2028\u2029]/u.test(v);
|
|
352
|
+
/** `oats trigger test <id> --run-source` (feature trigger-sources): the kernel runs a capability source's
|
|
353
|
+
* command for a test only with this flag; without it, it executes nothing and answers E_TRIGGER_SOURCE_RUN.
|
|
354
|
+
* The one place the flag is spelled: it is composed here, from `runSource: true`, never passed in by a caller. */
|
|
355
|
+
export const TRIGGER_RUN_SOURCE_FLAG = "--run-source";
|
|
356
|
+
export const TRIGGER_SOURCES_FEATURE = "trigger-sources";
|
|
357
|
+
/** `runSource` is an operator's confirmed press and nothing else: the strict boolean `true`, a trigger's test, on a
|
|
358
|
+
* CLI whose probe declares the feature (`features`: the negotiated probe's list, passed by the caller; never probed
|
|
359
|
+
* here). */
|
|
360
|
+
export const automationRunSourceValid = (kind, action, runSource, features) => runSource === undefined
|
|
361
|
+
|| (runSource === true && kind === "trigger" && action === "test" && Array.isArray(features) && features.includes(TRIGGER_SOURCES_FEATURE));
|
|
362
|
+
export function cliAutomation(bin, { kind, action, id, description, workspaceDir, runSource, features }, io = {}) {
|
|
363
|
+
if (!Object.hasOwn(AUTOMATION_VERBS, kind) || !AUTOMATION_VERBS[kind].includes(action)
|
|
364
|
+
|| (action === "list" ? id !== undefined : id === undefined ? !ID_OPTIONAL.has(action) : !automationIdValid(kind, id))
|
|
365
|
+
|| (action === "describe" ? !automationKeyLocal(id) || !automationDescriptionValid(description) : description !== undefined)
|
|
366
|
+
|| !automationRunSourceValid(kind, action, runSource, features)
|
|
367
|
+
|| typeof workspaceDir !== "string" || !isAbsolute(workspaceDir) || workspaceDir.includes("\0")) {
|
|
368
|
+
return Promise.resolve({ schemaVersion: 1, ok: false, error: { code: "E_BAD_ARGS", message: "Invalid automation request" } });
|
|
369
|
+
}
|
|
370
|
+
const verb = action === "describe" ? ["update", id, `--description=${description}`] : [action, ...(id === undefined ? [] : [id]), ...(runSource === true ? [TRIGGER_RUN_SOURCE_FLAG] : [])];
|
|
371
|
+
const argv = [kind, ...verb, "--dir", workspaceDir, "--json"];
|
|
372
|
+
return runJson(bin, argv, { cwd: workspaceDir, exec: io.exec, timeout: io.timeout || (action === "test" ? 60_000 : 30_000) });
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/** Team model v2 (feature team-model-2): `oats teams …` and `oats soul teams …`, config-only
|
|
376
|
+
* kernel verbs, argv only (no shell). Positionals are grammar-bound (a label, a soul key) and so
|
|
377
|
+
* never option-shaped; every option value travels as ONE `--flag=value` token (the kernel reads
|
|
378
|
+
* the inline form since 0.28), so a value can never become a flag of its own. A team id is the
|
|
379
|
+
* aweb `<name>:<namespace>` shape; a description is bounded printable text, never `-`-led. */
|
|
380
|
+
// The kernel's own grammars (feat/030-team-model lib/teams-verbs.mjs LABEL_RE; K1's soul-key
|
|
381
|
+
// pattern), bounded here: a label ≤64, a soul key ≤256.
|
|
382
|
+
const TEAM_LABEL_ARG = /^[a-z0-9][a-z0-9._-]{0,63}$/;
|
|
383
|
+
const argText = (v, max) => typeof v === "string" && v.length > 0 && v.length <= max && !v.startsWith("-") && !/[\x00-\x1f\x7f]/.test(v);
|
|
384
|
+
const TEAM_ID_ARG = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}:[A-Za-z0-9](?:[A-Za-z0-9.-]{0,251}[A-Za-z0-9])?$/;
|
|
385
|
+
const SOUL_KEY_RE = /^(?:\*|(?:[a-z0-9][a-z0-9._-]*\/)?[a-z0-9]+(?:-[a-z0-9]+)*)$/;
|
|
386
|
+
const SOUL_KEY = { test: v => typeof v === "string" && v.length <= 256 && SOUL_KEY_RE.test(v) };
|
|
387
|
+
const badTeams = () => Promise.resolve({ schemaVersion: 1, ok: false, error: { code: "E_BAD_ARGS", message: "Invalid teams request" } });
|
|
388
|
+
export function cliTeams(bin, { action = "list", label, team, description, workspaceDir }, io = {}) {
|
|
389
|
+
if (typeof workspaceDir !== "string" || !isAbsolute(workspaceDir) || workspaceDir.includes("\0")) return badTeams();
|
|
390
|
+
let verb;
|
|
391
|
+
if (action === "list") { if (label !== undefined || team !== undefined || description !== undefined) return badTeams(); verb = []; }
|
|
392
|
+
else if (action === "add") {
|
|
393
|
+
if (!TEAM_LABEL_ARG.test(label ?? "") || !TEAM_ID_ARG.test(team ?? "") || (description !== undefined && !argText(description, 512))) return badTeams();
|
|
394
|
+
verb = ["add", label, `--team=${team}`, ...(description === undefined ? [] : [`--description=${description}`])];
|
|
395
|
+
} else if (action === "remove" || action === "default") {
|
|
396
|
+
if (!TEAM_LABEL_ARG.test(label ?? "") || team !== undefined || description !== undefined) return badTeams();
|
|
397
|
+
verb = [action, label];
|
|
398
|
+
} else return badTeams();
|
|
399
|
+
return runJson(bin, ["teams", ...verb, "--dir", workspaceDir, "--json"], { cwd: workspaceDir, exec: io.exec, timeout: io.timeout || 15_000 /* inside the renderer proxy's 20s deadline */ });
|
|
400
|
+
}
|
|
401
|
+
export function cliSoulTeams(bin, { soul, add, remove, defaultLabel, clearDefault = false, workspaceDir }, io = {}) {
|
|
402
|
+
const list = v => v === undefined || (Array.isArray(v) && v.length > 0 && v.length <= 64 && v.every(l => TEAM_LABEL_ARG.test(l)) && new Set(v).size === v.length);
|
|
403
|
+
if (typeof workspaceDir !== "string" || !isAbsolute(workspaceDir) || workspaceDir.includes("\0") || !SOUL_KEY.test(soul ?? "")
|
|
404
|
+
|| !list(add) || !list(remove) || (defaultLabel !== undefined && !TEAM_LABEL_ARG.test(defaultLabel)) || typeof clearDefault !== "boolean"
|
|
405
|
+
|| (clearDefault && defaultLabel !== undefined) || (soul === "*" && (defaultLabel !== undefined || clearDefault))) return badTeams();
|
|
406
|
+
const argv = ["soul", "teams", soul, ...(add ? [`--add=${add.join(",")}`] : []), ...(remove ? [`--remove=${remove.join(",")}`] : []),
|
|
407
|
+
...(defaultLabel !== undefined ? [`--default=${defaultLabel}`] : []), ...(clearDefault ? ["--clear-default"] : []), "--dir", workspaceDir, "--json"];
|
|
408
|
+
return runJson(bin, argv, { cwd: workspaceDir, exec: io.exec, timeout: io.timeout || 15_000 });
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/** The roster's envelope as the CLI printed it. A group the kernel could not reach carries the kernel's
|
|
412
|
+
* own error in `probe.error`: each is marked the kernel's here (kernel-made.mjs), as `parseEnvelope` marks
|
|
413
|
+
* the envelope's own. remote-roster.mjs `remotePanel` reads the mark to say who made a row's text. */
|
|
414
|
+
function parseRosterEnvelope(stdout) {
|
|
415
|
+
const doc = parseEnvelope(stdout);
|
|
416
|
+
if (doc?.ok === true && Array.isArray(doc.result.groups)) for (const group of doc.result.groups) kernelMade(group?.probe?.error);
|
|
417
|
+
return doc;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/** One bounded aggregate read; the CLI owns registry and saved-route resolution. */
|
|
421
|
+
export function cliRemoteRoster(bin, io = {}) {
|
|
422
|
+
return runJson(bin, ["server", "roster", "--json"], { cwd: io.cwd || process.cwd(), exec: io.exec, timeout: io.timeout || 60_000, parse: parseRosterEnvelope });
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/** Local retire predates the envelope; preserve its incomplete-cleanup result. */
|
|
426
|
+
export function parseRetireEnvelope(stdout) {
|
|
427
|
+
const envelope = parseEnvelope(stdout);
|
|
428
|
+
if (envelope && (!envelope.ok || !envelope.result?.rollbackIncomplete?.length)) return envelope;
|
|
429
|
+
try {
|
|
430
|
+
const result = envelope?.result || JSON.parse(String(stdout));
|
|
431
|
+
if (typeof result?.retired !== "string") return null;
|
|
432
|
+
const incomplete = !!result.rollbackIncomplete?.length;
|
|
433
|
+
return { schemaVersion: 1, ok: !incomplete, result,
|
|
434
|
+
...(incomplete ? { error: { code: "E_RETIRE_INCOMPLETE", message: "Retirement cleanup is incomplete; the instance is retained for retry" } } : {}) };
|
|
435
|
+
} catch { return null; }
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
export function cliRetire(bin, { instance, home, workspaceDir, server }, io = {}) {
|
|
439
|
+
return runJson(bin, ["retire", instance, "--home", home, ...(server ? ["--server", server] : ["--dir", workspaceDir]), "--json"], {
|
|
440
|
+
cwd: workspaceDir, exec: io.exec, timeout: io.timeout || 600_000, parse: parseRetireEnvelope,
|
|
441
|
+
});
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/** The kernel's harness flag, named by the caller: --harness (feature harness)
|
|
445
|
+
* or a released kernel's --runtime. Anything else is refused, never guessed. */
|
|
446
|
+
function flagFor(harnessFlag) {
|
|
447
|
+
if (harnessFlag === "--harness" || harnessFlag === "--runtime") return harnessFlag;
|
|
448
|
+
throw Object.assign(new Error("The kernel's harness flag was not named"), { code: "E_BAD_ARGS" });
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
/** Shared explicit launch choices; every value remains one argv entry. */
|
|
452
|
+
export function launchChoiceArgv({ launchConfig, harness, model, yolo, harnessFlag } = {}) {
|
|
453
|
+
const argv = [];
|
|
454
|
+
for (const [key, v] of Object.entries({ launchConfig, harness, model })) {
|
|
455
|
+
if (v === undefined || v === "") continue;
|
|
456
|
+
const rule = SPAWN_ARG_RULES[key];
|
|
457
|
+
if (typeof v !== "string" || !rule.re.test(v)) throw Object.assign(new Error(`Invalid ${key}`), { code: "E_BAD_ARGS" });
|
|
458
|
+
argv.push(key === "harness" ? flagFor(harnessFlag) : rule.flag, v);
|
|
459
|
+
}
|
|
460
|
+
if (yolo !== undefined) {
|
|
461
|
+
if (typeof yolo !== "boolean") throw Object.assign(new Error("Invalid permission setting"), { code: "E_BAD_ARGS" });
|
|
462
|
+
argv.push(yolo ? "--yolo" : "--no-yolo");
|
|
463
|
+
}
|
|
464
|
+
return argv;
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
/** Start/restart is owned by the kernel, never a GUI stop-then-spawn pair. */
|
|
468
|
+
export function cliStart(bin, { home, workspaceDir, server, restart = false, ...choices }, io = {}) {
|
|
469
|
+
if (typeof home !== "string" || !home.startsWith("/") || home.includes("\0")
|
|
470
|
+
|| (server !== undefined && (typeof server !== "string" || !/^[a-z0-9][a-z0-9-]{0,63}$/.test(server)))
|
|
471
|
+
|| typeof restart !== "boolean") {
|
|
472
|
+
return Promise.resolve({ schemaVersion: 1, ok: false, error: { code: "E_BAD_ARGS", message: "Invalid start home, server or action" } });
|
|
473
|
+
}
|
|
474
|
+
let options;
|
|
475
|
+
try { options = launchChoiceArgv(choices); }
|
|
476
|
+
catch (e) { return Promise.resolve({ schemaVersion: 1, ok: false, error: { code: e.code, message: e.message } }); }
|
|
477
|
+
return runJson(bin, ["session", restart ? "restart" : "start", "--home", home,
|
|
478
|
+
...(server ? ["--server", server] : []), ...options, "--json"], {
|
|
479
|
+
cwd: workspaceDir, exec: io.exec, timeout: io.timeout,
|
|
480
|
+
});
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
/** Named configuration data travels in private JSON files, not shell text. */
|
|
484
|
+
export async function cliLaunchConfig(bin, { action, name, definition, keepEnv, context, server, home, soul, agentsRoot, choices, localCwd }, io = {}) {
|
|
485
|
+
let temporary;
|
|
486
|
+
const bad = message => { throw Object.assign(new Error(message), { code: "E_BAD_ARGS" }); };
|
|
487
|
+
const value = (v, label) => {
|
|
488
|
+
if (typeof v !== "string" || !v || v.startsWith("-") || v.includes("\0")) bad(`Invalid ${label}`);
|
|
489
|
+
return v;
|
|
490
|
+
};
|
|
491
|
+
try {
|
|
492
|
+
if (!["list", "set", "remove", "preview"].includes(action)) bad("Unknown launch configuration action");
|
|
493
|
+
const argv = ["launch-config", action];
|
|
494
|
+
if (["set", "remove"].includes(action)) {
|
|
495
|
+
if (typeof name !== "string" || !SPAWN_ARG_RULES.launchConfig.re.test(name)) bad("Invalid configuration name");
|
|
496
|
+
argv.push(name);
|
|
497
|
+
}
|
|
498
|
+
if (action === "set") {
|
|
499
|
+
if (!definition || typeof definition !== "object" || Array.isArray(definition)) bad("Specify a launch configuration object");
|
|
500
|
+
temporary = writeTaskFile(JSON.stringify(definition), io); argv.push("--file", temporary.file);
|
|
501
|
+
if (keepEnv !== undefined && typeof keepEnv !== "boolean") bad("Invalid environment preservation setting");
|
|
502
|
+
if (keepEnv) argv.push("--keep-env");
|
|
503
|
+
}
|
|
504
|
+
if (context) argv.push("--dir", value(context, "scope"));
|
|
505
|
+
if (server) argv.push("--server", value(server, "server"));
|
|
506
|
+
if (home) argv.push("--home", value(home, "home"));
|
|
507
|
+
if (soul) argv.push("--soul", value(soul, "soul"));
|
|
508
|
+
if (agentsRoot) argv.push("--agents-root", value(agentsRoot, "agents root"));
|
|
509
|
+
if (action === "preview") argv.push(...launchChoiceArgv(choices));
|
|
510
|
+
return await runJson(bin, [...argv, "--json"], { cwd: localCwd, exec: io.exec, timeout: io.timeout });
|
|
511
|
+
} catch (e) { return { schemaVersion: 1, ok: false, error: { code: e.code || "E_BAD_ARGS", message: e.message } }; }
|
|
512
|
+
finally { temporary?.cleanup(); }
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
/** Inspection and provider operations share one CLI boundary. Read-only:
|
|
516
|
+
* workspace model v2 removed `oats use`, and a soul is edited in its repository. */
|
|
517
|
+
/** Operation arguments the provider declares (`--arg name=value`): a bounded
|
|
518
|
+
* record of names to single-line values. The kernel refuses undeclared ones. */
|
|
519
|
+
export function operationArgs(args) {
|
|
520
|
+
if (args === undefined) return [];
|
|
521
|
+
if (!args || typeof args !== 'object' || Array.isArray(args) || Object.getPrototypeOf(args) !== Object.prototype) return null;
|
|
522
|
+
const entries = Object.entries(args);
|
|
523
|
+
if (entries.length > 8 || entries.some(([k, v]) => !/^[a-z][a-z0-9-]{0,63}$/.test(k) || typeof v !== 'string' || !v || v.length > 1024 || /[\x00-\x1f\x7f]/.test(v))) return null;
|
|
524
|
+
return entries.flatMap(([k, v]) => ['--arg', `${k}=${v}`]);
|
|
525
|
+
}
|
|
526
|
+
/** `maxAge` (feature observe-max-age) is inspect's alone; `features` is the probe's list and
|
|
527
|
+
* gates the flag, so an undeclared kernel gets the flagless argv even when a value is given. */
|
|
528
|
+
export async function cliCapability(bin, { action, context, server, soul, agentsRoot, home, operation, args, localCwd, maxAge, instructions = false, features }, io = {}) {
|
|
529
|
+
const bad = message => { throw Object.assign(new Error(message), { code: 'E_BAD_ARGS' }); };
|
|
530
|
+
const value = (v, label) => {
|
|
531
|
+
if (typeof v !== 'string' || !v || v.startsWith('-') || v.includes('\0')) bad(`Invalid ${label}`);
|
|
532
|
+
return v;
|
|
533
|
+
};
|
|
534
|
+
const target = [];
|
|
535
|
+
if (context) target.push('--dir', value(context, 'scope'));
|
|
536
|
+
if (server) target.push('--server', value(server, 'server'));
|
|
537
|
+
if (home) target.push('--home', value(home, 'home'));
|
|
538
|
+
if (soul) target.push('--soul', value(soul, 'soul'));
|
|
539
|
+
if (agentsRoot) target.push('--agents-root', value(agentsRoot, 'agents root'));
|
|
540
|
+
let argv;
|
|
541
|
+
if (action === 'inspect') argv = ['inspect'];
|
|
542
|
+
else if (action === 'run') {
|
|
543
|
+
if (typeof operation !== 'string' || !/^(knowledge|messaging|tasks):[a-zA-Z0-9._-]+$/.test(operation)) bad('Select a declared provider operation');
|
|
544
|
+
const pairs = operationArgs(args);
|
|
545
|
+
if (!pairs) bad('Invalid operation arguments');
|
|
546
|
+
argv = ['operation', 'run', operation, ...pairs];
|
|
547
|
+
} else bad('Unknown capability action');
|
|
548
|
+
if (action !== 'run' && args !== undefined) bad('Arguments belong to an operation run');
|
|
549
|
+
if (action !== 'inspect' && maxAge !== undefined) bad('Observation age belongs to an inspection');
|
|
550
|
+
// Reuse is local only: the kernel refuses --max-age with --server (E_BAD_ARGS), so a routed inspect never carries it.
|
|
551
|
+
if (server && maxAge !== undefined) bad('Observation age does not route to a server');
|
|
552
|
+
if (!validMaxAge(maxAge)) bad('Invalid observation age');
|
|
553
|
+
// --instructions (feature soul-composed-instructions) composes a soul's AGENTS.md: inspect --soul only; a CLI that
|
|
554
|
+
// does not advertise it gets the flagless argv. Routed with --server, the caller asks only for a host whose roster
|
|
555
|
+
// row names the feature (packages/desktop: server/capabilities.mjs, renderer/composed-gate.mjs): a host without it refuses the flag.
|
|
556
|
+
if (instructions && (action !== 'inspect' || !soul || home)) bad('Composed instructions belong to a soul inspection');
|
|
557
|
+
const composed = instructions && Array.isArray(features) && features.includes('soul-composed-instructions') ? ['--instructions'] : [];
|
|
558
|
+
return await runJson(bin, [...argv, ...target, ...composed, ...maxAgeArgv(features, maxAge), '--json'], {
|
|
559
|
+
cwd: localCwd, exec: io.exec, timeout: io.timeout ?? (action === 'run' ? 300_000 : ENVELOPE_TIMEOUT_MS),
|
|
560
|
+
});
|
|
561
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// The environment of a program the Desktop starts: the user's, without what the Desktop or its
|
|
2
|
+
// packaging added to the Desktop's own (#602). A tmux server takes its environment from the
|
|
3
|
+
// program that creates it, so whatever leaks here ends up in every agent's pane.
|
|
4
|
+
//
|
|
5
|
+
// This module is a leaf and must stay one: a Desktop process that runs as Node cleans its own
|
|
6
|
+
// environment with it before any other module is loaded (own-environment.mjs).
|
|
7
|
+
|
|
8
|
+
/** Set by main for its Node-mode children, and by Electron at startup on Linux. */
|
|
9
|
+
const DESKTOP_NAMES = ["ELECTRON_RUN_AS_NODE", "CHROME_DESKTOP"];
|
|
10
|
+
/** Set by the AppImage runtime. */
|
|
11
|
+
const APPIMAGE_NAMES = ["APPIMAGE", "APPDIR", "ARGV0", "OWD"];
|
|
12
|
+
|
|
13
|
+
/** The AppImage's mount: APPDIR when it is an absolute path other than the root, without its trailing slashes; else null. */
|
|
14
|
+
function mountOf(source) {
|
|
15
|
+
const appdir = source.APPDIR;
|
|
16
|
+
if (typeof appdir !== "string" || !appdir.startsWith("/")) return null;
|
|
17
|
+
return appdir.replace(/\/+$/, "") || null;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* A new object; `source` is never changed.
|
|
22
|
+
* 1. ELECTRON_RUN_AS_NODE and CHROME_DESKTOP are removed.
|
|
23
|
+
* 2. MallocNanoZone is removed when it is exactly "0" (the launch environment Electron's
|
|
24
|
+
* Info.plist declares on macOS; a user's own "0" cannot be told from it).
|
|
25
|
+
* 3. With a mount: APPIMAGE, APPDIR, ARGV0 and OWD are removed, and every other value is read
|
|
26
|
+
* as a `:` list (APPDIR exists only where an AppImage does, so `:` and not path.delimiter).
|
|
27
|
+
* An entry is under the mount when it is the mount or starts with the mount and a `/`. A
|
|
28
|
+
* value with no such entry is passed through as it is, not re-joined. Otherwise those
|
|
29
|
+
* entries and the empty ones are dropped, and the name is removed when nothing is left.
|
|
30
|
+
* Without a mount step 3 does nothing. A value that is not a string is never read and passes
|
|
31
|
+
* through. The rule is on values, not on the names the AppImage launcher exports, so it holds
|
|
32
|
+
* whatever that generated script exports; it matches whole entries only, so a value that merely
|
|
33
|
+
* contains the mount's path, or a sibling of the mount, is untouched. Applying it to its own
|
|
34
|
+
* result changes nothing.
|
|
35
|
+
*/
|
|
36
|
+
export function cliEnvironment(source = process.env) {
|
|
37
|
+
const env = { ...source };
|
|
38
|
+
for (const name of DESKTOP_NAMES) delete env[name];
|
|
39
|
+
if (env.MallocNanoZone === "0") delete env.MallocNanoZone;
|
|
40
|
+
const mount = mountOf(source);
|
|
41
|
+
if (mount === null) return env;
|
|
42
|
+
for (const name of APPIMAGE_NAMES) delete env[name];
|
|
43
|
+
const underMount = (entry) => entry === mount || entry.startsWith(`${mount}/`);
|
|
44
|
+
for (const [name, value] of Object.entries(env)) {
|
|
45
|
+
if (typeof value !== "string") continue;
|
|
46
|
+
const entries = value.split(":");
|
|
47
|
+
if (!entries.some(underMount)) continue;
|
|
48
|
+
const kept = entries.filter((entry) => entry !== "" && !underMount(entry));
|
|
49
|
+
if (kept.length) env[name] = kept.join(":");
|
|
50
|
+
else delete env[name];
|
|
51
|
+
}
|
|
52
|
+
return env;
|
|
53
|
+
}
|