@yunhozz/arc 0.5.2 → 0.5.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 (35) hide show
  1. package/MANIFEST.sha256 +34 -30
  2. package/README.md +10 -1
  3. package/claude/skill/SKILL.md +1 -1
  4. package/claude/skill/references/coordination.md +6 -0
  5. package/codex/skill/SKILL.md +1 -1
  6. package/codex/skill/references/coordination.md +6 -0
  7. package/gemini/skill/SKILL.md +1 -1
  8. package/gemini/skill/references/coordination.md +6 -0
  9. package/grok/skill/SKILL.md +1 -1
  10. package/grok/skill/references/coordination.md +6 -0
  11. package/lib/installer/runtime-assets.mjs +2 -0
  12. package/lib/runtime/bootstrap.mjs +1 -1
  13. package/lib/runtime/command.mjs +2 -2
  14. package/lib/runtime/host-service.mjs +155 -0
  15. package/lib/runtime/role-bridge-args.mjs +110 -8
  16. package/lib/runtime/role-bridge.mjs +47 -20
  17. package/lib/runtime/role-dispatch-policy.mjs +9 -1
  18. package/lib/runtime/role-dispatch-store.mjs +6 -2
  19. package/lib/runtime/role-observe.mjs +7 -2
  20. package/lib/runtime/role-routing.mjs +13 -1
  21. package/lib/runtime/role-supervisor.mjs +248 -9
  22. package/lib/runtime/tool-access.mjs +560 -0
  23. package/lib/watch/watcher.mjs +46 -25
  24. package/package.json +1 -1
  25. package/shared/skill/runtime/bootstrap.mjs +1 -1
  26. package/shared/skill/runtime/command.mjs +2 -2
  27. package/shared/skill/runtime/host-service.mjs +155 -0
  28. package/shared/skill/runtime/role-bridge-args.mjs +110 -8
  29. package/shared/skill/runtime/role-bridge.mjs +47 -20
  30. package/shared/skill/runtime/role-dispatch-policy.mjs +9 -1
  31. package/shared/skill/runtime/role-dispatch-store.mjs +6 -2
  32. package/shared/skill/runtime/role-observe.mjs +7 -2
  33. package/shared/skill/runtime/role-routing.mjs +13 -1
  34. package/shared/skill/runtime/role-supervisor.mjs +248 -9
  35. package/shared/skill/runtime/tool-access.mjs +560 -0
@@ -46,7 +46,7 @@ export function createWatcher({options, homes, scope: initialScope, git, now, re
46
46
  if (item.platform != null && item.platform!==platform) continue;
47
47
  rememberStart({...item,platform},startup);
48
48
  if (item.compressed) {
49
- if (!compressed.has(item.file)) debug(out,`compressed session skipped: ${path.basename(item.file)}`);
49
+ if (platforms.includes(platform) && !compressed.has(item.file)) debug(out,`compressed session skipped: ${path.basename(item.file)}`);
50
50
  compressed.add(item.file); continue;
51
51
  }
52
52
  if ([...followed.values()].some(row=>row.file===item.file)) continue;
@@ -91,6 +91,8 @@ export function createWatcher({options, homes, scope: initialScope, git, now, re
91
91
  },
92
92
  }],
93
93
  ]);
94
+ const tracked = new Set([...TRANSCRIPT_HANDLERS.keys()].filter(platform=>homes[platform]
95
+ && (platforms.includes(platform) || registry.getPlatform(platform)?.capabilities.watch.state==='verified')));
94
96
  const stamp = () => new Date(now()).toISOString();
95
97
  const notice = text => ({v:1,ts:stamp(),observedAt:stamp(),source:'watch',label:'watch',kind:'notice',text});
96
98
  const debug = (out, text) => { if (verbose) out.push(notice(text)); };
@@ -106,12 +108,12 @@ export function createWatcher({options, homes, scope: initialScope, git, now, re
106
108
  return e;
107
109
  };
108
110
  const dispatchInScope = ref => ref.inScope && (ref.cwd ? inScope(scope,ref.cwd)
109
- : [...followed.values()].some(row=>ref.sessionIds.includes(row.id) && cwdInScope(row.cwd)));
111
+ : [...followed.values()].some(row=>!row.hidden && ref.sessionIds.includes(row.id) && cwdInScope(row.cwd)));
110
112
  function mapped(row) {
111
113
  const ref = dispatch.bySession(row.id);
112
114
  return ref && ref.inScope && (ref.cwd ? inScope(scope,ref.cwd) : cwdInScope(row.cwd)) ? ref : null;
113
115
  }
114
- const followedDispatchRow = ref => [...followed.values()].find(row=>ref.sessionIds.includes(row.id) && mapped(row)===ref);
116
+ const followedDispatchRow = ref => [...followed.values()].find(row=>!row.hidden && ref.sessionIds.includes(row.id) && mapped(row)===ref);
115
117
  function dispatchPlatforms(ref, followedRow) {
116
118
  const target = ref.targetPlatform ?? followedRow?.platform
117
119
  ?? (ref.route==='native' ? ref.hostPlatform : undefined) ?? ref.childPlatform;
@@ -173,7 +175,7 @@ export function createWatcher({options, homes, scope: initialScope, git, now, re
173
175
  row.root=await sessionRoot(cwd);
174
176
  }
175
177
  async function ensureShellRoot(row, out) {
176
- if (row.gitTop && !shellRoots.has(row.gitTop) && shellRoots.size < L.maxRepos) {
178
+ if (!row.hidden && row.gitTop && !shellRoots.has(row.gitTop) && shellRoots.size < L.maxRepos) {
177
179
  const state = {snapshot:null,pending:false,pendingSince:undefined,lastTriggerAt:-Infinity,
178
180
  lastScanAt:-Infinity,claims:new Map(),candidates:new Map(),failures:0,off:false};
179
181
  shellRoots.set(row.gitTop,state);
@@ -219,7 +221,7 @@ export function createWatcher({options, homes, scope: initialScope, git, now, re
219
221
  }
220
222
  const inside=lineGate(row), entering=row.inScopeNow===false && inside;
221
223
  if (entering) events.push(clean({...identity(row),ts:line.timestamp??stamp(),kind:'session',text:sessionText(row)}));
222
- if (row.inScopeNow===true && !inside) debug(out,`session ${row.id.slice(0,8)} left scope: cwd=${row.cwd}`);
224
+ if (!row.hidden && row.inScopeNow===true && !inside) debug(out,`session ${row.id.slice(0,8)} left scope: cwd=${row.cwd}`);
223
225
  row.inScopeNow=inside;
224
226
  const normalized=handler.normalize(line,row.state,homes[row.platform]);
225
227
  if (inside) {
@@ -251,6 +253,10 @@ export function createWatcher({options, homes, scope: initialScope, git, now, re
251
253
  return {events,sawInScope,firstSession};
252
254
  }
253
255
  function emit(row, events, out) {
256
+ if (row.hidden) {
257
+ row.held=[];
258
+ return;
259
+ }
254
260
  if (row.holdUntil !== undefined && !mapped(row) && now() < row.holdUntil) row.held.push(...events);
255
261
  else {
256
262
  // Held events receive the final identity only when released.
@@ -286,7 +292,7 @@ export function createWatcher({options, homes, scope: initialScope, git, now, re
286
292
  }
287
293
  }
288
294
  function eligible(row) {
289
- if (!platforms.includes(row.platform) || row.origin === 'Codex Desktop') return false;
295
+ if (!tracked.has(row.platform) || row.origin === 'Codex Desktop') return false;
290
296
  if (row.parentId) {
291
297
  const chain=ancestry(row);
292
298
  if (chain.desktop) {ignored.set(row.file,row.size);return false;}
@@ -304,7 +310,10 @@ export function createWatcher({options, homes, scope: initialScope, git, now, re
304
310
  const previous = detached.get(row.file) ?? (!startup && !pending.has(row.file) ? seenAtStart.get(row.file) : undefined);
305
311
  let history;
306
312
  try { history = previous ? {endOffset:previous.offset} : await readTail(row.file); }
307
- catch (error) { debug(out,`session file unreadable: ${row.id.slice(0,8)} (${error.code ?? 'error'})`); ignored.set(row.file,row.size); return; }
313
+ catch (error) {
314
+ if (!row.hidden) debug(out,`session file unreadable: ${row.id.slice(0,8)} (${error.code ?? 'error'})`);
315
+ ignored.set(row.file,row.size); return;
316
+ }
308
317
  row.headCwd=row.cwd;
309
318
  row.tail=createTail(row.file,{offset:previous?.offset ?? history.endOffset});
310
319
  const handler=TRANSCRIPT_HANDLERS.get(row.platform);
@@ -313,17 +322,17 @@ export function createWatcher({options, homes, scope: initialScope, git, now, re
313
322
  await setCwd(row,previous?.cwd??row.headCwd,out);
314
323
  await verifyCwd(row.cwd,out);
315
324
  followed.set(row.id,row); pending.delete(row.file); detached.delete(row.file);
316
- if (!startup && !previous && !row.parentId && !mapped(row) && handler.shouldHold(row.origin) && now()-row.mtimeMs<=L.holdCreatedWithinMs) row.holdUntil=now()+L.holdMs;
325
+ if (!row.hidden && !startup && !previous && !row.parentId && !mapped(row) && handler.shouldHold(row.origin) && now()-row.mtimeMs<=L.holdCreatedWithinMs) row.holdUntil=now()+L.holdMs;
317
326
  const showHistory = startup ? tailCount > 0 && now()-row.mtimeMs<=L.historyWindowMs : !previous;
318
327
  const {events,firstSession}=await normalize(row,history.lines??[],false,out);
319
- if (showHistory) {
328
+ if (!row.hidden && showHistory) {
320
329
  if (!events.some(e=>e.kind==='session')) {
321
330
  const initialSession=firstSession ?? (lineGate(row)
322
331
  ? clean({...identity(row),ts:stamp(),kind:'session',text:sessionText(row)}) : undefined);
323
332
  if (initialSession) events.unshift(initialSession);
324
333
  }
325
334
  emit(row,events,out);
326
- } else if (startup && skipped) skipped.push(...events);
335
+ } else if (!row.hidden && startup && skipped) skipped.push(...events);
327
336
  if (row.inScopeNow===undefined) row.inScopeNow=lineGate(row);
328
337
  if (lineGate(row)) await ensureShellRoot(row,out);
329
338
  if (seenAtStart.has(row.file)) seenAtStart.get(row.file).cwd=row.cwd;
@@ -431,8 +440,7 @@ export function createWatcher({options, homes, scope: initialScope, git, now, re
431
440
  const updates = probe ? [] : await scanDispatch();
432
441
  for (const file of pending.keys()) if (!await details(file)) pending.delete(file);
433
442
  for (const [platform, handler] of TRANSCRIPT_HANDLERS) {
434
- const home=homes[platform];
435
- if (home && platforms.includes(platform)) await handler.discover({platform,home,startup,out,rows});
443
+ if (tracked.has(platform)) await handler.discover({platform,home:homes[platform],startup,out,rows});
436
444
  }
437
445
  rows.sort((a,b)=>b.mtimeMs-a.mtimeMs||a.file.localeCompare(b.file));
438
446
  let remaining=rows.filter(row=> {
@@ -442,6 +450,7 @@ export function createWatcher({options, homes, scope: initialScope, git, now, re
442
450
  return !previous || row.size>previous.size || pending.has(row.file);
443
451
  });
444
452
  for (const row of remaining) {
453
+ row.hidden=!platforms.includes(row.platform);
445
454
  const previous=detached.get(row.file) ?? seenAtStart.get(row.file);
446
455
  if (startup || !previous || row.size>previous.size) {
447
456
  const extract=TRANSCRIPT_HANDLERS.get(row.platform).lineCwd;
@@ -458,10 +467,13 @@ export function createWatcher({options, homes, scope: initialScope, git, now, re
458
467
  for(const row of remaining) {
459
468
  if (!eligible(row)) {next.push(row);continue;}
460
469
  if (!probe && followed.size>=L.maxFollowed) {
461
- const oldest=[...followed.values()].sort((a,b)=>a.mtimeMs-b.mtimeMs)[0];
462
- if (!capped) {out.push(notice('following the newest 64 sessions; others are skipped'));capped=true;}
463
- if (oldest.mtimeMs>=row.mtimeMs || row.parentId===oldest.id) continue;
464
- followed.delete(oldest.id); detached.set(oldest.file,{file:oldest.file,platform:oldest.platform,offset:oldest.tail.offset,size:oldest.size,cwd:oldest.cwd});
470
+ const peers=[...followed.values()].filter(followedRow=>followedRow.hidden===row.hidden);
471
+ if (peers.length>=L.maxFollowed) {
472
+ const oldest=peers.sort((a,b)=>a.mtimeMs-b.mtimeMs)[0];
473
+ if (!row.hidden && !capped) {out.push(notice('following the newest 64 sessions; others are skipped'));capped=true;}
474
+ if (oldest.mtimeMs>=row.mtimeMs || row.parentId===oldest.id) continue;
475
+ followed.delete(oldest.id); detached.set(oldest.file,{file:oldest.file,platform:oldest.platform,offset:oldest.tail.offset,size:oldest.size,cwd:oldest.cwd});
476
+ }
465
477
  }
466
478
  await attach(row,startup,out,skipped);progress=true;
467
479
  }
@@ -474,7 +486,10 @@ export function createWatcher({options, homes, scope: initialScope, git, now, re
474
486
  if (row.parentId && (!missingParent || chain.desktop)) pending.delete(row.file);
475
487
  if (row.parentId && row.origin!=='Codex Desktop' && missingParent && !chain.desktop) {
476
488
  const wait=pending.get(row.file) ?? {...row,until:now()+L.holdMs};
477
- if (now()>=wait.until) {pending.delete(row.file);ignored.set(row.file,row.size);debug(out,`parent session not found for ${row.id}`);}
489
+ if (now()>=wait.until) {
490
+ pending.delete(row.file);ignored.set(row.file,row.size);
491
+ if (!row.hidden) debug(out,`parent session not found for ${row.id}`);
492
+ }
478
493
  else pending.set(row.file,wait);
479
494
  }
480
495
  }
@@ -482,7 +497,7 @@ export function createWatcher({options, homes, scope: initialScope, git, now, re
482
497
  for (const row of followed.values()) {
483
498
  const ref=mapped(row);
484
499
  if (ref && row.dispatchId!==ref.dispatchId) {
485
- if (row.emitted) out.push(notice(`session ${row.id.slice(0,8)} is dispatch ${ref.dispatchId} (${ref.role??'dispatch'})`));
500
+ if (!row.hidden && row.emitted) out.push(notice(`session ${row.id.slice(0,8)} is dispatch ${ref.dispatchId} (${ref.role??'dispatch'})`));
486
501
  row.dispatchId=ref.dispatchId;
487
502
  }
488
503
  emit(row,[],out);
@@ -496,22 +511,28 @@ export function createWatcher({options, homes, scope: initialScope, git, now, re
496
511
  try { result=await row.tail.poll(); }
497
512
  catch (error) {
498
513
  followed.delete(id);ignored.set(row.file,row.size);
499
- debug(out,`session file unreadable: ${row.id.slice(0,8)} (${error.code??'error'})`);continue;
514
+ if (!row.hidden) debug(out,`session file unreadable: ${row.id.slice(0,8)} (${error.code??'error'})`);
515
+ continue;
516
+ }
517
+ if (result.gone) {
518
+ followed.delete(id);
519
+ if (!row.hidden) debug(out,`session file removed: ${row.id.slice(0,8)}`);
520
+ continue;
500
521
  }
501
- if (result.gone) {followed.delete(id);debug(out,`session file removed: ${row.id.slice(0,8)}`);continue;}
502
522
  if (result.reset) {
503
523
  row.state=TRANSCRIPT_HANDLERS.get(row.platform).createState();row.active=false;
504
524
  await setCwd(row,row.headCwd,out);row.inScopeNow=lineGate(row);
505
- debug(out,`session restarted from the beginning: ${row.id.slice(0,8)}`);
525
+ if (!row.hidden) debug(out,`session restarted from the beginning: ${row.id.slice(0,8)}`);
506
526
  }
507
- if (result.overflowed && !row.overflowed) debug(out,`line over 4 MiB skipped in ${row.id.slice(0,8)}`);
527
+ if (!row.hidden && result.overflowed && !row.overflowed) debug(out,`line over 4 MiB skipped in ${row.id.slice(0,8)}`);
508
528
  row.overflowed=result.overflowed;
509
529
  row.size=row.tail.offset;
510
530
  const {events,sawInScope}=await normalize(row,result.lines,true,out);
511
531
  if (sawInScope) row.lastActivity=now();
512
532
  emit(row,events,out);
513
533
  if (now()-row.lastActivity>=L.idleDetachMs && !row.held.length) {
514
- followed.delete(id);detached.set(row.file,{file:row.file,platform:row.platform,offset:row.tail.offset,size:row.size,cwd:row.cwd});debug(out,`detached idle session ${row.id.slice(0,8)}`);
534
+ followed.delete(id);detached.set(row.file,{file:row.file,platform:row.platform,offset:row.tail.offset,size:row.size,cwd:row.cwd});
535
+ if (!row.hidden) debug(out,`detached idle session ${row.id.slice(0,8)}`);
515
536
  }
516
537
  }
517
538
  }
@@ -635,11 +656,11 @@ export function createWatcher({options, homes, scope: initialScope, git, now, re
635
656
  return markEmitted(sort(out));
636
657
  },
637
658
  listActivity() {
638
- return [...followed.values()].map(row=>({
659
+ return [...followed.values()].filter(row=>!row.hidden).map(row=>({
639
660
  platform:row.platform,mtimeMs:row.mtimeMs,cwd:row.latestCwd ?? row.cwd,main:!row.parentId,
640
661
  }));
641
662
  },
642
- busy() {return [...followed.values()].some(row=>row.active && (row.inScopeNow || mapped(row)) && now()-row.lastActivity<=L.spinnerIdleMs);},
663
+ busy() {return [...followed.values()].some(row=>!row.hidden && row.active && (row.inScopeNow || mapped(row)) && now()-row.lastActivity<=L.spinnerIdleMs);},
643
664
  async close() {closed=true;followed.clear();pending.clear();earlierBacklog=undefined;},
644
665
  };
645
666
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yunhozz/arc",
3
- "version": "0.5.2",
3
+ "version": "0.5.4",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "registry": "https://registry.npmjs.org/"
@@ -8,7 +8,7 @@ export const COOPERATIVE_RUNTIME_MODULES=Object.freeze([
8
8
  'cli.mjs','command.mjs','bootstrap.mjs','cooperative-schema.mjs','cooperative.mjs','evaluate.mjs',
9
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
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','platform-registry.mjs','gemini-stream.mjs','grok-stream.mjs','grok-sandbox.mjs'
11
+ 'role-dispatch-policy.mjs','role-dispatch-store.mjs','role-bridge-args.mjs','role-observe.mjs','role-supervisor.mjs','platform-registry.mjs','gemini-stream.mjs','grok-stream.mjs','grok-sandbox.mjs','tool-access.mjs','host-service.mjs'
12
12
  ]);
13
13
  export const cooperativeCoverage=()=>({enforcement:'cooperative',provenance:'operator-attested',nativeVerified:false});
14
14
  export function commandResult({workflowId,state,input,decision='allow',ruleId='cooperative.recorded',persisted=false,...extra}){
@@ -51,9 +51,9 @@ export async function runWorkflowCommand(args,io={}){
51
51
  if(isRouting){
52
52
  if(!input||typeof input!=='object'||Array.isArray(input))throw Error('Invalid routing input');
53
53
  const context={cwd,userHome:os.homedir(),env:process.env,workflowId,hostPlatform:input.hostPlatform,executionEnvironment:input.executionEnvironment};
54
- 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];
54
+ const keys=Object.keys(input),allowed={'routing-status':[['hostPlatform','executionEnvironment'],[]],'prepare-dispatch':[['hostPlatform','executionEnvironment','role','expectedRevision','requestId','taskId'],['allowedPaths','toolAccess']],'run-dispatch':[['hostPlatform','executionEnvironment','dispatchId','brief'],[]],observe:[['hostPlatform','executionEnvironment','dispatchId'],['waitMs','event','nativeAgentId']],resume:[['hostPlatform','executionEnvironment','dispatchId','brief'],[]],cancel:[['hostPlatform','executionEnvironment','dispatchId'],[]]}[command];
55
55
  if(allowed&&(allowed[0].some(key=>!Object.hasOwn(input,key))||keys.some(key=>!allowed[0].includes(key)&&!allowed[1].includes(key))))result=invalidRoutingRequest(context);
56
- 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});
56
+ 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}:{}),...(Object.hasOwn(input,'toolAccess')?{toolAccess:input.toolAccess}:{})},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});
57
57
  result={workflowId,...result};
58
58
  }else result=await(command==='init'?initializeCooperativeWorkflow({cwd,workflowId,input}):runCooperativeCommand({cwd,workflowId,command,input}));
59
59
  output.write(JSON.stringify(result)+'\n');return result.decision==='deny'?2:result.decision==='hold'?3:0;
@@ -0,0 +1,155 @@
1
+ import childProcess from 'node:child_process';
2
+ import {constants, readFileSync, realpathSync} from 'node:fs';
3
+ import fsp from 'node:fs/promises';
4
+ import path from 'node:path';
5
+ import {setTimeout as sleep} from 'node:timers/promises';
6
+ import {CANCEL_GRACE_MS, PROBE_TIMEOUT_MS} from './role-dispatch-policy.mjs';
7
+
8
+ export const HOST_SERVICES = Object.freeze({
9
+ 'browser-cdp': Object.freeze({kind: 'cdp'}),
10
+ 'browser-playwright-chromium': Object.freeze({kind: 'playwright', browser: 'chromium'}),
11
+ 'browser-playwright-firefox': Object.freeze({kind: 'playwright', browser: 'firefox'}),
12
+ 'browser-playwright-webkit': Object.freeze({kind: 'playwright', browser: 'webkit'}),
13
+ });
14
+ export const CHROME_EXECUTABLE = '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
15
+ export const SANDBOX_EXEC = '/usr/bin/sandbox-exec';
16
+ export const hostDirFor = dispatchId => `/private/tmp/arc-host-${dispatchId.replaceAll('-', '').slice(0, 8)}`;
17
+
18
+ export function resolveGlobalPlaywright({run = childProcess.spawnSync} = {}) {
19
+ const probe = run('npm', ['root', '-g'], {cwd: '/private/tmp', encoding: 'utf8', timeout: PROBE_TIMEOUT_MS});
20
+ const root = probe.stdout?.trim();
21
+ if (probe.status !== 0 || !root || !path.isAbsolute(root)) return null;
22
+ for (const name of ['playwright', 'playwright-core']) {
23
+ try {
24
+ const {version} = JSON.parse(readFileSync(path.join(root, name, 'package.json'), 'utf8'));
25
+ if (typeof version === 'string' && version.length > 0) return {root, name, version};
26
+ return null;
27
+ } catch (error) {
28
+ if (error.code !== 'ENOENT') return null;
29
+ }
30
+ }
31
+ return null;
32
+ }
33
+
34
+ export async function hostServicePreflight({services, io = {}}) {
35
+ const hold = 'permission_scope_unverified';
36
+ for (const id of services) {
37
+ try {
38
+ switch (HOST_SERVICES[id]?.kind) {
39
+ case 'cdp': {
40
+ const access = io.access ?? fsp.access;
41
+ await access(CHROME_EXECUTABLE, constants.X_OK);
42
+ await access(SANDBOX_EXEC, constants.X_OK);
43
+ break;
44
+ }
45
+ case 'playwright':
46
+ if (!(io.resolveGlobalPlaywright ?? resolveGlobalPlaywright)()) return hold;
47
+ break;
48
+ default:
49
+ return hold;
50
+ }
51
+ } catch { return hold; }
52
+ }
53
+ return null;
54
+ }
55
+
56
+ function profilePath(filename) {
57
+ const unsafe = /["\\\n\r]/;
58
+ if (unsafe.test(filename)) throw Error('invalid sandbox profile path');
59
+ const resolved = realpathSync(filename);
60
+ if (unsafe.test(resolved)) throw Error('invalid sandbox profile path');
61
+ return resolved;
62
+ }
63
+
64
+ export function renderSandboxProfile({kind, userHome, dataDir}) {
65
+ if (kind === 'playwright') throw Error('playwright sandbox profile unmeasured (MI-B)');
66
+ if (kind !== 'cdp') throw Error('unknown host service kind');
67
+ return [
68
+ '(version 1)',
69
+ '(allow default)',
70
+ `(deny file-read* file-write* (subpath "${profilePath(userHome)}"))`,
71
+ '(deny process-exec (regex #"GoogleUpdater"))',
72
+ `(allow file-read* file-write* (subpath "${profilePath(dataDir)}"))`,
73
+ '(deny network-outbound)',
74
+ '(allow network-outbound (remote ip "localhost:*"))',
75
+ '',
76
+ ].join('\n');
77
+ }
78
+
79
+ const startFailed = () => Object.assign(Error('Host service failed to start'), {reasonCode: 'execution_failed'});
80
+
81
+ async function waitForCdpPort(dataDir, timeoutMs, exited, wait) {
82
+ const deadline = performance.now() + timeoutMs;
83
+ while (!exited() && performance.now() < deadline) {
84
+ const bytes = await fsp.readFile(path.join(dataDir, 'DevToolsActivePort'), 'utf8').catch(error => {
85
+ if (error.code !== 'ENOENT') throw error;
86
+ return '';
87
+ });
88
+ const first = bytes.split('\n', 1)[0].trim();
89
+ const port = Number(first);
90
+ if (!exited() && /^\d+$/.test(first) && port > 0 && port <= 65535) return port;
91
+ const remaining = deadline - performance.now();
92
+ if (remaining > 0 && !exited()) await wait(Math.min(25, remaining));
93
+ }
94
+ throw startFailed();
95
+ }
96
+
97
+ export async function startHostService({id, dispatchId, userHome, timeoutMs = PROBE_TIMEOUT_MS, onSpawn, io = {}}) {
98
+ // Playwright launches remain disabled until each engine's isolation is measured.
99
+ if (HOST_SERVICES[id]?.kind !== 'cdp') throw startFailed();
100
+ const hostDir = hostDirFor(dispatchId);
101
+ const dir = path.join(hostDir, id), dataDir = path.join(dir, 'udd'), profile = path.join(dir, 'chrome.sb');
102
+ const wait = io.sleep ?? sleep, kill = io.kill ?? process.kill;
103
+ let child, created = false, exited = false, cleanup;
104
+ const stop = () => cleanup ??= (async () => {
105
+ let warning = false;
106
+ const signalGroup = signal => {
107
+ try { kill(-child.pid, signal); } catch (error) { if (error.code !== 'ESRCH') warning = true; }
108
+ };
109
+ let groupExists = Boolean(child?.pid);
110
+ if (groupExists && exited) {
111
+ try { kill(-child.pid, 0); } catch (error) {
112
+ if (error.code === 'ESRCH') groupExists = false;
113
+ else warning = true;
114
+ }
115
+ }
116
+ if (groupExists) {
117
+ signalGroup('SIGTERM');
118
+ try { await wait(CANCEL_GRACE_MS); } catch { warning = true; }
119
+ signalGroup('SIGKILL');
120
+ }
121
+ // The supervisor removes the complete hostDir after collecting evidence.
122
+ if (created && io.removeDir) {
123
+ try { await io.removeDir(dir); } catch { warning = true; }
124
+ }
125
+ return warning ? 'warning' : 'ok';
126
+ })();
127
+ try {
128
+ // The supervisor reserves the host directory for the dispatch before starting any service.
129
+ await fsp.mkdir(dir, {mode: 0o700});
130
+ created = true;
131
+ await fsp.mkdir(dataDir, {mode: 0o700});
132
+ await fsp.writeFile(profile, renderSandboxProfile({kind: 'cdp', userHome, dataDir}), {flag: 'wx', mode: 0o600});
133
+ child = (io.spawn ?? childProcess.spawn)(SANDBOX_EXEC, [
134
+ '-f', profile, CHROME_EXECUTABLE,
135
+ '--headless=new', '--remote-debugging-address=127.0.0.1', '--remote-debugging-port=0',
136
+ `--user-data-dir=${dataDir}`, '--no-first-run', '--no-default-browser-check',
137
+ '--disable-extensions', '--use-mock-keychain', '--no-sandbox', '--disable-gpu',
138
+ '--proxy-server=127.0.0.1:9', '--proxy-bypass-list=127.0.0.1;localhost', 'about:blank',
139
+ ], {cwd: hostDir, detached: true, stdio: 'ignore', shell: false});
140
+ const markExited = () => { exited = true; };
141
+ child.once('error', markExited);
142
+ child.once('exit', markExited);
143
+ if (child.pid) onSpawn?.(child.pid);
144
+ const port = await waitForCdpPort(dataDir, timeoutMs, () => exited, wait);
145
+ return {id, started: true, endpoint: {port, url: `http://127.0.0.1:${port}`}, stop};
146
+ } catch {
147
+ const cleanup = await stop();
148
+ throw Object.assign(startFailed(), {cleanup});
149
+ }
150
+ }
151
+
152
+ export async function writeServicesFile(scratch, records) {
153
+ const endpoints = Object.fromEntries(records.map(({id, endpoint}) => [id, endpoint]));
154
+ await fsp.writeFile(path.join(scratch, 'services.json'), JSON.stringify(endpoints) + '\n', {flag: 'wx', mode: 0o600});
155
+ }
@@ -3,13 +3,15 @@ import crypto from 'node:crypto';
3
3
  import path from 'node:path';
4
4
  import {GROK_CONTRACT} from './grok-stream.mjs';
5
5
  import {GEMINI_CONTRACT} from './gemini-stream.mjs';
6
- import {DEFAULT_POLICY, effectiveClaudeSandboxSettings} from './role-dispatch-policy.mjs';
6
+ import {CODEX_PROFILE_ARGS_FORM, CODEX_PROFILE_GIT_ENTRIES, DEFAULT_POLICY, effectiveClaudeSandboxSettings} from './role-dispatch-policy.mjs';
7
+ import {TOOL_PATHS, TOOL_UNIX_SOCKETS} from './tool-access.mjs';
7
8
 
8
9
  const ROLES = ['arc_scouter', 'arc_planner', 'arc_implementer', 'arc_tester', 'arc_reviewer'];
9
10
  const deepFreeze = value => { for (const child of Object.values(value)) if (child && typeof child === 'object') deepFreeze(child); return Object.freeze(value); };
10
11
  export const ROLE_BRIDGE_PERMISSIONS = deepFreeze({
11
12
  claude: {
12
- arc_scouter: {permissionMode: 'default', sandbox: false}, arc_planner: {permissionMode: 'default', sandbox: false},
13
+ arc_scouter: {permissionMode: 'default', sandbox: false, allowedTools: ['WebFetch', 'WebSearch']},
14
+ arc_planner: {permissionMode: 'default', sandbox: false},
13
15
  arc_implementer: {permissionMode: 'acceptEdits', sandbox: true}, arc_tester: {permissionMode: 'default', sandbox: true}, arc_reviewer: {permissionMode: 'default', sandbox: false}
14
16
  },
15
17
  gemini: {
@@ -183,28 +185,128 @@ const permissionsFor = (platform, role) => {
183
185
  };
184
186
  const requireText = (value, label) => { if (typeof value !== 'string' || value === '') throw Error(`Missing ${label}`); return value; };
185
187
 
186
- export function buildClaudeArgs({role, profile, sessionId = null, policy = DEFAULT_POLICY}) {
188
+ function claudeSettingsFor(base, toolContext) {
189
+ if (toolContext === null) return {...base};
190
+ const {grants, scratch, forbidden, secretEnvNames} = toolContext;
191
+ const permissions = {...base.permissions};
192
+ const filesystem = {...base.sandbox.filesystem};
193
+ if (grants.network === 'domains') {
194
+ const reads = [...forbidden.readWhenExternal].sort((a, b) => a.path < b.path ? -1 : Number(a.path > b.path));
195
+ // Claude 2.1.327, 2026-11-24, MI-7
196
+ const readRules = reads.map(({path: name, kind}) => `Read(/${name}${kind === 'dir' ? '/**' : ''})`);
197
+ permissions.deny = [...permissions.deny, ...readRules];
198
+ // Claude 2.1.327, 2026-11-24, MI-9
199
+ filesystem.denyRead = reads.map(entry => entry.path);
200
+ }
201
+ if (grants.paths.length) filesystem.allowWrite = grants.paths.map(id => TOOL_PATHS[id]).sort();
202
+ const sandbox = {...base.sandbox, filesystem};
203
+ if (grants.network !== null) {
204
+ // Claude 2.1.327, 2026-11-24, MI-5
205
+ sandbox.network = {
206
+ allowedDomains: ['localhost', '127.0.0.1', ...[...grants.domains].sort()],
207
+ allowLocalBinding: true,
208
+ allowUnixSockets: [path.join(scratch, 'sock'), ...grants.unixSockets.map(id => TOOL_UNIX_SOCKETS[id]).sort()],
209
+ };
210
+ }
211
+ // Claude 2.1.327, 2026-11-24, MI-6
212
+ const values = new Map([...toolContext.env, ...secretEnvNames.map(name => [name, ''])]);
213
+ const env = Object.fromEntries([...values.keys()].sort().map(name => [name, values.get(name)]));
214
+ return {permissions, sandbox, env};
215
+ }
216
+
217
+ export function buildClaudeArgs({role, profile, sessionId = null, policy = DEFAULT_POLICY, toolContext = null}) {
187
218
  const permissions = permissionsFor('claude', role);
188
219
  if (!Array.isArray(profile?.tools) || profile.tools.length === 0) throw Error('Claude profile tools are required');
189
220
  const args = ['-p', '--safe-mode', '--output-format', 'stream-json', '--verbose', '--model', requireText(profile.model, 'model'), '--effort', requireText(profile.effort, 'effort'),
190
221
  '--append-system-prompt', requireText(profile.instructions, 'instructions'), '--tools', profile.tools.join(','), '--permission-mode', permissions.permissionMode];
222
+ if (permissions.allowedTools) {
223
+ if (!permissions.allowedTools.every(tool => profile.tools.includes(tool))) throw Error('Claude allowedTools must be listed in profile tools');
224
+ args.push('--allowedTools', permissions.allowedTools.join(','));
225
+ }
191
226
  if (permissions.sandbox) {
192
227
  const settings = effectiveClaudeSandboxSettings(policy);
193
228
  if (settings === null) throw Error('Claude sandbox settings are not available for this role');
194
- args.push('--settings', JSON.stringify(settings));
229
+ args.push('--settings', JSON.stringify(claudeSettingsFor(settings, toolContext)));
195
230
  }
196
231
  if (policy?.gates?.G6 === 'strict') args.push('--strict-mcp-config');
197
232
  if (sessionId !== null) args.push('--resume', requireText(sessionId, 'sessionId'));
198
233
  return args;
199
234
  }
200
235
 
201
- export function buildCodexArgs({role, profile, worktree, resultPath, threadId = null, policy = DEFAULT_POLICY}) {
236
+ const codexProtectionPaths = worktree => [path.join(worktree, '.git'), path.join(worktree, '.codex')];
237
+
238
+ export function assertCodexProtection(entries, worktree) {
239
+ if (!codexProtectionPaths(worktree).every((name, index) =>
240
+ entries[index]?.[0] === name && entries[index]?.[1] === 'read' && entries[index]?.length === 2)) {
241
+ throw Error('Codex profile protection entries missing');
242
+ }
243
+ }
244
+
245
+ export function codexFilesystemEntries({worktree, gitDir, gitCommonDir, hostDir, grants, forbidden}, toolPaths = TOOL_PATHS) {
246
+ const protectedPaths = codexProtectionPaths(worktree);
247
+ if (CODEX_PROFILE_GIT_ENTRIES) protectedPaths.push(...[gitDir, gitCommonDir].filter(Boolean));
248
+ const entries = [...new Set(protectedPaths)].map(name => [name, 'read']);
249
+ if (hostDir) entries.push([hostDir, 'read']);
250
+ for (const name of grants.paths.map(id => toolPaths[id]).sort()) {
251
+ if (!path.isAbsolute(name)) throw Error('Absolute tool path required');
252
+ entries.push([name, 'write']);
253
+ }
254
+ if (grants.network === 'domains') {
255
+ for (const name of [...new Set(forbidden.readWhenExternal.map(entry => entry.path))].sort()) entries.push([name, 'none']);
256
+ }
257
+ return entries;
258
+ }
259
+
260
+ export function renderCodexTable(entries) {
261
+ return '{' + entries.map(([key, value]) => JSON.stringify(key) + '=' + JSON.stringify(value)).join(',') + '}';
262
+ }
263
+
264
+ function codexProfileSettings(toolContext, worktree, toolPaths) {
265
+ const {grants, scratch} = toolContext;
266
+ const entries = codexFilesystemEntries(toolContext, toolPaths);
267
+ assertCodexProtection(entries, worktree);
268
+ const profile = 'permissions.arc_bridge';
269
+ const settings = ['-c', `${profile}.extends=":workspace"`, '-c', `${profile}.filesystem=${renderCodexTable(entries)}`];
270
+ if (grants.network !== null) {
271
+ const domains = ['127.0.0.1', ...[...grants.domains].sort()].map(name => [name, 'allow']);
272
+ const sockets = [path.join(scratch, 'sock'), ...grants.unixSockets.map(id => TOOL_UNIX_SOCKETS[id]).sort()].map(name => [name, 'allow']);
273
+ settings.push('-c', `${profile}.network.enabled=true`,
274
+ '-c', `${profile}.network.domains=${renderCodexTable(domains)}`,
275
+ '-c', `${profile}.network.allow_local_binding=true`,
276
+ '-c', `${profile}.network.unix_sockets=${renderCodexTable(sockets)}`);
277
+ }
278
+ return settings;
279
+ }
280
+
281
+ export function buildCodexArgs({role, profile, worktree, resultPath, threadId = null, policy = DEFAULT_POLICY, toolContext = null},
282
+ {toolPaths = TOOL_PATHS} = {}) {
202
283
  void policy;
203
284
  const permissions = permissionsFor('codex', role);
204
285
  if (typeof resultPath !== 'string' || !path.isAbsolute(resultPath)) throw Error('Absolute resultPath required');
205
- const settings = ['-m', requireText(profile?.model, 'model'), '-c', `model_reasoning_effort=${JSON.stringify(requireText(profile.effort, 'effort'))}`,
206
- '-c', `developer_instructions=${JSON.stringify(requireText(profile.instructions, 'instructions'))}`, '-c', `sandbox_mode=${JSON.stringify(permissions.sandboxMode)}`,
207
- '-c', 'approval_policy="never"', '-o', resultPath, '-'];
286
+ const writerContext = permissions.sandboxMode === 'workspace-write' ? toolContext : null;
287
+ const profileMode = writerContext?.grants.mechanisms.includes('codexProfile');
288
+ const settings = [];
289
+ if (profileMode) {
290
+ if (CODEX_PROFILE_ARGS_FORM === 'B') {
291
+ settings.push('-c', 'default_permissions="arc_bridge"');
292
+ if (writerContext.grants.network !== null) settings.push('-c', 'features.network_proxy=true');
293
+ } else {
294
+ settings.push('-P', 'arc_bridge');
295
+ if (writerContext.grants.network !== null) settings.push('--enable', 'network_proxy');
296
+ }
297
+ }
298
+ settings.push('-m', requireText(profile?.model, 'model'), '-c', `model_reasoning_effort=${JSON.stringify(requireText(profile.effort, 'effort'))}`,
299
+ '-c', `developer_instructions=${JSON.stringify(requireText(profile.instructions, 'instructions'))}`);
300
+ if (profileMode) settings.push(...codexProfileSettings(writerContext, worktree, toolPaths));
301
+ else settings.push('-c', `sandbox_mode=${JSON.stringify(permissions.sandboxMode)}`);
302
+ settings.push('-c', 'approval_policy="never"');
303
+ for (const [key, value] of writerContext?.env ?? []) {
304
+ settings.push('-c', `shell_environment_policy.set.${key}=${JSON.stringify(value)}`);
305
+ }
306
+ if (profileMode && writerContext.grants.network === 'domains') {
307
+ settings.push('-c', `shell_environment_policy.exclude=${JSON.stringify(writerContext.forbidden.envWhenExternal)}`);
308
+ }
309
+ settings.push('-o', resultPath, '-');
208
310
  if (threadId !== null) {
209
311
  if (typeof threadId !== 'string' || !/^[A-Za-z0-9._-]+$/.test(threadId)) throw Error('Invalid threadId');
210
312
  return [...(permissions.search ? ['--search'] : []), 'exec', 'resume', threadId, '--json', ...settings];