@yunhozz/arc 0.2.7 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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
@@ -7,6 +7,8 @@ import {runGate} from '../gate.mjs';
7
7
  const text=v=>typeof v==='string'&&v.length>0;
8
8
  const object=v=>v!==null&&typeof v==='object'&&!Array.isArray(v);
9
9
  const supported=new Set(['Read','Glob','Grep','Bash','Write','Edit','MultiEdit','exec_command','apply_patch','Agent','spawn_agent']);
10
+ // A bridge child carries this marker; its Hook events are observation-only and never recorded.
11
+ const bridgeChild=context=>text((context?.env??process.env).ARC_BRIDGE_CHILD);
10
12
  const deny=reason=>({decision:'deny',reason,ruleIds:['runtime.codex'],proposedTransition:null});
11
13
  /** Context is a trusted host dependency, never deserialized from stdin/tool_input.
12
14
  * describeTool must parse the complete tool invocation conservatively, and supply
@@ -32,6 +34,7 @@ export function renderCodexDecision(decision){
32
34
  * timeout, hosted/specialized paths and existing write_stdin are outside it. */
33
35
  export async function runCodexGate(input,context={}){
34
36
  if(input?.hook_event_name==='SubagentStart'){
37
+ if(bridgeChild(context))return {};
35
38
  // SubagentStart cannot prevent startup. Only a trusted provider can correlate
36
39
  // agent_id with a pending assignment; tool/event agent_type is not authority.
37
40
  try{
@@ -6,7 +6,9 @@ import {observeCooperativeTarget,validateObservedTarget,validateWorkflowId,workf
6
6
  import {saveDurableState} from './store.mjs';
7
7
  export const COOPERATIVE_RUNTIME_MODULES=Object.freeze([
8
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'
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'
10
12
  ]);
11
13
  export const cooperativeCoverage=()=>({enforcement:'cooperative',provenance:'operator-attested',nativeVerified:false});
12
14
  export function commandResult({workflowId,state,input,decision='allow',ruleId='cooperative.recorded',persisted=false,...extra}){
@@ -16,7 +18,7 @@ export async function cooperativeVersions(){
16
18
  const hash=bytes=>'sha256:'+crypto.createHash('sha256').update(bytes).digest('hex');
17
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));}
18
20
  const runtime=await Promise.all(COOPERATIVE_RUNTIME_MODULES.map(file=>fs.readFile(new URL(file,import.meta.url))));
19
- return {policy:'1',runtime:'cooperative-6',policyHash:hash(policy),runtimeHash:hash(Buffer.concat(runtime))};
21
+ return {policy:'1',runtime:'cooperative-8',policyHash:hash(policy),runtimeHash:hash(Buffer.concat(runtime))};
20
22
  }
21
23
  export async function initializeCooperativeWorkflow({cwd,workflowId,input,observe=observeCooperativeTarget,storage={}}){
22
24
  validateWorkflowId(workflowId);validateCooperativeCommand({command:'init',input});
@@ -1,13 +1,19 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
+ import os from 'node:os';
3
4
  import {initializeCooperativeWorkflow,commandResult} from './bootstrap.mjs';
4
5
  import {runCooperativeCommand} from './cooperative.mjs';
5
6
  import {validateWorkflowId} from './scope.mjs';
7
+ import {prepareRoleDispatch,routingStatus,invalidRoutingRequest} from './role-routing.mjs';
8
+ import {runBridgeDispatch,recordRoleObservation,resumeRoleDispatch,cancelRoleDispatch,heldRoutingResult} from './role-bridge.mjs';
6
9
  export async function runWorkflowCommand(args,io={}){
7
- const output=io.output??process.stdout;let workflowId=null;
10
+ const output=io.output??process.stdout;let workflowId=null,isRouting=false;
8
11
  try{
9
12
  const [command,...rest]=args,options={};
10
- if(!['init','record','status','reconcile','prepare','result'].includes(command))throw Error('Expected workflow command');
13
+ isRouting=['routing-status','prepare-dispatch','run-dispatch','observe','resume','cancel'].includes(command);
14
+ if(!['init','record','status','reconcile','prepare','result'].includes(command)&&!isRouting)throw Error('Expected workflow command');
15
+ // A bridge child must not drive routing itself: the supervisor sets ARC_BRIDGE_CHILD for the child CLI process tree.
16
+ if(isRouting&&(io.env??process.env).ARC_BRIDGE_CHILD){output.write(JSON.stringify({workflowId:null,...invalidRoutingRequest({}),message:'Routing commands are not available inside a bridge child.'})+'\n');return 2;}
11
17
  for(let i=0;i<rest.length;i+=2){const key=rest[i];if(!['--cwd','--workflow','--input'].includes(key)||options[key]!==undefined||typeof rest[i+1]!=='string')throw Error('Invalid workflow option');options[key]=rest[i+1];}
12
18
  const cwd=options['--cwd'];workflowId=options['--workflow'];validateWorkflowId(workflowId);
13
19
  if(typeof cwd!=='string'||!path.isAbsolute(cwd)||path.normalize(cwd)!==cwd)throw Error('Absolute workspace required');
@@ -15,7 +21,18 @@ export async function runWorkflowCommand(args,io={}){
15
21
  // Check/review, commit and external intents are recorded for the operator.
16
22
  // Actual Git mutations remain Orchestrator actions; reconciliation observes their results.
17
23
  const input=command==='status'?undefined:JSON.parse(io.input??fs.readFileSync(0,'utf8'));
18
- const result=await(command==='init'?initializeCooperativeWorkflow({cwd,workflowId,input}):runCooperativeCommand({cwd,workflowId,command,input}));
24
+ let result;
25
+ if(isRouting){
26
+ if(!input||typeof input!=='object'||Array.isArray(input))throw Error('Invalid routing input');
27
+ const context={cwd,userHome:os.homedir(),env:process.env,workflowId,hostPlatform:input.hostPlatform,executionEnvironment:input.executionEnvironment};
28
+ const keys=Object.keys(input),allowed={'routing-status':[['hostPlatform','executionEnvironment'],[]],'prepare-dispatch':[['hostPlatform','executionEnvironment','role','expectedRevision','requestId','taskId'],['allowedPaths']],'run-dispatch':[['hostPlatform','executionEnvironment','dispatchId','brief'],[]],observe:[['hostPlatform','executionEnvironment','dispatchId'],['waitMs','event','nativeAgentId']],resume:[['hostPlatform','executionEnvironment','dispatchId','brief'],[]],cancel:[['hostPlatform','executionEnvironment','dispatchId'],[]]}[command];
29
+ if(allowed&&(allowed[0].some(key=>!Object.hasOwn(input,key))||keys.some(key=>!allowed[0].includes(key)&&!allowed[1].includes(key))))result=invalidRoutingRequest(context);
30
+ else result=command==='routing-status'?await routingStatus({context}):command==='prepare-dispatch'?await prepareRoleDispatch({context,assignment:{role:input.role,requestId:input.requestId,taskId:input.taskId,...(Object.hasOwn(input,'allowedPaths')?{allowedPaths:input.allowedPaths}:{})},expectedRevision:input.expectedRevision}):command==='run-dispatch'?await runBridgeDispatch({context,dispatchId:input.dispatchId,brief:input.brief}):command==='observe'?await recordRoleObservation({context,dispatchId:input.dispatchId,...(Object.hasOwn(input,'waitMs')?{waitMs:input.waitMs}:{}),...(Object.hasOwn(input,'event')?{event:input.event}:{}),...(Object.hasOwn(input,'nativeAgentId')?{nativeAgentId:input.nativeAgentId}:{})}):command==='resume'?await resumeRoleDispatch({context,dispatchId:input.dispatchId,brief:input.brief}):await cancelRoleDispatch({context,dispatchId:input.dispatchId});
31
+ result={workflowId,...result};
32
+ }else result=await(command==='init'?initializeCooperativeWorkflow({cwd,workflowId,input}):runCooperativeCommand({cwd,workflowId,command,input}));
19
33
  output.write(JSON.stringify(result)+'\n');return result.decision==='deny'?2:result.decision==='hold'?3:0;
20
- }catch(error){output.write(JSON.stringify(commandResult({workflowId,decision:'hold',ruleId:'cooperative.error',error:error.message}))+'\n');return 1;}
34
+ }catch(error){
35
+ const result=isRouting?{workflowId:null,...heldRoutingResult('activation_unverified','Provide a valid routing request and verify the active configuration and installed markers.')}:commandResult({workflowId,decision:'hold',ruleId:'cooperative.error',error:error.message});
36
+ output.write(JSON.stringify(result)+'\n');return 1;
37
+ }
21
38
  }
@@ -0,0 +1,248 @@
1
+ import path from 'node:path';
2
+ import fs from 'node:fs';
3
+ import { StringDecoder } from 'node:string_decoder';
4
+ import { spawn } from 'node:child_process';
5
+ import { DEFAULT_POLICY } from './role-dispatch-policy.mjs';
6
+
7
+ const environments = new WeakMap();
8
+ export function resolveConfigHome(platform, { userHome, env = {}, cwd } = {}) {
9
+ if (!['codex', 'claude'].includes(platform)) throw Error('Target must be codex or claude');
10
+ if (typeof userHome !== 'string' || !path.isAbsolute(userHome) || !userHome.trim()) throw Error('userHome must be an absolute user directory');
11
+ userHome = path.resolve(userHome);
12
+ if (!env || typeof env !== 'object') throw Error('env must be an environment object');
13
+ const expand = value => value === '~' ? userHome : value.startsWith('~/') ? path.join(userHome, value.slice(2)) : value;
14
+ let home;
15
+ if (platform === 'codex') {
16
+ const raw = env.CODEX_HOME;
17
+ if (raw !== undefined && (typeof raw !== 'string' || !raw.trim())) throw Error('CODEX_HOME is empty or invalid');
18
+ const expanded = expand(raw ?? path.join(userHome, '.codex'));
19
+ if (path.isAbsolute(expanded)) home = path.resolve(expanded);
20
+ else { const base = cwd ?? process.cwd(); if (typeof base !== 'string' || !path.isAbsolute(base)) throw Error('cwd must be absolute for relative CODEX_HOME'); home = path.resolve(base, expanded); }
21
+ } else {
22
+ home = path.join(userHome, '.claude'); const raw = env.CLAUDE_CONFIG_DIR;
23
+ if (raw !== undefined && (typeof raw !== 'string' || !raw.trim() || !path.isAbsolute(expand(raw)) || path.resolve(expand(raw)) !== home)) throw Error('CLAUDE_CONFIG_DIR must select the default ~/.claude directory');
24
+ }
25
+ if (home === '/' || home === userHome) throw Error('Target home must not be the filesystem or user-home root');
26
+ return home;
27
+ }
28
+ export function resolveLocalCli(platform, { cwd, userHome, env = process.env } = {}) {
29
+ if (!['codex', 'claude'].includes(platform)) return { platform, reason: 'unsupported_platform' };
30
+ let home;
31
+ try {
32
+ if (typeof cwd !== 'string' || !path.isAbsolute(cwd) || path.resolve(cwd) !== cwd || !fs.statSync(cwd).isDirectory()) return { platform, reason: 'invalid_cwd' };
33
+ home = resolveConfigHome(platform, { cwd, userHome, env });
34
+ } catch { return { platform, reason: 'invalid_context' }; }
35
+ const dirs = typeof env.PATH === 'string' ? env.PATH.split(path.delimiter) : [];
36
+ let executable;
37
+ for (const dir of dirs) {
38
+ const candidate = path.resolve(cwd, dir || '.', platform);
39
+ try { if (fs.statSync(candidate).isFile()) { fs.accessSync(candidate, fs.constants.X_OK); executable = candidate; break; } } catch { /* continue PATH search */ }
40
+ }
41
+ if (!executable) return { platform, reason: 'cli_not_found' };
42
+ const context = Object.freeze({ platform, executable, cwd, configHome: home });
43
+ environments.set(context, Object.freeze({ ...env, [platform === 'codex' ? 'CODEX_HOME' : 'CLAUDE_CONFIG_DIR']: home }));
44
+ return context;
45
+ }
46
+ export function localCliEnvironment(context) { const env = environments.get(context); if (!env) throw Error('Invalid CLI context'); return { ...env }; }
47
+ /** Checks Codex authentication with refresh; only a token-presence boolean survives parsing. */
48
+ export async function probeCodexAuthStatus(context, { signal, timeoutMs = 10000 } = {}) {
49
+ const result = (authStatus, reason) => ({ platform: 'codex', authStatus, ...(reason ? { reason } : {}) });
50
+ if (!environments.has(context) || context.platform !== 'codex') return result('unknown', context?.reason ?? 'invalid_context');
51
+ if (signal?.aborted) return result('unknown', 'aborted');
52
+ let child;
53
+ try { child = spawn(context.executable, ['app-server'], { cwd: context.cwd, env: localCliEnvironment(context), stdio: ['pipe', 'pipe', 'pipe'], shell: false }); }
54
+ catch { return result('unknown', 'cli_execution_error'); }
55
+ let closed = false, failure, pending, nextId = 0, buffer = '', outputBytes = 0;
56
+ const decoder = new StringDecoder('utf8');
57
+ let resolveClosed;
58
+ const closedPromise = new Promise(resolve => { resolveClosed = resolve; });
59
+ const fail = reason => { failure ??= reason; if (pending) { const {reject} = pending; pending = null; reject(); } };
60
+ const onClose = () => { closed = true; resolveClosed(); fail('cli_execution_error'); };
61
+ const onError = () => fail('cli_execution_error');
62
+ const onAbort = () => fail('aborted');
63
+ const countOutput = chunk => { outputBytes += chunk.length; if (outputBytes > 1048576) { fail('invalid_response'); return false; } return !failure; };
64
+ const classify = value => {
65
+ if (!value || typeof value !== 'object' || Array.isArray(value) || !(value.requiresOpenaiAuth === null || typeof value.requiresOpenaiAuth === 'boolean') ||
66
+ !(value.authMethod === null || typeof value.authMethod === 'string') ||
67
+ !(value.authToken === null || typeof value.authToken === 'string')) return result('unknown', 'invalid_response');
68
+ const hasToken = typeof value.authToken === 'string' && value.authToken.length > 0;
69
+ if (value.requiresOpenaiAuth === false || typeof value.authMethod === 'string' && hasToken) return result('authenticated');
70
+ if (value.authMethod === null) return result('unauthorized', 'not_logged_in');
71
+ if (value.authToken !== null) return result('unknown', 'invalid_response');
72
+ if (value.authMethod === 'chatgpt') return result('unauthorized', 'token_rejected');
73
+ if (['headers', 'agentIdentity', 'personalAccessToken'].includes(value.authMethod)) return result('authenticated');
74
+ return result('unknown', 'auth_unverified');
75
+ };
76
+ const onData = chunk => {
77
+ if (!countOutput(chunk)) { buffer = ''; return; }
78
+ buffer += decoder.write(chunk);
79
+ let newline;
80
+ while (!failure && (newline = buffer.indexOf('\n')) !== -1) {
81
+ let line = buffer.slice(0, newline); buffer = buffer.slice(newline + 1);
82
+ if (!line.trim()) continue;
83
+ let message;
84
+ try { message = JSON.parse(line); } catch { line = ''; buffer = ''; fail('invalid_response'); return; }
85
+ line = '';
86
+ if (message && typeof message === 'object' && !Array.isArray(message) &&
87
+ (Object.hasOwn(message, 'method') || !Object.hasOwn(message, 'id'))) { message = null; continue; }
88
+ if (!message || !pending || message.id !== pending.id) { message = null; fail('invalid_response'); return; }
89
+ if (Object.hasOwn(message, 'error')) { message = null; fail('status_command_failed'); return; }
90
+ if (!Object.hasOwn(message, 'result')) { message = null; fail('invalid_response'); return; }
91
+ const value = pending.method === 'initialize'
92
+ ? (message.result && typeof message.result === 'object' && !Array.isArray(message.result) && typeof message.result.userAgent === 'string' && message.result.userAgent.length > 0 ? true : false)
93
+ : classify(message.result);
94
+ message = null;
95
+ const {resolve} = pending; pending = null; resolve(value);
96
+ }
97
+ };
98
+ const onStderr = chunk => { countOutput(chunk); };
99
+ child.on('close', onClose); child.on('error', onError);
100
+ child.stdout.on('data', onData); child.stderr.on('data', onStderr);
101
+ for (const stream of [child.stdin, child.stdout, child.stderr]) stream.on('error', onError);
102
+ signal?.addEventListener('abort', onAbort, { once: true });
103
+ if (signal?.aborted) onAbort();
104
+ const timer = setTimeout(() => fail('timeout'), Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : 10000);
105
+ const send = message => { if (failure || closed) throw new Error('Codex authentication unavailable'); child.stdin.write(JSON.stringify(message) + '\n'); };
106
+ const request = (method, params) => new Promise((resolve, reject) => {
107
+ if (failure || closed) { reject(); return; }
108
+ const id = ++nextId; pending = {id, method, resolve, reject};
109
+ try { send({id, method, params}); } catch { fail('cli_execution_error'); }
110
+ });
111
+ let authentication;
112
+ try {
113
+ if (!await request('initialize', {clientInfo: {name: 'arc', title: 'ARC', version: '1.0.0'}})) fail('invalid_response');
114
+ send({method: 'initialized', params: {}});
115
+ authentication = await request('getAuthStatus', {includeToken: true, refreshToken: true});
116
+ if (failure) authentication = result('unknown', failure);
117
+ } catch { authentication = result('unknown', failure ?? 'cli_execution_error'); }
118
+ finally {
119
+ clearTimeout(timer); signal?.removeEventListener('abort', onAbort);
120
+ buffer = ''; pending = null;
121
+ try { child.stdin.end(); } catch { /* cleanup only */ }
122
+ if (!closed) { try { child.kill('SIGTERM'); } catch { /* still wait for close */ } }
123
+ const wait = async ms => {
124
+ if (closed) return true;
125
+ let timerId;
126
+ const done = await Promise.race([closedPromise.then(() => true), new Promise(resolve => { timerId = setTimeout(() => resolve(false), ms); })]);
127
+ clearTimeout(timerId); return done;
128
+ };
129
+ if (!await wait(1000)) {
130
+ try { child.kill('SIGKILL'); } catch { /* bounded cleanup */ }
131
+ if (!await wait(1000)) authentication = result('unknown', 'cli_execution_error');
132
+ }
133
+ child.stdout.removeListener('data', onData); child.stderr.removeListener('data', onStderr);
134
+ child.removeListener('close', onClose);
135
+ // Keep error guards on streams until destruction, including late pipe errors.
136
+ for (const stream of [child.stdin, child.stdout, child.stderr]) stream.destroy();
137
+ }
138
+ return authentication;
139
+ }
140
+ /** Checks local Codex login state without starting app-server or refreshing credentials. */
141
+ export async function probeCodexLoginStatus(context, { signal, timeoutMs = 10000 } = {}) {
142
+ const result = (authStatus, reason) => ({ platform: 'codex', authStatus, ...(reason ? { reason } : {}) });
143
+ if (!environments.has(context) || context.platform !== 'codex') return result('unknown', context?.reason ?? 'invalid_context');
144
+ if (signal?.aborted) return result('unknown', 'aborted');
145
+ let child;
146
+ try { child = spawn(context.executable, ['login', 'status'], { cwd: context.cwd, env: localCliEnvironment(context), stdio: ['ignore', 'pipe', 'pipe'], shell: false }); }
147
+ catch { return result('unknown', 'status_command_failed'); }
148
+ let closed = false, stderr = '', outputBytes = 0, timer, resolveClosed;
149
+ const closedPromise = new Promise(resolve => { resolveClosed = resolve; });
150
+ let finish;
151
+ const authentication = new Promise(resolve => { finish = resolve; });
152
+ const fail = reason => finish(result('unknown', reason));
153
+ const onError = () => fail('status_command_failed');
154
+ const onAbort = () => fail('aborted');
155
+ const countOutput = chunk => {
156
+ outputBytes += chunk.length;
157
+ if (outputBytes > 65536) { stderr = ''; fail('status_command_failed'); return false; }
158
+ return true;
159
+ };
160
+ const onStdout = chunk => { countOutput(chunk); };
161
+ const onStderr = chunk => { if (countOutput(chunk)) stderr += chunk.toString(); };
162
+ const onClose = (code, exitSignal) => {
163
+ closed = true; resolveClosed();
164
+ finish(exitSignal ? result('unknown', 'status_command_failed') : code === 0 ? result('authenticated') :
165
+ code === 1 && stderr.trim() === 'Not logged in' ? result('unauthorized', 'not_logged_in') : result('unknown', 'status_command_failed'));
166
+ };
167
+ child.on('error', onError); child.on('close', onClose);
168
+ child.stdout.on('data', onStdout); child.stderr.on('data', onStderr);
169
+ for (const stream of [child.stdout, child.stderr]) stream.on('error', onError);
170
+ signal?.addEventListener('abort', onAbort, { once: true });
171
+ timer = setTimeout(() => fail('timeout'), Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : 10000);
172
+ if (signal?.aborted) onAbort();
173
+ const value = await authentication;
174
+ clearTimeout(timer); signal?.removeEventListener('abort', onAbort);
175
+ if (!closed) { try { child.kill('SIGTERM'); } catch { /* bounded cleanup */ } }
176
+ const wait = async ms => {
177
+ if (closed) return true;
178
+ let timerId;
179
+ const done = await Promise.race([closedPromise.then(() => true), new Promise(resolve => { timerId = setTimeout(() => resolve(false), ms); })]);
180
+ clearTimeout(timerId); return done;
181
+ };
182
+ if (!await wait(1000)) {
183
+ try { child.kill('SIGKILL'); } catch { /* bounded cleanup */ }
184
+ await wait(1000);
185
+ }
186
+ child.stdout.removeListener('data', onStdout); child.stderr.removeListener('data', onStderr);
187
+ child.removeListener('close', onClose);
188
+ child.stdout.destroy(); child.stderr.destroy();
189
+ return value;
190
+ }
191
+ export async function probePlatformAuth(context, { signal, timeoutMs = 10000 } = {}) {
192
+ const platform = context?.platform;
193
+ const result = (authStatus, reason) => ({ platform, authStatus, ...(reason ? { reason } : {}) });
194
+ if (platform !== 'claude') return result('unknown', 'invalid_context');
195
+ if (!environments.has(context)) return result('unknown', context?.reason ?? 'invalid_context');
196
+ if (signal?.aborted) return result('unknown', 'aborted');
197
+ return new Promise(resolve => {
198
+ let child, output = '', stderr = '', overflow = false, done = false, reason;
199
+ const finish = value => { if (done) return; done = true; clearTimeout(timer); signal?.removeEventListener('abort', abort); resolve(value); };
200
+ const abort = () => { reason = 'aborted'; child?.kill(); finish(result('unknown', reason)); };
201
+ const timer = setTimeout(() => { reason = 'timeout'; child?.kill(); finish(result('unknown', reason)); }, Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : 10000);
202
+ signal?.addEventListener('abort', abort, { once: true });
203
+ try { child = spawn(context.executable, ['auth', 'status', '--json'], { cwd: context.cwd, env: localCliEnvironment(context), stdio: ['ignore', 'pipe', 'pipe'], shell: false }); }
204
+ catch { finish(result('unknown', 'cli_execution_error')); return; }
205
+ child.stdout.on('data', chunk => { if (output.length + chunk.length > 65536) overflow = true; else if (!overflow) output += chunk.toString(); });
206
+ child.stderr.on('data', chunk => { if (stderr.length + chunk.length > 65536) overflow = true; else if (!overflow) stderr += chunk.toString(); });
207
+ child.on('error', () => finish(result('unknown', 'cli_execution_error')));
208
+ child.on('close', (code, exitSignal) => {
209
+ if (exitSignal || overflow) return finish(result('unknown', overflow ? 'invalid_response' : 'cli_execution_error'));
210
+ let parsed; try { parsed = JSON.parse(output); } catch { return finish(result('unknown', 'invalid_response')); }
211
+ if (parsed?.loggedIn === true && code === 0) return finish(result('authenticated'));
212
+ if (parsed?.loggedIn === false && code === 1) return finish(result('unauthorized', 'not_logged_in'));
213
+ finish(result('unknown', 'status_mismatch'));
214
+ });
215
+ if (signal?.aborted) abort();
216
+ });
217
+ }
218
+ export function compareVersions(a, b) {
219
+ const left = String(a).split('.').map(Number), right = String(b).split('.').map(Number);
220
+ for (let i = 0; i < Math.max(left.length, right.length); i += 1) { const x = left[i] ?? 0, y = right[i] ?? 0; if (x !== y) return x < y ? -1 : 1; }
221
+ return 0;
222
+ }
223
+ /** Runs `<cli> --version`; keeps only the parsed version, never the raw output. */
224
+ export async function probeCliVersion(context, { signal, timeoutMs = 10000, policy = DEFAULT_POLICY } = {}) {
225
+ const platform = context?.platform;
226
+ const result = (version, supported, reason) => ({ version, supported, ...(reason ? { reason } : {}) });
227
+ if (!environments.has(context) || signal?.aborted) return result(null, false, 'cli_execution_error');
228
+ return new Promise(resolve => {
229
+ let child, output = '', overflow = false, done = false;
230
+ const finish = value => { if (done) return; done = true; clearTimeout(timer); signal?.removeEventListener('abort', abort); resolve(value); };
231
+ const abort = () => { child?.kill(); finish(result(null, false, 'cli_execution_error')); };
232
+ const timer = setTimeout(() => { child?.kill(); finish(result(null, false, 'timeout')); }, Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : 10000);
233
+ signal?.addEventListener('abort', abort, { once: true });
234
+ try { child = spawn(context.executable, ['--version'], { cwd: context.cwd, env: localCliEnvironment(context), stdio: ['ignore', 'pipe', 'pipe'], shell: false }); }
235
+ catch { finish(result(null, false, 'cli_execution_error')); return; }
236
+ child.stdout.on('data', chunk => { if (output.length + chunk.length > 65536) overflow = true; else if (!overflow) output += chunk.toString(); });
237
+ child.stderr.on('data', chunk => { if (chunk.length > 65536) overflow = true; });
238
+ child.on('error', () => finish(result(null, false, 'cli_execution_error')));
239
+ child.on('close', (code, exitSignal) => {
240
+ if (exitSignal || code !== 0 || overflow) return finish(result(null, false, 'cli_execution_error'));
241
+ const version = /\d+\.\d+\.\d+/.exec(output)?.[0] ?? null;
242
+ if (!version) return finish(result(null, false, 'version_unparsed'));
243
+ const range = policy?.supportedVersions?.[platform];
244
+ const supported = Boolean(range) && compareVersions(version, range.min) >= 0 && compareVersions(version, range.below) < 0;
245
+ finish(supported ? result(version, true) : result(version, false, 'version_unsupported'));
246
+ });
247
+ });
248
+ }
@@ -0,0 +1,148 @@
1
+ // Pure helpers that turn an installed arc-routing profile into role-specific Claude/Codex CLI arguments. No processes are started here.
2
+ import crypto from 'node:crypto';
3
+ import path from 'node:path';
4
+ import {DEFAULT_POLICY, effectiveClaudeSandboxSettings} from './role-dispatch-policy.mjs';
5
+
6
+ const ROLES = ['arc_scouter', 'arc_planner', 'arc_implementer', 'arc_qa', 'arc_reviewer'];
7
+ const deepFreeze = value => { for (const child of Object.values(value)) if (child && typeof child === 'object') deepFreeze(child); return Object.freeze(value); };
8
+ export const ROLE_BRIDGE_PERMISSIONS = deepFreeze({
9
+ claude: {
10
+ arc_scouter: {permissionMode: 'default', sandbox: false}, arc_planner: {permissionMode: 'default', sandbox: false},
11
+ arc_implementer: {permissionMode: 'acceptEdits', sandbox: true}, arc_qa: {permissionMode: 'default', sandbox: true}, arc_reviewer: {permissionMode: 'default', sandbox: false}
12
+ },
13
+ codex: {
14
+ arc_scouter: {sandboxMode: 'read-only', search: true}, arc_planner: {sandboxMode: 'read-only', search: false},
15
+ arc_implementer: {sandboxMode: 'workspace-write', search: false}, arc_qa: {sandboxMode: 'workspace-write', search: false}, arc_reviewer: {sandboxMode: 'read-only', search: false}
16
+ }
17
+ });
18
+
19
+ const bad = message => { throw Error(`Invalid composite profile: ${message}`); };
20
+ const unquote = raw => {
21
+ const value = raw.trim();
22
+ if (/^"(?:[^"\\]|\\.)*"$/.test(value)) { try { return JSON.parse(value); } catch { bad('unsupported string escape'); } }
23
+ if (/^'[^']*'$/.test(value)) return value.slice(1, -1);
24
+ return value;
25
+ };
26
+
27
+ function parseClaude(text) {
28
+ const lines = text.split('\n').map(line => line.replace(/\r$/, ''));
29
+ if (lines[0] !== '---') bad('missing frontmatter');
30
+ const end = lines.indexOf('---', 1);
31
+ if (end < 0) bad('unterminated frontmatter');
32
+ const fields = {}; let tools = null, inTools = false;
33
+ for (const line of lines.slice(1, end)) {
34
+ const item = /^[ \t]+-[ \t]+(\S.*?)[ \t]*$/.exec(line);
35
+ if (item) { if (!inTools) bad('unexpected list item'); tools.push(unquote(item[1])); continue; }
36
+ const field = /^([A-Za-z][A-Za-z0-9_-]*):[ \t]*(.*?)[ \t]*$/.exec(line);
37
+ if (!field) { if (line.trim() === '') continue; bad('unrecognized frontmatter line'); }
38
+ inTools = false;
39
+ if (field[1] === 'tools') { if (field[2] !== '') bad('tools must be a block list'); if (tools !== null) bad('duplicate tools'); tools = []; inTools = true; continue; }
40
+ if (Object.hasOwn(fields, field[1])) bad(`duplicate ${field[1]}`);
41
+ fields[field[1]] = unquote(field[2]);
42
+ }
43
+ for (const key of ['name', 'description', 'model', 'effort']) if (typeof fields[key] !== 'string' || fields[key] === '') bad(`missing ${key}`);
44
+ if (tools !== null && tools.length === 0) bad('empty tools');
45
+ const instructions = lines.slice(end + 1).join('\n');
46
+ if (instructions.trim() === '') bad('empty instructions');
47
+ return {name: fields.name, description: fields.description, model: fields.model, effort: fields.effort, tools, instructions};
48
+ }
49
+
50
+ const ESCAPES = {b: '\b', t: '\t', n: '\n', f: '\f', r: '\r', '"': '"', '\\': '\\'};
51
+ // Decodes a TOML multiline basic string body; returns null when it is not terminated by """ on the same logical line.
52
+ function readMultiline(lines, index, rest) {
53
+ let out = '', buffer = rest, line = index;
54
+ for (;;) {
55
+ for (let i = 0; i < buffer.length; i++) {
56
+ const ch = buffer[i];
57
+ if (ch === '"' && buffer.startsWith('"""', i)) {
58
+ if (!/^(?:"{0,2})[ \t]*(?:#.*)?$/.test(buffer.slice(i + 3))) bad('unsupported developer_instructions terminator');
59
+ return {value: out + buffer.slice(i + 3).match(/^"*/)[0], next: line + 1};
60
+ }
61
+ if (ch !== '\\') { out += ch; continue; }
62
+ const next = buffer[i + 1];
63
+ if (next === undefined) { // line-ending backslash trims following whitespace and newlines
64
+ let j = line + 1; while (j < lines.length && /^[ \t]*$/.test(lines[j])) j++;
65
+ if (j >= lines.length) bad('unterminated developer_instructions');
66
+ out += ''; buffer = lines[j].replace(/^[ \t]+/, ''); line = j; i = -1; continue;
67
+ }
68
+ if (Object.hasOwn(ESCAPES, next)) { out += ESCAPES[next]; i++; continue; }
69
+ const width = next === 'u' ? 4 : next === 'U' ? 8 : 0, hex = buffer.slice(i + 2, i + 2 + width);
70
+ if (!width || !new RegExp(`^[0-9A-Fa-f]{${width}}$`).test(hex)) bad('invalid escape in developer_instructions');
71
+ try { out += String.fromCodePoint(parseInt(hex, 16)); } catch { bad('invalid code point in developer_instructions'); }
72
+ i += 1 + width;
73
+ }
74
+ line++;
75
+ if (line >= lines.length) bad('unterminated developer_instructions');
76
+ out += '\n'; buffer = lines[line];
77
+ }
78
+ }
79
+ function parseCodex(text) {
80
+ const lines = text.split('\n').map(line => line.replace(/\r$/, '')), fields = {};
81
+ let instructions = null;
82
+ for (let i = 0; i < lines.length; i++) {
83
+ const line = lines[i];
84
+ if (/^[ \t]*\[/.test(line)) break;
85
+ const multi = /^developer_instructions[ \t]*=[ \t]*"""(.*)$/.exec(line);
86
+ if (multi) {
87
+ if (instructions !== null) bad('duplicate developer_instructions');
88
+ const rest = multi[1], result = readMultiline(lines, i, rest === '' ? '' : rest);
89
+ // A newline directly after the opening delimiter is trimmed; readMultiline starts at an empty remainder, so skip that join.
90
+ instructions = rest === '' ? result.value.replace(/^\n/, '') : result.value; i = result.next - 1; continue;
91
+ }
92
+ if (/^developer_instructions[ \t]*=/.test(line)) bad('developer_instructions must be a multiline string');
93
+ const single = /^(name|description|model|model_reasoning_effort)[ \t]*=[ \t]*("(?:[^"\\]|\\.)*")[ \t]*(?:#.*)?$/.exec(line);
94
+ if (single) { if (Object.hasOwn(fields, single[1])) bad(`duplicate ${single[1]}`); fields[single[1]] = unquote(single[2]); continue; }
95
+ if (/^(name|description|model|model_reasoning_effort)[ \t]*=/.test(line)) bad(`${line.split('=')[0].trim()} must be a one-line string`);
96
+ }
97
+ for (const key of ['name', 'description', 'model', 'model_reasoning_effort']) if (typeof fields[key] !== 'string' || fields[key] === '') bad(`missing ${key}`);
98
+ if (instructions === null || instructions.trim() === '') bad('missing developer_instructions');
99
+ return {name: fields.name, description: fields.description, model: fields.model, effort: fields.model_reasoning_effort, tools: null, instructions};
100
+ }
101
+
102
+ /** Narrow extractor: the installed runtime cannot import lib/models, so only the managed profile shapes are accepted. */
103
+ export function parseCompositeProfile(platform, bytes) {
104
+ if (platform !== 'claude' && platform !== 'codex') bad('unknown platform');
105
+ const buffer = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes ?? '');
106
+ let text;
107
+ try { text = new TextDecoder('utf-8', {fatal: true}).decode(buffer); } catch { bad('not valid UTF-8'); }
108
+ if (text.charCodeAt(0) === 0xfeff) bad('unexpected BOM');
109
+ return platform === 'claude' ? parseClaude(text) : parseCodex(text);
110
+ }
111
+
112
+ const permissionsFor = (platform, role) => {
113
+ if (!ROLES.includes(role)) throw Error(`Unknown role: ${role}`);
114
+ return ROLE_BRIDGE_PERMISSIONS[platform][role];
115
+ };
116
+ const requireText = (value, label) => { if (typeof value !== 'string' || value === '') throw Error(`Missing ${label}`); return value; };
117
+
118
+ export function buildClaudeArgs({role, profile, sessionId = null, policy = DEFAULT_POLICY}) {
119
+ const permissions = permissionsFor('claude', role);
120
+ if (!Array.isArray(profile?.tools) || profile.tools.length === 0) throw Error('Claude profile tools are required');
121
+ const args = ['-p', '--safe-mode', '--output-format', 'stream-json', '--verbose', '--model', requireText(profile.model, 'model'), '--effort', requireText(profile.effort, 'effort'),
122
+ '--append-system-prompt', requireText(profile.instructions, 'instructions'), '--tools', profile.tools.join(','), '--permission-mode', permissions.permissionMode];
123
+ if (permissions.sandbox) {
124
+ const settings = effectiveClaudeSandboxSettings(policy);
125
+ if (settings === null) throw Error('Claude sandbox settings are not available for this role');
126
+ args.push('--settings', JSON.stringify(settings));
127
+ }
128
+ if (policy?.gates?.G6 === 'strict') args.push('--strict-mcp-config');
129
+ if (sessionId !== null) args.push('--resume', requireText(sessionId, 'sessionId'));
130
+ return args;
131
+ }
132
+
133
+ export function buildCodexArgs({role, profile, worktree, resultPath, threadId = null, policy = DEFAULT_POLICY}) {
134
+ void policy;
135
+ const permissions = permissionsFor('codex', role);
136
+ if (typeof resultPath !== 'string' || !path.isAbsolute(resultPath)) throw Error('Absolute resultPath required');
137
+ const settings = ['-m', requireText(profile?.model, 'model'), '-c', `model_reasoning_effort=${JSON.stringify(requireText(profile.effort, 'effort'))}`,
138
+ '-c', `developer_instructions=${JSON.stringify(requireText(profile.instructions, 'instructions'))}`, '-c', `sandbox_mode=${JSON.stringify(permissions.sandboxMode)}`,
139
+ '-c', 'approval_policy="never"', '-o', resultPath, '-'];
140
+ if (threadId !== null) {
141
+ if (typeof threadId !== 'string' || !/^[A-Za-z0-9._-]+$/.test(threadId)) throw Error('Invalid threadId');
142
+ return [...(permissions.search ? ['--search'] : []), 'exec', 'resume', threadId, '--json', ...settings];
143
+ }
144
+ if (typeof worktree !== 'string' || !path.isAbsolute(worktree)) throw Error('Absolute worktree required');
145
+ return [...(permissions.search ? ['--search'] : []), 'exec', '--json', '-C', worktree, ...settings];
146
+ }
147
+
148
+ export const argsDigest = args => 'sha256:' + crypto.createHash('sha256').update(JSON.stringify(args)).digest('hex');