@awebai/oats 0.44.1 → 0.46.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/bin/oats.mjs +65 -34
- package/docs/configuration.md +9 -3
- package/docs/desktop-cli-api.md +102 -11
- package/docs/desktop.md +4 -4
- package/docs/execution-targets.md +12 -2
- package/docs/first-team.md +10 -10
- package/docs/harness-trust.md +147 -0
- package/docs/implementation.md +5 -2
- package/docs/release-notes/v0.45.0.md +56 -0
- package/docs/release-notes/v0.46.0.md +71 -0
- package/docs/servers.md +1 -1
- package/docs/souls-and-instances.md +11 -8
- package/lib/harness-trust-json.mjs +81 -0
- package/lib/harness-trust-toml.mjs +138 -0
- package/lib/harness-trust-write.mjs +221 -0
- package/lib/harness-trust.mjs +12 -11
- package/lib/instance-inspect.mjs +21 -2
- package/lib/instance-resolution.mjs +18 -4
- package/lib/instruction-composition.mjs +16 -3
- package/lib/launch-prompt-fixtures/README.md +39 -4
- package/lib/launch-prompt-fixtures.mjs +9 -3
- package/lib/operator-coverage.mjs +10 -6
- package/lib/servers.mjs +3 -0
- package/lib/soul-composition.mjs +97 -0
- package/package.json +1 -1
- package/skills/oats-getting-started/SKILL.md +11 -1
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
/** Explicit operator-only native trust writes. Never called from spawn/start.
|
|
2
|
+
* Native writers do not cooperate with our locks: compare-and-replace narrows,
|
|
3
|
+
* but cannot eliminate, the race immediately before rename. No rollback. */
|
|
4
|
+
import * as fs from 'node:fs';
|
|
5
|
+
import { join, dirname, basename, resolve, isAbsolute } from 'node:path';
|
|
6
|
+
import { homedir } from 'node:os';
|
|
7
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
8
|
+
import { execFileSync } from 'node:child_process';
|
|
9
|
+
import { editClaudeTrust } from './harness-trust-json.mjs';
|
|
10
|
+
import { editCodexTrust } from './harness-trust-toml.mjs';
|
|
11
|
+
import { claudeTrusts, codexTrustsRoot, codexTrustedDirs } from './harness-trust.mjs';
|
|
12
|
+
const digest = bytes => createHash('sha256').update(bytes).digest('hex');
|
|
13
|
+
const error = (code, message, details) => Object.assign(new Error(message), { code, details });
|
|
14
|
+
const broken = () => error('E_CONFIG_BROKEN', 'Native trust configuration is unreadable, unsafe, invalid, or outside the supported format; inspect the selected file before retrying.');
|
|
15
|
+
const identity = s => `${s.dev}:${s.ino}`;
|
|
16
|
+
function stat(path) { try { return fs.lstatSync(path); } catch (e) { if (e.code === 'ENOENT') return null; throw e; } }
|
|
17
|
+
/** GNU ls uses '.' for a security context alone, '+' for an ACL. macOS
|
|
18
|
+
* '@' marks extended attributes. Refuse metadata we cannot preserve; a Linux
|
|
19
|
+
* context is checked on the same-directory candidate before any replacement. */
|
|
20
|
+
export function nativeSecurityContext(path, { platform = process.platform, run = execFileSync } = {}) {
|
|
21
|
+
const flags = platform === 'darwin' ? ['-lde', path] : ['-ld', '--', path];
|
|
22
|
+
const mode = run('ls', flags, { encoding: 'utf8' }).split(/\s/, 1)[0];
|
|
23
|
+
if (!/^-[-rwxStTs]{9}$/.test(mode)) {
|
|
24
|
+
if (platform !== 'linux' || !/^-[-rwxStTs]{9}\.$/.test(mode)) throw broken();
|
|
25
|
+
const context = run('ls', ['-Zd', '--', path], { encoding: 'utf8' }).trim().split(/\s/, 1)[0];
|
|
26
|
+
if (!context || context === '?' || context.split(':').length < 3) throw broken();
|
|
27
|
+
return context;
|
|
28
|
+
}
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
function regular(path, metadataProbe) {
|
|
32
|
+
const s = stat(path); if (!s) return null;
|
|
33
|
+
if (!s.isFile() || s.nlink !== 1 || s.uid !== process.getuid?.() || (s.mode & 0o7000)) throw broken();
|
|
34
|
+
s.securityContext = metadataProbe(path);
|
|
35
|
+
return s;
|
|
36
|
+
}
|
|
37
|
+
function canonicalMissingDirectory(path) {
|
|
38
|
+
let at = resolve(path), tail = [];
|
|
39
|
+
for (;;) {
|
|
40
|
+
const s = stat(at);
|
|
41
|
+
if (s) {
|
|
42
|
+
const real = fs.realpathSync.native(at); if (!fs.statSync(real).isDirectory()) throw broken();
|
|
43
|
+
return join(real, ...tail.reverse());
|
|
44
|
+
}
|
|
45
|
+
const parent = dirname(at); if (parent === at) throw broken(); tail.push(basename(at)); at = parent;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
function snapshot(file, metadataProbe) {
|
|
49
|
+
const s = regular(file, metadataProbe); if (!s) return { bytes: null, digest: null, identity: null, mode: null, securityContext: null };
|
|
50
|
+
const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
|
|
51
|
+
try {
|
|
52
|
+
if (identity(fs.fstatSync(fd)) !== identity(s)) throw broken();
|
|
53
|
+
const bytes = fs.readFileSync(fd); if (bytes.length > 8 * 1024 * 1024) throw broken();
|
|
54
|
+
if (identity(fs.lstatSync(file)) !== identity(s)) throw broken();
|
|
55
|
+
return { bytes, digest: digest(bytes), identity: identity(s), mode: s.mode & 0o777, uid: s.uid, gid: s.gid, securityContext: s.securityContext };
|
|
56
|
+
} finally { fs.closeSync(fd); }
|
|
57
|
+
}
|
|
58
|
+
const same = (a, b) => a.digest === b.digest && a.identity === b.identity && a.mode === b.mode && a.uid === b.uid && a.gid === b.gid && a.securityContext === b.securityContext;
|
|
59
|
+
function nativePath(harness, env) {
|
|
60
|
+
const home = env.HOME || homedir(); if (!isAbsolute(home)) throw broken();
|
|
61
|
+
const override = harness === 'claude' ? env.CLAUDE_CONFIG_DIR : env.CODEX_HOME;
|
|
62
|
+
if (override && !isAbsolute(override)) throw broken();
|
|
63
|
+
const dir = override || (harness === 'claude' ? home : join(home, '.codex'));
|
|
64
|
+
return join(canonicalMissingDirectory(dir), harness === 'claude' ? '.claude.json' : 'config.toml');
|
|
65
|
+
}
|
|
66
|
+
function validAudit(file, metadataProbe) {
|
|
67
|
+
const observed = snapshot(file, metadataProbe);
|
|
68
|
+
if (observed.bytes) {
|
|
69
|
+
const text = observed.bytes.toString('utf8');
|
|
70
|
+
if (text && !text.endsWith('\n')) throw broken();
|
|
71
|
+
for (const line of text.split('\n').slice(0, -1)) {
|
|
72
|
+
let row; try { row = JSON.parse(line); } catch { throw broken(); }
|
|
73
|
+
if (!row || typeof row !== 'object' || Array.isArray(row)) throw broken();
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return observed;
|
|
77
|
+
}
|
|
78
|
+
function syncDirectory(path) { const fd = fs.openSync(path, 'r'); try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); } }
|
|
79
|
+
function ensureDirectory(path) {
|
|
80
|
+
if (stat(path)) { if (!fs.lstatSync(path).isDirectory() || fs.realpathSync.native(path) !== path) throw broken(); return; }
|
|
81
|
+
ensureDirectory(dirname(path)); fs.mkdirSync(path, { mode: 0o700 }); syncDirectory(dirname(path));
|
|
82
|
+
}
|
|
83
|
+
/** Planning performs reads only, including when native directories do not exist. */
|
|
84
|
+
export function planHarnessTrust(root, { harness = 'all', env = process.env, metadataProbe = nativeSecurityContext } = {}) {
|
|
85
|
+
if (!['all', 'claude', 'codex'].includes(harness)) throw error('E_BAD_ARGS', '--harness must be claude, codex, or all');
|
|
86
|
+
// Native lookup preserves the on-disk casing on case-insensitive APFS; the
|
|
87
|
+
// JS realpath implementation can retain the caller's spelling as a wrong key.
|
|
88
|
+
root = fs.realpathSync.native(root);
|
|
89
|
+
const result = { operation: 'harness-trust', mode: 'plan', root, entries: [], audit: null, warnings: [] }, plans = [];
|
|
90
|
+
for (const name of harness === 'all' ? ['claude', 'codex'] : [harness]) {
|
|
91
|
+
const key = ['projects', root, name === 'claude' ? 'hasTrustDialogAccepted' : 'trust_level'];
|
|
92
|
+
const entry = { harness: name, file: null, key, current: null, desired: name === 'claude' ? true : 'trusted', beforeDigest: null, afterDigest: null, status: 'refused' };
|
|
93
|
+
result.entries.push(entry);
|
|
94
|
+
try {
|
|
95
|
+
const file = nativePath(name, env); entry.file = file;
|
|
96
|
+
const before = snapshot(file, metadataProbe); entry.beforeDigest = before.digest;
|
|
97
|
+
const text = before.bytes?.toString('utf8') ?? (name === 'claude' ? '{}' : '');
|
|
98
|
+
if (before.bytes && !Buffer.from(text).equals(before.bytes)) throw broken();
|
|
99
|
+
const edited = (name === 'claude' ? editClaudeTrust : editCodexTrust)(text, root);
|
|
100
|
+
// Preflight the existing reader's supported representation as well as
|
|
101
|
+
// native syntax; never discover a known compatibility gap after writing.
|
|
102
|
+
if (name === 'codex' && !codexTrustedDirs(edited.text).has(root)) throw broken();
|
|
103
|
+
const after = Buffer.from(edited.text);
|
|
104
|
+
entry.current = edited.current; entry.afterDigest = digest(after);
|
|
105
|
+
entry.status = before.bytes?.equals(after) ? 'unchanged' : 'change';
|
|
106
|
+
plans.push({ entry, before, after });
|
|
107
|
+
const overrideKey = name === 'claude' ? 'CLAUDE_CONFIG_DIR' : 'CODEX_HOME';
|
|
108
|
+
if (env[overrideKey]) result.warnings.push(`${overrideKey} selects ${env[overrideKey]}; effective file ${file}`);
|
|
109
|
+
} catch { /* Per-file refusal; never echo native content or parser exceptions. */ }
|
|
110
|
+
}
|
|
111
|
+
if (result.entries.some(e => e.status === 'refused')) throw error('E_CONFIG_BROKEN', broken().message, result);
|
|
112
|
+
return { result, plans };
|
|
113
|
+
}
|
|
114
|
+
export function harnessTrust(root, { harness = 'all', plan = false, env = process.env, checkpoint = () => {}, metadataProbe = nativeSecurityContext } = {}) {
|
|
115
|
+
let prepared;
|
|
116
|
+
try { prepared = planHarnessTrust(root, { harness, env, metadataProbe }); }
|
|
117
|
+
catch (e) { if (e.details?.operation === 'harness-trust') e.details.mode = plan ? 'plan' : 'apply'; throw e; }
|
|
118
|
+
const { result, plans } = prepared;
|
|
119
|
+
if (plan) return result;
|
|
120
|
+
result.mode = 'apply'; const operationId = randomUUID(), auditPath = join(result.root, '.agents', 'harness-trust.jsonl');
|
|
121
|
+
const locks = [], temps = new Map(), parents = new Map(); let mayHaveChanged = false, currentMayHaveChanged = false, reason = 'audit', current = null, auditSnapshot, failure, acquiringLock;
|
|
122
|
+
result.audit = { path: auditPath, operationId, status: 'incomplete' };
|
|
123
|
+
const checkParent = file => {
|
|
124
|
+
const dir = dirname(file);
|
|
125
|
+
if (fs.realpathSync.native(dir) !== dir || identity(fs.statSync(dir)) !== parents.get(dir)) throw new Error('parent changed');
|
|
126
|
+
};
|
|
127
|
+
const append = (entry, phase, status) => {
|
|
128
|
+
checkpoint('before-audit', { phase, entry });
|
|
129
|
+
checkParent(auditPath);
|
|
130
|
+
const now = validAudit(auditPath, metadataProbe); if (!same(now, auditSnapshot)) throw new Error('audit changed');
|
|
131
|
+
const row = Buffer.from(JSON.stringify({ version: 1, kind: 'harness-trust', at: new Date().toISOString(), operationId, phase, harness: entry.harness, root: result.root, file: entry.file, beforeDigest: entry.beforeDigest, afterDigest: entry.afterDigest, status }) + '\n');
|
|
132
|
+
const expected = digest(Buffer.concat([now.bytes ?? Buffer.alloc(0), row]));
|
|
133
|
+
const fd = fs.openSync(auditPath, fs.constants.O_WRONLY | fs.constants.O_APPEND | fs.constants.O_CREAT | fs.constants.O_NOFOLLOW | (now.identity === null ? fs.constants.O_EXCL : 0), 0o600);
|
|
134
|
+
let writtenIdentity;
|
|
135
|
+
try {
|
|
136
|
+
writtenIdentity = identity(fs.fstatSync(fd));
|
|
137
|
+
if (now.identity !== null && writtenIdentity !== now.identity) throw new Error('audit replaced');
|
|
138
|
+
fs.writeFileSync(fd, row);
|
|
139
|
+
fs.fsyncSync(fd);
|
|
140
|
+
} finally { fs.closeSync(fd); }
|
|
141
|
+
checkParent(auditPath); syncDirectory(dirname(auditPath));
|
|
142
|
+
const after = validAudit(auditPath, metadataProbe);
|
|
143
|
+
if (after.identity !== writtenIdentity || after.digest !== expected) throw new Error('audit changed after append');
|
|
144
|
+
auditSnapshot = after;
|
|
145
|
+
};
|
|
146
|
+
try {
|
|
147
|
+
// Validate the complete existing audit before creating any directories/locks.
|
|
148
|
+
auditSnapshot = validAudit(auditPath, metadataProbe);
|
|
149
|
+
checkpoint('before-locks', { result }); reason = 'locked';
|
|
150
|
+
const lockPaths = [auditPath, ...plans.map(p => p.entry.file)].map(f => `${f}.oats-trust.lock`).sort();
|
|
151
|
+
for (const lock of lockPaths) {
|
|
152
|
+
acquiringLock = lock;
|
|
153
|
+
ensureDirectory(dirname(lock));
|
|
154
|
+
const dir = dirname(lock), observed = identity(fs.statSync(dir));
|
|
155
|
+
if (parents.has(dir) && parents.get(dir) !== observed) throw new Error('parent changed');
|
|
156
|
+
parents.set(dir, observed);
|
|
157
|
+
const fd = fs.openSync(lock, 'wx', 0o600);
|
|
158
|
+
locks.push({ path: lock, identity: identity(fs.fstatSync(fd)) }); fs.closeSync(fd);
|
|
159
|
+
}
|
|
160
|
+
reason = 'changed';
|
|
161
|
+
for (const p of plans) { checkParent(p.entry.file); if (!same(snapshot(p.entry.file, metadataProbe), p.before)) throw new Error('configuration changed'); }
|
|
162
|
+
if (!same(validAudit(auditPath, metadataProbe), auditSnapshot)) { reason = 'audit'; throw new Error('audit changed'); }
|
|
163
|
+
for (const p of plans) {
|
|
164
|
+
current = p; currentMayHaveChanged = false; reason = 'audit';
|
|
165
|
+
if (p.entry.status === 'unchanged') {
|
|
166
|
+
reason = 'verify';
|
|
167
|
+
if (!(p.entry.harness === 'claude' ? claudeTrusts(result.root, { env }) : codexTrustsRoot(result.root, { env }))) throw new Error('verification failed');
|
|
168
|
+
reason = 'audit'; append(p.entry, 'outcome', 'unchanged'); current = null; continue;
|
|
169
|
+
}
|
|
170
|
+
append(p.entry, 'intent', 'planned'); reason = 'write';
|
|
171
|
+
checkParent(p.entry.file);
|
|
172
|
+
const tmp = join(dirname(p.entry.file), `.${basename(p.entry.file)}.oats-${operationId}.tmp`);
|
|
173
|
+
const parentIdentity = identity(fs.statSync(dirname(p.entry.file)));
|
|
174
|
+
const fd = fs.openSync(tmp, 'wx', p.before.mode ?? 0o600); temps.set(tmp, identity(fs.fstatSync(fd)));
|
|
175
|
+
try {
|
|
176
|
+
if (p.before.uid !== undefined) fs.fchownSync(fd, p.before.uid, p.before.gid);
|
|
177
|
+
fs.fchmodSync(fd, p.before.mode ?? 0o600); fs.writeFileSync(fd, p.after); fs.fsyncSync(fd);
|
|
178
|
+
} finally { fs.closeSync(fd); }
|
|
179
|
+
const candidate = snapshot(tmp, metadataProbe);
|
|
180
|
+
if (p.before.identity !== null && candidate.securityContext !== p.before.securityContext) throw new Error('candidate security context differs');
|
|
181
|
+
reason = 'changed'; checkpoint('before-replace', { entry: p.entry });
|
|
182
|
+
if (identity(fs.statSync(dirname(p.entry.file))) !== parentIdentity || fs.realpathSync.native(dirname(p.entry.file)) !== dirname(p.entry.file) || !same(snapshot(p.entry.file, metadataProbe), p.before)) throw new Error('configuration changed');
|
|
183
|
+
reason = 'write';
|
|
184
|
+
// Once rename is attempted, conservatively report uncertainty on any error.
|
|
185
|
+
mayHaveChanged = true; currentMayHaveChanged = true; fs.renameSync(tmp, p.entry.file); temps.delete(tmp); syncDirectory(dirname(p.entry.file));
|
|
186
|
+
reason = 'verify'; checkpoint('after-replace', { entry: p.entry });
|
|
187
|
+
const observed = snapshot(p.entry.file, metadataProbe);
|
|
188
|
+
const expectedDigest = p.entry.afterDigest; p.entry.afterDigest = observed.digest;
|
|
189
|
+
if (observed.securityContext !== candidate.securityContext || observed.digest !== expectedDigest || !(p.entry.harness === 'claude' ? claudeTrusts(result.root, { env }) : codexTrustsRoot(result.root, { env }))) throw new Error('verification failed');
|
|
190
|
+
p.entry.status = 'applied'; reason = 'audit'; append(p.entry, 'outcome', 'applied'); current = null;
|
|
191
|
+
}
|
|
192
|
+
result.audit.status = 'recorded';
|
|
193
|
+
} catch {
|
|
194
|
+
if (current) {
|
|
195
|
+
current.entry.status = currentMayHaveChanged ? 'incomplete' : 'failed';
|
|
196
|
+
// The intent retains the proposed digest. A failed outcome reports only
|
|
197
|
+
// bytes actually observed, never the proposal as proof of a replacement.
|
|
198
|
+
try { checkParent(current.entry.file); current.entry.afterDigest = snapshot(current.entry.file, metadataProbe).digest; }
|
|
199
|
+
catch { current.entry.afterDigest = null; result.warnings.push(`Final digest unconfirmed for ${current.entry.file}.`); }
|
|
200
|
+
if (reason !== 'audit') { try { append(current.entry, 'outcome', current.entry.status); result.audit.status = 'recorded'; } catch { result.audit.status = 'incomplete'; } }
|
|
201
|
+
}
|
|
202
|
+
for (const p of plans) if (p.entry.status === 'change') p.entry.status = 'not-attempted';
|
|
203
|
+
failure = error('E_HARNESS_TRUST_INCOMPLETE', `Harness trust ${reason} failed${reason === 'locked' && acquiringLock ? `; could not acquire lock ${acquiringLock}` : ''}; inspect native configuration and ${auditPath} before retrying. No rollback was attempted.`, { ...result, reason, mayHaveChanged });
|
|
204
|
+
} finally {
|
|
205
|
+
// Cleanup is part of the outcome. Do not silently succeed with a lock left
|
|
206
|
+
// behind, and never delete a path another writer replaced.
|
|
207
|
+
for (const [path, owned] of [...temps, ...locks.reverse().map(l => [l.path, l.identity])]) {
|
|
208
|
+
try {
|
|
209
|
+
const observed = stat(path);
|
|
210
|
+
if (!observed) continue;
|
|
211
|
+
if (identity(observed) !== owned) throw new Error('replaced cleanup path');
|
|
212
|
+
fs.unlinkSync(path);
|
|
213
|
+
} catch {
|
|
214
|
+
result.warnings.push(`Cleanup unconfirmed for ${path}; inspect it before retrying.`);
|
|
215
|
+
failure ??= error('E_HARNESS_TRUST_INCOMPLETE', 'Harness trust cleanup failed; native changes and audit are retained. Inspect the reported paths before retrying.', { ...result, reason: 'write', mayHaveChanged });
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
if (failure) throw failure;
|
|
220
|
+
return result;
|
|
221
|
+
}
|
package/lib/harness-trust.mjs
CHANGED
|
@@ -2,15 +2,15 @@
|
|
|
2
2
|
* covered by the operator's one-time trust of the deployment root, so the launched session
|
|
3
3
|
* does not stop at the harness's folder-trust prompt.
|
|
4
4
|
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
5
|
+
* This module only reads native configuration. The explicit operator command
|
|
6
|
+
* in harness-trust-write.mjs is the separate deployment-root write boundary. A configuration that is missing, unreadable or in a form this
|
|
7
7
|
* reader does not know counts as not trusted, so a launch is warned about rather than
|
|
8
8
|
* silently stalled.
|
|
9
9
|
*
|
|
10
10
|
* - Claude walks up from its working directory, stopping at a git root, and honours
|
|
11
11
|
* `projects["<dir>"].hasTrustDialogAccepted` in ~/.claude.json
|
|
12
|
-
* ($CLAUDE_CONFIG_DIR/.claude.json when that is set).
|
|
13
|
-
*
|
|
12
|
+
* ($CLAUDE_CONFIG_DIR/.claude.json when that is set). A deployment-root entry covers
|
|
13
|
+
* descendants only when no intervening Git boundary prevents inheritance.
|
|
14
14
|
* - Codex honours only an exact `[projects."<dir>"] trust_level = "trusted"` entry in
|
|
15
15
|
* ~/.codex/config.toml ($CODEX_HOME/config.toml), never a parent's. A per-invocation
|
|
16
16
|
* override does trust a home, so the kernel's codex launch adds one for the home when the
|
|
@@ -19,7 +19,7 @@ import { existsSync, readFileSync, realpathSync } from "node:fs";
|
|
|
19
19
|
import { dirname, join, resolve } from "node:path";
|
|
20
20
|
import { homedir } from "node:os";
|
|
21
21
|
|
|
22
|
-
const real = (p) => { try { return realpathSync(p); } catch { return resolve(p); } };
|
|
22
|
+
const real = (p) => { try { return realpathSync.native(p); } catch { return resolve(p); } };
|
|
23
23
|
const userHome = (env) => env.HOME || homedir();
|
|
24
24
|
|
|
25
25
|
/** `dir` and its ancestors, nearest first. */
|
|
@@ -92,7 +92,7 @@ function assignment(line) {
|
|
|
92
92
|
/** The directories config.toml marks `trust_level = "trusted"`, in the forms Codex writes and
|
|
93
93
|
* their plain TOML equivalents: `[projects."<dir>"]` tables, `"<dir>" = { trust_level = … }`
|
|
94
94
|
* under `[projects]`, and dotted `projects."<dir>".trust_level` keys. */
|
|
95
|
-
function codexTrustedDirs(text) {
|
|
95
|
+
export function codexTrustedDirs(text) {
|
|
96
96
|
const trusted = new Set();
|
|
97
97
|
let table = [];
|
|
98
98
|
for (const raw of text.split(/\r?\n/)) {
|
|
@@ -125,11 +125,12 @@ export function codexTrustsRoot(root, { env = process.env } = {}) {
|
|
|
125
125
|
return false;
|
|
126
126
|
}
|
|
127
127
|
|
|
128
|
-
/**
|
|
129
|
-
const
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
}
|
|
128
|
+
/** Shell-quoted operator remedy; never invoked by readiness or a launch. */
|
|
129
|
+
const quote = value => "'" + value.replaceAll("'", "'\"'\"'") + "'";
|
|
130
|
+
const TRUST_STEP = Object.fromEntries(["claude", "codex"].map(harness => [harness, root => {
|
|
131
|
+
const command = `oats harness trust --dir ${quote(root)} --harness ${harness}`;
|
|
132
|
+
return `preview with \`${command} --plan\`, then apply with \`${command}\`; a nested Git boundary may still require operator inspection`;
|
|
133
|
+
}]));
|
|
133
134
|
|
|
134
135
|
/** The spawn and readiness warning for a home its harness will not trust without asking;
|
|
135
136
|
* null when `covered`, or for a harness without a folder-trust prompt. */
|
package/lib/instance-inspect.mjs
CHANGED
|
@@ -24,6 +24,7 @@ import { loadLocal } from "./workspace.mjs";
|
|
|
24
24
|
import { ensureModuleTree } from "./operator-dispatch.mjs";
|
|
25
25
|
import { operatorCoverage, operatorProblems } from "./operator-coverage.mjs";
|
|
26
26
|
import { readLockIfPresent } from "./packages.mjs";
|
|
27
|
+
import { composeSoulInstructions } from "./soul-composition.mjs";
|
|
27
28
|
/** Bounds of a provider check's answer (bytes, nesting, entries), as the released binding wire set them. */
|
|
28
29
|
const BINDING_LIMITS = Object.freeze({ maxBytes: 1024 * 1024, maxDepth: 32, maxEntries: 16384 });
|
|
29
30
|
import { parseStrictJson } from "./canonical-json.mjs";
|
|
@@ -248,7 +249,25 @@ function soulRow(t) {
|
|
|
248
249
|
return { soulsApi: SOULS_API, name: s.name, repoKey: s.repoKey, commit: s.commit, kind: s.external === true ? "external" : s.external === false ? "member" : null, path: s.path,
|
|
249
250
|
description: def.description ?? null, work: def.work ?? null, harness: def.harness ?? null, model: def.model ?? null,
|
|
250
251
|
declarations: declarationsOf(s.definition), declarationProblems: s.problems,
|
|
251
|
-
instructions: s.soulDir ? readTextCapped(join(s.soulDir, "AGENTS.md")) : null
|
|
252
|
+
instructions: s.soulDir ? readTextCapped(join(s.soulDir, "AGENTS.md")) : null,
|
|
253
|
+
// Feature soul-composed-instructions: only on a soul target that asked (inspect --instructions).
|
|
254
|
+
...(t.kind === "soul" && t.composedInstructions !== undefined ? { composedInstructions: t.composedInstructions } : {}) };
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** The soul target with `composedInstructions` (feature soul-composed-instructions): the AGENTS.md a
|
|
258
|
+
* spawn of it here with no flags would write (lib/soul-composition.mjs), or null when the soul
|
|
259
|
+
* resolves but cannot be composed here — with the kernel's refusal as a problem naming
|
|
260
|
+
* composedInstructions, unless the soul copy's own problem (copyError) already says why. */
|
|
261
|
+
export async function withComposedInstructions(t, { compose = composeSoulInstructions } = {}) {
|
|
262
|
+
if (t.kind !== "soul") return t;
|
|
263
|
+
if (t.soul.copyError || !t.soul.soulDir || !t.prepared) return { ...t, composedInstructions: null };
|
|
264
|
+
try {
|
|
265
|
+
const { composedInstructions } = await compose({ deployment: t.deployment, prepared: t.prepared, soulDir: t.soul.soulDir });
|
|
266
|
+
return { ...t, composedInstructions };
|
|
267
|
+
} catch (e) {
|
|
268
|
+
if (typeof e?.code !== "string" || !e.code.startsWith("E_")) throw e;
|
|
269
|
+
return { ...t, composedInstructions: null, composedInstructionsProblem: { code: e.code, message: `composedInstructions: ${e.message}` } };
|
|
270
|
+
}
|
|
252
271
|
}
|
|
253
272
|
|
|
254
273
|
/** `oats inspect --json` on the workspace model. */
|
|
@@ -280,7 +299,7 @@ export function inspectDocument(t, { kernel }) {
|
|
|
280
299
|
launchConfig: m.launch?.launchConfig ?? null, launchConfigDefault: m.launch?.launchConfigDefault === true, launched: !!m.launched, createdAt: m.createdAt || null,
|
|
281
300
|
resolution: m.workspace?.resolution ?? null, soulDir: t.soul.soulDir, instructions: { ...readTextCapped(join(t.home, "AGENTS.md")), sources: m.instructions || [] } } : null,
|
|
282
301
|
...(m ? { identity: servedIdentityOf(m) } : {}),
|
|
283
|
-
problems: [...t.soul.problems, ...(t.soul.copyError ? [t.soul.copyError] : []), ...(t.discoveryError ? [t.discoveryError] : []),
|
|
302
|
+
problems: [...t.soul.problems, ...(t.soul.copyError ? [t.soul.copyError] : []), ...(t.composedInstructionsProblem ? [t.composedInstructionsProblem] : []), ...(t.discoveryError ? [t.discoveryError] : []),
|
|
284
303
|
...t.modules.filter((x) => !x.manifest).map((x) => ({ code: "module-missing", message: `${x.name} is recorded but its module copy has no readable oats.json`, capability: x.name })),
|
|
285
304
|
...capabilities.filter((c) => !c.compatibility.ok).map((c) => ({ code: "capability-incompatible", message: `${c.id} requires oats ${c.compatibility.range}; this kernel is ${c.compatibility.kernel} (re-spawn from the deployment with a release whose range admits it)`, capability: c.id, range: c.compatibility.range, kernel: c.compatibility.kernel }))],
|
|
286
305
|
};
|
|
@@ -481,12 +481,26 @@ export function requireMemberClone(prepared, { explicit } = {}) {
|
|
|
481
481
|
/** Would a spawn of this discovered soul be refused before it touches this machine (feature desktop-facts)?
|
|
482
482
|
* The same checks prepareInstance makes — souls.disabled, then the soul's resolution (its teams here, slot
|
|
483
483
|
* conflicts, missing or private capabilities, compatibility …) — without spawning anything.
|
|
484
|
-
*
|
|
484
|
+
* `capabilities` (feature souls-capabilities) is what that one resolution composes, one entry per module in
|
|
485
|
+
* its order (by name, codepoint), keyed like an `oats capabilities` row — { name, kind: "member", repoKey,
|
|
486
|
+
* from } | { name, kind: "package", package, from } — with `from` its capabilitiesFrom ("soul" | "workspace").
|
|
487
|
+
* null whenever the soul is not spawnable: nothing resolved, so nothing is known to be composed.
|
|
488
|
+
* → { spawnable: true, problem: null, capabilities: [...] } | { spawnable: false, problem: { code, message }, capabilities: null } */
|
|
485
489
|
export async function soulSpawnability(local, discovery, lock, soulEntry, { remoteOptions, remote } = {}) {
|
|
486
490
|
const disabled = disabledEntry(local, soulEntry);
|
|
487
|
-
if (disabled !== null) return { spawnable: false, problem: { code: "E_SOUL_DISABLED", message: `disabled on this machine (oats-local.yaml souls.disabled: ${disabled})` } };
|
|
488
|
-
|
|
489
|
-
|
|
491
|
+
if (disabled !== null) return { spawnable: false, problem: { code: "E_SOUL_DISABLED", message: `disabled on this machine (oats-local.yaml souls.disabled: ${disabled})` }, capabilities: null };
|
|
492
|
+
let resolution;
|
|
493
|
+
try { resolution = await resolveSoul(discovery, soulEntry, { local, lock, spawn: {}, remoteOptions, remote }); }
|
|
494
|
+
catch (e) { if (typeof e?.code === "string" && e.code.startsWith("E_")) return { spawnable: false, problem: { code: e.code, message: e.message }, capabilities: null }; throw e; }
|
|
495
|
+
return { spawnable: true, problem: null, capabilities: composedCapabilities(resolution) };
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
/** A resolution's modules as `oats capabilities` row identities, each with why the soul has it (feature
|
|
499
|
+
* souls-capabilities). Only the identity keys: no commit, version, layer or integrity. */
|
|
500
|
+
function composedCapabilities(resolution) {
|
|
501
|
+
return resolution.modules.map((m) => m.from.kind === "package"
|
|
502
|
+
? { name: m.name, kind: "package", package: m.from.package, from: resolution.capabilitiesFrom[m.name] }
|
|
503
|
+
: { name: m.name, kind: "member", repoKey: m.from.repoKey, from: resolution.capabilitiesFrom[m.name] });
|
|
490
504
|
}
|
|
491
505
|
|
|
492
506
|
/** The async half of a spawn: everything that touches the network. Returns a
|
|
@@ -1,11 +1,24 @@
|
|
|
1
1
|
/** Formatting shared by current preparation and retained instruction projection.
|
|
2
2
|
* Selection/order is supplied by the caller; this module never discovers config. */
|
|
3
3
|
|
|
4
|
-
|
|
4
|
+
/** The composed document and where each part of it is: `body` and every `blocks[i]` as
|
|
5
|
+
* `[start, end)` in JS string units. The parts tile the text: the body starts at 0, each
|
|
6
|
+
* part ends where the next starts (after the blank separator line before the next opening
|
|
7
|
+
* marker), and the last part ends at `text.length`. A block starts at the `<` of its opening
|
|
8
|
+
* marker. The one renderer: renderInstructionText is its `.text`. */
|
|
9
|
+
export function renderInstructionParts(body, blocks) {
|
|
5
10
|
let text = body.replace(/\n*$/, "\n");
|
|
11
|
+
const spans = [];
|
|
6
12
|
for (const { source, file, content } of blocks) {
|
|
7
|
-
text +=
|
|
13
|
+
text += "\n";
|
|
14
|
+
const start = text.length;
|
|
15
|
+
text += `<!-- oats:${source} src=${file} -->\n${content.trim()}\n<!-- /oats:${source} -->\n`;
|
|
16
|
+
spans.push({ start });
|
|
8
17
|
}
|
|
9
|
-
|
|
18
|
+
const bodyEnd = spans.length ? spans[0].start : text.length;
|
|
19
|
+
return { text, body: { start: 0, end: bodyEnd }, blocks: spans.map(({ start }, i) => ({ start, end: i + 1 < spans.length ? spans[i + 1].start : text.length })) };
|
|
10
20
|
}
|
|
11
21
|
|
|
22
|
+
export function renderInstructionText(body, blocks) {
|
|
23
|
+
return renderInstructionParts(body, blocks).text;
|
|
24
|
+
}
|
|
@@ -27,8 +27,8 @@ blocked outcome and sends no key. Captured folder-trust screens live only in
|
|
|
27
27
|
`test/fixtures/launch-prompts/` as negative test evidence.
|
|
28
28
|
|
|
29
29
|
Normal-output completion has a separate accepted finite policy: all surrounding
|
|
30
|
-
bytes must equal one of the captured normal banners,
|
|
31
|
-
|
|
30
|
+
bytes must equal one of the captured normal banners, except for its bounded
|
|
31
|
+
directory line and the source-derived billing atoms described below. Candidates are the exact home, a home-directory-relative `~` spelling,
|
|
32
32
|
and `~/…/` followed by nonempty whole-component suffixes within the user home.
|
|
33
33
|
Every complete line must fit 110 columns. Only conservative ASCII path components
|
|
34
34
|
without traversal or empty segments qualify. These variants can only terminate
|
|
@@ -45,5 +45,40 @@ network and real-home access, seeded onboarding/trust/feature flag, one Enter,
|
|
|
45
45
|
stable bytes at 200ms/1s/3s, and verified private-server cleanup. The prompt and
|
|
46
46
|
blank transition were byte-identical to the earlier captures. No configuration,
|
|
47
47
|
credentials or extracted source is included. No task or real-account/channel
|
|
48
|
-
connection was tested.
|
|
49
|
-
unqualified; a submitted answer can be followed by a retained blocked result.
|
|
48
|
+
connection was tested. Apart from the billing atoms below, other
|
|
49
|
+
model/billing/effort/permission variants remain unqualified; a submitted answer can be followed by a retained blocked result.
|
|
50
|
+
|
|
51
|
+
## Source-derived subscription billing variants
|
|
52
|
+
|
|
53
|
+
**SOURCE-DERIVED / SYNTHETIC, not observed subscription captures:** the adapter
|
|
54
|
+
also constructs complete empty-frame variants for `Claude Max`, `Claude Pro`,
|
|
55
|
+
`Claude Team` and `Claude Enterprise`. It substitutes only the billing atom in
|
|
56
|
+
row 2 of each accepted API frame. Opus 5.5, auto mode, medium effort, separators,
|
|
57
|
+
empty input, notices and all remaining rows stay exact. The existing bounded
|
|
58
|
+
home-row policy is unchanged. These variants cannot authorize input.
|
|
59
|
+
|
|
60
|
+
Provenance is the same pinned 2.1.289 darwin-arm64 executable SHA256 above,
|
|
61
|
+
rechecked by read-only inspection. In that binary, `Knr` at the region containing
|
|
62
|
+
byte offset 182366506 falls back to the four subscription labels (or
|
|
63
|
+
`Claude API` by default). Before that fallback it may return
|
|
64
|
+
`Claude ${planDisplayName}` when the account value and gates permit it. Those
|
|
65
|
+
custom display names are not qualified unless their complete bytes equal an
|
|
66
|
+
explicitly accepted label; subscription membership alone does not qualify a
|
|
67
|
+
banner. The welcome-data
|
|
68
|
+
region containing offset 197387574 selects that billing value independently;
|
|
69
|
+
`Hgr` at offset 197387656 splits model/billing only when their display widths
|
|
70
|
+
plus the three-character separator exceed the available width. These four
|
|
71
|
+
short labels fit the accepted Opus 5.5 header at 110 columns. The test generates
|
|
72
|
+
these explicitly synthetic derivatives and checks the real qualification and
|
|
73
|
+
controller path with a test-local executable hash substitution. No binary or
|
|
74
|
+
proprietary extracted module is included.
|
|
75
|
+
|
|
76
|
+
The reported Max journey is different evidence: its later retained pane has
|
|
77
|
+
SHA256 `9eb587ab3ac7f97b746169619e02e3c8dd7df2c9069ff4368b6f0858c0964c68`,
|
|
78
|
+
1597 bytes and 51 newline rows. It shows task activity and bypass-permissions
|
|
79
|
+
mode. Captured at 2026-10-07T14:31:54.028296Z, it follows the submitted Enter at
|
|
80
|
+
14:31:45.365Z and block at 14:31:45.476Z. Its geometry, executable digest and
|
|
81
|
+
plugin version were not independently recorded; no earlier raw frame exists.
|
|
82
|
+
It is not padded, cropped or claimed as a qualified 110x35 first frame. See the
|
|
83
|
+
[published operator evidence](https://github.com/awebai/oats/issues/754#issuecomment-6040215059).
|
|
84
|
+
The billing-only extension does not recognize that later task-filled screen.
|
|
@@ -58,7 +58,8 @@ function captured(name) {
|
|
|
58
58
|
}
|
|
59
59
|
|
|
60
60
|
// Accepted as a completion-only finite policy, not a general claim about
|
|
61
|
-
// Claude's path renderer.
|
|
61
|
+
// Claude's path renderer. Apart from the source-derived billing atom below,
|
|
62
|
+
// all surrounding bytes remain the captured frame.
|
|
62
63
|
// Nothing produced here can match a prompt or authorize an input action.
|
|
63
64
|
function completedFrames(home) {
|
|
64
65
|
if (typeof home !== "string" || !/^\/[A-Za-z0-9_./-]+$/.test(home)) return [];
|
|
@@ -74,11 +75,16 @@ function completedFrames(home) {
|
|
|
74
75
|
}
|
|
75
76
|
const banners = ["frame-07-after-channel-200ms.txt", "frame-08-installed-after-channel-200ms.txt"];
|
|
76
77
|
const prefix = " ▝▝ ▝▝ ";
|
|
77
|
-
|
|
78
|
+
// Source-derived billing atoms change only this header row. The complete
|
|
79
|
+
// empty input/status frame remains exact; these are not account captures.
|
|
80
|
+
// See launch-prompt-fixtures/README.md for the pinned source provenance.
|
|
81
|
+
const billings = ["API Usage Billing", "Claude Max", "Claude Pro", "Claude Team", "Claude Enterprise"];
|
|
82
|
+
return banners.flatMap(name => [...paths].filter(path => prefix.length + path.length <= MANIFEST.geometry.width).flatMap(path => billings.map(billing => {
|
|
78
83
|
const variant = captured(name).split("\n");
|
|
84
|
+
variant[1] = "▝▜██████▀ Opus 5.5 · " + billing;
|
|
79
85
|
variant[2] = prefix + path;
|
|
80
86
|
return variant.join("\n");
|
|
81
|
-
}));
|
|
87
|
+
})));
|
|
82
88
|
}
|
|
83
89
|
|
|
84
90
|
/** Read-only qualification: no version command or harness invocation. argv is
|
|
@@ -8,6 +8,10 @@ import { resolveSoul } from "./resolve.mjs";
|
|
|
8
8
|
|
|
9
9
|
export const OPERATOR_CAPABILITY = "oats.setup";
|
|
10
10
|
const SEAT = "an eligible soul is not a launched seat";
|
|
11
|
+
/** The core slot an operator must not empty (maintainer decision, 0.45.0): messaging, so it is reachable.
|
|
12
|
+
* Emptying knowledge or tasks (`knowledge: none`, `tasks: none`) does not disqualify an operator. Only
|
|
13
|
+
* `slot-none` is judged here: a capability the soul turns `off` is not (#671's rule, unchanged). */
|
|
14
|
+
const OPERATOR_SLOTS = new Set(["messaging"]);
|
|
11
15
|
|
|
12
16
|
/** The Desktop refuses a whole readiness answer whose item `reason` or `remedy` is over 1024 characters
|
|
13
17
|
* (packages/desktop/renderer/readiness-contract.mjs): each detail is clipped, lists show three and a count,
|
|
@@ -26,9 +30,9 @@ const declaresOperator = (entry) => obj(entry?.definition?.capabilities) && Obje
|
|
|
26
30
|
/**
|
|
27
31
|
* The coverage of the workspace and of `teams` (labels), from one discovery. A soul covers when it is
|
|
28
32
|
* offered (soulCandidates), not disabled here (souls.disabled), resolves as a spawn would (resolveSoul),
|
|
29
|
-
* composes oats.setup, and
|
|
30
|
-
*
|
|
31
|
-
* team is among its resolved teams. Souls are resolved in turn until every question is answered.
|
|
33
|
+
* composes oats.setup, and does not empty the messaging slot the workspace fills (no `slot-none` on
|
|
34
|
+
* messaging in turnedOff: it stays reachable; `knowledge: none` and `tasks: none` are its own choice).
|
|
35
|
+
* It covers a team when the team is among its resolved teams. Souls are resolved in turn until every question is answered.
|
|
32
36
|
*
|
|
33
37
|
* → { known: true, workspace: { covered, by }, teams: [{ label, covered, by }], excluded: [{ soul, code, slots? }] }
|
|
34
38
|
* | { known: false, reason }
|
|
@@ -67,8 +71,8 @@ export async function operatorCoverage({ discovery, local = null, lock = null, t
|
|
|
67
71
|
throw e;
|
|
68
72
|
}
|
|
69
73
|
if (!(res.modules || []).some((m) => m.name === OPERATOR_CAPABILITY)) continue;
|
|
70
|
-
const emptied = (res.turnedOff || []).filter((o) => o.reason === "slot-none");
|
|
71
|
-
if (emptied.length) { excluded.push({ soul, code: "slot-none", slots: emptied.map((o) => o.slot) }); continue; }
|
|
74
|
+
const emptied = (res.turnedOff || []).filter((o) => o.reason === "slot-none" && OPERATOR_SLOTS.has(o.slot));
|
|
75
|
+
if (emptied.length) { excluded.push({ soul, code: "slot-none", slots: [...new Set(emptied.map((o) => o.slot))] }); continue; }
|
|
72
76
|
by.workspace ??= soul;
|
|
73
77
|
for (const t of res.teams || []) if (wanted.includes(t.label) && !by.teams.has(t.label)) by.teams.set(t.label, soul);
|
|
74
78
|
}
|
|
@@ -89,7 +93,7 @@ export function operatorProblems(coverage, { workspace = null, unknownRemedy = "
|
|
|
89
93
|
if (!coverage?.known) return [{ code: "operator-coverage-unknown", message: clip(`operator coverage unknown: ${clip(coverage?.reason ?? "not computed", 700)}; this says nothing about whether an operator soul exists`, MAX_TEXT), remedy: clip(unknownRemedy, MAX_TEXT) }];
|
|
90
94
|
const named = workspace ? `workspace ${workspace}` : "this workspace";
|
|
91
95
|
const why = coverage.excluded.length ? ` (not usable here: ${some(coverage.excluded.map((x) => clip(`${x.soul} ${x.code}${x.slots ? ` ${x.slots.join(",")}` : ""}`)))})` : "";
|
|
92
|
-
const remedy = `give a soul the ${OPERATOR_CAPABILITY} capability in its soul.yaml (reviewed source), keeping the workspace's
|
|
96
|
+
const remedy = `give a soul the ${OPERATOR_CAPABILITY} capability in its soul.yaml (reviewed source), keeping the workspace's messaging (no \`messaging: none\`), then \`oats spawn <soul> --preview\``;
|
|
93
97
|
const out = [];
|
|
94
98
|
if (!coverage.workspace.covered) {
|
|
95
99
|
out.push({ code: "operator-soul-missing", message: clip(`no soul ${clip(named)} offers composes ${OPERATOR_CAPABILITY}, so it has no operator soul${why}; ${SEAT}`, MAX_TEXT), remedy, excluded: coverage.excluded });
|
package/lib/servers.mjs
CHANGED
|
@@ -708,6 +708,9 @@ export function routeCommand(serverId, cmd, oatsArgs, io = {}) {
|
|
|
708
708
|
if (!Array.isArray(remote.features) || !remote.features.includes("operations") || ![1, 2].includes(remote.operationsApi)) {
|
|
709
709
|
throw serverError("E_REMOTE_INCOMPATIBLE", `remote oats ${remote.version} at ${target.sshHost} does not advertise the operations contract (kernels from ${OPERATIONS_REMOTE_VERSION} do); upgrade it there; nothing was sent`);
|
|
710
710
|
}
|
|
711
|
+
// `inspect --instructions` (feature soul-composed-instructions): an older host would ignore the
|
|
712
|
+
// flag and answer without the field — refused here instead, nothing sent.
|
|
713
|
+
if (cmd === "inspect" && args.includes("--instructions")) requireRemoteFeature(remote, target, "soul-composed-instructions");
|
|
711
714
|
const scoped = args.includes("--dir") || args.includes("--home") ? args : [...args, "--dir", target.workspace];
|
|
712
715
|
const { envelope, stderr } = runRemote(target, json([cmd, ...scoped]), io);
|
|
713
716
|
return { envelope: envelope.result && typeof envelope.result === "object" ? { ...envelope, result: { ...envelope.result, server: serverId, ...(route ? { route: { home: route.home, instance: route.snapshot?.instance || null, frozen: !!route.snapshot } } : {}) } } : envelope, stderr };
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/** The instructions a spawn of a soul would write, composed WITHOUT a spawn: the one path
|
|
2
|
+
* behind `oats doctor --soul` and `oats inspect --soul --instructions`.
|
|
3
|
+
*
|
|
4
|
+
* It runs spawn's own two halves: the kernel half (composeInstanceAgentsMd: the soul's
|
|
5
|
+
* AGENTS.md, the instance-boundary and work-mode blocks) and materialize (each capability's
|
|
6
|
+
* inject), into a scratch home OUTSIDE the deployment that is removed before it returns (and
|
|
7
|
+
* at exit). Nothing in the deployment is written. Capability blocks are reported
|
|
8
|
+
* home-relative (`.oats/modules/<cap>/<inject>`, where an instance carries them); kernel
|
|
9
|
+
* blocks keep the installed package's absolute path, as spawn writes them.
|
|
10
|
+
*
|
|
11
|
+
* Single-path guard: the reported text is re-rendered by renderInstructionParts (for the
|
|
12
|
+
* ranges), so rendering the same parts with the scratch paths must give back, byte for byte,
|
|
13
|
+
* the AGENTS.md materialize wrote — else E_COMPOSITION_INCOMPLETE, never a second answer. */
|
|
14
|
+
import { existsSync, mkdtempSync, readFileSync, realpathSync, rmSync } from "node:fs";
|
|
15
|
+
import { tmpdir } from "node:os";
|
|
16
|
+
import { isAbsolute, join, relative, sep } from "node:path";
|
|
17
|
+
import { composeInstanceAgentsMd, findAgentAt } from "./core.mjs";
|
|
18
|
+
import { agentDirOf, materializePrepared } from "./instance-resolution.mjs";
|
|
19
|
+
import { renderInstructionParts } from "./instruction-composition.mjs";
|
|
20
|
+
import { oatsError } from "./errors.mjs";
|
|
21
|
+
|
|
22
|
+
/** The cap of a reported text, as inspect's `instructions` (JS string length). */
|
|
23
|
+
export const COMPOSED_TEXT_CAP = 200_000;
|
|
24
|
+
|
|
25
|
+
const fail = (code, message, details) => Object.assign(oatsError(code, message), details ? { details } : {});
|
|
26
|
+
|
|
27
|
+
/** A Node.js filesystem/system error (EACCES, EISDIR, ENOENT…), as opposed to a kernel refusal (E_…)
|
|
28
|
+
* or a programming error: the composition reports it as its own refusal, never a crash. */
|
|
29
|
+
const systemError = (e) => typeof e?.syscall === "string" && typeof e.code === "string" && !e.code.startsWith("E_");
|
|
30
|
+
|
|
31
|
+
/** `[start, end)` clamped to the capped text; `truncated` when the cap cut into the part. */
|
|
32
|
+
function clampSpan({ start, end }, length) {
|
|
33
|
+
return { start: Math.min(start, length), end: Math.min(end, length), truncated: end > length };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Compose `prepared`'s soul, whose copy is at `soulDir`, as a spawn here with no flags would.
|
|
37
|
+
* → { text, blocks, resolved, oatsCoreDeclared, composedInstructions }
|
|
38
|
+
* - text: the full document (capability markers home-relative);
|
|
39
|
+
* - blocks: every block in text order ({ source, file, content }, capability blocks
|
|
40
|
+
* home-relative and `materialized: true`);
|
|
41
|
+
* - composedInstructions: inspect's `{ file: null, text, truncated, resolution, body, sources }`,
|
|
42
|
+
* `text` capped at `cap` and every range clamped to it.
|
|
43
|
+
* Throws an E_ coded error when the soul cannot be composed here. `materialize` is a test seam. */
|
|
44
|
+
export async function composeSoulInstructions({ deployment, prepared, soulDir, cap = COMPOSED_TEXT_CAP, materialize = materializePrepared }) {
|
|
45
|
+
const soulName = prepared.soulEntry?.name ?? agentDirOf(prepared.soulEntry);
|
|
46
|
+
let agent, composition, body;
|
|
47
|
+
try {
|
|
48
|
+
agent = findAgentAt(join(deployment, "agents"), agentDirOf(prepared.soulEntry), soulDir);
|
|
49
|
+
if (!agent) throw fail("E_SOUL_UNKNOWN", `soul "${soulName}" was fetched but is not readable as a soul`);
|
|
50
|
+
const bodyFile = join(soulDir, "AGENTS.md");
|
|
51
|
+
if (!existsSync(bodyFile)) throw fail("E_SOUL_INCOMPLETE", `soul "${soulName}" has no canonical AGENTS.md (${bodyFile})`);
|
|
52
|
+
// The work mode and kind as a spawn with no flags derives them (spawnInstance: o.work || agent.work || "checkout").
|
|
53
|
+
composition = composeInstanceAgentsMd(soulDir, deployment, agent.name, agent.work || "checkout", agent.kind, prepared);
|
|
54
|
+
body = readFileSync(bodyFile, "utf8");
|
|
55
|
+
} catch (e) {
|
|
56
|
+
if (systemError(e)) throw fail("E_SOUL_INCOMPLETE", `soul "${soulName}" cannot be read here: ${e.message}`, { cause: e.code });
|
|
57
|
+
throw e;
|
|
58
|
+
}
|
|
59
|
+
let scratch;
|
|
60
|
+
try { scratch = realpathSync(mkdtempSync(join(tmpdir(), "oats-compose-home-"))); }
|
|
61
|
+
catch (e) { throw fail("E_MATERIALIZE_HOME", `cannot create a scratch home to compose soul "${soulName}" in under ${tmpdir()}: ${e.message}`, { why: "unwritable", cause: e.code }); }
|
|
62
|
+
const remove = () => { try { rmSync(scratch, { recursive: true, force: true }); } catch { /* best effort: a temporary copy only */ } };
|
|
63
|
+
process.once("exit", remove);
|
|
64
|
+
try {
|
|
65
|
+
const outcome = await materialize({ ...prepared, soulAgentsMd: composition.text, soulDir }, scratch);
|
|
66
|
+
const written = readFileSync(join(scratch, "AGENTS.md"), "utf8");
|
|
67
|
+
const materialized = Array.isArray(outcome?.blocks) ? outcome.blocks : [];
|
|
68
|
+
if (renderInstructionParts(body, [...composition.blocks, ...materialized]).text !== written) {
|
|
69
|
+
throw fail("E_COMPOSITION_INCOMPLETE", `soul "${soulName}": the instructions materialize wrote are not the kernel's composition plus the capability blocks it reported; nothing is reported in their place`);
|
|
70
|
+
}
|
|
71
|
+
const homeRelative = (file) => {
|
|
72
|
+
const rel = relative(scratch, file);
|
|
73
|
+
if (!rel || rel.startsWith("..") || isAbsolute(rel)) throw fail("E_COMPOSITION_INCOMPLETE", `soul "${soulName}": a capability block (${file}) is not inside the composed home`);
|
|
74
|
+
return rel.split(sep).join("/");
|
|
75
|
+
};
|
|
76
|
+
const capabilityBlocks = materialized.map((b) => ({ source: b.source, file: homeRelative(b.file), content: b.content, materialized: true }));
|
|
77
|
+
const blocks = [...composition.blocks, ...capabilityBlocks];
|
|
78
|
+
const parts = renderInstructionParts(body, blocks);
|
|
79
|
+
const length = Math.min(parts.text.length, cap);
|
|
80
|
+
const kernelBlocks = composition.blocks.length;
|
|
81
|
+
return {
|
|
82
|
+
text: parts.text, blocks, resolved: composition.resolved, oatsCoreDeclared: composition.oatsCoreDeclared,
|
|
83
|
+
composedInstructions: {
|
|
84
|
+
file: null, text: parts.text.slice(0, length), truncated: parts.text.length > length,
|
|
85
|
+
resolution: prepared.resolution?.revision ?? null,
|
|
86
|
+
body: clampSpan(parts.body, length),
|
|
87
|
+
sources: parts.blocks.map((span, i) => ({ source: blocks[i].source, file: i < kernelBlocks ? null : blocks[i].file, ...clampSpan(span, length) })),
|
|
88
|
+
},
|
|
89
|
+
};
|
|
90
|
+
} catch (e) {
|
|
91
|
+
if (systemError(e)) throw fail("E_MATERIALIZE_HOME", `soul "${soulName}" could not be composed in a scratch home: ${e.message}`, { why: "scratch", cause: e.code });
|
|
92
|
+
throw e;
|
|
93
|
+
} finally {
|
|
94
|
+
remove();
|
|
95
|
+
process.removeListener("exit", remove);
|
|
96
|
+
}
|
|
97
|
+
}
|