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