@yunhozz/arc 0.2.7 → 0.2.8

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.
Files changed (118) hide show
  1. package/MANIFEST.sha256 +115 -68
  2. package/README.md +21 -5
  3. package/claude/agents/arc-implementer.md +3 -3
  4. package/claude/agents/arc-planner.md +3 -3
  5. package/claude/agents/arc-qa.md +3 -3
  6. package/claude/agents/arc-reviewer.md +3 -3
  7. package/claude/agents/arc-scouter.md +3 -3
  8. package/claude/skill/SKILL.md +5 -5
  9. package/claude/skill/models.toml +7 -48
  10. package/claude/skill/references/commit.md +7 -7
  11. package/claude/skill/references/coordination.md +39 -3
  12. package/claude/skill/references/git-recovery.md +1 -1
  13. package/claude/skill/references/handoff-prep.md +6 -6
  14. package/claude/skill/references/handoff.md +8 -3
  15. package/claude/skill/references/limits.md +2 -0
  16. package/claude/skill/references/planning.md +8 -8
  17. package/claude/skill/references/verification.md +9 -9
  18. package/claude/skill/runtime/adapters/claude.mjs +4 -0
  19. package/claude/skill/runtime/adapters/codex.mjs +3 -0
  20. package/claude/skill/runtime/bootstrap.mjs +4 -2
  21. package/claude/skill/runtime/command.mjs +21 -4
  22. package/claude/skill/runtime/local-cli.mjs +248 -0
  23. package/claude/skill/runtime/role-bridge-args.mjs +148 -0
  24. package/claude/skill/runtime/role-bridge.mjs +227 -0
  25. package/claude/skill/runtime/role-dispatch-policy.mjs +110 -0
  26. package/claude/skill/runtime/role-dispatch-store.mjs +134 -0
  27. package/claude/skill/runtime/role-observe.mjs +299 -0
  28. package/claude/skill/runtime/role-policy.json +12 -10
  29. package/claude/skill/runtime/role-routing-config.mjs +19 -0
  30. package/claude/skill/runtime/role-routing.mjs +233 -0
  31. package/claude/skill/runtime/role-supervisor.mjs +356 -0
  32. package/claude/skill/scripts/model_config.py +23 -5
  33. package/codex/agents/arc-implementer.toml +3 -3
  34. package/codex/agents/arc-planner.toml +3 -3
  35. package/codex/agents/arc-qa.toml +3 -3
  36. package/codex/agents/arc-reviewer.toml +3 -3
  37. package/codex/agents/arc-scouter.toml +3 -3
  38. package/codex/skill/SKILL.md +5 -5
  39. package/codex/skill/models.toml +7 -48
  40. package/codex/skill/references/commit.md +7 -7
  41. package/codex/skill/references/coordination.md +38 -2
  42. package/codex/skill/references/handoff-prep.md +6 -6
  43. package/codex/skill/references/handoff-worktree.md +3 -3
  44. package/codex/skill/references/handoff.md +8 -3
  45. package/codex/skill/references/limits.md +2 -0
  46. package/codex/skill/references/planning.md +8 -8
  47. package/codex/skill/references/verification.md +9 -9
  48. package/codex/skill/runtime/adapters/claude.mjs +4 -0
  49. package/codex/skill/runtime/adapters/codex.mjs +3 -0
  50. package/codex/skill/runtime/bootstrap.mjs +4 -2
  51. package/codex/skill/runtime/command.mjs +21 -4
  52. package/codex/skill/runtime/local-cli.mjs +248 -0
  53. package/codex/skill/runtime/role-bridge-args.mjs +148 -0
  54. package/codex/skill/runtime/role-bridge.mjs +227 -0
  55. package/codex/skill/runtime/role-dispatch-policy.mjs +110 -0
  56. package/codex/skill/runtime/role-dispatch-store.mjs +134 -0
  57. package/codex/skill/runtime/role-observe.mjs +299 -0
  58. package/codex/skill/runtime/role-policy.json +12 -10
  59. package/codex/skill/runtime/role-routing-config.mjs +19 -0
  60. package/codex/skill/runtime/role-routing.mjs +233 -0
  61. package/codex/skill/runtime/role-supervisor.mjs +356 -0
  62. package/codex/skill/scripts/model_config.py +17 -22
  63. package/lib/cli/root.mjs +3 -2
  64. package/lib/installer/install-mode.mjs +34 -0
  65. package/lib/installer/install.mjs +1 -1
  66. package/lib/installer/plan.mjs +16 -7
  67. package/lib/installer/preset.mjs +18 -11
  68. package/lib/installer/role-routing.mjs +175 -0
  69. package/lib/installer/runtime-assets.mjs +9 -0
  70. package/lib/installer/targets.mjs +2 -7
  71. package/lib/installer/transaction.mjs +1 -1
  72. package/lib/installer/uninstall.mjs +10 -5
  73. package/lib/installer/upgrade-state.mjs +9 -6
  74. package/lib/installer/upgrade.mjs +2 -2
  75. package/lib/management/operations.mjs +94 -5
  76. package/lib/management/status.mjs +12 -6
  77. package/lib/management/update.mjs +3 -1
  78. package/lib/models/catalog.mjs +3 -3
  79. package/lib/models/claude-models.json +297 -0
  80. package/lib/models/codex-catalog.mjs +9 -6
  81. package/lib/models/codex-models.json +189 -0
  82. package/lib/models/config.mjs +25 -20
  83. package/lib/models/index.mjs +1 -1
  84. package/lib/models/static-catalog.mjs +42 -0
  85. package/lib/policy/role-policy.json +12 -10
  86. package/lib/runtime/adapters/claude.mjs +4 -0
  87. package/lib/runtime/adapters/codex.mjs +3 -0
  88. package/lib/runtime/bootstrap.mjs +4 -2
  89. package/lib/runtime/command.mjs +21 -4
  90. package/lib/runtime/local-cli.mjs +248 -0
  91. package/lib/runtime/role-bridge-args.mjs +148 -0
  92. package/lib/runtime/role-bridge.mjs +227 -0
  93. package/lib/runtime/role-dispatch-policy.mjs +110 -0
  94. package/lib/runtime/role-dispatch-store.mjs +134 -0
  95. package/lib/runtime/role-observe.mjs +299 -0
  96. package/lib/runtime/role-routing-config.mjs +19 -0
  97. package/lib/runtime/role-routing.mjs +233 -0
  98. package/lib/runtime/role-supervisor.mjs +356 -0
  99. package/lib/tui/app.mjs +32 -23
  100. package/lib/tui/custom-preset.mjs +138 -66
  101. package/lib/tui/render.mjs +4 -3
  102. package/lib/tui/setup.mjs +96 -51
  103. package/lib/watch/args.mjs +43 -0
  104. package/lib/watch/discover-claude.mjs +63 -0
  105. package/lib/watch/discover-codex.mjs +45 -0
  106. package/lib/watch/dispatch.mjs +133 -0
  107. package/lib/watch/git.mjs +29 -0
  108. package/lib/watch/index.mjs +112 -0
  109. package/lib/watch/labels.mjs +24 -0
  110. package/lib/watch/model.mjs +48 -0
  111. package/lib/watch/normalize-claude.mjs +99 -0
  112. package/lib/watch/normalize-codex.mjs +96 -0
  113. package/lib/watch/policy.mjs +52 -0
  114. package/lib/watch/render.mjs +86 -0
  115. package/lib/watch/scope.mjs +64 -0
  116. package/lib/watch/tail.mjs +75 -0
  117. package/lib/watch/watcher.mjs +337 -0
  118. package/package.json +2 -2
@@ -0,0 +1,227 @@
1
+ // A caller's JSON, local hook or child process ID cannot authorize execution.
2
+ // run-dispatch only asks the supervisor (the sole child spawner) to start; observe reads and records state under the routing lock.
3
+ import fsp from 'node:fs/promises';
4
+ import path from 'node:path';
5
+ import {DEFAULT_POLICY, reason, profileName, bridgeGateReasons, environmentReasons} from './role-dispatch-policy.mjs';
6
+ import {readLease, writeLease, listLeases, readHostLimits, NON_TERMINAL_STATES, readHeartbeat, requestCancel, clearCancel, TERMINAL_STATES} from './role-dispatch-store.mjs';
7
+ import {withRoutingLock, readActivation, readRevision, authenticate, versionOf} from './role-routing.mjs';
8
+ import {resolveConfigHome} from './local-cli.mjs';
9
+ import {startSupervisor, processAlive, resolveWorktree, artifactDirectory, segmentDirectory, buildBridgeInvocation} from './role-supervisor.mjs';
10
+
11
+ export const heldRoutingResult=(code,releaseCondition)=>({decision:'hold',routeStatus:'held',supportStatus:'unverified',route:null,executionEnvironment:null,hostPlatform:null,role:null,requested:null,authentication:null,reasons:[{code,releaseCondition}]});
12
+
13
+ const ID=/^[A-Za-z0-9._-]{1,128}$/;
14
+ const NATIVE_EVENTS={started:[['reserved'],'running'],completed:[['running'],'completed'],failed:[['running'],'failed'],cancelled:[['running','reserved'],'cancelled']};
15
+ const sleep=ms=>new Promise(resolve=>setTimeout(resolve,ms));
16
+ const hostOf=context=>['codex','claude'].includes(context?.hostPlatform)?context.hostPlatform:null;
17
+ const environmentOf=(context,host)=>['codex-cli','claude-cli','codex-desktop','claude-desktop'].includes(context?.executionEnvironment)&&host&&context.executionEnvironment.startsWith(`${host}-`)?context.executionEnvironment:null;
18
+ const validContext=context=>{const host=hostOf(context);return Boolean(host&&environmentOf(context,host)&&typeof context.workflowId==='string'&&context.workflowId&&typeof context.cwd==='string');};
19
+ const blank=(context,dispatchId,decision,code)=>({decision,routeStatus:'held',supportStatus:'unverified',dispatchId:typeof dispatchId==='string'&&ID.test(dispatchId)?dispatchId:null,route:null,profileName:null,executionEnvironment:context?.executionEnvironment??null,hostPlatform:context?.hostPlatform??null,role:null,requested:null,authentication:null,cliVersion:null,claims:null,reasons:[reason(code)]});
20
+ const bridgeTarget=lease=>lease.route==='native'?lease.hostPlatform:lease.hostPlatform==='codex'?'claude':'codex';
21
+ const supportOf=lease=>lease.route==='bridge'&&!String(lease.executionEnvironment).endsWith('-desktop')&&lease.state==='completed'&&lease.reasons.length===0&&['identity','model','effort','permissions','terminal'].every(key=>lease.claims?.[key]?.level==='runtime-observed')?'verified':'unverified';
22
+ /** Result view of a lease. failed and unknown hold dependent work; every other observed state is reported as allow. */
23
+ function fromLease(lease,decision=['failed','unknown'].includes(lease.state)?'hold':'allow'){
24
+ const platform=bridgeTarget(lease);
25
+ return {decision,routeStatus:lease.state,supportStatus:supportOf(lease),dispatchId:lease.dispatchId,route:lease.route,profileName:profileName(platform,lease.role),executionEnvironment:lease.executionEnvironment,hostPlatform:lease.hostPlatform,role:lease.role,requested:{platform,model:lease.claims?.model?.requested??null,effort:lease.claims?.effort?.requested??null},authentication:null,cliVersion:null,claims:lease.claims,reasons:lease.reasons,resultPath:lease.resultPath};
26
+ }
27
+ const homesOf=context=>({codex:resolveConfigHome('codex',context),claude:resolveConfigHome('claude',context)});
28
+ const residualOf=error=>Array.isArray(error?.residualPaths)?error.residualPaths:undefined;
29
+ const hold=(context,dispatchId,code,error)=>{const result=blank(context,dispatchId,'hold',code);const residual=residualOf(error);if(residual)result.residualPaths=residual;return result;};
30
+ const classifyLock=error=>{const code=error?.code==='ARC_ROUTING_LOCK_RELEASE'&&error.failure?error.failure.code:error?.code;return code==='ARC_HOST_SANDBOX'?'host_sandbox_blocked':'activation_unverified';};
31
+
32
+ /** Starts the detached supervisor for a reserved bridge lease; the supervisor, not this function, spawns the child. */
33
+ export async function runBridgeDispatch({context,dispatchId,brief,now=Date.now(),policy=DEFAULT_POLICY,startSupervisor:starter=startSupervisor}={}){
34
+ if(!validContext(context)||typeof dispatchId!=='string'||!ID.test(dispatchId)||dispatchId.startsWith('.')||typeof brief!=='string'){return blank(context,dispatchId,'deny','invalid_request');}
35
+ const bytes=Buffer.byteLength(brief,'utf8');
36
+ if(bytes<1||bytes>policy.briefMaxBytes)return blank(context,dispatchId,'deny','invalid_request');
37
+ let homes,result,residual;
38
+ try{homes=homesOf(context);}catch{return blank(context,dispatchId,'hold','activation_unverified');}
39
+ try{
40
+ await withRoutingLock(homes.codex,async()=>{
41
+ const lease=await readLease(homes.codex,dispatchId);
42
+ if(!lease||lease.workflowId!==context.workflowId||lease.hostPlatform!==context.hostPlatform||lease.route!=='bridge'||lease.state!=='reserved'){result=blank(context,dispatchId,'deny','invalid_request');return;}
43
+ let config;try{config=await readActivation(homes,lease.revision);}catch{result=blank(context,dispatchId,'hold','activation_unverified');return;}
44
+ let target;try{target=await resolveWorktree(context.cwd);}catch{result=blank(context,dispatchId,'hold','activation_unverified');return;}
45
+ const directory=artifactDirectory(target,lease.workflowId,dispatchId),resultPath=path.join(directory,'result.md');
46
+ let invocation;try{invocation=await buildBridgeInvocation({lease,config,homes,worktree:target.realpath,resultPath,policy});}catch(error){result=blank(context,dispatchId,'hold',error.reasonCode??'activation_unverified');return;}
47
+ await fsp.mkdir(directory,{recursive:true,mode:0o700});await fsp.chmod(directory,0o700);
48
+ await fsp.writeFile(path.join(directory,'brief.md'),brief,{mode:0o600,flag:'w'});await fsp.chmod(path.join(directory,'brief.md'),0o600);
49
+ let supervisor;
50
+ try{supervisor=await starter({codexHome:homes.codex,dispatchId,cwd:target.realpath,userHome:context.userHome,env:context.env??process.env});}
51
+ catch{result=blank(context,dispatchId,'hold','host_sandbox_blocked');return;}
52
+ const next=await writeLease(homes.codex,{...lease,state:'starting',supervisor,argsDigest:invocation.argsDigest,resultPath},{now});
53
+ result=fromLease(next,'allow');
54
+ },{retryMs:policy.lockRetryMs});
55
+ }catch(error){
56
+ if(error?.code==='ARC_ROUTING_LOCK_RELEASE'&&!error.failure&&result){residual=residualOf(error);}
57
+ else return hold(context,dispatchId,classifyLock(error),error);
58
+ }
59
+ if(residual)result.residualPaths=residual;
60
+ return result;
61
+ }
62
+
63
+ const TEXT=/^[^\p{Cc}]{1,256}$/u;
64
+ async function markLostIfDue(homes,lease,{now,lostMs,policy}){
65
+ if(!['starting','running'].includes(lease.state)||!lease.supervisor)return lease;
66
+ const heartbeat=await readHeartbeat(homes.codex,lease.dispatchId);
67
+ const lastSeen=Math.max(heartbeat?.at??0,Date.parse(lease.updatedAt)||0);
68
+ if(now-lastSeen<=lostMs||processAlive(lease.supervisor))return lease;
69
+ try{
70
+ return await withRoutingLock(homes.codex,async()=>{
71
+ const current=await readLease(homes.codex,lease.dispatchId);
72
+ if(!current||!['starting','running'].includes(current.state))return current??lease;
73
+ return writeLease(homes.codex,{...current,state:'unknown',claims:{...(current.claims??{}),terminal:{level:'unverified',source:'none'}},reasons:[reason('terminal_state_unverified')]},{now});
74
+ },{retryMs:policy.lockRetryMs});
75
+ }catch{return lease;}// a busy lock only delays the transition; the next observe retries it
76
+ }
77
+ async function recordNativeEvent({context,homes,dispatchId,event,nativeAgentId,now,policy}){
78
+ let result;
79
+ try{
80
+ await withRoutingLock(homes.codex,async()=>{
81
+ const lease=await readLease(homes.codex,dispatchId);
82
+ const rule=NATIVE_EVENTS[event];
83
+ if(!lease||lease.route!=='native'||lease.workflowId!==context.workflowId||!rule[0].includes(lease.state)||(event==='started')!==(nativeAgentId!==undefined)){result=blank(context,dispatchId,'deny','invalid_request');return;}
84
+ const attested={level:'operator-attested',source:'orchestrator'};
85
+ const claims={...lease.claims,...(event==='started'?{identity:{...attested,observed:nativeAgentId}}:{terminal:{...attested,observed:event}})};
86
+ const next=await writeLease(homes.codex,{...lease,state:rule[1],claims,nativeAgentId:nativeAgentId??lease.nativeAgentId,reasons:event==='failed'?[reason('execution_failed')]:[]},{now});
87
+ result=fromLease(next);
88
+ },{retryMs:policy.lockRetryMs});
89
+ }catch(error){return hold(context,dispatchId,classifyLock(error),error);}
90
+ return result;
91
+ }
92
+
93
+ /** bridge: waits up to waitMs for a terminal or unknown state and marks a lost supervisor unknown. native: records operator events. */
94
+ export async function recordRoleObservation({context,dispatchId,waitMs,event,nativeAgentId,now,lostMs,pollMs=500,policy=DEFAULT_POLICY}={}){
95
+ if(!validContext(context)||typeof dispatchId!=='string'||!ID.test(dispatchId)||dispatchId.startsWith('.'))return blank(context,dispatchId,'deny','invalid_request');
96
+ if(waitMs!==undefined&&(!Number.isInteger(waitMs)||waitMs<0||waitMs>policy.observeMaxWaitMs))return blank(context,dispatchId,'deny','invalid_request');
97
+ if(event!==undefined&&!Object.hasOwn(NATIVE_EVENTS,event))return blank(context,dispatchId,'deny','invalid_request');
98
+ if(nativeAgentId!==undefined&&(typeof nativeAgentId!=='string'||!TEXT.test(nativeAgentId)))return blank(context,dispatchId,'deny','invalid_request');
99
+ let homes,lease;
100
+ try{homes=homesOf(context);lease=await readLease(homes.codex,dispatchId);}catch{return blank(context,dispatchId,'hold','activation_unverified');}
101
+ if(!lease||lease.workflowId!==context.workflowId||lease.hostPlatform!==context.hostPlatform)return blank(context,dispatchId,'deny','invalid_request');
102
+ if(lease.route==='native'){
103
+ if(waitMs!==undefined||event===undefined)return blank(context,dispatchId,'deny','invalid_request');
104
+ return recordNativeEvent({context,homes,dispatchId,event,nativeAgentId,now:now??Date.now(),policy});
105
+ }
106
+ if(event!==undefined||nativeAgentId!==undefined)return blank(context,dispatchId,'deny','invalid_request');
107
+ const end=Date.now()+(waitMs??0),lost=lostMs??policy.supervisorLostMs;
108
+ try{
109
+ for(;;){
110
+ lease=await markLostIfDue(homes,lease,{now:now??Date.now(),lostMs:lost,policy});
111
+ if(TERMINAL_STATES.includes(lease.state)||lease.state==='unknown'||Date.now()>=end)return fromLease(lease);
112
+ await sleep(Math.min(pollMs,Math.max(0,end-Date.now())));
113
+ lease=await readLease(homes.codex,dispatchId)??lease;
114
+ }
115
+ }catch{return blank(context,dispatchId,'hold','activation_unverified');}
116
+ }
117
+
118
+ /** Continues a completed or failed bridge dispatch in its recorded session. The input carries no session id; only the lease value is used. */
119
+ export async function resumeRoleDispatch({context,dispatchId,brief,now=Date.now(),policy=DEFAULT_POLICY,startSupervisor:starter=startSupervisor}={}){
120
+ if(!validContext(context)||typeof dispatchId!=='string'||!ID.test(dispatchId)||dispatchId.startsWith('.')||typeof brief!=='string'){return blank(context,dispatchId,'deny','invalid_request');}
121
+ const bytes=Buffer.byteLength(brief,'utf8');
122
+ if(bytes<1||bytes>policy.briefMaxBytes)return blank(context,dispatchId,'deny','invalid_request');
123
+ let homes,result,residual;
124
+ try{homes=homesOf(context);}catch{return blank(context,dispatchId,'hold','activation_unverified');}
125
+ try{
126
+ await withRoutingLock(homes.codex,async()=>{
127
+ const lease=await readLease(homes.codex,dispatchId);
128
+ if(!lease||lease.workflowId!==context.workflowId||lease.hostPlatform!==context.hostPlatform||lease.route!=='bridge'||!['completed','failed'].includes(lease.state)){result=blank(context,dispatchId,'deny','invalid_request');return;}
129
+ if(!lease.sessionId){result=blank(context,dispatchId,'hold','execution_identity_unverified');return;}
130
+ let config;
131
+ try{config=await readActivation(homes,lease.revision);}
132
+ catch{
133
+ let active=null;try{active=await readRevision(homes);}catch{/* unreadable activation stays unverified */}
134
+ result=blank(context,dispatchId,'hold',active!==null&&active!==lease.revision?'revision_changed':'activation_unverified');return;
135
+ }
136
+ const requested=config.roles[lease.role],platform=requested.platform,codes=new Set();
137
+ const {cli,authentication}=await authenticate(platform,context,policy);
138
+ if(authentication.status!=='Available')codes.add(authentication.status);
139
+ const version=await versionOf(cli,policy);
140
+ if(cli&&!version.supported)codes.add('permission_scope_unverified');
141
+ for(const code of environmentReasons(context.executionEnvironment,policy))codes.add(code);
142
+ for(const code of bridgeGateReasons({platform,role:lease.role,hostPlatform:context.hostPlatform,policy}))codes.add(code);
143
+ // The dispatch itself is terminal here, so only other non-terminal bridge leases occupy slots. The workflow total is not increased by a follow-up segment.
144
+ let limits;try{limits=readHostLimits(homes[context.hostPlatform]);}catch{codes.add('activation_unverified');}
145
+ if(limits&&(await listLeases(homes.codex)).filter(item=>item.route==='bridge'&&NON_TERMINAL_STATES.includes(item.state)).length+1>limits.maxConcurrent)codes.add('capacity_exhausted');
146
+ if(codes.size){result=blank(context,dispatchId,'hold','activation_unverified');result.reasons=[...codes].map(reason);return;}
147
+ let target;try{target=await resolveWorktree(context.cwd);}catch{result=blank(context,dispatchId,'hold','activation_unverified');return;}
148
+ const segment=lease.segment+1,directory=segmentDirectory(target,lease.workflowId,dispatchId,segment),resultPath=path.join(directory,'result.md');
149
+ let invocation;try{invocation=await buildBridgeInvocation({lease:{...lease,segment},config,homes,worktree:target.realpath,resultPath,policy});}catch(error){result=blank(context,dispatchId,'hold',error.reasonCode??'activation_unverified');return;}
150
+ await fsp.mkdir(directory,{recursive:true,mode:0o700});await fsp.chmod(path.dirname(directory),0o700);await fsp.chmod(directory,0o700);
151
+ await fsp.writeFile(path.join(directory,'brief.md'),brief,{mode:0o600,flag:'w'});await fsp.chmod(path.join(directory,'brief.md'),0o600);
152
+ await clearCancel(homes.codex,dispatchId);
153
+ let supervisor;
154
+ try{supervisor=await starter({codexHome:homes.codex,dispatchId,cwd:target.realpath,userHome:context.userHome,env:context.env??process.env});}
155
+ catch{result=blank(context,dispatchId,'hold','host_sandbox_blocked');return;}
156
+ const claims=lease.claims?{...lease.claims,terminal:{level:'unverified',source:'none'}}:null;
157
+ const next=await writeLease(homes.codex,{...lease,state:'starting',supervisor,child:null,argsDigest:invocation.argsDigest,resultPath,segment,claims,reasons:[]},{now});
158
+ result={...fromLease(next,'allow'),segment};
159
+ },{retryMs:policy.lockRetryMs});
160
+ }catch(error){
161
+ if(error?.code==='ARC_ROUTING_LOCK_RELEASE'&&!error.failure&&result){residual=residualOf(error);}
162
+ else return hold(context,dispatchId,classifyLock(error),error);
163
+ }
164
+ if(residual)result.residualPaths=residual;
165
+ return result;
166
+ }
167
+
168
+ const groupExists=pid=>{try{process.kill(-pid,0);return true;}catch(error){return error.code!=='ESRCH';}};
169
+ const pidExists=pid=>{try{process.kill(pid,0);return true;}catch(error){return error.code!=='ESRCH';}};
170
+ const signalGroup=(pid,signal)=>{try{process.kill(-pid,signal);}catch{/* group already gone */}};
171
+ /** Reserved leases have no child and are cleaned up at once. A live supervisor receives a cancel marker and records cancelled itself after observing the exit. An unknown lease (or one whose supervisor is gone) is stopped here only for a process identified by pid and start time, and cancelled only after the group is observed gone. */
172
+ export async function cancelRoleDispatch({context,dispatchId,now=Date.now(),policy=DEFAULT_POLICY}={}){
173
+ if(!validContext(context)||typeof dispatchId!=='string'||!ID.test(dispatchId)||dispatchId.startsWith('.'))return blank(context,dispatchId,'deny','invalid_request');
174
+ let homes,result,direct=null,residual;
175
+ try{homes=homesOf(context);}catch{return blank(context,dispatchId,'hold','activation_unverified');}
176
+ const graceMs=policy.cancelGraceMs;
177
+ try{
178
+ await withRoutingLock(homes.codex,async()=>{
179
+ const lease=await readLease(homes.codex,dispatchId);
180
+ if(!lease||lease.workflowId!==context.workflowId||lease.hostPlatform!==context.hostPlatform){result=blank(context,dispatchId,'deny','invalid_request');return;}
181
+ if(lease.route==='native'){
182
+ // A native lease has no child: only a reserved one is cancelled here (under the lock); started native dispatches are closed with observe events.
183
+ if(lease.state!=='reserved'){result=blank(context,dispatchId,'deny','invalid_request');return;}
184
+ const claims={...lease.claims,terminal:{level:'operator-attested',source:'orchestrator',observed:'cancelled'}};
185
+ result=fromLease(await writeLease(homes.codex,{...lease,state:'cancelled',claims,reasons:[]},{now}),'allow');return;
186
+ }
187
+ if(TERMINAL_STATES.includes(lease.state)){result=fromLease(lease,'allow');return;}
188
+ if(lease.state==='reserved'){result=fromLease(await writeLease(homes.codex,{...lease,state:'cancelled',reasons:[]},{now}),'allow');return;}
189
+ const supervised=['starting','running'].includes(lease.state)&&lease.supervisor&&processAlive(lease.supervisor);
190
+ if(supervised){
191
+ await requestCancel(homes.codex,dispatchId);
192
+ if(lease.child&&processAlive(lease.child))signalGroup(lease.child.pid,'SIGTERM');
193
+ result={...fromLease(lease,'allow'),routeStatus:'cancelling'};return;
194
+ }
195
+ if(lease.child&&processAlive(lease.child)){signalGroup(lease.child.pid,'SIGTERM');direct={lease,identified:true};}
196
+ else if(lease.child&&!groupExists(lease.child.pid)&&!pidExists(lease.child.pid))direct={lease,identified:false};
197
+ else result=fromLease(lease,'hold');
198
+ },{retryMs:policy.lockRetryMs});
199
+ }catch(error){
200
+ if(error?.code==='ARC_ROUTING_LOCK_RELEASE'&&!error.failure&&(result||direct)){residual=residualOf(error);}
201
+ else return hold(context,dispatchId,classifyLock(error),error);
202
+ }
203
+ if(direct){
204
+ const pid=direct.lease.child.pid,begin=Date.now();let killed=false,gone=!groupExists(pid);
205
+ while(!gone&&Date.now()<begin+2*graceMs){
206
+ if(!killed&&Date.now()>=begin+graceMs){signalGroup(pid,'SIGKILL');killed=true;}
207
+ await sleep(25);gone=!groupExists(pid);
208
+ }
209
+ if(!gone)result=fromLease(direct.lease,'hold');
210
+ else{
211
+ try{
212
+ await withRoutingLock(homes.codex,async()=>{
213
+ const current=await readLease(homes.codex,dispatchId);
214
+ if(!current||TERMINAL_STATES.includes(current.state)||current.child?.pid!==pid){result=current?fromLease(current,'allow'):blank(context,dispatchId,'deny','invalid_request');return;}
215
+ const claims={...(current.claims??{}),terminal:{level:'runtime-observed',source:'cancel-group-gone',observed:{pid}}};
216
+ // The recorded reasons (for example terminal_state_unverified) stay on the cancelled lease.
217
+ result=fromLease(await writeLease(homes.codex,{...current,state:'cancelled',claims},{now:Date.now()}),'allow');
218
+ },{retryMs:policy.lockRetryMs});
219
+ }catch(error){
220
+ if(error?.code==='ARC_ROUTING_LOCK_RELEASE'&&!error.failure&&result){residual=residualOf(error);}
221
+ else return hold(context,dispatchId,classifyLock(error),error);
222
+ }
223
+ }
224
+ }
225
+ if(residual)result.residualPaths=residual;
226
+ return result;
227
+ }
@@ -0,0 +1,110 @@
1
+ // Fixed policy values for composite role dispatch. Gate results mirror the recorded G1-G8 outcomes.
2
+ export const SUPPORTED_CLI_VERSIONS = Object.freeze({
3
+ claude: Object.freeze({min: '2.1.322', below: '2.2.0'}),
4
+ codex: Object.freeze({min: '0.167.0', below: '0.168.0'})
5
+ });
6
+ export const BRIDGE_GATE_RESULTS = Object.freeze({G1: 'fail', G2: 'fail', G3: 'pass', G4: 'pass', G5: 'wide', G6: 'strict', G7: 'pass', G8: 'pass'});
7
+ // No sandbox settings JSON has been recorded: G1 failed, so there is nothing to apply.
8
+ const RECORDED_CLAUDE_SANDBOX_SETTINGS = null;
9
+ const isRecordedObject = value => value !== null && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).length > 0;
10
+ export const CLAUDE_SANDBOX_SETTINGS = BRIDGE_GATE_RESULTS.G1 === 'pass' && isRecordedObject(RECORDED_CLAUDE_SANDBOX_SETTINGS) ? RECORDED_CLAUDE_SANDBOX_SETTINGS : null;
11
+ /** G1 counts as passed only with an explicitly recorded settings object; otherwise the settings are null. */
12
+ export const effectiveClaudeSandboxSettings = policy => policy?.gates?.G1 === 'pass' && isRecordedObject(policy.claudeSandboxSettings) ? policy.claudeSandboxSettings : null;
13
+ // Short Claude model aliases of the lib/models Claude catalog (claude-models.json). The runtime cannot import lib/models, so they are fixed here; a test keeps both in sync.
14
+ export const CATALOG_MODEL_ALIASES = Object.freeze(['fable', 'opus', 'sonnet', 'haiku']);
15
+ export const CODEX_DELEGATION_CALL_NAMES = Object.freeze(['spawn_agent', 'wait_agent']);
16
+ export const DESKTOP_CHECKLIST_PASSED = Object.freeze({'claude-desktop': false, 'codex-desktop': false});
17
+ export const ROLE_TIMEOUT_MINUTES = Object.freeze({arc_scouter: 20, arc_planner: 20, arc_implementer: 60, arc_qa: 30, arc_reviewer: 20});
18
+ export const HEARTBEAT_MS = 5000;
19
+ export const SUPERVISOR_LOST_MS = 30000;
20
+ export const OBSERVE_MAX_WAIT_MS = 540000;
21
+ export const BRIEF_MAX_BYTES = 262144;
22
+ export const EVENTS_MAX_BYTES = 4194304;
23
+ export const CANCEL_GRACE_MS = 10000;
24
+ export const LOCK_RETRY_MS = 2000;
25
+ export const LEASE_RETENTION_MS = 2592000000;
26
+ export const PROBE_TIMEOUT_MS = 10000;
27
+
28
+ export const DEFAULT_POLICY = Object.freeze({
29
+ supportedVersions: SUPPORTED_CLI_VERSIONS,
30
+ gates: BRIDGE_GATE_RESULTS,
31
+ claudeSandboxSettings: CLAUDE_SANDBOX_SETTINGS,
32
+ codexDelegationCallNames: CODEX_DELEGATION_CALL_NAMES,
33
+ desktopChecklist: DESKTOP_CHECKLIST_PASSED,
34
+ roleTimeoutMinutes: ROLE_TIMEOUT_MINUTES,
35
+ heartbeatMs: HEARTBEAT_MS,
36
+ supervisorLostMs: SUPERVISOR_LOST_MS,
37
+ observeMaxWaitMs: OBSERVE_MAX_WAIT_MS,
38
+ briefMaxBytes: BRIEF_MAX_BYTES,
39
+ eventsMaxBytes: EVENTS_MAX_BYTES,
40
+ cancelGraceMs: CANCEL_GRACE_MS,
41
+ lockRetryMs: LOCK_RETRY_MS,
42
+ leaseRetentionMs: LEASE_RETENTION_MS,
43
+ probeTimeoutMs: PROBE_TIMEOUT_MS
44
+ });
45
+
46
+ export const RELEASE_CONDITIONS = Object.freeze({
47
+ activation_unverified: 'Verify the active configuration, both prepared markers, installed bytes, host limits and the shared lock, and inspect the lease records in <CODEX_HOME>/arc-role-dispatch for unreadable or corrupted files.',
48
+ 'Not Available': 'Install the target platform CLI so that it is found on PATH.',
49
+ Unauthorized: 'Authenticate the target platform CLI.',
50
+ Incomplete: 'Make the target platform CLI authentication status check complete successfully.',
51
+ environment_unverified: 'Desktop hosts are held in this release; use a CLI host or a later ARC update that changes the support status.',
52
+ host_sandbox_blocked: 'Allow the host to write the Codex home and keep a detached supervisor alive, with explicit user approval.',
53
+ capacity_exhausted: 'Finish or release active bridge executions, or raise the host limits.',
54
+ permission_scope_unverified: 'Use a supported CLI version or update ARC, and verify enforcement of the role permissions and approved scope before starting.',
55
+ native_profile_reload_unverified: 'Verify that the host session loaded the requested profile revision.',
56
+ revision_changed: 'Re-run routing-status and prepare a new dispatch under the current revision.',
57
+ duplicate_dispatch: 'Use a new requestId, or finish the existing dispatch for the same workflow, task and role.',
58
+ invalid_request: 'Provide a valid request with exactly the documented keys.',
59
+ permission_scope_mismatch: 'Inspect the recorded permission mismatch before dependent work.',
60
+ model_effort_mismatch: 'Inspect the observed model and effort against the requested values.',
61
+ auth_rejected: 'Authenticate the target platform CLI.',
62
+ model_rejected: 'Choose a model the target platform accepts.',
63
+ effort_rejected: 'Choose an effort the target platform accepts.',
64
+ permission_violation_observed: 'Reconcile the observed changes before dependent work.',
65
+ delegation_observed: 'Reconcile the observed delegation before dependent work.',
66
+ invalid_output: 'Inspect the dispatch record; the CLI produced no usable result.',
67
+ execution_failed: 'Inspect the dispatch record for the abnormal exit.',
68
+ timeout: 'Inspect the dispatch record and decide whether to resume or start a new dispatch.',
69
+ execution_identity_unverified: 'Verify the assignment-to-execution identity before observing or resuming.',
70
+ terminal_state_unverified: 'Inspect the supervisor and child process state; the slot stays occupied.',
71
+ model_effort_unverified: 'Provide a trusted observer for the requested model and effort.'
72
+ });
73
+ export const reason = code => {
74
+ if (!Object.hasOwn(RELEASE_CONDITIONS, code)) throw Error(`Unknown reason code: ${code}`);
75
+ return {code, releaseCondition: RELEASE_CONDITIONS[code]};
76
+ };
77
+ export const profileName = (platform, role) => {
78
+ const suffix = role.slice('arc_'.length);
79
+ return platform === 'claude' ? `arc-routing-${suffix}` : `arc_routing_${suffix}`;
80
+ };
81
+ export const revisionTag = revision => `[arc-routing rev ${revision}]`;
82
+
83
+ export function bridgeGateReasons({platform, role, hostPlatform, policy = DEFAULT_POLICY}) {
84
+ const gates = policy.gates ?? BRIDGE_GATE_RESULTS, codes = [];
85
+ if (platform === 'claude' && (role === 'arc_implementer' || role === 'arc_qa') && effectiveClaudeSandboxSettings({gates, claudeSandboxSettings: policy.claudeSandboxSettings}) === null) codes.push('permission_scope_unverified');
86
+ if (platform === 'codex' && gates.G4 === 'fail') codes.push('permission_scope_unverified');
87
+ if (hostPlatform === 'codex' && gates.G2 === 'fail') codes.push('host_sandbox_blocked');
88
+ return [...new Set(codes)];
89
+ }
90
+ export function environmentReasons(executionEnvironment, policy = DEFAULT_POLICY) {
91
+ const checklist = policy.desktopChecklist ?? DESKTOP_CHECKLIST_PASSED;
92
+ return typeof executionEnvironment === 'string' && executionEnvironment.endsWith('-desktop') && checklist[executionEnvironment] !== true ? ['environment_unverified'] : [];
93
+ }
94
+ /** route is 'native' or 'bridge'; requested optionally carries the requested model and effort for the claims. */
95
+ export function initialClaims(route, policy = DEFAULT_POLICY, requested = {}) {
96
+ void policy;
97
+ const attested = source => ({level: 'operator-attested', source});
98
+ if (route === 'native') return {
99
+ identity: attested('orchestrator'),
100
+ model: {...attested('orchestrator'), requested: requested.model ?? null},
101
+ effort: {...attested('orchestrator'), requested: requested.effort ?? null},
102
+ permissions: {...attested('prompt-contract'), details: 'Role permissions are a prompt contract, not enforced by ARC.'},
103
+ terminal: attested('orchestrator')
104
+ };
105
+ const unverified = {level: 'unverified', source: 'none'};
106
+ return {
107
+ identity: {...unverified}, model: {...unverified, requested: requested.model ?? null}, effort: {...unverified, requested: requested.effort ?? null},
108
+ permissions: {...unverified, details: null}, terminal: {...unverified}
109
+ };
110
+ }
@@ -0,0 +1,134 @@
1
+ // Global dispatch lease storage. Every write assumes the caller holds arc-role-platform-routing.lock.
2
+ import fs from 'node:fs';
3
+ import fsp from 'node:fs/promises';
4
+ import path from 'node:path';
5
+ import crypto from 'node:crypto';
6
+
7
+ export const NON_TERMINAL_STATES = Object.freeze(['reserved', 'starting', 'running', 'unknown']);
8
+ export const TERMINAL_STATES = Object.freeze(['completed', 'failed', 'cancelled']);
9
+ const KEYS = ['version', 'dispatchId', 'workflowId', 'taskId', 'requestId', 'role', 'route', 'hostPlatform', 'executionEnvironment', 'revision', 'profileHash', 'argsDigest', 'state', 'supervisor', 'child', 'sessionId', 'timeoutMinutes', 'claims', 'reasons', 'allowedPaths', 'resultPath', 'segment', 'nativeAgentId', 'createdAt', 'updatedAt'];
10
+ const ID = /^[A-Za-z0-9._-]{1,128}$/;
11
+ const isObject = value => value && typeof value === 'object' && !Array.isArray(value);
12
+ const text = value => typeof value === 'string' && value.length > 0;
13
+ const nullableText = value => value === null || text(value);
14
+ const process_ = value => value === null || isObject(value) && Object.keys(value).length === 2 && Number.isInteger(value.pid) && value.pid > 0 && text(value.startTime);
15
+
16
+ export const dispatchDirectory = codexHome => path.join(codexHome, 'arc-role-dispatch');
17
+ const leasePath = (codexHome, dispatchId) => {
18
+ if (typeof dispatchId !== 'string' || !ID.test(dispatchId) || dispatchId.startsWith('.')) throw Error('Invalid dispatch id');
19
+ return path.join(dispatchDirectory(codexHome), `${dispatchId}.json`);
20
+ };
21
+ export function validateLease(value) {
22
+ if (!isObject(value) || Object.keys(value).length !== KEYS.length || KEYS.some(key => !Object.hasOwn(value, key))) throw Error('Invalid lease keys');
23
+ const ok = value.version === 1 && typeof value.dispatchId === 'string' && ID.test(value.dispatchId) && !value.dispatchId.startsWith('.')
24
+ && ['workflowId', 'taskId', 'requestId', 'role', 'executionEnvironment', 'revision', 'createdAt', 'updatedAt'].every(key => text(value[key]))
25
+ && ['native', 'bridge'].includes(value.route) && ['codex', 'claude'].includes(value.hostPlatform)
26
+ && nullableText(value.profileHash) && nullableText(value.argsDigest) && nullableText(value.sessionId) && nullableText(value.resultPath) && nullableText(value.nativeAgentId)
27
+ && [...NON_TERMINAL_STATES, ...TERMINAL_STATES].includes(value.state) && process_(value.supervisor) && process_(value.child)
28
+ && Number.isInteger(value.timeoutMinutes) && value.timeoutMinutes > 0 && Number.isInteger(value.segment) && value.segment >= 0
29
+ && (value.claims === null || isObject(value.claims)) && Array.isArray(value.reasons) && Array.isArray(value.allowedPaths) && value.allowedPaths.every(text);
30
+ if (!ok) throw Error('Invalid lease values');
31
+ return structuredClone(value);
32
+ }
33
+ /** Creates the lease directory when missing. An existing one must be a real directory owned by the current user and has its group and other access removed (0700 when the owner has full access); anything else is refused. */
34
+ export async function ensureDispatchDirectory(codexHome, {uid = process.getuid?.()} = {}) {
35
+ const directory = dispatchDirectory(codexHome);
36
+ await fsp.mkdir(directory, {recursive: true, mode: 0o700});
37
+ const stat = await fsp.lstat(directory);
38
+ if (!stat.isDirectory()) throw Error('Dispatch path is not a directory');
39
+ if (uid !== undefined && stat.uid !== uid) throw Error('Dispatch directory is not owned by the current user');
40
+ if ((stat.mode & 0o077) !== 0) await fsp.chmod(directory, stat.mode & 0o700); // only tightens: owner bits are never widened, so a sandbox-restricted directory still fails on write
41
+ return directory;
42
+ }
43
+ export async function createLease(codexHome, lease) {
44
+ const value = validateLease(lease);
45
+ await ensureDispatchDirectory(codexHome);
46
+ const handle = await fsp.open(leasePath(codexHome, value.dispatchId), 'wx', 0o600);
47
+ try { await handle.writeFile(JSON.stringify(value, null, 2) + '\n'); await handle.sync(); } finally { await handle.close(); }
48
+ return value;
49
+ }
50
+ export async function readLease(codexHome, dispatchId) {
51
+ let bytes;
52
+ try { bytes = await fsp.readFile(leasePath(codexHome, dispatchId), 'utf8'); } catch (error) { if (error.code === 'ENOENT') return null; throw error; }
53
+ return validateLease(JSON.parse(bytes));
54
+ }
55
+ export async function writeLease(codexHome, lease, {now = Date.now()} = {}) {
56
+ await ensureDispatchDirectory(codexHome);
57
+ const value = validateLease({...lease, updatedAt: new Date(now).toISOString()}), target = leasePath(codexHome, value.dispatchId);
58
+ const temp = path.join(dispatchDirectory(codexHome), `.${value.dispatchId}.${crypto.randomUUID()}.tmp`);
59
+ try {
60
+ const handle = await fsp.open(temp, 'wx', 0o600);
61
+ try { await handle.writeFile(JSON.stringify(value, null, 2) + '\n'); await handle.sync(); } finally { await handle.close(); }
62
+ await fsp.rename(temp, target);
63
+ } catch (error) { await fsp.unlink(temp).catch(() => {}); throw error; }
64
+ return value;
65
+ }
66
+ const HEARTBEAT_SUFFIX = '.heartbeat.json';
67
+ const leaseFiles = async codexHome => {
68
+ try { return (await fsp.readdir(dispatchDirectory(codexHome))).filter(name => name.endsWith('.json') && !name.endsWith(HEARTBEAT_SUFFIX) && !name.startsWith('.')).sort(); }
69
+ catch (error) { if (error.code === 'ENOENT') return []; throw error; }
70
+ };
71
+ export async function listLeases(codexHome) {
72
+ const leases = [];
73
+ for (const name of await leaseFiles(codexHome)) leases.push(validateLease(JSON.parse(await fsp.readFile(path.join(dispatchDirectory(codexHome), name), 'utf8'))));
74
+ return leases;
75
+ }
76
+ /** Removes only terminal leases whose updatedAt is older than retentionMs. Failures are counted, never thrown. */
77
+ export async function pruneTerminalLeases(codexHome, {now = Date.now(), retentionMs}) {
78
+ let removed = 0, errors = 0, names;
79
+ try { names = await leaseFiles(codexHome); } catch { return {removed, errors: 1}; }
80
+ for (const name of names) {
81
+ const file = path.join(dispatchDirectory(codexHome), name);
82
+ try {
83
+ const lease = validateLease(JSON.parse(await fsp.readFile(file, 'utf8')));
84
+ const updated = Date.parse(lease.updatedAt);
85
+ if (!TERMINAL_STATES.includes(lease.state) || !Number.isFinite(updated) || now - updated <= retentionMs) continue;
86
+ await fsp.unlink(file); removed += 1;
87
+ for (const extra of [`${lease.dispatchId}${HEARTBEAT_SUFFIX}`, `${lease.dispatchId}.cancel`]) await fsp.unlink(path.join(dispatchDirectory(codexHome), extra)).catch(() => {});
88
+ } catch { errors += 1; }
89
+ }
90
+ return {removed, errors};
91
+ }
92
+ /** Reads only the three keys written by serializeLimits; any other content is rejected. */
93
+ export function readHostLimits(hostHome) {
94
+ const values = {};
95
+ for (const raw of fs.readFileSync(path.join(hostHome, 'skills', 'arc', 'limits.toml'), 'utf8').split(/\r?\n/)) {
96
+ const line = raw.trim();
97
+ if (!line || line.startsWith('#')) continue;
98
+ const match = /^([a-z_]+)[ \t]*=[ \t]*(\d{1,15})[ \t]*(?:#.*)?$/.exec(line);
99
+ if (!match || !['version', 'max_total_subagents', 'max_concurrent_subagents'].includes(match[1]) || Object.hasOwn(values, match[1])) throw Error('Invalid limits file');
100
+ values[match[1]] = Number(match[2]);
101
+ }
102
+ if (Object.keys(values).length !== 3 || values.version !== 1 || values.max_total_subagents < 1 || values.max_concurrent_subagents < 1) throw Error('Invalid limits file');
103
+ return {maxTotal: values.max_total_subagents, maxConcurrent: values.max_concurrent_subagents};
104
+ }
105
+
106
+ const sidecarPath = (codexHome, dispatchId, suffix) => path.join(dispatchDirectory(codexHome), `${path.basename(leasePath(codexHome, dispatchId), '.json')}${suffix}`);
107
+ /** The supervisor alone writes its heartbeat; no routing lock is needed because the file is replaced atomically and holds no lease state. */
108
+ export async function writeHeartbeat(codexHome, dispatchId, {at, pid}) {
109
+ if (!Number.isFinite(at) || !Number.isInteger(pid) || pid <= 0) throw Error('Invalid heartbeat');
110
+ const target = sidecarPath(codexHome, dispatchId, HEARTBEAT_SUFFIX), temp = path.join(dispatchDirectory(codexHome), `.${dispatchId}.${crypto.randomUUID()}.hb.tmp`);
111
+ try {
112
+ const handle = await fsp.open(temp, 'wx', 0o600);
113
+ try { await handle.writeFile(JSON.stringify({at, pid}) + '\n'); } finally { await handle.close(); }
114
+ await fsp.rename(temp, target);
115
+ } catch (error) { await fsp.unlink(temp).catch(() => {}); throw error; }
116
+ }
117
+ export async function readHeartbeat(codexHome, dispatchId) {
118
+ try {
119
+ const value = JSON.parse(await fsp.readFile(sidecarPath(codexHome, dispatchId, HEARTBEAT_SUFFIX), 'utf8'));
120
+ return isObject(value) && Number.isFinite(value.at) && Number.isInteger(value.pid) ? {at: value.at, pid: value.pid} : null;
121
+ } catch { return null; }
122
+ }
123
+ /** Marker file asking the supervisor to stop the child; the supervisor polls for it. */
124
+ export async function requestCancel(codexHome, dispatchId) {
125
+ const handle = await fsp.open(sidecarPath(codexHome, dispatchId, '.cancel'), 'a', 0o600);
126
+ await handle.close();
127
+ }
128
+ /** Removes a stale cancel marker before a resumed segment starts; the caller holds the routing lock. */
129
+ export async function clearCancel(codexHome, dispatchId) {
130
+ try { await fsp.unlink(sidecarPath(codexHome, dispatchId, '.cancel')); } catch (error) { if (error.code !== 'ENOENT') throw error; }
131
+ }
132
+ export async function cancelRequested(codexHome, dispatchId) {
133
+ try { await fsp.access(sidecarPath(codexHome, dispatchId, '.cancel')); return true; } catch { return false; }
134
+ }