@yunhozz/arc 0.4.2 → 0.4.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 +91 -67
- package/README.md +7 -6
- package/claude/agents/arc-implementer.md +1 -0
- package/claude/agents/arc-planner.md +1 -0
- package/claude/agents/arc-qa.md +1 -0
- package/claude/agents/arc-reviewer.md +1 -0
- package/claude/agents/arc-scouter.md +1 -0
- package/claude/skill/SKILL.md +6 -3
- package/claude/skill/references/coordination.md +1 -1
- package/claude/skill/references/planning.md +36 -0
- package/codex/agents/arc-implementer.toml +1 -0
- package/codex/agents/arc-planner.toml +1 -0
- package/codex/agents/arc-qa.toml +1 -0
- package/codex/agents/arc-reviewer.toml +1 -0
- package/codex/agents/arc-scouter.toml +1 -0
- package/codex/skill/SKILL.md +6 -3
- package/codex/skill/references/coordination.md +1 -1
- package/codex/skill/references/planning.md +36 -0
- package/gemini/agents/arc-implementer.md +1 -0
- package/gemini/agents/arc-planner.md +1 -0
- package/gemini/agents/arc-qa.md +1 -0
- package/gemini/agents/arc-reviewer.md +1 -0
- package/gemini/agents/arc-scouter.md +1 -0
- package/gemini/skill/SKILL.md +6 -3
- package/gemini/skill/references/coordination.md +1 -1
- package/gemini/skill/references/planning.md +36 -0
- package/grok/AGENTS.md +8 -0
- package/grok/agents/arc-implementer.md +38 -0
- package/grok/agents/arc-planner.md +48 -0
- package/grok/agents/arc-qa.md +38 -0
- package/grok/agents/arc-reviewer.md +40 -0
- package/grok/agents/arc-scouter.md +39 -0
- package/grok/instructions.md +4 -0
- package/grok/skill/SKILL.md +81 -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 +204 -0
- package/grok/skill/references/verification.md +155 -0
- package/grok/skill/references/worktree-creation.md +8 -0
- package/lib/installer/global-config.mjs +8 -3
- package/lib/installer/grok-compat.mjs +107 -0
- package/lib/installer/language.mjs +54 -6
- package/lib/installer/plan.mjs +20 -14
- package/lib/installer/runtime-assets.mjs +1 -0
- package/lib/installer/uninstall.mjs +14 -1
- package/lib/installer/upgrade-state.mjs +13 -4
- package/lib/installer/upgrade.mjs +8 -3
- package/lib/management/operations.mjs +8 -5
- package/lib/management/status.mjs +26 -5
- 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/placement.mjs +2 -2
- package/lib/policy/render.mjs +1 -1
- package/lib/policy/role-policy.json +60 -15
- package/lib/prompts/agent-fragments.json +71 -1
- package/lib/prompts/render.mjs +7 -2
- 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 +40 -5
- package/lib/tui/render.mjs +19 -8
- package/lib/tui/setup.mjs +53 -36
- 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 +60 -15
- package/shared/skill/runtime/role-routing.mjs +2 -1
- package/shared/skill/runtime/role-supervisor.mjs +57 -13
|
@@ -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,16 +35,37 @@ 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
|
});
|
|
52
|
+
const settings = statuses.filter(status => status.state === 'installed' && status.settings).map(status => status.settings);
|
|
53
|
+
const settingsRows = settings.length ? [
|
|
54
|
+
['Run mode', ({runMode}) => runMode === 'full-auto' ? 'Full Auto' : 'Supervised'],
|
|
55
|
+
['Language', ({language}) => language === 'ko' ? 'Korean' : 'English'],
|
|
56
|
+
['Total subagents', ({limits}) => String(limits.max_total_subagents)],
|
|
57
|
+
['Concurrent subagents', ({limits}) => String(limits.max_concurrent_subagents)]
|
|
58
|
+
].map(([label, displayValue]) => {
|
|
59
|
+
const values = settings.map(displayValue);
|
|
60
|
+
return [label, values.every(value => value === values[0]) ? values[0] : 'mixed'];
|
|
61
|
+
}) : [];
|
|
42
62
|
const width = text => [...escapeTerminalText(text)].reduce((sum, character) => sum + cellWidth(character), 0);
|
|
43
|
-
const labelWidth = Math.max(width('
|
|
63
|
+
const labelWidth = Math.max(width('Installed on'), ...settingsRows.map(([label]) => width(label)),
|
|
64
|
+
...(version ? [width('Version')] : []), ...platforms.map(({runtime}) => width(runtime.label)));
|
|
44
65
|
const row = (label, value) => label + ' '.repeat(labelWidth - width(label) + 3) + value;
|
|
45
|
-
const info = [row('
|
|
46
|
-
|
|
66
|
+
const info = [row('Installed on', homeModeLine(installState, statuses, registry)),
|
|
67
|
+
...settingsRows.map(([label, value]) => row(label, value)), ''];
|
|
68
|
+
const infoTones = info.map(() => undefined), notes = new Map();
|
|
47
69
|
const humanize = value => value.replace(/\b[a-z]+(?:_[a-z0-9]+)+\b/g, token => REASON_TEXT[token] ?? token.replaceAll('_', ' '));
|
|
48
70
|
const diagnosticText = value => {
|
|
49
71
|
const code = value.trim();
|
|
@@ -65,13 +87,26 @@ export function statusInfo(installState, statuses, registry = installerRegistryO
|
|
|
65
87
|
notes.get(message).add(runtime.label);
|
|
66
88
|
}
|
|
67
89
|
}
|
|
68
|
-
|
|
90
|
+
let versionNote;
|
|
91
|
+
if (version) {
|
|
92
|
+
const {currentVersion, latestVersion, canUpgrade, newerWithoutHarness, message} = version;
|
|
93
|
+
const value = canUpgrade || newerWithoutHarness ? `${currentVersion} → ${latestVersion}`
|
|
94
|
+
: latestVersion !== null ? `${currentVersion} · up to date` : `${currentVersion} · latest unavailable`;
|
|
95
|
+
info.push('', row('Version', value));
|
|
96
|
+
infoTones.push(undefined, undefined);
|
|
97
|
+
versionNote = newerWithoutHarness ? 'No installed ARC harness; run Configure first.' : latestVersion === null ? message : null;
|
|
98
|
+
}
|
|
99
|
+
if (notes.size || versionNote) {
|
|
69
100
|
info.push('', 'Notes');
|
|
70
101
|
infoTones.push(undefined, undefined);
|
|
71
102
|
for (const [message, labels] of notes) {
|
|
72
103
|
info.push(`• ${message} (${[...labels].join(', ')})`);
|
|
73
104
|
infoTones.push('note');
|
|
74
105
|
}
|
|
106
|
+
if (versionNote) {
|
|
107
|
+
info.push(`• ${versionNote}`);
|
|
108
|
+
infoTones.push('note');
|
|
109
|
+
}
|
|
75
110
|
}
|
|
76
111
|
return {info, infoTones};
|
|
77
112
|
}
|
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
|
@@ -12,7 +12,9 @@ import {deriveInstallPlan} from './derive-install-plan.mjs';
|
|
|
12
12
|
import {diagramRows} from './diagram.mjs';
|
|
13
13
|
import {editRole} from './custom-preset.mjs';
|
|
14
14
|
import {arrowValue,cellWidth,wrapDetailRows} from './render.mjs';
|
|
15
|
-
const
|
|
15
|
+
const runModeName = value => value === 'full-auto' ? 'Full Auto' : 'Supervised';
|
|
16
|
+
const languageName = value => value === 'ko' ? 'Korean' : 'English';
|
|
17
|
+
const fullAutoNotice='Full Auto: ARC auto-approves specs, plans, choices; push/merge/holds ask you.';
|
|
16
18
|
export function loadRoleDefaults({context,statuses,target,readText=filename=>readFileSync(filename,'utf8')}) {
|
|
17
19
|
if(!installerRegistryOf(context).isPlatformId(target))throw new ModelValidationError('Unsupported role target');
|
|
18
20
|
const installed=statuses.find(status=>status.platform===target)?.settings?.modelConfig;
|
|
@@ -20,16 +22,20 @@ export function loadRoleDefaults({context,statuses,target,readText=filename=>rea
|
|
|
20
22
|
const resolved=resolveModelSettings(config,context);if(resolved.platform!==target)throw new ModelValidationError('Model configuration platform does not match target');
|
|
21
23
|
return resolved.roles;
|
|
22
24
|
}
|
|
23
|
-
const installSettingKeys=['language','maxTotalSubagents','maxConcurrentSubagents'];
|
|
25
|
+
const installSettingKeys=['runMode','language','maxTotalSubagents','maxConcurrentSubagents'];
|
|
24
26
|
const installRoleNames=['Scouter','Planner','Implementer','QA','Reviewer'];
|
|
25
27
|
export function roleDisplayName(role){return installRoleNames[ROLES.indexOf(role)]??role;}
|
|
26
28
|
|
|
27
29
|
export function installSettingsDraft(statuses,platforms){
|
|
28
|
-
const
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
30
|
+
const participatingStatuses=platforms.map(platform=>statuses.find(status=>status.platform===platform))
|
|
31
|
+
.filter(status=>status&&status.state!=='absent');
|
|
32
|
+
const values=participatingStatuses.map(({settings})=>({
|
|
33
|
+
runMode:settings?.runMode??'supervised',
|
|
34
|
+
language:settings?.language??'en',
|
|
35
|
+
maxTotalSubagents:settings?.limits?.max_total_subagents??100,
|
|
36
|
+
maxConcurrentSubagents:settings?.limits?.max_concurrent_subagents??5,
|
|
37
|
+
}));
|
|
38
|
+
const first=values[0]??{runMode:'supervised',language:'en',maxTotalSubagents:100,maxConcurrentSubagents:5};
|
|
33
39
|
return {...first,mixed:new Set(installSettingKeys.filter(key=>values.some(value=>value[key]!==first[key]))),touched:new Set()};
|
|
34
40
|
}
|
|
35
41
|
|
|
@@ -48,26 +54,6 @@ export function installPrepareOptions(plan,draft,catalog){
|
|
|
48
54
|
return {kind:'install',target:'composite',platforms:plan.platforms,config,settings};
|
|
49
55
|
}
|
|
50
56
|
|
|
51
|
-
export async function editInstallSettings({ui,settings}){
|
|
52
|
-
let selected=0;
|
|
53
|
-
const display=(key,state)=>settings.mixed.has(key)&&!settings.touched.has(key)?'(mixed)':key==='language'?arrowValue(languageLabel(settings[key]),state.frame,state.selected===0):String(settings[key]);
|
|
54
|
-
const rows=(state={})=>['Language '+display('language',state),'Total subagents '+display('maxTotalSubagents',state),'Concurrent subagents '+display('maxConcurrentSubagents',state),'Back'];
|
|
55
|
-
const cycleLanguage=()=>{settings.language=settings.language==='ko'?'en':'ko';settings.touched.add('language');};
|
|
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})});
|
|
58
|
-
if(choice===null||choice===3)return;
|
|
59
|
-
selected=choice;
|
|
60
|
-
if(choice===0){cycleLanguage();continue;}
|
|
61
|
-
const key=installSettingKeys[choice];if(!key)continue;
|
|
62
|
-
let raw=settings.mixed.has(key)&&!settings.touched.has(key)?'':String(settings[key]);
|
|
63
|
-
while(true){
|
|
64
|
-
raw=await ui.text(choice===1?'Total subagents':'Concurrent subagents',raw);if(raw===null)break;
|
|
65
|
-
let value;try{value=parsePositiveLimit(raw);}catch{await ui.page('Invalid limit',['Enter a positive whole number.']);continue;}
|
|
66
|
-
settings[key]=value;settings.touched.add(key);break;
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
|
|
71
57
|
export async function editHosts({ui,hosts,rolePlatforms,availabilityOf,registry=DEFAULT_INSTALLER_REGISTRY}){
|
|
72
58
|
const ids=registry.byDisplayOrder().map(descriptor=>descriptor.runtime.id),locked=new Set(rolePlatforms),checked=new Set([...hosts,...rolePlatforms]);
|
|
73
59
|
const labels=ids.map(id=>platformLabel(id,registry)),labelWidths=labels.map(label=>[...label].reduce((width,character)=>width+cellWidth(character),0)),suffixColumn=Math.max(0,...labelWidths)+2;
|
|
@@ -86,7 +72,7 @@ export async function editHosts({ui,hosts,rolePlatforms,availabilityOf,registry=
|
|
|
86
72
|
const detail=feedback?.id===id?feedback.message:noneChangeable?'':reasonDetail(id,availability[selected],availability[selected].status,registry);
|
|
87
73
|
return detail?[...base,detail]:base;
|
|
88
74
|
};
|
|
89
|
-
const choice=await ui.menu('Hosts — CLIs where you start ARC sessions',[...rows,'Done'],{selected,backRow:true,notice:info,fitRows:true,hint:'checklist'});
|
|
75
|
+
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
76
|
if(choice===null)return null;
|
|
91
77
|
if(choice===ids.length)return ids.filter(id=>checked.has(id));
|
|
92
78
|
selected=choice;feedback=undefined;const id=ids[choice];if(!id)continue;
|
|
@@ -149,17 +135,38 @@ export async function runInstallFlow({ui,statuses,draft,installState,currentConf
|
|
|
149
135
|
const reason=firstId?`! ${firstRole===undefined?'Hosts':installRoleNames[firstRole]}: ${platformLabel(firstId,registry)} - Unavailable (${REASON_TEXT[gates.get(firstId).reason]})`:null;
|
|
150
136
|
const warningId=plan.platforms.find(id=>gates.get(id).warning==='auth_unverified');
|
|
151
137
|
const info=[...(installState.legacyAnchor&&plan.anchorMove?['Mixed routing files will move to the Claude home.']:[]),...(reason?[reason]:warningId?[`${platformLabel(warningId,registry)}: auth unverified`]:[])];
|
|
152
|
-
const
|
|
153
|
-
const
|
|
138
|
+
const hostsRow='Hosts: '+sortByDisplay(draft.hosts,registry).map(id=>platformLabel(id,registry)).join(', ');
|
|
139
|
+
const isMixed=key=>settings.mixed.has(key)&&!settings.touched.has(key);
|
|
140
|
+
const display=(key,name=String,state,index)=>{
|
|
141
|
+
if(isMixed(key))return '(mixed)';
|
|
142
|
+
const label=name(settings[key]);
|
|
143
|
+
return state?arrowValue(label,state.frame,state.selected===index):label;
|
|
144
|
+
};
|
|
145
|
+
const controlsFor=state=>[
|
|
146
|
+
hostsRow,
|
|
147
|
+
'Run mode '+display('runMode',runModeName,state,6),
|
|
148
|
+
'Language '+display('language',languageName,state,7),
|
|
149
|
+
'Total subagents '+display('maxTotalSubagents'),
|
|
150
|
+
'Concurrent subagents '+display('maxConcurrentSubagents'),
|
|
151
|
+
`Apply - ${plan.modeLabel}`,'Back',
|
|
152
|
+
];
|
|
153
|
+
const cycleRunMode=()=>{settings.runMode=settings.runMode==='full-auto'?'supervised':'full-auto';settings.touched.add('runMode');};
|
|
154
|
+
const cycleLanguage=()=>{settings.language=settings.language==='ko'?'en':'ko';settings.touched.add('language');};
|
|
155
|
+
const choice=await ui.menu('Configure',[...installRoleNames,...controlsFor().slice(0,-1)],{
|
|
154
156
|
selected,backRow:true,refreshMs:600,notice:info,
|
|
157
|
+
onHorizontal:({selected})=>{if(selected===6)cycleRunMode();else if(selected===7)cycleLanguage();},
|
|
155
158
|
renderBody:state=>{
|
|
156
|
-
const
|
|
159
|
+
const controls=controlsFor(state);
|
|
160
|
+
const notices=settings.runMode==='full-auto'&&!isMixed('runMode')?[...info,fullAutoNotice]:info;
|
|
161
|
+
const noticeRows=wrapDetailRows(notices,state.columns).length;
|
|
162
|
+
const diagram=diagramRows(roleRows,{...state,selectedRole:state.selected<ROLES.length?state.selected:undefined,blocked,footerRows:noticeRows+controls.length,registry});
|
|
157
163
|
if(diagram.mode==='guard')return {rows:diagram.rows,notices:[],selected:undefined,position:null};
|
|
158
164
|
const diagramBody=diagram.mode==='compact'?diagram.rows.slice(0,ROLES.length):diagram.rows;
|
|
159
165
|
const rows=[...diagramBody,...controls];
|
|
160
166
|
const selected=state.selected<ROLES.length?(diagram.mode==='compact'?state.selected:state.selected<3?0:8):diagramBody.length+state.selected-ROLES.length;
|
|
161
|
-
const capacity=Math.max(1,state.rows-
|
|
162
|
-
|
|
167
|
+
const capacity=Math.max(1,state.rows-noticeRows-5),offset=Math.max(0,Math.min(selected-capacity+1,rows.length-capacity));
|
|
168
|
+
const rowKinds=[...diagramBody.map(()=>undefined),...controls.map((_,i)=>i===controls.length-2?'confirm':i===controls.length-1?'cancel':undefined)];
|
|
169
|
+
return {rows:rows.slice(offset,offset+capacity),rowKinds:rowKinds.slice(offset,offset+capacity),selected:selected-offset,notices,showSelection:diagram.mode==='compact'||state.selected>=ROLES.length,position:rows.length>capacity?`${offset+1}-${Math.min(rows.length,offset+capacity)}/${rows.length}`:null};
|
|
163
170
|
},
|
|
164
171
|
});
|
|
165
172
|
if(choice===null)return null;
|
|
@@ -173,14 +180,24 @@ export async function runInstallFlow({ui,statuses,draft,installState,currentConf
|
|
|
173
180
|
}else if(choice===5){
|
|
174
181
|
const hosts=await editHosts({ui,hosts:draft.hosts,rolePlatforms:ROLES.map(role=>draft.roles[role].platform),availabilityOf:id=>availabilityOf(id,'host'),registry});
|
|
175
182
|
if(hosts!==null)draft.hosts=hosts;
|
|
176
|
-
}else if(choice===6)
|
|
177
|
-
else if(choice===7)
|
|
183
|
+
}else if(choice===6)cycleRunMode();
|
|
184
|
+
else if(choice===7)cycleLanguage();
|
|
185
|
+
else if(choice===8||choice===9){
|
|
186
|
+
const key=choice===8?'maxTotalSubagents':'maxConcurrentSubagents';
|
|
187
|
+
const title=choice===8?'Total subagents':'Concurrent subagents';
|
|
188
|
+
let raw=isMixed(key)?'':String(settings[key]);
|
|
189
|
+
while(true){
|
|
190
|
+
raw=await ui.text(title,raw);if(raw===null)break;
|
|
191
|
+
let value;try{value=parsePositiveLimit(raw);}catch{await ui.page('Invalid limit',['Enter a positive whole number.']);continue;}
|
|
192
|
+
settings[key]=value;settings.touched.add(key);break;
|
|
193
|
+
}
|
|
194
|
+
}else if(choice===10){
|
|
178
195
|
if(reason)continue;
|
|
179
196
|
if(plan.rule==='D1-f'){
|
|
180
197
|
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
198
|
}
|
|
182
199
|
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.']});
|
|
200
|
+
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
201
|
if(confirm!==0)continue;
|
|
185
202
|
}
|
|
186
203
|
const prepared=await prepare(installPrepareOptions(plan,{...draft,registry},Object.fromEntries([...catalogs].map(([id,result])=>[id,result.catalog]))));
|
package/lib/tui/terminal.mjs
CHANGED
|
@@ -3,7 +3,7 @@ import {renderScreen} from './render.mjs';
|
|
|
3
3
|
import {toAnsi256} from '../color/palette.mjs';
|
|
4
4
|
export {toAnsi256};
|
|
5
5
|
|
|
6
|
-
const BASIC={logo:'92',shadow:'32',sparkle:'92',tagline:'32',version:'32',rule:'32',title:'1;92',spinner:'32',selected:'42;30',selectedPad:'42',hint:'2',hintSep:'2',position:'2',ok:'32',muted:'2',error:'31',warn:'33'};
|
|
6
|
+
const BASIC={logo:'92',shadow:'32',sparkle:'92',tagline:'32',version:'32',rule:'32',title:'1;92',spinner:'32',selected:'42;30',selectedPad:'42',actionConfirm:'1;32',actionCancel:'2',actionDanger:'31',hint:'2',hintSep:'2',position:'2',ok:'32',muted:'2',error:'31',warn:'33'};
|
|
7
7
|
const rgb=color=>[0,1,2].map(index=>Math.max(0,Math.min(255,Math.round(Number(color[index])||0))));
|
|
8
8
|
export function formatLine(line,style,depth){
|
|
9
9
|
if(depth==='none'||!style?.runs?.length)return line;
|