@yunhozz/arc 0.2.7 → 0.3.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/MANIFEST.sha256 +115 -68
- package/README.md +21 -5
- package/claude/agents/arc-implementer.md +3 -3
- package/claude/agents/arc-planner.md +3 -3
- package/claude/agents/arc-qa.md +3 -3
- package/claude/agents/arc-reviewer.md +3 -3
- package/claude/agents/arc-scouter.md +3 -3
- package/claude/skill/SKILL.md +5 -5
- package/claude/skill/models.toml +7 -48
- package/claude/skill/references/commit.md +7 -7
- package/claude/skill/references/coordination.md +39 -3
- package/claude/skill/references/git-recovery.md +1 -1
- package/claude/skill/references/handoff-prep.md +6 -6
- package/claude/skill/references/handoff.md +8 -3
- package/claude/skill/references/limits.md +2 -0
- package/claude/skill/references/planning.md +8 -8
- package/claude/skill/references/verification.md +9 -9
- package/claude/skill/runtime/adapters/claude.mjs +4 -0
- package/claude/skill/runtime/adapters/codex.mjs +3 -0
- package/claude/skill/runtime/bootstrap.mjs +4 -2
- package/claude/skill/runtime/command.mjs +21 -4
- package/claude/skill/runtime/local-cli.mjs +248 -0
- package/claude/skill/runtime/role-bridge-args.mjs +148 -0
- package/claude/skill/runtime/role-bridge.mjs +227 -0
- package/claude/skill/runtime/role-dispatch-policy.mjs +110 -0
- package/claude/skill/runtime/role-dispatch-store.mjs +134 -0
- package/claude/skill/runtime/role-observe.mjs +299 -0
- package/claude/skill/runtime/role-policy.json +12 -10
- package/claude/skill/runtime/role-routing-config.mjs +19 -0
- package/claude/skill/runtime/role-routing.mjs +233 -0
- package/claude/skill/runtime/role-supervisor.mjs +356 -0
- package/claude/skill/scripts/model_config.py +23 -5
- package/codex/agents/arc-implementer.toml +3 -3
- package/codex/agents/arc-planner.toml +3 -3
- package/codex/agents/arc-qa.toml +3 -3
- package/codex/agents/arc-reviewer.toml +3 -3
- package/codex/agents/arc-scouter.toml +3 -3
- package/codex/skill/SKILL.md +5 -5
- package/codex/skill/models.toml +7 -48
- package/codex/skill/references/commit.md +7 -7
- package/codex/skill/references/coordination.md +38 -2
- package/codex/skill/references/handoff-prep.md +6 -6
- package/codex/skill/references/handoff-worktree.md +3 -3
- package/codex/skill/references/handoff.md +8 -3
- package/codex/skill/references/limits.md +2 -0
- package/codex/skill/references/planning.md +8 -8
- package/codex/skill/references/verification.md +9 -9
- package/codex/skill/runtime/adapters/claude.mjs +4 -0
- package/codex/skill/runtime/adapters/codex.mjs +3 -0
- package/codex/skill/runtime/bootstrap.mjs +4 -2
- package/codex/skill/runtime/command.mjs +21 -4
- package/codex/skill/runtime/local-cli.mjs +248 -0
- package/codex/skill/runtime/role-bridge-args.mjs +148 -0
- package/codex/skill/runtime/role-bridge.mjs +227 -0
- package/codex/skill/runtime/role-dispatch-policy.mjs +110 -0
- package/codex/skill/runtime/role-dispatch-store.mjs +134 -0
- package/codex/skill/runtime/role-observe.mjs +299 -0
- package/codex/skill/runtime/role-policy.json +12 -10
- package/codex/skill/runtime/role-routing-config.mjs +19 -0
- package/codex/skill/runtime/role-routing.mjs +233 -0
- package/codex/skill/runtime/role-supervisor.mjs +356 -0
- package/codex/skill/scripts/model_config.py +17 -22
- package/lib/cli/root.mjs +3 -2
- package/lib/installer/install-mode.mjs +34 -0
- package/lib/installer/install.mjs +1 -1
- package/lib/installer/plan.mjs +16 -7
- package/lib/installer/preset.mjs +18 -11
- package/lib/installer/role-routing.mjs +175 -0
- package/lib/installer/runtime-assets.mjs +9 -0
- package/lib/installer/targets.mjs +2 -7
- package/lib/installer/transaction.mjs +1 -1
- package/lib/installer/uninstall.mjs +10 -5
- package/lib/installer/upgrade-state.mjs +9 -6
- package/lib/installer/upgrade.mjs +2 -2
- package/lib/management/operations.mjs +94 -5
- package/lib/management/status.mjs +12 -6
- package/lib/management/update.mjs +3 -1
- package/lib/models/catalog.mjs +3 -3
- package/lib/models/claude-models.json +297 -0
- package/lib/models/codex-catalog.mjs +9 -6
- package/lib/models/codex-models.json +189 -0
- package/lib/models/config.mjs +25 -20
- package/lib/models/index.mjs +1 -1
- package/lib/models/static-catalog.mjs +42 -0
- package/lib/policy/role-policy.json +12 -10
- package/lib/runtime/adapters/claude.mjs +4 -0
- package/lib/runtime/adapters/codex.mjs +3 -0
- package/lib/runtime/bootstrap.mjs +4 -2
- package/lib/runtime/command.mjs +21 -4
- package/lib/runtime/local-cli.mjs +248 -0
- package/lib/runtime/role-bridge-args.mjs +148 -0
- package/lib/runtime/role-bridge.mjs +227 -0
- package/lib/runtime/role-dispatch-policy.mjs +110 -0
- package/lib/runtime/role-dispatch-store.mjs +134 -0
- package/lib/runtime/role-observe.mjs +299 -0
- package/lib/runtime/role-routing-config.mjs +19 -0
- package/lib/runtime/role-routing.mjs +233 -0
- package/lib/runtime/role-supervisor.mjs +356 -0
- package/lib/tui/app.mjs +32 -23
- package/lib/tui/custom-preset.mjs +138 -66
- package/lib/tui/render.mjs +4 -3
- package/lib/tui/setup.mjs +96 -51
- package/lib/watch/args.mjs +43 -0
- package/lib/watch/discover-claude.mjs +63 -0
- package/lib/watch/discover-codex.mjs +45 -0
- package/lib/watch/dispatch.mjs +133 -0
- package/lib/watch/git.mjs +29 -0
- package/lib/watch/index.mjs +112 -0
- package/lib/watch/labels.mjs +24 -0
- package/lib/watch/model.mjs +48 -0
- package/lib/watch/normalize-claude.mjs +99 -0
- package/lib/watch/normalize-codex.mjs +96 -0
- package/lib/watch/policy.mjs +52 -0
- package/lib/watch/render.mjs +86 -0
- package/lib/watch/scope.mjs +64 -0
- package/lib/watch/tail.mjs +75 -0
- package/lib/watch/watcher.mjs +337 -0
- package/package.json +2 -2
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import { StringDecoder } from 'node:string_decoder';
|
|
4
|
+
import { spawn } from 'node:child_process';
|
|
5
|
+
import { DEFAULT_POLICY } from './role-dispatch-policy.mjs';
|
|
6
|
+
|
|
7
|
+
const environments = new WeakMap();
|
|
8
|
+
export function resolveConfigHome(platform, { userHome, env = {}, cwd } = {}) {
|
|
9
|
+
if (!['codex', 'claude'].includes(platform)) throw Error('Target must be codex or claude');
|
|
10
|
+
if (typeof userHome !== 'string' || !path.isAbsolute(userHome) || !userHome.trim()) throw Error('userHome must be an absolute user directory');
|
|
11
|
+
userHome = path.resolve(userHome);
|
|
12
|
+
if (!env || typeof env !== 'object') throw Error('env must be an environment object');
|
|
13
|
+
const expand = value => value === '~' ? userHome : value.startsWith('~/') ? path.join(userHome, value.slice(2)) : value;
|
|
14
|
+
let home;
|
|
15
|
+
if (platform === 'codex') {
|
|
16
|
+
const raw = env.CODEX_HOME;
|
|
17
|
+
if (raw !== undefined && (typeof raw !== 'string' || !raw.trim())) throw Error('CODEX_HOME is empty or invalid');
|
|
18
|
+
const expanded = expand(raw ?? path.join(userHome, '.codex'));
|
|
19
|
+
if (path.isAbsolute(expanded)) home = path.resolve(expanded);
|
|
20
|
+
else { const base = cwd ?? process.cwd(); if (typeof base !== 'string' || !path.isAbsolute(base)) throw Error('cwd must be absolute for relative CODEX_HOME'); home = path.resolve(base, expanded); }
|
|
21
|
+
} else {
|
|
22
|
+
home = path.join(userHome, '.claude'); const raw = env.CLAUDE_CONFIG_DIR;
|
|
23
|
+
if (raw !== undefined && (typeof raw !== 'string' || !raw.trim() || !path.isAbsolute(expand(raw)) || path.resolve(expand(raw)) !== home)) throw Error('CLAUDE_CONFIG_DIR must select the default ~/.claude directory');
|
|
24
|
+
}
|
|
25
|
+
if (home === '/' || home === userHome) throw Error('Target home must not be the filesystem or user-home root');
|
|
26
|
+
return home;
|
|
27
|
+
}
|
|
28
|
+
export function resolveLocalCli(platform, { cwd, userHome, env = process.env } = {}) {
|
|
29
|
+
if (!['codex', 'claude'].includes(platform)) return { platform, reason: 'unsupported_platform' };
|
|
30
|
+
let home;
|
|
31
|
+
try {
|
|
32
|
+
if (typeof cwd !== 'string' || !path.isAbsolute(cwd) || path.resolve(cwd) !== cwd || !fs.statSync(cwd).isDirectory()) return { platform, reason: 'invalid_cwd' };
|
|
33
|
+
home = resolveConfigHome(platform, { cwd, userHome, env });
|
|
34
|
+
} catch { return { platform, reason: 'invalid_context' }; }
|
|
35
|
+
const dirs = typeof env.PATH === 'string' ? env.PATH.split(path.delimiter) : [];
|
|
36
|
+
let executable;
|
|
37
|
+
for (const dir of dirs) {
|
|
38
|
+
const candidate = path.resolve(cwd, dir || '.', platform);
|
|
39
|
+
try { if (fs.statSync(candidate).isFile()) { fs.accessSync(candidate, fs.constants.X_OK); executable = candidate; break; } } catch { /* continue PATH search */ }
|
|
40
|
+
}
|
|
41
|
+
if (!executable) return { platform, reason: 'cli_not_found' };
|
|
42
|
+
const context = Object.freeze({ platform, executable, cwd, configHome: home });
|
|
43
|
+
environments.set(context, Object.freeze({ ...env, [platform === 'codex' ? 'CODEX_HOME' : 'CLAUDE_CONFIG_DIR']: home }));
|
|
44
|
+
return context;
|
|
45
|
+
}
|
|
46
|
+
export function localCliEnvironment(context) { const env = environments.get(context); if (!env) throw Error('Invalid CLI context'); return { ...env }; }
|
|
47
|
+
/** Checks Codex authentication with refresh; only a token-presence boolean survives parsing. */
|
|
48
|
+
export async function probeCodexAuthStatus(context, { signal, timeoutMs = 10000 } = {}) {
|
|
49
|
+
const result = (authStatus, reason) => ({ platform: 'codex', authStatus, ...(reason ? { reason } : {}) });
|
|
50
|
+
if (!environments.has(context) || context.platform !== 'codex') return result('unknown', context?.reason ?? 'invalid_context');
|
|
51
|
+
if (signal?.aborted) return result('unknown', 'aborted');
|
|
52
|
+
let child;
|
|
53
|
+
try { child = spawn(context.executable, ['app-server'], { cwd: context.cwd, env: localCliEnvironment(context), stdio: ['pipe', 'pipe', 'pipe'], shell: false }); }
|
|
54
|
+
catch { return result('unknown', 'cli_execution_error'); }
|
|
55
|
+
let closed = false, failure, pending, nextId = 0, buffer = '', outputBytes = 0;
|
|
56
|
+
const decoder = new StringDecoder('utf8');
|
|
57
|
+
let resolveClosed;
|
|
58
|
+
const closedPromise = new Promise(resolve => { resolveClosed = resolve; });
|
|
59
|
+
const fail = reason => { failure ??= reason; if (pending) { const {reject} = pending; pending = null; reject(); } };
|
|
60
|
+
const onClose = () => { closed = true; resolveClosed(); fail('cli_execution_error'); };
|
|
61
|
+
const onError = () => fail('cli_execution_error');
|
|
62
|
+
const onAbort = () => fail('aborted');
|
|
63
|
+
const countOutput = chunk => { outputBytes += chunk.length; if (outputBytes > 1048576) { fail('invalid_response'); return false; } return !failure; };
|
|
64
|
+
const classify = value => {
|
|
65
|
+
if (!value || typeof value !== 'object' || Array.isArray(value) || !(value.requiresOpenaiAuth === null || typeof value.requiresOpenaiAuth === 'boolean') ||
|
|
66
|
+
!(value.authMethod === null || typeof value.authMethod === 'string') ||
|
|
67
|
+
!(value.authToken === null || typeof value.authToken === 'string')) return result('unknown', 'invalid_response');
|
|
68
|
+
const hasToken = typeof value.authToken === 'string' && value.authToken.length > 0;
|
|
69
|
+
if (value.requiresOpenaiAuth === false || typeof value.authMethod === 'string' && hasToken) return result('authenticated');
|
|
70
|
+
if (value.authMethod === null) return result('unauthorized', 'not_logged_in');
|
|
71
|
+
if (value.authToken !== null) return result('unknown', 'invalid_response');
|
|
72
|
+
if (value.authMethod === 'chatgpt') return result('unauthorized', 'token_rejected');
|
|
73
|
+
if (['headers', 'agentIdentity', 'personalAccessToken'].includes(value.authMethod)) return result('authenticated');
|
|
74
|
+
return result('unknown', 'auth_unverified');
|
|
75
|
+
};
|
|
76
|
+
const onData = chunk => {
|
|
77
|
+
if (!countOutput(chunk)) { buffer = ''; return; }
|
|
78
|
+
buffer += decoder.write(chunk);
|
|
79
|
+
let newline;
|
|
80
|
+
while (!failure && (newline = buffer.indexOf('\n')) !== -1) {
|
|
81
|
+
let line = buffer.slice(0, newline); buffer = buffer.slice(newline + 1);
|
|
82
|
+
if (!line.trim()) continue;
|
|
83
|
+
let message;
|
|
84
|
+
try { message = JSON.parse(line); } catch { line = ''; buffer = ''; fail('invalid_response'); return; }
|
|
85
|
+
line = '';
|
|
86
|
+
if (message && typeof message === 'object' && !Array.isArray(message) &&
|
|
87
|
+
(Object.hasOwn(message, 'method') || !Object.hasOwn(message, 'id'))) { message = null; continue; }
|
|
88
|
+
if (!message || !pending || message.id !== pending.id) { message = null; fail('invalid_response'); return; }
|
|
89
|
+
if (Object.hasOwn(message, 'error')) { message = null; fail('status_command_failed'); return; }
|
|
90
|
+
if (!Object.hasOwn(message, 'result')) { message = null; fail('invalid_response'); return; }
|
|
91
|
+
const value = pending.method === 'initialize'
|
|
92
|
+
? (message.result && typeof message.result === 'object' && !Array.isArray(message.result) && typeof message.result.userAgent === 'string' && message.result.userAgent.length > 0 ? true : false)
|
|
93
|
+
: classify(message.result);
|
|
94
|
+
message = null;
|
|
95
|
+
const {resolve} = pending; pending = null; resolve(value);
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
const onStderr = chunk => { countOutput(chunk); };
|
|
99
|
+
child.on('close', onClose); child.on('error', onError);
|
|
100
|
+
child.stdout.on('data', onData); child.stderr.on('data', onStderr);
|
|
101
|
+
for (const stream of [child.stdin, child.stdout, child.stderr]) stream.on('error', onError);
|
|
102
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
103
|
+
if (signal?.aborted) onAbort();
|
|
104
|
+
const timer = setTimeout(() => fail('timeout'), Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : 10000);
|
|
105
|
+
const send = message => { if (failure || closed) throw new Error('Codex authentication unavailable'); child.stdin.write(JSON.stringify(message) + '\n'); };
|
|
106
|
+
const request = (method, params) => new Promise((resolve, reject) => {
|
|
107
|
+
if (failure || closed) { reject(); return; }
|
|
108
|
+
const id = ++nextId; pending = {id, method, resolve, reject};
|
|
109
|
+
try { send({id, method, params}); } catch { fail('cli_execution_error'); }
|
|
110
|
+
});
|
|
111
|
+
let authentication;
|
|
112
|
+
try {
|
|
113
|
+
if (!await request('initialize', {clientInfo: {name: 'arc', title: 'ARC', version: '1.0.0'}})) fail('invalid_response');
|
|
114
|
+
send({method: 'initialized', params: {}});
|
|
115
|
+
authentication = await request('getAuthStatus', {includeToken: true, refreshToken: true});
|
|
116
|
+
if (failure) authentication = result('unknown', failure);
|
|
117
|
+
} catch { authentication = result('unknown', failure ?? 'cli_execution_error'); }
|
|
118
|
+
finally {
|
|
119
|
+
clearTimeout(timer); signal?.removeEventListener('abort', onAbort);
|
|
120
|
+
buffer = ''; pending = null;
|
|
121
|
+
try { child.stdin.end(); } catch { /* cleanup only */ }
|
|
122
|
+
if (!closed) { try { child.kill('SIGTERM'); } catch { /* still wait for close */ } }
|
|
123
|
+
const wait = async ms => {
|
|
124
|
+
if (closed) return true;
|
|
125
|
+
let timerId;
|
|
126
|
+
const done = await Promise.race([closedPromise.then(() => true), new Promise(resolve => { timerId = setTimeout(() => resolve(false), ms); })]);
|
|
127
|
+
clearTimeout(timerId); return done;
|
|
128
|
+
};
|
|
129
|
+
if (!await wait(1000)) {
|
|
130
|
+
try { child.kill('SIGKILL'); } catch { /* bounded cleanup */ }
|
|
131
|
+
if (!await wait(1000)) authentication = result('unknown', 'cli_execution_error');
|
|
132
|
+
}
|
|
133
|
+
child.stdout.removeListener('data', onData); child.stderr.removeListener('data', onStderr);
|
|
134
|
+
child.removeListener('close', onClose);
|
|
135
|
+
// Keep error guards on streams until destruction, including late pipe errors.
|
|
136
|
+
for (const stream of [child.stdin, child.stdout, child.stderr]) stream.destroy();
|
|
137
|
+
}
|
|
138
|
+
return authentication;
|
|
139
|
+
}
|
|
140
|
+
/** Checks local Codex login state without starting app-server or refreshing credentials. */
|
|
141
|
+
export async function probeCodexLoginStatus(context, { signal, timeoutMs = 10000 } = {}) {
|
|
142
|
+
const result = (authStatus, reason) => ({ platform: 'codex', authStatus, ...(reason ? { reason } : {}) });
|
|
143
|
+
if (!environments.has(context) || context.platform !== 'codex') return result('unknown', context?.reason ?? 'invalid_context');
|
|
144
|
+
if (signal?.aborted) return result('unknown', 'aborted');
|
|
145
|
+
let child;
|
|
146
|
+
try { child = spawn(context.executable, ['login', 'status'], { cwd: context.cwd, env: localCliEnvironment(context), stdio: ['ignore', 'pipe', 'pipe'], shell: false }); }
|
|
147
|
+
catch { return result('unknown', 'status_command_failed'); }
|
|
148
|
+
let closed = false, stderr = '', outputBytes = 0, timer, resolveClosed;
|
|
149
|
+
const closedPromise = new Promise(resolve => { resolveClosed = resolve; });
|
|
150
|
+
let finish;
|
|
151
|
+
const authentication = new Promise(resolve => { finish = resolve; });
|
|
152
|
+
const fail = reason => finish(result('unknown', reason));
|
|
153
|
+
const onError = () => fail('status_command_failed');
|
|
154
|
+
const onAbort = () => fail('aborted');
|
|
155
|
+
const countOutput = chunk => {
|
|
156
|
+
outputBytes += chunk.length;
|
|
157
|
+
if (outputBytes > 65536) { stderr = ''; fail('status_command_failed'); return false; }
|
|
158
|
+
return true;
|
|
159
|
+
};
|
|
160
|
+
const onStdout = chunk => { countOutput(chunk); };
|
|
161
|
+
const onStderr = chunk => { if (countOutput(chunk)) stderr += chunk.toString(); };
|
|
162
|
+
const onClose = (code, exitSignal) => {
|
|
163
|
+
closed = true; resolveClosed();
|
|
164
|
+
finish(exitSignal ? result('unknown', 'status_command_failed') : code === 0 ? result('authenticated') :
|
|
165
|
+
code === 1 && stderr.trim() === 'Not logged in' ? result('unauthorized', 'not_logged_in') : result('unknown', 'status_command_failed'));
|
|
166
|
+
};
|
|
167
|
+
child.on('error', onError); child.on('close', onClose);
|
|
168
|
+
child.stdout.on('data', onStdout); child.stderr.on('data', onStderr);
|
|
169
|
+
for (const stream of [child.stdout, child.stderr]) stream.on('error', onError);
|
|
170
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
171
|
+
timer = setTimeout(() => fail('timeout'), Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : 10000);
|
|
172
|
+
if (signal?.aborted) onAbort();
|
|
173
|
+
const value = await authentication;
|
|
174
|
+
clearTimeout(timer); signal?.removeEventListener('abort', onAbort);
|
|
175
|
+
if (!closed) { try { child.kill('SIGTERM'); } catch { /* bounded cleanup */ } }
|
|
176
|
+
const wait = async ms => {
|
|
177
|
+
if (closed) return true;
|
|
178
|
+
let timerId;
|
|
179
|
+
const done = await Promise.race([closedPromise.then(() => true), new Promise(resolve => { timerId = setTimeout(() => resolve(false), ms); })]);
|
|
180
|
+
clearTimeout(timerId); return done;
|
|
181
|
+
};
|
|
182
|
+
if (!await wait(1000)) {
|
|
183
|
+
try { child.kill('SIGKILL'); } catch { /* bounded cleanup */ }
|
|
184
|
+
await wait(1000);
|
|
185
|
+
}
|
|
186
|
+
child.stdout.removeListener('data', onStdout); child.stderr.removeListener('data', onStderr);
|
|
187
|
+
child.removeListener('close', onClose);
|
|
188
|
+
child.stdout.destroy(); child.stderr.destroy();
|
|
189
|
+
return value;
|
|
190
|
+
}
|
|
191
|
+
export async function probePlatformAuth(context, { signal, timeoutMs = 10000 } = {}) {
|
|
192
|
+
const platform = context?.platform;
|
|
193
|
+
const result = (authStatus, reason) => ({ platform, authStatus, ...(reason ? { reason } : {}) });
|
|
194
|
+
if (platform !== 'claude') return result('unknown', 'invalid_context');
|
|
195
|
+
if (!environments.has(context)) return result('unknown', context?.reason ?? 'invalid_context');
|
|
196
|
+
if (signal?.aborted) return result('unknown', 'aborted');
|
|
197
|
+
return new Promise(resolve => {
|
|
198
|
+
let child, output = '', stderr = '', overflow = false, done = false, reason;
|
|
199
|
+
const finish = value => { if (done) return; done = true; clearTimeout(timer); signal?.removeEventListener('abort', abort); resolve(value); };
|
|
200
|
+
const abort = () => { reason = 'aborted'; child?.kill(); finish(result('unknown', reason)); };
|
|
201
|
+
const timer = setTimeout(() => { reason = 'timeout'; child?.kill(); finish(result('unknown', reason)); }, Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : 10000);
|
|
202
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
203
|
+
try { child = spawn(context.executable, ['auth', 'status', '--json'], { cwd: context.cwd, env: localCliEnvironment(context), stdio: ['ignore', 'pipe', 'pipe'], shell: false }); }
|
|
204
|
+
catch { finish(result('unknown', 'cli_execution_error')); return; }
|
|
205
|
+
child.stdout.on('data', chunk => { if (output.length + chunk.length > 65536) overflow = true; else if (!overflow) output += chunk.toString(); });
|
|
206
|
+
child.stderr.on('data', chunk => { if (stderr.length + chunk.length > 65536) overflow = true; else if (!overflow) stderr += chunk.toString(); });
|
|
207
|
+
child.on('error', () => finish(result('unknown', 'cli_execution_error')));
|
|
208
|
+
child.on('close', (code, exitSignal) => {
|
|
209
|
+
if (exitSignal || overflow) return finish(result('unknown', overflow ? 'invalid_response' : 'cli_execution_error'));
|
|
210
|
+
let parsed; try { parsed = JSON.parse(output); } catch { return finish(result('unknown', 'invalid_response')); }
|
|
211
|
+
if (parsed?.loggedIn === true && code === 0) return finish(result('authenticated'));
|
|
212
|
+
if (parsed?.loggedIn === false && code === 1) return finish(result('unauthorized', 'not_logged_in'));
|
|
213
|
+
finish(result('unknown', 'status_mismatch'));
|
|
214
|
+
});
|
|
215
|
+
if (signal?.aborted) abort();
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
export function compareVersions(a, b) {
|
|
219
|
+
const left = String(a).split('.').map(Number), right = String(b).split('.').map(Number);
|
|
220
|
+
for (let i = 0; i < Math.max(left.length, right.length); i += 1) { const x = left[i] ?? 0, y = right[i] ?? 0; if (x !== y) return x < y ? -1 : 1; }
|
|
221
|
+
return 0;
|
|
222
|
+
}
|
|
223
|
+
/** Runs `<cli> --version`; keeps only the parsed version, never the raw output. */
|
|
224
|
+
export async function probeCliVersion(context, { signal, timeoutMs = 10000, policy = DEFAULT_POLICY } = {}) {
|
|
225
|
+
const platform = context?.platform;
|
|
226
|
+
const result = (version, supported, reason) => ({ version, supported, ...(reason ? { reason } : {}) });
|
|
227
|
+
if (!environments.has(context) || signal?.aborted) return result(null, false, 'cli_execution_error');
|
|
228
|
+
return new Promise(resolve => {
|
|
229
|
+
let child, output = '', overflow = false, done = false;
|
|
230
|
+
const finish = value => { if (done) return; done = true; clearTimeout(timer); signal?.removeEventListener('abort', abort); resolve(value); };
|
|
231
|
+
const abort = () => { child?.kill(); finish(result(null, false, 'cli_execution_error')); };
|
|
232
|
+
const timer = setTimeout(() => { child?.kill(); finish(result(null, false, 'timeout')); }, Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : 10000);
|
|
233
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
234
|
+
try { child = spawn(context.executable, ['--version'], { cwd: context.cwd, env: localCliEnvironment(context), stdio: ['ignore', 'pipe', 'pipe'], shell: false }); }
|
|
235
|
+
catch { finish(result(null, false, 'cli_execution_error')); return; }
|
|
236
|
+
child.stdout.on('data', chunk => { if (output.length + chunk.length > 65536) overflow = true; else if (!overflow) output += chunk.toString(); });
|
|
237
|
+
child.stderr.on('data', chunk => { if (chunk.length > 65536) overflow = true; });
|
|
238
|
+
child.on('error', () => finish(result(null, false, 'cli_execution_error')));
|
|
239
|
+
child.on('close', (code, exitSignal) => {
|
|
240
|
+
if (exitSignal || code !== 0 || overflow) return finish(result(null, false, 'cli_execution_error'));
|
|
241
|
+
const version = /\d+\.\d+\.\d+/.exec(output)?.[0] ?? null;
|
|
242
|
+
if (!version) return finish(result(null, false, 'version_unparsed'));
|
|
243
|
+
const range = policy?.supportedVersions?.[platform];
|
|
244
|
+
const supported = Boolean(range) && compareVersions(version, range.min) >= 0 && compareVersions(version, range.below) < 0;
|
|
245
|
+
finish(supported ? result(version, true) : result(version, false, 'version_unsupported'));
|
|
246
|
+
});
|
|
247
|
+
});
|
|
248
|
+
}
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
// Pure helpers that turn an installed arc-routing profile into role-specific Claude/Codex CLI arguments. No processes are started here.
|
|
2
|
+
import crypto from 'node:crypto';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import {DEFAULT_POLICY, effectiveClaudeSandboxSettings} from './role-dispatch-policy.mjs';
|
|
5
|
+
|
|
6
|
+
const ROLES = ['arc_scouter', 'arc_planner', 'arc_implementer', 'arc_qa', 'arc_reviewer'];
|
|
7
|
+
const deepFreeze = value => { for (const child of Object.values(value)) if (child && typeof child === 'object') deepFreeze(child); return Object.freeze(value); };
|
|
8
|
+
export const ROLE_BRIDGE_PERMISSIONS = deepFreeze({
|
|
9
|
+
claude: {
|
|
10
|
+
arc_scouter: {permissionMode: 'default', sandbox: false}, arc_planner: {permissionMode: 'default', sandbox: false},
|
|
11
|
+
arc_implementer: {permissionMode: 'acceptEdits', sandbox: true}, arc_qa: {permissionMode: 'default', sandbox: true}, arc_reviewer: {permissionMode: 'default', sandbox: false}
|
|
12
|
+
},
|
|
13
|
+
codex: {
|
|
14
|
+
arc_scouter: {sandboxMode: 'read-only', search: true}, arc_planner: {sandboxMode: 'read-only', search: false},
|
|
15
|
+
arc_implementer: {sandboxMode: 'workspace-write', search: false}, arc_qa: {sandboxMode: 'workspace-write', search: false}, arc_reviewer: {sandboxMode: 'read-only', search: false}
|
|
16
|
+
}
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
const bad = message => { throw Error(`Invalid composite profile: ${message}`); };
|
|
20
|
+
const unquote = raw => {
|
|
21
|
+
const value = raw.trim();
|
|
22
|
+
if (/^"(?:[^"\\]|\\.)*"$/.test(value)) { try { return JSON.parse(value); } catch { bad('unsupported string escape'); } }
|
|
23
|
+
if (/^'[^']*'$/.test(value)) return value.slice(1, -1);
|
|
24
|
+
return value;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
function parseClaude(text) {
|
|
28
|
+
const lines = text.split('\n').map(line => line.replace(/\r$/, ''));
|
|
29
|
+
if (lines[0] !== '---') bad('missing frontmatter');
|
|
30
|
+
const end = lines.indexOf('---', 1);
|
|
31
|
+
if (end < 0) bad('unterminated frontmatter');
|
|
32
|
+
const fields = {}; let tools = null, inTools = false;
|
|
33
|
+
for (const line of lines.slice(1, end)) {
|
|
34
|
+
const item = /^[ \t]+-[ \t]+(\S.*?)[ \t]*$/.exec(line);
|
|
35
|
+
if (item) { if (!inTools) bad('unexpected list item'); tools.push(unquote(item[1])); continue; }
|
|
36
|
+
const field = /^([A-Za-z][A-Za-z0-9_-]*):[ \t]*(.*?)[ \t]*$/.exec(line);
|
|
37
|
+
if (!field) { if (line.trim() === '') continue; bad('unrecognized frontmatter line'); }
|
|
38
|
+
inTools = false;
|
|
39
|
+
if (field[1] === 'tools') { if (field[2] !== '') bad('tools must be a block list'); if (tools !== null) bad('duplicate tools'); tools = []; inTools = true; continue; }
|
|
40
|
+
if (Object.hasOwn(fields, field[1])) bad(`duplicate ${field[1]}`);
|
|
41
|
+
fields[field[1]] = unquote(field[2]);
|
|
42
|
+
}
|
|
43
|
+
for (const key of ['name', 'description', 'model', 'effort']) if (typeof fields[key] !== 'string' || fields[key] === '') bad(`missing ${key}`);
|
|
44
|
+
if (tools !== null && tools.length === 0) bad('empty tools');
|
|
45
|
+
const instructions = lines.slice(end + 1).join('\n');
|
|
46
|
+
if (instructions.trim() === '') bad('empty instructions');
|
|
47
|
+
return {name: fields.name, description: fields.description, model: fields.model, effort: fields.effort, tools, instructions};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const ESCAPES = {b: '\b', t: '\t', n: '\n', f: '\f', r: '\r', '"': '"', '\\': '\\'};
|
|
51
|
+
// Decodes a TOML multiline basic string body; returns null when it is not terminated by """ on the same logical line.
|
|
52
|
+
function readMultiline(lines, index, rest) {
|
|
53
|
+
let out = '', buffer = rest, line = index;
|
|
54
|
+
for (;;) {
|
|
55
|
+
for (let i = 0; i < buffer.length; i++) {
|
|
56
|
+
const ch = buffer[i];
|
|
57
|
+
if (ch === '"' && buffer.startsWith('"""', i)) {
|
|
58
|
+
if (!/^(?:"{0,2})[ \t]*(?:#.*)?$/.test(buffer.slice(i + 3))) bad('unsupported developer_instructions terminator');
|
|
59
|
+
return {value: out + buffer.slice(i + 3).match(/^"*/)[0], next: line + 1};
|
|
60
|
+
}
|
|
61
|
+
if (ch !== '\\') { out += ch; continue; }
|
|
62
|
+
const next = buffer[i + 1];
|
|
63
|
+
if (next === undefined) { // line-ending backslash trims following whitespace and newlines
|
|
64
|
+
let j = line + 1; while (j < lines.length && /^[ \t]*$/.test(lines[j])) j++;
|
|
65
|
+
if (j >= lines.length) bad('unterminated developer_instructions');
|
|
66
|
+
out += ''; buffer = lines[j].replace(/^[ \t]+/, ''); line = j; i = -1; continue;
|
|
67
|
+
}
|
|
68
|
+
if (Object.hasOwn(ESCAPES, next)) { out += ESCAPES[next]; i++; continue; }
|
|
69
|
+
const width = next === 'u' ? 4 : next === 'U' ? 8 : 0, hex = buffer.slice(i + 2, i + 2 + width);
|
|
70
|
+
if (!width || !new RegExp(`^[0-9A-Fa-f]{${width}}$`).test(hex)) bad('invalid escape in developer_instructions');
|
|
71
|
+
try { out += String.fromCodePoint(parseInt(hex, 16)); } catch { bad('invalid code point in developer_instructions'); }
|
|
72
|
+
i += 1 + width;
|
|
73
|
+
}
|
|
74
|
+
line++;
|
|
75
|
+
if (line >= lines.length) bad('unterminated developer_instructions');
|
|
76
|
+
out += '\n'; buffer = lines[line];
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
function parseCodex(text) {
|
|
80
|
+
const lines = text.split('\n').map(line => line.replace(/\r$/, '')), fields = {};
|
|
81
|
+
let instructions = null;
|
|
82
|
+
for (let i = 0; i < lines.length; i++) {
|
|
83
|
+
const line = lines[i];
|
|
84
|
+
if (/^[ \t]*\[/.test(line)) break;
|
|
85
|
+
const multi = /^developer_instructions[ \t]*=[ \t]*"""(.*)$/.exec(line);
|
|
86
|
+
if (multi) {
|
|
87
|
+
if (instructions !== null) bad('duplicate developer_instructions');
|
|
88
|
+
const rest = multi[1], result = readMultiline(lines, i, rest === '' ? '' : rest);
|
|
89
|
+
// A newline directly after the opening delimiter is trimmed; readMultiline starts at an empty remainder, so skip that join.
|
|
90
|
+
instructions = rest === '' ? result.value.replace(/^\n/, '') : result.value; i = result.next - 1; continue;
|
|
91
|
+
}
|
|
92
|
+
if (/^developer_instructions[ \t]*=/.test(line)) bad('developer_instructions must be a multiline string');
|
|
93
|
+
const single = /^(name|description|model|model_reasoning_effort)[ \t]*=[ \t]*("(?:[^"\\]|\\.)*")[ \t]*(?:#.*)?$/.exec(line);
|
|
94
|
+
if (single) { if (Object.hasOwn(fields, single[1])) bad(`duplicate ${single[1]}`); fields[single[1]] = unquote(single[2]); continue; }
|
|
95
|
+
if (/^(name|description|model|model_reasoning_effort)[ \t]*=/.test(line)) bad(`${line.split('=')[0].trim()} must be a one-line string`);
|
|
96
|
+
}
|
|
97
|
+
for (const key of ['name', 'description', 'model', 'model_reasoning_effort']) if (typeof fields[key] !== 'string' || fields[key] === '') bad(`missing ${key}`);
|
|
98
|
+
if (instructions === null || instructions.trim() === '') bad('missing developer_instructions');
|
|
99
|
+
return {name: fields.name, description: fields.description, model: fields.model, effort: fields.model_reasoning_effort, tools: null, instructions};
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Narrow extractor: the installed runtime cannot import lib/models, so only the managed profile shapes are accepted. */
|
|
103
|
+
export function parseCompositeProfile(platform, bytes) {
|
|
104
|
+
if (platform !== 'claude' && platform !== 'codex') bad('unknown platform');
|
|
105
|
+
const buffer = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes ?? '');
|
|
106
|
+
let text;
|
|
107
|
+
try { text = new TextDecoder('utf-8', {fatal: true}).decode(buffer); } catch { bad('not valid UTF-8'); }
|
|
108
|
+
if (text.charCodeAt(0) === 0xfeff) bad('unexpected BOM');
|
|
109
|
+
return platform === 'claude' ? parseClaude(text) : parseCodex(text);
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
const permissionsFor = (platform, role) => {
|
|
113
|
+
if (!ROLES.includes(role)) throw Error(`Unknown role: ${role}`);
|
|
114
|
+
return ROLE_BRIDGE_PERMISSIONS[platform][role];
|
|
115
|
+
};
|
|
116
|
+
const requireText = (value, label) => { if (typeof value !== 'string' || value === '') throw Error(`Missing ${label}`); return value; };
|
|
117
|
+
|
|
118
|
+
export function buildClaudeArgs({role, profile, sessionId = null, policy = DEFAULT_POLICY}) {
|
|
119
|
+
const permissions = permissionsFor('claude', role);
|
|
120
|
+
if (!Array.isArray(profile?.tools) || profile.tools.length === 0) throw Error('Claude profile tools are required');
|
|
121
|
+
const args = ['-p', '--safe-mode', '--output-format', 'stream-json', '--verbose', '--model', requireText(profile.model, 'model'), '--effort', requireText(profile.effort, 'effort'),
|
|
122
|
+
'--append-system-prompt', requireText(profile.instructions, 'instructions'), '--tools', profile.tools.join(','), '--permission-mode', permissions.permissionMode];
|
|
123
|
+
if (permissions.sandbox) {
|
|
124
|
+
const settings = effectiveClaudeSandboxSettings(policy);
|
|
125
|
+
if (settings === null) throw Error('Claude sandbox settings are not available for this role');
|
|
126
|
+
args.push('--settings', JSON.stringify(settings));
|
|
127
|
+
}
|
|
128
|
+
if (policy?.gates?.G6 === 'strict') args.push('--strict-mcp-config');
|
|
129
|
+
if (sessionId !== null) args.push('--resume', requireText(sessionId, 'sessionId'));
|
|
130
|
+
return args;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function buildCodexArgs({role, profile, worktree, resultPath, threadId = null, policy = DEFAULT_POLICY}) {
|
|
134
|
+
void policy;
|
|
135
|
+
const permissions = permissionsFor('codex', role);
|
|
136
|
+
if (typeof resultPath !== 'string' || !path.isAbsolute(resultPath)) throw Error('Absolute resultPath required');
|
|
137
|
+
const settings = ['-m', requireText(profile?.model, 'model'), '-c', `model_reasoning_effort=${JSON.stringify(requireText(profile.effort, 'effort'))}`,
|
|
138
|
+
'-c', `developer_instructions=${JSON.stringify(requireText(profile.instructions, 'instructions'))}`, '-c', `sandbox_mode=${JSON.stringify(permissions.sandboxMode)}`,
|
|
139
|
+
'-c', 'approval_policy="never"', '-o', resultPath, '-'];
|
|
140
|
+
if (threadId !== null) {
|
|
141
|
+
if (typeof threadId !== 'string' || !/^[A-Za-z0-9._-]+$/.test(threadId)) throw Error('Invalid threadId');
|
|
142
|
+
return [...(permissions.search ? ['--search'] : []), 'exec', 'resume', threadId, '--json', ...settings];
|
|
143
|
+
}
|
|
144
|
+
if (typeof worktree !== 'string' || !path.isAbsolute(worktree)) throw Error('Absolute worktree required');
|
|
145
|
+
return [...(permissions.search ? ['--search'] : []), 'exec', '--json', '-C', worktree, ...settings];
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export const argsDigest = args => 'sha256:' + crypto.createHash('sha256').update(JSON.stringify(args)).digest('hex');
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
// A caller's JSON, local hook or child process ID cannot authorize execution.
|
|
2
|
+
// run-dispatch only asks the supervisor (the sole child spawner) to start; observe reads and records state under the routing lock.
|
|
3
|
+
import fsp from 'node:fs/promises';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import {DEFAULT_POLICY, reason, profileName, bridgeGateReasons, environmentReasons} from './role-dispatch-policy.mjs';
|
|
6
|
+
import {readLease, writeLease, listLeases, readHostLimits, NON_TERMINAL_STATES, readHeartbeat, requestCancel, clearCancel, TERMINAL_STATES} from './role-dispatch-store.mjs';
|
|
7
|
+
import {withRoutingLock, readActivation, readRevision, authenticate, versionOf} from './role-routing.mjs';
|
|
8
|
+
import {resolveConfigHome} from './local-cli.mjs';
|
|
9
|
+
import {startSupervisor, processAlive, resolveWorktree, artifactDirectory, segmentDirectory, buildBridgeInvocation} from './role-supervisor.mjs';
|
|
10
|
+
|
|
11
|
+
export const heldRoutingResult=(code,releaseCondition)=>({decision:'hold',routeStatus:'held',supportStatus:'unverified',route:null,executionEnvironment:null,hostPlatform:null,role:null,requested:null,authentication:null,reasons:[{code,releaseCondition}]});
|
|
12
|
+
|
|
13
|
+
const ID=/^[A-Za-z0-9._-]{1,128}$/;
|
|
14
|
+
const NATIVE_EVENTS={started:[['reserved'],'running'],completed:[['running'],'completed'],failed:[['running'],'failed'],cancelled:[['running','reserved'],'cancelled']};
|
|
15
|
+
const sleep=ms=>new Promise(resolve=>setTimeout(resolve,ms));
|
|
16
|
+
const hostOf=context=>['codex','claude'].includes(context?.hostPlatform)?context.hostPlatform:null;
|
|
17
|
+
const environmentOf=(context,host)=>['codex-cli','claude-cli','codex-desktop','claude-desktop'].includes(context?.executionEnvironment)&&host&&context.executionEnvironment.startsWith(`${host}-`)?context.executionEnvironment:null;
|
|
18
|
+
const validContext=context=>{const host=hostOf(context);return Boolean(host&&environmentOf(context,host)&&typeof context.workflowId==='string'&&context.workflowId&&typeof context.cwd==='string');};
|
|
19
|
+
const blank=(context,dispatchId,decision,code)=>({decision,routeStatus:'held',supportStatus:'unverified',dispatchId:typeof dispatchId==='string'&&ID.test(dispatchId)?dispatchId:null,route:null,profileName:null,executionEnvironment:context?.executionEnvironment??null,hostPlatform:context?.hostPlatform??null,role:null,requested:null,authentication:null,cliVersion:null,claims:null,reasons:[reason(code)]});
|
|
20
|
+
const bridgeTarget=lease=>lease.route==='native'?lease.hostPlatform:lease.hostPlatform==='codex'?'claude':'codex';
|
|
21
|
+
const supportOf=lease=>lease.route==='bridge'&&!String(lease.executionEnvironment).endsWith('-desktop')&&lease.state==='completed'&&lease.reasons.length===0&&['identity','model','effort','permissions','terminal'].every(key=>lease.claims?.[key]?.level==='runtime-observed')?'verified':'unverified';
|
|
22
|
+
/** Result view of a lease. failed and unknown hold dependent work; every other observed state is reported as allow. */
|
|
23
|
+
function fromLease(lease,decision=['failed','unknown'].includes(lease.state)?'hold':'allow'){
|
|
24
|
+
const platform=bridgeTarget(lease);
|
|
25
|
+
return {decision,routeStatus:lease.state,supportStatus:supportOf(lease),dispatchId:lease.dispatchId,route:lease.route,profileName:profileName(platform,lease.role),executionEnvironment:lease.executionEnvironment,hostPlatform:lease.hostPlatform,role:lease.role,requested:{platform,model:lease.claims?.model?.requested??null,effort:lease.claims?.effort?.requested??null},authentication:null,cliVersion:null,claims:lease.claims,reasons:lease.reasons,resultPath:lease.resultPath};
|
|
26
|
+
}
|
|
27
|
+
const homesOf=context=>({codex:resolveConfigHome('codex',context),claude:resolveConfigHome('claude',context)});
|
|
28
|
+
const residualOf=error=>Array.isArray(error?.residualPaths)?error.residualPaths:undefined;
|
|
29
|
+
const hold=(context,dispatchId,code,error)=>{const result=blank(context,dispatchId,'hold',code);const residual=residualOf(error);if(residual)result.residualPaths=residual;return result;};
|
|
30
|
+
const classifyLock=error=>{const code=error?.code==='ARC_ROUTING_LOCK_RELEASE'&&error.failure?error.failure.code:error?.code;return code==='ARC_HOST_SANDBOX'?'host_sandbox_blocked':'activation_unverified';};
|
|
31
|
+
|
|
32
|
+
/** Starts the detached supervisor for a reserved bridge lease; the supervisor, not this function, spawns the child. */
|
|
33
|
+
export async function runBridgeDispatch({context,dispatchId,brief,now=Date.now(),policy=DEFAULT_POLICY,startSupervisor:starter=startSupervisor}={}){
|
|
34
|
+
if(!validContext(context)||typeof dispatchId!=='string'||!ID.test(dispatchId)||dispatchId.startsWith('.')||typeof brief!=='string'){return blank(context,dispatchId,'deny','invalid_request');}
|
|
35
|
+
const bytes=Buffer.byteLength(brief,'utf8');
|
|
36
|
+
if(bytes<1||bytes>policy.briefMaxBytes)return blank(context,dispatchId,'deny','invalid_request');
|
|
37
|
+
let homes,result,residual;
|
|
38
|
+
try{homes=homesOf(context);}catch{return blank(context,dispatchId,'hold','activation_unverified');}
|
|
39
|
+
try{
|
|
40
|
+
await withRoutingLock(homes.codex,async()=>{
|
|
41
|
+
const lease=await readLease(homes.codex,dispatchId);
|
|
42
|
+
if(!lease||lease.workflowId!==context.workflowId||lease.hostPlatform!==context.hostPlatform||lease.route!=='bridge'||lease.state!=='reserved'){result=blank(context,dispatchId,'deny','invalid_request');return;}
|
|
43
|
+
let config;try{config=await readActivation(homes,lease.revision);}catch{result=blank(context,dispatchId,'hold','activation_unverified');return;}
|
|
44
|
+
let target;try{target=await resolveWorktree(context.cwd);}catch{result=blank(context,dispatchId,'hold','activation_unverified');return;}
|
|
45
|
+
const directory=artifactDirectory(target,lease.workflowId,dispatchId),resultPath=path.join(directory,'result.md');
|
|
46
|
+
let invocation;try{invocation=await buildBridgeInvocation({lease,config,homes,worktree:target.realpath,resultPath,policy});}catch(error){result=blank(context,dispatchId,'hold',error.reasonCode??'activation_unverified');return;}
|
|
47
|
+
await fsp.mkdir(directory,{recursive:true,mode:0o700});await fsp.chmod(directory,0o700);
|
|
48
|
+
await fsp.writeFile(path.join(directory,'brief.md'),brief,{mode:0o600,flag:'w'});await fsp.chmod(path.join(directory,'brief.md'),0o600);
|
|
49
|
+
let supervisor;
|
|
50
|
+
try{supervisor=await starter({codexHome:homes.codex,dispatchId,cwd:target.realpath,userHome:context.userHome,env:context.env??process.env});}
|
|
51
|
+
catch{result=blank(context,dispatchId,'hold','host_sandbox_blocked');return;}
|
|
52
|
+
const next=await writeLease(homes.codex,{...lease,state:'starting',supervisor,argsDigest:invocation.argsDigest,resultPath},{now});
|
|
53
|
+
result=fromLease(next,'allow');
|
|
54
|
+
},{retryMs:policy.lockRetryMs});
|
|
55
|
+
}catch(error){
|
|
56
|
+
if(error?.code==='ARC_ROUTING_LOCK_RELEASE'&&!error.failure&&result){residual=residualOf(error);}
|
|
57
|
+
else return hold(context,dispatchId,classifyLock(error),error);
|
|
58
|
+
}
|
|
59
|
+
if(residual)result.residualPaths=residual;
|
|
60
|
+
return result;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const TEXT=/^[^\p{Cc}]{1,256}$/u;
|
|
64
|
+
async function markLostIfDue(homes,lease,{now,lostMs,policy}){
|
|
65
|
+
if(!['starting','running'].includes(lease.state)||!lease.supervisor)return lease;
|
|
66
|
+
const heartbeat=await readHeartbeat(homes.codex,lease.dispatchId);
|
|
67
|
+
const lastSeen=Math.max(heartbeat?.at??0,Date.parse(lease.updatedAt)||0);
|
|
68
|
+
if(now-lastSeen<=lostMs||processAlive(lease.supervisor))return lease;
|
|
69
|
+
try{
|
|
70
|
+
return await withRoutingLock(homes.codex,async()=>{
|
|
71
|
+
const current=await readLease(homes.codex,lease.dispatchId);
|
|
72
|
+
if(!current||!['starting','running'].includes(current.state))return current??lease;
|
|
73
|
+
return writeLease(homes.codex,{...current,state:'unknown',claims:{...(current.claims??{}),terminal:{level:'unverified',source:'none'}},reasons:[reason('terminal_state_unverified')]},{now});
|
|
74
|
+
},{retryMs:policy.lockRetryMs});
|
|
75
|
+
}catch{return lease;}// a busy lock only delays the transition; the next observe retries it
|
|
76
|
+
}
|
|
77
|
+
async function recordNativeEvent({context,homes,dispatchId,event,nativeAgentId,now,policy}){
|
|
78
|
+
let result;
|
|
79
|
+
try{
|
|
80
|
+
await withRoutingLock(homes.codex,async()=>{
|
|
81
|
+
const lease=await readLease(homes.codex,dispatchId);
|
|
82
|
+
const rule=NATIVE_EVENTS[event];
|
|
83
|
+
if(!lease||lease.route!=='native'||lease.workflowId!==context.workflowId||!rule[0].includes(lease.state)||(event==='started')!==(nativeAgentId!==undefined)){result=blank(context,dispatchId,'deny','invalid_request');return;}
|
|
84
|
+
const attested={level:'operator-attested',source:'orchestrator'};
|
|
85
|
+
const claims={...lease.claims,...(event==='started'?{identity:{...attested,observed:nativeAgentId}}:{terminal:{...attested,observed:event}})};
|
|
86
|
+
const next=await writeLease(homes.codex,{...lease,state:rule[1],claims,nativeAgentId:nativeAgentId??lease.nativeAgentId,reasons:event==='failed'?[reason('execution_failed')]:[]},{now});
|
|
87
|
+
result=fromLease(next);
|
|
88
|
+
},{retryMs:policy.lockRetryMs});
|
|
89
|
+
}catch(error){return hold(context,dispatchId,classifyLock(error),error);}
|
|
90
|
+
return result;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** bridge: waits up to waitMs for a terminal or unknown state and marks a lost supervisor unknown. native: records operator events. */
|
|
94
|
+
export async function recordRoleObservation({context,dispatchId,waitMs,event,nativeAgentId,now,lostMs,pollMs=500,policy=DEFAULT_POLICY}={}){
|
|
95
|
+
if(!validContext(context)||typeof dispatchId!=='string'||!ID.test(dispatchId)||dispatchId.startsWith('.'))return blank(context,dispatchId,'deny','invalid_request');
|
|
96
|
+
if(waitMs!==undefined&&(!Number.isInteger(waitMs)||waitMs<0||waitMs>policy.observeMaxWaitMs))return blank(context,dispatchId,'deny','invalid_request');
|
|
97
|
+
if(event!==undefined&&!Object.hasOwn(NATIVE_EVENTS,event))return blank(context,dispatchId,'deny','invalid_request');
|
|
98
|
+
if(nativeAgentId!==undefined&&(typeof nativeAgentId!=='string'||!TEXT.test(nativeAgentId)))return blank(context,dispatchId,'deny','invalid_request');
|
|
99
|
+
let homes,lease;
|
|
100
|
+
try{homes=homesOf(context);lease=await readLease(homes.codex,dispatchId);}catch{return blank(context,dispatchId,'hold','activation_unverified');}
|
|
101
|
+
if(!lease||lease.workflowId!==context.workflowId||lease.hostPlatform!==context.hostPlatform)return blank(context,dispatchId,'deny','invalid_request');
|
|
102
|
+
if(lease.route==='native'){
|
|
103
|
+
if(waitMs!==undefined||event===undefined)return blank(context,dispatchId,'deny','invalid_request');
|
|
104
|
+
return recordNativeEvent({context,homes,dispatchId,event,nativeAgentId,now:now??Date.now(),policy});
|
|
105
|
+
}
|
|
106
|
+
if(event!==undefined||nativeAgentId!==undefined)return blank(context,dispatchId,'deny','invalid_request');
|
|
107
|
+
const end=Date.now()+(waitMs??0),lost=lostMs??policy.supervisorLostMs;
|
|
108
|
+
try{
|
|
109
|
+
for(;;){
|
|
110
|
+
lease=await markLostIfDue(homes,lease,{now:now??Date.now(),lostMs:lost,policy});
|
|
111
|
+
if(TERMINAL_STATES.includes(lease.state)||lease.state==='unknown'||Date.now()>=end)return fromLease(lease);
|
|
112
|
+
await sleep(Math.min(pollMs,Math.max(0,end-Date.now())));
|
|
113
|
+
lease=await readLease(homes.codex,dispatchId)??lease;
|
|
114
|
+
}
|
|
115
|
+
}catch{return blank(context,dispatchId,'hold','activation_unverified');}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Continues a completed or failed bridge dispatch in its recorded session. The input carries no session id; only the lease value is used. */
|
|
119
|
+
export async function resumeRoleDispatch({context,dispatchId,brief,now=Date.now(),policy=DEFAULT_POLICY,startSupervisor:starter=startSupervisor}={}){
|
|
120
|
+
if(!validContext(context)||typeof dispatchId!=='string'||!ID.test(dispatchId)||dispatchId.startsWith('.')||typeof brief!=='string'){return blank(context,dispatchId,'deny','invalid_request');}
|
|
121
|
+
const bytes=Buffer.byteLength(brief,'utf8');
|
|
122
|
+
if(bytes<1||bytes>policy.briefMaxBytes)return blank(context,dispatchId,'deny','invalid_request');
|
|
123
|
+
let homes,result,residual;
|
|
124
|
+
try{homes=homesOf(context);}catch{return blank(context,dispatchId,'hold','activation_unverified');}
|
|
125
|
+
try{
|
|
126
|
+
await withRoutingLock(homes.codex,async()=>{
|
|
127
|
+
const lease=await readLease(homes.codex,dispatchId);
|
|
128
|
+
if(!lease||lease.workflowId!==context.workflowId||lease.hostPlatform!==context.hostPlatform||lease.route!=='bridge'||!['completed','failed'].includes(lease.state)){result=blank(context,dispatchId,'deny','invalid_request');return;}
|
|
129
|
+
if(!lease.sessionId){result=blank(context,dispatchId,'hold','execution_identity_unverified');return;}
|
|
130
|
+
let config;
|
|
131
|
+
try{config=await readActivation(homes,lease.revision);}
|
|
132
|
+
catch{
|
|
133
|
+
let active=null;try{active=await readRevision(homes);}catch{/* unreadable activation stays unverified */}
|
|
134
|
+
result=blank(context,dispatchId,'hold',active!==null&&active!==lease.revision?'revision_changed':'activation_unverified');return;
|
|
135
|
+
}
|
|
136
|
+
const requested=config.roles[lease.role],platform=requested.platform,codes=new Set();
|
|
137
|
+
const {cli,authentication}=await authenticate(platform,context,policy);
|
|
138
|
+
if(authentication.status!=='Available')codes.add(authentication.status);
|
|
139
|
+
const version=await versionOf(cli,policy);
|
|
140
|
+
if(cli&&!version.supported)codes.add('permission_scope_unverified');
|
|
141
|
+
for(const code of environmentReasons(context.executionEnvironment,policy))codes.add(code);
|
|
142
|
+
for(const code of bridgeGateReasons({platform,role:lease.role,hostPlatform:context.hostPlatform,policy}))codes.add(code);
|
|
143
|
+
// The dispatch itself is terminal here, so only other non-terminal bridge leases occupy slots. The workflow total is not increased by a follow-up segment.
|
|
144
|
+
let limits;try{limits=readHostLimits(homes[context.hostPlatform]);}catch{codes.add('activation_unverified');}
|
|
145
|
+
if(limits&&(await listLeases(homes.codex)).filter(item=>item.route==='bridge'&&NON_TERMINAL_STATES.includes(item.state)).length+1>limits.maxConcurrent)codes.add('capacity_exhausted');
|
|
146
|
+
if(codes.size){result=blank(context,dispatchId,'hold','activation_unverified');result.reasons=[...codes].map(reason);return;}
|
|
147
|
+
let target;try{target=await resolveWorktree(context.cwd);}catch{result=blank(context,dispatchId,'hold','activation_unverified');return;}
|
|
148
|
+
const segment=lease.segment+1,directory=segmentDirectory(target,lease.workflowId,dispatchId,segment),resultPath=path.join(directory,'result.md');
|
|
149
|
+
let invocation;try{invocation=await buildBridgeInvocation({lease:{...lease,segment},config,homes,worktree:target.realpath,resultPath,policy});}catch(error){result=blank(context,dispatchId,'hold',error.reasonCode??'activation_unverified');return;}
|
|
150
|
+
await fsp.mkdir(directory,{recursive:true,mode:0o700});await fsp.chmod(path.dirname(directory),0o700);await fsp.chmod(directory,0o700);
|
|
151
|
+
await fsp.writeFile(path.join(directory,'brief.md'),brief,{mode:0o600,flag:'w'});await fsp.chmod(path.join(directory,'brief.md'),0o600);
|
|
152
|
+
await clearCancel(homes.codex,dispatchId);
|
|
153
|
+
let supervisor;
|
|
154
|
+
try{supervisor=await starter({codexHome:homes.codex,dispatchId,cwd:target.realpath,userHome:context.userHome,env:context.env??process.env});}
|
|
155
|
+
catch{result=blank(context,dispatchId,'hold','host_sandbox_blocked');return;}
|
|
156
|
+
const claims=lease.claims?{...lease.claims,terminal:{level:'unverified',source:'none'}}:null;
|
|
157
|
+
const next=await writeLease(homes.codex,{...lease,state:'starting',supervisor,child:null,argsDigest:invocation.argsDigest,resultPath,segment,claims,reasons:[]},{now});
|
|
158
|
+
result={...fromLease(next,'allow'),segment};
|
|
159
|
+
},{retryMs:policy.lockRetryMs});
|
|
160
|
+
}catch(error){
|
|
161
|
+
if(error?.code==='ARC_ROUTING_LOCK_RELEASE'&&!error.failure&&result){residual=residualOf(error);}
|
|
162
|
+
else return hold(context,dispatchId,classifyLock(error),error);
|
|
163
|
+
}
|
|
164
|
+
if(residual)result.residualPaths=residual;
|
|
165
|
+
return result;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const groupExists=pid=>{try{process.kill(-pid,0);return true;}catch(error){return error.code!=='ESRCH';}};
|
|
169
|
+
const pidExists=pid=>{try{process.kill(pid,0);return true;}catch(error){return error.code!=='ESRCH';}};
|
|
170
|
+
const signalGroup=(pid,signal)=>{try{process.kill(-pid,signal);}catch{/* group already gone */}};
|
|
171
|
+
/** Reserved leases have no child and are cleaned up at once. A live supervisor receives a cancel marker and records cancelled itself after observing the exit. An unknown lease (or one whose supervisor is gone) is stopped here only for a process identified by pid and start time, and cancelled only after the group is observed gone. */
|
|
172
|
+
export async function cancelRoleDispatch({context,dispatchId,now=Date.now(),policy=DEFAULT_POLICY}={}){
|
|
173
|
+
if(!validContext(context)||typeof dispatchId!=='string'||!ID.test(dispatchId)||dispatchId.startsWith('.'))return blank(context,dispatchId,'deny','invalid_request');
|
|
174
|
+
let homes,result,direct=null,residual;
|
|
175
|
+
try{homes=homesOf(context);}catch{return blank(context,dispatchId,'hold','activation_unverified');}
|
|
176
|
+
const graceMs=policy.cancelGraceMs;
|
|
177
|
+
try{
|
|
178
|
+
await withRoutingLock(homes.codex,async()=>{
|
|
179
|
+
const lease=await readLease(homes.codex,dispatchId);
|
|
180
|
+
if(!lease||lease.workflowId!==context.workflowId||lease.hostPlatform!==context.hostPlatform){result=blank(context,dispatchId,'deny','invalid_request');return;}
|
|
181
|
+
if(lease.route==='native'){
|
|
182
|
+
// A native lease has no child: only a reserved one is cancelled here (under the lock); started native dispatches are closed with observe events.
|
|
183
|
+
if(lease.state!=='reserved'){result=blank(context,dispatchId,'deny','invalid_request');return;}
|
|
184
|
+
const claims={...lease.claims,terminal:{level:'operator-attested',source:'orchestrator',observed:'cancelled'}};
|
|
185
|
+
result=fromLease(await writeLease(homes.codex,{...lease,state:'cancelled',claims,reasons:[]},{now}),'allow');return;
|
|
186
|
+
}
|
|
187
|
+
if(TERMINAL_STATES.includes(lease.state)){result=fromLease(lease,'allow');return;}
|
|
188
|
+
if(lease.state==='reserved'){result=fromLease(await writeLease(homes.codex,{...lease,state:'cancelled',reasons:[]},{now}),'allow');return;}
|
|
189
|
+
const supervised=['starting','running'].includes(lease.state)&&lease.supervisor&&processAlive(lease.supervisor);
|
|
190
|
+
if(supervised){
|
|
191
|
+
await requestCancel(homes.codex,dispatchId);
|
|
192
|
+
if(lease.child&&processAlive(lease.child))signalGroup(lease.child.pid,'SIGTERM');
|
|
193
|
+
result={...fromLease(lease,'allow'),routeStatus:'cancelling'};return;
|
|
194
|
+
}
|
|
195
|
+
if(lease.child&&processAlive(lease.child)){signalGroup(lease.child.pid,'SIGTERM');direct={lease,identified:true};}
|
|
196
|
+
else if(lease.child&&!groupExists(lease.child.pid)&&!pidExists(lease.child.pid))direct={lease,identified:false};
|
|
197
|
+
else result=fromLease(lease,'hold');
|
|
198
|
+
},{retryMs:policy.lockRetryMs});
|
|
199
|
+
}catch(error){
|
|
200
|
+
if(error?.code==='ARC_ROUTING_LOCK_RELEASE'&&!error.failure&&(result||direct)){residual=residualOf(error);}
|
|
201
|
+
else return hold(context,dispatchId,classifyLock(error),error);
|
|
202
|
+
}
|
|
203
|
+
if(direct){
|
|
204
|
+
const pid=direct.lease.child.pid,begin=Date.now();let killed=false,gone=!groupExists(pid);
|
|
205
|
+
while(!gone&&Date.now()<begin+2*graceMs){
|
|
206
|
+
if(!killed&&Date.now()>=begin+graceMs){signalGroup(pid,'SIGKILL');killed=true;}
|
|
207
|
+
await sleep(25);gone=!groupExists(pid);
|
|
208
|
+
}
|
|
209
|
+
if(!gone)result=fromLease(direct.lease,'hold');
|
|
210
|
+
else{
|
|
211
|
+
try{
|
|
212
|
+
await withRoutingLock(homes.codex,async()=>{
|
|
213
|
+
const current=await readLease(homes.codex,dispatchId);
|
|
214
|
+
if(!current||TERMINAL_STATES.includes(current.state)||current.child?.pid!==pid){result=current?fromLease(current,'allow'):blank(context,dispatchId,'deny','invalid_request');return;}
|
|
215
|
+
const claims={...(current.claims??{}),terminal:{level:'runtime-observed',source:'cancel-group-gone',observed:{pid}}};
|
|
216
|
+
// The recorded reasons (for example terminal_state_unverified) stay on the cancelled lease.
|
|
217
|
+
result=fromLease(await writeLease(homes.codex,{...current,state:'cancelled',claims},{now:Date.now()}),'allow');
|
|
218
|
+
},{retryMs:policy.lockRetryMs});
|
|
219
|
+
}catch(error){
|
|
220
|
+
if(error?.code==='ARC_ROUTING_LOCK_RELEASE'&&!error.failure&&result){residual=residualOf(error);}
|
|
221
|
+
else return hold(context,dispatchId,classifyLock(error),error);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
if(residual)result.residualPaths=residual;
|
|
226
|
+
return result;
|
|
227
|
+
}
|