Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
741 lines (678 loc) · 23.9 KB
/
Copy pathindex.js
File metadata and controls
741 lines (678 loc) · 23.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
#!/usr/bin/env node
/**
* Browser CLI v0.1 — Playwright REPL for AI Agents + Human Users
*
* Layered architecture:
* stdin → parser → policy → dispatcher → handlers → wrapper → stdout
*
* Modes:
* local (default): launches new Chromium per invocation
* CDP: connects to external Chrome via --cdp http://localhost:<port>
*
* Flags:
* --config <path> Config file (JSON)
* --show Headed browser (local mode)
* --login <profile> Auto-login after boot
* --force-login Skip session marker check, force login flow
* --response-schema=v1|v2 Response format (default v1)
* --policy=safe|normal|aggressive Tier mode (default normal)
* --log-file <path> ndjson structured log
* --run-id <id> Optional run identifier
* --clean=true|false Normalize text output whitespace (default true)
* --input <path|- > Trinity Tool Contract v1.0 input envelope
*
* (v0.1 new)
* --cdp <url> Connect via CDP (http://localhost:<port>)
* --cmd "<command>" Run single command and exit
* --tab-index <N> Target tab index on CDP connect (default 0)
* --new-context Create new context instead of reusing
* --reuse-tab Prefer reusing existing tab; refuse to create hidden one
* --viewport <WxH> Initial viewport, e.g. 1440x900
* --focus-on-connect Bring Chrome window to front on connect (default OFF
* — set to avoid focus-stealing when AI runs in background)
* --agent-name <name> Tag AI actions in log (default "unknown")
* --event-port <N> Event server port (default 9876, CDP mode)
* --actions-log <path> Unified action log (default /tmp/browser-cli-actions.ndjson)
* --no-recorder Disable auto-inject recorder in CDP mode
*/
'use strict';
const { chromium } = require('playwright');
const fs = require('fs');
const path = require('path');
const readline = require('readline');
const { load: loadConfig } = require('./lib/config-loader');
const parser = require('./lib/parser');
const policy = require('./lib/policy');
const { wrap } = require('./lib/wrapper');
const { Logger } = require('./lib/logger');
const { createCollector } = require('./lib/artifacts');
const { createSession } = require('./lib/session');
const { ERROR_CODES, classify: classifyError } = require('./lib/errors');
const commands = require('./lib/commands');
const cdp = require('./lib/cdp');
const { buildRecorderScript } = require('./lib/recorder');
const eventServer = require('./lib/event-server');
const { ActionLogger } = require('./lib/action-logger');
const { resolveInitialViewport } = require('./lib/viewport');
const contract = require('./lib/contract');
const pkg = require('./package.json');
// ─── Parse CLI args ───
function parseBoolFlag(value, fallback = false) {
if (value == null) return fallback;
const normalized = String(value).trim().toLowerCase();
if (['false', '0', 'no', 'off', 'raw'].includes(normalized)) return false;
if (['true', '1', 'yes', 'on', 'clean'].includes(normalized)) return true;
return fallback;
}
function parseArgs(argv) {
const a = argv.slice(2);
const has = (flag) => a.includes(flag);
const val = (flag) => {
const i = a.indexOf(flag);
return i >= 0 && i + 1 < a.length ? a[i + 1] : null;
};
const kv = (prefix) => {
const found = a.find(x => x.startsWith(prefix + '='));
return found ? found.slice(prefix.length + 1) : null;
};
return {
show: has('--show'),
configPath: val('--config'),
autoLogin: has('--login') ? (val('--login') || 'backend') : null,
forceLogin: has('--force-login'),
responseSchema: kv('--response-schema') || val('--response-schema') || (val('--input') ? 'v3' : 'v1'),
policyMode: kv('--policy') || val('--policy') || null,
logFile: val('--log-file'),
runId: val('--run-id'),
clean: parseBoolFlag(kv('--clean') || val('--clean'), true),
inputPath: val('--input'),
// v0.1 new flags
cdpUrl: val('--cdp'),
cmdInline: val('--cmd'),
tabIndex: parseInt(val('--tab-index') || '0', 10),
newContext: has('--new-context'),
reuseTab: has('--reuse-tab'),
viewport: val('--viewport'),
focusOnConnect: has('--focus-on-connect'),
agentName: val('--agent-name') || process.env.AGENT_NAME || 'unknown',
eventPort: parseInt(val('--event-port') || '9876', 10),
actionsLog: val('--actions-log') || '/tmp/browser-cli-actions.ndjson',
noRecorder: has('--no-recorder'),
};
}
const CLI = parseArgs(process.argv);
let contractEnvelope = null;
if (CLI.inputPath) {
try {
contractEnvelope = contract.readEnvelope(CLI.inputPath);
const validation = contract.validateEnvelope(contractEnvelope);
if (!validation.ok) {
process.stdout.write(JSON.stringify({
contract_version: '1.0',
tool: 'browser-cli',
tool_version: pkg.version,
run_id: contractEnvelope && contractEnvelope.run_id ? contractEnvelope.run_id : 'invalid-input',
action: contractEnvelope && contractEnvelope.action ? contractEnvelope.action : 'browser.invalid',
status: 'FAIL',
verdict: {
code: 'INVALID_INPUT',
summary: validation.error,
promotion_allowed: false,
evidence_complete: true,
decided_by: 'tool',
},
artifacts: [],
logs: [],
errors: [{
code: 'INVALID_INPUT',
message: validation.error,
recoverable: false,
category: 'INVALID_INPUT',
}],
retry: { safe: false, reason: 'Fix the input envelope before retrying.' },
meta: { duration_ms: 0, timestamp: new Date().toISOString(), schema: 'v3' },
}) + '\n');
process.exit(2);
}
if (!CLI.runId) CLI.runId = contractEnvelope.run_id;
if (!CLI.policyMode && contractEnvelope.constraints) CLI.policyMode = contractEnvelope.constraints.policy_tier;
if (!CLI.logFile && contractEnvelope.audit && contractEnvelope.audit.log_path) {
CLI.logFile = contractEnvelope.audit.log_path;
}
} catch (err) {
process.stdout.write(JSON.stringify({
contract_version: '1.0',
tool: 'browser-cli',
tool_version: pkg.version,
run_id: 'invalid-input',
action: 'browser.invalid',
status: 'FAIL',
verdict: {
code: 'INVALID_INPUT',
summary: err.message,
promotion_allowed: false,
evidence_complete: true,
decided_by: 'tool',
},
artifacts: [],
logs: [],
errors: [{
code: 'INVALID_INPUT',
message: err.message,
recoverable: false,
category: 'INVALID_INPUT',
}],
retry: { safe: false, reason: 'Fix the input envelope before retrying.' },
meta: { duration_ms: 0, timestamp: new Date().toISOString(), schema: 'v3' },
}) + '\n');
process.exit(2);
}
}
// ─── Load config ───
const { config: loadedConfig, errors: configErrors } = loadConfig(CLI.configPath);
if (configErrors.length) {
for (const err of configErrors) process.stderr.write(`Config warning: ${err}\n`);
}
const config = loadedConfig;
if (contractEnvelope && contractEnvelope.artifacts && contractEnvelope.artifacts.base_dir) {
config.downloadDir = contractEnvelope.artifacts.base_dir;
}
const initialViewport = resolveInitialViewport({
cliValue: CLI.viewport,
config,
env: process.env,
});
// ─── Load helpers (YAML macros) ───
let helpers = {};
if (config.helpers && CLI.configPath) {
const helpersPath = path.resolve(path.dirname(CLI.configPath), config.helpers);
if (fs.existsSync(helpersPath)) {
try {
const yaml = require('yaml');
const parsed = yaml.parse(fs.readFileSync(helpersPath, 'utf8'));
helpers = parsed.helpers || {};
} catch (e) { /* ignore */ }
}
}
// ─── Resolve policy mode ───
const policyMode = policy.resolveMode({
cliFlag: CLI.policyMode,
configValue: config.policy && config.policy.mode,
envValue: process.env.BROWSER_CLI_POLICY,
});
// ─── Logger ───
const logger = new Logger({ logFile: CLI.logFile, enableHuman: true });
// ─── Globals ───
let browser, context, page;
let eventSrv = null;
let actionLogger = null;
const state = {
ajaxLog: [],
consoleLog: [],
monitoringAjax: false,
monitoringConsole: false,
};
const session = createSession();
const isCdpMode = !!CLI.cdpUrl;
// Shared active-page setter for tab-switch commands
function setActivePage(newPage) {
page = newPage;
}
// ─── Output (stdout = JSON response only) ───
function out(obj) {
process.stdout.write(JSON.stringify(obj) + '\n');
}
// ─── URL resolver ───
function resolveUrl(url) {
if (url.startsWith('http')) return url;
return (config.baseUrl || '') + (url.startsWith('/') ? url : '/' + url);
}
// ─── Login helper ───
async function doLogin(profile) {
const auth = (config.auth || {})[profile];
if (!auth) return { ok: false, error: `No auth profile "${profile}" in config`, error_code: ERROR_CODES.AUTH_FAILED };
try {
await page.goto(resolveUrl(auth.loginUrl), { waitUntil: 'domcontentloaded' });
// CSRF token
if (auth.csrfField) {
const csrfValue = await page.evaluate((field) => {
const el = document.querySelector(`input[name="${field}"]`);
return el ? el.value : '';
}, auth.csrfField);
if (csrfValue) {
auth.fields[auth.csrfField] = csrfValue;
}
}
// Fill fields
for (const [name, value] of Object.entries(auth.fields)) {
const isHidden = await page.evaluate((n) => {
const el = document.querySelector(`input[name="${n}"]`);
return el ? (el.type === 'hidden' || !el.offsetParent) : true;
}, name);
if (isHidden) {
await page.evaluate(({ n, v }) => {
const el = document.querySelector(`input[name="${n}"]`);
if (el) el.value = v;
}, { n: name, v: String(value) });
} else {
const input = await page.$(`input[name="${name}"]`);
if (input) await input.fill(String(value));
}
}
// Submit
const submitField = auth.submitField || 'submit';
const submitBtn = await page.$(`input[name="${submitField}"], button[name="${submitField}"], button[type="submit"]`);
if (submitBtn) {
await submitBtn.click();
} else {
await page.keyboard.press('Enter');
}
await page.waitForLoadState('domcontentloaded');
const user = auth.fields.username || auth.fields.email || profile;
session.markAuth(profile, user);
return { ok: true, user, url: page.url() };
} catch (e) {
return { ok: false, error: e.message, error_code: ERROR_CODES.AUTH_FAILED };
}
}
// ─── Dispatcher ───
async function dispatch(parseResult, input) {
const startTs = Date.now();
if (parseResult.error) {
return wrap(
{ ok: false, error: parseResult.error, error_code: ERROR_CODES.PARSE_ERROR },
CLI.responseSchema,
{ verb: 'parse', args: [], options: {} },
{ startTs, input, profile: config.activeProfile || null, session: session.snapshot(), runId: CLI.runId }
);
}
const { verb, args = [], options = {} } = parseResult;
// Log AI action (before execution) in CDP mode
if (actionLogger && verb) {
let url = '';
try { url = page && page.url(); } catch (_) {}
actionLogger.logAiAction({
agentName: CLI.agentName,
verb,
args,
url,
via: isCdpMode ? 'cdp' : 'local',
});
}
// Helper expansion
if (helpers[verb]) {
return await executeHelper(verb, args, parseResult, input, startTs);
}
// Policy check
if (!policy.isAllowed(verb, policyMode)) {
const tier = policy.tierOf(verb);
const raw = {
ok: false,
error: `Command "${verb}" (tier=${tier}) denied by policy mode "${policyMode}"`,
error_code: ERROR_CODES.POLICY_DENIED,
};
logger.event('POLICY_DENIED', { verb, tier, mode: policyMode });
return wrap(raw, CLI.responseSchema, parseResult, {
startTs, input, profile: config.activeProfile || null,
session: session.snapshot(), policyTier: tier, runId: CLI.runId,
});
}
// Lookup handler
const handler = commands[verb];
if (!handler) {
return wrap(
{ ok: false, error: `Unknown command: ${verb}`, error_code: ERROR_CODES.UNKNOWN_COMMAND },
CLI.responseSchema,
parseResult,
{ startTs, input, profile: config.activeProfile || null, session: session.snapshot(), runId: CLI.runId }
);
}
// Build handler context
const artifacts = createCollector();
const ctx = {
page, context, config,
state, session, helpers,
resolveUrl, doLogin,
artifacts: artifacts.list,
runCommand,
setActivePage, // for tabs commands
eventServer: eventSrv,
actionLogger,
cleanText: CLI.clean,
commandOptions: options,
};
// Execute with optional per-command timeout/retry
const timeoutMs = options.timeout_ms;
const maxRetries = options.retry || 0;
let raw;
let attempt = 0;
while (attempt <= maxRetries) {
try {
if (timeoutMs) {
raw = await withTimeout(handler(ctx, ...args), timeoutMs);
} else {
raw = await handler(ctx, ...args);
}
if (raw && raw.ok !== false) break;
attempt++;
if (attempt > maxRetries) break;
} catch (e) {
const code = classifyError(e);
raw = { ok: false, error: e.message, error_code: code };
attempt++;
if (attempt > maxRetries) break;
}
}
const tier = policy.tierOf(verb);
logger.event('COMMAND_EXECUTED', {
verb, args, ok: raw && raw.ok !== false,
tier, mode: policyMode, attempt, duration_ms: Date.now() - startTs,
});
return wrap(raw, CLI.responseSchema, parseResult, {
startTs, input,
profile: session.profile,
session: session.snapshot(),
artifacts: artifacts.list,
policyTier: tier,
runId: CLI.runId,
toolVersion: pkg.version,
contractEnvelope,
logFile: CLI.logFile,
actionsLog: actionLogger ? CLI.actionsLog : null,
});
}
// ─── Helper execution ───
async function executeHelper(helperName, helperArgs, parseResult, input, startTs) {
const h = helpers[helperName];
if (!h || !Array.isArray(h.steps)) {
return wrap(
{ ok: false, error: `Helper invalid: ${helperName}`, error_code: ERROR_CODES.HELPER_NOT_FOUND },
CLI.responseSchema, parseResult,
{ startTs, input, session: session.snapshot(), runId: CLI.runId }
);
}
const expandedSteps = h.steps.map(step => {
(h.args || []).forEach((argName, i) => {
step = step.replace(new RegExp(`\\{${argName}\\}`, 'g'), helperArgs[i] || '');
step = step.replace(new RegExp(`\\{${i}\\}`, 'g'), helperArgs[i] || '');
});
return step;
});
const expandedVerbs = expandedSteps.map(s => {
const p = parser.parse(s);
return p.verb || '';
}).filter(Boolean);
const derivedTier = policy.deriveHelperTier(expandedVerbs);
const allowedMax = policy.allowedMax(policyMode);
const TIER_RANK = { safe: 1, medium: 2, high: 3 };
if (TIER_RANK[derivedTier] > TIER_RANK[allowedMax]) {
logger.event('POLICY_DENIED', { helper: helperName, tier: derivedTier, mode: policyMode });
return wrap(
{ ok: false, error: `Helper "${helperName}" (derived tier=${derivedTier}) denied by policy "${policyMode}"`, error_code: ERROR_CODES.POLICY_DENIED },
CLI.responseSchema, parseResult,
{ startTs, input, session: session.snapshot(), policyTier: derivedTier, runId: CLI.runId }
);
}
const results = [];
for (const step of expandedSteps) {
const r = await runCommand(step);
results.push(r);
}
return wrap(
{ ok: true, helper: helperName, results },
CLI.responseSchema, parseResult,
{ startTs, input, session: session.snapshot(), policyTier: derivedTier, runId: CLI.runId }
);
}
// ─── Timeout wrapper ───
function withTimeout(promise, ms) {
return Promise.race([
promise,
new Promise((_, reject) => setTimeout(() => reject(new Error(`timeout after ${ms}ms`)), ms)),
]);
}
// ─── runCommand (top-level) ───
async function runCommand(line) {
const parsed = parser.parse(line);
if (parsed.skip) return { ok: true, skipped: true };
if (parsed.chain) {
const results = [];
for (const step of parsed.chain) {
results.push(await dispatch(step, null));
}
return { ok: true, chain: results };
}
return await dispatch(parsed, line);
}
// ─── Session marker check (for skip-login in CDP mode) ───
async function hasActiveSession(profile) {
const auth = (config.auth || {})[profile];
if (!auth || !auth.sessionMarker) return false;
return cdp.hasSessionMarkerOnPage(page, auth.sessionMarker);
}
// ─── Graceful exit ───
async function gracefulExit(code = 0) {
logger.event('EXIT', { mode: isCdpMode ? 'cdp' : 'local' });
logger.close();
// Stop event server
if (eventSrv) {
try { await eventSrv.stop(); } catch (_) {}
}
if (browser) {
try {
if (isCdpMode) {
// Per CDP_CONTRACT Rule 5 — disconnect, don't close Chrome
await cdp.disconnect(browser);
} else {
await browser.close();
}
} catch (_) {}
}
process.exit(code);
}
// ─── Main ───
async function main() {
const downloadDir = path.resolve(config.downloadDir || './downloads');
if (!fs.existsSync(downloadDir)) fs.mkdirSync(downloadDir, { recursive: true });
// ─── Launch or Connect ───
if (isCdpMode) {
try {
const r = await cdp.connect(CLI.cdpUrl, {
tabIndex: CLI.tabIndex,
newContext: CLI.newContext,
reuseTab: CLI.reuseTab,
focusOnConnect: CLI.focusOnConnect,
viewport: initialViewport,
});
browser = r.browser;
context = r.context;
page = r.page;
logger.event('CDP_TAB_SELECTED', {
source: r.tabSource,
tabs_count: r.tabsCount,
});
if (initialViewport.source !== 'default') {
await page.setViewportSize({
width: initialViewport.width,
height: initialViewport.height,
});
}
} catch (err) {
process.stderr.write(`Fatal CDP connect error: ${err.message}\n`);
process.exit(1);
}
// Start event server + action logger (recorder infrastructure)
if (!CLI.noRecorder) {
actionLogger = new ActionLogger(CLI.actionsLog);
eventSrv = eventServer.start({
port: CLI.eventPort,
logPath: CLI.actionsLog,
});
// Inject recorder script on every page
const recorderScript = buildRecorderScript({
port: CLI.eventPort,
denySelectors: (config.recorder && config.recorder.deny_selectors) || [],
denyUrlParams: (config.recorder && config.recorder.deny_url_params) || [],
});
await context.addInitScript({ content: recorderScript });
}
} else {
browser = await chromium.launch({ headless: !CLI.show, channel: 'chrome' });
context = await browser.newContext({
acceptDownloads: true,
viewport: {
width: initialViewport.width,
height: initialViewport.height,
},
ignoreHTTPSErrors: true,
});
page = await context.newPage();
}
logger.event('BOOT', {
mode: isCdpMode ? 'cdp' : 'local',
cdp_url: isCdpMode ? CLI.cdpUrl : null,
responseSchema: CLI.responseSchema,
policyMode,
config: CLI.configPath,
show: CLI.show,
runId: CLI.runId,
agentName: CLI.agentName,
input: CLI.inputPath ? 'contract' : null,
clean: CLI.clean,
recorder: !CLI.noRecorder && isCdpMode,
viewport: {
width: initialViewport.width,
height: initialViewport.height,
source: initialViewport.source,
},
});
// Auto-login
if (CLI.autoLogin) {
// In CDP mode with session marker: skip login if already authenticated
if (isCdpMode && !CLI.forceLogin) {
const hasSession = await hasActiveSession(CLI.autoLogin);
if (hasSession) {
logger.human(`Login: skipped (session marker found for profile "${CLI.autoLogin}")`);
logger.event('LOGIN_SKIPPED', { profile: CLI.autoLogin, reason: 'session-marker' });
session.markAuth(CLI.autoLogin, 'cdp-cookies');
} else {
const r = await doLogin(CLI.autoLogin);
logger.human(`Login: ${JSON.stringify(r)}`);
logger.event('LOGIN', { profile: CLI.autoLogin, ok: r.ok });
}
} else {
const r = await doLogin(CLI.autoLogin);
logger.human(`Login: ${JSON.stringify(r)}`);
logger.event('LOGIN', { profile: CLI.autoLogin, ok: r.ok });
}
}
logger.human(`browser-cli v0.1 ready | mode=${isCdpMode ? 'cdp' : 'local'} | schema=${CLI.responseSchema} | policy=${policyMode}`);
// ─── One-shot --cmd mode ───
if (CLI.cmdInline) {
const result = await runCommand(CLI.cmdInline);
out(result);
await gracefulExit(0);
return;
}
// ─── Trinity Tool Contract --input mode ───
if (contractEnvelope) {
try {
if (contractEnvelope.constraints && contractEnvelope.constraints.network === false && contract.requiresNetwork(contractEnvelope)) {
const result = wrap(
{ ok: false, error: 'Network access is not allowed by the input constraints.', error_code: ERROR_CODES.POLICY_DENIED },
'v3',
{ verb: 'input', args: [], options: {} },
{
startTs: Date.now(),
input: CLI.inputPath,
runId: CLI.runId,
toolVersion: pkg.version,
contractEnvelope,
policyTier: policyMode,
logFile: CLI.logFile,
actionsLog: actionLogger ? CLI.actionsLog : null,
}
);
out(result);
await gracefulExit(3);
return;
}
const mapped = contract.commandFromEnvelope(contractEnvelope);
for (const pre of mapped.pre || []) {
const preResult = await runCommand(pre);
const failed = preResult && (preResult.ok === false || preResult.status === 'FAIL' || preResult.status === 'ERROR');
if (failed) {
out(preResult);
await gracefulExit(preResult.status === 'ERROR' ? 20 : 1);
return;
}
}
const result = await runCommand(mapped.command);
out(result);
await gracefulExit(result.status === 'PASS' || result.ok === true ? 0 : 1);
return;
} catch (err) {
const result = wrap(
{ ok: false, error: err.message, error_code: ERROR_CODES.PARSE_ERROR },
'v3',
{ verb: 'input', args: [], options: {} },
{
startTs: Date.now(),
input: CLI.inputPath,
runId: CLI.runId,
toolVersion: pkg.version,
contractEnvelope,
policyTier: policyMode,
logFile: CLI.logFile,
actionsLog: CLI.actionsLog,
}
);
out(result);
await gracefulExit(2);
return;
}
}
// ─── REPL / pipe mode ───
const isPiped = !process.stdin.isTTY;
const rl = readline.createInterface({
input: process.stdin,
output: isPiped ? undefined : process.stderr,
prompt: isPiped ? '' : '> ',
terminal: !isPiped,
});
if (!isPiped) rl.prompt();
const lineQueue = [];
let processing = false;
async function processQueue() {
if (processing) return;
processing = true;
while (lineQueue.length > 0) {
const line = lineQueue.shift();
if (line == null) continue;
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#')) continue;
if (trimmed === 'exit' || trimmed === 'quit') {
await gracefulExit(0);
return;
}
const result = await runCommand(trimmed);
out(result);
}
processing = false;
if (!isPiped) rl.prompt();
}
rl.on('line', (line) => {
lineQueue.push(line);
processQueue();
});
rl.on('close', async () => {
while (lineQueue.length > 0 || processing) {
await new Promise(r => setTimeout(r, 100));
}
await gracefulExit(0);
});
}
main().catch(e => {
process.stderr.write(`Fatal: ${e.message}\n`);
process.exit(1);
});