@awebai/oats 0.51.0 → 0.52.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/bin/oats.mjs +109 -37
- package/docs/capabilities.md +9 -2
- package/docs/configuration.md +134 -88
- package/docs/desktop-cli-api.md +927 -92
- package/docs/desktop-instance-start.md +56 -0
- package/docs/desktop.md +10 -7
- package/docs/execution-targets.md +144 -58
- package/docs/first-team.md +3 -1
- package/docs/harness-trust.md +50 -2
- package/docs/implementation.md +66 -9
- package/docs/integrations.md +9 -8
- package/docs/knowledge-reference/acceptance.md +1 -0
- package/docs/knowledge-reference/harvester.md +5 -3
- package/docs/knowledge-reference/model.md +5 -3
- package/docs/knowledge-theory.md +1 -1
- package/docs/knowledge.md +25 -2
- package/docs/launch-prompt-completion.md +50 -48
- package/docs/oats-local.schema.json +4 -3
- package/docs/official-catalog.md +4 -4
- package/docs/packages.md +14 -14
- package/docs/release-lane.md +15 -5
- package/docs/release-notes/v0.44.0.md +1 -1
- package/docs/release-notes/v0.52.0.md +933 -0
- package/docs/schedules.md +91 -4
- package/docs/souls-and-instances.md +95 -25
- package/docs/tui.md +152 -0
- package/docs/workspaces.md +2 -2
- package/lib/claim.mjs +186 -46
- package/lib/core.mjs +730 -185
- package/lib/errors.mjs +170 -0
- package/lib/harness-trust-write.mjs +68 -27
- package/lib/harness-trust.mjs +34 -16
- package/lib/instance-inspect.mjs +40 -11
- package/lib/instance-lifecycle.mjs +169 -47
- package/lib/launch-preference.mjs +16 -0
- package/lib/launch-prompt-completion.mjs +7 -43
- package/lib/launch-prompt-evidence.mjs +14 -7
- package/lib/launch-prompt-fixtures/README.md +86 -152
- package/lib/launch-prompt-fixtures/dev-channel-confirmation.json +50 -0
- package/lib/launch-prompt-fixtures.mjs +122 -109
- package/lib/launch-prompt-transport.mjs +2 -56
- package/lib/launch-prompts.mjs +102 -100
- package/lib/schedule-host.mjs +154 -22
- package/lib/schedule.mjs +73 -24
- package/lib/system-tools.mjs +39 -0
- package/lib/tmux-server-scope.mjs +62 -0
- package/lib/triggers.mjs +4 -4
- package/lib/workspace.mjs +5 -11
- package/lib/worktree-hooks.mjs +98 -20
- package/lib/worktree.mjs +83 -24
- package/package-catalog.json +3 -3
- package/package.json +7 -2
- package/packages/client/capability-show-contract.mjs +230 -0
- package/packages/client/capability-warnings-contract.mjs +57 -0
- package/packages/client/cli-adapter.mjs +548 -0
- package/packages/client/cli-environment.mjs +53 -0
- package/packages/client/cli-locator.mjs +253 -0
- package/packages/client/cli-probe-contract.mjs +47 -0
- package/packages/client/client-terms.mjs +60 -0
- package/packages/client/deployment-contract.mjs +68 -0
- package/packages/client/deployment-data.mjs +483 -0
- package/packages/client/deployment-facts.mjs +34 -0
- package/packages/client/deployment-label.mjs +76 -0
- package/packages/client/deployment-observer.mjs +89 -0
- package/packages/client/deployment-panel.mjs +142 -0
- package/packages/client/deployment-read-cli.mjs +53 -0
- package/packages/client/display-text.mjs +44 -0
- package/packages/client/harness-names.mjs +30 -0
- package/packages/client/inspect-contract.mjs +62 -0
- package/packages/client/instance-acts.mjs +54 -0
- package/packages/client/instance-admission.mjs +45 -0
- package/packages/client/instance-events-contract.mjs +74 -0
- package/packages/client/instance-git-contract.mjs +80 -0
- package/packages/client/instance-presentation.mjs +22 -0
- package/packages/client/instance-tree.mjs +453 -0
- package/packages/client/kernel-environment.mjs +11 -0
- package/packages/client/launch-contract.mjs +51 -0
- package/packages/client/launch-prompt-outcome.mjs +165 -0
- package/packages/client/lifecycle-cli.mjs +61 -0
- package/packages/client/lifecycle-contract.mjs +372 -0
- package/packages/client/liveness-main.mjs +10 -0
- package/packages/client/liveness.mjs +35 -0
- package/packages/client/machine-contract.mjs +123 -0
- package/packages/client/own-environment.mjs +22 -0
- package/packages/client/panel-views.mjs +286 -0
- package/packages/client/readiness-contract.mjs +172 -0
- package/packages/client/refresh-loop.mjs +52 -0
- package/packages/client/remote-address.mjs +126 -0
- package/packages/client/remote-roster.mjs +67 -0
- package/packages/client/roster-sections.mjs +80 -0
- package/packages/client/spawn-apply-cli.mjs +104 -0
- package/packages/client/spawn-apply-contract.mjs +183 -0
- package/packages/client/spawn-decision.mjs +46 -0
- package/packages/client/spawn-messages.mjs +119 -0
- package/packages/client/spawn-preview-cli.mjs +32 -0
- package/packages/client/spawn-preview-contract.mjs +314 -0
- package/packages/client/team-members.mjs +41 -0
- package/packages/client/team-rows.mjs +45 -0
- package/packages/client/terminal-contract.mjs +57 -0
- package/packages/client/tmux-status.mjs +66 -0
- package/packages/client/waiting-on-you.mjs +88 -0
- package/packages/client/workspace-admission.mjs +45 -0
- package/packages/client/workspace-cli.mjs +142 -0
- package/packages/client/workspace-views.mjs +147 -0
- package/packages/tui/README.md +46 -0
- package/packages/tui/bin/tui.mjs +7 -0
- package/packages/tui/lib/actions.mjs +29 -0
- package/packages/tui/lib/client.mjs +4 -0
- package/packages/tui/lib/main.mjs +105 -0
- package/packages/tui/lib/term/keys.mjs +323 -0
- package/packages/tui/lib/term/screen.mjs +122 -0
- package/packages/tui/lib/term/style.mjs +43 -0
- package/packages/tui/lib/term/text.mjs +49 -0
- package/packages/tui/lib/term/tty.mjs +168 -0
- package/packages/tui/lib/term/width.mjs +124 -0
- package/packages/tui/lib/views/frame.mjs +62 -0
- package/packages/tui/lib/views/help.mjs +28 -0
- package/packages/tui/package.json +8 -0
- package/skills/oats-getting-started/SKILL.md +29 -22
- package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-05-channel-seeded.txt +0 -35
- package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-06-first-after-channel.txt +0 -35
- package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-07-after-channel-200ms.txt +0 -35
- package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-08-installed-after-channel-200ms.txt +0 -35
- package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/manifest.json +0 -77
- package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/max-bypass-source.json +0 -88
- package/lib/launch-prompt-fixtures/structural-completion.json +0 -205
- package/lib/launch-prompt-policy.mjs +0 -87
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
/** Readiness on the workspace model (`readinessApi: 2`), shared by the
|
|
2
|
+
* zero-dependency server and renderer. The subject is a soul or an instance,
|
|
3
|
+
* never a scope. The four checks are the kernel's; a provider's binding check
|
|
4
|
+
* is relayed verbatim. An admitted read is not a lease or spawn authority. */
|
|
5
|
+
import { effectiveOf, REPORT_FROM } from './launch-contract.mjs';
|
|
6
|
+
import { defaultTeamOf } from './team-rows.mjs';
|
|
7
|
+
import { remoteReason } from './remote-address.mjs';
|
|
8
|
+
import { warningsOf } from './capability-warnings-contract.mjs';
|
|
9
|
+
import { displayLine } from './display-text.mjs';
|
|
10
|
+
export const READINESS_API = 2;
|
|
11
|
+
export const CHECKS = ['installed', 'configured', 'member', 'providers'];
|
|
12
|
+
export const record = v => !!v && typeof v === 'object' && !Array.isArray(v);
|
|
13
|
+
export const absolute = v => typeof v === 'string' && v.startsWith('/') && v.length <= 4096 && !/[\x00-\x1f\x7f]/.test(v);
|
|
14
|
+
const name = v => typeof v === 'string' && /^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$/.test(v);
|
|
15
|
+
const exact = (v, keys) => record(v) && Object.keys(v).every(k => keys.includes(k));
|
|
16
|
+
const states = ['pass', 'fail', 'unknown', 'not-applicable'];
|
|
17
|
+
const unsafe = /[\x00-\x08\x0b-\x1f\x7f]|[a-z][a-z0-9+.-]*:\/\/[^\s/]*@|(?:token|authorization|password|secret|api[_ -]?key)\s*[:=]\s*\S+/i;
|
|
18
|
+
function text(v, max = 1024) { if (typeof v !== 'string' || v.length > max) throw Error(); return unsafe.test(v) ? '[Detail withheld]' : v; }
|
|
19
|
+
const nullable = v => v == null ? null : text(v);
|
|
20
|
+
export function readinessSelector(v) {
|
|
21
|
+
if (!record(v)) return null;
|
|
22
|
+
if (v.kind === 'soul' && exact(v, ['kind', 'soul', 'agentsRoot']) && name(v.soul) && absolute(v.agentsRoot)) return { kind: v.kind, soul: v.soul, agentsRoot: v.agentsRoot };
|
|
23
|
+
if (v.kind === 'instance' && exact(v, ['kind', 'instance', 'agent', 'agentsRoot', 'server']) && name(v.instance) && name(v.agent) && absolute(v.agentsRoot)
|
|
24
|
+
&& (v.server == null || typeof v.server === 'string' && /^[a-z0-9][a-z0-9-]{0,63}$/.test(v.server))) return { kind: v.kind, instance: v.instance, agent: v.agent, agentsRoot: v.agentsRoot, server: v.server ?? null };
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
/** The probe integer is the gate (no feature string). */
|
|
28
|
+
export function readinessSupported(cli) { return cli?.ok === true && absolute(cli.bin) && cli.readinessApi === READINESS_API; }
|
|
29
|
+
export function readinessTarget(v) {
|
|
30
|
+
const selector = readinessSelector(v?.selector);
|
|
31
|
+
if (!selector || !record(v) || typeof v.workspace !== 'string' || !v.workspace || v.workspace.length > 4096 || !absolute(v.context)
|
|
32
|
+
|| v.observedAs !== selector.kind || selector.kind === 'instance' && !absolute(v.home)) return null;
|
|
33
|
+
return { workspace: v.workspace, context: v.context, observedAs: selector.kind, selector, ...(selector.kind === 'instance' ? { home: v.home } : {}) };
|
|
34
|
+
}
|
|
35
|
+
const ERRORS = {
|
|
36
|
+
E_BAD_ARGS: 'Readiness requires one workspace and a bounded, qualified read selector.',
|
|
37
|
+
E_WORKSPACE_UNKNOWN: 'Select a known local workspace.', E_TARGET_CHANGED: 'The selected workspace, target or CLI changed. Refresh readiness.',
|
|
38
|
+
E_SESSION_UNKNOWN: 'The selected instance is no longer reported.', E_AMBIGUOUS_INSTANCE: 'The selected instance is ambiguous.',
|
|
39
|
+
E_SOUL_UNKNOWN: 'Select one local soul and its exact agents root.', E_HOME_MISMATCH: 'The instance home no longer matches its admitted identity.',
|
|
40
|
+
'cli-unavailable': 'Select a compatible installed OATS CLI.', 'cli-no-readiness': 'The installed OATS CLI is older than this Desktop (no readiness API 2). Update OATS and retry.',
|
|
41
|
+
'unsupported-remote-operation': "This computer's OATS can't route this to the server. Update OATS here.",
|
|
42
|
+
E_UNSUPPORTED_MODE: 'Captured incarnation: readiness comes from its resolution, not current configuration.',
|
|
43
|
+
'unsupported-action': 'Readiness is unavailable for this captured target; no classic fallback.', E_BUSY: 'The readiness read limit is reached. Retry when another read finishes.',
|
|
44
|
+
E_FORBIDDEN_FRAME: 'This frame cannot request readiness.', E_CLI_FAILED: 'The installed CLI could not complete the readiness read.',
|
|
45
|
+
E_CLI_TIMEOUT: 'The readiness read timed out.', E_CLI_OUTPUT_LIMIT: 'The readiness read exceeded its output limit.',
|
|
46
|
+
E_CLI_PROTOCOL: 'The installed CLI returned invalid or contradictory readiness data.',
|
|
47
|
+
'classic-workspace': 'This workspace still uses the classic layout, which answers an older readiness shape. Readiness shows here once it is on the workspace model.', E_USAGE: 'The installed CLI does not support this read.',
|
|
48
|
+
};
|
|
49
|
+
/** A provider binding check's own answer → the item status the kernel reports for it. */
|
|
50
|
+
export const PROVIDER_ITEM_STATUS = Object.freeze({ ready: 'pass', 'needs-configuration': 'fail', 'authorization-required': 'fail', unavailable: 'unknown' });
|
|
51
|
+
/** `reason`: a remote read's reason (remote-address.mjs), kept only when it validates. */
|
|
52
|
+
export function readinessFailure(code, target = null, reason = null) {
|
|
53
|
+
if (!Object.hasOwn(ERRORS, code)) code = 'E_CLI_FAILED';
|
|
54
|
+
return { readinessViewApi: 1, status: 'unavailable', target: readinessTarget(target), data: null, reason: remoteReason(reason) || { code, message: ERRORS[code] } };
|
|
55
|
+
}
|
|
56
|
+
/** The fixed sentence for a readiness code: the headline of a host refusal outside the remote table. */
|
|
57
|
+
export const readinessMessage = code => readinessFailure(code).reason.message;
|
|
58
|
+
const problems = v => {
|
|
59
|
+
if (!Array.isArray(v) || v.length > 64) throw Error();
|
|
60
|
+
return v.map(p => { if (!record(p)) throw Error(); return { code: text(p.code, 128), message: text(p.message) }; });
|
|
61
|
+
};
|
|
62
|
+
/** A module's origin as the kernel records it: member commit, or package version + commit + integrity. */
|
|
63
|
+
function origin(v) {
|
|
64
|
+
if (!record(v) || !['member', 'package', 'external'].includes(v.kind)) throw Error();
|
|
65
|
+
const out = { kind: v.kind };
|
|
66
|
+
for (const k of ['package', 'version', 'commit', 'integrity', 'repoKey']) if (Object.hasOwn(v, k)) out[k] = nullable(v[k]);
|
|
67
|
+
return out;
|
|
68
|
+
}
|
|
69
|
+
const EVIDENCE = ['repoKey', 'workspace', 'commit', 'command', 'version', 'integrity', 'file'];
|
|
70
|
+
function item(v) {
|
|
71
|
+
if (!record(v) || !states.includes(v.status) || typeof v.required !== 'boolean') throw Error();
|
|
72
|
+
const evidence = {};
|
|
73
|
+
if (v.evidence != null) {
|
|
74
|
+
if (!record(v.evidence)) throw Error();
|
|
75
|
+
for (const k of EVIDENCE) if (Object.hasOwn(v.evidence, k)) evidence[k] = v.evidence[k] === null ? null : text(v.evidence[k], 4096);
|
|
76
|
+
if (Object.hasOwn(v.evidence, 'from')) evidence.from = origin(v.evidence.from);
|
|
77
|
+
}
|
|
78
|
+
const out = { subject: text(v.subject), status: v.status, required: v.required, reason: nullable(v.reason), producer: text(v.producer),
|
|
79
|
+
evidence, remedy: nullable(v.remedy) };
|
|
80
|
+
if (v.capability != null) { if (!record(v.capability)) throw Error(); out.capability = { id: text(v.capability.id, 256) }; }
|
|
81
|
+
if (typeof v.code === 'string') out.code = text(v.code, 128);
|
|
82
|
+
// launch-prompt (0.52.0): the home's last start stopped at a screen the kernel does not confirm, and its
|
|
83
|
+
// reason quotes what that terminal showed. One display line, for this code only; the kernel's sentence
|
|
84
|
+
// already says whose text it is ("found …"). The item's own `differed` is not read: the reason says it once.
|
|
85
|
+
if (v.code === 'launch-prompt') out.reason = displayLine(out.reason);
|
|
86
|
+
// harness-trust (0.52.0): the configuration file whose folder trust the item is about, top-level beside
|
|
87
|
+
// `evidence`, also on a passing item. Read tolerantly: anything but an absolute path with nothing unsafe
|
|
88
|
+
// in it drops this fact, never the read (dropped, not withheld: the answer must read the same when it is
|
|
89
|
+
// projected again). The item's other top-level keys (`harness`, `deployment`) are not read.
|
|
90
|
+
if (v.code === 'harness-trust' && absolute(v.file) && !unsafe.test(v.file)) out.file = v.file;
|
|
91
|
+
// Team model v2 (0.30, K1 amendment g): team items live in checks.configured (no fifth check),
|
|
92
|
+
// subject 'team <label>' or 'teams', and carry the team's label, whether it is the default, and
|
|
93
|
+
// where it is declared (at).
|
|
94
|
+
if (Object.hasOwn(v, 'label')) { if (typeof v.label !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(v.label)) throw Error(); out.label = v.label; }
|
|
95
|
+
if (Object.hasOwn(v, 'default')) { if (typeof v.default !== 'boolean') throw Error(); out.default = v.default; }
|
|
96
|
+
// Where the value is declared (a team; launch-changed's current layer), or null: launch-changed's `at`
|
|
97
|
+
// is null when the current launch comes from a flag or the host default.
|
|
98
|
+
if (Object.hasOwn(v, 'at')) { if (v.at !== null && (typeof v.at !== 'string' || !v.at || v.at.length > 512 || /[\x00-\x1f\x7f]/.test(v.at))) throw Error(); out.at = v.at; }
|
|
99
|
+
// `recorded`/`current` mean what the item's code says (--home only), so they are decoded per code:
|
|
100
|
+
// - launch-changed (launch preferences): each an effective launch {harness, model, launchConfig}, plus
|
|
101
|
+
// the current layer's `from` (its `at` is above: null when that layer is the host default);
|
|
102
|
+
// - default-team-changed (team model v2): each the kernel's DefaultTeam {label, team, from}, or null.
|
|
103
|
+
// Another code's recorded/current/from are not read (they may be anything; the item still shows).
|
|
104
|
+
if (v.code === 'launch-changed') {
|
|
105
|
+
for (const key of ['recorded', 'current']) { const l = effectiveOf(v[key]); if (!l) throw Error(); out[key] = l; }
|
|
106
|
+
if (!REPORT_FROM.includes(v.from)) throw Error(); out.from = v.from;
|
|
107
|
+
if (!Object.hasOwn(v, 'at')) throw Error();
|
|
108
|
+
} else if (v.code === 'default-team-changed') {
|
|
109
|
+
for (const key of ['recorded', 'current']) { const d = Object.hasOwn(v, key) ? defaultTeamOf(v[key]) : undefined; if (d === undefined) throw Error(); out[key] = d; }
|
|
110
|
+
}
|
|
111
|
+
// The provider's own binding-check answer, relayed verbatim (`providers`):
|
|
112
|
+
// {status, problems, warnings}. Warnings (always emitted, maybe []) never change status.
|
|
113
|
+
if (Object.hasOwn(v, 'result')) {
|
|
114
|
+
if (v.result === null) out.result = null;
|
|
115
|
+
// A known answer fixes the item status (a contradiction fails closed). The four
|
|
116
|
+
// statuses are additive: an unrecognised one is relayed as sent, and the kernel's
|
|
117
|
+
// item status stands (docs/desktop-cli-api.md, providers).
|
|
118
|
+
else if (record(v.result) && typeof v.result.status === 'string' && v.result.status && v.result.status.length <= 64
|
|
119
|
+
&& (!Object.hasOwn(PROVIDER_ITEM_STATUS, v.result.status) || PROVIDER_ITEM_STATUS[v.result.status] === v.status)) {
|
|
120
|
+
out.result = { status: v.result.status, problems: problems(v.result.problems), warnings: problems(v.result.warnings) };
|
|
121
|
+
} else throw Error();
|
|
122
|
+
}
|
|
123
|
+
if (Object.hasOwn(v, 'problems')) out.problems = problems(v.problems);
|
|
124
|
+
return out;
|
|
125
|
+
}
|
|
126
|
+
function subjectOf(v, t) {
|
|
127
|
+
if (!record(v)) return null;
|
|
128
|
+
if (t.observedAs === 'soul') {
|
|
129
|
+
if (v.kind !== 'soul' || v.soul !== t.selector.soul) return null;
|
|
130
|
+
return { kind: 'soul', soul: v.soul, repoKey: nullable(v.repoKey), commit: nullable(v.commit), team: nullable(v.team) };
|
|
131
|
+
}
|
|
132
|
+
if (v.kind !== 'instance' || v.instance !== t.selector.instance || v.home !== t.home || v.soul !== t.selector.agent) return null;
|
|
133
|
+
return { kind: 'instance', instance: v.instance, home: v.home, soul: v.soul };
|
|
134
|
+
}
|
|
135
|
+
function policy(v) {
|
|
136
|
+
if (!record(v)) throw Error();
|
|
137
|
+
const result = {};
|
|
138
|
+
for (const key of ['childSpawns', 'worktrees']) {
|
|
139
|
+
const p = v[key];
|
|
140
|
+
if (!record(p) || ![true, false, null].includes(p.allowed) || typeof p.enforced !== 'boolean' || !record(p.origin)) throw Error();
|
|
141
|
+
result[key] = { allowed: p.allowed, enforced: p.enforced, origin: { kind: text(p.origin.kind), detail: nullable(p.origin.detail) },
|
|
142
|
+
...(key === 'worktrees' ? { mode: nullable(p.mode) } : {}) };
|
|
143
|
+
}
|
|
144
|
+
return result;
|
|
145
|
+
}
|
|
146
|
+
export function readinessData(v, target) {
|
|
147
|
+
try {
|
|
148
|
+
const t = readinessTarget(target);
|
|
149
|
+
if (!t || !record(v) || v.readinessApi !== READINESS_API || !record(v.checks) || !record(v.summary)) return null;
|
|
150
|
+
const subject = subjectOf(v.subject, t);
|
|
151
|
+
if (!subject) return null;
|
|
152
|
+
if (typeof v.at !== 'string' || v.at.length > 40 || !Number.isFinite(Date.parse(v.at))) return null;
|
|
153
|
+
const checks = {};
|
|
154
|
+
for (const key of CHECKS) {
|
|
155
|
+
const c = v.checks[key];
|
|
156
|
+
if (!record(c) || !states.includes(c.status) || !Array.isArray(c.items) || c.items.length > 1000) return null;
|
|
157
|
+
checks[key] = { status: c.status, items: c.items.map(item) };
|
|
158
|
+
}
|
|
159
|
+
const required = Object.values(checks).flatMap(c => c.items).filter(i => i.required);
|
|
160
|
+
const s = v.summary;
|
|
161
|
+
if (typeof s.ready !== 'boolean' || !['required', 'pass', 'fail', 'unknown'].every(k => Number.isInteger(s[k]) && s[k] >= 0)
|
|
162
|
+
|| s.required !== required.length || ['pass', 'fail', 'unknown'].some(k => s[k] !== required.filter(i => i.status === k).length)
|
|
163
|
+
|| s.ready !== (required.length > 0 && required.every(i => ['pass', 'not-applicable'].includes(i.status)))) return null;
|
|
164
|
+
if (!Array.isArray(v.notes) || v.notes.length > 64) return null;
|
|
165
|
+
return { readinessApi: READINESS_API, subject, at: v.at, checks,
|
|
166
|
+
summary: { ready: s.ready, required: s.required, pass: s.pass, fail: s.fail, unknown: s.unknown },
|
|
167
|
+
policy: policy(v.policy), notes: v.notes.map(n => text(n)),
|
|
168
|
+
// Capability warnings (0.49.0): tolerant (a malformed list reads as none, never refuses the document), idempotent
|
|
169
|
+
// (the server projects, the renderer projects again), and outside the summary: they never change ready or a count.
|
|
170
|
+
warnings: warningsOf(v.warnings) };
|
|
171
|
+
} catch { return null; }
|
|
172
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/** The deployment refresh loop: one observation cycle at a time, the next one
|
|
2
|
+
* scheduled an interval AFTER the previous completed (never back to back, so
|
|
3
|
+
* a slow kernel is never asked twice at once), backing off while the window
|
|
4
|
+
* is blurred. A request during a run schedules exactly one follow-up, never
|
|
5
|
+
* a queue: a mutation's result must be observed, and one requester asking
|
|
6
|
+
* `live` is enough to make that follow-up live. */
|
|
7
|
+
export const REFRESH_FOCUSED_MS = 5000, REFRESH_BLURRED_MS = 30000;
|
|
8
|
+
|
|
9
|
+
export function createRefreshLoop({ run, focusedMs = REFRESH_FOCUSED_MS, blurredMs = REFRESH_BLURRED_MS, timers = { setTimeout, clearTimeout }, now = () => Date.now() } = {}) {
|
|
10
|
+
let focused = true, active = false, timer = null, inflight = null, followUp = null, completedAt = null;
|
|
11
|
+
function clear() { if (timer !== null) { timers.clearTimeout(timer); timer = null; } }
|
|
12
|
+
function arm(ms) {
|
|
13
|
+
clear();
|
|
14
|
+
timer = timers.setTimeout(() => { timer = null; void execute(false); }, Math.max(0, ms));
|
|
15
|
+
if (typeof timer?.unref === 'function') timer.unref(); // the loop never keeps the process alive on its own
|
|
16
|
+
}
|
|
17
|
+
function execute(live) {
|
|
18
|
+
clear();
|
|
19
|
+
inflight = Promise.resolve().then(() => run({ live })).catch(() => {}).then(() => {
|
|
20
|
+
inflight = null; completedAt = now();
|
|
21
|
+
if (followUp) {
|
|
22
|
+
// The follow-up runs regardless of stop(): its requesters await an observation.
|
|
23
|
+
const { live: again, waiters } = followUp; followUp = null;
|
|
24
|
+
const promise = execute(again); for (const resolve of waiters) resolve(promise);
|
|
25
|
+
} else if (active) arm(focused ? focusedMs : blurredMs);
|
|
26
|
+
});
|
|
27
|
+
return inflight;
|
|
28
|
+
}
|
|
29
|
+
return {
|
|
30
|
+
start() { active = true; return execute(false); },
|
|
31
|
+
/** Observe now (or right after the current run) and resolve once that observation completed. */
|
|
32
|
+
request({ live = false } = {}) {
|
|
33
|
+
if (!inflight) return execute(live);
|
|
34
|
+
followUp ||= { live: false, waiters: [] };
|
|
35
|
+
followUp.live ||= live; // never downgrade a live request
|
|
36
|
+
return new Promise(resolve => followUp.waiters.push(resolve));
|
|
37
|
+
},
|
|
38
|
+
setFocused(value) {
|
|
39
|
+
const next = Boolean(value);
|
|
40
|
+
if (next === focused) return;
|
|
41
|
+
focused = next;
|
|
42
|
+
if (!active) return;
|
|
43
|
+
// Focus return: one prompt refresh when idle; a run in flight already is that refresh.
|
|
44
|
+
if (focused) { if (!inflight) void execute(false); }
|
|
45
|
+
// Blur with a timer pending: the next run moves out to blurredMs after the last completion, never earlier.
|
|
46
|
+
else if (timer !== null) arm(completedAt + blurredMs - now());
|
|
47
|
+
},
|
|
48
|
+
running() { return inflight !== null; },
|
|
49
|
+
focused() { return focused; },
|
|
50
|
+
stop() { active = false; clear(); },
|
|
51
|
+
};
|
|
52
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
/** Which roster rows can be addressed, why a row can't, and the copy for a remote read or plan
|
|
2
|
+
* that the host (or this machine's router) refused. Shared by the renderer and the server. */
|
|
3
|
+
import { unsupportedSession } from './instance-presentation.mjs';
|
|
4
|
+
import { displayLine, cleanLine, DETAIL_WITHHELD } from './display-text.mjs';
|
|
5
|
+
|
|
6
|
+
/** A local row, or a remote row the kernel reports addressable (routed by `--server <id> --home <abs>`).
|
|
7
|
+
* A local OATS before 0.31 reports no `addressable` at all: a row it spawned keeps its saved route. */
|
|
8
|
+
export const canAddressRemote = row => !!row && (!row.server || row.addressable === true
|
|
9
|
+
|| (row.addressable === undefined && row.savedRoute === true));
|
|
10
|
+
|
|
11
|
+
/** The server's registration label as the roster reports it, else its id. */
|
|
12
|
+
export const serverLabel = row => row?.repoName || row?.server || '';
|
|
13
|
+
|
|
14
|
+
/** The server's label as a sentence shows it: one display line (display-text.mjs), so the sentence is one
|
|
15
|
+
* too. A label with nothing to show, or a withheld one, reads "the server", the words the fixed sentences
|
|
16
|
+
* already use. For the sentence only: routing, comparison and requests keep the label and the server id
|
|
17
|
+
* as they are. `first`: the label opens the sentence. */
|
|
18
|
+
export const shownLabel = (label, first = false) => {
|
|
19
|
+
const line = displayLine(label);
|
|
20
|
+
return line === null || line === DETAIL_WITHHELD ? first ? 'The server' : 'the server' : line;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
/** Why a remote row is refused when the kernel does not report it addressable. */
|
|
24
|
+
export function unaddressableSentence(row) {
|
|
25
|
+
const label = serverLabel(row);
|
|
26
|
+
if (row.missingRemotely === true) return `${row.instance} is no longer on ${shownLabel(label)}. Remove it from this computer with: oats server forget ${row.server} --instance ${row.instance}`;
|
|
27
|
+
return row.addressable === undefined ? `This computer's OATS does not report whether ${shownLabel(label)} can reach this instance. Update OATS here.`
|
|
28
|
+
: `${shownLabel(label, true)} did not report this instance as reachable.`;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Why a row can't be opened, as `{key, label, sentence}`, or null when nothing stands in the way.
|
|
32
|
+
* `label` is the roster meta line's state segment; `sentence` is the row's title, accessible
|
|
33
|
+
* description and actions-menu reason. */
|
|
34
|
+
export function rowReason(row) {
|
|
35
|
+
const label = serverLabel(row);
|
|
36
|
+
const herdr = unsupportedSession(row);
|
|
37
|
+
if (herdr) return { key: 'herdr', label: 'Herdr no longer supported', sentence: herdr };
|
|
38
|
+
if (row.server && row.serverUnreached) return { key: 'unreached', label: `${label} not reached`,
|
|
39
|
+
sentence: row.runtimeError || `${label} was not reached.` };
|
|
40
|
+
if (row.server && row.missingRemotely === true) return { key: 'missing', label: `gone from ${label}`, sentence: unaddressableSentence(row) };
|
|
41
|
+
if (!canAddressRemote(row)) return { key: 'unaddressable', label: `not reachable on ${label}`, sentence: unaddressableSentence(row) };
|
|
42
|
+
if (row.running == null) return { key: 'unknown', label: 'state unknown', sentence: row.runtimeError || `${row.instance}: status unknown` };
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const HEADLINES = {
|
|
47
|
+
E_REMOTE_INCOMPATIBLE: label => `${shownLabel(label, true)} runs an OATS that can't do this yet.`,
|
|
48
|
+
E_SNAPSHOT_UNKNOWN: label => `${shownLabel(label, true)} doesn't list this instance any more.`,
|
|
49
|
+
E_HOME_MISMATCH: label => `${shownLabel(label, true)} answered for a different instance. Nothing was changed.`,
|
|
50
|
+
E_AMBIGUOUS: label => `${shownLabel(label, true)} answered for a different instance. Nothing was changed.`,
|
|
51
|
+
// Transport: ssh itself failed, or this machine's own deadline on the remote read passed.
|
|
52
|
+
E_SSH: label => `Couldn't reach ${shownLabel(label)}.`,
|
|
53
|
+
E_CLI_TIMEOUT: label => `Couldn't reach ${shownLabel(label)}.`,
|
|
54
|
+
};
|
|
55
|
+
/** The headline for a remote failure: the table's, else the view's own sentence for the code. The
|
|
56
|
+
* server's label is shown as one display line, so a headline is always one. */
|
|
57
|
+
export const remoteHeadline = (code, label, fallback) => Object.hasOwn(HEADLINES, code) ? HEADLINES[code](label) : fallback;
|
|
58
|
+
|
|
59
|
+
export const readingFrom = label => `Reading from ${label}…`;
|
|
60
|
+
|
|
61
|
+
/** A host's E_REMOTE_INCOMPATIBLE for a panel read (the context panel's Soul tab and teams): the server,
|
|
62
|
+
* what it can't show and what to upgrade. `what`: "soul", "teams". */
|
|
63
|
+
export const incompatibleSentence = (label, what) =>
|
|
64
|
+
`${shownLabel(label, true)} runs an OATS that can't show this instance's ${what} here (it needs the operations feature). Update OATS on ${shownLabel(label)}.`;
|
|
65
|
+
|
|
66
|
+
/** Why an instance inspection for a remote row is not sent (an Error for a failed block: the sentence, and
|
|
67
|
+
* the code when there is one), or null. A row the kernel does not report addressable says why; this
|
|
68
|
+
* computer's OATS without remote operations can't route it. A local row is never blocked. */
|
|
69
|
+
export function remoteInspectBlock(row, cli) {
|
|
70
|
+
if (!row?.server) return null;
|
|
71
|
+
if (!canAddressRemote(row)) return new Error(unaddressableSentence(row));
|
|
72
|
+
if (!Array.isArray(cli?.remote) || !cli.remote.includes('operations')) {
|
|
73
|
+
const { message, code, detail } = unroutableReason(serverLabel(row));
|
|
74
|
+
return Object.assign(new Error(message), { code, detail });
|
|
75
|
+
}
|
|
76
|
+
return null;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** The error a view's loading state shows for a failed read: the relayed remote reason when the request's
|
|
80
|
+
* error carries one (re-validated where it was received), as an Error with its code and detail; else the
|
|
81
|
+
* error as it came. `what` ("soul", "teams") words a host's E_REMOTE_INCOMPATIBLE for the panel read
|
|
82
|
+
* (incompatibleSentence); without it the relayed headline stands. */
|
|
83
|
+
export function relayedFailure(error, label, what = null) {
|
|
84
|
+
const reason = error?.reason;
|
|
85
|
+
if (!reason || typeof reason.message !== 'string') return error;
|
|
86
|
+
const message = what && reason.code === 'E_REMOTE_INCOMPATIBLE' ? incompatibleSentence(label, what) : reason.message;
|
|
87
|
+
return Object.assign(new Error(message), { code: reason.code, detail: reason.detail ?? null });
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const CODE = /^E_[A-Z0-9_]{1,64}$/;
|
|
91
|
+
const MAX_MESSAGE = 512;
|
|
92
|
+
/** A code in the kernel's code shape. */
|
|
93
|
+
export const kernelCode = v => typeof v === 'string' && CODE.test(v);
|
|
94
|
+
|
|
95
|
+
/** A failure's Details line as nodes: its code, and the kernel's own message when a host sent one. The
|
|
96
|
+
* code and the colon are text. The message is alone inside a <bdi>, as a text node: its bidirectional
|
|
97
|
+
* layout is isolated from the text around it. Only a message that is already a display line is shown. */
|
|
98
|
+
export function codeLineNodes(doc, reason) {
|
|
99
|
+
const code = typeof reason?.code === 'string' && reason.code ? reason.code : null;
|
|
100
|
+
if (!code) return [];
|
|
101
|
+
if (!cleanLine(reason.detail)) return [doc.createTextNode(code)];
|
|
102
|
+
const field = doc.createElement('bdi'); field.append(doc.createTextNode(reason.detail));
|
|
103
|
+
return [doc.createTextNode(`${code}: `), field];
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** A host's (or the remote transport's) refusal: the kernel's code verbatim, a headline, and the
|
|
107
|
+
* kernel's message as the detail, through the display filter (one line, or withheld). Null for anything
|
|
108
|
+
* not shaped like a kernel error. */
|
|
109
|
+
export function hostReason(error, label, fallback) {
|
|
110
|
+
if (!kernelCode(error?.code)) return null;
|
|
111
|
+
return { code: error.code, message: remoteHeadline(error.code, label, fallback), detail: displayLine(error.message), remote: true };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** This machine's OATS has no `remote` entry for the operation: nothing was sent. */
|
|
115
|
+
export const unroutableReason = label => ({ code: 'unsupported-remote-operation',
|
|
116
|
+
message: `This computer's OATS can't route this to ${shownLabel(label)}. Update OATS here.`, detail: null, remote: true });
|
|
117
|
+
|
|
118
|
+
/** Re-validate a relayed remote reason (server → main → renderer), or null. Its message and its detail
|
|
119
|
+
* are each already a display line (what the filter would return for them), within their limits. */
|
|
120
|
+
export function remoteReason(v) {
|
|
121
|
+
if (!v || typeof v !== 'object' || Array.isArray(v) || Object.keys(v).some(k => !['code', 'message', 'detail', 'remote'].includes(k))
|
|
122
|
+
|| v.remote !== true || !(kernelCode(v.code) || v.code === 'unsupported-remote-operation')
|
|
123
|
+
|| !cleanLine(v.message) || v.message.length > MAX_MESSAGE
|
|
124
|
+
|| !(v.detail === null || cleanLine(v.detail))) return null;
|
|
125
|
+
return { code: v.code, message: v.message, detail: v.detail, remote: true };
|
|
126
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { harnessOf } from "./harness-names.mjs";
|
|
2
|
+
import { unsupportedSession } from "./instance-presentation.mjs";
|
|
3
|
+
import { waitingOnYouData } from "./waiting-on-you.mjs";
|
|
4
|
+
/** Projection of the installed CLI's remote roster. Never reads remote paths locally. */
|
|
5
|
+
export function remoteWorkspace(group) {
|
|
6
|
+
return {
|
|
7
|
+
id: `remote:${group.id}`, name: group.label || group.server,
|
|
8
|
+
scope: group.target.workspace, roots: [], team: null, remote: true,
|
|
9
|
+
server: group.server, registrationPresent: group.registrationPresent, group,
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** A remote deployment's panel. `at` is the time the panel is made, an ISO string: a caller that holds
|
|
14
|
+
* the time of its call passes it (panel-views.mjs passes `held.at`); without it the clock is read. */
|
|
15
|
+
export function remotePanel(group, at = new Date().toISOString()) {
|
|
16
|
+
const ws = remoteWorkspace(group);
|
|
17
|
+
// A row's soul subtitle: its own group's soul list only, a string as the host reported it, never synthesized.
|
|
18
|
+
const described = name => { const soul = (group.souls || []).find((a) => a?.name === name); return typeof soul?.description === "string" ? soul.description : null; };
|
|
19
|
+
// A Herdr-recorded row is unsupported whatever the host's probe said: it cannot open or start.
|
|
20
|
+
const instances = (group.instances || []).map(({ runtime: _released, ...i }) => {
|
|
21
|
+
const unsupported = unsupportedSession(i);
|
|
22
|
+
return {
|
|
23
|
+
...i, server: group.server, savedRoute: i.savedRoute === true,
|
|
24
|
+
// The last roster read of this server failed: its rows are last-known, their state unknown.
|
|
25
|
+
serverUnreached: !group.probe.ok,
|
|
26
|
+
home: i.home, agentsRoot: i.agentsRoot || group.agentsRoot,
|
|
27
|
+
workspace: group.target.workspace, repoName: group.label || group.server,
|
|
28
|
+
harness: harnessOf({ runtime: _released, ...i }) || null, model: i.model || null, description: described(i.agent),
|
|
29
|
+
running: group.probe.ok ? i.running : null,
|
|
30
|
+
runtimeError: group.probe.ok ? i.runtimeError : group.probe.error?.message || "Server is unreachable",
|
|
31
|
+
tmux: i.tmux || null, git: i.git || null, task: i.task || "", next: i.next || "",
|
|
32
|
+
// Needs input: only a remote kernel with the feature reports it — validated, never synthesized when absent.
|
|
33
|
+
...(Object.hasOwn(i, "waitingOnYou") ? { waitingOnYou: waitingOnYouData(i.waitingOnYou) } : {}),
|
|
34
|
+
...(unsupported ? { running: null, runtimeState: "unsupported", runtimeError: unsupported } : {}),
|
|
35
|
+
};
|
|
36
|
+
});
|
|
37
|
+
return {
|
|
38
|
+
workspace: { id: ws.id, name: ws.name, scope: ws.scope, team: null, server: ws.server,
|
|
39
|
+
remote: true, registrationPresent: ws.registrationPresent === true },
|
|
40
|
+
team: null, generatedAt: at,
|
|
41
|
+
running: instances.filter((i) => i.running).length, instances,
|
|
42
|
+
error: group.probe.ok ? null : group.probe.error?.message || "Server is unreachable",
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function remoteAgents(group) {
|
|
47
|
+
if (!group.registrationPresent || !group.probe.ok) return [];
|
|
48
|
+
return (group.souls || []).map(({ runtime: _released, ...a }) => ({
|
|
49
|
+
...a, server: group.server, remote: true,
|
|
50
|
+
agentsRoot: a.agentsRoot || group.agentsRoot,
|
|
51
|
+
workspace: group.target.workspace, repoName: group.label || group.server,
|
|
52
|
+
// The reported default harness only (a pre-0.27 host's `runtime` is read as it); never a guessed pi.
|
|
53
|
+
harness: harnessOf({ runtime: _released, ...a }) || null, backend: a.backend || "tmux", work: a.work || "checkout",
|
|
54
|
+
kind: a.kind || "persistent", description: a.description || "",
|
|
55
|
+
}));
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function unavailableGroups(groups, error) {
|
|
59
|
+
return groups.map((g) => ({ ...g, probe: { ok: false, error }, instances: (g.instances || []).map((i) => ({ ...i, running: null })) }));
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function spawnedWorkspace(groups, result) {
|
|
63
|
+
if (!result.server || !result.target) return undefined;
|
|
64
|
+
const group = groups.find((g) => g.server === result.server && g.registrationPresent
|
|
65
|
+
&& g.target.sshHost === result.target.sshHost && g.target.workspace === result.target.workspace);
|
|
66
|
+
return group ? remoteWorkspace(group).id : undefined;
|
|
67
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/** A view's deployments and its roster, from the panel's facts alone (#482): which deployment
|
|
2
|
+
* deployment-level surfaces read, a deployment's state in words, which rows are held from a stale
|
|
3
|
+
* deployment, and the roster split into one section per deployment when a view has two or more.
|
|
4
|
+
*
|
|
5
|
+
* A deployment is `{ id, machine, path, label, local, reachable, identityFrom, primary, stale?, reason? }`
|
|
6
|
+
* and a row carries `deployment: { id }`. Nothing is derived from a host name or a path beyond the
|
|
7
|
+
* display label. A view with one deployment has one section and no heading. */
|
|
8
|
+
import { rosterGroups } from './instance-tree.mjs';
|
|
9
|
+
import { machineLabelParts } from './deployment-label.mjs';
|
|
10
|
+
import { requireTerms } from './client-terms.mjs';
|
|
11
|
+
|
|
12
|
+
const text = (v, max = 4096) => typeof v === 'string' && v.length > 0 && v.length <= max;
|
|
13
|
+
|
|
14
|
+
/** Grouping and "On …" lines apply only to a view of two or more deployments. */
|
|
15
|
+
export const isMultiDeployment = deployments => Array.isArray(deployments) && deployments.length >= 2;
|
|
16
|
+
|
|
17
|
+
/** The deployment deployment-level surfaces read and act on: the one marked primary, else the first. */
|
|
18
|
+
export const primaryDeployment = deployments => (Array.isArray(deployments) && (deployments.find(d => d?.primary) || deployments[0])) || null;
|
|
19
|
+
|
|
20
|
+
/** A deployment's state, in words (never colour alone): `{ key, text, detail }`.
|
|
21
|
+
* live: reached (or, on this computer, observed) now. stale: this computer's deployment whose last
|
|
22
|
+
* re-read failed (its rows are the last observation). remembered: not reached, its workspace is the
|
|
23
|
+
* last report. not reached / not observed: with why. */
|
|
24
|
+
export function deploymentState(d) {
|
|
25
|
+
// This computer's deployment whose last re-read failed: its rows are the last observation.
|
|
26
|
+
if (d?.stale) return { key: 'stale', text: 'stale', detail: d.reason || '' };
|
|
27
|
+
if (d?.reachable) return { key: 'live', text: 'live', detail: '' };
|
|
28
|
+
if (d?.identityFrom === 'remembered') {
|
|
29
|
+
return { key: 'remembered', text: 'remembered', detail: ['Last report, not live now.', d.reason].filter(Boolean).join(' ') };
|
|
30
|
+
}
|
|
31
|
+
// This computer's own deployment is not "reached": it is observed or not, the reason says why
|
|
32
|
+
// (still reading, or the kernel's refusal).
|
|
33
|
+
if (d?.local) return { key: 'unobserved', text: 'not observed', detail: d.reason || '' };
|
|
34
|
+
return { key: 'unreached', text: 'not reached', detail: d?.reason || '' };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The deployment a row belongs to, by the id the panel tagged it with (null when untagged). */
|
|
38
|
+
const rowDeployment = row => (text(row?.deployment?.id) ? row.deployment.id : null);
|
|
39
|
+
|
|
40
|
+
/** Whether a row is held from its deployment's last observation (the deployment is stale): its
|
|
41
|
+
* Start and actions wait for a current read, as for a stale roster. */
|
|
42
|
+
export const rowStale = (row, deployments) => {
|
|
43
|
+
const id = rowDeployment(row);
|
|
44
|
+
return !!id && Array.isArray(deployments) && deployments.some(d => d?.id === id && d.stale);
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
/** The sidebar roster's sections. One deployment (or none reported): a single section with no
|
|
48
|
+
* heading whose groups are exactly the relation clusters the roster always drew. Two or more: one
|
|
49
|
+
* section per deployment, in the panel's order, each with its own clusters (relations are recorded
|
|
50
|
+
* within one deployment); a row without a known deployment (a pending spawn) joins the primary's.
|
|
51
|
+
* Sections with no visible row are left out. Each is labelled by its machine, with the path tail
|
|
52
|
+
* only when one machine holds two (deployment-label.mjs machineLabels), in the client's terms
|
|
53
|
+
* (client-terms.mjs: the label of a deployment that names no machine). Returns
|
|
54
|
+
* `[{ deployment|null, label|null, groups }]`, a group being `{ key, label, clusters }` as before. */
|
|
55
|
+
export function rosterSections(instances, visible, deployments, terms) {
|
|
56
|
+
requireTerms(terms, 'rosterSections');
|
|
57
|
+
const groupsOf = (all, shown) => rosterGroups(all, shown); // the relation groups the palette lists too
|
|
58
|
+
if (!isMultiDeployment(deployments)) return [{ deployment: null, label: null, groups: groupsOf(instances, visible) }];
|
|
59
|
+
const sectionOf = splitByDeployment(deployments);
|
|
60
|
+
const all = sectionOf(instances), shown = sectionOf(visible), labels = machineLabelParts(deployments, terms);
|
|
61
|
+
const label = ({ machine, tail }) => (tail ? `${machine} · ${tail}` : machine);
|
|
62
|
+
return deployments.map(d => ({ deployment: d, parts: labels.get(d.id), all: all.get(d.id), shown: shown.get(d.id) }))
|
|
63
|
+
.filter(s => s.shown.length)
|
|
64
|
+
.map(s => ({ deployment: s.deployment, label: label(s.parts), machine: s.parts.machine, tail: s.parts.tail, groups: groupsOf(s.all, s.shown) }));
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** `rows → Map<deployment id, rows>` over the given deployments; an unknown or missing deployment
|
|
68
|
+
* id goes to the primary deployment. */
|
|
69
|
+
export function splitByDeployment(deployments) {
|
|
70
|
+
const primary = primaryDeployment(deployments)?.id;
|
|
71
|
+
const ids = new Set(deployments.map(d => d.id));
|
|
72
|
+
return rows => {
|
|
73
|
+
const out = new Map(deployments.map(d => [d.id, []]));
|
|
74
|
+
for (const row of rows || []) {
|
|
75
|
+
const id = rowDeployment(row);
|
|
76
|
+
out.get(id && ids.has(id) ? id : primary)?.push(row);
|
|
77
|
+
}
|
|
78
|
+
return out;
|
|
79
|
+
};
|
|
80
|
+
}
|
|
@@ -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
|
+
}
|