@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.
- package/MANIFEST.sha256 +34 -30
- package/README.md +10 -1
- package/claude/skill/SKILL.md +1 -1
- package/claude/skill/references/coordination.md +6 -0
- package/codex/skill/SKILL.md +1 -1
- package/codex/skill/references/coordination.md +6 -0
- package/gemini/skill/SKILL.md +1 -1
- package/gemini/skill/references/coordination.md +6 -0
- package/grok/skill/SKILL.md +1 -1
- package/grok/skill/references/coordination.md +6 -0
- package/lib/installer/runtime-assets.mjs +2 -0
- package/lib/runtime/bootstrap.mjs +1 -1
- package/lib/runtime/command.mjs +2 -2
- package/lib/runtime/host-service.mjs +155 -0
- package/lib/runtime/role-bridge-args.mjs +110 -8
- package/lib/runtime/role-bridge.mjs +47 -20
- package/lib/runtime/role-dispatch-policy.mjs +9 -1
- package/lib/runtime/role-dispatch-store.mjs +6 -2
- package/lib/runtime/role-observe.mjs +7 -2
- package/lib/runtime/role-routing.mjs +13 -1
- package/lib/runtime/role-supervisor.mjs +248 -9
- package/lib/runtime/tool-access.mjs +560 -0
- package/lib/watch/watcher.mjs +46 -25
- package/package.json +1 -1
- package/shared/skill/runtime/bootstrap.mjs +1 -1
- package/shared/skill/runtime/command.mjs +2 -2
- package/shared/skill/runtime/host-service.mjs +155 -0
- package/shared/skill/runtime/role-bridge-args.mjs +110 -8
- package/shared/skill/runtime/role-bridge.mjs +47 -20
- package/shared/skill/runtime/role-dispatch-policy.mjs +9 -1
- package/shared/skill/runtime/role-dispatch-store.mjs +6 -2
- package/shared/skill/runtime/role-observe.mjs +7 -2
- package/shared/skill/runtime/role-routing.mjs +13 -1
- package/shared/skill/runtime/role-supervisor.mjs +248 -9
- package/shared/skill/runtime/tool-access.mjs +560 -0
|
@@ -10,13 +10,15 @@ import {promisify} from 'node:util';
|
|
|
10
10
|
import {GROK_CONTRACT, normalizeGrokStreamEvent, evaluateGrokObservation} from './grok-stream.mjs';
|
|
11
11
|
import {GROK_SANDBOX_RELATIVE, grokSandboxProfileName, renderGrokSandboxProfile, grokProfileCovered, inspectGrokProfileSlot, checkGrokHome, createGrokSandboxProfile, verifyGrokSandboxProfile, removeGrokSandboxProfile, grokEventsBaseline, readGrokProfileApplied, grokConfigSecurityProjection} from './grok-sandbox.mjs';
|
|
12
12
|
import {GEMINI_CONTRACT, normalizeGeminiStreamEvent, evaluateGeminiObservation} from './gemini-stream.mjs';
|
|
13
|
-
import {DEFAULT_POLICY, DESCENDANT_LIMIT, DESCENDANT_SAMPLE_MS, reason, bridgeGateReasons} from './role-dispatch-policy.mjs';
|
|
14
|
-
import {readLease, writeLease, writeHeartbeat, cancelRequested, TERMINAL_STATES} from './role-dispatch-store.mjs';
|
|
13
|
+
import {CODEX_PROFILE_SANDBOX_TYPE, DEFAULT_POLICY, DESCENDANT_LIMIT, DESCENDANT_SAMPLE_MS, reason, bridgeGateReasons} from './role-dispatch-policy.mjs';
|
|
14
|
+
import {readLease, writeLease, writeHeartbeat, cancelRequested, dispatchDirectory, TERMINAL_STATES} from './role-dispatch-store.mjs';
|
|
15
15
|
import {withRoutingLock, readActivation, resolveRuntimeHomes} from './role-routing.mjs';
|
|
16
16
|
import {resolveLocalCli, localCliEnvironment} from './local-cli.mjs';
|
|
17
17
|
import {parseCompositeProfile, buildBridgeArgs, argsDigest, ROLE_BRIDGE_PERMISSIONS} from './role-bridge-args.mjs';
|
|
18
18
|
import {createLineParser, normalizeClaudeStreamEvent, normalizeCodexStreamEvent, eventRecord, evaluateClaudeInit, evaluateCodexContext, readClaudeTranscriptEffort, readCodexTurnContext, classifyFailure, snapshotWorktree, snapshotControlFiles, observeHeadAdvance, detectViolations, toleratedRecord, allowedPathsCoverControl, claudeProjectSettingsWidenScope, resolveWorktree} from './role-observe.mjs';
|
|
19
19
|
import {getPlatform, routingProfileFile} from './platform-registry.mjs';
|
|
20
|
+
import {buildToolContext, collectEvidence, createScratch, hasRetainedCleanup, removeScratch, toolAccessPreflight, toolAccessReasons, TOOL_ACCESS_ADAPTERS} from './tool-access.mjs';
|
|
21
|
+
import {hostDirFor, startHostService, writeServicesFile} from './host-service.mjs';
|
|
20
22
|
|
|
21
23
|
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
22
24
|
const sha256 = bytes => 'sha256:' + crypto.createHash('sha256').update(bytes).digest('hex');
|
|
@@ -267,6 +269,150 @@ export async function reapRecordedDescendants(artifactDir, lease, options) {
|
|
|
267
269
|
finally { await file?.close().catch(() => {}); }
|
|
268
270
|
}
|
|
269
271
|
|
|
272
|
+
const HOST_SERVICES_FILE = 'host-services.json';
|
|
273
|
+
const HOST_SERVICES_MAX_BYTES = 16384;
|
|
274
|
+
const dirIdentity = ({dev, ino}) => ({dev, ino});
|
|
275
|
+
const hasKeys = (value, keys) => value && typeof value === 'object' && !Array.isArray(value)
|
|
276
|
+
&& Object.keys(value).length === keys.length && keys.every(key => Object.hasOwn(value, key));
|
|
277
|
+
const validDirIdentity = value => hasKeys(value, ['dev', 'ino']) && Number.isSafeInteger(value.dev)
|
|
278
|
+
&& Number.isSafeInteger(value.ino) && value.ino > 0;
|
|
279
|
+
|
|
280
|
+
function writeHostServicesSnapshot(artifactDir, snapshot) {
|
|
281
|
+
const filename = path.join(artifactDir, HOST_SERVICES_FILE);
|
|
282
|
+
const temporary = `${filename}.${crypto.randomUUID()}.tmp`;
|
|
283
|
+
try {
|
|
284
|
+
fs.writeFileSync(temporary, JSON.stringify(snapshot) + '\n', {mode: 0o600, flag: 'wx'});
|
|
285
|
+
fs.renameSync(temporary, filename);
|
|
286
|
+
} finally {
|
|
287
|
+
try { fs.unlinkSync(temporary); } catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function hostServiceGroupStatus(pgid) {
|
|
292
|
+
try { process.kill(-pgid, 0); return 'present'; }
|
|
293
|
+
catch (error) {
|
|
294
|
+
if (error.code === 'ESRCH') return 'gone';
|
|
295
|
+
if (error.code === 'EPERM') return 'denied';
|
|
296
|
+
throw error;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
async function waitForHostServiceGroupExit(pgid) {
|
|
301
|
+
const deadline = performance.now() + 500;
|
|
302
|
+
while (hostServiceGroupStatus(pgid) !== 'gone') {
|
|
303
|
+
const remaining = deadline - performance.now();
|
|
304
|
+
if (remaining <= 0) return false;
|
|
305
|
+
await sleep(Math.min(25, remaining));
|
|
306
|
+
}
|
|
307
|
+
return true;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
async function recoveryProcessTable(supervisor) {
|
|
311
|
+
const table = await sampleProcessTable();
|
|
312
|
+
const rows = new Map(table?.map(row => [row.pid, row]));
|
|
313
|
+
if (!rows.has(process.pid)) throw Error('Process table unavailable');
|
|
314
|
+
if (supervisor && sameStart(rows.get(supervisor.pid), supervisor)) throw Error('Supervisor still present');
|
|
315
|
+
return rows;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
async function reapHostServiceGroup(entry, graceMs, supervisor) {
|
|
319
|
+
const {pid, pgid, startTime} = entry;
|
|
320
|
+
const groupMembers = table => [...table.values()].filter(row => row.pgid === pgid);
|
|
321
|
+
const safeMembers = table => {
|
|
322
|
+
const lineage = supervisorLineage(table, process.pid);
|
|
323
|
+
const members = groupMembers(table);
|
|
324
|
+
if (members.some(row => row.uid !== process.geteuid() || lineage.has(row.pid))) throw Error('Unverified service group');
|
|
325
|
+
return members;
|
|
326
|
+
};
|
|
327
|
+
const signal = name => {
|
|
328
|
+
try { process.kill(-pgid, name); }
|
|
329
|
+
catch (error) { if (error.code !== 'ESRCH') throw error; }
|
|
330
|
+
};
|
|
331
|
+
const before = await recoveryProcessTable(supervisor);
|
|
332
|
+
const leader = before.get(pid);
|
|
333
|
+
if (!leader) {
|
|
334
|
+
const status = hostServiceGroupStatus(pgid);
|
|
335
|
+
if (status !== 'denied') return status === 'gone';
|
|
336
|
+
const fresh = await recoveryProcessTable(supervisor);
|
|
337
|
+
return groupMembers(fresh).length === 0 && await waitForHostServiceGroupExit(pgid);
|
|
338
|
+
}
|
|
339
|
+
if (leader.pgid !== pgid || leader.startTime !== startTime) return false;
|
|
340
|
+
const members = safeMembers(before);
|
|
341
|
+
signal('SIGTERM');
|
|
342
|
+
if (graceMs > 0) await sleep(graceMs);
|
|
343
|
+
const status = hostServiceGroupStatus(pgid);
|
|
344
|
+
if (status === 'gone') return true;
|
|
345
|
+
|
|
346
|
+
// A leader can exit on TERM while its descendants keep the group alive.
|
|
347
|
+
const after = await recoveryProcessTable(supervisor);
|
|
348
|
+
const currentLeader = after.get(pid);
|
|
349
|
+
if (currentLeader && (currentLeader.pgid !== pgid || currentLeader.startTime !== startTime)) return false;
|
|
350
|
+
const remaining = safeMembers(after);
|
|
351
|
+
// macOS can report a zombie-only group as EPERM until it is reaped.
|
|
352
|
+
if (status === 'denied') return remaining.length === 0 && await waitForHostServiceGroupExit(pgid);
|
|
353
|
+
if (!members.some(member => after.get(member.pid)?.pgid === pgid && sameStart(after.get(member.pid), member))) {
|
|
354
|
+
return remaining.length === 0 && await waitForHostServiceGroupExit(pgid);
|
|
355
|
+
}
|
|
356
|
+
signal('SIGKILL');
|
|
357
|
+
return await waitForHostServiceGroupExit(pgid);
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
const quarantineOptions = (artifactDir, anchorHome, lease) => ({
|
|
361
|
+
artifactDir, fallbackDir: dispatchDirectory(anchorHome), quarantineKey: `${lease.dispatchId}-${lease.segment ?? 0}`,
|
|
362
|
+
});
|
|
363
|
+
|
|
364
|
+
export async function reapRecordedHostServices(artifactDir, lease, {anchorHome, graceMs = DEFAULT_POLICY.cancelGraceMs} = {}) {
|
|
365
|
+
let file;
|
|
366
|
+
try {
|
|
367
|
+
const requested = lease.toolAccess.services;
|
|
368
|
+
const adapter = TOOL_ACCESS_ADAPTERS[lease.targetPlatform];
|
|
369
|
+
const uid = process.geteuid(), id8 = lease.dispatchId.replaceAll('-', '').slice(0, 8);
|
|
370
|
+
const scratch = adapter?.scratchRoot?.({id8, uid});
|
|
371
|
+
if (!scratch) return 'warning';
|
|
372
|
+
const hostDir = hostDirFor(lease.dispatchId);
|
|
373
|
+
file = await fsp.open(path.join(artifactDir, HOST_SERVICES_FILE), fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK);
|
|
374
|
+
const stat = await file.stat();
|
|
375
|
+
if (!stat.isFile() || stat.uid !== uid || stat.size > HOST_SERVICES_MAX_BYTES) return 'warning';
|
|
376
|
+
const bytes = Buffer.alloc(HOST_SERVICES_MAX_BYTES + 1);
|
|
377
|
+
const {bytesRead} = await file.read(bytes, 0, bytes.length, 0);
|
|
378
|
+
if (bytesRead !== stat.size) return 'warning';
|
|
379
|
+
const snapshot = JSON.parse(bytes.toString('utf8', 0, bytesRead));
|
|
380
|
+
if (!hasKeys(snapshot, ['version', 'dispatchId', 'segment', 'hostDir', 'scratch', 'services', 'pending'])
|
|
381
|
+
|| snapshot.version !== 1 || snapshot.dispatchId !== lease.dispatchId || snapshot.segment !== (lease.segment ?? 0)
|
|
382
|
+
|| !validDirIdentity(snapshot.hostDir) || !validDirIdentity(snapshot.scratch)
|
|
383
|
+
|| (snapshot.pending !== null && !requested.includes(snapshot.pending))
|
|
384
|
+
|| !Array.isArray(snapshot.services) || snapshot.services.length > requested.length
|
|
385
|
+
|| (!snapshot.services.length && snapshot.pending === null)) return 'warning';
|
|
386
|
+
const ids = new Set(), pids = new Set();
|
|
387
|
+
for (const entry of snapshot.services) {
|
|
388
|
+
if (!hasKeys(entry, ['id', 'pid', 'pgid', 'startTime']) || !requested.includes(entry.id) || ids.has(entry.id) || entry.id === snapshot.pending
|
|
389
|
+
|| !validPid(entry.pid) || entry.pid <= 1 || entry.pgid !== entry.pid || pids.has(entry.pid)
|
|
390
|
+
|| typeof entry.startTime !== 'string' || !DESCENDANT_START.test(entry.startTime)) return 'warning';
|
|
391
|
+
ids.add(entry.id);
|
|
392
|
+
pids.add(entry.pid);
|
|
393
|
+
}
|
|
394
|
+
for (const entry of snapshot.services.reverse()) {
|
|
395
|
+
if (!await reapHostServiceGroup(entry, graceMs, lease.supervisor)) return 'warning';
|
|
396
|
+
}
|
|
397
|
+
if (snapshot.pending !== null || snapshot.services.length !== requested.length) return 'warning';
|
|
398
|
+
if (lease.child && hostServiceGroupStatus(lease.child.pid) !== 'gone') return 'warning';
|
|
399
|
+
const parent = adapter.scratchParent?.({uid});
|
|
400
|
+
if (parent) {
|
|
401
|
+
const parentStat = await fsp.lstat(parent);
|
|
402
|
+
if (!parentStat.isDirectory() || parentStat.uid !== uid) return 'warning';
|
|
403
|
+
}
|
|
404
|
+
const cleanup = {...quarantineOptions(artifactDir, anchorHome, lease), missingOk: true};
|
|
405
|
+
if (await hasRetainedCleanup(scratch, cleanup) || await hasRetainedCleanup(hostDir, cleanup)) return 'warning';
|
|
406
|
+
await collectEvidence({scratch, artifactDir, identity: snapshot.scratch, recovery: true});
|
|
407
|
+
await recoveryProcessTable(lease.supervisor);
|
|
408
|
+
if (lease.child && hostServiceGroupStatus(lease.child.pid) !== 'gone') return 'warning';
|
|
409
|
+
const scratchRemoved = await removeScratch(scratch, {...cleanup, identity: snapshot.scratch});
|
|
410
|
+
const hostRemoved = await removeScratch(hostDir, {...cleanup, identity: snapshot.hostDir});
|
|
411
|
+
return hostRemoved && scratchRemoved ? 'ok' : 'warning';
|
|
412
|
+
} catch { return 'warning'; }
|
|
413
|
+
finally { await file?.close().catch(() => {}); }
|
|
414
|
+
}
|
|
415
|
+
|
|
270
416
|
export {resolveWorktree};
|
|
271
417
|
export const artifactDirectory = (target, workflowId, dispatchId) => path.join(target.gitCommonDir, 'arc', 'workflows', workflowId, 'dispatches', dispatchId);
|
|
272
418
|
/** Segment 0 (the first run) keeps its files in the dispatch directory; resumed segments use segments/<n>/. */
|
|
@@ -278,9 +424,9 @@ export const geminiPolicyFile = (homes, role) => path.join(homes.gemini ?? '', '
|
|
|
278
424
|
export const grokPromptFile = resultPath => path.join(path.dirname(resultPath), 'prompt.md');
|
|
279
425
|
|
|
280
426
|
/** Builds the child CLI arguments from the hash-verified target profile. Errors carry reasonCode. */
|
|
281
|
-
export async function buildBridgeInvocation({lease, config, homes, worktree, resultPath, policy = DEFAULT_POLICY, supervisorImplementations = SUPERVISOR_IMPLEMENTATIONS}) {
|
|
427
|
+
export async function buildBridgeInvocation({lease, config, homes, worktree, resultPath, userHome, env = process.env, target = {}, runtimePlatforms, policy = DEFAULT_POLICY, supervisorImplementations = SUPERVISOR_IMPLEMENTATIONS, observeToolContext}) {
|
|
282
428
|
const fail = (reasonCode, message) => Object.assign(Error(message), {reasonCode});
|
|
283
|
-
const requested = config.roles[lease.role], platform = lease.version
|
|
429
|
+
const requested = config.roles[lease.role], platform = lease.version >= 2 ? lease.targetPlatform : requested.platform;
|
|
284
430
|
if (platform !== requested.platform) throw fail('activation_unverified', 'Lease target differs from the active role target');
|
|
285
431
|
const implementation = supervisorImplementations.get(platform);
|
|
286
432
|
if (platform === 'gemini' || platform === 'grok' || lease.hostPlatform === 'gemini' || lease.hostPlatform === 'grok') {
|
|
@@ -306,16 +452,32 @@ export async function buildBridgeInvocation({lease, config, homes, worktree, res
|
|
|
306
452
|
let bytes;
|
|
307
453
|
try { bytes = await fsp.readFile(file); } catch { throw fail('activation_unverified', 'Profile unreadable'); }
|
|
308
454
|
if (sha256(bytes) !== lease.profileHash) throw fail('activation_unverified', 'Profile hash differs from the reserved lease');
|
|
455
|
+
const {reasons} = toolAccessReasons({platform, role: lease.role, route: lease.route, toolAccess: lease.toolAccess, policy});
|
|
456
|
+
if (reasons.length) throw fail(reasons[0], 'Tool access is not available for this dispatch');
|
|
457
|
+
const cli = resolveLocalCli(platform, {cwd: worktree, userHome, env, runtimePlatforms});
|
|
458
|
+
if (lease.toolAccess !== undefined && cli.reason) throw fail('permission_scope_unverified', 'Tool access requires a local CLI');
|
|
459
|
+
const cliEnv = cli.reason ? env : localCliEnvironment(cli);
|
|
460
|
+
const toolContext = buildToolContext({
|
|
461
|
+
platform, role: lease.role, dispatchId: lease.dispatchId, toolAccess: lease.toolAccess, uid: process.getuid(),
|
|
462
|
+
userHome, homes, env: cliEnv, envNames: Object.keys(cliEnv), worktree, gitDir: target.gitDir, gitCommonDir: target.gitCommonDir, policy,
|
|
463
|
+
});
|
|
464
|
+
if (toolContext) {
|
|
465
|
+
const preflightReasons = await toolAccessPreflight({platform, role: lease.role, grants: toolContext.grants, worktree, userHome, homes, env: cliEnv, io: fsp});
|
|
466
|
+
if (preflightReasons.length) throw fail(preflightReasons[0], 'Tool access preflight failed');
|
|
467
|
+
}
|
|
309
468
|
let profile, args;
|
|
310
469
|
try {
|
|
311
470
|
profile = parseCompositeProfile(platform, bytes);
|
|
312
|
-
args = buildBridgeArgs(platform, {role: lease.role, profile, sessionId: lease.sessionId, worktree, resultPath, threadId: lease.sessionId, policy, policyFile: geminiPolicyFile(homes, lease.role), ...(platform === 'grok' ? {promptFile: grokPromptFile(resultPath), sandboxProfile: grokSandbox?.name} : {}), resume: lease.segment > 0});
|
|
471
|
+
args = buildBridgeArgs(platform, {role: lease.role, profile, sessionId: lease.sessionId, worktree, resultPath, threadId: lease.sessionId, policy, policyFile: geminiPolicyFile(homes, lease.role), ...(platform === 'grok' ? {promptFile: grokPromptFile(resultPath), sandboxProfile: grokSandbox?.name} : {}), resume: lease.segment > 0, toolContext});
|
|
313
472
|
} catch { throw fail('permission_scope_unverified', 'Profile arguments unavailable'); }
|
|
314
473
|
const expected = platform === 'claude'
|
|
315
474
|
? {model: requested.model, effort: requested.effort, tools: profile.tools, permissionMode: permissions.permissionMode}
|
|
316
475
|
: platform === 'gemini' || platform === 'grok' ? {model: requested.model, effort: 'default'}
|
|
317
|
-
: {model: requested.model, effort: requested.effort,
|
|
318
|
-
|
|
476
|
+
: {model: requested.model, effort: requested.effort,
|
|
477
|
+
sandboxMode: toolContext?.grants.mechanisms.includes('codexProfile') ? CODEX_PROFILE_SANDBOX_TYPE : permissions.sandboxMode,
|
|
478
|
+
approvalPolicy: 'never'};
|
|
479
|
+
observeToolContext?.(structuredClone(toolContext));
|
|
480
|
+
return {platform, args, argsDigest: argsDigest(args), expected, requested, toolContext, ...(platform === 'gemini' ? {stdinInstructions: profile.instructions} : {}), ...(platform === 'grok' ? {promptFile: {path: grokPromptFile(resultPath), instructions: profile.instructions}, childEnv: GROK_CONTRACT.childEnv} : {}), ...(grokSandbox ? {grokSandbox} : {})};
|
|
319
481
|
}
|
|
320
482
|
|
|
321
483
|
/** Starts this module as a detached supervisor process (own session, stdio ignored, unref'd). env defaults to the inherited environment. */
|
|
@@ -338,6 +500,9 @@ export async function runSupervisor(options) {
|
|
|
338
500
|
const eventsMax = options.eventsMaxBytes ?? policy.eventsMaxBytes, codexWaitMs = options.codexWaitMs ?? 10000;
|
|
339
501
|
const lockRetryMs = options.lockRetryMs ?? policy.lockRetryMs, lockDeadlineMs = options.lockDeadlineMs ?? 30000;
|
|
340
502
|
const startedAt = new Date().toISOString();
|
|
503
|
+
const scratchIo = {create: createScratch, collect: collectEvidence, remove: removeScratch, ...options.scratchIo};
|
|
504
|
+
const hostServiceIo = options.hostServiceIo;
|
|
505
|
+
const startService = hostServiceIo?.start ?? startHostService;
|
|
341
506
|
|
|
342
507
|
// Lease writes retry a busy lock; the supervisor never gives up a terminal write because of a short contention.
|
|
343
508
|
const locked = async fn => {
|
|
@@ -366,6 +531,7 @@ export async function runSupervisor(options) {
|
|
|
366
531
|
return true;
|
|
367
532
|
});
|
|
368
533
|
if (!guarded) return; // not the supervisor registered for this dispatch
|
|
534
|
+
const quarantine = quarantineOptions(artifactDir, codexHome, lease);
|
|
369
535
|
|
|
370
536
|
const timers = new Set();
|
|
371
537
|
let hbBusy = false;
|
|
@@ -373,9 +539,40 @@ export async function runSupervisor(options) {
|
|
|
373
539
|
await beat();
|
|
374
540
|
timers.add(setInterval(beat, heartbeatMs));
|
|
375
541
|
|
|
542
|
+
let createdScratch, scratchIdentity, createdHostDir, hostDirIdentity, toolAccessResult;
|
|
543
|
+
let hostServiceRecoveryWarning = false;
|
|
544
|
+
const hostServices = [];
|
|
545
|
+
const recordHostServiceRecovery = record => {
|
|
546
|
+
if (hostServiceRecoveryWarning) return;
|
|
547
|
+
try { record(); } catch { hostServiceRecoveryWarning = true; }
|
|
548
|
+
};
|
|
549
|
+
const finishToolAccess = async () => {
|
|
550
|
+
if (!createdScratch) return {};
|
|
551
|
+
return toolAccessResult ??= (async () => {
|
|
552
|
+
const {scratch, conditions} = createdScratch;
|
|
553
|
+
for (const service of [...hostServices].reverse()) {
|
|
554
|
+
if (!service.started) continue;
|
|
555
|
+
try { service.cleanup = await service.stop(); } catch { service.cleanup = 'warning'; }
|
|
556
|
+
}
|
|
557
|
+
let evidence = {copied: 0, skipped: [], truncated: false}, collected = false, removed = false;
|
|
558
|
+
try { evidence = await scratchIo.collect({scratch, artifactDir, identity: scratchIdentity}); collected = true; } catch { /* preserve terminal result */ }
|
|
559
|
+
try { removed = await scratchIo.remove(scratch, {...quarantine, identity: scratchIdentity}); } catch { /* reported below */ }
|
|
560
|
+
if (createdHostDir) {
|
|
561
|
+
if (!await removeScratch(createdHostDir, {...quarantine, identity: hostDirIdentity})) {
|
|
562
|
+
for (const service of hostServices) service.cleanup = 'warning';
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
const servicesRecord = createdScratch.hostDir ? {
|
|
566
|
+
hostServices: hostServices.map(({id, started, endpoint, cleanup}) => ({id, started, endpoint, cleanup})),
|
|
567
|
+
...(hostServiceRecoveryWarning ? {hostServiceRecovery: 'warning'} : {}),
|
|
568
|
+
} : {};
|
|
569
|
+
return {toolAccess: {conditions, scratch: {path: scratch, removed: collected && removed}, evidence, ...servicesRecord}};
|
|
570
|
+
})();
|
|
571
|
+
};
|
|
376
572
|
const writeRecord = async body => {
|
|
573
|
+
const toolAccessRecord = await finishToolAccess();
|
|
377
574
|
const file = path.join(artifactDir, 'record.json');
|
|
378
|
-
await fsp.writeFile(file, JSON.stringify({version: 1, dispatchId, role: lease.role, startedAt, endedAt: new Date().toISOString(), ...body}, null, 2) + '\n', {mode: 0o600});
|
|
575
|
+
await fsp.writeFile(file, JSON.stringify({version: 1, dispatchId, role: lease.role, startedAt, endedAt: new Date().toISOString(), ...body, ...toolAccessRecord}, null, 2) + '\n', {mode: 0o600});
|
|
379
576
|
await fsp.chmod(file, 0o600);
|
|
380
577
|
};
|
|
381
578
|
const commit = async (state, codes, claims, extra = {}) => {
|
|
@@ -475,7 +672,7 @@ export async function runSupervisor(options) {
|
|
|
475
672
|
const implementation = (options.supervisorImplementations ?? SUPERVISOR_IMPLEMENTATIONS).get(platform);
|
|
476
673
|
if (!implementation) throw Error('Invalid composite profile: unknown platform');
|
|
477
674
|
let invocation;
|
|
478
|
-
try { invocation = await buildBridgeInvocation({lease, config, homes, worktree: target.realpath, resultPath: resultFile, policy, supervisorImplementations: options.supervisorImplementations}); } catch (error) { return await earlyFailure(error.reasonCode ?? 'activation_unverified'); }
|
|
675
|
+
try { invocation = await buildBridgeInvocation({lease, config, homes, worktree: target.realpath, resultPath: resultFile, userHome, env, target, runtimePlatforms, policy, supervisorImplementations: options.supervisorImplementations, observeToolContext: options.observeToolContext}); } catch (error) { return await earlyFailure(error.reasonCode ?? 'activation_unverified'); }
|
|
479
676
|
if (invocation.argsDigest !== lease.argsDigest) return await earlyFailure('activation_unverified');
|
|
480
677
|
const brief = await fsp.readFile(path.join(artifactDir, 'brief.md'), 'utf8');
|
|
481
678
|
const cli = resolveLocalCli(platform, context);
|
|
@@ -495,6 +692,48 @@ export async function runSupervisor(options) {
|
|
|
495
692
|
const {path, sha256, dirCreated} = createdGrokProfile;
|
|
496
693
|
grokSandboxProfile = {name: invocation.grokSandbox.name, path, sha256, dirCreated, created: true, removed: null, dirRemoved: false, eventsBaseline: null, applied: null};
|
|
497
694
|
}
|
|
695
|
+
if (invocation.toolContext) {
|
|
696
|
+
const {scratch, parent, hostDir, grants} = invocation.toolContext;
|
|
697
|
+
try { scratchIdentity = await scratchIo.create({scratch, parent, uid: process.getuid(), ...quarantine}); }
|
|
698
|
+
catch (error) { return await earlyFailure(error.reasonCode ?? 'execution_failed'); }
|
|
699
|
+
createdScratch = invocation.toolContext;
|
|
700
|
+
if (hostDir) {
|
|
701
|
+
try {
|
|
702
|
+
await fsp.mkdir(hostDir, {mode: 0o700});
|
|
703
|
+
const stat = fs.lstatSync(hostDir);
|
|
704
|
+
if (!stat.isDirectory() || stat.uid !== process.geteuid()) throw Error('Host directory changed during creation');
|
|
705
|
+
hostDirIdentity = dirIdentity(stat);
|
|
706
|
+
createdHostDir = hostDir;
|
|
707
|
+
const recovery = {version: 1, dispatchId, segment: lease.segment ?? 0,
|
|
708
|
+
hostDir: hostDirIdentity, scratch: scratchIdentity, services: [], pending: null};
|
|
709
|
+
for (const id of grants.services) {
|
|
710
|
+
try {
|
|
711
|
+
// A crash during spawn leaves an explicit unverified entry until the identity is published.
|
|
712
|
+
recordHostServiceRecovery(() => {
|
|
713
|
+
recovery.pending = id;
|
|
714
|
+
writeHostServicesSnapshot(artifactDir, recovery);
|
|
715
|
+
});
|
|
716
|
+
hostServices.push(await startService({
|
|
717
|
+
id, dispatchId, scratch, userHome, timeoutMs: policy.probeTimeoutMs, io: hostServiceIo,
|
|
718
|
+
onSpawn(pid) {
|
|
719
|
+
recordHostServiceRecovery(() => {
|
|
720
|
+
const startTime = processStartTime(pid);
|
|
721
|
+
if (typeof startTime !== 'string' || !DESCENDANT_START.test(startTime)) throw Error('Host service start time unavailable');
|
|
722
|
+
recovery.services.push({id, pid, pgid: pid, startTime});
|
|
723
|
+
recovery.pending = null;
|
|
724
|
+
writeHostServicesSnapshot(artifactDir, recovery);
|
|
725
|
+
});
|
|
726
|
+
},
|
|
727
|
+
}));
|
|
728
|
+
} catch (error) {
|
|
729
|
+
hostServices.push({id, started: false, endpoint: null, cleanup: error.cleanup ?? 'ok'});
|
|
730
|
+
throw error;
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
await writeServicesFile(scratch, hostServices);
|
|
734
|
+
} catch { return await earlyFailure('execution_failed'); }
|
|
735
|
+
}
|
|
736
|
+
}
|
|
498
737
|
const extra = invocation.grokSandbox ? [
|
|
499
738
|
{label: 'grok-home:config.toml', path: path.join(homes.grok, 'config.toml'), project: grokConfigSecurityProjection},
|
|
500
739
|
{label: 'grok-home:sandbox.toml', path: path.join(homes.grok, 'sandbox.toml')},
|