@yunhozz/arc 0.3.4 → 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
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import {runtimeRegistryOf, routingProfileFile} from './platform-registry.mjs';
|
|
1
2
|
import fs from 'node:fs/promises';
|
|
2
3
|
import {constants} from 'node:fs';
|
|
3
4
|
import path from 'node:path';
|
|
@@ -6,7 +7,7 @@ import {COOPERATIVE_RUNTIME_MODULES, cooperativeVersions} from './bootstrap.mjs'
|
|
|
6
7
|
import {inspectPath} from './scope.mjs';
|
|
7
8
|
import {resolveConfigHome, resolveLocalCli, probePlatformAuth, probeCodexAuthStatus, probeCliVersion} from './local-cli.mjs';
|
|
8
9
|
import {ROUTING_ROLES, parseRoleRoutingConfig} from './role-routing-config.mjs';
|
|
9
|
-
import {DEFAULT_POLICY, reason, profileName, revisionTag, bridgeGateReasons, environmentReasons, initialClaims} from './role-dispatch-policy.mjs';
|
|
10
|
+
import {DEFAULT_POLICY, reason, profileName, revisionTag, bridgeGateReasons, environmentReasons, initialClaims, capabilityReasons} from './role-dispatch-policy.mjs';
|
|
10
11
|
import {NON_TERMINAL_STATES, createLease, listLeases, pruneTerminalLeases, readHostLimits} from './role-dispatch-store.mjs';
|
|
11
12
|
|
|
12
13
|
const exact=(value,keys)=>value&&typeof value==='object'&&!Array.isArray(value)&&Object.keys(value).length===keys.length&&keys.every(key=>Object.hasOwn(value,key));
|
|
@@ -62,12 +63,36 @@ export async function acquireRoleRoutingLock(home){
|
|
|
62
63
|
}catch{return false;}
|
|
63
64
|
};
|
|
64
65
|
}
|
|
65
|
-
export
|
|
66
|
-
const
|
|
67
|
-
const
|
|
66
|
+
export function resolveRuntimeHomes(context){
|
|
67
|
+
const homes={};
|
|
68
|
+
for(const id of runtimeRegistryOf(context).platformIds()){
|
|
69
|
+
try{homes[id]=resolveConfigHome(id,context);}catch{/* unresolved homes are omitted */}
|
|
70
|
+
}
|
|
71
|
+
return homes;
|
|
72
|
+
}
|
|
73
|
+
export function matchRegisteredHome({dir,homes}){
|
|
74
|
+
const resolved=path.resolve(dir);
|
|
75
|
+
for(const [id,home] of Object.entries(homes))if(path.resolve(home)===resolved)return id;
|
|
76
|
+
return null;
|
|
77
|
+
}
|
|
78
|
+
export async function locateAnchorHome({host,homes}){
|
|
79
|
+
const home=homes[host];if(typeof home!=='string'||!path.isAbsolute(home))throw Error('Invalid host home');
|
|
80
|
+
const marker=JSON.parse((await readStable(path.join(home,'arc-role-platform-routing.prepared.json'),[])).toString('utf8'));
|
|
81
|
+
if(!exact(marker,['version','revision','platform','targetHome','activeConfigPath','configHash','runtime','profiles'])||marker.version!==1||typeof marker.revision!=='string'||!marker.revision||marker.platform!==host||marker.targetHome!==home||!validHash(marker.configHash)||!exact(marker.runtime,['version','hash','policyHash'])||typeof marker.runtime.version!=='string'||!marker.runtime.version||!validHash(marker.runtime.hash)||!validHash(marker.runtime.policyHash)||!marker.profiles||typeof marker.profiles!=='object'||Array.isArray(marker.profiles))throw Error('Invalid marker');
|
|
82
|
+
const active=marker.activeConfigPath;
|
|
83
|
+
if(typeof active!=='string'||!path.isAbsolute(active)||path.normalize(active)!==active||path.basename(active)!=='arc-role-platform-routing.json')throw Error('Invalid marker');
|
|
84
|
+
const anchorHome=path.dirname(active);
|
|
85
|
+
if(matchRegisteredHome({dir:anchorHome,homes})===null)throw Error('Unregistered anchor home');
|
|
86
|
+
return anchorHome;
|
|
87
|
+
}
|
|
88
|
+
export async function readActivation(homes,expectedRevision,{anchorHome=homes.codex,host,runtimePlatforms}={}){
|
|
89
|
+
const snapshot=[],activePath=path.join(anchorHome,'arc-role-platform-routing.json');
|
|
90
|
+
const configBytes=await readStable(activePath,snapshot),config=parseRoleRoutingConfig(configBytes.toString('utf8'),{runtimePlatforms});
|
|
91
|
+
if(anchorHome!==homes[config.platforms[0]])throw Error('Anchor mismatch');
|
|
92
|
+
if(host!==undefined&&!config.platforms.includes(host))throw Error('Host outside participating platforms');
|
|
68
93
|
if(config.revision!==expectedRevision)throw Error('Revision mismatch');
|
|
69
94
|
const versions=await cooperativeVersions();
|
|
70
|
-
for(const platform of
|
|
95
|
+
for(const platform of config.platforms){
|
|
71
96
|
const home=homes[platform],marker=JSON.parse((await readStable(path.join(home,'arc-role-platform-routing.prepared.json'),snapshot)).toString('utf8'));
|
|
72
97
|
if(!exact(marker,['version','revision','platform','targetHome','activeConfigPath','configHash','runtime','profiles'])||marker.version!==1||marker.revision!==config.revision||marker.platform!==platform||marker.targetHome!==home||marker.activeConfigPath!==activePath||marker.configHash!==hash(configBytes))throw Error('Invalid marker');
|
|
73
98
|
if(!exact(marker.runtime,['version','hash','policyHash'])||marker.runtime.version!==versions.runtime||!validHash(marker.runtime.hash)||!validHash(marker.runtime.policyHash))throw Error('Invalid runtime marker');
|
|
@@ -78,11 +103,13 @@ export async function readActivation(homes,expectedRevision){
|
|
|
78
103
|
const roles=ROUTING_ROLES.filter(role=>config.roles[role].platform===platform);
|
|
79
104
|
if(!exact(marker.profiles,roles))throw Error('Invalid profiles');
|
|
80
105
|
for(const role of roles){
|
|
81
|
-
const
|
|
106
|
+
const relative=`agents/${routingProfileFile(runtimeRegistryOf({runtimePlatforms}).getPlatform(platform),role)}`,entry=marker.profiles[role];
|
|
82
107
|
if(!exact(entry,['path','hash'])||entry.path!==relative||!validHash(entry.hash)||hash(await readStable(path.join(home,relative),snapshot))!==entry.hash)throw Error('Profile mismatch');
|
|
83
108
|
}
|
|
84
109
|
}
|
|
85
|
-
await checkSnapshot(snapshot);
|
|
110
|
+
await checkSnapshot(snapshot);
|
|
111
|
+
if(host!==undefined&&await locateAnchorHome({host,homes})!==anchorHome)throw Error('Host marker changed');
|
|
112
|
+
return config;
|
|
86
113
|
}
|
|
87
114
|
|
|
88
115
|
|
|
@@ -115,8 +142,8 @@ export async function withRoutingLock(codexHome,fn,{retryMs=DEFAULT_POLICY.lockR
|
|
|
115
142
|
|
|
116
143
|
const textValue=value=>typeof value==='string'&&/^[^\p{Cc}]{1,256}$/u.test(value);
|
|
117
144
|
const validRelativePath=value=>typeof value==='string'&&value.length>0&&value.length<=1024&&!value.includes('\0')&&!value.startsWith('/')&&!/^[A-Za-z]:/.test(value)&&value.replace(/\/$/,'').split('/').every(part=>part&&part!=='..');
|
|
118
|
-
const hostOf=context=>
|
|
119
|
-
const environmentOf=(context,host)=>
|
|
145
|
+
const hostOf=context=>runtimeRegistryOf(context).isPlatformId(context?.hostPlatform)?context.hostPlatform:null;
|
|
146
|
+
const environmentOf=(context,host)=>runtimeRegistryOf(context).getPlatform(host)?.executionEnvironments.includes(context?.executionEnvironment)?context.executionEnvironment:null;
|
|
120
147
|
function validateAssignment(assignment,expectedRevision,context){
|
|
121
148
|
const role=assignment?.role;
|
|
122
149
|
if(!ROUTING_ROLES.includes(role)||!textValue(assignment.requestId)||!textValue(assignment.taskId)||!textValue(expectedRevision)||!textValue(context?.workflowId))return false;
|
|
@@ -133,13 +160,15 @@ const classify=error=>{
|
|
|
133
160
|
export async function authenticate(platform,context,policy){
|
|
134
161
|
const cli=resolveLocalCli(platform,context);
|
|
135
162
|
if(cli.reason)return {cli:null,authentication:{status:cli.reason==='cli_not_found'?'Not Available':'Incomplete',reason:cli.reason}};
|
|
136
|
-
const
|
|
163
|
+
const kind=runtimeRegistryOf(context).getPlatform(platform).auth.kind;
|
|
164
|
+
const auth=await (kind==='codex-refresh'?probeCodexAuthStatus:probePlatformAuth)(cli,{timeoutMs:policy.probeTimeoutMs});
|
|
165
|
+
if(kind==='none')return {cli,authentication:auth};
|
|
137
166
|
return {cli,authentication:{status:auth.authStatus==='authenticated'?'Available':auth.authStatus==='unauthorized'?'Unauthorized':'Incomplete',...(auth.reason?{reason:auth.reason}:{})}};
|
|
138
167
|
}
|
|
139
168
|
export const versionOf=(cli,policy)=>cli?probeCliVersion(cli,{timeoutMs:policy.probeTimeoutMs}):{version:null,reason:'cli_not_found'};
|
|
140
|
-
export async function readRevision(homes){
|
|
141
|
-
const bytes=await readStable(path.join(
|
|
142
|
-
return parseRoleRoutingConfig(bytes.toString('utf8')).revision;
|
|
169
|
+
export async function readRevision(homes,{anchorHome=homes.codex,runtimePlatforms}={}){
|
|
170
|
+
const bytes=await readStable(path.join(anchorHome,'arc-role-platform-routing.json'),[]);
|
|
171
|
+
return parseRoleRoutingConfig(bytes.toString('utf8'),{runtimePlatforms}).revision;
|
|
143
172
|
}
|
|
144
173
|
export async function readProfileHash(home,role){
|
|
145
174
|
const marker=JSON.parse(await fs.readFile(path.join(home,'arc-role-platform-routing.prepared.json'),'utf8'));
|
|
@@ -152,17 +181,17 @@ export async function routingStatus({context,now=Date.now(),policy=DEFAULT_POLIC
|
|
|
152
181
|
const host=hostOf(context),environment=environmentOf(context,host);
|
|
153
182
|
const result={decision:'hold',revision:null,hostPlatform:host,executionEnvironment:environment,roles:null,platforms:null,pruned:{removed:0,errors:0},reasons:[]};
|
|
154
183
|
if(!host||!environment){result.decision='deny';result.reasons=[reason('invalid_request')];return result;}
|
|
155
|
-
|
|
156
|
-
try{
|
|
184
|
+
const homes=resolveRuntimeHomes(context),runtimePlatforms=runtimeRegistryOf(context);let anchorHome;
|
|
185
|
+
try{anchorHome=await locateAnchorHome({host,homes});}
|
|
157
186
|
catch{result.reasons=[reason('activation_unverified')];return result;}
|
|
158
187
|
try{
|
|
159
|
-
await withRoutingLock(
|
|
160
|
-
|
|
161
|
-
|
|
188
|
+
await withRoutingLock(anchorHome,async()=>{
|
|
189
|
+
let config;try{config=await readActivation(homes,await readRevision(homes,{anchorHome,runtimePlatforms}),{anchorHome,host,runtimePlatforms});}catch{result.reasons=[reason('activation_unverified')];return;}
|
|
190
|
+
result.pruned=await pruneTerminalLeases(anchorHome,{now,retentionMs:policy.leaseRetentionMs,runtimePlatforms});
|
|
162
191
|
result.revision=config.revision;result.roles={};
|
|
163
|
-
for(const role of ROUTING_ROLES){const requested=config.roles[role];result.roles[role]={route:requested.platform===host?'native':'bridge',platform:requested.platform,model:requested.model,effort:requested.effort,profileName:profileName(requested.platform,role),revisionTag:revisionTag(config.revision)};}
|
|
192
|
+
for(const role of ROUTING_ROLES){const requested=config.roles[role];result.roles[role]={route:requested.platform===host?'native':'bridge',platform:requested.platform,model:requested.model,effort:requested.effort,profileName:profileName(requested.platform,role,{runtimePlatforms}),revisionTag:revisionTag(config.revision)};}
|
|
164
193
|
result.platforms={};
|
|
165
|
-
for(const platform of
|
|
194
|
+
for(const platform of config.platforms.filter(name=>name===host||ROUTING_ROLES.some(role=>config.roles[role].platform===name))){
|
|
166
195
|
const {cli,authentication}=await authenticate(platform,context,policy);
|
|
167
196
|
result.platforms[platform]={authentication,cliVersion:await versionOf(cli,policy)};
|
|
168
197
|
}
|
|
@@ -180,25 +209,29 @@ export async function prepareRoleDispatch({context,assignment,expectedRevision,n
|
|
|
180
209
|
const host=hostOf(context),environment=environmentOf(context,host),role=ROUTING_ROLES.includes(assignment?.role)?assignment.role:null;
|
|
181
210
|
const result=blankResult(host,environment,role);
|
|
182
211
|
if(!host||!environment||!validateAssignment(assignment,expectedRevision,context)){result.decision='deny';result.reasons=[reason('invalid_request')];return result;}
|
|
183
|
-
const codes=new Set();let duplicate=false,
|
|
184
|
-
|
|
212
|
+
const codes=new Set();let duplicate=false,anchorHome;
|
|
213
|
+
const homes=resolveRuntimeHomes(context),runtimePlatforms=runtimeRegistryOf(context);
|
|
214
|
+
try{anchorHome=await locateAnchorHome({host,homes});}
|
|
185
215
|
catch{result.reasons=[reason('activation_unverified')];return result;}
|
|
186
216
|
try{
|
|
187
|
-
await withRoutingLock(
|
|
188
|
-
await
|
|
189
|
-
let config;try{config=await readActivation(homes,expectedRevision);}catch{result.reasons=[reason('activation_unverified')];return;}
|
|
217
|
+
await withRoutingLock(anchorHome,async()=>{
|
|
218
|
+
let config;try{config=await readActivation(homes,expectedRevision,{anchorHome,host,runtimePlatforms});}catch{result.reasons=[reason('activation_unverified')];return;}
|
|
190
219
|
const requested=config.roles[role],route=requested.platform===host?'native':'bridge';
|
|
191
|
-
result.requested={...requested};result.route=route;result.profileName=profileName(requested.platform,role);
|
|
220
|
+
result.requested={...requested};result.route=route;result.profileName=profileName(requested.platform,role,{runtimePlatforms});
|
|
221
|
+
const capabilities=capabilityReasons({hostPlatform:host,targetPlatform:requested.platform,route,runtimePlatforms});
|
|
222
|
+
if(capabilities.length){result.reasons=capabilities.map(reason);return;}
|
|
223
|
+
await pruneTerminalLeases(anchorHome,{now,retentionMs:policy.leaseRetentionMs,runtimePlatforms});
|
|
192
224
|
const {cli,authentication}=await authenticate(requested.platform,context,policy);
|
|
193
225
|
result.authentication=authentication;
|
|
194
|
-
if(authentication.status!=='Available')codes.add(authentication.status);
|
|
226
|
+
if(authentication.status!=='Available'&&!(runtimePlatforms.getPlatform(requested.platform).auth.kind==='none'&&authentication.authStatus==='unknown'&&authentication.reason==='auth_unverified'))codes.add(authentication.status??'Incomplete');
|
|
195
227
|
if(route==='bridge'){
|
|
196
228
|
result.cliVersion=await versionOf(cli,policy);
|
|
197
229
|
}
|
|
198
230
|
for(const code of environmentReasons(environment,policy))codes.add(code);
|
|
199
|
-
const leases=await listLeases(
|
|
231
|
+
const leases=await listLeases(anchorHome,{runtimePlatforms});
|
|
200
232
|
const live=leases.filter(lease=>NON_TERMINAL_STATES.includes(lease.state));
|
|
201
233
|
if(leases.some(lease=>lease.requestId===assignment.requestId)||live.some(lease=>lease.workflowId===context.workflowId&&lease.taskId===assignment.taskId&&lease.role===role)){duplicate=true;codes.add('duplicate_dispatch');}
|
|
234
|
+
if(host==='gemini'&&(policy.gates?.GG2??DEFAULT_POLICY.gates.GG2)!=='pass')codes.add('host_sandbox_blocked');
|
|
202
235
|
if(route==='bridge'){
|
|
203
236
|
let limits;try{limits=readHostLimits(resolveConfigHome(host,context));}catch{codes.add('activation_unverified');}
|
|
204
237
|
if(limits){
|
|
@@ -210,7 +243,7 @@ export async function prepareRoleDispatch({context,assignment,expectedRevision,n
|
|
|
210
243
|
result.reasons=[...codes].map(reason);
|
|
211
244
|
if(codes.size){result.decision=duplicate?'deny':'hold';return;}
|
|
212
245
|
const claims=initialClaims(route,policy,requested),iso=new Date(now).toISOString(),dispatchId=crypto.randomUUID();
|
|
213
|
-
const lease=await createLease(
|
|
246
|
+
const lease=await createLease(anchorHome,{version:2,targetPlatform:route==='native'?host:requested.platform,dispatchId,workflowId:context.workflowId,taskId:assignment.taskId,requestId:assignment.requestId,role,route,hostPlatform:host,executionEnvironment:environment,revision:config.revision,profileHash:await readProfileHash(homes[requested.platform],role),argsDigest:null,state:'reserved',supervisor:null,child:null,sessionId:route==='bridge'&&requested.platform==='gemini'?crypto.randomUUID():null,timeoutMinutes:policy.roleTimeoutMinutes[role],claims,reasons:[],allowedPaths:assignment.allowedPaths??[],resultPath:null,segment:0,nativeAgentId:null,createdAt:iso,updatedAt:iso},{runtimePlatforms,config});
|
|
214
247
|
Object.assign(result,{decision:'allow',routeStatus:'reserved',dispatchId:lease.dispatchId,claims});
|
|
215
248
|
},{retryMs:policy.lockRetryMs});
|
|
216
249
|
}catch(error){
|
|
@@ -6,18 +6,63 @@ import path from 'node:path';
|
|
|
6
6
|
import crypto from 'node:crypto';
|
|
7
7
|
import {spawn, spawnSync} from 'node:child_process';
|
|
8
8
|
import {fileURLToPath} from 'node:url';
|
|
9
|
-
import {
|
|
9
|
+
import {GEMINI_CONTRACT, normalizeGeminiStreamEvent, evaluateGeminiObservation} from './gemini-stream.mjs';
|
|
10
|
+
import {DEFAULT_POLICY, reason, bridgeGateReasons} from './role-dispatch-policy.mjs';
|
|
10
11
|
import {readLease, writeLease, writeHeartbeat, cancelRequested, TERMINAL_STATES} from './role-dispatch-store.mjs';
|
|
11
|
-
import {withRoutingLock, readActivation} from './role-routing.mjs';
|
|
12
|
+
import {withRoutingLock, readActivation, resolveRuntimeHomes} from './role-routing.mjs';
|
|
12
13
|
import {observeCooperativeTarget} from './scope.mjs';
|
|
13
|
-
import {
|
|
14
|
-
import {parseCompositeProfile,
|
|
14
|
+
import {resolveLocalCli, localCliEnvironment} from './local-cli.mjs';
|
|
15
|
+
import {parseCompositeProfile, buildBridgeArgs, argsDigest, ROLE_BRIDGE_PERMISSIONS} from './role-bridge-args.mjs';
|
|
15
16
|
import {createLineParser, normalizeClaudeStreamEvent, normalizeCodexStreamEvent, eventRecord, evaluateClaudeInit, evaluateCodexContext, readClaudeTranscriptEffort, readCodexTurnContext, classifyFailure, snapshotWorktree, detectViolations} from './role-observe.mjs';
|
|
17
|
+
import {getPlatform, routingProfileFile} from './platform-registry.mjs';
|
|
16
18
|
|
|
17
19
|
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
18
20
|
const sha256 = bytes => 'sha256:' + crypto.createHash('sha256').update(bytes).digest('hex');
|
|
19
21
|
const STDERR_LIMIT = 65536;
|
|
20
22
|
|
|
23
|
+
export const SUPERVISOR_IMPLEMENTATIONS = new Map([
|
|
24
|
+
['claude', {
|
|
25
|
+
normalize: normalizeClaudeStreamEvent,
|
|
26
|
+
async observe({state, invocation, homes, requested, terminalClaim, lease}) {
|
|
27
|
+
const evaluation = state.initEval ?? evaluateClaudeInit({init: null, expected: invocation.expected});
|
|
28
|
+
const observed = await readClaudeTranscriptEffort({claudeHome: homes.claude, sessionId: state.init?.sessionId});
|
|
29
|
+
const effort = observed === null ? {level: 'unverified', source: 'none', requested: requested.effort, observed: null, label: 'model_effort_unverified'}
|
|
30
|
+
: {level: observed === requested.effort ? 'runtime-observed' : 'unverified', source: 'claude-transcript', requested: requested.effort, observed};
|
|
31
|
+
return {claims: {...evaluation.claims, effort, terminal: terminalClaim}, effortMismatch: observed !== null && observed !== requested.effort, sessionId: state.init?.sessionId ?? lease.sessionId};
|
|
32
|
+
},
|
|
33
|
+
async resultPath(state, resultFile) {
|
|
34
|
+
if (state.terminal && !state.terminalError && typeof state.resultText === 'string') { await fsp.writeFile(resultFile, state.resultText, {mode: 0o600}); return resultFile; }
|
|
35
|
+
return null;
|
|
36
|
+
},
|
|
37
|
+
session: state => state.init?.sessionId,
|
|
38
|
+
}],
|
|
39
|
+
['gemini', {
|
|
40
|
+
resume: 'off',
|
|
41
|
+
normalize: normalizeGeminiStreamEvent,
|
|
42
|
+
async observe({state, invocation, terminalClaim, lease}) {
|
|
43
|
+
const evaluation = evaluateGeminiObservation({state, expected: invocation.expected, sessionId: lease.sessionId});
|
|
44
|
+
return {...evaluation, claims: {...evaluation.claims, terminal: terminalClaim}, effortMismatch: false, sessionId: lease.sessionId};
|
|
45
|
+
},
|
|
46
|
+
async resultPath(state, resultFile) {
|
|
47
|
+
if (!state.terminal || state.terminalError || typeof state.resultText !== 'string' || !state.resultText.trim()) return null;
|
|
48
|
+
await fsp.writeFile(resultFile, state.resultText, {mode: 0o600}); return resultFile;
|
|
49
|
+
},
|
|
50
|
+
session: state => state.geminiSessionId ?? state.init?.sessionId,
|
|
51
|
+
}],
|
|
52
|
+
['codex', {
|
|
53
|
+
normalize: normalizeCodexStreamEvent,
|
|
54
|
+
async observe({state, invocation, readContext, policy, terminalClaim, lease}) {
|
|
55
|
+
let finalContext = null;
|
|
56
|
+
if (state.threadId) finalContext = await readContext().catch(() => null);
|
|
57
|
+
const evaluation = finalContext ? evaluateCodexContext({context: finalContext, expected: invocation.expected, policy}) : state.codexEval ?? evaluateCodexContext({context: null, expected: invocation.expected, policy});
|
|
58
|
+
return {claims: {identity: state.threadId ? {level: 'runtime-observed', source: 'codex-stream-thread', observed: state.threadId} : {level: 'unverified', source: 'none'}, ...evaluation.claims, terminal: terminalClaim}, reason: evaluation.reason, effortMismatch: false, sessionId: state.threadId ?? lease.sessionId};
|
|
59
|
+
},
|
|
60
|
+
async resultPath(state, resultFile) { return fs.existsSync(resultFile) ? resultFile : null; },
|
|
61
|
+
session: state => state.threadId,
|
|
62
|
+
}],
|
|
63
|
+
]);
|
|
64
|
+
export const SUPERVISOR_PLATFORM_IDS = Object.freeze([...SUPERVISOR_IMPLEMENTATIONS.keys()]);
|
|
65
|
+
|
|
21
66
|
/** `ps -o lstart=` start time; used with the pid to tell a live process from a reused pid. Null when ps is unavailable or the pid is gone. */
|
|
22
67
|
export function processStartTime(pid) {
|
|
23
68
|
if (!Number.isInteger(pid) || pid <= 0) return null;
|
|
@@ -41,24 +86,36 @@ export const artifactDirectory = (target, workflowId, dispatchId) => path.join(t
|
|
|
41
86
|
/** Segment 0 (the first run) keeps its files in the dispatch directory; resumed segments use segments/<n>/. */
|
|
42
87
|
export const segmentDirectory = (target, workflowId, dispatchId, segment) => segment > 0 ? path.join(artifactDirectory(target, workflowId, dispatchId), 'segments', String(segment)) : artifactDirectory(target, workflowId, dispatchId);
|
|
43
88
|
|
|
89
|
+
// U-P1: reserved path only; policy contents and installation await live format verification.
|
|
90
|
+
export const geminiPolicyFile = (homes, role) => path.join(homes.gemini ?? '', 'skills', 'arc', 'policies', `${role}.toml`);
|
|
91
|
+
|
|
44
92
|
/** Builds the child CLI arguments from the hash-verified target profile. Errors carry reasonCode. */
|
|
45
|
-
export async function buildBridgeInvocation({lease, config, homes, worktree, resultPath, policy = DEFAULT_POLICY}) {
|
|
93
|
+
export async function buildBridgeInvocation({lease, config, homes, worktree, resultPath, policy = DEFAULT_POLICY, supervisorImplementations = SUPERVISOR_IMPLEMENTATIONS}) {
|
|
46
94
|
const fail = (reasonCode, message) => Object.assign(Error(message), {reasonCode});
|
|
47
|
-
const requested = config.roles[lease.role], platform = requested.platform;
|
|
48
|
-
|
|
95
|
+
const requested = config.roles[lease.role], platform = lease.version === 2 ? lease.targetPlatform : requested.platform;
|
|
96
|
+
if (platform !== requested.platform) throw fail('activation_unverified', 'Lease target differs from the active role target');
|
|
97
|
+
const implementation = supervisorImplementations.get(platform);
|
|
98
|
+
if (platform === 'gemini' || lease.hostPlatform === 'gemini') {
|
|
99
|
+
const gates = bridgeGateReasons({platform, role: lease.role, hostPlatform: lease.hostPlatform, policy});
|
|
100
|
+
if (gates.length) throw fail(gates[0], 'Gemini bridge gates are not verified');
|
|
101
|
+
}
|
|
102
|
+
if (platform === 'gemini' && lease.segment > 0 && !['on', 'verified'].includes(implementation?.resume)) throw fail('resume_unverified', 'Gemini resume is not verified');
|
|
103
|
+
if (!implementation) throw fail('permission_scope_unverified', 'Invalid composite profile: unknown platform');
|
|
104
|
+
const file = path.join(homes[platform], 'agents', routingProfileFile(getPlatform(platform), lease.role));
|
|
49
105
|
let bytes;
|
|
50
106
|
try { bytes = await fsp.readFile(file); } catch { throw fail('activation_unverified', 'Profile unreadable'); }
|
|
51
107
|
if (sha256(bytes) !== lease.profileHash) throw fail('activation_unverified', 'Profile hash differs from the reserved lease');
|
|
52
108
|
let profile, args;
|
|
53
109
|
try {
|
|
54
110
|
profile = parseCompositeProfile(platform, bytes);
|
|
55
|
-
args = platform
|
|
111
|
+
args = buildBridgeArgs(platform, {role: lease.role, profile, sessionId: lease.sessionId, worktree, resultPath, threadId: lease.sessionId, policy, policyFile: geminiPolicyFile(homes, lease.role), resume: lease.segment > 0});
|
|
56
112
|
} catch { throw fail('permission_scope_unverified', 'Profile arguments unavailable'); }
|
|
57
113
|
const permissions = ROLE_BRIDGE_PERMISSIONS[platform][lease.role];
|
|
58
114
|
const expected = platform === 'claude'
|
|
59
115
|
? {model: requested.model, effort: requested.effort, tools: profile.tools, permissionMode: permissions.permissionMode}
|
|
116
|
+
: platform === 'gemini' ? {model: requested.model, effort: 'default'}
|
|
60
117
|
: {model: requested.model, effort: requested.effort, sandboxMode: permissions.sandboxMode, approvalPolicy: 'never'};
|
|
61
|
-
return {platform, args, argsDigest: argsDigest(args), expected, requested};
|
|
118
|
+
return {platform, args, argsDigest: argsDigest(args), expected, requested, ...(platform === 'gemini' ? {stdinInstructions: profile.instructions} : {})};
|
|
62
119
|
}
|
|
63
120
|
|
|
64
121
|
/** Starts this module as a detached supervisor process (own session, stdio ignored, unref'd). env defaults to the inherited environment. */
|
|
@@ -89,19 +146,19 @@ export async function runSupervisor(options) {
|
|
|
89
146
|
}
|
|
90
147
|
}
|
|
91
148
|
};
|
|
92
|
-
const context = {cwd, userHome, env};
|
|
93
|
-
const homes =
|
|
149
|
+
const context = {cwd, userHome, env, runtimePlatforms: options.runtimePlatforms};
|
|
150
|
+
const homes = resolveRuntimeHomes(context), runtimePlatforms = options.runtimePlatforms;
|
|
94
151
|
const target = await resolveWorktree(cwd);
|
|
95
|
-
let lease = await readLease(codexHome, dispatchId);
|
|
152
|
+
let lease = await readLease(codexHome, dispatchId, {runtimePlatforms});
|
|
96
153
|
if (!lease || lease.route !== 'bridge') return;
|
|
97
154
|
const artifactDir = segmentDirectory(target, lease.workflowId, dispatchId, lease.segment), resultFile = path.join(artifactDir, 'result.md');
|
|
98
155
|
const mine = current => current && current.state === 'starting' && current.supervisor?.pid === process.pid;
|
|
99
156
|
let config;
|
|
100
157
|
const guarded = await locked(async () => {
|
|
101
|
-
const current = await readLease(codexHome, dispatchId);
|
|
158
|
+
const current = await readLease(codexHome, dispatchId, {runtimePlatforms});
|
|
102
159
|
if (!mine(current)) return false;
|
|
103
160
|
lease = current;
|
|
104
|
-
try { config = await readActivation(homes, lease.revision); } catch { config = null; }
|
|
161
|
+
try { config = await readActivation(homes, lease.revision, {anchorHome: codexHome, host: lease.hostPlatform, runtimePlatforms}); } catch { config = null; }
|
|
105
162
|
return true;
|
|
106
163
|
});
|
|
107
164
|
if (!guarded) return; // not the supervisor registered for this dispatch
|
|
@@ -119,9 +176,9 @@ export async function runSupervisor(options) {
|
|
|
119
176
|
};
|
|
120
177
|
const commit = async (state, codes, claims, extra = {}) => {
|
|
121
178
|
await locked(async () => {
|
|
122
|
-
const current = await readLease(codexHome, dispatchId);
|
|
179
|
+
const current = await readLease(codexHome, dispatchId, {runtimePlatforms});
|
|
123
180
|
if (!current || TERMINAL_STATES.includes(current.state)) return;
|
|
124
|
-
await writeLease(codexHome, {...current, state, claims: claims ?? current.claims, reasons: [...new Set(codes)].map(reason), sessionId: extra.sessionId ?? current.sessionId, resultPath: extra.resultPath ?? null});
|
|
181
|
+
await writeLease(codexHome, {...current, state, claims: claims ?? current.claims, reasons: [...new Set(codes)].map(reason), sessionId: extra.sessionId ?? current.sessionId, resultPath: extra.resultPath ?? null}, {runtimePlatforms});
|
|
125
182
|
});
|
|
126
183
|
};
|
|
127
184
|
const earlyFailure = async (code, spawned = null) => {
|
|
@@ -148,8 +205,10 @@ export async function runSupervisor(options) {
|
|
|
148
205
|
try {
|
|
149
206
|
if (config === null) return await earlyFailure('activation_unverified');
|
|
150
207
|
const requested = config.roles[lease.role], platform = requested.platform;
|
|
208
|
+
const implementation = (options.supervisorImplementations ?? SUPERVISOR_IMPLEMENTATIONS).get(platform);
|
|
209
|
+
if (!implementation) throw Error('Invalid composite profile: unknown platform');
|
|
151
210
|
let invocation;
|
|
152
|
-
try { invocation = await buildBridgeInvocation({lease, config, homes, worktree: target.realpath, resultPath: resultFile, policy}); } catch (error) { return await earlyFailure(error.reasonCode ?? 'activation_unverified'); }
|
|
211
|
+
try { invocation = await buildBridgeInvocation({lease, config, homes, worktree: target.realpath, resultPath: resultFile, policy, supervisorImplementations: options.supervisorImplementations}); } catch (error) { return await earlyFailure(error.reasonCode ?? 'activation_unverified'); }
|
|
153
212
|
if (invocation.argsDigest !== lease.argsDigest) return await earlyFailure('activation_unverified');
|
|
154
213
|
const brief = await fsp.readFile(path.join(artifactDir, 'brief.md'), 'utf8');
|
|
155
214
|
const cli = resolveLocalCli(platform, context);
|
|
@@ -166,7 +225,7 @@ export async function runSupervisor(options) {
|
|
|
166
225
|
child.on('error', () => { exited = true; exitResolve({code: null, signal: null, spawnError: true}); });
|
|
167
226
|
child.stdin.on('error', () => {});
|
|
168
227
|
if (options.afterSpawn) await options.afterSpawn(child); // test injection point for post-spawn failures
|
|
169
|
-
child.stdin.end(brief);
|
|
228
|
+
child.stdin.end(invocation.stdinInstructions === undefined ? brief : `${invocation.stdinInstructions}\n\n${brief}`);
|
|
170
229
|
const stdoutClosed = new Promise(resolve => { child.stdout.on('close', resolve); child.stdout.on('error', resolve); });
|
|
171
230
|
|
|
172
231
|
const state = {init: null, initEval: null, threadId: null, codexEval: null, terminal: false, terminalError: false, resultText: undefined, messages: [], mismatch: null, internal: null};
|
|
@@ -211,9 +270,29 @@ export async function runSupervisor(options) {
|
|
|
211
270
|
}
|
|
212
271
|
};
|
|
213
272
|
const handle = raw => {
|
|
214
|
-
const normalized =
|
|
273
|
+
const normalized = implementation.normalize(raw);
|
|
215
274
|
if (!normalized) return;
|
|
216
275
|
writeEvent(normalized);
|
|
276
|
+
if (platform === 'gemini') {
|
|
277
|
+
if (normalized.kind !== 'unknown') {
|
|
278
|
+
if (normalized.sessionId) {
|
|
279
|
+
if (normalized.sessionId !== lease.sessionId) state.geminiSessionMismatch = true;
|
|
280
|
+
state.geminiSessionId = normalized.sessionId;
|
|
281
|
+
}
|
|
282
|
+
if (normalized.model) {
|
|
283
|
+
if (normalized.model !== invocation.expected.model) state.geminiModelMismatch = true;
|
|
284
|
+
state.geminiModel = normalized.model;
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
if (normalized.kind === 'init') state.init = normalized;
|
|
288
|
+
if (normalized.kind === 'message' && normalized.role === 'assistant' && typeof normalized.text === 'string') {
|
|
289
|
+
state.resultText = (state.resultText ?? '') + normalized.text;
|
|
290
|
+
}
|
|
291
|
+
if (normalized.kind === 'result') {
|
|
292
|
+
state.terminal = true; state.terminalError ||= normalized.isError === true;
|
|
293
|
+
}
|
|
294
|
+
return;
|
|
295
|
+
}
|
|
217
296
|
if (normalized.kind === 'init') {
|
|
218
297
|
state.init = normalized; state.initEval = evaluateClaudeInit({init: normalized, expected: invocation.expected});
|
|
219
298
|
if (state.initEval.reason && !state.mismatch) { state.mismatch = state.initEval.reason; terminate('mismatch'); }
|
|
@@ -235,9 +314,9 @@ export async function runSupervisor(options) {
|
|
|
235
314
|
const startTime = child.pid ? processStartTime(child.pid) ?? 'unavailable' : null;
|
|
236
315
|
if (startTime === null) throw Error('Child did not start');
|
|
237
316
|
await locked(async () => {
|
|
238
|
-
const current = await readLease(codexHome, dispatchId);
|
|
317
|
+
const current = await readLease(codexHome, dispatchId, {runtimePlatforms});
|
|
239
318
|
if (!mine(current)) throw Error('Lease changed before the child was recorded');
|
|
240
|
-
await writeLease(codexHome, {...current, state: 'running', child: {pid: child.pid, startTime}});
|
|
319
|
+
await writeLease(codexHome, {...current, state: 'running', child: {pid: child.pid, startTime}}, {runtimePlatforms});
|
|
241
320
|
});
|
|
242
321
|
} catch { state.internal = 'execution_failed'; terminate('internal'); }
|
|
243
322
|
|
|
@@ -262,8 +341,8 @@ export async function runSupervisor(options) {
|
|
|
262
341
|
const claims = {...lease.claims, terminal: {level: 'unverified', source: 'none'}};
|
|
263
342
|
await writeRecord({state: 'unknown', reasons: [...(terminating === 'timeout' ? ['timeout'] : []), 'terminal_state_unverified'], terminatedBy: terminating, eventsTruncated, ignoredLines: parser.ignored, lineOverflow: parser.overflow}).catch(() => {});
|
|
264
343
|
await locked(async () => {
|
|
265
|
-
const current = await readLease(codexHome, dispatchId);
|
|
266
|
-
if (current && !TERMINAL_STATES.includes(current.state)) await writeLease(codexHome, {...current, state: 'unknown', claims, reasons: [...(terminating === 'timeout' ? ['timeout'] : []), 'terminal_state_unverified'].map(reason)});
|
|
344
|
+
const current = await readLease(codexHome, dispatchId, {runtimePlatforms});
|
|
345
|
+
if (current && !TERMINAL_STATES.includes(current.state)) await writeLease(codexHome, {...current, state: 'unknown', claims, reasons: [...(terminating === 'timeout' ? ['timeout'] : []), 'terminal_state_unverified'].map(reason)}, {runtimePlatforms});
|
|
267
346
|
});
|
|
268
347
|
return;
|
|
269
348
|
}
|
|
@@ -274,39 +353,24 @@ export async function runSupervisor(options) {
|
|
|
274
353
|
const codes = [];
|
|
275
354
|
if (state.mismatch) codes.push(state.mismatch);
|
|
276
355
|
if (state.internal) codes.push(state.internal);
|
|
277
|
-
let claims, effortMismatch = false;
|
|
278
356
|
const terminalClaim = {level: 'runtime-observed', source: 'supervisor-exit', observed: {exitCode: exit.code, signal: exit.signal}};
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
effortMismatch = observed !== null && observed !== requested.effort;
|
|
286
|
-
claims = {...evaluation.claims, effort, terminal: terminalClaim};
|
|
287
|
-
sessionId = state.init?.sessionId ?? sessionId;
|
|
288
|
-
} else {
|
|
289
|
-
let finalContext = null;
|
|
290
|
-
if (state.threadId) finalContext = await readContext().catch(() => null);
|
|
291
|
-
const evaluation = finalContext ? evaluateCodexContext({context: finalContext, expected: invocation.expected, policy}) : state.codexEval ?? evaluateCodexContext({context: null, expected: invocation.expected, policy});
|
|
292
|
-
if (evaluation.reason && !codes.includes(evaluation.reason)) codes.push(evaluation.reason);
|
|
293
|
-
claims = {identity: state.threadId ? {level: 'runtime-observed', source: 'codex-stream-thread', observed: state.threadId} : {level: 'unverified', source: 'none'}, ...evaluation.claims, terminal: terminalClaim};
|
|
294
|
-
sessionId = state.threadId ?? sessionId;
|
|
295
|
-
}
|
|
357
|
+
const observation = await implementation.observe({state, invocation, homes, requested, terminalClaim, lease, readContext, policy});
|
|
358
|
+
let {claims, sessionId} = observation;
|
|
359
|
+
const {effortMismatch} = observation;
|
|
360
|
+
const cancelledBeforeIdentity = platform === 'gemini' && terminating === 'cancel' && !implementation.session(state);
|
|
361
|
+
if (observation.reason && !(cancelledBeforeIdentity && observation.reason === 'execution_identity_unverified') && !codes.includes(observation.reason)) codes.push(observation.reason);
|
|
362
|
+
if (platform === 'gemini' && terminating !== 'cancel' && (exit.code !== 0 || exit.signal || state.terminalError)) codes.push('execution_failed');
|
|
296
363
|
if (effortMismatch) codes.push('model_effort_mismatch');
|
|
297
364
|
if (violations.reason) codes.push(violations.reason);
|
|
298
365
|
if (after === null) claims.permissions = {level: 'unverified', source: 'worktree-snapshot', details: 'post-run snapshot unavailable'};
|
|
299
366
|
else if (violations.reason) claims.permissions = {...claims.permissions, level: 'unverified', details: 'permission violation observed'};
|
|
300
367
|
if (terminating === 'timeout') codes.push('timeout');
|
|
301
368
|
|
|
302
|
-
|
|
303
|
-
if (platform === 'claude') {
|
|
304
|
-
if (state.terminal && !state.terminalError && typeof state.resultText === 'string') { await fsp.writeFile(resultFile, state.resultText, {mode: 0o600}); resultPath = resultFile; }
|
|
305
|
-
} else if (fs.existsSync(resultFile)) resultPath = resultFile;
|
|
369
|
+
const resultPath = await implementation.resultPath(state, resultFile);
|
|
306
370
|
if (resultPath) await fsp.chmod(resultPath, 0o600);
|
|
307
371
|
|
|
308
372
|
let finalState = 'failed';
|
|
309
|
-
const observedSession =
|
|
373
|
+
const observedSession = implementation.session(state);
|
|
310
374
|
if (!codes.length && terminating === 'cancel') finalState = 'cancelled';
|
|
311
375
|
else if (!codes.length) {
|
|
312
376
|
const failure = classifyFailure({exitCode: exit.code, signal: exit.signal, terminal: state.terminal, terminalError: state.terminalError, messages: [...state.messages, Buffer.concat(stderrParts).toString('utf8')]});
|
|
@@ -319,13 +383,14 @@ export async function runSupervisor(options) {
|
|
|
319
383
|
claims.identity = {level: 'unverified', source: 'none'};
|
|
320
384
|
}
|
|
321
385
|
}
|
|
386
|
+
if (platform === 'gemini' && codes.includes('execution_identity_unverified') && terminating !== 'cancel') finalState = 'unknown';
|
|
322
387
|
if (lease.sessionId && observedSession && observedSession !== lease.sessionId && finalState !== 'cancelled') {
|
|
323
388
|
// A resumed segment must continue the recorded session; a different observed id leaves the slot occupied.
|
|
324
389
|
finalState = 'unknown'; sessionId = lease.sessionId; if (!codes.includes('execution_identity_unverified')) codes.push('execution_identity_unverified');
|
|
325
390
|
claims.identity = {level: 'unverified', source: 'none'};
|
|
326
391
|
}
|
|
327
392
|
if (exit.spawnError && !codes.length) { codes.push('execution_failed'); finalState = 'failed'; }
|
|
328
|
-
await writeRecord({state: finalState, reasons: [...new Set(codes)], exit: {code: exit.code, signal: exit.signal}, terminatedBy: terminating, eventsTruncated, ignoredLines: parser.ignored, lineOverflow: parser.overflow, violations: {changedPaths: violations.changedPaths, headChanged: violations.headChanged, refsChanged: violations.refsChanged}, ...(orphanGroupReaped ? {orphanGroupReaped: true} : {}), argsDigest: invocation.argsDigest, resultPath});
|
|
393
|
+
await writeRecord({state: finalState, reasons: [...new Set(codes)], exit: {code: exit.code, signal: exit.signal}, terminatedBy: terminating, eventsTruncated, ignoredLines: parser.ignored, lineOverflow: parser.overflow, violations: {changedPaths: violations.changedPaths, headChanged: violations.headChanged, refsChanged: violations.refsChanged}, ...(orphanGroupReaped ? {orphanGroupReaped: true} : {}), argsDigest: invocation.argsDigest, resultPath, ...(platform === 'gemini' ? {unverifiedContracts: {delegation: GEMINI_CONTRACT.delegation}} : {})});
|
|
329
394
|
await commit(finalState, codes, claims, {sessionId, resultPath});
|
|
330
395
|
} catch {
|
|
331
396
|
// Unexpected failure after the child started: stop it, then record a failed state if the child is gone.
|
|
@@ -340,8 +405,8 @@ export async function runSupervisor(options) {
|
|
|
340
405
|
const codes = ['execution_failed', 'terminal_state_unverified'];
|
|
341
406
|
await writeRecord({state: 'unknown', reasons: codes, spawned: true, childPid: spawnedPid}).catch(() => {});
|
|
342
407
|
await locked(async () => {
|
|
343
|
-
const current = await readLease(codexHome, dispatchId);
|
|
344
|
-
if (current && !TERMINAL_STATES.includes(current.state)) await writeLease(codexHome, {...current, state: 'unknown', reasons: codes.map(reason)});
|
|
408
|
+
const current = await readLease(codexHome, dispatchId, {runtimePlatforms});
|
|
409
|
+
if (current && !TERMINAL_STATES.includes(current.state)) await writeLease(codexHome, {...current, state: 'unknown', reasons: codes.map(reason)}, {runtimePlatforms});
|
|
345
410
|
}).catch(() => {});
|
|
346
411
|
}
|
|
347
412
|
} finally {
|
package/lib/runtime/schema.mjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import {isPlatformId} from './platform-registry.mjs';
|
|
1
2
|
/**
|
|
2
3
|
* @typedef {object} WorkflowState
|
|
3
4
|
* @property {1} schemaVersion
|
|
@@ -11,7 +12,7 @@
|
|
|
11
12
|
* @property {Array<object>} leases
|
|
12
13
|
* @typedef {object} NormalizedRequest
|
|
13
14
|
* @property {string} requestId
|
|
14
|
-
* @property {
|
|
15
|
+
* @property {string} platform
|
|
15
16
|
* @property {string} operation
|
|
16
17
|
* @property {string} actorRef
|
|
17
18
|
* @property {string} taskId
|
|
@@ -47,7 +48,7 @@ export function validateWorkflowState(s){
|
|
|
47
48
|
if(!unique(s.approvals,'id')||s.approvals.some(a=>!approval(a)))fail('approval provenance');
|
|
48
49
|
if(!unique(s.identities,'actorRef')||s.identities.some(i=>!ROLES.includes(i.role)||!text(i.taskId)||!text(i.observationRef)))fail('identity');
|
|
49
50
|
if(!unique(s.leases,'actorRef')||s.leases.some(l=>!text(l.taskId)||!['active','suspended','retired'].includes(l.status)))fail('lease');
|
|
50
|
-
if(s.assignments.some(a=>!object(a)||!((a.status==='pending'&&a.actorRef===null&&text(a.assignmentId)&&text(a.correlationRef)&&text(a.requestId)&&text(a.requestedBy)&&
|
|
51
|
+
if(s.assignments.some(a=>!object(a)||!((a.status==='pending'&&a.actorRef===null&&text(a.assignmentId)&&text(a.correlationRef)&&text(a.requestId)&&text(a.requestedBy)&&isPlatformId(a.platform))||text(a.actorRef))||!text(a.taskId)||!ROLES.includes(a.role)||!strings(a.paths)||a.paths.some(p=>!absolute(p))||!strings(a.operations)||a.operations.some(op=>!OPERATIONS.includes(op))||!text(a.approvalRef)))fail('assignment');
|
|
51
52
|
for(const a of s.assignments){
|
|
52
53
|
if(a.checks!==undefined&&(!Array.isArray(a.checks)||a.checks.some(c=>!object(c)||!absolute(c.executable)||!Array.isArray(c.args)||!c.args.every(x=>typeof x==='string')||!absolute(c.cwd)||!object(c.env)||!strings(c.outputs)||c.outputs.some(p=>!absolute(p)))))fail('check descriptor');
|
|
53
54
|
if(a.temporary!==undefined&&(!object(a.temporary)||!strings(a.temporary.paths)||a.temporary.paths.some(p=>!absolute(p))||!text(a.temporary.cleanupOwner)||!Number.isFinite(Date.parse(a.temporary.expiresAt))))fail('temporary assignment');
|
|
@@ -63,7 +64,7 @@ export function validateWorkflowState(s){
|
|
|
63
64
|
return s;
|
|
64
65
|
}
|
|
65
66
|
export function validateRequest(r){
|
|
66
|
-
if(!object(r)||['requestId','actorRef','taskId','toolName'].some(k=>!text(r[k]))||!
|
|
67
|
+
if(!object(r)||['requestId','actorRef','taskId','toolName'].some(k=>!text(r[k]))||!isPlatformId(r.platform)||!OPERATIONS.includes(r.operation)||!absolute(r.cwd)||!object(r.arguments)||!object(r.descriptor)||!strings(r.paths)||r.paths.some(p=>!absolute(p)))fail('request');
|
|
67
68
|
return r;
|
|
68
69
|
}
|
|
69
70
|
export function validateEvidence(e){
|
|
@@ -72,7 +73,7 @@ export function validateEvidence(e){
|
|
|
72
73
|
if(e.facts!==undefined&&(!Array.isArray(e.facts)||e.facts.some(f=>!object(f)||!text(f.kind)||!text(f.workflowId)||!Number.isSafeInteger(f.revision)||!object(f.target)||!hash(f.policyHash)||!text(f.sourceRef)||!object(f.data))))fail('facts');
|
|
73
74
|
for(const p of e.provenance){
|
|
74
75
|
if(!['platform-event','user-message','human-confirmation'].includes(p.source))fail('provenance source');
|
|
75
|
-
if(p.source==='platform-event'&&(!text(p.eventRef)||!text(p.actorRef)||!
|
|
76
|
+
if(p.source==='platform-event'&&(!text(p.eventRef)||!text(p.actorRef)||!isPlatformId(p.platform)))fail('platform provenance');
|
|
76
77
|
if(p.source!=='platform-event'&&(!text(p.messageRef)||!hash(p.contentHash)))fail('approval provenance');
|
|
77
78
|
if(!object(p.verification)||p.verification.status!=='verified'||!text(p.verification.verifierRef)||!text(p.verification.sourceRef))fail('unverified provenance');
|
|
78
79
|
}
|