@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,175 @@
|
|
|
1
|
+
// Remote terminal addressing is an installed-CLI operation, never a renderer
|
|
2
|
+
// supplied SSH command, executable path, socket or server registration.
|
|
3
|
+
//
|
|
4
|
+
// Opening an agent's terminal with the kernel's own viewer (`oats session attach`): the arguments
|
|
5
|
+
// of the viewer for this machine and for another, whether its detach key can be used, and, for
|
|
6
|
+
// another machine, the preflight (`oats session inspect`) that runs before the viewer starts.
|
|
7
|
+
//
|
|
8
|
+
// A failed `prepareRemoteTerm` throws one of these, and `preflightFailure` reads any of them:
|
|
9
|
+
//
|
|
10
|
+
// code E_TERM_CONTEXT_CHANGED the caller's `signal` aborted or its `current()` turned false
|
|
11
|
+
// code E_TERM_REMOTE_NO_SSH, the preflight's own outcomes: terminal-contract.mjs has a
|
|
12
|
+
// E_TERM_REMOTE_UNREACHABLE, sentence for each
|
|
13
|
+
// E_TERM_PREPARE_TIMEOUT,
|
|
14
|
+
// E_TERM_REMOTE_NO_ANSWER,
|
|
15
|
+
// E_TERM_REMOTE_GONE, E_HERDR_REMOVED
|
|
16
|
+
// any other refusal envelope the kernel's refusal, or a host's relayed by it, with its
|
|
17
|
+
// `code` and `message` as given (E_TERM_OPEN_FAILED and a
|
|
18
|
+
// fixed message where it gave none)
|
|
19
|
+
// code unsupported-remote-operation, the installed CLI cannot do it: decided before any process
|
|
20
|
+
// unsupported-detach-key
|
|
21
|
+
// no code, or one that is not a string the target was invalid, the CLI did not start, or it
|
|
22
|
+
// answered no envelope
|
|
23
|
+
//
|
|
24
|
+
// Not loadable by a page: it reaches `node:` builtins through its runner.
|
|
25
|
+
import { requireRemoteSupport } from "./cli-locator.mjs";
|
|
26
|
+
import { runTerminalCommand } from './terminal-exec.mjs';
|
|
27
|
+
import { HERDR_REMOVED, terminalFailure, terminalMessage } from './terminal-contract.mjs';
|
|
28
|
+
|
|
29
|
+
/** The kernel feature of `session attach --detach-key` (docs/desktop-cli-api.md). */
|
|
30
|
+
export const DETACH_KEY_FEATURE = "session-attach-detach-key";
|
|
31
|
+
/** The kernel feature under which a roster group's `probe.features` is the host's own list
|
|
32
|
+
* (docs/desktop-cli-api.md, `probe.features`). Without it that key says nothing. */
|
|
33
|
+
const PROBE_FEATURES_FEATURE = "server-probe-features";
|
|
34
|
+
// Array.isArray, as in requireRemoteSupport: a string must not pass a gate that exists to fail closed.
|
|
35
|
+
const lists = (cli, feature) => cli?.ok === true && Array.isArray(cli.features) && cli.features.includes(feature);
|
|
36
|
+
|
|
37
|
+
/** This machine's CLI takes the key: an accepted probe (`cli.ok === true`) whose `features` is an
|
|
38
|
+
* array naming the feature. */
|
|
39
|
+
export function detachKeySupported(cli) {
|
|
40
|
+
return lists(cli, DETACH_KEY_FEATURE);
|
|
41
|
+
}
|
|
42
|
+
/** The key can be offered for a row on another machine: this machine's CLI takes it and relays what
|
|
43
|
+
* each host lists about itself, the group's last roster read succeeded, and the host's own list
|
|
44
|
+
* names the feature. `group` is a group of `oats server roster --json` as read. `features: null`,
|
|
45
|
+
* a missing key and a failed read are unknown, and unknown is not supported; nothing is decided
|
|
46
|
+
* from a refusal and nothing probes. For what a client offers only: `sessionAttachArgv` does not
|
|
47
|
+
* ask it, because the kernel refuses a host without the feature and starts no viewer. */
|
|
48
|
+
export function hostDetachKeySupported(cli, group) {
|
|
49
|
+
const probe = group?.probe;
|
|
50
|
+
return detachKeySupported(cli) && lists(cli, PROBE_FEATURES_FEATURE)
|
|
51
|
+
&& probe?.ok === true && Array.isArray(probe.features) && probe.features.includes(DETACH_KEY_FEATURE);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const coded = (code, message) => Object.assign(new Error(message), { code });
|
|
55
|
+
const herdrRemoved = message => coded('E_HERDR_REMOVED', message);
|
|
56
|
+
const unreachable = () => coded('E_TERM_REMOTE_UNREACHABLE', 'the remote server could not be reached');
|
|
57
|
+
/** The CLI's JSON envelope, or null when it printed none. */
|
|
58
|
+
function envelopeOf(stdout) {
|
|
59
|
+
let envelope;
|
|
60
|
+
try { envelope = JSON.parse(stdout); } catch { return null; }
|
|
61
|
+
return envelope?.schemaVersion === 1 && typeof envelope.ok === 'boolean' ? envelope : null;
|
|
62
|
+
}
|
|
63
|
+
/** What a refusal said, for each error `refusal` returns from its last line: the envelope's own
|
|
64
|
+
* `code`, `message` and `details.fix`, each null where it gave no string. Kept beside the error and
|
|
65
|
+
* not on it, so the error thrown has the properties it always had; read by `preflightFailure` only. */
|
|
66
|
+
const keptRefusals = new WeakMap();
|
|
67
|
+
const stringOrNull = value => (typeof value === 'string' ? value : null);
|
|
68
|
+
/** A refusal envelope as a coded error. The CLI reports ssh's own failure as E_SSH: a transport
|
|
69
|
+
* failure, unless its details say ssh never started on this computer (nothing to retry); a 0.31
|
|
70
|
+
* kernel's E_HERDR_REMOVED keeps its message; any other refusal keeps the host's code. */
|
|
71
|
+
function refusal(envelope) {
|
|
72
|
+
const { code, message, details } = envelope.error || {};
|
|
73
|
+
if (code === 'E_SSH' && details?.sshStarted === false) return coded('E_TERM_REMOTE_NO_SSH', 'ssh is not available on this computer');
|
|
74
|
+
if (code === 'E_SSH') return unreachable();
|
|
75
|
+
if (code === 'E_HERDR_REMOVED') return herdrRemoved(typeof message === 'string' && message ? message : HERDR_REMOVED);
|
|
76
|
+
const error = coded(typeof code === 'string' && code ? code : 'E_TERM_OPEN_FAILED', message || 'remote session inspection failed');
|
|
77
|
+
keptRefusals.set(error, { code: stringOrNull(code), message: stringOrNull(message), fix: stringOrNull(details?.fix) });
|
|
78
|
+
return error;
|
|
79
|
+
}
|
|
80
|
+
/** What a failed preflight says. `error` is what `prepareRemoteTerm` threw; `server` is the label a
|
|
81
|
+
* sentence names.
|
|
82
|
+
*
|
|
83
|
+
* code the terminal table's code for it (E_TERM_OPEN_FAILED for anything the table does not know)
|
|
84
|
+
* sentence the table's sentence, naming `server` where it has a place for one
|
|
85
|
+
* said null, or { code, message, fix }: what the kernel said (this machine's, or another
|
|
86
|
+
* host's relayed by it), only for a refusal kept as it came for which the table has no
|
|
87
|
+
* sentence of its own. Each is the envelope's own string or null, and `said` is null
|
|
88
|
+
* when all three are. Text from outside: a client draws `message` and `fix` with
|
|
89
|
+
* kernel-lines.mjs `kernelLines` and nothing else.
|
|
90
|
+
*
|
|
91
|
+
* Any other error has `said: null`, also one made by hand with a refusal's code and message: the
|
|
92
|
+
* message of a CLI that did not start holds a path and is never shown. */
|
|
93
|
+
export function preflightFailure(error, server) {
|
|
94
|
+
const code = terminalFailure(error?.code).code;
|
|
95
|
+
const kept = code === 'E_TERM_OPEN_FAILED' ? keptRefusals.get(error) : undefined;
|
|
96
|
+
const said = kept && (kept.code !== null || kept.message !== null || kept.fix !== null) ? { ...kept } : null;
|
|
97
|
+
return { code, sentence: terminalMessage(error?.code, server), said };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** A remote terminal is its server and its absolute home: routed as `--server S --home H`, never by a bare name. */
|
|
101
|
+
export function remoteTargetKey(remote) {
|
|
102
|
+
if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(remote?.serverId || "")
|
|
103
|
+
|| !/^[a-z0-9][a-z0-9-]*$/.test(remote?.instance || "")) throw new Error("invalid remote terminal target");
|
|
104
|
+
if (typeof remote.home !== "string" || !remote.home.startsWith("/") || remote.home.includes("\0")) throw new Error("invalid remote terminal home");
|
|
105
|
+
return JSON.stringify(["remote", remote.serverId, remote.home]);
|
|
106
|
+
}
|
|
107
|
+
/** The arguments of the kernel's viewer (the binary is `cli.bin`), a new array each call.
|
|
108
|
+
*
|
|
109
|
+
* target { home } on this machine; { serverId, instance, home } on another (what
|
|
110
|
+
* `remoteTargetKey` admits, and it refuses as it always did)
|
|
111
|
+
* detachKey undefined for none; else a non-empty string, appended as `--detach-key <key>`
|
|
112
|
+
*
|
|
113
|
+
* The client holds no copy of the kernel's key grammar: a key the kernel does not accept is the
|
|
114
|
+
* kernel's refusal. A key for a CLI that does not take one throws `unsupported-detach-key`: a
|
|
115
|
+
* kernel without the feature ignores the flag and opens a viewer with no exit, so the flag is
|
|
116
|
+
* never tried (docs/desktop-cli-api.md). Its message is for a developer; a client decides what it
|
|
117
|
+
* offers with `detachKeySupported`. */
|
|
118
|
+
export function sessionAttachArgv(cli, target, { detachKey } = {}) {
|
|
119
|
+
let address;
|
|
120
|
+
if (target?.serverId !== undefined) {
|
|
121
|
+
remoteTargetKey(target);
|
|
122
|
+
address = ["--server", target.serverId, "--home", target.home];
|
|
123
|
+
} else {
|
|
124
|
+
if (typeof target?.home !== "string" || !target.home.startsWith("/") || target.home.includes("\0")) throw new Error("invalid session home");
|
|
125
|
+
address = ["--home", target.home];
|
|
126
|
+
}
|
|
127
|
+
if (detachKey === undefined) return ["session", "attach", ...address];
|
|
128
|
+
if (typeof detachKey !== "string" || !detachKey) throw new TypeError("a detach key is a non-empty string");
|
|
129
|
+
if (!detachKeySupported(cli)) throw Object.assign(new Error(`installed oats ${cli?.version || "unknown"} does not support session attach --detach-key; update the CLI`), { code: "unsupported-detach-key" });
|
|
130
|
+
return ["session", "attach", ...address, "--detach-key", detachKey];
|
|
131
|
+
}
|
|
132
|
+
/** The preflight of an attach on another machine, and the viewer to start after it: { binary, args }.
|
|
133
|
+
*
|
|
134
|
+
* run the whole run of the CLI, in the shape of terminal-exec.mjs `runTerminalCommand`; a
|
|
135
|
+
* caller that passes it owns the run, and `exec` is then not used
|
|
136
|
+
* exec what the default runner starts the CLI with, in `execFile`'s signature
|
|
137
|
+
* detachKey as `sessionAttachArgv` takes it. The viewer's arguments are built before the
|
|
138
|
+
* inspect runs, so a key that cannot be used starts no process; the inspect never
|
|
139
|
+
* carries the key. */
|
|
140
|
+
export async function prepareRemoteTerm(cli, remote, { exec, run = (binary, args, options) => runTerminalCommand(binary, args, options, exec), signal, current = () => true, detachKey } = {}) {
|
|
141
|
+
const check = () => { if (signal?.aborted || !current()) throw Object.assign(new Error('Terminal context changed'), { code: 'E_TERM_CONTEXT_CHANGED' }); };
|
|
142
|
+
check();
|
|
143
|
+
requireRemoteSupport(cli, "session");
|
|
144
|
+
const bin = cli.bin;
|
|
145
|
+
remoteTargetKey(remote);
|
|
146
|
+
const address = ["--server", remote.serverId, "--home", remote.home];
|
|
147
|
+
const args = sessionAttachArgv(cli, remote, { detachKey });
|
|
148
|
+
check(); // actual execution owner, not only IPC admission
|
|
149
|
+
let stdout;
|
|
150
|
+
try {
|
|
151
|
+
({ stdout } = await run(bin, ["session", "inspect", ...address, "--json"], {
|
|
152
|
+
encoding: "utf8", timeout: 20000, maxBuffer: 1024 * 1024, shell: false, ...(signal ? { signal } : {}),
|
|
153
|
+
}));
|
|
154
|
+
} catch (error) {
|
|
155
|
+
check();
|
|
156
|
+
const envelope = typeof error?.stdout === 'string' ? envelopeOf(error.stdout) : null;
|
|
157
|
+
if (envelope && !envelope.ok) throw refusal(envelope);
|
|
158
|
+
// Killed by execFile at the deadline: a stalled link outlives ssh's keepalives (about 45 s),
|
|
159
|
+
// so it is a timeout. A CLI that ended without a refusal, by a nonzero exit (255 included) or
|
|
160
|
+
// a signal of its own, gave no answer: ssh's own failures arrive as E_SSH, so this is more
|
|
161
|
+
// likely the local CLI. A CLI that never started keeps its own error.
|
|
162
|
+
if (error?.killed) throw coded('E_TERM_PREPARE_TIMEOUT', 'remote session inspection timed out');
|
|
163
|
+
if (Number.isInteger(error?.code) || error?.signal) throw coded('E_TERM_REMOTE_NO_ANSWER', 'the local oats gave no answer');
|
|
164
|
+
throw error;
|
|
165
|
+
}
|
|
166
|
+
check();
|
|
167
|
+
const envelope = envelopeOf(stdout);
|
|
168
|
+
if (!envelope) throw new Error("remote session inspection answered no envelope");
|
|
169
|
+
if (!envelope.ok) throw refusal(envelope);
|
|
170
|
+
// A 0.31 kernel refuses a Herdr-recorded instance; an older one still reports its live Herdr
|
|
171
|
+
// session. Neither is attached: the refusal keeps its code so the broker reports it.
|
|
172
|
+
if (envelope.result?.backend === 'herdr') throw herdrRemoved(HERDR_REMOVED);
|
|
173
|
+
if (envelope.result?.present !== true) throw coded('E_TERM_REMOTE_GONE', "remote terminal no longer exists");
|
|
174
|
+
return { binary: bin, args };
|
|
175
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/** Private K6e transport. Only the server broker supplies an admitted immutable intent.
|
|
2
|
+
* started is conservative dispatch evidence, NOT a creation/rollback receipt.
|
|
3
|
+
* The broker must qualify a success receipt before exposing it or handing off. */
|
|
4
|
+
import { retainedSpawnDetails } from './launch-prompt-outcome.mjs';
|
|
5
|
+
import { execFile } from 'node:child_process';
|
|
6
|
+
import { parseEnvelope, writeTaskFile } from './cli-adapter.mjs';
|
|
7
|
+
import { absolute, record, previewTarget, choiceArgv } from './spawn-preview-contract.mjs';
|
|
8
|
+
import { spawnDecision } from './spawn-decision.mjs';
|
|
9
|
+
import { spawnApplySupported, spawnApplyChoicesSupported, spawnPrepareInput, spawnReference, spawnApplyReason, spawnApplyDeadline,
|
|
10
|
+
SPAWN_APPLY_MS, ROLLED_BACK_CODES } from './spawn-apply-contract.mjs';
|
|
11
|
+
const failure = (code, started = false) => ({ started, envelope: { schemaVersion: 1, ok: false, error: spawnApplyReason(code) } });
|
|
12
|
+
const named = v => typeof v === 'string' && /^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$/.test(v);
|
|
13
|
+
const worktreeEvent = cli => Array.isArray(cli?.features) && cli.features.includes('worktree-event');
|
|
14
|
+
/** After our deadline's SIGTERM, a worktree-event kernel rolls the spawn back and prints its envelope;
|
|
15
|
+
* a CLI still running this long after it is killed (SIGKILL) and its outcome is unknown. */
|
|
16
|
+
export const SIGTERM_GRACE_MS = 20000;
|
|
17
|
+
function refusal(doc, cli) {
|
|
18
|
+
// worktree-event: the three rolled-back codes keep the kernel's own message (it names the
|
|
19
|
+
// capability and its log), and whether its compensation was confirmed.
|
|
20
|
+
const rolledBack = worktreeEvent(cli) && ROLLED_BACK_CODES.includes(doc.error?.code);
|
|
21
|
+
const error = spawnApplyReason(doc.error?.code, rolledBack ? doc.error?.message : undefined);
|
|
22
|
+
let details;
|
|
23
|
+
if (rolledBack) {
|
|
24
|
+
if (doc.error?.details?.unconfirmed === true) details = { unconfirmed: true };
|
|
25
|
+
} else if (error.code === 'E_DECISION_STALE') {
|
|
26
|
+
const decision = spawnDecision(doc.error?.details?.decision, { effectiveRequired: true });
|
|
27
|
+
if (!decision) return failure('E_CLI_PROTOCOL', true);
|
|
28
|
+
details = { decision };
|
|
29
|
+
} else if (error.code === 'E_SPAWN_INCOMPLETE') {
|
|
30
|
+
details = retainedSpawnDetails(doc.error?.details);
|
|
31
|
+
if (!details) return failure('E_CLI_PROTOCOL', true);
|
|
32
|
+
} else if (['E_IDEMPOTENCY_CONFLICT', 'E_PLACEMENT_TAKEN', 'E_INSTANCE_NAME_TAKEN'].includes(error.code)) {
|
|
33
|
+
const d = doc.error?.details;
|
|
34
|
+
if (!record(d) || !named(d.instance) || !absolute(d.home)) return failure('E_CLI_PROTOCOL', true);
|
|
35
|
+
details = { instance: d.instance, home: d.home };
|
|
36
|
+
}
|
|
37
|
+
return { started: true, envelope: { schemaVersion: 1, ok: false, error: { ...error, ...(details ? { details } : {}) } } };
|
|
38
|
+
}
|
|
39
|
+
/** `io.exec` is a client's own `execFile` (the rule is at cli-adapter.mjs `runJson`). Its return is used here:
|
|
40
|
+
* the child of a spawn this call owns is ended through it at the deadline. */
|
|
41
|
+
export async function cliSpawnApply(cli, options = {}, io = {}) {
|
|
42
|
+
// Repeat the complete positive mode fence here, before even creating inputs.
|
|
43
|
+
if (!spawnApplySupported(cli)) return failure('E_APPLY_UNAVAILABLE');
|
|
44
|
+
if (!record(options) || Object.keys(options).some(k => !['target', 'choices', 'task', 'wake', 'decision', 'key', 'deadlineMs'].includes(k))) return failure('E_BAD_ARGS');
|
|
45
|
+
// The broker derives the deadline from the confirmed preview (spawnApplyDeadlineMs); 60 s without one.
|
|
46
|
+
const timeout = options.deadlineMs ?? SPAWN_APPLY_MS;
|
|
47
|
+
if (!spawnApplyDeadline(timeout)) return failure('E_BAD_ARGS');
|
|
48
|
+
const target = previewTarget(options.target), decision = spawnDecision(options.decision, { effectiveRequired: true });
|
|
49
|
+
const input = spawnPrepareInput({ action: 'prepare', selector: target?.selector, choices: options.choices, task: options.task,
|
|
50
|
+
...(Object.hasOwn(options, 'wake') ? { wake: options.wake } : {}) });
|
|
51
|
+
if (!target || !decision || !input || !spawnReference(options.key) || decision.effective.work === 'attached') return failure('E_BAD_ARGS');
|
|
52
|
+
if (!spawnApplyChoicesSupported(cli, input.choices, !!input.wake)) return failure('E_UNSUPPORTED_OPTION');
|
|
53
|
+
let taskFile, wakeFile, started = false;
|
|
54
|
+
try {
|
|
55
|
+
taskFile = writeTaskFile(input.task, io);
|
|
56
|
+
if (input.wake) wakeFile = writeTaskFile(JSON.stringify(input.wake), io);
|
|
57
|
+
const choices = input.choices;
|
|
58
|
+
const argv = ['spawn', target.selector.soul, '--dir', target.context, '--agents-root', target.selector.agentsRoot, ...choiceArgv(choices, cli)];
|
|
59
|
+
argv.push('--expect-decision', decision.revision, '--idempotency-key', options.key, '--task-file', taskFile.file);
|
|
60
|
+
if (wakeFile) argv.push('--wake-file', wakeFile.file);
|
|
61
|
+
argv.push('--json');
|
|
62
|
+
const env = { ...(io.env ?? process.env) };
|
|
63
|
+
for (const k of ['PI_AGENTS_ROOT', 'OATS_DEPLOYMENT', 'OATS_RESOLUTION', 'OATS_PREVIEW_PREFLIGHT_BUDGET_MS']) delete env[k];
|
|
64
|
+
// File construction is synchronous; repeat immediately at the process owner
|
|
65
|
+
// too, so even a re-entrant injected dependency cannot downgrade the mode.
|
|
66
|
+
if (!spawnApplySupported(cli)) return failure('E_APPLY_UNAVAILABLE');
|
|
67
|
+
if (!spawnApplyChoicesSupported(cli, choices, !!input.wake)) return failure('E_UNSUPPORTED_OPTION');
|
|
68
|
+
// worktree-event: the deadline is ours, not execFile's. execFile's own timeout destroys the child's
|
|
69
|
+
// output before it signals it, which would lose the envelope a kernel prints after our SIGTERM
|
|
70
|
+
// (E_INTERRUPTED, once its rollback is done). So: SIGTERM at the deadline with the output still read,
|
|
71
|
+
// and SIGKILL only if the CLI is still running SIGTERM_GRACE_MS later. Older kernels keep execFile's.
|
|
72
|
+
const own = worktreeEvent(cli), timer = io.timer ?? ((fn, ms) => { const t = setTimeout(fn, ms); return () => clearTimeout(t); });
|
|
73
|
+
const limit = io.timeoutMs ?? timeout, grace = io.graceMs ?? SIGTERM_GRACE_MS;
|
|
74
|
+
return await new Promise(resolve => {
|
|
75
|
+
let expired = false, settled = false, cancelDeadline = () => {}, cancelGrace = () => {};
|
|
76
|
+
try {
|
|
77
|
+
started = true;
|
|
78
|
+
const child = (io.exec ?? execFile)(cli.bin, argv, { cwd: target.context, env, shell: false, encoding: 'utf8', ...(own ? {} : { timeout: limit }), maxBuffer: 4 * 1024 * 1024 }, (err, stdout) => {
|
|
79
|
+
settled = true; cancelDeadline(); cancelGrace();
|
|
80
|
+
if (err?.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER' || typeof stdout === 'string' && Buffer.byteLength(stdout) > 4 * 1024 * 1024) return resolve(failure('E_CLI_OUTPUT_LIMIT', true));
|
|
81
|
+
if (err?.killed && !own) return resolve(failure('E_CLI_TIMEOUT', true));
|
|
82
|
+
const doc = typeof stdout === 'string' ? parseEnvelope(stdout) : null;
|
|
83
|
+
// Killed by our deadline: a complete envelope on stdout is the outcome (failure or success,
|
|
84
|
+
// which the broker still qualifies). Only without one is it unknown.
|
|
85
|
+
if (expired || err?.killed) {
|
|
86
|
+
if (!doc) return resolve(failure('E_CLI_TIMEOUT', true));
|
|
87
|
+
return resolve(doc.ok === false ? refusal(doc, cli) : { started: true, envelope: doc });
|
|
88
|
+
}
|
|
89
|
+
if (doc?.ok === false) return resolve(refusal(doc, cli));
|
|
90
|
+
if (err) return resolve(failure('E_CLI_FAILED', true));
|
|
91
|
+
resolve(doc?.ok === true ? { started: true, envelope: doc } : failure('E_CLI_PROTOCOL', true));
|
|
92
|
+
});
|
|
93
|
+
if (own && !settled) cancelDeadline = timer(() => {
|
|
94
|
+
expired = true;
|
|
95
|
+
try { child?.kill('SIGTERM'); } catch { /* already gone */ }
|
|
96
|
+
cancelGrace = timer(() => {
|
|
97
|
+
try { child?.stdout?.destroy(); child?.stderr?.destroy(); child?.kill('SIGKILL'); } catch { /* already gone */ }
|
|
98
|
+
}, grace);
|
|
99
|
+
}, limit);
|
|
100
|
+
} catch { cancelDeadline(); cancelGrace(); resolve(failure('E_CLI_FAILED', true)); }
|
|
101
|
+
});
|
|
102
|
+
} catch { return failure(started ? 'E_CLI_FAILED' : 'E_INPUT_PREPARATION', started); }
|
|
103
|
+
finally { wakeFile?.cleanup(); taskFile?.cleanup(); }
|
|
104
|
+
}
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
/** Confirmed K6d input/data boundary. No kernel resolution or renderer key authority. */
|
|
2
|
+
import { retainedSpawnDetails, launchFlagIgnored, flagIgnoredFact } from './launch-prompt-outcome.mjs';
|
|
3
|
+
import { harnessOf } from './harness-names.mjs';
|
|
4
|
+
import { record, previewSupported, previewSelector, previewChoices, previewTarget, previewData, previewFailure, MAX_HOOKS } from './spawn-preview-contract.mjs';
|
|
5
|
+
import { spawnDecision, sameSpawnDecision } from './spawn-decision.mjs';
|
|
6
|
+
const exact = (v, keys) => record(v) && Object.keys(v).every(k => keys.includes(k));
|
|
7
|
+
const bytes = v => new TextEncoder().encode(v).byteLength;
|
|
8
|
+
function fits(v, max) { try { return bytes(JSON.stringify(v)) <= max; } catch { return false; } }
|
|
9
|
+
const text = (v, max) => typeof v === 'string' && !v.includes('\0') && bytes(v) <= max;
|
|
10
|
+
export const WAKE_OUTCOME_UNKNOWN = 'Agent created; wake outcome unavailable — check Schedules';
|
|
11
|
+
export const spawnReference = v => typeof v === 'string' && /^[a-f0-9]{64}$/.test(v);
|
|
12
|
+
export const spawnApplySupported = cli => previewSupported(cli) && cli.spawnApplyApi === 1
|
|
13
|
+
&& cli.features.length <= 128 && cli.features.every(f => typeof f === 'string')
|
|
14
|
+
&& cli.features.includes('spawn-apply-2') && cli.features.includes('spawn-idempotency-2');
|
|
15
|
+
/** The apply's CLI deadline. 60 s, unless the CLI declares feature worktree-event and the confirmed
|
|
16
|
+
* preview runs n > 0 `worktree` hooks: the kernel bounds each at 30 minutes, so 60 s + n × 30 min + 60 s.
|
|
17
|
+
* Derived from the preview the operator confirmed, never reread. */
|
|
18
|
+
export const SPAWN_APPLY_MS = 60000;
|
|
19
|
+
export const WORKTREE_HOOK_MS = 30 * 60000;
|
|
20
|
+
export function spawnApplyDeadlineMs(cli, preview) {
|
|
21
|
+
const n = Array.isArray(cli?.features) && cli.features.includes('worktree-event') && Array.isArray(preview?.worktreeHooks) ? preview.worktreeHooks.length : 0;
|
|
22
|
+
return n > 0 ? SPAWN_APPLY_MS + n * WORKTREE_HOOK_MS + SPAWN_APPLY_MS : SPAWN_APPLY_MS;
|
|
23
|
+
}
|
|
24
|
+
/** Whether a deadline is one spawnApplyDeadlineMs can produce (at most MAX_HOOKS hooks). */
|
|
25
|
+
export const spawnApplyDeadline = v => v === SPAWN_APPLY_MS
|
|
26
|
+
|| Number.isSafeInteger(v) && v > 2 * SPAWN_APPLY_MS && (v - 2 * SPAWN_APPLY_MS) % WORKTREE_HOOK_MS === 0 && (v - 2 * SPAWN_APPLY_MS) / WORKTREE_HOOK_MS <= MAX_HOOKS;
|
|
27
|
+
export function spawnApplyChoicesSupported(cli, choices, wakeRequested = false) {
|
|
28
|
+
const has = (values, value) => Array.isArray(values) && values.includes(value);
|
|
29
|
+
return !!choices && (!choices.harness || has(cli?.harnesses, choices.harness))
|
|
30
|
+
&& (!choices.backend || has(cli?.sessionBackends, choices.backend))
|
|
31
|
+
&& (choices.yolo === undefined || has(cli?.launchOptions, 'yolo'))
|
|
32
|
+
&& (!choices.launchConfig || has(cli?.features, 'launch-config'))
|
|
33
|
+
&& (!wakeRequested || has(cli?.features, 'schedule'))
|
|
34
|
+
&& (choices.name === undefined || has(cli?.features, 'spawn-name'))
|
|
35
|
+
&& (choices.identity === undefined || has(cli?.features, 'spawn-provider-payload'));
|
|
36
|
+
}
|
|
37
|
+
export function spawnWake(v) {
|
|
38
|
+
if (!exact(v, ['cron', 'tz', 'message', 'enabled']) || !text(v.cron, 256) || !v.cron.trim()
|
|
39
|
+
|| !text(v.tz, 128) || !v.tz.trim() || /[\x00-\x1f\x7f]/.test(v.cron + v.tz)
|
|
40
|
+
|| !text(v.message, 8192) || !v.message.trim() || v.enabled !== undefined && typeof v.enabled !== 'boolean') return null;
|
|
41
|
+
return { cron: v.cron, tz: v.tz, message: v.message, enabled: v.enabled ?? true };
|
|
42
|
+
}
|
|
43
|
+
export function spawnPrepareInput(v) {
|
|
44
|
+
if (!exact(v, ['action', 'selector', 'choices', 'task', 'wake']) || v.action !== 'prepare' || !fits(v, 65536)) return null;
|
|
45
|
+
const selector = previewSelector(v.selector), choices = previewChoices(v.choices);
|
|
46
|
+
const task = v.task === undefined ? '' : v.task;
|
|
47
|
+
if (!selector || !choices || !text(task, 32768) || !fits({ selector, choices }, 16384)) return null;
|
|
48
|
+
const wake = Object.hasOwn(v, 'wake') ? spawnWake(v.wake) : undefined;
|
|
49
|
+
if (wake === null) return null;
|
|
50
|
+
return { action: 'prepare', selector, choices, task, ...(wake ? { wake } : {}) };
|
|
51
|
+
}
|
|
52
|
+
export function spawnRefInput(v) {
|
|
53
|
+
return exact(v, ['action', 'spawnRef']) && ['apply', 'result'].includes(v.action) && spawnReference(v.spawnRef)
|
|
54
|
+
? { action: v.action, spawnRef: v.spawnRef } : null;
|
|
55
|
+
}
|
|
56
|
+
/** A READ success alone never creates an executable confirmation. */
|
|
57
|
+
export function spawnPreparedData(v, target) {
|
|
58
|
+
const data = previewData(v, target);
|
|
59
|
+
return data && spawnDecision(data.decision, { effectiveRequired: true }) && data.work !== 'attached'
|
|
60
|
+
&& data.preflight.status === 'complete' ? data : null;
|
|
61
|
+
}
|
|
62
|
+
export function spawnWakeOutcome(value, requested) {
|
|
63
|
+
if (value === undefined) return { requested: null, saved: null, error: null };
|
|
64
|
+
if (!record(value) || ![null, true, false].includes(value.requested) || ![null, true, false].includes(value.saved)
|
|
65
|
+
|| value.requested !== null && value.requested !== requested
|
|
66
|
+
|| value.requested !== true && value.saved !== null) return null;
|
|
67
|
+
let error = null;
|
|
68
|
+
if (value.error !== null) {
|
|
69
|
+
if (!record(value.error) || typeof value.error.code !== 'string' || !value.error.code || value.error.code.length > 128 || value.saved !== false) return null;
|
|
70
|
+
// Wake errors may contain task/credential/provider text. Only the reported
|
|
71
|
+
// failure fact crosses; neither raw message nor an arbitrary code is UI text.
|
|
72
|
+
error = { code: 'E_WAKE_SAVE_FAILED', message: 'The agent was created, but its wake schedule was not saved.' };
|
|
73
|
+
}
|
|
74
|
+
if (value.saved === false && !error) return null;
|
|
75
|
+
return { requested: value.requested, saved: value.saved, error };
|
|
76
|
+
}
|
|
77
|
+
/** A qualified creation receipt, not executable terminal/session instructions.
|
|
78
|
+
*
|
|
79
|
+
* `flagIgnored` (optional) is the one fact of the kernel's answer the receipt carries as text: a launched
|
|
80
|
+
* spawn where Claude Code ignored the channel option (launchFlagIgnored: `launchPrompts.status`
|
|
81
|
+
* "flag-ignored", with the answer's warnings as bounded display lines). Absent for any other status, for
|
|
82
|
+
* an answer without `launchPrompts`, and for a spawn that was not launched. It holds facts and no sentence.
|
|
83
|
+
* Every other warning of an apply stays a count (`warningCount`). */
|
|
84
|
+
export function spawnCreationReceipt(v, { target, preview, wakeRequested = false } = {}) {
|
|
85
|
+
const selected = previewTarget(target), expected = spawnDecision(preview?.decision, { effectiveRequired: true });
|
|
86
|
+
const decision = spawnDecision(v?.decision, { effectiveRequired: true });
|
|
87
|
+
if (!selected || !expected || !record(v) || !sameSpawnDecision(expected, decision)
|
|
88
|
+
|| v.agent !== selected.selector.soul || v.instance !== expected.instance || v.home !== expected.home
|
|
89
|
+
|| v.branch !== expected.branch || v.repo !== expected.effective.repo || v.work !== expected.effective.work
|
|
90
|
+
|| harnessOf(v) !== expected.effective.harness || v.model !== expected.effective.model
|
|
91
|
+
|| typeof v.launched !== 'boolean' || typeof v.replayed !== 'boolean'
|
|
92
|
+
|| v.yolo !== undefined && v.yolo !== expected.effective.yolo
|
|
93
|
+
|| !Array.isArray(v.warnings) || v.warnings.length > 512 || !v.warnings.every(w => typeof w === 'string' && w.length <= 4096)) return null;
|
|
94
|
+
let wake = spawnWakeOutcome(v.wake, wakeRequested);
|
|
95
|
+
// Older first-response compatibility: the CLI may have saved the wake outcome
|
|
96
|
+
// but failed to record it in the home. A reported save failure is still known.
|
|
97
|
+
if (v.wake === undefined && v.wakeScheduleError !== undefined) {
|
|
98
|
+
if (!wakeRequested) return null;
|
|
99
|
+
wake = spawnWakeOutcome({ requested: true, saved: false, error: v.wakeScheduleError }, true);
|
|
100
|
+
}
|
|
101
|
+
if (!wake) return null;
|
|
102
|
+
const flagIgnored = v.launched ? launchFlagIgnored(v) : null;
|
|
103
|
+
return { instance: v.instance, agent: v.agent, home: v.home, agentsRoot: selected.selector.agentsRoot,
|
|
104
|
+
workspace: selected.workspace, server: null, repo: v.repo, work: v.work, branch: v.branch,
|
|
105
|
+
harness: harnessOf(v), model: v.model, launched: v.launched, replayed: v.replayed, decision,
|
|
106
|
+
warningCount: v.warnings.length, wake, ...(flagIgnored ? { flagIgnored } : {}) };
|
|
107
|
+
}
|
|
108
|
+
/** Project the Desktop HTTP view again at the main/renderer trust boundaries. */
|
|
109
|
+
export function spawnApplyView(v, expected = {}) {
|
|
110
|
+
if (!record(v) || v.spawnApplyViewApi !== 1) return null;
|
|
111
|
+
const target = v.target === null ? null : previewTarget(v.target);
|
|
112
|
+
if (v.target !== null && !target || target && expected.workspace && target.workspace !== expected.workspace
|
|
113
|
+
|| target && expected.selector && (target.selector.soul !== expected.selector.soul || target.selector.agentsRoot !== expected.selector.agentsRoot)
|
|
114
|
+
|| v.spawnRef !== null && !spawnReference(v.spawnRef) || expected.ref && v.spawnRef !== null && v.spawnRef !== expected.ref) return null;
|
|
115
|
+
if (['unavailable', 'refused', 'unknown', 'stale', 'incomplete'].includes(v.status)) {
|
|
116
|
+
const out = spawnApplyFailure(v.reason?.code, { target, spawnRef: v.spawnRef, status: v.status, message: v.reason?.message });
|
|
117
|
+
if (v.status === 'incomplete') {
|
|
118
|
+
const incomplete = retainedSpawnDetails(v.incomplete);
|
|
119
|
+
if (v.reason?.code !== 'E_SPAWN_INCOMPLETE' || !target || !incomplete) return null;
|
|
120
|
+
out.incomplete = incomplete;
|
|
121
|
+
}
|
|
122
|
+
return out;
|
|
123
|
+
}
|
|
124
|
+
if (!['prepared', 'pending', 'complete', 'partial'].includes(v.status) || !target || !spawnReference(v.spawnRef)
|
|
125
|
+
|| typeof v.wakeRequested !== 'boolean') return null;
|
|
126
|
+
const preview = spawnPreparedData(v.preview, target);
|
|
127
|
+
if (!preview || !preview.backendStatus.installed) return null;
|
|
128
|
+
let receipt = null, reason = null;
|
|
129
|
+
if (['complete', 'partial'].includes(v.status)) {
|
|
130
|
+
if (!record(v.receipt) || !Number.isInteger(v.receipt.warningCount) || v.receipt.warningCount < 0 || v.receipt.warningCount > 512
|
|
131
|
+
|| v.receipt.workspace !== target.workspace || v.receipt.agentsRoot !== target.selector.agentsRoot || v.receipt.server !== null) return null;
|
|
132
|
+
// The receipt is rebuilt from its own keys: the warnings are a count here, so `flagIgnored` is read from
|
|
133
|
+
// the receipt's key through the reader's decoder, never composed again. Tolerant: a value that does not
|
|
134
|
+
// decode is dropped, and the receipt stands.
|
|
135
|
+
receipt = spawnCreationReceipt({ ...v.receipt, warnings: Array(v.receipt.warningCount).fill(''), launchPrompts: undefined }, { target, preview, wakeRequested: v.wakeRequested });
|
|
136
|
+
if (!receipt) return null;
|
|
137
|
+
const flagIgnored = receipt.launched ? flagIgnoredFact(v.receipt.flagIgnored) : undefined;
|
|
138
|
+
if (flagIgnored) receipt.flagIgnored = flagIgnored;
|
|
139
|
+
const partial = v.wakeRequested && receipt.wake.saved !== true;
|
|
140
|
+
if ((v.status === 'partial') !== partial) return null;
|
|
141
|
+
if (partial) reason = receipt.wake.error ?? { code: 'E_WAKE_OUTCOME_UNKNOWN', message: WAKE_OUTCOME_UNKNOWN };
|
|
142
|
+
}
|
|
143
|
+
// The CLI deadline the broker set from this preview (spawnApplyDeadlineMs): the renderer follows a
|
|
144
|
+
// `pending` apply for this long (plus a margin). Absent from an older backend.
|
|
145
|
+
const applyWithinMs = spawnApplyDeadline(v.applyWithinMs) ? v.applyWithinMs : undefined;
|
|
146
|
+
return { spawnApplyViewApi: 1, status: v.status, target, spawnRef: v.spawnRef, preview, wakeRequested: v.wakeRequested,
|
|
147
|
+
receipt, reason, ...(applyWithinMs ? { applyWithinMs } : {}), ...(v.repeated === true ? { repeated: true } : {}) };
|
|
148
|
+
}
|
|
149
|
+
const errors = {
|
|
150
|
+
E_APPLY_UNAVAILABLE: 'Confirmed spawn requires preview API 2, apply API 1 and advertised spawn-preview-2, spawn-apply-2 and spawn-idempotency-2.',
|
|
151
|
+
E_BAD_ARGS: 'Provide one qualified spawn draft, or only its server-owned confirmation reference.',
|
|
152
|
+
E_PLAN_REQUIRED: 'Review this local spawn and explicitly confirm the server-owned decision.',
|
|
153
|
+
E_PLAN_CHANGED: 'The workspace, soul, anchor or CLI changed. Review a new confirmation.',
|
|
154
|
+
E_INTENT_EXPIRED: 'This confirmation is unavailable. A lost submitted intent does not prove that nothing happened; check the roster before reviewing another spawn.',
|
|
155
|
+
E_BUSY: 'The bounded spawn transaction capacity is in use. Wait for the current operation.',
|
|
156
|
+
E_PREFLIGHT_INCOMPLETE: 'The preview preflight did not complete. It is not an executable confirmation.',
|
|
157
|
+
E_BACKEND_UNAVAILABLE: 'The preview reports that the selected backend is not installed. Observe a new preview after it is available.',
|
|
158
|
+
E_INSTANCE_GONE: 'The previously observed confirmed instance is no longer present. Inspect the roster; this is not an automatic spawn retry.',
|
|
159
|
+
E_DECISION_STALE: 'The confirmed decision changed. Review a fresh preview and explicitly confirm again.',
|
|
160
|
+
E_IDEMPOTENCY_CONFLICT: 'This confirmation key belongs to a different recorded decision. Review a new confirmation; do not retry with a replacement key.',
|
|
161
|
+
E_PLACEMENT_TAKEN: 'Another spawn reserved the confirmed home. Review a new preview before confirming again.',
|
|
162
|
+
// spawn-name: explicit names are unique across the deployment; a taken name is never suffixed.
|
|
163
|
+
E_INSTANCE_NAME_TAKEN: 'Another instance took the confirmed name. Review a new preview before confirming again.',
|
|
164
|
+
E_OUTCOME_UNKNOWN: 'The spawn outcome is unknown. Check this same confirmation; never create a replacement key to retry it.',
|
|
165
|
+
E_SPAWN_INCOMPLETE: 'The confirmed home exists but spawn completion is unconfirmed. Inspect its existing session; do not spawn another instance to recover it.',
|
|
166
|
+
E_FORBIDDEN_FRAME: 'This frame cannot use spawn transactions.',
|
|
167
|
+
E_CLI_PROTOCOL: 'The CLI returned an invalid or mismatched confirmed-spawn result.',
|
|
168
|
+
E_CLI_FAILED: 'The installed CLI could not complete the confirmed-spawn request.',
|
|
169
|
+
E_CLI_TIMEOUT: 'The spawn command timed out. Creation may already have happened; do not start a new confirmation to retry it.',
|
|
170
|
+
E_CLI_OUTPUT_LIMIT: 'The spawn command exceeded its output limit. Its creation outcome is unconfirmed.',
|
|
171
|
+
E_INPUT_PREPARATION: 'Private spawn instruction files could not be prepared; no CLI was invoked.',
|
|
172
|
+
E_INTERRUPTED: 'The spawn was interrupted while its worktree hooks ran.',
|
|
173
|
+
E_REQUIRED_HOOK_FAILED: 'A required worktree hook failed.',
|
|
174
|
+
E_HOOK_ENVIRONMENT_CONTRACT: 'A worktree hook broke the hook environment contract.',
|
|
175
|
+
};
|
|
176
|
+
/** Feature worktree-event: a dispatched spawn failure with one of these codes and no
|
|
177
|
+
* `details.unconfirmed: true` was rolled back by the kernel (confirmed compensation): nothing
|
|
178
|
+
* was created. With the marker its cleanup is owed. Only these three; every other code keeps
|
|
179
|
+
* the unknown-unless-proven rule. */
|
|
180
|
+
export const ROLLED_BACK_CODES = ['E_INTERRUPTED', 'E_REQUIRED_HOOK_FAILED', 'E_HOOK_ENVIRONMENT_CONTRACT'];
|
|
181
|
+
/** The kernel's message travels only for ROLLED_BACK_CODES (it names the capability and its log);
|
|
182
|
+
* bounded here, and shown through displayLine. */
|
|
183
|
+
const kernelText = v => typeof v === 'string' && !!v.trim() && v.length <= 4096 && !v.includes('\0');
|
|
184
|
+
export function spawnApplyReason(code, kernelMessage) {
|
|
185
|
+
if (typeof code !== 'string') code = 'E_CLI_FAILED';
|
|
186
|
+
if (ROLLED_BACK_CODES.includes(code)) return { code, message: kernelText(kernelMessage) ? kernelMessage : errors[code] };
|
|
187
|
+
if (Object.hasOwn(errors, code)) return { code, message: errors[code] };
|
|
188
|
+
const reason = previewFailure(code).reason;
|
|
189
|
+
return reason.code === code && code !== 'E_CLI_FAILED' ? reason : { code: 'E_CLI_FAILED', message: errors.E_CLI_FAILED };
|
|
190
|
+
}
|
|
191
|
+
export function spawnApplyFailure(code, { target = null, spawnRef = null, status = 'unavailable', message } = {}) {
|
|
192
|
+
return { spawnApplyViewApi: 1, status: ['unavailable', 'unknown', 'refused', 'stale', 'incomplete'].includes(status) ? status : 'unavailable',
|
|
193
|
+
target: previewTarget(target), spawnRef: spawnReference(spawnRef) ? spawnRef : null,
|
|
194
|
+
preview: null, receipt: null, reason: spawnApplyReason(code, message) };
|
|
195
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/** Producer-owned K6 decision data. Never compute revisions or derive argv from it. */
|
|
2
|
+
import { absolute, record } from './readiness-contract.mjs';
|
|
3
|
+
import { harnessOf, HARNESSES } from './harness-names.mjs';
|
|
4
|
+
const name = v => typeof v === 'string' && /^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$/.test(v);
|
|
5
|
+
const safe = v => typeof v === 'string' && v.length <= 4096
|
|
6
|
+
&& !/[\x00-\x1f\x7f]|https?:\/\/[^/\s]*@|(?:gh[pousr]_|github_pat_)[A-Za-z0-9_]{16,}/.test(v);
|
|
7
|
+
const nullable = v => v === null || safe(v);
|
|
8
|
+
export function spawnEffective(v) {
|
|
9
|
+
if (!record(v) || !absolute(v.repo) || !['worktree', 'checkout', 'directory', 'workspace', 'attached'].includes(v.work)
|
|
10
|
+
|| !HARNESSES.includes(harnessOf(v)) || !nullable(v.model) || !nullable(v.launchConfig)
|
|
11
|
+
|| v.yolo !== null && typeof v.yolo !== 'boolean' || v.backend !== 'tmux'
|
|
12
|
+
|| typeof v.childSpawns !== 'boolean') return null;
|
|
13
|
+
let relation = null;
|
|
14
|
+
if (v.relation !== null) {
|
|
15
|
+
const r = v.relation, a = r?.anchor;
|
|
16
|
+
if (!record(r) || !['child', 'sibling', 'parent'].includes(r.kind) || !record(a)
|
|
17
|
+
|| !name(a.instance) || !absolute(a.agentsRoot)) return null;
|
|
18
|
+
relation = { kind: r.kind, anchor: { instance: a.instance, agentsRoot: a.agentsRoot } };
|
|
19
|
+
}
|
|
20
|
+
return { repo: v.repo, work: v.work, harness: harnessOf(v), model: v.model, launchConfig: v.launchConfig,
|
|
21
|
+
yolo: v.yolo, backend: v.backend, childSpawns: v.childSpawns, relation };
|
|
22
|
+
}
|
|
23
|
+
export function spawnDecision(v, { effectiveRequired = false } = {}) {
|
|
24
|
+
if (!record(v) || !name(v.instance) || !absolute(v.home) || !nullable(v.branch)
|
|
25
|
+
|| typeof v.revision !== 'string' || !/^[a-f0-9]{24}$/.test(v.revision)) return null;
|
|
26
|
+
let base = null;
|
|
27
|
+
if (v.base !== null) {
|
|
28
|
+
if (!record(v.base) || !safe(v.base.ref) || !v.base.ref || typeof v.base.oid !== 'string'
|
|
29
|
+
|| !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(v.base.oid)) return null;
|
|
30
|
+
base = { ref: v.base.ref, oid: v.base.oid };
|
|
31
|
+
}
|
|
32
|
+
const hasEffective = Object.hasOwn(v, 'effective');
|
|
33
|
+
const effective = hasEffective ? spawnEffective(v.effective) : null;
|
|
34
|
+
if (hasEffective && !effective || effectiveRequired && !effective) return null;
|
|
35
|
+
if (effective && (effective.work === 'worktree' ? !v.branch || !base : v.branch !== null || base !== null)) return null;
|
|
36
|
+
// The workspace resolution the decision binds (a member that moved between
|
|
37
|
+
// preview and apply is E_DECISION_STALE); absent only before workspace v2.
|
|
38
|
+
if (Object.hasOwn(v, 'resolution') && (typeof v.resolution !== 'string' || !/^[a-f0-9]{24}$/.test(v.resolution))) return null;
|
|
39
|
+
return { instance: v.instance, home: v.home, branch: v.branch, base,
|
|
40
|
+
...(hasEffective ? { effective } : {}), ...(Object.hasOwn(v, 'resolution') ? { resolution: v.resolution } : {}), revision: v.revision };
|
|
41
|
+
}
|
|
42
|
+
/** Equality of projected strong decisions, not an attempt to recompute their hash. */
|
|
43
|
+
export function sameSpawnDecision(a, b) {
|
|
44
|
+
const left = spawnDecision(a, { effectiveRequired: true }), right = spawnDecision(b, { effectiveRequired: true });
|
|
45
|
+
return !!left && !!right && JSON.stringify(left) === JSON.stringify(right);
|
|
46
|
+
}
|