@yunhozz/arc 0.3.5 → 0.4.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 +133 -94
- package/README.md +56 -21
- package/claude/skill/SKILL.md +1 -1
- package/claude/skill/references/commit.md +10 -8
- package/claude/skill/references/coordination.md +6 -4
- package/claude/skill/references/handoff-prep.md +12 -12
- package/claude/skill/references/handoff.md +2 -0
- package/claude/skill/references/planning.md +8 -8
- package/claude/skill/references/verification.md +6 -6
- package/codex/skill/SKILL.md +1 -1
- package/codex/skill/references/commit.md +10 -8
- package/codex/skill/references/coordination.md +6 -4
- package/codex/skill/references/handoff-prep.md +12 -12
- package/codex/skill/references/handoff.md +2 -0
- package/codex/skill/references/planning.md +8 -8
- package/codex/skill/references/verification.md +6 -6
- package/gemini/GEMINI.md +8 -0
- package/gemini/agents/arc-implementer.md +37 -0
- package/gemini/agents/arc-planner.md +47 -0
- package/gemini/agents/arc-qa.md +37 -0
- package/gemini/agents/arc-reviewer.md +39 -0
- package/gemini/agents/arc-scouter.md +38 -0
- package/gemini/instructions.md +4 -0
- package/gemini/skill/SKILL.md +78 -0
- package/gemini/skill/models.toml +23 -0
- package/gemini/skill/references/arc-visual-companion.md +28 -0
- package/gemini/skill/references/commit.md +55 -0
- package/gemini/skill/references/coordination.md +149 -0
- package/gemini/skill/references/git-recovery.md +34 -0
- package/gemini/skill/references/handoff-prep.md +110 -0
- package/gemini/skill/references/handoff.md +227 -0
- package/gemini/skill/references/limits.md +31 -0
- package/gemini/skill/references/planning.md +168 -0
- package/gemini/skill/references/verification.md +155 -0
- package/gemini/skill/references/worktree-creation.md +8 -0
- package/lib/color/palette.mjs +6 -0
- package/lib/installer/acquisition.mjs +7 -5
- package/lib/installer/install-mode.mjs +49 -26
- package/lib/installer/install.mjs +3 -2
- package/lib/installer/manifest.mjs +20 -14
- package/lib/installer/plan.mjs +24 -21
- package/lib/installer/preset.mjs +9 -8
- package/lib/installer/role-routing.mjs +129 -77
- package/lib/installer/runtime-assets.mjs +2 -0
- package/lib/installer/runtime-config.mjs +3 -0
- package/lib/installer/skill-sources.mjs +4 -3
- package/lib/installer/superpowers.mjs +2 -1
- package/lib/installer/target-errors.mjs +1 -0
- package/lib/installer/targets.mjs +14 -6
- package/lib/installer/uninstall.mjs +5 -4
- package/lib/installer/upgrade-state.mjs +14 -10
- package/lib/installer/upgrade.mjs +9 -5
- package/lib/management/operations.mjs +91 -47
- package/lib/management/status.mjs +10 -8
- package/lib/management/update.mjs +8 -7
- package/lib/models/catalog-gemini.mjs +48 -0
- package/lib/models/catalog.mjs +27 -12
- package/lib/models/config.mjs +23 -22
- package/lib/models/gemini-models.json +12 -0
- package/lib/models/profiles.mjs +7 -5
- package/lib/models/static-catalog.mjs +13 -14
- package/lib/npm/upgrade.mjs +2 -2
- package/lib/platforms/availability.mjs +98 -0
- package/lib/platforms/claude.mjs +14 -0
- package/lib/platforms/codex.mjs +16 -0
- package/lib/platforms/formats/gemini-markdown.mjs +48 -0
- package/lib/platforms/formats/markdown.mjs +39 -0
- package/lib/platforms/formats/toml.mjs +39 -0
- package/lib/platforms/gemini.mjs +14 -0
- package/lib/platforms/index.mjs +27 -0
- package/lib/policy/placement.mjs +4 -4
- package/lib/policy/render.mjs +13 -8
- package/lib/policy/role-policy.json +40 -21
- package/lib/prompts/agent-fragments.json +71 -1
- package/lib/prompts/render.mjs +32 -11
- package/lib/runtime/bootstrap.mjs +1 -1
- package/lib/runtime/cooperative-schema.mjs +0 -23
- package/lib/runtime/cooperative.mjs +13 -34
- package/lib/runtime/evaluate.mjs +3 -69
- package/lib/runtime/gemini-stream.mjs +32 -0
- package/lib/runtime/git-evidence.mjs +0 -98
- package/lib/runtime/identity.mjs +2 -1
- package/lib/runtime/local-cli.mjs +14 -24
- package/lib/runtime/operations.mjs +2 -2
- package/lib/runtime/platform-registry.mjs +130 -0
- package/lib/runtime/role-bridge-args.mjs +57 -2
- package/lib/runtime/role-bridge.mjs +86 -65
- package/lib/runtime/role-dispatch-policy.mjs +17 -7
- package/lib/runtime/role-dispatch-store.mjs +20 -14
- package/lib/runtime/role-observe.mjs +1 -0
- package/lib/runtime/role-routing-config.mjs +36 -9
- package/lib/runtime/role-routing.mjs +62 -29
- package/lib/runtime/role-supervisor.mjs +114 -49
- package/lib/runtime/schema.mjs +5 -4
- package/lib/tui/app.mjs +37 -32
- package/lib/tui/custom-preset.mjs +114 -68
- package/lib/tui/derive-install-plan.mjs +19 -0
- package/lib/tui/diagram.mjs +68 -0
- package/lib/tui/mode.mjs +77 -0
- package/lib/tui/render.mjs +47 -16
- package/lib/tui/setup.mjs +167 -100
- package/lib/tui/terminal.mjs +9 -6
- package/lib/watch/anchor-store.mjs +44 -0
- package/lib/watch/dispatch.mjs +3 -3
- package/lib/watch/index.mjs +37 -24
- package/lib/watch/model.mjs +1 -0
- package/lib/watch/normalize-claude.mjs +50 -10
- package/lib/watch/normalize-codex.mjs +79 -5
- package/lib/watch/render.mjs +30 -13
- package/lib/watch/scope.mjs +2 -1
- package/lib/watch/status-line.mjs +51 -0
- package/lib/watch/tail.mjs +27 -0
- package/lib/watch/watcher.mjs +193 -53
- package/package.json +2 -1
- package/scripts/update-manifest.mjs +2 -2
- package/shared/skill/runtime/bootstrap.mjs +1 -1
- package/shared/skill/runtime/cooperative-schema.mjs +0 -23
- package/shared/skill/runtime/cooperative.mjs +13 -34
- package/shared/skill/runtime/evaluate.mjs +3 -69
- package/shared/skill/runtime/gemini-stream.mjs +32 -0
- package/shared/skill/runtime/git-evidence.mjs +0 -98
- package/shared/skill/runtime/identity.mjs +2 -1
- package/shared/skill/runtime/local-cli.mjs +14 -24
- package/shared/skill/runtime/operations.mjs +2 -2
- package/shared/skill/runtime/platform-registry.mjs +130 -0
- package/shared/skill/runtime/role-bridge-args.mjs +57 -2
- package/shared/skill/runtime/role-bridge.mjs +86 -65
- package/shared/skill/runtime/role-dispatch-policy.mjs +17 -7
- package/shared/skill/runtime/role-dispatch-store.mjs +20 -14
- package/shared/skill/runtime/role-observe.mjs +1 -0
- package/shared/skill/runtime/role-policy.json +40 -21
- package/shared/skill/runtime/role-routing-config.mjs +36 -9
- package/shared/skill/runtime/role-routing.mjs +62 -29
- package/shared/skill/runtime/role-supervisor.mjs +114 -49
- package/shared/skill/runtime/schema.mjs +5 -4
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
|
|
3
|
+
export const CAPABILITY_KEYS = Object.freeze([
|
|
4
|
+
'install', 'standalone', 'compositeRole', 'compositeHost', 'bridge',
|
|
5
|
+
'nativeProfile', 'authProbe', 'catalog', 'watch',
|
|
6
|
+
]);
|
|
7
|
+
|
|
8
|
+
export const CAPABILITY_PREREQUISITES = Object.freeze({
|
|
9
|
+
install: Object.freeze([]), nativeProfile: Object.freeze(['install']),
|
|
10
|
+
catalog: Object.freeze(['install']), standalone: Object.freeze(['install', 'nativeProfile', 'catalog']),
|
|
11
|
+
bridge: Object.freeze(['install', 'catalog']), compositeRole: Object.freeze(['bridge']),
|
|
12
|
+
compositeHost: Object.freeze(['install', 'nativeProfile']), authProbe: Object.freeze([]), watch: Object.freeze([]),
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
function frozenCopy(value) {
|
|
16
|
+
if (Array.isArray(value)) return Object.freeze(value.map(frozenCopy));
|
|
17
|
+
if (value && typeof value === 'object') return Object.freeze(Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, frozenCopy(entry)])));
|
|
18
|
+
return value;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function createPlatformRegistry(descriptors) {
|
|
22
|
+
const ids = new Set(), anchors = new Set(), displays = new Set();
|
|
23
|
+
const platforms = Object.freeze(descriptors.map(descriptor => {
|
|
24
|
+
const {id, anchorOrder, displayOrder} = descriptor;
|
|
25
|
+
if (ids.has(id)) throw Error(`Duplicate platform id: ${id}`);
|
|
26
|
+
if (anchors.has(anchorOrder)) throw Error(`Duplicate platform anchorOrder: ${anchorOrder}`);
|
|
27
|
+
if (displays.has(displayOrder)) throw Error(`Duplicate platform displayOrder: ${displayOrder}`);
|
|
28
|
+
ids.add(id); anchors.add(anchorOrder); displays.add(displayOrder);
|
|
29
|
+
const capabilities = Object.fromEntries(CAPABILITY_KEYS.map(key => [key, descriptor.capabilities?.[key] ?? {state: 'off'}]));
|
|
30
|
+
for (const [key, prerequisites] of Object.entries(CAPABILITY_PREREQUISITES)) {
|
|
31
|
+
if (capabilities[key].state !== 'verified') continue;
|
|
32
|
+
for (const prerequisite of prerequisites) if (capabilities[prerequisite].state !== 'verified') throw Error(`${id} capability ${key} requires ${prerequisite}`);
|
|
33
|
+
}
|
|
34
|
+
return frozenCopy({...descriptor, capabilities});
|
|
35
|
+
}).sort((a, b) => a.anchorOrder - b.anchorOrder));
|
|
36
|
+
const byId = new Map(platforms.map(platform => [platform.id, platform]));
|
|
37
|
+
const platformIds = Object.freeze(platforms.map(platform => platform.id));
|
|
38
|
+
const displayOrder = Object.freeze([...platforms].sort((a, b) => a.displayOrder - b.displayOrder));
|
|
39
|
+
return Object.freeze({
|
|
40
|
+
platforms,
|
|
41
|
+
platformIds: () => platformIds,
|
|
42
|
+
getPlatform: id => byId.get(id) ?? null,
|
|
43
|
+
byDisplayOrder: () => displayOrder,
|
|
44
|
+
byAnchorOrder: () => platforms,
|
|
45
|
+
isPlatformId: value => byId.has(value),
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function resolveHome(platform, {userHome, env = {}, cwd} = {}) {
|
|
50
|
+
if (typeof userHome !== 'string' || !path.isAbsolute(userHome) || !userHome.trim()) throw Error('userHome must be an absolute user directory');
|
|
51
|
+
userHome = path.resolve(userHome);
|
|
52
|
+
if (!env || typeof env !== 'object') throw Error('env must be an environment object');
|
|
53
|
+
const expand = value => value === '~' ? userHome : value.startsWith('~/') ? path.join(userHome, value.slice(2)) : value;
|
|
54
|
+
let home;
|
|
55
|
+
if (platform === 'codex') {
|
|
56
|
+
const raw = env.CODEX_HOME;
|
|
57
|
+
if (raw !== undefined && (typeof raw !== 'string' || !raw.trim())) throw Error('CODEX_HOME is empty or invalid');
|
|
58
|
+
const expanded = expand(raw ?? path.join(userHome, '.codex'));
|
|
59
|
+
if (path.isAbsolute(expanded)) home = path.resolve(expanded);
|
|
60
|
+
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); }
|
|
61
|
+
} else if (platform === 'gemini') {
|
|
62
|
+
if (env.GEMINI_CLI_HOME !== undefined) throw Error('GEMINI_CLI_HOME is not verified');
|
|
63
|
+
home = path.join(userHome, '.gemini');
|
|
64
|
+
} else {
|
|
65
|
+
home = path.join(userHome, '.claude'); const raw = env.CLAUDE_CONFIG_DIR;
|
|
66
|
+
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');
|
|
67
|
+
}
|
|
68
|
+
if (home === '/' || home === userHome) throw Error('Target home must not be the filesystem or user-home root');
|
|
69
|
+
return home;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const validText = value => typeof value === 'string' && value.length > 0 && value === value.trim() && !/[\p{Cc}\u2028\u2029]/u.test(value);
|
|
73
|
+
const verifiedCapabilities = Object.fromEntries(CAPABILITY_KEYS.map(key => [key, {state: 'verified'}]));
|
|
74
|
+
|
|
75
|
+
export const DEFAULT_PLATFORM_REGISTRY = createPlatformRegistry([
|
|
76
|
+
{
|
|
77
|
+
id: 'codex', label: 'Codex', displayOrder: 1, anchorOrder: 1,
|
|
78
|
+
home: {env: 'CODEX_HOME', resolve: context => resolveHome('codex', context)},
|
|
79
|
+
cli: {command: 'codex', supportedVersions: null},
|
|
80
|
+
auth: {kind: 'codex-refresh'},
|
|
81
|
+
models: {effortField: 'model_reasoning_effort'},
|
|
82
|
+
profile: {
|
|
83
|
+
ext: 'toml',
|
|
84
|
+
standaloneName: role => role,
|
|
85
|
+
routingName: role => `arc_routing_${role.slice(4)}`,
|
|
86
|
+
},
|
|
87
|
+
executionEnvironments: ['codex-cli', 'codex-desktop'],
|
|
88
|
+
routing: {validatePair: (model, effort) => validText(model) && validText(effort)},
|
|
89
|
+
capabilities: verifiedCapabilities,
|
|
90
|
+
},
|
|
91
|
+
{
|
|
92
|
+
id: 'claude', label: 'Claude', displayOrder: 0, anchorOrder: 0,
|
|
93
|
+
home: {env: 'CLAUDE_CONFIG_DIR', resolve: context => resolveHome('claude', context)},
|
|
94
|
+
cli: {command: 'claude', supportedVersions: null},
|
|
95
|
+
auth: {kind: 'cli-status-json'},
|
|
96
|
+
models: {effortField: 'effort'},
|
|
97
|
+
profile: {
|
|
98
|
+
ext: 'md',
|
|
99
|
+
standaloneName: role => `arc-${role.slice(4)}`,
|
|
100
|
+
routingName: role => `arc-routing-${role.slice(4)}`,
|
|
101
|
+
},
|
|
102
|
+
executionEnvironments: ['claude-cli', 'claude-desktop'],
|
|
103
|
+
routing: {validatePair: (model, effort) => validText(model) && validText(effort) && /^[A-Za-z0-9][A-Za-z0-9._:/@+\-]*$/.test(model) && ['low', 'medium', 'high', 'xhigh', 'max'].includes(effort)},
|
|
104
|
+
capabilities: verifiedCapabilities,
|
|
105
|
+
},
|
|
106
|
+
{
|
|
107
|
+
id: 'gemini', label: 'Gemini', displayOrder: 2, anchorOrder: 2,
|
|
108
|
+
home: {env: 'GEMINI_CLI_HOME', resolve: context => resolveHome('gemini', context)},
|
|
109
|
+
cli: {command: 'gemini', supportedVersions: '>=0.68.0 <0.69.0'},
|
|
110
|
+
auth: {kind: 'none'},
|
|
111
|
+
models: {effortField: 'effort'},
|
|
112
|
+
profile: {
|
|
113
|
+
ext: 'md',
|
|
114
|
+
standaloneName: role => `arc-${role.slice(4)}`,
|
|
115
|
+
routingName: role => `arc-routing-${role.slice(4)}`,
|
|
116
|
+
},
|
|
117
|
+
executionEnvironments: ['gemini-cli'],
|
|
118
|
+
routing: {validatePair: (model, effort) => validText(model) && /^[A-Za-z0-9][A-Za-z0-9._:/@+\-]*$/.test(model) && effort === 'default'},
|
|
119
|
+
capabilities: {install: {state: 'verified'}, nativeProfile: {state: 'verified'}, catalog: {state: 'verified'}, standalone: {state: 'verified'}, bridge: {state: 'verified'}, compositeRole: {state: 'verified'}, ...Object.fromEntries(Object.entries({
|
|
120
|
+
compositeHost: 'composite host not verified',
|
|
121
|
+
authProbe: 'no official auth status command', watch: 'watch support out of scope',
|
|
122
|
+
}).map(([key, reason]) => [key, {state: 'off', reason}]))},
|
|
123
|
+
},
|
|
124
|
+
]);
|
|
125
|
+
|
|
126
|
+
export const RUNTIME_PLATFORMS = DEFAULT_PLATFORM_REGISTRY.platforms;
|
|
127
|
+
export const {platformIds, getPlatform, byDisplayOrder, byAnchorOrder, isPlatformId} = DEFAULT_PLATFORM_REGISTRY;
|
|
128
|
+
export const runtimeRegistryOf = context => context?.runtimePlatforms ?? DEFAULT_PLATFORM_REGISTRY;
|
|
129
|
+
export const standaloneProfileFile = (descriptor, role) => `arc-${role.slice(4)}.${descriptor.profile.ext}`;
|
|
130
|
+
export const routingProfileFile = (descriptor, role) => `arc-routing-${role.slice(4)}.${descriptor.profile.ext}`;
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// Pure helpers that turn an installed arc-routing profile into role-specific Claude/Codex CLI arguments. No processes are started here.
|
|
2
2
|
import crypto from 'node:crypto';
|
|
3
3
|
import path from 'node:path';
|
|
4
|
+
import {GEMINI_CONTRACT} from './gemini-stream.mjs';
|
|
4
5
|
import {DEFAULT_POLICY, effectiveClaudeSandboxSettings} from './role-dispatch-policy.mjs';
|
|
5
6
|
|
|
6
7
|
const ROLES = ['arc_scouter', 'arc_planner', 'arc_implementer', 'arc_qa', 'arc_reviewer'];
|
|
@@ -10,12 +11,23 @@ export const ROLE_BRIDGE_PERMISSIONS = deepFreeze({
|
|
|
10
11
|
arc_scouter: {permissionMode: 'default', sandbox: false}, arc_planner: {permissionMode: 'default', sandbox: false},
|
|
11
12
|
arc_implementer: {permissionMode: 'acceptEdits', sandbox: true}, arc_qa: {permissionMode: 'default', sandbox: true}, arc_reviewer: {permissionMode: 'default', sandbox: false}
|
|
12
13
|
},
|
|
14
|
+
gemini: {
|
|
15
|
+
arc_scouter: {approvalMode: 'plan', sandbox: false}, arc_planner: {approvalMode: 'plan', sandbox: false},
|
|
16
|
+
arc_implementer: {approvalMode: 'auto_edit', sandbox: true}, arc_qa: {approvalMode: 'auto_edit', sandbox: true}, arc_reviewer: {approvalMode: 'plan', sandbox: false}
|
|
17
|
+
},
|
|
13
18
|
codex: {
|
|
14
19
|
arc_scouter: {sandboxMode: 'read-only', search: true}, arc_planner: {sandboxMode: 'read-only', search: false},
|
|
15
20
|
arc_implementer: {sandboxMode: 'workspace-write', search: false}, arc_qa: {sandboxMode: 'workspace-write', search: false}, arc_reviewer: {sandboxMode: 'read-only', search: false}
|
|
16
21
|
}
|
|
17
22
|
});
|
|
18
23
|
|
|
24
|
+
const BRIDGE_IMPLEMENTATIONS = new Map([
|
|
25
|
+
['claude', {parse: parseClaude, buildArgs: buildClaudeArgs}],
|
|
26
|
+
['codex', {parse: parseCodex, buildArgs: buildCodexArgs}],
|
|
27
|
+
['gemini', {parse: parseGemini, buildArgs: buildGeminiArgs}],
|
|
28
|
+
]);
|
|
29
|
+
export const BRIDGE_PLATFORM_IDS = Object.freeze([...BRIDGE_IMPLEMENTATIONS.keys()]);
|
|
30
|
+
|
|
19
31
|
const bad = message => { throw Error(`Invalid composite profile: ${message}`); };
|
|
20
32
|
const unquote = raw => {
|
|
21
33
|
const value = raw.trim();
|
|
@@ -47,6 +59,26 @@ function parseClaude(text) {
|
|
|
47
59
|
return {name: fields.name, description: fields.description, model: fields.model, effort: fields.effort, tools, instructions};
|
|
48
60
|
}
|
|
49
61
|
|
|
62
|
+
// Managed Gemini profiles use scalar-only frontmatter. Keep this independent of installer imports.
|
|
63
|
+
function parseGemini(text) {
|
|
64
|
+
const match = /^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]+)$/.exec(text);
|
|
65
|
+
if (!match || !match[2].trim()) bad('missing Gemini frontmatter or instructions');
|
|
66
|
+
const fields = {};
|
|
67
|
+
const nonStringScalar = /^(?:~|null|true|false|yes|no|on|off|[-+]?(?:\.inf|\.nan|0[xob][0-9a-f_]+|(?:\d[\d_]*(?:\.[\d_]*)?|\.[\d_]+)(?:e[-+]?\d+)?)|\d{4}-\d{2}-\d{2}(?:[Tt ].*)?)$/i;
|
|
68
|
+
for (const line of match[1].split(/\r?\n/)) {
|
|
69
|
+
const entry = /^([a-z][a-zA-Z0-9_-]*): (.+)$/.exec(line);
|
|
70
|
+
if (!entry || Object.hasOwn(fields, entry[1])) bad('malformed or duplicate Gemini field');
|
|
71
|
+
const value = entry[2];
|
|
72
|
+
if (value !== value.trim() || /[\p{Cc}\u2028\u2029{}#&*!|>"']/u.test(value)
|
|
73
|
+
|| /^(?:[-?:](?:\s|$)|[\[\],%@`])/.test(value) || value.includes(': ') || nonStringScalar.test(value)) bad('unsupported Gemini scalar');
|
|
74
|
+
fields[entry[1]] = value;
|
|
75
|
+
}
|
|
76
|
+
for (const key of ['name', 'description', 'model']) if (!fields[key]) bad(`missing ${key}`);
|
|
77
|
+
if (Object.hasOwn(fields, 'effort')) bad('Gemini effort must be omitted');
|
|
78
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._:/@+\-]*$/.test(fields.model)) bad('invalid Gemini model');
|
|
79
|
+
return {name: fields.name, description: fields.description, model: fields.model, effort: 'default', tools: null, instructions: match[2].replaceAll('\r\n', '\n')};
|
|
80
|
+
}
|
|
81
|
+
|
|
50
82
|
const ESCAPES = {b: '\b', t: '\t', n: '\n', f: '\f', r: '\r', '"': '"', '\\': '\\'};
|
|
51
83
|
// Decodes a TOML multiline basic string body; returns null when it is not terminated by """ on the same logical line.
|
|
52
84
|
function readMultiline(lines, index, rest) {
|
|
@@ -101,12 +133,19 @@ function parseCodex(text) {
|
|
|
101
133
|
|
|
102
134
|
/** Narrow extractor: the installed runtime cannot import lib/models, so only the managed profile shapes are accepted. */
|
|
103
135
|
export function parseCompositeProfile(platform, bytes) {
|
|
104
|
-
|
|
136
|
+
const implementation = BRIDGE_IMPLEMENTATIONS.get(platform);
|
|
137
|
+
if (!implementation) bad('unknown platform');
|
|
105
138
|
const buffer = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes ?? '');
|
|
106
139
|
let text;
|
|
107
140
|
try { text = new TextDecoder('utf-8', {fatal: true}).decode(buffer); } catch { bad('not valid UTF-8'); }
|
|
108
141
|
if (text.charCodeAt(0) === 0xfeff) bad('unexpected BOM');
|
|
109
|
-
return
|
|
142
|
+
return implementation.parse(text);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export function buildBridgeArgs(platform, options) {
|
|
146
|
+
const implementation = BRIDGE_IMPLEMENTATIONS.get(platform);
|
|
147
|
+
if (!implementation) bad('unknown platform');
|
|
148
|
+
return implementation.buildArgs(options);
|
|
110
149
|
}
|
|
111
150
|
|
|
112
151
|
const permissionsFor = (platform, role) => {
|
|
@@ -146,3 +185,19 @@ export function buildCodexArgs({role, profile, worktree, resultPath, threadId =
|
|
|
146
185
|
}
|
|
147
186
|
|
|
148
187
|
export const argsDigest = args => 'sha256:' + crypto.createHash('sha256').update(JSON.stringify(args)).digest('hex');
|
|
188
|
+
|
|
189
|
+
/** L5 verifies run/observe/cancel and isolation; UUID resume remains unverified. */
|
|
190
|
+
export function buildGeminiArgs({role, model, profile, sessionId, policyFile, promptFlag = GEMINI_CONTRACT.prompt, resume = false}) {
|
|
191
|
+
const permissions = permissionsFor('gemini', role);
|
|
192
|
+
if (typeof sessionId !== 'string' || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(sessionId)) throw Error('Gemini sessionId must be a UUID');
|
|
193
|
+
if (typeof policyFile !== 'string' || !path.isAbsolute(policyFile)) throw Error('Absolute policyFile required');
|
|
194
|
+
if (promptFlag !== GEMINI_CONTRACT.prompt) throw Error('Unsupported Gemini prompt');
|
|
195
|
+
const selectedModel = requireText(model ?? profile?.model, 'model');
|
|
196
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._:/@+\-]*$/.test(selectedModel) || selectedModel === 'yolo') throw Error('Invalid Gemini model');
|
|
197
|
+
const args = ['-p', promptFlag, '-m', selectedModel, '-o', 'stream-json', '--session-id', sessionId,
|
|
198
|
+
'--approval-mode', permissions.approvalMode, '--policy', policyFile];
|
|
199
|
+
if (permissions.sandbox) args.push('--sandbox');
|
|
200
|
+
args.push(...GEMINI_CONTRACT.isolationArgs);
|
|
201
|
+
if (resume) args.push(GEMINI_CONTRACT.resumeFlag, sessionId);
|
|
202
|
+
return args;
|
|
203
|
+
}
|
|
@@ -1,30 +1,35 @@
|
|
|
1
|
+
import {runtimeRegistryOf, DEFAULT_PLATFORM_REGISTRY} from './platform-registry.mjs';
|
|
1
2
|
// A caller's JSON, local hook or child process ID cannot authorize execution.
|
|
2
3
|
// run-dispatch only asks the supervisor (the sole child spawner) to start; observe reads and records state under the routing lock.
|
|
3
4
|
import fsp from 'node:fs/promises';
|
|
4
5
|
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} from './role-routing.mjs';
|
|
8
|
-
import {
|
|
9
|
-
import {startSupervisor, processAlive, resolveWorktree, artifactDirectory, segmentDirectory, buildBridgeInvocation} from './role-supervisor.mjs';
|
|
6
|
+
import {DEFAULT_POLICY, reason, profileName, bridgeGateReasons, environmentReasons, capabilityReasons} from './role-dispatch-policy.mjs';
|
|
7
|
+
import {readLease, writeLease, listLeases, readHostLimits, NON_TERMINAL_STATES, readHeartbeat, requestCancel, clearCancel, TERMINAL_STATES, validateLease} from './role-dispatch-store.mjs';
|
|
8
|
+
import {withRoutingLock, readActivation, readRevision, authenticate, resolveRuntimeHomes, locateAnchorHome} from './role-routing.mjs';
|
|
9
|
+
import {SUPERVISOR_IMPLEMENTATIONS, startSupervisor, processAlive, resolveWorktree, artifactDirectory, segmentDirectory, buildBridgeInvocation} from './role-supervisor.mjs';
|
|
10
10
|
|
|
11
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
12
|
|
|
13
13
|
const ID=/^[A-Za-z0-9._-]{1,128}$/;
|
|
14
|
+
const v1Platforms = Object.freeze(['codex', 'claude']);
|
|
14
15
|
const NATIVE_EVENTS={started:[['reserved'],'running'],completed:[['running'],'completed'],failed:[['running'],'failed'],cancelled:[['running','reserved'],'cancelled']};
|
|
15
16
|
const sleep=ms=>new Promise(resolve=>setTimeout(resolve,ms));
|
|
16
|
-
const hostOf=context=>
|
|
17
|
-
const environmentOf=(context,host)=>
|
|
17
|
+
const hostOf=context=>runtimeRegistryOf(context).isPlatformId(context?.hostPlatform)?context.hostPlatform:null;
|
|
18
|
+
const environmentOf=(context,host)=>runtimeRegistryOf(context).getPlatform(host)?.executionEnvironments.includes(context?.executionEnvironment)?context.executionEnvironment:null;
|
|
18
19
|
const validContext=context=>{const host=hostOf(context);return Boolean(host&&environmentOf(context,host)&&typeof context.workflowId==='string'&&context.workflowId&&typeof context.cwd==='string');};
|
|
19
20
|
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
|
-
|
|
21
|
+
export function leaseTargetPlatform(lease,registry=DEFAULT_PLATFORM_REGISTRY){
|
|
22
|
+
if(lease.version===2)return lease.targetPlatform;
|
|
23
|
+
if(!v1Platforms.includes(lease.hostPlatform))throw Error('Invalid composite profile: unknown platform');
|
|
24
|
+
if(lease.route==='native')return lease.hostPlatform;
|
|
25
|
+
return v1Platforms.find(id=>id!==lease.hostPlatform);
|
|
26
|
+
}
|
|
21
27
|
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
28
|
/** 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=
|
|
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};
|
|
29
|
+
function fromLease(lease,decision=['failed','unknown'].includes(lease.state)?'hold':'allow',runtimePlatforms=DEFAULT_PLATFORM_REGISTRY){
|
|
30
|
+
const platform=leaseTargetPlatform(lease,runtimePlatforms);
|
|
31
|
+
return {decision,routeStatus:lease.state,supportStatus:supportOf(lease),dispatchId:lease.dispatchId,route:lease.route,profileName:profileName(platform,lease.role,{runtimePlatforms}),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
32
|
}
|
|
27
|
-
const homesOf=context=>({codex:resolveConfigHome('codex',context),claude:resolveConfigHome('claude',context)});
|
|
28
33
|
const residualOf=error=>Array.isArray(error?.residualPaths)?error.residualPaths:undefined;
|
|
29
34
|
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
35
|
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';};
|
|
@@ -34,23 +39,29 @@ export async function runBridgeDispatch({context,dispatchId,brief,now=Date.now()
|
|
|
34
39
|
if(!validContext(context)||typeof dispatchId!=='string'||!ID.test(dispatchId)||dispatchId.startsWith('.')||typeof brief!=='string'){return blank(context,dispatchId,'deny','invalid_request');}
|
|
35
40
|
const bytes=Buffer.byteLength(brief,'utf8');
|
|
36
41
|
if(bytes<1||bytes>policy.briefMaxBytes)return blank(context,dispatchId,'deny','invalid_request');
|
|
37
|
-
|
|
38
|
-
|
|
42
|
+
const homes=resolveRuntimeHomes(context),runtimePlatforms=runtimeRegistryOf(context);
|
|
43
|
+
const view=(lease,decision)=>fromLease(lease,decision,runtimePlatforms);
|
|
44
|
+
let anchorHome,result,residual;
|
|
45
|
+
try{anchorHome=await locateAnchorHome({host:context.hostPlatform,homes});}catch{return blank(context,dispatchId,'hold','activation_unverified');}
|
|
39
46
|
try{
|
|
40
|
-
await withRoutingLock(
|
|
41
|
-
const lease=await readLease(
|
|
47
|
+
await withRoutingLock(anchorHome,async()=>{
|
|
48
|
+
const lease=await readLease(anchorHome,dispatchId,{runtimePlatforms});
|
|
42
49
|
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
|
-
|
|
50
|
+
leaseTargetPlatform(lease,runtimePlatforms);
|
|
51
|
+
let config;try{config=await readActivation(homes,lease.revision,{anchorHome,host:context.hostPlatform,runtimePlatforms});}catch{result=blank(context,dispatchId,'hold','activation_unverified');return;}
|
|
52
|
+
validateLease(lease,{runtimePlatforms,config});
|
|
53
|
+
const capabilities=capabilityReasons({hostPlatform:lease.hostPlatform,targetPlatform:leaseTargetPlatform(lease,runtimePlatforms),route:lease.route,runtimePlatforms});
|
|
54
|
+
if(capabilities.length){result=blank(context,dispatchId,'hold',capabilities[0]);return;}
|
|
44
55
|
let target;try{target=await resolveWorktree(context.cwd);}catch{result=blank(context,dispatchId,'hold','activation_unverified');return;}
|
|
45
56
|
const directory=artifactDirectory(target,lease.workflowId,dispatchId),resultPath=path.join(directory,'result.md');
|
|
46
57
|
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
58
|
await fsp.mkdir(directory,{recursive:true,mode:0o700});await fsp.chmod(directory,0o700);
|
|
48
59
|
await fsp.writeFile(path.join(directory,'brief.md'),brief,{mode:0o600,flag:'w'});await fsp.chmod(path.join(directory,'brief.md'),0o600);
|
|
49
60
|
let supervisor;
|
|
50
|
-
try{supervisor=await starter({codexHome:
|
|
61
|
+
try{supervisor=await starter({codexHome:anchorHome,dispatchId,cwd:target.realpath,userHome:context.userHome,env:context.env??process.env});}
|
|
51
62
|
catch{result=blank(context,dispatchId,'hold','host_sandbox_blocked');return;}
|
|
52
|
-
const next=await writeLease(
|
|
53
|
-
result=
|
|
63
|
+
const next=await writeLease(anchorHome,{...lease,state:'starting',supervisor,argsDigest:invocation.argsDigest,resultPath},{now,runtimePlatforms});
|
|
64
|
+
result=view(next,'allow');
|
|
54
65
|
},{retryMs:policy.lockRetryMs});
|
|
55
66
|
}catch(error){
|
|
56
67
|
if(error?.code==='ARC_ROUTING_LOCK_RELEASE'&&!error.failure&&result){residual=residualOf(error);}
|
|
@@ -61,30 +72,31 @@ export async function runBridgeDispatch({context,dispatchId,brief,now=Date.now()
|
|
|
61
72
|
}
|
|
62
73
|
|
|
63
74
|
const TEXT=/^[^\p{Cc}]{1,256}$/u;
|
|
64
|
-
async function markLostIfDue(
|
|
75
|
+
async function markLostIfDue(anchorHome,lease,{now,lostMs,policy,runtimePlatforms}){
|
|
65
76
|
if(!['starting','running'].includes(lease.state)||!lease.supervisor)return lease;
|
|
66
|
-
const heartbeat=await readHeartbeat(
|
|
77
|
+
const heartbeat=await readHeartbeat(anchorHome,lease.dispatchId);
|
|
67
78
|
const lastSeen=Math.max(heartbeat?.at??0,Date.parse(lease.updatedAt)||0);
|
|
68
79
|
if(now-lastSeen<=lostMs||processAlive(lease.supervisor))return lease;
|
|
69
80
|
try{
|
|
70
|
-
return await withRoutingLock(
|
|
71
|
-
const current=await readLease(
|
|
81
|
+
return await withRoutingLock(anchorHome,async()=>{
|
|
82
|
+
const current=await readLease(anchorHome,lease.dispatchId,{runtimePlatforms});
|
|
72
83
|
if(!current||!['starting','running'].includes(current.state))return current??lease;
|
|
73
|
-
return writeLease(
|
|
84
|
+
return writeLease(anchorHome,{...current,state:'unknown',claims:{...(current.claims??{}),terminal:{level:'unverified',source:'none'}},reasons:[reason('terminal_state_unverified')]},{now,runtimePlatforms});
|
|
74
85
|
},{retryMs:policy.lockRetryMs});
|
|
75
86
|
}catch{return lease;}// a busy lock only delays the transition; the next observe retries it
|
|
76
87
|
}
|
|
77
|
-
async function recordNativeEvent({context,
|
|
88
|
+
async function recordNativeEvent({context,anchorHome,dispatchId,event,nativeAgentId,now,policy,runtimePlatforms}){
|
|
89
|
+
const view=(lease,decision)=>fromLease(lease,decision,runtimePlatforms);
|
|
78
90
|
let result;
|
|
79
91
|
try{
|
|
80
|
-
await withRoutingLock(
|
|
81
|
-
const lease=await readLease(
|
|
92
|
+
await withRoutingLock(anchorHome,async()=>{
|
|
93
|
+
const lease=await readLease(anchorHome,dispatchId,{runtimePlatforms});
|
|
82
94
|
const rule=NATIVE_EVENTS[event];
|
|
83
95
|
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
96
|
const attested={level:'operator-attested',source:'orchestrator'};
|
|
85
97
|
const claims={...lease.claims,...(event==='started'?{identity:{...attested,observed:nativeAgentId}}:{terminal:{...attested,observed:event}})};
|
|
86
|
-
const next=await writeLease(
|
|
87
|
-
result=
|
|
98
|
+
const next=await writeLease(anchorHome,{...lease,state:rule[1],claims,nativeAgentId:nativeAgentId??lease.nativeAgentId,reasons:event==='failed'?[reason('execution_failed')]:[]},{now,runtimePlatforms});
|
|
99
|
+
result=view(next);
|
|
88
100
|
},{retryMs:policy.lockRetryMs});
|
|
89
101
|
}catch(error){return hold(context,dispatchId,classifyLock(error),error);}
|
|
90
102
|
return result;
|
|
@@ -96,64 +108,70 @@ export async function recordRoleObservation({context,dispatchId,waitMs,event,nat
|
|
|
96
108
|
if(waitMs!==undefined&&(!Number.isInteger(waitMs)||waitMs<0||waitMs>policy.observeMaxWaitMs))return blank(context,dispatchId,'deny','invalid_request');
|
|
97
109
|
if(event!==undefined&&!Object.hasOwn(NATIVE_EVENTS,event))return blank(context,dispatchId,'deny','invalid_request');
|
|
98
110
|
if(nativeAgentId!==undefined&&(typeof nativeAgentId!=='string'||!TEXT.test(nativeAgentId)))return blank(context,dispatchId,'deny','invalid_request');
|
|
99
|
-
|
|
100
|
-
|
|
111
|
+
const homes=resolveRuntimeHomes(context),runtimePlatforms=runtimeRegistryOf(context);
|
|
112
|
+
const view=(lease,decision)=>fromLease(lease,decision,runtimePlatforms);
|
|
113
|
+
let anchorHome,lease;
|
|
114
|
+
try{anchorHome=await locateAnchorHome({host:context.hostPlatform,homes});lease=await readLease(anchorHome,dispatchId,{runtimePlatforms});if(lease)leaseTargetPlatform(lease,runtimePlatforms);}catch{return blank(context,dispatchId,'hold','activation_unverified');}
|
|
101
115
|
if(!lease||lease.workflowId!==context.workflowId||lease.hostPlatform!==context.hostPlatform)return blank(context,dispatchId,'deny','invalid_request');
|
|
102
116
|
if(lease.route==='native'){
|
|
103
117
|
if(waitMs!==undefined||event===undefined)return blank(context,dispatchId,'deny','invalid_request');
|
|
104
|
-
return recordNativeEvent({context,
|
|
118
|
+
return recordNativeEvent({context,anchorHome,dispatchId,event,nativeAgentId,now:now??Date.now(),policy,runtimePlatforms});
|
|
105
119
|
}
|
|
106
120
|
if(event!==undefined||nativeAgentId!==undefined)return blank(context,dispatchId,'deny','invalid_request');
|
|
107
121
|
const end=Date.now()+(waitMs??0),lost=lostMs??policy.supervisorLostMs;
|
|
108
122
|
try{
|
|
109
123
|
for(;;){
|
|
110
|
-
lease=await markLostIfDue(
|
|
111
|
-
if(TERMINAL_STATES.includes(lease.state)||lease.state==='unknown'||Date.now()>=end)return
|
|
124
|
+
lease=await markLostIfDue(anchorHome,lease,{now:now??Date.now(),lostMs:lost,policy,runtimePlatforms});
|
|
125
|
+
if(TERMINAL_STATES.includes(lease.state)||lease.state==='unknown'||Date.now()>=end)return view(lease);
|
|
112
126
|
await sleep(Math.min(pollMs,Math.max(0,end-Date.now())));
|
|
113
|
-
lease=await readLease(
|
|
127
|
+
lease=await readLease(anchorHome,dispatchId,{runtimePlatforms})??lease;
|
|
114
128
|
}
|
|
115
129
|
}catch{return blank(context,dispatchId,'hold','activation_unverified');}
|
|
116
130
|
}
|
|
117
131
|
|
|
118
132
|
/** 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}={}){
|
|
133
|
+
export async function resumeRoleDispatch({context,dispatchId,brief,now=Date.now(),policy=DEFAULT_POLICY,startSupervisor:starter=startSupervisor,supervisorImplementations=SUPERVISOR_IMPLEMENTATIONS}={}){
|
|
120
134
|
if(!validContext(context)||typeof dispatchId!=='string'||!ID.test(dispatchId)||dispatchId.startsWith('.')||typeof brief!=='string'){return blank(context,dispatchId,'deny','invalid_request');}
|
|
121
135
|
const bytes=Buffer.byteLength(brief,'utf8');
|
|
122
136
|
if(bytes<1||bytes>policy.briefMaxBytes)return blank(context,dispatchId,'deny','invalid_request');
|
|
123
|
-
|
|
124
|
-
|
|
137
|
+
const homes=resolveRuntimeHomes(context),runtimePlatforms=runtimeRegistryOf(context);
|
|
138
|
+
const view=(lease,decision)=>fromLease(lease,decision,runtimePlatforms);
|
|
139
|
+
let anchorHome,result,residual;
|
|
140
|
+
try{anchorHome=await locateAnchorHome({host:context.hostPlatform,homes});}catch{return blank(context,dispatchId,'hold','activation_unverified');}
|
|
125
141
|
try{
|
|
126
|
-
await withRoutingLock(
|
|
127
|
-
const lease=await readLease(
|
|
142
|
+
await withRoutingLock(anchorHome,async()=>{
|
|
143
|
+
const lease=await readLease(anchorHome,dispatchId,{runtimePlatforms});
|
|
128
144
|
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;}
|
|
145
|
+
const targetPlatform=leaseTargetPlatform(lease,runtimePlatforms);
|
|
146
|
+
if(targetPlatform==='gemini'&&!['on','verified'].includes(supervisorImplementations.get(targetPlatform)?.resume)){result=blank(context,dispatchId,'hold','resume_unverified');return;}
|
|
129
147
|
if(!lease.sessionId){result=blank(context,dispatchId,'hold','execution_identity_unverified');return;}
|
|
130
148
|
let config;
|
|
131
|
-
try{config=await readActivation(homes,lease.revision);}
|
|
149
|
+
try{config=await readActivation(homes,lease.revision,{anchorHome,host:context.hostPlatform,runtimePlatforms});}
|
|
132
150
|
catch{
|
|
133
|
-
let active=null;try{active=await readRevision(homes);}catch{/* unreadable activation stays unverified */}
|
|
151
|
+
let active=null;try{active=await readRevision(homes,{anchorHome,runtimePlatforms});}catch{/* unreadable activation stays unverified */}
|
|
134
152
|
result=blank(context,dispatchId,'hold',active!==null&&active!==lease.revision?'revision_changed':'activation_unverified');return;
|
|
135
153
|
}
|
|
136
154
|
const requested=config.roles[lease.role],platform=requested.platform,codes=new Set();
|
|
137
155
|
const {authentication}=await authenticate(platform,context,policy);
|
|
138
|
-
if(authentication.status!=='Available')codes.add(authentication.status);
|
|
156
|
+
if(authentication.status!=='Available'&&!(runtimePlatforms.getPlatform(platform).auth.kind==='none'&&authentication.authStatus==='unknown'&&authentication.reason==='auth_unverified'))codes.add(authentication.status??'Incomplete');
|
|
139
157
|
for(const code of environmentReasons(context.executionEnvironment,policy))codes.add(code);
|
|
140
158
|
for(const code of bridgeGateReasons({platform,role:lease.role,hostPlatform:context.hostPlatform,policy}))codes.add(code);
|
|
141
159
|
// 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.
|
|
142
160
|
let limits;try{limits=readHostLimits(homes[context.hostPlatform]);}catch{codes.add('activation_unverified');}
|
|
143
|
-
if(limits&&(await listLeases(
|
|
161
|
+
if(limits&&(await listLeases(anchorHome,{runtimePlatforms})).filter(item=>item.route==='bridge'&&NON_TERMINAL_STATES.includes(item.state)).length+1>limits.maxConcurrent)codes.add('capacity_exhausted');
|
|
144
162
|
if(codes.size){result=blank(context,dispatchId,'hold','activation_unverified');result.reasons=[...codes].map(reason);return;}
|
|
145
163
|
let target;try{target=await resolveWorktree(context.cwd);}catch{result=blank(context,dispatchId,'hold','activation_unverified');return;}
|
|
146
164
|
const segment=lease.segment+1,directory=segmentDirectory(target,lease.workflowId,dispatchId,segment),resultPath=path.join(directory,'result.md');
|
|
147
|
-
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;}
|
|
165
|
+
let invocation;try{invocation=await buildBridgeInvocation({lease:{...lease,segment},config,homes,worktree:target.realpath,resultPath,policy,supervisorImplementations});}catch(error){result=blank(context,dispatchId,'hold',error.reasonCode??'activation_unverified');return;}
|
|
148
166
|
await fsp.mkdir(directory,{recursive:true,mode:0o700});await fsp.chmod(path.dirname(directory),0o700);await fsp.chmod(directory,0o700);
|
|
149
167
|
await fsp.writeFile(path.join(directory,'brief.md'),brief,{mode:0o600,flag:'w'});await fsp.chmod(path.join(directory,'brief.md'),0o600);
|
|
150
|
-
await clearCancel(
|
|
168
|
+
await clearCancel(anchorHome,dispatchId);
|
|
151
169
|
let supervisor;
|
|
152
|
-
try{supervisor=await starter({codexHome:
|
|
170
|
+
try{supervisor=await starter({codexHome:anchorHome,dispatchId,cwd:target.realpath,userHome:context.userHome,env:context.env??process.env});}
|
|
153
171
|
catch{result=blank(context,dispatchId,'hold','host_sandbox_blocked');return;}
|
|
154
172
|
const claims=lease.claims?{...lease.claims,terminal:{level:'unverified',source:'none'}}:null;
|
|
155
|
-
const next=await writeLease(
|
|
156
|
-
result={...
|
|
173
|
+
const next=await writeLease(anchorHome,{...lease,state:'starting',supervisor,child:null,argsDigest:invocation.argsDigest,resultPath,segment,claims,reasons:[]},{now,runtimePlatforms});
|
|
174
|
+
result={...view(next,'allow'),segment};
|
|
157
175
|
},{retryMs:policy.lockRetryMs});
|
|
158
176
|
}catch(error){
|
|
159
177
|
if(error?.code==='ARC_ROUTING_LOCK_RELEASE'&&!error.failure&&result){residual=residualOf(error);}
|
|
@@ -169,30 +187,33 @@ const signalGroup=(pid,signal)=>{try{process.kill(-pid,signal);}catch{/* group a
|
|
|
169
187
|
/** 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. */
|
|
170
188
|
export async function cancelRoleDispatch({context,dispatchId,now=Date.now(),policy=DEFAULT_POLICY}={}){
|
|
171
189
|
if(!validContext(context)||typeof dispatchId!=='string'||!ID.test(dispatchId)||dispatchId.startsWith('.'))return blank(context,dispatchId,'deny','invalid_request');
|
|
172
|
-
|
|
173
|
-
|
|
190
|
+
const homes=resolveRuntimeHomes(context),runtimePlatforms=runtimeRegistryOf(context);
|
|
191
|
+
const view=(lease,decision)=>fromLease(lease,decision,runtimePlatforms);
|
|
192
|
+
let anchorHome,result,direct=null,residual;
|
|
193
|
+
try{anchorHome=await locateAnchorHome({host:context.hostPlatform,homes});}catch{return blank(context,dispatchId,'hold','activation_unverified');}
|
|
174
194
|
const graceMs=policy.cancelGraceMs;
|
|
175
195
|
try{
|
|
176
|
-
await withRoutingLock(
|
|
177
|
-
const lease=await readLease(
|
|
196
|
+
await withRoutingLock(anchorHome,async()=>{
|
|
197
|
+
const lease=await readLease(anchorHome,dispatchId,{runtimePlatforms});
|
|
178
198
|
if(!lease||lease.workflowId!==context.workflowId||lease.hostPlatform!==context.hostPlatform){result=blank(context,dispatchId,'deny','invalid_request');return;}
|
|
199
|
+
leaseTargetPlatform(lease,runtimePlatforms);
|
|
179
200
|
if(lease.route==='native'){
|
|
180
201
|
// A native lease has no child: only a reserved one is cancelled here (under the lock); started native dispatches are closed with observe events.
|
|
181
202
|
if(lease.state!=='reserved'){result=blank(context,dispatchId,'deny','invalid_request');return;}
|
|
182
203
|
const claims={...lease.claims,terminal:{level:'operator-attested',source:'orchestrator',observed:'cancelled'}};
|
|
183
|
-
result=
|
|
204
|
+
result=view(await writeLease(anchorHome,{...lease,state:'cancelled',claims,reasons:[]},{now,runtimePlatforms}),'allow');return;
|
|
184
205
|
}
|
|
185
|
-
if(TERMINAL_STATES.includes(lease.state)){result=
|
|
186
|
-
if(lease.state==='reserved'){result=
|
|
206
|
+
if(TERMINAL_STATES.includes(lease.state)){result=view(lease,'allow');return;}
|
|
207
|
+
if(lease.state==='reserved'){result=view(await writeLease(anchorHome,{...lease,state:'cancelled',reasons:[]},{now,runtimePlatforms}),'allow');return;}
|
|
187
208
|
const supervised=['starting','running'].includes(lease.state)&&lease.supervisor&&processAlive(lease.supervisor);
|
|
188
209
|
if(supervised){
|
|
189
|
-
await requestCancel(
|
|
210
|
+
await requestCancel(anchorHome,dispatchId);
|
|
190
211
|
if(lease.child&&processAlive(lease.child))signalGroup(lease.child.pid,'SIGTERM');
|
|
191
|
-
result={...
|
|
212
|
+
result={...view(lease,'allow'),routeStatus:'cancelling'};return;
|
|
192
213
|
}
|
|
193
214
|
if(lease.child&&processAlive(lease.child)){signalGroup(lease.child.pid,'SIGTERM');direct={lease,identified:true};}
|
|
194
215
|
else if(lease.child&&!groupExists(lease.child.pid)&&!pidExists(lease.child.pid))direct={lease,identified:false};
|
|
195
|
-
else result=
|
|
216
|
+
else result=view(lease,'hold');
|
|
196
217
|
},{retryMs:policy.lockRetryMs});
|
|
197
218
|
}catch(error){
|
|
198
219
|
if(error?.code==='ARC_ROUTING_LOCK_RELEASE'&&!error.failure&&(result||direct)){residual=residualOf(error);}
|
|
@@ -204,15 +225,15 @@ export async function cancelRoleDispatch({context,dispatchId,now=Date.now(),poli
|
|
|
204
225
|
if(!killed&&Date.now()>=begin+graceMs){signalGroup(pid,'SIGKILL');killed=true;}
|
|
205
226
|
await sleep(25);gone=!groupExists(pid);
|
|
206
227
|
}
|
|
207
|
-
if(!gone)result=
|
|
228
|
+
if(!gone)result=view(direct.lease,'hold');
|
|
208
229
|
else{
|
|
209
230
|
try{
|
|
210
|
-
await withRoutingLock(
|
|
211
|
-
const current=await readLease(
|
|
212
|
-
if(!current||TERMINAL_STATES.includes(current.state)||current.child?.pid!==pid){result=current?
|
|
231
|
+
await withRoutingLock(anchorHome,async()=>{
|
|
232
|
+
const current=await readLease(anchorHome,dispatchId,{runtimePlatforms});
|
|
233
|
+
if(!current||TERMINAL_STATES.includes(current.state)||current.child?.pid!==pid){result=current?view(current,'allow'):blank(context,dispatchId,'deny','invalid_request');return;}
|
|
213
234
|
const claims={...(current.claims??{}),terminal:{level:'runtime-observed',source:'cancel-group-gone',observed:{pid}}};
|
|
214
235
|
// The recorded reasons (for example terminal_state_unverified) stay on the cancelled lease.
|
|
215
|
-
result=
|
|
236
|
+
result=view(await writeLease(anchorHome,{...current,state:'cancelled',claims},{now:Date.now(),runtimePlatforms}),'allow');
|
|
216
237
|
},{retryMs:policy.lockRetryMs});
|
|
217
238
|
}catch(error){
|
|
218
239
|
if(error?.code==='ARC_ROUTING_LOCK_RELEASE'&&!error.failure&&result){residual=residualOf(error);}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
+
import {runtimeRegistryOf} from './platform-registry.mjs';
|
|
1
2
|
// Fixed policy values for composite role dispatch. G2 'escalation' means the bridge runs only with per-call user escalation approval on a Codex host; it is not a verified pass.
|
|
2
|
-
export const BRIDGE_GATE_RESULTS = Object.freeze({G1: 'fail', G2: 'escalation', G3: 'pass', G4: 'pass', G5: 'wide', G6: 'strict', G7: 'pass', G8: 'pass'});
|
|
3
|
+
export const BRIDGE_GATE_RESULTS = Object.freeze({G1: 'fail', G2: 'escalation', G3: 'pass', G4: 'pass', G5: 'wide', G6: 'strict', G7: 'pass', G8: 'pass', GG1: 'fail', GG2: 'fail'});
|
|
3
4
|
// No sandbox settings JSON has been recorded: G1 failed, so there is nothing to apply.
|
|
4
5
|
const RECORDED_CLAUDE_SANDBOX_SETTINGS = null;
|
|
5
6
|
const isRecordedObject = value => value !== null && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).length > 0;
|
|
@@ -39,12 +40,14 @@ export const DEFAULT_POLICY = Object.freeze({
|
|
|
39
40
|
});
|
|
40
41
|
|
|
41
42
|
export const RELEASE_CONDITIONS = Object.freeze({
|
|
42
|
-
activation_unverified: 'Verify the active configuration,
|
|
43
|
+
activation_unverified: 'Verify the active configuration, all prepared markers, installed bytes, host limits and the shared lock, and inspect the lease records in <anchor home>/arc-role-dispatch for unreadable or corrupted files.',
|
|
44
|
+
resume_unverified: 'Update ARC after verifying Gemini session resume against the recorded session UUID.',
|
|
45
|
+
capability_not_verified: 'Update ARC to a release that verifies this platform capability.',
|
|
43
46
|
'Not Available': 'Install the target platform CLI so that it is found on PATH.',
|
|
44
47
|
Unauthorized: 'Authenticate the target platform CLI.',
|
|
45
48
|
Incomplete: 'Make the target platform CLI authentication status check complete successfully.',
|
|
46
49
|
environment_unverified: 'Desktop hosts are held in this release. If this session is not running inside a Desktop app (for example a terminal or IDE terminal session), declare codex-cli or claude-cli instead; otherwise use a CLI host or a later ARC update that changes the support status.',
|
|
47
|
-
host_sandbox_blocked: 'Allow the host to write the
|
|
50
|
+
host_sandbox_blocked: 'Allow the host to write the anchor home and keep a detached supervisor alive, with explicit user approval.',
|
|
48
51
|
capacity_exhausted: 'Finish or release active bridge executions, or raise the host limits.',
|
|
49
52
|
permission_scope_unverified: 'Update ARC and verify enforcement of the role permissions and approved scope before starting.',
|
|
50
53
|
native_profile_reload_unverified: 'Verify that the host session loaded the requested profile revision.',
|
|
@@ -69,15 +72,22 @@ export const reason = code => {
|
|
|
69
72
|
if (!Object.hasOwn(RELEASE_CONDITIONS, code)) throw Error(`Unknown reason code: ${code}`);
|
|
70
73
|
return {code, releaseCondition: RELEASE_CONDITIONS[code]};
|
|
71
74
|
};
|
|
72
|
-
export const profileName = (platform, role) =>
|
|
73
|
-
const suffix = role.slice('arc_'.length);
|
|
74
|
-
return platform === 'claude' ? `arc-routing-${suffix}` : `arc_routing_${suffix}`;
|
|
75
|
-
};
|
|
75
|
+
export const profileName = (platform, role, options) => runtimeRegistryOf(options).getPlatform(platform).profile.routingName(role);
|
|
76
76
|
export const revisionTag = revision => `[arc-routing rev ${revision}]`;
|
|
77
77
|
|
|
78
|
+
export function capabilityReasons({hostPlatform, targetPlatform, route, runtimePlatforms}) {
|
|
79
|
+
const registry = runtimeRegistryOf({runtimePlatforms});
|
|
80
|
+
const host = registry.getPlatform(hostPlatform), target = registry.getPlatform(targetPlatform);
|
|
81
|
+
return host?.capabilities.compositeHost.state === 'verified'
|
|
82
|
+
&& target?.capabilities.compositeRole.state === 'verified'
|
|
83
|
+
&& (route !== 'bridge' || target?.capabilities.bridge.state === 'verified') ? [] : ['capability_not_verified'];
|
|
84
|
+
}
|
|
85
|
+
|
|
78
86
|
export function bridgeGateReasons({platform, role, hostPlatform, policy = DEFAULT_POLICY}) {
|
|
79
87
|
const gates = policy.gates ?? BRIDGE_GATE_RESULTS, codes = [];
|
|
80
88
|
if (platform === 'claude' && (role === 'arc_implementer' || role === 'arc_qa') && effectiveClaudeSandboxSettings({gates, claudeSandboxSettings: policy.claudeSandboxSettings}) === null) codes.push('permission_scope_unverified');
|
|
89
|
+
if (platform === 'gemini' && (role === 'arc_implementer' || role === 'arc_qa') && gates.GG1 !== 'pass') codes.push('permission_scope_unverified');
|
|
90
|
+
if (hostPlatform === 'gemini' && gates.GG2 !== 'pass') codes.push('host_sandbox_blocked');
|
|
81
91
|
if (platform === 'codex' && gates.G4 === 'fail') codes.push('permission_scope_unverified');
|
|
82
92
|
if (hostPlatform === 'codex' && gates.G2 === 'fail') codes.push('host_sandbox_blocked');
|
|
83
93
|
return [...new Set(codes)];
|