@yunhozz/arc 0.3.3 → 0.3.4

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 (126) hide show
  1. package/MANIFEST.sha256 +80 -122
  2. package/README.md +3 -3
  3. package/claude/skill/SKILL.md +1 -0
  4. package/claude/skill/references/coordination.md +5 -3
  5. package/claude/skill/references/git-recovery.md +5 -0
  6. package/claude/skill/references/handoff-prep.md +6 -8
  7. package/claude/skill/references/handoff.md +4 -4
  8. package/claude/skill/references/planning.md +5 -0
  9. package/claude/skill/references/worktree-creation.md +14 -0
  10. package/codex/skill/references/coordination.md +5 -3
  11. package/codex/skill/references/git-recovery.md +1 -5
  12. package/codex/skill/references/worktree-creation.md +20 -0
  13. package/lib/installer/manifest.mjs +10 -9
  14. package/lib/installer/package-references.mjs +2 -2
  15. package/lib/installer/plan.mjs +3 -1
  16. package/lib/installer/skill-sources.mjs +23 -0
  17. package/lib/installer/superpowers.mjs +5 -5
  18. package/lib/runtime/bootstrap.mjs +1 -1
  19. package/lib/runtime/local-cli.mjs +10 -20
  20. package/lib/runtime/role-bridge.mjs +2 -4
  21. package/lib/runtime/role-dispatch-policy.mjs +4 -9
  22. package/lib/runtime/role-routing.mjs +1 -2
  23. package/lib/watch/dispatch.mjs +10 -2
  24. package/lib/watch/git.mjs +4 -2
  25. package/lib/watch/index.mjs +16 -8
  26. package/lib/watch/model.mjs +8 -4
  27. package/lib/watch/normalize-claude.mjs +83 -6
  28. package/lib/watch/normalize-codex.mjs +15 -11
  29. package/lib/watch/render.mjs +73 -19
  30. package/lib/watch/scope.mjs +5 -5
  31. package/lib/watch/watcher.mjs +110 -10
  32. package/package.json +2 -1
  33. package/scripts/check-installer-parity.mjs +3 -1
  34. package/scripts/update-manifest.mjs +1 -1
  35. package/scripts/update-runtime-assets.mjs +1 -1
  36. package/{codex → shared}/skill/references/handoff-worktree.md +17 -16
  37. package/{codex → shared}/skill/runtime/bootstrap.mjs +1 -1
  38. package/{codex → shared}/skill/runtime/local-cli.mjs +10 -20
  39. package/{codex → shared}/skill/runtime/role-bridge.mjs +2 -4
  40. package/{claude → shared}/skill/runtime/role-dispatch-policy.mjs +4 -9
  41. package/{claude → shared}/skill/runtime/role-routing.mjs +1 -2
  42. package/claude/skill/runtime/bootstrap.mjs +0 -38
  43. package/claude/skill/runtime/local-cli.mjs +0 -248
  44. package/claude/skill/runtime/role-bridge.mjs +0 -227
  45. package/codex/skill/references/brainstorming.md +0 -316
  46. package/codex/skill/references/builder-check-prompt.md +0 -23
  47. package/codex/skill/references/scripts/frame-template.html +0 -213
  48. package/codex/skill/references/scripts/helper.js +0 -167
  49. package/codex/skill/references/scripts/server.cjs +0 -723
  50. package/codex/skill/references/scripts/start-server.sh +0 -216
  51. package/codex/skill/references/scripts/stop-server.sh +0 -120
  52. package/codex/skill/references/superpowers-LICENSE +0 -21
  53. package/codex/skill/references/superpowers-provenance.json +0 -26
  54. package/codex/skill/references/test-driven-development.md +0 -330
  55. package/codex/skill/references/visual-companion.md +0 -299
  56. package/codex/skill/references/writing-good-tests.md +0 -198
  57. package/codex/skill/references/writing-plans.md +0 -204
  58. package/codex/skill/runtime/acceptance.mjs +0 -68
  59. package/codex/skill/runtime/adapters/claude.mjs +0 -86
  60. package/codex/skill/runtime/adapters/codex.mjs +0 -65
  61. package/codex/skill/runtime/assignment.mjs +0 -42
  62. package/codex/skill/runtime/capabilities.mjs +0 -44
  63. package/codex/skill/runtime/cli.mjs +0 -8
  64. package/codex/skill/runtime/command.mjs +0 -38
  65. package/codex/skill/runtime/cooperative-schema.mjs +0 -87
  66. package/codex/skill/runtime/cooperative.mjs +0 -239
  67. package/codex/skill/runtime/evaluate.mjs +0 -331
  68. package/codex/skill/runtime/external.mjs +0 -51
  69. package/codex/skill/runtime/gate.mjs +0 -71
  70. package/codex/skill/runtime/git-evidence.mjs +0 -258
  71. package/codex/skill/runtime/git-query.mjs +0 -88
  72. package/codex/skill/runtime/identity.mjs +0 -49
  73. package/codex/skill/runtime/operations.mjs +0 -6
  74. package/codex/skill/runtime/role-bridge-args.mjs +0 -148
  75. package/codex/skill/runtime/role-dispatch-policy.mjs +0 -110
  76. package/codex/skill/runtime/role-dispatch-store.mjs +0 -134
  77. package/codex/skill/runtime/role-observe.mjs +0 -299
  78. package/codex/skill/runtime/role-policy.json +0 -654
  79. package/codex/skill/runtime/role-routing-config.mjs +0 -19
  80. package/codex/skill/runtime/role-routing.mjs +0 -233
  81. package/codex/skill/runtime/role-supervisor.mjs +0 -356
  82. package/codex/skill/runtime/schema.mjs +0 -98
  83. package/codex/skill/runtime/scope.mjs +0 -36
  84. package/codex/skill/runtime/store.mjs +0 -94
  85. package/codex/skill/runtime/target-preparation.mjs +0 -110
  86. package/codex/skill/runtime/verification.mjs +0 -125
  87. /package/{claude → shared}/skill/references/brainstorming.md +0 -0
  88. /package/{claude → shared}/skill/references/builder-check-prompt.md +0 -0
  89. /package/{claude → shared}/skill/references/scripts/frame-template.html +0 -0
  90. /package/{claude → shared}/skill/references/scripts/helper.js +0 -0
  91. /package/{claude → shared}/skill/references/scripts/server.cjs +0 -0
  92. /package/{claude → shared}/skill/references/scripts/start-server.sh +0 -0
  93. /package/{claude → shared}/skill/references/scripts/stop-server.sh +0 -0
  94. /package/{claude → shared}/skill/references/superpowers-LICENSE +0 -0
  95. /package/{claude → shared}/skill/references/superpowers-provenance.json +0 -0
  96. /package/{claude → shared}/skill/references/test-driven-development.md +0 -0
  97. /package/{claude → shared}/skill/references/visual-companion.md +0 -0
  98. /package/{claude → shared}/skill/references/writing-good-tests.md +0 -0
  99. /package/{claude → shared}/skill/references/writing-plans.md +0 -0
  100. /package/{claude → shared}/skill/runtime/acceptance.mjs +0 -0
  101. /package/{claude → shared}/skill/runtime/adapters/claude.mjs +0 -0
  102. /package/{claude → shared}/skill/runtime/adapters/codex.mjs +0 -0
  103. /package/{claude → shared}/skill/runtime/assignment.mjs +0 -0
  104. /package/{claude → shared}/skill/runtime/capabilities.mjs +0 -0
  105. /package/{claude → shared}/skill/runtime/cli.mjs +0 -0
  106. /package/{claude → shared}/skill/runtime/command.mjs +0 -0
  107. /package/{claude → shared}/skill/runtime/cooperative-schema.mjs +0 -0
  108. /package/{claude → shared}/skill/runtime/cooperative.mjs +0 -0
  109. /package/{claude → shared}/skill/runtime/evaluate.mjs +0 -0
  110. /package/{claude → shared}/skill/runtime/external.mjs +0 -0
  111. /package/{claude → shared}/skill/runtime/gate.mjs +0 -0
  112. /package/{claude → shared}/skill/runtime/git-evidence.mjs +0 -0
  113. /package/{claude → shared}/skill/runtime/git-query.mjs +0 -0
  114. /package/{claude → shared}/skill/runtime/identity.mjs +0 -0
  115. /package/{claude → shared}/skill/runtime/operations.mjs +0 -0
  116. /package/{claude → shared}/skill/runtime/role-bridge-args.mjs +0 -0
  117. /package/{claude → shared}/skill/runtime/role-dispatch-store.mjs +0 -0
  118. /package/{claude → shared}/skill/runtime/role-observe.mjs +0 -0
  119. /package/{claude → shared}/skill/runtime/role-policy.json +0 -0
  120. /package/{claude → shared}/skill/runtime/role-routing-config.mjs +0 -0
  121. /package/{claude → shared}/skill/runtime/role-supervisor.mjs +0 -0
  122. /package/{claude → shared}/skill/runtime/schema.mjs +0 -0
  123. /package/{claude → shared}/skill/runtime/scope.mjs +0 -0
  124. /package/{claude → shared}/skill/runtime/store.mjs +0 -0
  125. /package/{claude → shared}/skill/runtime/target-preparation.mjs +0 -0
  126. /package/{claude → shared}/skill/runtime/verification.mjs +0 -0
@@ -4,7 +4,7 @@ import fsp from 'node:fs/promises';
4
4
  import path from 'node:path';
5
5
  import {DEFAULT_POLICY, reason, profileName, bridgeGateReasons, environmentReasons} from './role-dispatch-policy.mjs';
6
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';
7
+ import {withRoutingLock, readActivation, readRevision, authenticate} from './role-routing.mjs';
8
8
  import {resolveConfigHome} from './local-cli.mjs';
9
9
  import {startSupervisor, processAlive, resolveWorktree, artifactDirectory, segmentDirectory, buildBridgeInvocation} from './role-supervisor.mjs';
10
10
 
@@ -134,10 +134,8 @@ export async function resumeRoleDispatch({context,dispatchId,brief,now=Date.now(
134
134
  result=blank(context,dispatchId,'hold',active!==null&&active!==lease.revision?'revision_changed':'activation_unverified');return;
135
135
  }
136
136
  const requested=config.roles[lease.role],platform=requested.platform,codes=new Set();
137
- const {cli,authentication}=await authenticate(platform,context,policy);
137
+ const {authentication}=await authenticate(platform,context,policy);
138
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
139
  for(const code of environmentReasons(context.executionEnvironment,policy))codes.add(code);
142
140
  for(const code of bridgeGateReasons({platform,role:lease.role,hostPlatform:context.hostPlatform,policy}))codes.add(code);
143
141
  // 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.
@@ -1,9 +1,5 @@
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'});
1
+ // Fixed policy values for composite role dispatch. G2 'escalation' means the bridge runs only with per-call user escalation approval on a Codex host; it is not a verified pass.
2
+ export const BRIDGE_GATE_RESULTS = Object.freeze({G1: 'fail', G2: 'escalation', G3: 'pass', G4: 'pass', G5: 'wide', G6: 'strict', G7: 'pass', G8: 'pass'});
7
3
  // No sandbox settings JSON has been recorded: G1 failed, so there is nothing to apply.
8
4
  const RECORDED_CLAUDE_SANDBOX_SETTINGS = null;
9
5
  const isRecordedObject = value => value !== null && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).length > 0;
@@ -26,7 +22,6 @@ export const LEASE_RETENTION_MS = 2592000000;
26
22
  export const PROBE_TIMEOUT_MS = 10000;
27
23
 
28
24
  export const DEFAULT_POLICY = Object.freeze({
29
- supportedVersions: SUPPORTED_CLI_VERSIONS,
30
25
  gates: BRIDGE_GATE_RESULTS,
31
26
  claudeSandboxSettings: CLAUDE_SANDBOX_SETTINGS,
32
27
  codexDelegationCallNames: CODEX_DELEGATION_CALL_NAMES,
@@ -48,10 +43,10 @@ export const RELEASE_CONDITIONS = Object.freeze({
48
43
  'Not Available': 'Install the target platform CLI so that it is found on PATH.',
49
44
  Unauthorized: 'Authenticate the target platform CLI.',
50
45
  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.',
46
+ environment_unverified: 'Desktop hosts are held in this release. If this session is not running inside a Desktop app (for example a terminal or IDE terminal session), declare codex-cli or claude-cli instead; otherwise use a CLI host or a later ARC update that changes the support status.',
52
47
  host_sandbox_blocked: 'Allow the host to write the Codex home and keep a detached supervisor alive, with explicit user approval.',
53
48
  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.',
49
+ permission_scope_unverified: 'Update ARC and verify enforcement of the role permissions and approved scope before starting.',
55
50
  native_profile_reload_unverified: 'Verify that the host session loaded the requested profile revision.',
56
51
  revision_changed: 'Re-run routing-status and prepare a new dispatch under the current revision.',
57
52
  duplicate_dispatch: 'Use a new requestId, or finish the existing dispatch for the same workflow, task and role.',
@@ -136,7 +136,7 @@ export async function authenticate(platform,context,policy){
136
136
  const auth=await (platform==='codex'?probeCodexAuthStatus:probePlatformAuth)(cli,{timeoutMs:policy.probeTimeoutMs});
137
137
  return {cli,authentication:{status:auth.authStatus==='authenticated'?'Available':auth.authStatus==='unauthorized'?'Unauthorized':'Incomplete',...(auth.reason?{reason:auth.reason}:{})}};
138
138
  }
139
- export const versionOf=(cli,policy)=>cli?probeCliVersion(cli,{timeoutMs:policy.probeTimeoutMs,policy}):{version:null,supported:false,reason:'cli_not_found'};
139
+ export const versionOf=(cli,policy)=>cli?probeCliVersion(cli,{timeoutMs:policy.probeTimeoutMs}):{version:null,reason:'cli_not_found'};
140
140
  export async function readRevision(homes){
141
141
  const bytes=await readStable(path.join(homes.codex,'arc-role-platform-routing.json'),[]);
142
142
  return parseRoleRoutingConfig(bytes.toString('utf8')).revision;
@@ -194,7 +194,6 @@ export async function prepareRoleDispatch({context,assignment,expectedRevision,n
194
194
  if(authentication.status!=='Available')codes.add(authentication.status);
195
195
  if(route==='bridge'){
196
196
  result.cliVersion=await versionOf(cli,policy);
197
- if(cli&&!result.cliVersion.supported)codes.add('permission_scope_unverified');
198
197
  }
199
198
  for(const code of environmentReasons(environment,policy))codes.add(code);
200
199
  const leases=await listLeases(homes.codex);
@@ -1,38 +0,0 @@
1
- import fs from 'node:fs/promises';
2
- import path from 'node:path';
3
- import crypto from 'node:crypto';
4
- import {validateCooperativeCommand,validateCooperativeState} from './cooperative-schema.mjs';
5
- import {observeCooperativeTarget,validateObservedTarget,validateWorkflowId,workflowStatePath,inspectPath} from './scope.mjs';
6
- import {saveDurableState} from './store.mjs';
7
- export const COOPERATIVE_RUNTIME_MODULES=Object.freeze([
8
- 'cli.mjs','command.mjs','bootstrap.mjs','cooperative-schema.mjs','cooperative.mjs','evaluate.mjs',
9
- 'scope.mjs','store.mjs','git-evidence.mjs','assignment.mjs','verification.mjs','acceptance.mjs','external.mjs','schema.mjs','operations.mjs','gate.mjs','adapters/codex.mjs','adapters/claude.mjs','capabilities.mjs','identity.mjs','git-query.mjs','target-preparation.mjs',
10
- 'local-cli.mjs','role-routing-config.mjs','role-routing.mjs','role-bridge.mjs',
11
- 'role-dispatch-policy.mjs','role-dispatch-store.mjs','role-bridge-args.mjs','role-observe.mjs','role-supervisor.mjs'
12
- ]);
13
- export const cooperativeCoverage=()=>({enforcement:'cooperative',provenance:'operator-attested',nativeVerified:false});
14
- export function commandResult({workflowId,state,input,decision='allow',ruleId='cooperative.recorded',persisted=false,...extra}){
15
- return {decision,ruleIds:[ruleId],workflowId,taskId:input?.taskId??null,requestId:input?.requestId??null,revision:state?.revision??0,coverage:cooperativeCoverage(),requiredEvidence:[],nextActions:[],persisted,...extra};
16
- }
17
- export async function cooperativeVersions(){
18
- const hash=bytes=>'sha256:'+crypto.createHash('sha256').update(bytes).digest('hex');
19
- let policy;try{policy=await fs.readFile(new URL('../policy/role-policy.json',import.meta.url));}catch(error){if(error.code!=='ENOENT')throw error;policy=await fs.readFile(new URL('./role-policy.json',import.meta.url));}
20
- const runtime=await Promise.all(COOPERATIVE_RUNTIME_MODULES.map(file=>fs.readFile(new URL(file,import.meta.url))));
21
- return {policy:'1',runtime:'cooperative-8',policyHash:hash(policy),runtimeHash:hash(Buffer.concat(runtime))};
22
- }
23
- export async function initializeCooperativeWorkflow({cwd,workflowId,input,observe=observeCooperativeTarget,storage={}}){
24
- validateWorkflowId(workflowId);validateCooperativeCommand({command:'init',input});
25
- if(input.mode!=='plan')return commandResult({workflowId,input,decision:'hold',ruleId:'cooperative.unsupported'});
26
- const target=await validateObservedTarget(cwd,await observe(cwd));const statePath=await workflowStatePath(target,workflowId);
27
- const parent=path.dirname(statePath);await fs.mkdir(parent,{recursive:true,mode:0o700});await inspectPath(parent,{directory:true});
28
- const lockPath=statePath+'.lock';let lock;
29
- try{
30
- lock=await fs.open(lockPath,'wx',0o600);await inspectPath(statePath,{missing:true});
31
- const state={schemaVersion:1,workflowKind:'cooperative',contractVersion:1,workflowId,revision:0,mode:'plan',coverage:cooperativeCoverage(),versions:await cooperativeVersions(),target,targetVersion:1,scopeVersion:0};
32
- for(const key of ['actors','selections','assignments','identities','leases','scopes','approvals','documents','tasks','requests','intents','results','checks','findings','acceptances','commits','audit','unresolved','records','targetHistory'])state[key]=[];
33
- state.plannerLedger={version:1,stages:[]};
34
- state.actors.push({actor:input.actor,source:'operator-attested'});state.selections.push({...input.selection,actor:input.actor,source:'operator-attested',targetVersion:1});
35
- state.audit.push({command:'init',revision:0,source:'operator-attested',actor:input.actor});validateCooperativeState(state);
36
- await saveDurableState({statePath,state,create:true,storage});return commandResult({workflowId,state,input,persisted:true,ruleId:'cooperative.initialized'});
37
- }finally{if(lock){await lock.close();await fs.unlink(lockPath);}}
38
- }
@@ -1,248 +0,0 @@
1
- import path from 'node:path';
2
- import fs from 'node:fs';
3
- import { StringDecoder } from 'node:string_decoder';
4
- import { spawn } from 'node:child_process';
5
- import { DEFAULT_POLICY } from './role-dispatch-policy.mjs';
6
-
7
- const environments = new WeakMap();
8
- export function resolveConfigHome(platform, { userHome, env = {}, cwd } = {}) {
9
- if (!['codex', 'claude'].includes(platform)) throw Error('Target must be codex or claude');
10
- if (typeof userHome !== 'string' || !path.isAbsolute(userHome) || !userHome.trim()) throw Error('userHome must be an absolute user directory');
11
- userHome = path.resolve(userHome);
12
- if (!env || typeof env !== 'object') throw Error('env must be an environment object');
13
- const expand = value => value === '~' ? userHome : value.startsWith('~/') ? path.join(userHome, value.slice(2)) : value;
14
- let home;
15
- if (platform === 'codex') {
16
- const raw = env.CODEX_HOME;
17
- if (raw !== undefined && (typeof raw !== 'string' || !raw.trim())) throw Error('CODEX_HOME is empty or invalid');
18
- const expanded = expand(raw ?? path.join(userHome, '.codex'));
19
- if (path.isAbsolute(expanded)) home = path.resolve(expanded);
20
- else { const base = cwd ?? process.cwd(); if (typeof base !== 'string' || !path.isAbsolute(base)) throw Error('cwd must be absolute for relative CODEX_HOME'); home = path.resolve(base, expanded); }
21
- } else {
22
- home = path.join(userHome, '.claude'); const raw = env.CLAUDE_CONFIG_DIR;
23
- if (raw !== undefined && (typeof raw !== 'string' || !raw.trim() || !path.isAbsolute(expand(raw)) || path.resolve(expand(raw)) !== home)) throw Error('CLAUDE_CONFIG_DIR must select the default ~/.claude directory');
24
- }
25
- if (home === '/' || home === userHome) throw Error('Target home must not be the filesystem or user-home root');
26
- return home;
27
- }
28
- export function resolveLocalCli(platform, { cwd, userHome, env = process.env } = {}) {
29
- if (!['codex', 'claude'].includes(platform)) return { platform, reason: 'unsupported_platform' };
30
- let home;
31
- try {
32
- if (typeof cwd !== 'string' || !path.isAbsolute(cwd) || path.resolve(cwd) !== cwd || !fs.statSync(cwd).isDirectory()) return { platform, reason: 'invalid_cwd' };
33
- home = resolveConfigHome(platform, { cwd, userHome, env });
34
- } catch { return { platform, reason: 'invalid_context' }; }
35
- const dirs = typeof env.PATH === 'string' ? env.PATH.split(path.delimiter) : [];
36
- let executable;
37
- for (const dir of dirs) {
38
- const candidate = path.resolve(cwd, dir || '.', platform);
39
- try { if (fs.statSync(candidate).isFile()) { fs.accessSync(candidate, fs.constants.X_OK); executable = candidate; break; } } catch { /* continue PATH search */ }
40
- }
41
- if (!executable) return { platform, reason: 'cli_not_found' };
42
- const context = Object.freeze({ platform, executable, cwd, configHome: home });
43
- environments.set(context, Object.freeze({ ...env, [platform === 'codex' ? 'CODEX_HOME' : 'CLAUDE_CONFIG_DIR']: home }));
44
- return context;
45
- }
46
- export function localCliEnvironment(context) { const env = environments.get(context); if (!env) throw Error('Invalid CLI context'); return { ...env }; }
47
- /** Checks Codex authentication with refresh; only a token-presence boolean survives parsing. */
48
- export async function probeCodexAuthStatus(context, { signal, timeoutMs = 10000 } = {}) {
49
- const result = (authStatus, reason) => ({ platform: 'codex', authStatus, ...(reason ? { reason } : {}) });
50
- if (!environments.has(context) || context.platform !== 'codex') return result('unknown', context?.reason ?? 'invalid_context');
51
- if (signal?.aborted) return result('unknown', 'aborted');
52
- let child;
53
- try { child = spawn(context.executable, ['app-server'], { cwd: context.cwd, env: localCliEnvironment(context), stdio: ['pipe', 'pipe', 'pipe'], shell: false }); }
54
- catch { return result('unknown', 'cli_execution_error'); }
55
- let closed = false, failure, pending, nextId = 0, buffer = '', outputBytes = 0;
56
- const decoder = new StringDecoder('utf8');
57
- let resolveClosed;
58
- const closedPromise = new Promise(resolve => { resolveClosed = resolve; });
59
- const fail = reason => { failure ??= reason; if (pending) { const {reject} = pending; pending = null; reject(); } };
60
- const onClose = () => { closed = true; resolveClosed(); fail('cli_execution_error'); };
61
- const onError = () => fail('cli_execution_error');
62
- const onAbort = () => fail('aborted');
63
- const countOutput = chunk => { outputBytes += chunk.length; if (outputBytes > 1048576) { fail('invalid_response'); return false; } return !failure; };
64
- const classify = value => {
65
- if (!value || typeof value !== 'object' || Array.isArray(value) || !(value.requiresOpenaiAuth === null || typeof value.requiresOpenaiAuth === 'boolean') ||
66
- !(value.authMethod === null || typeof value.authMethod === 'string') ||
67
- !(value.authToken === null || typeof value.authToken === 'string')) return result('unknown', 'invalid_response');
68
- const hasToken = typeof value.authToken === 'string' && value.authToken.length > 0;
69
- if (value.requiresOpenaiAuth === false || typeof value.authMethod === 'string' && hasToken) return result('authenticated');
70
- if (value.authMethod === null) return result('unauthorized', 'not_logged_in');
71
- if (value.authToken !== null) return result('unknown', 'invalid_response');
72
- if (value.authMethod === 'chatgpt') return result('unauthorized', 'token_rejected');
73
- if (['headers', 'agentIdentity', 'personalAccessToken'].includes(value.authMethod)) return result('authenticated');
74
- return result('unknown', 'auth_unverified');
75
- };
76
- const onData = chunk => {
77
- if (!countOutput(chunk)) { buffer = ''; return; }
78
- buffer += decoder.write(chunk);
79
- let newline;
80
- while (!failure && (newline = buffer.indexOf('\n')) !== -1) {
81
- let line = buffer.slice(0, newline); buffer = buffer.slice(newline + 1);
82
- if (!line.trim()) continue;
83
- let message;
84
- try { message = JSON.parse(line); } catch { line = ''; buffer = ''; fail('invalid_response'); return; }
85
- line = '';
86
- if (message && typeof message === 'object' && !Array.isArray(message) &&
87
- (Object.hasOwn(message, 'method') || !Object.hasOwn(message, 'id'))) { message = null; continue; }
88
- if (!message || !pending || message.id !== pending.id) { message = null; fail('invalid_response'); return; }
89
- if (Object.hasOwn(message, 'error')) { message = null; fail('status_command_failed'); return; }
90
- if (!Object.hasOwn(message, 'result')) { message = null; fail('invalid_response'); return; }
91
- const value = pending.method === 'initialize'
92
- ? (message.result && typeof message.result === 'object' && !Array.isArray(message.result) && typeof message.result.userAgent === 'string' && message.result.userAgent.length > 0 ? true : false)
93
- : classify(message.result);
94
- message = null;
95
- const {resolve} = pending; pending = null; resolve(value);
96
- }
97
- };
98
- const onStderr = chunk => { countOutput(chunk); };
99
- child.on('close', onClose); child.on('error', onError);
100
- child.stdout.on('data', onData); child.stderr.on('data', onStderr);
101
- for (const stream of [child.stdin, child.stdout, child.stderr]) stream.on('error', onError);
102
- signal?.addEventListener('abort', onAbort, { once: true });
103
- if (signal?.aborted) onAbort();
104
- const timer = setTimeout(() => fail('timeout'), Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : 10000);
105
- const send = message => { if (failure || closed) throw new Error('Codex authentication unavailable'); child.stdin.write(JSON.stringify(message) + '\n'); };
106
- const request = (method, params) => new Promise((resolve, reject) => {
107
- if (failure || closed) { reject(); return; }
108
- const id = ++nextId; pending = {id, method, resolve, reject};
109
- try { send({id, method, params}); } catch { fail('cli_execution_error'); }
110
- });
111
- let authentication;
112
- try {
113
- if (!await request('initialize', {clientInfo: {name: 'arc', title: 'ARC', version: '1.0.0'}})) fail('invalid_response');
114
- send({method: 'initialized', params: {}});
115
- authentication = await request('getAuthStatus', {includeToken: true, refreshToken: true});
116
- if (failure) authentication = result('unknown', failure);
117
- } catch { authentication = result('unknown', failure ?? 'cli_execution_error'); }
118
- finally {
119
- clearTimeout(timer); signal?.removeEventListener('abort', onAbort);
120
- buffer = ''; pending = null;
121
- try { child.stdin.end(); } catch { /* cleanup only */ }
122
- if (!closed) { try { child.kill('SIGTERM'); } catch { /* still wait for close */ } }
123
- const wait = async ms => {
124
- if (closed) return true;
125
- let timerId;
126
- const done = await Promise.race([closedPromise.then(() => true), new Promise(resolve => { timerId = setTimeout(() => resolve(false), ms); })]);
127
- clearTimeout(timerId); return done;
128
- };
129
- if (!await wait(1000)) {
130
- try { child.kill('SIGKILL'); } catch { /* bounded cleanup */ }
131
- if (!await wait(1000)) authentication = result('unknown', 'cli_execution_error');
132
- }
133
- child.stdout.removeListener('data', onData); child.stderr.removeListener('data', onStderr);
134
- child.removeListener('close', onClose);
135
- // Keep error guards on streams until destruction, including late pipe errors.
136
- for (const stream of [child.stdin, child.stdout, child.stderr]) stream.destroy();
137
- }
138
- return authentication;
139
- }
140
- /** Checks local Codex login state without starting app-server or refreshing credentials. */
141
- export async function probeCodexLoginStatus(context, { signal, timeoutMs = 10000 } = {}) {
142
- const result = (authStatus, reason) => ({ platform: 'codex', authStatus, ...(reason ? { reason } : {}) });
143
- if (!environments.has(context) || context.platform !== 'codex') return result('unknown', context?.reason ?? 'invalid_context');
144
- if (signal?.aborted) return result('unknown', 'aborted');
145
- let child;
146
- try { child = spawn(context.executable, ['login', 'status'], { cwd: context.cwd, env: localCliEnvironment(context), stdio: ['ignore', 'pipe', 'pipe'], shell: false }); }
147
- catch { return result('unknown', 'status_command_failed'); }
148
- let closed = false, stderr = '', outputBytes = 0, timer, resolveClosed;
149
- const closedPromise = new Promise(resolve => { resolveClosed = resolve; });
150
- let finish;
151
- const authentication = new Promise(resolve => { finish = resolve; });
152
- const fail = reason => finish(result('unknown', reason));
153
- const onError = () => fail('status_command_failed');
154
- const onAbort = () => fail('aborted');
155
- const countOutput = chunk => {
156
- outputBytes += chunk.length;
157
- if (outputBytes > 65536) { stderr = ''; fail('status_command_failed'); return false; }
158
- return true;
159
- };
160
- const onStdout = chunk => { countOutput(chunk); };
161
- const onStderr = chunk => { if (countOutput(chunk)) stderr += chunk.toString(); };
162
- const onClose = (code, exitSignal) => {
163
- closed = true; resolveClosed();
164
- finish(exitSignal ? result('unknown', 'status_command_failed') : code === 0 ? result('authenticated') :
165
- code === 1 && stderr.trim() === 'Not logged in' ? result('unauthorized', 'not_logged_in') : result('unknown', 'status_command_failed'));
166
- };
167
- child.on('error', onError); child.on('close', onClose);
168
- child.stdout.on('data', onStdout); child.stderr.on('data', onStderr);
169
- for (const stream of [child.stdout, child.stderr]) stream.on('error', onError);
170
- signal?.addEventListener('abort', onAbort, { once: true });
171
- timer = setTimeout(() => fail('timeout'), Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : 10000);
172
- if (signal?.aborted) onAbort();
173
- const value = await authentication;
174
- clearTimeout(timer); signal?.removeEventListener('abort', onAbort);
175
- if (!closed) { try { child.kill('SIGTERM'); } catch { /* bounded cleanup */ } }
176
- const wait = async ms => {
177
- if (closed) return true;
178
- let timerId;
179
- const done = await Promise.race([closedPromise.then(() => true), new Promise(resolve => { timerId = setTimeout(() => resolve(false), ms); })]);
180
- clearTimeout(timerId); return done;
181
- };
182
- if (!await wait(1000)) {
183
- try { child.kill('SIGKILL'); } catch { /* bounded cleanup */ }
184
- await wait(1000);
185
- }
186
- child.stdout.removeListener('data', onStdout); child.stderr.removeListener('data', onStderr);
187
- child.removeListener('close', onClose);
188
- child.stdout.destroy(); child.stderr.destroy();
189
- return value;
190
- }
191
- export async function probePlatformAuth(context, { signal, timeoutMs = 10000 } = {}) {
192
- const platform = context?.platform;
193
- const result = (authStatus, reason) => ({ platform, authStatus, ...(reason ? { reason } : {}) });
194
- if (platform !== 'claude') return result('unknown', 'invalid_context');
195
- if (!environments.has(context)) return result('unknown', context?.reason ?? 'invalid_context');
196
- if (signal?.aborted) return result('unknown', 'aborted');
197
- return new Promise(resolve => {
198
- let child, output = '', stderr = '', overflow = false, done = false, reason;
199
- const finish = value => { if (done) return; done = true; clearTimeout(timer); signal?.removeEventListener('abort', abort); resolve(value); };
200
- const abort = () => { reason = 'aborted'; child?.kill(); finish(result('unknown', reason)); };
201
- const timer = setTimeout(() => { reason = 'timeout'; child?.kill(); finish(result('unknown', reason)); }, Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : 10000);
202
- signal?.addEventListener('abort', abort, { once: true });
203
- try { child = spawn(context.executable, ['auth', 'status', '--json'], { cwd: context.cwd, env: localCliEnvironment(context), stdio: ['ignore', 'pipe', 'pipe'], shell: false }); }
204
- catch { finish(result('unknown', 'cli_execution_error')); return; }
205
- child.stdout.on('data', chunk => { if (output.length + chunk.length > 65536) overflow = true; else if (!overflow) output += chunk.toString(); });
206
- child.stderr.on('data', chunk => { if (stderr.length + chunk.length > 65536) overflow = true; else if (!overflow) stderr += chunk.toString(); });
207
- child.on('error', () => finish(result('unknown', 'cli_execution_error')));
208
- child.on('close', (code, exitSignal) => {
209
- if (exitSignal || overflow) return finish(result('unknown', overflow ? 'invalid_response' : 'cli_execution_error'));
210
- let parsed; try { parsed = JSON.parse(output); } catch { return finish(result('unknown', 'invalid_response')); }
211
- if (parsed?.loggedIn === true && code === 0) return finish(result('authenticated'));
212
- if (parsed?.loggedIn === false && code === 1) return finish(result('unauthorized', 'not_logged_in'));
213
- finish(result('unknown', 'status_mismatch'));
214
- });
215
- if (signal?.aborted) abort();
216
- });
217
- }
218
- export function compareVersions(a, b) {
219
- const left = String(a).split('.').map(Number), right = String(b).split('.').map(Number);
220
- for (let i = 0; i < Math.max(left.length, right.length); i += 1) { const x = left[i] ?? 0, y = right[i] ?? 0; if (x !== y) return x < y ? -1 : 1; }
221
- return 0;
222
- }
223
- /** Runs `<cli> --version`; keeps only the parsed version, never the raw output. */
224
- export async function probeCliVersion(context, { signal, timeoutMs = 10000, policy = DEFAULT_POLICY } = {}) {
225
- const platform = context?.platform;
226
- const result = (version, supported, reason) => ({ version, supported, ...(reason ? { reason } : {}) });
227
- if (!environments.has(context) || signal?.aborted) return result(null, false, 'cli_execution_error');
228
- return new Promise(resolve => {
229
- let child, output = '', overflow = false, done = false;
230
- const finish = value => { if (done) return; done = true; clearTimeout(timer); signal?.removeEventListener('abort', abort); resolve(value); };
231
- const abort = () => { child?.kill(); finish(result(null, false, 'cli_execution_error')); };
232
- const timer = setTimeout(() => { child?.kill(); finish(result(null, false, 'timeout')); }, Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : 10000);
233
- signal?.addEventListener('abort', abort, { once: true });
234
- try { child = spawn(context.executable, ['--version'], { cwd: context.cwd, env: localCliEnvironment(context), stdio: ['ignore', 'pipe', 'pipe'], shell: false }); }
235
- catch { finish(result(null, false, 'cli_execution_error')); return; }
236
- child.stdout.on('data', chunk => { if (output.length + chunk.length > 65536) overflow = true; else if (!overflow) output += chunk.toString(); });
237
- child.stderr.on('data', chunk => { if (chunk.length > 65536) overflow = true; });
238
- child.on('error', () => finish(result(null, false, 'cli_execution_error')));
239
- child.on('close', (code, exitSignal) => {
240
- if (exitSignal || code !== 0 || overflow) return finish(result(null, false, 'cli_execution_error'));
241
- const version = /\d+\.\d+\.\d+/.exec(output)?.[0] ?? null;
242
- if (!version) return finish(result(null, false, 'version_unparsed'));
243
- const range = policy?.supportedVersions?.[platform];
244
- const supported = Boolean(range) && compareVersions(version, range.min) >= 0 && compareVersions(version, range.below) < 0;
245
- finish(supported ? result(version, true) : result(version, false, 'version_unsupported'));
246
- });
247
- });
248
- }
@@ -1,227 +0,0 @@
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
- }