@yunhozz/arc 0.4.2 → 0.4.3
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 +66 -42
- package/README.md +6 -6
- package/claude/skill/references/coordination.md +1 -1
- package/codex/skill/references/coordination.md +1 -1
- package/gemini/skill/references/coordination.md +1 -1
- package/grok/AGENTS.md +8 -0
- package/grok/agents/arc-implementer.md +37 -0
- package/grok/agents/arc-planner.md +47 -0
- package/grok/agents/arc-qa.md +37 -0
- package/grok/agents/arc-reviewer.md +39 -0
- package/grok/agents/arc-scouter.md +38 -0
- package/grok/instructions.md +4 -0
- package/grok/skill/SKILL.md +78 -0
- package/grok/skill/models.toml +23 -0
- package/grok/skill/references/arc-visual-companion.md +28 -0
- package/grok/skill/references/commit.md +55 -0
- package/grok/skill/references/coordination.md +149 -0
- package/grok/skill/references/git-recovery.md +34 -0
- package/grok/skill/references/handoff-prep.md +110 -0
- package/grok/skill/references/handoff.md +227 -0
- package/grok/skill/references/limits.md +31 -0
- package/grok/skill/references/planning.md +168 -0
- package/grok/skill/references/verification.md +155 -0
- package/grok/skill/references/worktree-creation.md +8 -0
- package/lib/installer/grok-compat.mjs +107 -0
- package/lib/installer/plan.mjs +7 -3
- package/lib/installer/runtime-assets.mjs +1 -0
- package/lib/installer/uninstall.mjs +14 -1
- package/lib/installer/upgrade-state.mjs +4 -2
- package/lib/installer/upgrade.mjs +5 -0
- package/lib/management/operations.mjs +1 -1
- package/lib/management/status.mjs +4 -2
- package/lib/management/update.mjs +4 -4
- package/lib/models/codex-models.json +72 -0
- package/lib/models/grok-models.json +7 -0
- package/lib/platforms/formats/grok-markdown.mjs +49 -0
- package/lib/platforms/grok.mjs +14 -0
- package/lib/platforms/index.mjs +2 -1
- package/lib/policy/role-policy.json +34 -15
- package/lib/prompts/agent-fragments.json +70 -0
- package/lib/prompts/render.mjs +6 -1
- package/lib/runtime/bootstrap.mjs +1 -1
- package/lib/runtime/grok-stream.mjs +46 -0
- package/lib/runtime/platform-registry.mjs +21 -0
- package/lib/runtime/role-bridge-args.mjs +40 -0
- package/lib/runtime/role-bridge.mjs +1 -1
- package/lib/runtime/role-dispatch-policy.mjs +4 -2
- package/lib/runtime/role-routing.mjs +2 -1
- package/lib/runtime/role-supervisor.mjs +57 -13
- package/lib/tui/app.mjs +18 -11
- package/lib/tui/custom-preset.mjs +6 -4
- package/lib/tui/mode.mjs +26 -3
- package/lib/tui/render.mjs +19 -8
- package/lib/tui/setup.mjs +5 -5
- package/lib/tui/terminal.mjs +1 -1
- package/lib/watch/status-line.mjs +10 -2
- package/package.json +2 -1
- package/scripts/update-manifest.mjs +2 -2
- package/shared/skill/references/superpowers-provenance.json +1 -1
- package/shared/skill/runtime/bootstrap.mjs +1 -1
- package/shared/skill/runtime/grok-stream.mjs +46 -0
- package/shared/skill/runtime/platform-registry.mjs +21 -0
- package/shared/skill/runtime/role-bridge-args.mjs +40 -0
- package/shared/skill/runtime/role-bridge.mjs +1 -1
- package/shared/skill/runtime/role-dispatch-policy.mjs +4 -2
- package/shared/skill/runtime/role-policy.json +34 -15
- package/shared/skill/runtime/role-routing.mjs +2 -1
- package/shared/skill/runtime/role-supervisor.mjs +57 -13
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// Pure helpers that turn an installed arc-routing profile into role-specific Claude/Codex CLI arguments. No processes are started here.
|
|
2
2
|
import crypto from 'node:crypto';
|
|
3
3
|
import path from 'node:path';
|
|
4
|
+
import {GROK_CONTRACT} from './grok-stream.mjs';
|
|
4
5
|
import {GEMINI_CONTRACT} from './gemini-stream.mjs';
|
|
5
6
|
import {DEFAULT_POLICY, effectiveClaudeSandboxSettings} from './role-dispatch-policy.mjs';
|
|
6
7
|
|
|
@@ -15,6 +16,13 @@ export const ROLE_BRIDGE_PERMISSIONS = deepFreeze({
|
|
|
15
16
|
arc_scouter: {approvalMode: 'plan', sandbox: false}, arc_planner: {approvalMode: 'plan', sandbox: false},
|
|
16
17
|
arc_implementer: {approvalMode: 'auto_edit', sandbox: true}, arc_qa: {approvalMode: 'auto_edit', sandbox: true}, arc_reviewer: {approvalMode: 'plan', sandbox: false}
|
|
17
18
|
},
|
|
19
|
+
grok: {
|
|
20
|
+
arc_scouter: {permissionMode: 'plan', sandbox: 'read-only', deny: GROK_CONTRACT.readOnlyDeny},
|
|
21
|
+
arc_planner: {permissionMode: 'plan', sandbox: 'read-only', deny: GROK_CONTRACT.readOnlyDeny},
|
|
22
|
+
arc_reviewer: {permissionMode: 'plan', sandbox: 'read-only', deny: GROK_CONTRACT.readOnlyDeny},
|
|
23
|
+
arc_implementer: {permissionMode: 'acceptEdits', sandbox: 'workspace', deny: []},
|
|
24
|
+
arc_qa: {permissionMode: 'acceptEdits', sandbox: 'workspace', deny: []},
|
|
25
|
+
},
|
|
18
26
|
codex: {
|
|
19
27
|
arc_scouter: {sandboxMode: 'read-only', search: true}, arc_planner: {sandboxMode: 'read-only', search: false},
|
|
20
28
|
arc_implementer: {sandboxMode: 'workspace-write', search: false}, arc_qa: {sandboxMode: 'workspace-write', search: false}, arc_reviewer: {sandboxMode: 'read-only', search: false}
|
|
@@ -25,6 +33,7 @@ const BRIDGE_IMPLEMENTATIONS = new Map([
|
|
|
25
33
|
['claude', {parse: parseClaude, buildArgs: buildClaudeArgs}],
|
|
26
34
|
['codex', {parse: parseCodex, buildArgs: buildCodexArgs}],
|
|
27
35
|
['gemini', {parse: parseGemini, buildArgs: buildGeminiArgs}],
|
|
36
|
+
['grok', {parse: parseGrok, buildArgs: buildGrokArgs}],
|
|
28
37
|
]);
|
|
29
38
|
export const BRIDGE_PLATFORM_IDS = Object.freeze([...BRIDGE_IMPLEMENTATIONS.keys()]);
|
|
30
39
|
|
|
@@ -79,6 +88,26 @@ function parseGemini(text) {
|
|
|
79
88
|
return {name: fields.name, description: fields.description, model: fields.model, effort: 'default', tools: null, instructions: match[2].replaceAll('\r\n', '\n')};
|
|
80
89
|
}
|
|
81
90
|
|
|
91
|
+
// ARC Grok metadata uses the same scalar grammar with an exact key set.
|
|
92
|
+
export function parseGrok(text) {
|
|
93
|
+
const match = /^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]+)$/.exec(text);
|
|
94
|
+
if (!match || !match[2].trim()) bad('missing Grok frontmatter or instructions');
|
|
95
|
+
const fields = {};
|
|
96
|
+
const nonStringScalar = /^(?:~|null|true|false|yes|no|on|off|[-+]?(?:\.inf|\.nan|0[xob][0-9a-f_]+|(?:\d[\d_]*(?:\.[\d_]*)?|\.[\d_]+)(?:e[-+]?\d+)?)|\d{4}-\d{2}-\d{2}(?:[Tt ].*)?)$/i;
|
|
97
|
+
for (const line of match[1].split(/\r?\n/)) {
|
|
98
|
+
const entry = /^([a-z][a-zA-Z0-9_-]*): (.+)$/.exec(line);
|
|
99
|
+
if (!entry || Object.hasOwn(fields, entry[1])) bad('malformed or duplicate Grok field');
|
|
100
|
+
const value = entry[2];
|
|
101
|
+
if (value !== value.trim() || /[\p{Cc}\u2028\u2029{}#&*!|>"']/u.test(value)
|
|
102
|
+
|| /^(?:[-?:](?:\s|$)|[\[\],%@`])/.test(value) || value.includes(': ') || nonStringScalar.test(value)) bad('unsupported Grok scalar');
|
|
103
|
+
fields[entry[1]] = value;
|
|
104
|
+
}
|
|
105
|
+
for (const key of ['name', 'description', 'model']) if (!fields[key]) bad(`missing ${key}`);
|
|
106
|
+
if (Object.keys(fields).length !== 3) bad('Grok fields must be exactly name, description, model');
|
|
107
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._:/@+\-]*$/.test(fields.model)) bad('invalid Grok model');
|
|
108
|
+
return {name: fields.name, description: fields.description, model: fields.model, effort: 'default', tools: null, instructions: match[2].replaceAll('\r\n', '\n')};
|
|
109
|
+
}
|
|
110
|
+
|
|
82
111
|
const ESCAPES = {b: '\b', t: '\t', n: '\n', f: '\f', r: '\r', '"': '"', '\\': '\\'};
|
|
83
112
|
// Decodes a TOML multiline basic string body; returns null when it is not terminated by """ on the same logical line.
|
|
84
113
|
function readMultiline(lines, index, rest) {
|
|
@@ -201,3 +230,14 @@ export function buildGeminiArgs({role, model, profile, sessionId, policyFile, pr
|
|
|
201
230
|
if (resume) args.push(GEMINI_CONTRACT.resumeFlag, sessionId);
|
|
202
231
|
return args;
|
|
203
232
|
}
|
|
233
|
+
|
|
234
|
+
export function buildGrokArgs({role, profile, sessionId, promptFile}) {
|
|
235
|
+
const permissions = permissionsFor('grok', role);
|
|
236
|
+
if (typeof promptFile !== 'string' || !path.isAbsolute(promptFile)) throw Error('Absolute promptFile required');
|
|
237
|
+
if (typeof sessionId !== 'string' || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(sessionId)) throw Error('Grok sessionId must be a UUID');
|
|
238
|
+
const model = requireText(profile?.model, 'model');
|
|
239
|
+
if (!/^[A-Za-z0-9][A-Za-z0-9._:/@+\-]*$/.test(model)) throw Error('Invalid Grok model');
|
|
240
|
+
return ['--prompt-file', promptFile, '--output-format', GROK_CONTRACT.outputFormat, '-m', model, '--session-id', sessionId,
|
|
241
|
+
'--permission-mode', permissions.permissionMode, '--sandbox', permissions.sandbox,
|
|
242
|
+
...permissions.deny.flatMap(rule => ['--deny', rule]), ...GROK_CONTRACT.isolationArgs];
|
|
243
|
+
}
|
|
@@ -143,7 +143,7 @@ export async function resumeRoleDispatch({context,dispatchId,brief,now=Date.now(
|
|
|
143
143
|
const lease=await readLease(anchorHome,dispatchId,{runtimePlatforms});
|
|
144
144
|
if(!lease||lease.workflowId!==context.workflowId||lease.hostPlatform!==context.hostPlatform||lease.route!=='bridge'||!['completed','failed'].includes(lease.state)){result=blank(context,dispatchId,'deny','invalid_request');return;}
|
|
145
145
|
const targetPlatform=leaseTargetPlatform(lease,runtimePlatforms);
|
|
146
|
-
if(targetPlatform==='gemini'&&!['on','verified'].includes(supervisorImplementations.get(targetPlatform)?.resume)){result=blank(context,dispatchId,'hold','resume_unverified');return;}
|
|
146
|
+
if((targetPlatform==='gemini'||targetPlatform==='grok')&&!['on','verified'].includes(supervisorImplementations.get(targetPlatform)?.resume)){result=blank(context,dispatchId,'hold','resume_unverified');return;}
|
|
147
147
|
if(!lease.sessionId){result=blank(context,dispatchId,'hold','execution_identity_unverified');return;}
|
|
148
148
|
let config;
|
|
149
149
|
try{config=await readActivation(homes,lease.revision,{anchorHome,host:context.hostPlatform,runtimePlatforms});}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {runtimeRegistryOf} from './platform-registry.mjs';
|
|
2
2
|
// Fixed policy values for composite role dispatch. G2 'escalation' means the bridge runs only with per-call user escalation approval on a Codex host; it is not a verified pass.
|
|
3
|
-
export const BRIDGE_GATE_RESULTS = Object.freeze({G1: 'fail', G2: 'escalation', G3: 'pass', G4: 'pass', G5: 'wide', G6: 'strict', G7: 'pass', G8: 'pass', GG1: 'fail', GG2: 'fail'});
|
|
3
|
+
export const BRIDGE_GATE_RESULTS = Object.freeze({G1: 'fail', G2: 'escalation', G3: 'pass', G4: 'pass', G5: 'wide', G6: 'strict', G7: 'pass', G8: 'pass', GG1: 'fail', GG2: 'fail', GK1: 'fail', GK2: 'fail'});
|
|
4
4
|
// No sandbox settings JSON has been recorded: G1 failed, so there is nothing to apply.
|
|
5
5
|
const RECORDED_CLAUDE_SANDBOX_SETTINGS = null;
|
|
6
6
|
const isRecordedObject = value => value !== null && typeof value === 'object' && !Array.isArray(value) && Object.keys(value).length > 0;
|
|
@@ -41,7 +41,7 @@ export const DEFAULT_POLICY = Object.freeze({
|
|
|
41
41
|
|
|
42
42
|
export const RELEASE_CONDITIONS = Object.freeze({
|
|
43
43
|
activation_unverified: 'Verify the active configuration, all prepared markers, installed bytes, host limits and the shared lock, and inspect the lease records in <anchor home>/arc-role-dispatch for unreadable or corrupted files.',
|
|
44
|
-
resume_unverified: 'Update ARC after verifying
|
|
44
|
+
resume_unverified: 'Update ARC after verifying platform session resume against the recorded session UUID.',
|
|
45
45
|
capability_not_verified: 'Update ARC to a release that verifies this platform capability.',
|
|
46
46
|
'Not Available': 'Install the target platform CLI so that it is found on PATH.',
|
|
47
47
|
Unauthorized: 'Authenticate the target platform CLI.',
|
|
@@ -87,6 +87,8 @@ export function bridgeGateReasons({platform, role, hostPlatform, policy = DEFAUL
|
|
|
87
87
|
const gates = policy.gates ?? BRIDGE_GATE_RESULTS, codes = [];
|
|
88
88
|
if (platform === 'claude' && (role === 'arc_implementer' || role === 'arc_qa') && effectiveClaudeSandboxSettings({gates, claudeSandboxSettings: policy.claudeSandboxSettings}) === null) codes.push('permission_scope_unverified');
|
|
89
89
|
if (platform === 'gemini' && (role === 'arc_implementer' || role === 'arc_qa') && gates.GG1 !== 'pass') codes.push('permission_scope_unverified');
|
|
90
|
+
if (platform === 'grok' && (role === 'arc_implementer' || role === 'arc_qa') && gates.GK1 !== 'pass') codes.push('permission_scope_unverified');
|
|
91
|
+
if (hostPlatform === 'grok' && gates.GK2 !== 'pass') codes.push('host_sandbox_blocked');
|
|
90
92
|
if (hostPlatform === 'gemini' && gates.GG2 !== 'pass') codes.push('host_sandbox_blocked');
|
|
91
93
|
if (platform === 'codex' && gates.G4 === 'fail') codes.push('permission_scope_unverified');
|
|
92
94
|
if (hostPlatform === 'codex' && gates.G2 === 'fail') codes.push('host_sandbox_blocked');
|
|
@@ -231,6 +231,7 @@ export async function prepareRoleDispatch({context,assignment,expectedRevision,n
|
|
|
231
231
|
const leases=await listLeases(anchorHome,{runtimePlatforms});
|
|
232
232
|
const live=leases.filter(lease=>NON_TERMINAL_STATES.includes(lease.state));
|
|
233
233
|
if(leases.some(lease=>lease.requestId===assignment.requestId)||live.some(lease=>lease.workflowId===context.workflowId&&lease.taskId===assignment.taskId&&lease.role===role)){duplicate=true;codes.add('duplicate_dispatch');}
|
|
234
|
+
if(host==='grok'&&(policy.gates?.GK2??DEFAULT_POLICY.gates.GK2)!=='pass')codes.add('host_sandbox_blocked');
|
|
234
235
|
if(host==='gemini'&&(policy.gates?.GG2??DEFAULT_POLICY.gates.GG2)!=='pass')codes.add('host_sandbox_blocked');
|
|
235
236
|
if(route==='bridge'){
|
|
236
237
|
let limits;try{limits=readHostLimits(resolveConfigHome(host,context));}catch{codes.add('activation_unverified');}
|
|
@@ -243,7 +244,7 @@ export async function prepareRoleDispatch({context,assignment,expectedRevision,n
|
|
|
243
244
|
result.reasons=[...codes].map(reason);
|
|
244
245
|
if(codes.size){result.decision=duplicate?'deny':'hold';return;}
|
|
245
246
|
const claims=initialClaims(route,policy,requested),iso=new Date(now).toISOString(),dispatchId=crypto.randomUUID();
|
|
246
|
-
const lease=await createLease(anchorHome,{version:2,targetPlatform:route==='native'?host:requested.platform,dispatchId,workflowId:context.workflowId,taskId:assignment.taskId,requestId:assignment.requestId,role,route,hostPlatform:host,executionEnvironment:environment,revision:config.revision,profileHash:await readProfileHash(homes[requested.platform],role),argsDigest:null,state:'reserved',supervisor:null,child:null,sessionId:route==='bridge'&&requested.platform==='gemini'?crypto.randomUUID():null,timeoutMinutes:policy.roleTimeoutMinutes[role],claims,reasons:[],allowedPaths:assignment.allowedPaths??[],resultPath:null,segment:0,nativeAgentId:null,createdAt:iso,updatedAt:iso},{runtimePlatforms,config});
|
|
247
|
+
const lease=await createLease(anchorHome,{version:2,targetPlatform:route==='native'?host:requested.platform,dispatchId,workflowId:context.workflowId,taskId:assignment.taskId,requestId:assignment.requestId,role,route,hostPlatform:host,executionEnvironment:environment,revision:config.revision,profileHash:await readProfileHash(homes[requested.platform],role),argsDigest:null,state:'reserved',supervisor:null,child:null,sessionId:route==='bridge'&&(requested.platform==='gemini'||requested.platform==='grok')?crypto.randomUUID():null,timeoutMinutes:policy.roleTimeoutMinutes[role],claims,reasons:[],allowedPaths:assignment.allowedPaths??[],resultPath:null,segment:0,nativeAgentId:null,createdAt:iso,updatedAt:iso},{runtimePlatforms,config});
|
|
247
248
|
Object.assign(result,{decision:'allow',routeStatus:'reserved',dispatchId:lease.dispatchId,claims});
|
|
248
249
|
},{retryMs:policy.lockRetryMs});
|
|
249
250
|
}catch(error){
|
|
@@ -6,6 +6,7 @@ import path from 'node:path';
|
|
|
6
6
|
import crypto from 'node:crypto';
|
|
7
7
|
import {spawn, spawnSync} from 'node:child_process';
|
|
8
8
|
import {fileURLToPath} from 'node:url';
|
|
9
|
+
import {GROK_CONTRACT, normalizeGrokStreamEvent, evaluateGrokObservation} from './grok-stream.mjs';
|
|
9
10
|
import {GEMINI_CONTRACT, normalizeGeminiStreamEvent, evaluateGeminiObservation} from './gemini-stream.mjs';
|
|
10
11
|
import {DEFAULT_POLICY, reason, bridgeGateReasons} from './role-dispatch-policy.mjs';
|
|
11
12
|
import {readLease, writeLease, writeHeartbeat, cancelRequested, TERMINAL_STATES} from './role-dispatch-store.mjs';
|
|
@@ -49,6 +50,19 @@ export const SUPERVISOR_IMPLEMENTATIONS = new Map([
|
|
|
49
50
|
},
|
|
50
51
|
session: state => state.geminiSessionId ?? state.init?.sessionId,
|
|
51
52
|
}],
|
|
53
|
+
['grok', {
|
|
54
|
+
resume: 'off',
|
|
55
|
+
normalize: normalizeGrokStreamEvent,
|
|
56
|
+
async observe({state, invocation, terminalClaim, lease}) {
|
|
57
|
+
const evaluation = evaluateGrokObservation({state, expected: invocation.expected, sessionId: lease.sessionId});
|
|
58
|
+
return {...evaluation, claims: {...evaluation.claims, terminal: terminalClaim}, effortMismatch: false, sessionId: lease.sessionId};
|
|
59
|
+
},
|
|
60
|
+
async resultPath(state, resultFile) {
|
|
61
|
+
if (!state.terminal || state.terminalError || typeof state.resultText !== 'string' || !state.resultText.trim()) return null;
|
|
62
|
+
await fsp.writeFile(resultFile, state.resultText, {mode: 0o600}); return resultFile;
|
|
63
|
+
},
|
|
64
|
+
session: state => state.grokSessionId,
|
|
65
|
+
}],
|
|
52
66
|
['codex', {
|
|
53
67
|
normalize: normalizeCodexStreamEvent,
|
|
54
68
|
async observe({state, invocation, readContext, policy, terminalClaim, lease}) {
|
|
@@ -89,17 +103,19 @@ export const segmentDirectory = (target, workflowId, dispatchId, segment) => seg
|
|
|
89
103
|
// U-P1: reserved path only; policy contents and installation await live format verification.
|
|
90
104
|
export const geminiPolicyFile = (homes, role) => path.join(homes.gemini ?? '', 'skills', 'arc', 'policies', `${role}.toml`);
|
|
91
105
|
|
|
106
|
+
export const grokPromptFile = resultPath => path.join(path.dirname(resultPath), 'prompt.md');
|
|
107
|
+
|
|
92
108
|
/** Builds the child CLI arguments from the hash-verified target profile. Errors carry reasonCode. */
|
|
93
109
|
export async function buildBridgeInvocation({lease, config, homes, worktree, resultPath, policy = DEFAULT_POLICY, supervisorImplementations = SUPERVISOR_IMPLEMENTATIONS}) {
|
|
94
110
|
const fail = (reasonCode, message) => Object.assign(Error(message), {reasonCode});
|
|
95
111
|
const requested = config.roles[lease.role], platform = lease.version === 2 ? lease.targetPlatform : requested.platform;
|
|
96
112
|
if (platform !== requested.platform) throw fail('activation_unverified', 'Lease target differs from the active role target');
|
|
97
113
|
const implementation = supervisorImplementations.get(platform);
|
|
98
|
-
if (platform === 'gemini' || lease.hostPlatform === 'gemini') {
|
|
114
|
+
if (platform === 'gemini' || platform === 'grok' || lease.hostPlatform === 'gemini' || lease.hostPlatform === 'grok') {
|
|
99
115
|
const gates = bridgeGateReasons({platform, role: lease.role, hostPlatform: lease.hostPlatform, policy});
|
|
100
|
-
if (gates.length) throw fail(gates[0], 'Gemini bridge gates are not verified');
|
|
116
|
+
if (gates.length) throw fail(gates[0], platform === 'grok' || lease.hostPlatform === 'grok' ? 'Grok bridge gates are not verified' : 'Gemini bridge gates are not verified');
|
|
101
117
|
}
|
|
102
|
-
if (platform === 'gemini' && lease.segment > 0 && !['on', 'verified'].includes(implementation?.resume)) throw fail('resume_unverified', 'Gemini resume is not verified');
|
|
118
|
+
if ((platform === 'gemini' || platform === 'grok') && lease.segment > 0 && !['on', 'verified'].includes(implementation?.resume)) throw fail('resume_unverified', platform === 'grok' ? 'Grok resume is not verified' : 'Gemini resume is not verified');
|
|
103
119
|
if (!implementation) throw fail('permission_scope_unverified', 'Invalid composite profile: unknown platform');
|
|
104
120
|
const file = path.join(homes[platform], 'agents', routingProfileFile(getPlatform(platform), lease.role));
|
|
105
121
|
let bytes;
|
|
@@ -108,14 +124,14 @@ export async function buildBridgeInvocation({lease, config, homes, worktree, res
|
|
|
108
124
|
let profile, args;
|
|
109
125
|
try {
|
|
110
126
|
profile = parseCompositeProfile(platform, bytes);
|
|
111
|
-
args = buildBridgeArgs(platform, {role: lease.role, profile, sessionId: lease.sessionId, worktree, resultPath, threadId: lease.sessionId, policy, policyFile: geminiPolicyFile(homes, lease.role), resume: lease.segment > 0});
|
|
127
|
+
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)} : {}), resume: lease.segment > 0});
|
|
112
128
|
} catch { throw fail('permission_scope_unverified', 'Profile arguments unavailable'); }
|
|
113
129
|
const permissions = ROLE_BRIDGE_PERMISSIONS[platform][lease.role];
|
|
114
130
|
const expected = platform === 'claude'
|
|
115
131
|
? {model: requested.model, effort: requested.effort, tools: profile.tools, permissionMode: permissions.permissionMode}
|
|
116
|
-
: platform === 'gemini' ? {model: requested.model, effort: 'default'}
|
|
132
|
+
: platform === 'gemini' || platform === 'grok' ? {model: requested.model, effort: 'default'}
|
|
117
133
|
: {model: requested.model, effort: requested.effort, sandboxMode: permissions.sandboxMode, approvalPolicy: 'never'};
|
|
118
|
-
return {platform, args, argsDigest: argsDigest(args), expected, requested, ...(platform === 'gemini' ? {stdinInstructions: profile.instructions} : {})};
|
|
134
|
+
return {platform, args, argsDigest: argsDigest(args), expected, requested, ...(platform === 'gemini' ? {stdinInstructions: profile.instructions} : {}), ...(platform === 'grok' ? {promptFile: {path: grokPromptFile(resultPath), instructions: profile.instructions}, childEnv: GROK_CONTRACT.childEnv} : {})};
|
|
119
135
|
}
|
|
120
136
|
|
|
121
137
|
/** Starts this module as a detached supervisor process (own session, stdio ignored, unref'd). env defaults to the inherited environment. */
|
|
@@ -216,16 +232,26 @@ export async function runSupervisor(options) {
|
|
|
216
232
|
let before;
|
|
217
233
|
try { before = await snapshotWorktree(target.realpath); } catch { return await earlyFailure('execution_failed'); }
|
|
218
234
|
|
|
235
|
+
if (invocation.promptFile) {
|
|
236
|
+
let promptFd;
|
|
237
|
+
try {
|
|
238
|
+
promptFd = fs.openSync(invocation.promptFile.path, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, 0o600);
|
|
239
|
+
fs.writeFileSync(promptFd, `${invocation.promptFile.instructions}\n\n${brief}`);
|
|
240
|
+
fs.fchmodSync(promptFd, 0o600);
|
|
241
|
+
} catch { return await earlyFailure('execution_failed'); }
|
|
242
|
+
finally { if (promptFd !== undefined) fs.closeSync(promptFd); }
|
|
243
|
+
}
|
|
219
244
|
eventsFd = fs.openSync(path.join(artifactDir, 'events.jsonl'), 'a', 0o600);
|
|
220
|
-
// The child is a process-group leader so one signal reaches its descendants.
|
|
221
|
-
child = spawn(cli.executable, invocation.args, {cwd: target.realpath, env: {...localCliEnvironment(cli), ARC_BRIDGE_CHILD: dispatchId}, detached: true, stdio: ['pipe', 'pipe', 'pipe'], shell: false});
|
|
245
|
+
// The child is a process-group leader so one signal reaches its descendants. The prompt uses the platform-specific input channel.
|
|
246
|
+
child = spawn(cli.executable, invocation.args, {cwd: target.realpath, env: {...localCliEnvironment(cli), ...invocation.childEnv, ARC_BRIDGE_CHILD: dispatchId}, detached: true, stdio: ['pipe', 'pipe', 'pipe'], shell: false});
|
|
222
247
|
let exitResolve, exited = false;
|
|
223
248
|
const exitPromise = new Promise(resolve => { exitResolve = resolve; });
|
|
224
249
|
child.on('exit', (code, signal) => { exited = true; exitResolve({code, signal}); });
|
|
225
250
|
child.on('error', () => { exited = true; exitResolve({code: null, signal: null, spawnError: true}); });
|
|
226
251
|
child.stdin.on('error', () => {});
|
|
227
252
|
if (options.afterSpawn) await options.afterSpawn(child); // test injection point for post-spawn failures
|
|
228
|
-
child.stdin.end(
|
|
253
|
+
if (platform === 'grok') child.stdin.end();
|
|
254
|
+
else child.stdin.end(invocation.stdinInstructions === undefined ? brief : `${invocation.stdinInstructions}\n\n${brief}`);
|
|
229
255
|
const stdoutClosed = new Promise(resolve => { child.stdout.on('close', resolve); child.stdout.on('error', resolve); });
|
|
230
256
|
|
|
231
257
|
const state = {init: null, initEval: null, threadId: null, codexEval: null, terminal: false, terminalError: false, resultText: undefined, messages: [], mismatch: null, internal: null};
|
|
@@ -273,6 +299,23 @@ export async function runSupervisor(options) {
|
|
|
273
299
|
const normalized = implementation.normalize(raw);
|
|
274
300
|
if (!normalized) return;
|
|
275
301
|
writeEvent(normalized);
|
|
302
|
+
if (platform === 'grok') {
|
|
303
|
+
if (normalized.kind !== 'unknown' && normalized.model !== undefined) {
|
|
304
|
+
if (normalized.model !== invocation.expected.model) state.grokModelMismatch = true;
|
|
305
|
+
state.grokModel = normalized.model;
|
|
306
|
+
}
|
|
307
|
+
if (normalized.kind === 'text' && typeof normalized.text === 'string') state.resultText = (state.resultText ?? '') + normalized.text;
|
|
308
|
+
if (normalized.kind === 'error') state.terminalError = true;
|
|
309
|
+
if (normalized.kind === 'end') {
|
|
310
|
+
state.terminal = true;
|
|
311
|
+
state.terminalError ||= !GROK_CONTRACT.successStopReasons.includes(normalized.stopReason);
|
|
312
|
+
if (normalized.sessionId !== undefined) {
|
|
313
|
+
if (normalized.sessionId !== lease.sessionId) state.grokSessionMismatch = true;
|
|
314
|
+
state.grokSessionId = normalized.sessionId;
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
return;
|
|
318
|
+
}
|
|
276
319
|
if (platform === 'gemini') {
|
|
277
320
|
if (normalized.kind !== 'unknown') {
|
|
278
321
|
if (normalized.sessionId) {
|
|
@@ -357,16 +400,17 @@ export async function runSupervisor(options) {
|
|
|
357
400
|
const observation = await implementation.observe({state, invocation, homes, requested, terminalClaim, lease, readContext, policy});
|
|
358
401
|
let {claims, sessionId} = observation;
|
|
359
402
|
const {effortMismatch} = observation;
|
|
360
|
-
const cancelledBeforeIdentity = platform === 'gemini' && terminating === 'cancel' && !implementation.session(state);
|
|
403
|
+
const cancelledBeforeIdentity = (platform === 'gemini' || platform === 'grok') && terminating === 'cancel' && !implementation.session(state);
|
|
361
404
|
if (observation.reason && !(cancelledBeforeIdentity && observation.reason === 'execution_identity_unverified') && !codes.includes(observation.reason)) codes.push(observation.reason);
|
|
362
405
|
if (platform === 'gemini' && terminating !== 'cancel' && (exit.code !== 0 || exit.signal || state.terminalError)) codes.push('execution_failed');
|
|
406
|
+
if (platform === 'grok' && terminating !== 'cancel' && (exit.code !== 0 || exit.signal || state.terminalError || !state.terminal)) codes.push('execution_failed');
|
|
363
407
|
if (effortMismatch) codes.push('model_effort_mismatch');
|
|
364
408
|
if (violations.reason) codes.push(violations.reason);
|
|
365
409
|
if (after === null) claims.permissions = {level: 'unverified', source: 'worktree-snapshot', details: 'post-run snapshot unavailable'};
|
|
366
410
|
else if (violations.reason) claims.permissions = {...claims.permissions, level: 'unverified', details: 'permission violation observed'};
|
|
367
411
|
if (terminating === 'timeout') codes.push('timeout');
|
|
368
412
|
|
|
369
|
-
const resultPath = await implementation.resultPath(state, resultFile);
|
|
413
|
+
const resultPath = platform === 'grok' && (exit.code !== 0 || exit.signal) ? null : await implementation.resultPath(state, resultFile);
|
|
370
414
|
if (resultPath) await fsp.chmod(resultPath, 0o600);
|
|
371
415
|
|
|
372
416
|
let finalState = 'failed';
|
|
@@ -383,14 +427,14 @@ export async function runSupervisor(options) {
|
|
|
383
427
|
claims.identity = {level: 'unverified', source: 'none'};
|
|
384
428
|
}
|
|
385
429
|
}
|
|
386
|
-
if (platform === 'gemini' && codes.includes('execution_identity_unverified') && terminating !== 'cancel') finalState = 'unknown';
|
|
430
|
+
if ((platform === 'gemini' || platform === 'grok') && codes.includes('execution_identity_unverified') && terminating !== 'cancel') finalState = 'unknown';
|
|
387
431
|
if (lease.sessionId && observedSession && observedSession !== lease.sessionId && finalState !== 'cancelled') {
|
|
388
432
|
// A resumed segment must continue the recorded session; a different observed id leaves the slot occupied.
|
|
389
433
|
finalState = 'unknown'; sessionId = lease.sessionId; if (!codes.includes('execution_identity_unverified')) codes.push('execution_identity_unverified');
|
|
390
434
|
claims.identity = {level: 'unverified', source: 'none'};
|
|
391
435
|
}
|
|
392
436
|
if (exit.spawnError && !codes.length) { codes.push('execution_failed'); finalState = 'failed'; }
|
|
393
|
-
await writeRecord({state: finalState, reasons: [...new Set(codes)], exit: {code: exit.code, signal: exit.signal}, terminatedBy: terminating, eventsTruncated, ignoredLines: parser.ignored, lineOverflow: parser.overflow, violations: {changedPaths: violations.changedPaths, headChanged: violations.headChanged, refsChanged: violations.refsChanged}, ...(orphanGroupReaped ? {orphanGroupReaped: true} : {}), argsDigest: invocation.argsDigest, resultPath, ...(platform === 'gemini' ? {unverifiedContracts: {delegation: GEMINI_CONTRACT.delegation}} : {})});
|
|
437
|
+
await writeRecord({state: finalState, reasons: [...new Set(codes)], exit: {code: exit.code, signal: exit.signal}, terminatedBy: terminating, eventsTruncated, ignoredLines: parser.ignored, lineOverflow: parser.overflow, violations: {changedPaths: violations.changedPaths, headChanged: violations.headChanged, refsChanged: violations.refsChanged}, ...(orphanGroupReaped ? {orphanGroupReaped: true} : {}), argsDigest: invocation.argsDigest, resultPath, ...(platform === 'gemini' ? {unverifiedContracts: {delegation: GEMINI_CONTRACT.delegation}} : platform === 'grok' ? {unverifiedContracts: {delegation: GROK_CONTRACT.delegation}} : {})});
|
|
394
438
|
await commit(finalState, codes, claims, {sessionId, resultPath});
|
|
395
439
|
} catch {
|
|
396
440
|
// Unexpected failure after the child started: stop it, then record a failed state if the child is gone.
|
package/lib/tui/app.mjs
CHANGED
|
@@ -5,16 +5,16 @@ import {createManagementContext,prepareOperation,executeOperation,forceFinishBlo
|
|
|
5
5
|
import {collectStatus} from '../management/status.mjs';
|
|
6
6
|
import {runInstallFlow,loadRoleDefaults,roleDisplayName} from './setup.mjs';
|
|
7
7
|
import {loadStaticModelCatalog} from '../models/static-catalog.mjs';
|
|
8
|
-
import {statusInfo} from './mode.mjs';
|
|
8
|
+
import {statusInfo,statusVersion} from './mode.mjs';
|
|
9
9
|
import {installerRegistryOf,platformLabel} from '../platforms/index.mjs';
|
|
10
10
|
const packageVersion=JSON.parse(readFileSync(new URL('../../package.json',import.meta.url),'utf8')).version;
|
|
11
|
-
const home=[{id:'install',label:'
|
|
11
|
+
const home=[{id:'install',label:'Configure'},{id:'status',label:'Status'},{id:'uninstall',label:'Uninstall'},{id:'exit',label:'Exit'}];
|
|
12
12
|
function goHome(){throw Object.assign(Error('Return home'),{code:'ARC_TUI_HOME'});}
|
|
13
13
|
function interrupted(){return Object.assign(Error('Session interrupted'),{code:'ARC_CANCELLED'});}
|
|
14
14
|
export function createTuiInterface(session,{input,controller}={}){
|
|
15
15
|
async function event(){const e=await session.nextEvent();if(e.name==='interrupt')throw interrupted();if(e.name==='eof')throw Object.assign(Error('Session closed'),{code:'ARC_TUI_EOF'});if(e.name==='error')throw e.error;return e;}
|
|
16
|
-
async function menu(title,rows,{selected=0,info=[],infoTones,notice=[],fitRows=false,backRow=false,backLabel='back',wordmark=false,version,renderBody,onHorizontal,refreshMs,hint='menu'}={}){
|
|
17
|
-
const actions=backRow?[...rows,'Back']:rows;
|
|
16
|
+
async function menu(title,rows,{selected=0,info=[],infoTones,notice=[],fitRows=false,backRow=false,actionKinds,backLabel='back',wordmark=false,version,renderBody,onHorizontal,refreshMs,hint='menu'}={}){
|
|
17
|
+
const actions=backRow?[...rows,'Back']:rows,kinds=rows.map((_,index)=>actionKinds?.[index]);if(backRow)kinds.push('cancel');
|
|
18
18
|
selected=actions.length?Math.max(0,Math.min(selected,actions.length-1)):0;
|
|
19
19
|
const animate=wordmark&&session.frameMs>0,pulse=typeof onHorizontal==='function'&&session.motion===true,tickMs=animate||pulse?session.frameMs:refreshMs;
|
|
20
20
|
let pending,settled,wake,timer,blink=true,frame=0,blinkElapsed=0,repainting=false;
|
|
@@ -27,14 +27,15 @@ export function createTuiInterface(session,{input,controller}={}){
|
|
|
27
27
|
const capacity=Math.max(1,viewport.rows-(wordmark?wordmarkRows(viewport):1)-information.length-noticeRows.length-4),offset=Math.max(0,Math.min(displayIndex-capacity+1,display.length-capacity)),visible=display.slice(offset,offset+capacity).map(row=>fitRows?fitChoiceRow(row,viewport.columns):row);
|
|
28
28
|
const screen={title,wordmark,version,frame,notices,rows:[...information,...visible],selected:actions.length?information.length+displayIndex-offset:undefined,hint:navigationHint(hint,{backLabel,horizontal:typeof onHorizontal==='function'}),...(display.length>capacity?{position:(offset+1)+'-'+Math.min(offset+capacity,display.length)+'/'+display.length}:{})};
|
|
29
29
|
if(infoTones){screen.rowTones=[...tones,...visible.map(()=>undefined)];screen.rowStatusSpans=spans;}
|
|
30
|
-
|
|
30
|
+
if(backRow||actionKinds)screen.rowKinds=[...information.map(()=>undefined),...kinds.slice(offset,offset+capacity)];
|
|
31
|
+
const body=renderBody?.({selected,blink,frame,...viewport});if(body){delete screen.rowTones;delete screen.rowStatusSpans;delete screen.rowKinds;if(body.rowKinds)screen.rowKinds=body.rowKinds;screen.rows=body.rows;screen.selected=body.selected;screen.showSelection=body.showSelection;screen.compactFooter=body.compactFooter;if(Object.hasOwn(body,'notices'))screen.notices=body.notices;if(Object.hasOwn(body,'position'))screen.position=body.position;}
|
|
31
32
|
const rendered=(repainting?(session.repaint??session.render):session.render).call(session,screen);pending??=event().then(e=>{settled={e};wake?.();},error=>{settled={error};wake?.();});
|
|
32
33
|
if(tickMs>0){if(!settled)await new Promise(resolve=>{wake=resolve;timer=setTimeout(resolve,tickMs);});clearTimeout(timer);timer=undefined;wake=undefined;if(!settled){if(animate||pulse)frame++;if(refreshMs>0){blinkElapsed+=tickMs;while(blinkElapsed>=refreshMs){blink=!blink;blinkElapsed-=refreshMs;}}repainting=true;continue;}}else await pending;
|
|
33
34
|
if(Object.hasOwn(settled,'error'))throw settled.error;const e=settled.e;pending=undefined;settled=undefined;repainting=false;
|
|
34
35
|
if(e.name==='up'&&actions.length)selected=(selected+actions.length-1)%actions.length;else if(e.name==='down'&&actions.length)selected=(selected+1)%actions.length;else if((e.name==='left'||e.name==='right')&&onHorizontal)onHorizontal({direction:e.name,selected,...viewport});else if(e.name==='escape'){if(backLabel==='exit')return null;goHome();}else if(e.name==='enter'&&actions.length&&rendered.selectionEnabled!==false)return backRow&&selected===rows.length?null:selected;
|
|
35
36
|
}}finally{if(timer!==undefined)clearTimeout(timer);}
|
|
36
37
|
}
|
|
37
|
-
async function text(title,initial=''){let value=initial,selected=2;while(true){const rendered=session.render({title,mode:'text',rows:[value,'','Save','Back',''],selected,hint:navigationHint('text')});const e=await event();if(e.name==='text'||e.name==='paste')value+=e.text;else if(e.name==='backspace')value=[...value].slice(0,-1).join('');else if(e.name==='up'||e.name==='down')selected=selected===2?3:2;else if(e.name==='escape')goHome();else if(e.name==='enter'&&rendered.selectionEnabled!==false)return selected===2?value:null;}}
|
|
38
|
+
async function text(title,initial=''){let value=initial,selected=2;while(true){const rendered=session.render({title,mode:'text',rows:[value,'','Save','Back',''],rowKinds:[undefined,undefined,'confirm','cancel',undefined],selected,hint:navigationHint('text')});const e=await event();if(e.name==='text'||e.name==='paste')value+=e.text;else if(e.name==='backspace')value=[...value].slice(0,-1).join('');else if(e.name==='up'||e.name==='down')selected=selected===2?3:2;else if(e.name==='escape')goHome();else if(e.name==='enter'&&rendered.selectionEnabled!==false)return selected===2?value:null;}}
|
|
38
39
|
async function page(title,rows){
|
|
39
40
|
let offset=0;
|
|
40
41
|
while(true){const viewport=session.viewport(),wrapped=wrapDetailRows(rows,viewport.columns),size=Math.max(1,viewport.rows-4),last=Math.max(0,wrapped.length-size);
|
|
@@ -95,8 +96,8 @@ export async function runTui(options={}){
|
|
|
95
96
|
if(!prepared)return;const result=await ui.busy(()=>api.executeOperation(context,prepared));code=result.code;
|
|
96
97
|
if(code!==130&&!result.exitSession&&!retried&&['composite','switch'].includes(prepared.kind)&&result.error?.blockingDispatches?.length){
|
|
97
98
|
const entries=result.error.blockingDispatches,eligible=entries.some(entry=>entry.forceFinishable);
|
|
98
|
-
if(await ui.menu('Active dispatches',eligible?['Force finish and retry']:[],{backRow:true,selected:1,...blockingInfo(entries,Date.now())})===0){
|
|
99
|
-
const notRetried='
|
|
99
|
+
if(await ui.menu('Active dispatches',eligible?['Force finish and retry']:[],{backRow:true,actionKinds:eligible?['confirm']:[],selected:1,...blockingInfo(entries,Date.now())})===0){
|
|
100
|
+
const notRetried='Configure was not retried.';let finished;
|
|
100
101
|
try{finished=await ui.busy(()=>api.forceFinishBlockingDispatches(context,entries));}
|
|
101
102
|
catch(error){if(['ARC_CANCELLED','ARC_TUI_EOF','ARC_TUI_HOME'].includes(error.code))throw error;await ui.page('Force finish',[...(error.forceFinish?.finished??[]).map(id=>'Finished: '+id),error.message,...(error.residualPaths??[]).map(p=>'Residual path: '+p),notRetried]);return false;}
|
|
102
103
|
if(finished.skipped.length||finished.residualPaths.length){await ui.page('Force finish',[...finished.finished.map(id=>'Finished: '+id),...finished.skipped.map(s=>`Skipped: ${s.dispatchId} (${s.reason})`),...finished.residualPaths.map(p=>'Residual path: '+p),notRetried]);return false;}
|
|
@@ -117,7 +118,7 @@ export async function runTui(options={}){
|
|
|
117
118
|
while(true){const choice=await ui.menu('Uninstall',[...platforms.map(({runtime:{id,label}})=>label+(installed(id)?'':' (not installed)')),'Everything (incl. CLI)'],{selected,backRow:true});if(choice===null)return null;selected=choice;
|
|
118
119
|
const single=choice<platforms.length,target=single?platforms[choice].runtime.id:'all';if(single&&!installed(target))continue;
|
|
119
120
|
const state=single?await loadInstallState():null,switching=single&&state.mode==='composite'&&state.platforms.includes(target);
|
|
120
|
-
const proceed=await ui.menu('Uninstall',['Remove'],{backRow:true,selected:1,info:[single?`Remove ARC from ${platformLabel(target,registry)}?`:'Remove ARC from all platforms and the arc CLI?',...(switching?['Mixed routing will be turned off.']:[])]});
|
|
121
|
+
const proceed=await ui.menu('Uninstall',['Remove'],{backRow:true,actionKinds:['danger'],selected:1,info:[single?`Remove ARC from ${platformLabel(target,registry)}?`:'Remove ARC from all platforms and the arc CLI?',...(switching?['Mixed routing will be turned off.']:[])]});
|
|
121
122
|
if(proceed===0)return ui.busy(()=>prepareRequest({kind:'uninstall',target,removeCli:!single,...(switching?{switchFromComposite:true}:{})}));
|
|
122
123
|
}
|
|
123
124
|
}
|
|
@@ -127,8 +128,14 @@ export async function runTui(options={}){
|
|
|
127
128
|
try{
|
|
128
129
|
let prepared;
|
|
129
130
|
if(action==='install'){const currentConfig=installState.mode==='composite'?await (api.readCompositeConfig?api.readCompositeConfig(context):readCompositeConfig(context)):undefined;prepared=await runInstallFlow({ui,statuses,draft,installState,currentConfig,loadRoleDefaults:target=>loadRoleDefaults({context,statuses,target}),loadCatalog:target=>api.loadCatalog?api.loadCatalog(target):loadStaticModelCatalog(target,{signal:controller.signal}),prepare:settings=>ui.busy(()=>prepareRequest(settings)),registry});}
|
|
130
|
-
else if(action==='status')
|
|
131
|
-
|
|
131
|
+
else if(action==='status'){
|
|
132
|
+
let failed;
|
|
133
|
+
try{prepared=await ui.busy(()=>prepareRequest({kind:'update'}));}
|
|
134
|
+
catch(error){if(['ARC_CANCELLED','ARC_TUI_EOF','ARC_TUI_HOME'].includes(error.code))throw error;failed=error;}
|
|
135
|
+
const version=statusVersion({prepared,failed,packageVersion}),showUpgrade=version.canUpgrade;
|
|
136
|
+
const choice=await ui.menu('Status',showUpgrade?['Upgrade']:[],{backRow:true,actionKinds:showUpgrade?['confirm']:[],selected:showUpgrade?1:0,...statusInfo(installState,statuses,registry,{version})});
|
|
137
|
+
if(choice!==0||!showUpgrade)prepared=null;
|
|
138
|
+
}
|
|
132
139
|
else if(action==='uninstall')prepared=await uninstall(statuses);
|
|
133
140
|
if(await execute(prepared,{request:lastRequest}))return code;
|
|
134
141
|
}catch(error){if(error.code==='ARC_TUI_HOME')continue;if(['ARC_CANCELLED','ARC_TUI_EOF'].includes(error.code))throw error;code=error.code==='ARC_CLI_INPUT'?2:1;try{await ui.page('Operation unavailable',[error.message,...(error.residualPaths??[]).map(p=>'Residual path: '+p),'No changes were applied.']);}catch(navigation){if(navigation.code!=='ARC_TUI_HOME')throw navigation;}}
|
|
@@ -51,6 +51,7 @@ function compactMenu(state, items, details, page) {
|
|
|
51
51
|
const visible = items.slice(offset, offset + capacity).map(row => compactRow(row, state.columns));
|
|
52
52
|
return {
|
|
53
53
|
rows: [...visible, 'Back'],
|
|
54
|
+
rowKinds: [...visible.map(() => undefined), 'cancel'],
|
|
54
55
|
notices: [...information, `←/→: Details ${detailPage + 1}/${detailPages}`],
|
|
55
56
|
selected: selected === items.length ? visible.length : selected - offset,
|
|
56
57
|
position: items.length > capacity ? `${offset + 1}-${offset + visible.length}/${items.length}` : null,
|
|
@@ -90,19 +91,20 @@ export async function selectCatalogPair({ ui, catalog, current, roleName }) {
|
|
|
90
91
|
if (state.columns < 40 || state.rows < 24) return modelPager.render(state, rows, compactDetails);
|
|
91
92
|
const guarded = detailGuard(info)(state);
|
|
92
93
|
if (guarded) return modelPager.render(state, rows, compactDetails);
|
|
93
|
-
const information = wrapDetailRows(info(state), state.columns), items = [...rows, 'Back'], display = [], starts = [], lengths = [];
|
|
94
|
+
const information = wrapDetailRows(info(state), state.columns), items = [...rows, 'Back'], display = [], kinds = [], starts = [], lengths = [];
|
|
94
95
|
for (let index = 0; index < items.length; index++) {
|
|
95
96
|
starts[index] = display.length;
|
|
96
97
|
const block = wrapDetailRows([items[index]], state.columns);
|
|
97
98
|
lengths[index] = block.length;
|
|
98
99
|
display.push(...block);
|
|
100
|
+
kinds.push(...block.map(() => index === items.length - 1 ? 'cancel' : undefined));
|
|
99
101
|
}
|
|
100
102
|
const selected = Math.max(0, Math.min(state.selected, items.length - 1)), commonCapacity = Math.max(1, state.rows - information.length - 5), positionNeeded = display.length > commonCapacity, reservedRows = positionNeeded ? 5 : 4, requiredRows = information.length + lengths[selected] + reservedRows;
|
|
101
103
|
if (state.rows < requiredRows) return modelPager.render(state, rows, compactDetails);
|
|
102
104
|
const capacity = Math.max(1, state.rows - information.length - reservedRows), maxOffset = Math.max(0, display.length - capacity);
|
|
103
105
|
const offset = Math.max(0, Math.min(maxOffset, starts[selected] + lengths[selected] - capacity));
|
|
104
106
|
modelPager.reset();
|
|
105
|
-
return { rows: display.slice(offset, offset + capacity), notices: info(state), selected: starts[selected] - offset, position: display.length > capacity ? `${offset + 1}-${Math.min(display.length, offset + capacity)}/${display.length}` : null };
|
|
107
|
+
return { rows: display.slice(offset, offset + capacity), rowKinds: kinds.slice(offset, offset + capacity), notices: info(state), selected: starts[selected] - offset, position: display.length > capacity ? `${offset + 1}-${Math.min(display.length, offset + capacity)}/${display.length}` : null };
|
|
106
108
|
};
|
|
107
109
|
const choice = await ui.menu(`Model — ${roleName}`, rows, {
|
|
108
110
|
selected: Math.max(0, models.indexOf(current.model)), backRow: true, notice: info,
|
|
@@ -144,7 +146,7 @@ export async function selectPlatform({ui, roleName, current, availabilityOf, reg
|
|
|
144
146
|
const information = info(state), items = [...rows, 'Back'];
|
|
145
147
|
const capacity = Math.max(1, state.rows - wrapDetailRows(information,state.columns).length - 5);
|
|
146
148
|
const offset = Math.max(0, Math.min(state.selected - capacity + 1, items.length - capacity));
|
|
147
|
-
return {rows: items.slice(offset, offset + capacity).map(row => compactRow(row, state.columns)), notices: information, selected: state.selected - offset, position: items.length > capacity ? `${offset + 1}-${Math.min(items.length, offset + capacity)}/${items.length}` : null};
|
|
149
|
+
return {rows: items.slice(offset, offset + capacity).map(row => compactRow(row, state.columns)), rowKinds: [...rows.map(() => undefined), 'cancel'].slice(offset, offset + capacity), notices: information, selected: state.selected - offset, position: items.length > capacity ? `${offset + 1}-${Math.min(items.length, offset + capacity)}/${items.length}` : null};
|
|
148
150
|
},
|
|
149
151
|
});
|
|
150
152
|
if (choice === null) return null;
|
|
@@ -218,7 +220,7 @@ export async function editRole({ui, roleName, current, availabilityOf, loadCatal
|
|
|
218
220
|
const notices = info(), items = editorRows(state).map(row => compactRow(row, state.columns));
|
|
219
221
|
const capacity = Math.max(1, state.rows - wrapDetailRows(notices, state.columns).length - 5);
|
|
220
222
|
const offset = Math.max(0, Math.min(state.selected - capacity + 1, items.length - capacity));
|
|
221
|
-
return {rows: items.slice(offset, offset + capacity), notices, selected: state.selected - offset, position: items.length > capacity ? `${offset + 1}-${Math.min(items.length, offset + capacity)}/${items.length}` : null};
|
|
223
|
+
return {rows: items.slice(offset, offset + capacity), rowKinds: [undefined, undefined, undefined, 'confirm', 'cancel'].slice(offset, offset + capacity), notices, selected: state.selected - offset, position: items.length > capacity ? `${offset + 1}-${Math.min(items.length, offset + capacity)}/${items.length}` : null};
|
|
222
224
|
},
|
|
223
225
|
});
|
|
224
226
|
if (choice === null) return null;
|
package/lib/tui/mode.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import {installerRegistryOf, mixedLabel} from '../platforms/index.mjs';
|
|
2
2
|
import {REASON_TEXT, supportedVersion} from '../platforms/availability.mjs';
|
|
3
3
|
import {cellWidth, escapeTerminalText} from './render.mjs';
|
|
4
|
+
import {isNewerVersion} from '../management/update.mjs';
|
|
4
5
|
|
|
5
6
|
// Preserve the State vocabulary and authentication precedence of the home renderer.
|
|
6
7
|
function stateLabel(status, runtime) {
|
|
@@ -34,13 +35,22 @@ export function homeModeLine(installState, statuses, registry = installerRegistr
|
|
|
34
35
|
return labels.length ? labels.join(', ') : 'Not installed';
|
|
35
36
|
}
|
|
36
37
|
|
|
37
|
-
export function
|
|
38
|
+
export function statusVersion({prepared = null, failed = null, packageVersion}) {
|
|
39
|
+
const currentVersion = prepared ? prepared.currentVersion : packageVersion;
|
|
40
|
+
const latestVersion = prepared?.latestVersion ?? null;
|
|
41
|
+
const canUpgrade = prepared?.canUpgrade ?? false;
|
|
42
|
+
const newerWithoutHarness = !!prepared && !canUpgrade && prepared.state.targets.length === 0 && latestVersion !== null && isNewerVersion(latestVersion, currentVersion);
|
|
43
|
+
const message = (prepared ? prepared.latestError : failed)?.message?.split(/[\r\n]/)[0] ?? null;
|
|
44
|
+
return {currentVersion, latestVersion, canUpgrade, newerWithoutHarness, message};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function statusInfo(installState, statuses, registry = installerRegistryOf(), {version} = {}) {
|
|
38
48
|
const platforms = registry.byDisplayOrder().flatMap(({runtime}) => {
|
|
39
49
|
const status = statuses.find(status => status.platform === runtime.id);
|
|
40
50
|
return status ? [{runtime, status, state: stateLabel(status, runtime)}] : [];
|
|
41
51
|
});
|
|
42
52
|
const width = text => [...escapeTerminalText(text)].reduce((sum, character) => sum + cellWidth(character), 0);
|
|
43
|
-
const labelWidth = Math.max(width('Mode'), ...platforms.map(({runtime}) => width(runtime.label)));
|
|
53
|
+
const labelWidth = Math.max(width('Mode'), ...(version ? [width('Version')] : []), ...platforms.map(({runtime}) => width(runtime.label)));
|
|
44
54
|
const row = (label, value) => label + ' '.repeat(labelWidth - width(label) + 3) + value;
|
|
45
55
|
const info = [row('Mode', homeModeLine(installState, statuses, registry)), ''];
|
|
46
56
|
const infoTones = [undefined, undefined], notes = new Map();
|
|
@@ -65,13 +75,26 @@ export function statusInfo(installState, statuses, registry = installerRegistryO
|
|
|
65
75
|
notes.get(message).add(runtime.label);
|
|
66
76
|
}
|
|
67
77
|
}
|
|
68
|
-
|
|
78
|
+
let versionNote;
|
|
79
|
+
if (version) {
|
|
80
|
+
const {currentVersion, latestVersion, canUpgrade, newerWithoutHarness, message} = version;
|
|
81
|
+
const value = canUpgrade || newerWithoutHarness ? `${currentVersion} → ${latestVersion}`
|
|
82
|
+
: latestVersion !== null ? `${currentVersion} · up to date` : `${currentVersion} · latest unavailable`;
|
|
83
|
+
info.push('', row('Version', value));
|
|
84
|
+
infoTones.push(undefined, undefined);
|
|
85
|
+
versionNote = newerWithoutHarness ? 'No installed ARC harness; run Configure first.' : latestVersion === null ? message : null;
|
|
86
|
+
}
|
|
87
|
+
if (notes.size || versionNote) {
|
|
69
88
|
info.push('', 'Notes');
|
|
70
89
|
infoTones.push(undefined, undefined);
|
|
71
90
|
for (const [message, labels] of notes) {
|
|
72
91
|
info.push(`• ${message} (${[...labels].join(', ')})`);
|
|
73
92
|
infoTones.push('note');
|
|
74
93
|
}
|
|
94
|
+
if (versionNote) {
|
|
95
|
+
info.push(`• ${versionNote}`);
|
|
96
|
+
infoTones.push('note');
|
|
97
|
+
}
|
|
75
98
|
}
|
|
76
99
|
return {info, infoTones};
|
|
77
100
|
}
|
package/lib/tui/render.mjs
CHANGED
|
@@ -60,18 +60,25 @@ export function wordmarkRows({columns=80,rows=24}={}){return columns-1>=24&&rows
|
|
|
60
60
|
export function renderScreen(screen={}, {columns=80,rows=24}={}){
|
|
61
61
|
// Leave the last column unused to avoid terminal autowrap at the right edge.
|
|
62
62
|
columns=Math.max(1,Math.floor(Number(columns)||80)-1);rows=Math.max(1,Math.floor(Number(rows)||24));
|
|
63
|
-
const entries=screen.rows??[],hint=screen.hint??navigationHint('menu'),full=wordmarkRows({columns:columns+1,rows})===8;
|
|
63
|
+
const entries=[...(screen.rows??[])],rowKinds=[...(screen.rowKinds??[])],rowTones=[...(screen.rowTones??[])],rowStatusSpans=[...(screen.rowStatusSpans??[])],hint=screen.hint??navigationHint('menu'),full=wordmarkRows({columns:columns+1,rows})===8;
|
|
64
|
+
let selected=screen.selected;
|
|
64
65
|
const version=screen.version?'ver '+escapeTerminalText(screen.version):'',tagline=' ✦ agent role coordination';
|
|
65
66
|
const fullTag=tagline+(version?' '+version:''),tag=version&&!fit(fullTag,columns).complete?' ✦ '+version:fullTag;
|
|
66
67
|
const frame=screen.frame??0,f=frame%36,sparkleFrame=f>=18?0:f,spinner='⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏'[frame%10];
|
|
67
68
|
const heading=screen.wordmark?[...(full?[...wordmark,tag]:['ARC ✦'+(version?' '+version:'')]),'─'.repeat(Math.min(columns,PANEL))]:[(screen.mode==='busy'?spinner+' ':'')+escapeTerminalText(screen.title)],position=screen.position?[escapeTerminalText(screen.position)]:[];
|
|
68
69
|
const notices=wrapDetailRows(screen.notices??[],columns+1);while(notices.at(-1)==='')notices.pop();
|
|
69
70
|
const footer=screen.compactFooter?[]:screen.mode==='busy'||screen.hint==='Session ended'?[escapeTerminalText(hint)]:[...(screen.mode==='text'||screen.mode==='page'||notices.length?[]:['']),'─'.repeat(columns),escapeTerminalText(hint)];
|
|
71
|
+
if(!screen.position)for(let k=1;k<entries.length;k++){
|
|
72
|
+
if(rowKinds[k]===undefined||rowKinds[k-1]!==undefined||entries[k-1]==='')continue;
|
|
73
|
+
if(heading.length+entries.length+1+position.length+(notices.length?notices.length+1:0)+footer.length>rows)continue;
|
|
74
|
+
entries.splice(k,0,'');rowKinds.splice(k,0,undefined);rowTones.splice(k,0,undefined);rowStatusSpans.splice(k,0,undefined);
|
|
75
|
+
if(selected>=k)selected++;k++;
|
|
76
|
+
}
|
|
70
77
|
const noticeStart=heading.length+entries.length+position.length,noticeLines=notices.length?['',...notices.map(row=>' '+row)]:[];
|
|
71
|
-
const showSelection=screen.showSelection!==false,lines=[...heading,...entries.map((row,index)=>(index===
|
|
78
|
+
const showSelection=screen.showSelection!==false,lines=[...heading,...entries.map((row,index)=>(index===selected&&showSelection?'> ':' ')+escapeTerminalText(row)),...position,...noticeLines,...footer];
|
|
72
79
|
const fitted=lines.map(line=>fit(line,columns)),tailSize=noticeLines.length+footer.length,bodySize=Math.max(0,rows-tailSize),bodyEnd=Math.min(noticeStart,bodySize);
|
|
73
80
|
const indices=[...Array.from({length:bodyEnd},(_,index)=>index),...(tailSize?Array.from({length:Math.min(rows,tailSize)},(_,index)=>lines.length-Math.min(rows,tailSize)+index):[])],visible=indices.map(index=>fitted[index].text),styles=[];
|
|
74
|
-
const selectedLine=heading.length+
|
|
81
|
+
const selectedLine=heading.length+selected;
|
|
75
82
|
for(let line=0;line<visible.length;line++){
|
|
76
83
|
const source=indices[line],runs=[];
|
|
77
84
|
function add(from,to,role,fg,bg,bold){
|
|
@@ -90,13 +97,17 @@ export function renderScreen(screen={}, {columns=80,rows=24}={}){
|
|
|
90
97
|
}
|
|
91
98
|
else if(screen.wordmark&&source===heading.length-1){for(let i=0;i<length;i++){let color=gradientAt(i/(length-1||1));if(i>=0.75*length)color=mix(color,[24,52,42],(i-0.75*length)/(0.25*length));add(i,i+1,'rule',color);}}
|
|
92
99
|
else if(!screen.wordmark&&source===0){if(screen.mode==='busy')add(0,1,'spinner',[52,211,153]);add(screen.mode==='busy'?2:0,length,'title',[110,231,183],undefined,true);}
|
|
93
|
-
else if(source===selectedLine&&showSelection&&Number.isInteger(
|
|
100
|
+
else if(source===selectedLine&&showSelection&&Number.isInteger(selected)&&selected>=0&&selected<entries.length&&source<bodyEnd){
|
|
94
101
|
const used=[...visible[line]].reduce((sum,character)=>sum+cellWidth(character),0),padding=Math.max(0,Math.min(columns,PANEL)-used);visible[line]+=' '.repeat(padding);
|
|
95
102
|
add(0,length,'selected',[236,253,245],[6,95,70],true);add(length,length+padding,'selectedPad',undefined,[9,70,53]);
|
|
96
103
|
}
|
|
97
|
-
else if(source>=heading.length&&source<heading.length+entries.length&&
|
|
98
|
-
const
|
|
99
|
-
|
|
104
|
+
else if(source>=heading.length&&source<heading.length+entries.length&&rowKinds[source-heading.length]){
|
|
105
|
+
const kind=rowKinds[source-heading.length],role=kind==='confirm'?'actionConfirm':kind==='cancel'?'actionCancel':'actionDanger';
|
|
106
|
+
add(2,length,role,kind==='confirm'?[52,211,153]:kind==='cancel'?[150,170,160]:[248,113,113],undefined,kind==='confirm');
|
|
107
|
+
}
|
|
108
|
+
else if(source>=heading.length&&source<heading.length+entries.length&&rowTones[source-heading.length]){
|
|
109
|
+
const tone=rowTones[source-heading.length],text=visible[line].slice(2);
|
|
110
|
+
if(tone==='status'||tone==='platform-status')for(const {from,to,role} of rowStatusSpans[source-heading.length]??(tone==='status'?statusSpans:platformStatusSpans)(entries[source-heading.length]))add(from+2,to+2,role,TONE_FG[role]);
|
|
100
111
|
else if(tone==='diagnostic'){const separator=text.indexOf(': ');if(separator>=0)add(2+[...text.slice(0,separator+2)].length,length,'warn',TONE_FG.warn);}
|
|
101
112
|
else if(tone==='diagnostic-cont'||tone==='note')add(2,length,'warn',TONE_FG.warn);
|
|
102
113
|
}
|
|
@@ -106,6 +117,6 @@ export function renderScreen(screen={}, {columns=80,rows=24}={}){
|
|
|
106
117
|
else if(footer.length>1&&source===lines.length-2)add(0,length,'rule',[36,140,106]);
|
|
107
118
|
if(runs.length)styles.push({line,runs});
|
|
108
119
|
}
|
|
109
|
-
const selectionEnabled=Number.isInteger(
|
|
120
|
+
const selectionEnabled=Number.isInteger(selected)&&selected>=0&&selected<entries.length&&selectedLine<bodyEnd&&fitted[selectedLine].complete;
|
|
110
121
|
return{text:visible.join('\n'),selectionEnabled,styles};
|
|
111
122
|
}
|
package/lib/tui/setup.mjs
CHANGED
|
@@ -54,7 +54,7 @@ export async function editInstallSettings({ui,settings}){
|
|
|
54
54
|
const rows=(state={})=>['Language '+display('language',state),'Total subagents '+display('maxTotalSubagents',state),'Concurrent subagents '+display('maxConcurrentSubagents',state),'Back'];
|
|
55
55
|
const cycleLanguage=()=>{settings.language=settings.language==='ko'?'en':'ko';settings.touched.add('language');};
|
|
56
56
|
while(true){
|
|
57
|
-
const choice=await ui.menu('Settings',rows(),{selected,onHorizontal:({selected})=>{if(selected===0)cycleLanguage();},renderBody:state=>({rows:rows(state),selected:state.selected,position:null})});
|
|
57
|
+
const choice=await ui.menu('Settings',rows(),{selected,onHorizontal:({selected})=>{if(selected===0)cycleLanguage();},renderBody:state=>({rows:rows(state),rowKinds:[undefined,undefined,undefined,'cancel'],selected:state.selected,position:null})});
|
|
58
58
|
if(choice===null||choice===3)return;
|
|
59
59
|
selected=choice;
|
|
60
60
|
if(choice===0){cycleLanguage();continue;}
|
|
@@ -86,7 +86,7 @@ export async function editHosts({ui,hosts,rolePlatforms,availabilityOf,registry=
|
|
|
86
86
|
const detail=feedback?.id===id?feedback.message:noneChangeable?'':reasonDetail(id,availability[selected],availability[selected].status,registry);
|
|
87
87
|
return detail?[...base,detail]:base;
|
|
88
88
|
};
|
|
89
|
-
const choice=await ui.menu('Hosts — CLIs where you start ARC sessions',[...rows,'Done'],{selected,backRow:true,notice:info,fitRows:true,hint:'checklist'});
|
|
89
|
+
const choice=await ui.menu('Hosts — CLIs where you start ARC sessions',[...rows,'Done'],{selected,backRow:true,actionKinds:[...rows.map(()=>undefined),'confirm'],notice:info,fitRows:true,hint:'checklist'});
|
|
90
90
|
if(choice===null)return null;
|
|
91
91
|
if(choice===ids.length)return ids.filter(id=>checked.has(id));
|
|
92
92
|
selected=choice;feedback=undefined;const id=ids[choice];if(!id)continue;
|
|
@@ -150,7 +150,7 @@ export async function runInstallFlow({ui,statuses,draft,installState,currentConf
|
|
|
150
150
|
const warningId=plan.platforms.find(id=>gates.get(id).warning==='auth_unverified');
|
|
151
151
|
const info=[...(installState.legacyAnchor&&plan.anchorMove?['Mixed routing files will move to the Claude home.']:[]),...(reason?[reason]:warningId?[`${platformLabel(warningId,registry)}: auth unverified`]:[])];
|
|
152
152
|
const controls=['Hosts: '+sortByDisplay(draft.hosts,registry).map(id=>platformLabel(id,registry)).join(', '),'Settings',`Apply - ${plan.modeLabel}`,'Back'];
|
|
153
|
-
const choice=await ui.menu('
|
|
153
|
+
const choice=await ui.menu('Configure',[...installRoleNames,...controls.slice(0,-1)],{
|
|
154
154
|
selected,backRow:true,refreshMs:600,notice:info,
|
|
155
155
|
renderBody:state=>{
|
|
156
156
|
const diagram=diagramRows(roleRows,{...state,selectedRole:state.selected<ROLES.length?state.selected:undefined,blocked,footerRows:wrapDetailRows(info,state.columns).length+controls.length,registry});
|
|
@@ -159,7 +159,7 @@ export async function runInstallFlow({ui,statuses,draft,installState,currentConf
|
|
|
159
159
|
const rows=[...diagramBody,...controls];
|
|
160
160
|
const selected=state.selected<ROLES.length?(diagram.mode==='compact'?state.selected:state.selected<3?0:8):diagramBody.length+state.selected-ROLES.length;
|
|
161
161
|
const capacity=Math.max(1,state.rows-wrapDetailRows(info,state.columns).length-5),offset=Math.max(0,Math.min(selected-capacity+1,rows.length-capacity));
|
|
162
|
-
return {rows:rows.slice(offset,offset+capacity),selected:selected-offset,notices:info,showSelection:diagram.mode==='compact'||state.selected>=ROLES.length,position:rows.length>capacity?`${offset+1}-${Math.min(rows.length,offset+capacity)}/${rows.length}`:null};
|
|
162
|
+
return {rows:rows.slice(offset,offset+capacity),rowKinds:[...diagramBody.map(()=>undefined),undefined,undefined,'confirm','cancel'].slice(offset,offset+capacity),selected:selected-offset,notices:info,showSelection:diagram.mode==='compact'||state.selected>=ROLES.length,position:rows.length>capacity?`${offset+1}-${Math.min(rows.length,offset+capacity)}/${rows.length}`:null};
|
|
163
163
|
},
|
|
164
164
|
});
|
|
165
165
|
if(choice===null)return null;
|
|
@@ -180,7 +180,7 @@ export async function runInstallFlow({ui,statuses,draft,installState,currentConf
|
|
|
180
180
|
await ui.page('Operation unavailable',[installState.reason??'Mixed routing configuration cannot be verified.',...(installState.residualPaths??[]).map(value=>'Residual path: '+value),'No changes were applied.']);continue;
|
|
181
181
|
}
|
|
182
182
|
if(plan.rule==='D1-b'){
|
|
183
|
-
const confirm=await ui.menu('Switch to '+platformLabel(plan.platforms[0],registry),['Continue'],{backRow:true,selected:1,info:['Mixed routing will be turned off.']});
|
|
183
|
+
const confirm=await ui.menu('Switch to '+platformLabel(plan.platforms[0],registry),['Continue'],{backRow:true,actionKinds:['confirm'],selected:1,info:['Mixed routing will be turned off.']});
|
|
184
184
|
if(confirm!==0)continue;
|
|
185
185
|
}
|
|
186
186
|
const prepared=await prepare(installPrepareOptions(plan,{...draft,registry},Object.fromEntries([...catalogs].map(([id,result])=>[id,result.catalog]))));
|