@aisac/cli 0.0.0-stage → 0.4.0-beta.10
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/README.md +202 -2
- package/dist/assets/claude/.claude-plugin/plugin.json +147 -0
- package/dist/assets/claude/hooks/context-compaction.ts +6934 -0
- package/dist/assets/claude/hooks/hooks.json +3 -0
- package/dist/assets/claude/hooks/native-host-contract-runtime.ts +18 -0
- package/dist/assets/claude/hooks/native-host-contract.test.ts +51 -0
- package/dist/assets/claude/hooks/provider-window.js +263 -0
- package/dist/assets/claude/hooks/state-fitting.d.mts +47 -0
- package/dist/assets/claude/hooks/state-fitting.mjs +324 -0
- package/dist/assets/codex-context-compaction.mjs +4786 -0
- package/dist/assets/context-selection-fitting.mjs +194 -0
- package/dist/assets/context-state-fitting.mjs +324 -0
- package/dist/assets/context-telemetry-reporter.mjs +305 -0
- package/dist/assets/jev-paid-pilot-terminal.mjs +1066 -0
- package/dist/claude-checkpoint.mjs +1338 -0
- package/dist/claude-compatibility.mjs +506 -0
- package/dist/claude-observation.mjs +1338 -0
- package/dist/cli.mjs +805 -0
- package/dist/codex-compatibility.mjs +531 -0
- package/dist/codex-diagnostics.mjs +447 -0
- package/dist/codex-engineering.mjs +165 -0
- package/dist/codex-permissions.mjs +590 -0
- package/dist/codex-protocol-fingerprint.json +131 -0
- package/dist/context-telemetry.mjs +257 -0
- package/dist/engineering-pack-public-key.json +10 -0
- package/dist/engineering-pack.mjs +845 -0
- package/dist/engineering.mjs +194 -0
- package/dist/extensions-catalog.mjs +310 -0
- package/dist/extensions-cli.mjs +486 -0
- package/dist/extensions-preferences.mjs +151 -0
- package/dist/guardrails/continuity.mjs +239 -0
- package/dist/guardrails/format.mjs +111 -0
- package/dist/guardrails/guards.mjs +397 -0
- package/dist/guardrails/run.mjs +211 -0
- package/dist/guardrails/shell-words.mjs +206 -0
- package/dist/guardrails-plugin.mjs +149 -0
- package/dist/launch.mjs +786 -0
- package/dist/mcp-servers.mjs +192 -0
- package/dist/mcp.mjs +962 -0
- package/dist/monitor.mjs +166 -0
- package/dist/package.json +5 -0
- package/dist/platform.mjs +156 -0
- package/dist/policy.mjs +218 -0
- package/dist/state.mjs +408 -0
- package/dist/telemetry-report.mjs +133 -0
- package/package.json +24 -4
package/dist/cli.mjs
ADDED
|
@@ -0,0 +1,805 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { dirname } from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { stdin, stdout } from 'node:process';
|
|
5
|
+
import { createInterface } from 'node:readline/promises';
|
|
6
|
+
import {
|
|
7
|
+
DISCLOSURE_VERSION,
|
|
8
|
+
atomicJson,
|
|
9
|
+
ensureStateRoot,
|
|
10
|
+
errorMessage,
|
|
11
|
+
isValidConfig,
|
|
12
|
+
readConfig,
|
|
13
|
+
readPrivateToken,
|
|
14
|
+
removeOwnedSetup,
|
|
15
|
+
stateRoot,
|
|
16
|
+
tokenDigest,
|
|
17
|
+
} from './state.mjs';
|
|
18
|
+
import {
|
|
19
|
+
captureLockPlatformCheck,
|
|
20
|
+
codexPlatformCheck,
|
|
21
|
+
defaultClientSelection,
|
|
22
|
+
nativeVersion,
|
|
23
|
+
platformCheck,
|
|
24
|
+
resolveNative,
|
|
25
|
+
} from './platform.mjs';
|
|
26
|
+
import { launchClaude, launchCodex } from './launch.mjs';
|
|
27
|
+
import { claudeCompatibilityError, resolveClaudeCompatibility } from './claude-compatibility.mjs';
|
|
28
|
+
import { codexCompatibilityError, resolveCodexCompatibility } from './codex-compatibility.mjs';
|
|
29
|
+
import { providerFreeProbe } from './mcp.mjs';
|
|
30
|
+
import { codexPolicyJson, makePolicy, publicPolicy, isProfile } from './policy.mjs';
|
|
31
|
+
import { readDiagnostics } from './claude-observation.mjs';
|
|
32
|
+
import { readCodexDiagnostics } from './codex-diagnostics.mjs';
|
|
33
|
+
import { checkEngineeringLicense, licenseLine, unavailableLicense } from './engineering.mjs';
|
|
34
|
+
import {
|
|
35
|
+
isPackLocale,
|
|
36
|
+
readLastLaunch,
|
|
37
|
+
readStoredLocale,
|
|
38
|
+
resolvePackLocale,
|
|
39
|
+
writeStoredLocale,
|
|
40
|
+
} from './engineering-pack.mjs';
|
|
41
|
+
import { extensionsSummary, hooksCommand, mcpCommand } from './extensions-cli.mjs';
|
|
42
|
+
import { sessionServers } from './mcp-servers.mjs';
|
|
43
|
+
import { anyFormatter } from './guardrails/format.mjs';
|
|
44
|
+
|
|
45
|
+
const VERSION = '0.4.0-beta.10';
|
|
46
|
+
// The command is `aisac`; `aibrain` is an alias installed from the same entry.
|
|
47
|
+
const COMMAND = 'aisac';
|
|
48
|
+
const ENDPOINT = 'https://mcp.ai-brain.aisac.cloud/mcp';
|
|
49
|
+
const PACKAGE_ROOT = dirname(fileURLToPath(import.meta.url));
|
|
50
|
+
const LEGACY_DISCLOSURE_VERSION = 'aibrain-paid-context-v1-2026-10-09';
|
|
51
|
+
|
|
52
|
+
function usage() {
|
|
53
|
+
console.log(
|
|
54
|
+
`${COMMAND} ${VERSION}\n\nUsage:\n ${COMMAND} setup [--client claude|codex|both] [--context-profile upstream|conservative]\n [--compact-at 1..95] [--keep-threshold 0..1] [--preserve-recent 1..100]\n [--min-reduction 0..1] [--truncate-head-chars 0..4096]\n [--max-state-tokens 1000..25000] [--max-request-tokens 1000..30000]\n [--tool-policy compatible|read_only] [--goal TEXT]\n ${COMMAND} doctor [--json]\n ${COMMAND} status [--json]\n ${COMMAND} disable\n ${COMMAND} setup --undo\n ${COMMAND} claude [-- native-args...]\n ${COMMAND} codex [-- native-args...]\n\nPolicy notes:\n Automatic monitoring asks for compaction at compact-at percent; state/request\n limits are estimated upper bounds and do not override server quotas.\n min-reduction, truncate-head-chars and tool-policy apply only to Claude;\n Codex keeps native compaction and same-session recovery.`,
|
|
55
|
+
);
|
|
56
|
+
console.log(
|
|
57
|
+
'Telemetry: setup --telemetry on|off (omitted preserves the stored choice; fresh defaults off).',
|
|
58
|
+
);
|
|
59
|
+
console.log(
|
|
60
|
+
'Claude shadow: setup --claude-shadow on|off and --claude-diagnostics on|off (preview stays applied=false).',
|
|
61
|
+
);
|
|
62
|
+
console.log(
|
|
63
|
+
'AISAC Engineering: `aisac claude` and `aisac codex` (Codex 0.164+) load the licensed method; setup --lang pt-BR|en picks its language; setup and doctor report the license; status stays offline. `aibrain` is an alias of `aisac`.',
|
|
64
|
+
);
|
|
65
|
+
console.log(
|
|
66
|
+
'Guardrails: `aisac hooks` lists them (a checklist on a terminal); `aisac hooks enable|disable <id>...` and `aisac hooks reset` change the next `aisac claude` session.',
|
|
67
|
+
);
|
|
68
|
+
console.log(
|
|
69
|
+
'MCP catalog: `aisac mcp` lists the reviewed servers (GitHub, Supabase, Vercel, Playwright, Context7); `aisac mcp enable|disable <id>...`, `aisac mcp reset`, `aisac mcp info <id>` and `aisac mcp login <id>` (Codex) change or explain the next session.',
|
|
70
|
+
);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// Telemetry is opt-in; setup omits the flag to preserve the stored choice.
|
|
74
|
+
function version() {
|
|
75
|
+
console.log(`${COMMAND} ${VERSION}`);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async function maskedPrompt() {
|
|
79
|
+
if (!stdin.isTTY || !stdout.isTTY) throw new Error('token_file_required_in_noninteractive_mode');
|
|
80
|
+
stdout.write('AI Brain PAT: ');
|
|
81
|
+
const wasRaw = stdin.isRaw ?? false;
|
|
82
|
+
const wasPaused = stdin.isPaused();
|
|
83
|
+
stdin.setRawMode?.(true);
|
|
84
|
+
stdin.resume();
|
|
85
|
+
let value = '';
|
|
86
|
+
/** @type {((chunk: Buffer) => void) | undefined} */
|
|
87
|
+
let onData;
|
|
88
|
+
/** @type {(() => void) | undefined} */
|
|
89
|
+
let onEnd;
|
|
90
|
+
try {
|
|
91
|
+
return await new Promise((resolve, reject) => {
|
|
92
|
+
/** @param {Buffer} chunk */
|
|
93
|
+
onData = (chunk) => {
|
|
94
|
+
for (const byte of chunk) {
|
|
95
|
+
if (byte === 3) return reject(new Error('token_prompt_cancelled'));
|
|
96
|
+
if (byte === 13 || byte === 10) {
|
|
97
|
+
stdout.write('\n');
|
|
98
|
+
return resolve(value.trim());
|
|
99
|
+
}
|
|
100
|
+
if (byte === 127) value = value.slice(0, -1);
|
|
101
|
+
else if (byte >= 32) {
|
|
102
|
+
if (value.length >= 16 * 1024) return reject(new Error('token_prompt_too_large'));
|
|
103
|
+
value += String.fromCharCode(byte);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
onEnd = () => reject(new Error('token_prompt_cancelled'));
|
|
108
|
+
stdin.on('data', onData);
|
|
109
|
+
stdin.once('end', onEnd);
|
|
110
|
+
});
|
|
111
|
+
} finally {
|
|
112
|
+
if (onData) stdin.off('data', onData);
|
|
113
|
+
if (onEnd) stdin.off('end', onEnd);
|
|
114
|
+
stdin.setRawMode?.(wasRaw);
|
|
115
|
+
if (wasPaused) stdin.pause();
|
|
116
|
+
else stdin.resume();
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** @param {string[]} args @param {string} name */
|
|
121
|
+
function option(args, name) {
|
|
122
|
+
const index = args.indexOf(name);
|
|
123
|
+
return index >= 0 ? args[index + 1] : undefined;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** @param {string[]} args @param {Set<string>} allowed @param {Set<string>} valueOptions */
|
|
127
|
+
function validateOptions(args, allowed, valueOptions) {
|
|
128
|
+
const seen = new Set();
|
|
129
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
130
|
+
const argument = args[index];
|
|
131
|
+
if (!allowed.has(argument)) throw new Error('unknown_option');
|
|
132
|
+
if (seen.has(argument)) throw new Error(`duplicate_option:${argument}`);
|
|
133
|
+
seen.add(argument);
|
|
134
|
+
if (valueOptions.has(argument)) {
|
|
135
|
+
const value = args[index + 1];
|
|
136
|
+
if (!value || value.startsWith('-')) throw new Error(`option_value_required:${argument}`);
|
|
137
|
+
index += 1;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const POLICY_OPTION_NAMES = new Set([
|
|
143
|
+
'--compact-at',
|
|
144
|
+
'--keep-threshold',
|
|
145
|
+
'--preserve-recent',
|
|
146
|
+
'--min-reduction',
|
|
147
|
+
'--truncate-head-chars',
|
|
148
|
+
'--max-state-tokens',
|
|
149
|
+
'--max-request-tokens',
|
|
150
|
+
'--tool-policy',
|
|
151
|
+
]);
|
|
152
|
+
|
|
153
|
+
/** @param {string[]} args */
|
|
154
|
+
function policyOverrides(args) {
|
|
155
|
+
/** @type {Record<string, string | number>} */
|
|
156
|
+
const values = {};
|
|
157
|
+
/** @type {Map<string, [string, (value: string) => string | number]>} */
|
|
158
|
+
const fields = new Map([
|
|
159
|
+
['--compact-at', ['compactAtPercent', Number]],
|
|
160
|
+
['--keep-threshold', ['keepThreshold', Number]],
|
|
161
|
+
['--preserve-recent', ['preserveRecentMessages', Number]],
|
|
162
|
+
['--min-reduction', ['minReductionRatio', Number]],
|
|
163
|
+
['--truncate-head-chars', ['truncateHeadChars', Number]],
|
|
164
|
+
['--max-state-tokens', ['maxStateTokens', Number]],
|
|
165
|
+
['--max-request-tokens', ['maxRequestTokens', Number]],
|
|
166
|
+
['--tool-policy', ['toolPolicy', String]],
|
|
167
|
+
]);
|
|
168
|
+
for (const [optionName, [field, convert]] of fields) {
|
|
169
|
+
const raw = option(args, optionName);
|
|
170
|
+
if (raw === undefined) continue;
|
|
171
|
+
const converted = convert(raw);
|
|
172
|
+
if (typeof converted === 'number' && !Number.isFinite(converted))
|
|
173
|
+
throw new Error(`invalid_${field}`);
|
|
174
|
+
values[field] = converted;
|
|
175
|
+
}
|
|
176
|
+
return values;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** @param {string[]} args @param {Awaited<ReturnType<typeof readConfig>>} previous */
|
|
180
|
+
function selectedPolicy(args, previous) {
|
|
181
|
+
const explicitProfile = option(args, '--context-profile');
|
|
182
|
+
const explicitV2 =
|
|
183
|
+
explicitProfile !== undefined ||
|
|
184
|
+
args.some(
|
|
185
|
+
(item) =>
|
|
186
|
+
POLICY_OPTION_NAMES.has(item) ||
|
|
187
|
+
item === '--goal' ||
|
|
188
|
+
item === '--claude-shadow' ||
|
|
189
|
+
item === '--claude-diagnostics',
|
|
190
|
+
);
|
|
191
|
+
if (previous?.schemaVersion === 1 && !explicitV2)
|
|
192
|
+
return { v2: false, policy: makePolicy('conservative') };
|
|
193
|
+
const inherited = previous?.schemaVersion === 2 ? previous.context : undefined;
|
|
194
|
+
const profile = explicitProfile ?? inherited?.profile ?? (previous ? 'conservative' : 'upstream');
|
|
195
|
+
if (!isProfile(profile)) throw new Error('invalid_context_profile');
|
|
196
|
+
const overrides = policyOverrides(args);
|
|
197
|
+
if (inherited !== undefined && explicitProfile === undefined) {
|
|
198
|
+
for (const key of [
|
|
199
|
+
'compactAtPercent',
|
|
200
|
+
'keepThreshold',
|
|
201
|
+
'preserveRecentMessages',
|
|
202
|
+
'minReductionRatio',
|
|
203
|
+
'truncateHeadChars',
|
|
204
|
+
'maxStateTokens',
|
|
205
|
+
'maxRequestTokens',
|
|
206
|
+
'toolPolicy',
|
|
207
|
+
]) {
|
|
208
|
+
if (!Object.hasOwn(overrides, key))
|
|
209
|
+
overrides[key] =
|
|
210
|
+
inherited[
|
|
211
|
+
/** @type {keyof Omit<import('./policy.mjs').ContextPolicy, 'profile' | 'goal'>} */ (
|
|
212
|
+
key
|
|
213
|
+
)
|
|
214
|
+
];
|
|
215
|
+
}
|
|
216
|
+
if (option(args, '--goal') === undefined && inherited.goal !== undefined)
|
|
217
|
+
overrides.goal = inherited.goal;
|
|
218
|
+
}
|
|
219
|
+
const clients = option(args, '--client') ?? defaultClientSelection();
|
|
220
|
+
if (
|
|
221
|
+
clients === 'codex' &&
|
|
222
|
+
args.some(
|
|
223
|
+
(item) =>
|
|
224
|
+
item === '--min-reduction' || item === '--truncate-head-chars' || item === '--tool-policy',
|
|
225
|
+
)
|
|
226
|
+
)
|
|
227
|
+
throw new Error('claude_only_policy_option_for_codex');
|
|
228
|
+
const goal = option(args, '--goal');
|
|
229
|
+
return { v2: true, policy: makePolicy(profile, overrides, goal ?? inherited?.goal) };
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/** @param {import('./policy.mjs').ContextPolicy} policy */
|
|
233
|
+
function policySummary(policy) {
|
|
234
|
+
return JSON.stringify({ effective: publicPolicy(policy) });
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** @param {string[]} args @param {Awaited<ReturnType<typeof readConfig>>} previous */
|
|
238
|
+
function telemetrySelection(args, previous) {
|
|
239
|
+
const requested = option(args, '--telemetry');
|
|
240
|
+
if (requested !== undefined && requested !== 'on' && requested !== 'off')
|
|
241
|
+
throw new Error('invalid_telemetry');
|
|
242
|
+
const current = previous?.telemetry;
|
|
243
|
+
const enabled = requested === undefined ? current?.enabled === true : requested === 'on';
|
|
244
|
+
return {
|
|
245
|
+
enabled,
|
|
246
|
+
disclosedAt: current?.disclosedAt ?? null,
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** @param {string[]} args @param {Awaited<ReturnType<typeof readConfig>>} previous */
|
|
251
|
+
function claudeObservationSelection(args, previous) {
|
|
252
|
+
const shadow = option(args, '--claude-shadow');
|
|
253
|
+
const diagnostics = option(args, '--claude-diagnostics');
|
|
254
|
+
for (const value of [shadow, diagnostics]) {
|
|
255
|
+
if (value !== undefined && value !== 'on' && value !== 'off')
|
|
256
|
+
throw new Error('invalid_claude_observation');
|
|
257
|
+
}
|
|
258
|
+
const current = previous?.claudeObservation;
|
|
259
|
+
const shadowEnabled = shadow === undefined ? current?.shadowEnabled === true : shadow === 'on';
|
|
260
|
+
const diagnosticsEnabled =
|
|
261
|
+
diagnostics === undefined ? current?.diagnosticsEnabled === true : diagnostics === 'on';
|
|
262
|
+
const enabled = shadowEnabled || diagnosticsEnabled;
|
|
263
|
+
return {
|
|
264
|
+
shadowEnabled,
|
|
265
|
+
diagnosticsEnabled,
|
|
266
|
+
disclosedAt: enabled
|
|
267
|
+
? (current?.disclosedAt ?? new Date().toISOString())
|
|
268
|
+
: (current?.disclosedAt ?? null),
|
|
269
|
+
};
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** @param {Awaited<ReturnType<typeof readConfig>>} previous Disable future-launch egress locally without probing the server or requiring native clients. */
|
|
273
|
+
async function disableTelemetryLocally(previous) {
|
|
274
|
+
if (!previous) {
|
|
275
|
+
console.log('Context dashboard telemetry is already disabled; no local setup exists.');
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
const root = await ensureStateRoot();
|
|
279
|
+
await atomicJson(`${root}/config.json`, {
|
|
280
|
+
...previous,
|
|
281
|
+
telemetry: {
|
|
282
|
+
enabled: false,
|
|
283
|
+
disclosedAt: previous.telemetry?.disclosedAt ?? null,
|
|
284
|
+
},
|
|
285
|
+
});
|
|
286
|
+
console.log(
|
|
287
|
+
`Context dashboard telemetry disabled for future launches in ${root}. Close and restart currently monitored sessions to stop their launch-captured reporting settings.`,
|
|
288
|
+
);
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** @param {Awaited<ReturnType<typeof readConfig>>} previous @param {string[]} args */
|
|
292
|
+
async function updateLocalOptOut(previous, args) {
|
|
293
|
+
const allowed = new Set([
|
|
294
|
+
'--accept-disclosure',
|
|
295
|
+
'--telemetry',
|
|
296
|
+
'off',
|
|
297
|
+
'--claude-shadow',
|
|
298
|
+
'--claude-diagnostics',
|
|
299
|
+
]);
|
|
300
|
+
const hasOptOut =
|
|
301
|
+
args.includes('--telemetry') ||
|
|
302
|
+
args.includes('--claude-shadow') ||
|
|
303
|
+
args.includes('--claude-diagnostics');
|
|
304
|
+
if (!hasOptOut || args.some((argument) => !allowed.has(argument))) return false;
|
|
305
|
+
const requestedOff =
|
|
306
|
+
option(args, '--telemetry') === 'off' ||
|
|
307
|
+
option(args, '--claude-shadow') === 'off' ||
|
|
308
|
+
option(args, '--claude-diagnostics') === 'off';
|
|
309
|
+
if (!requestedOff) return false;
|
|
310
|
+
if (!previous) {
|
|
311
|
+
console.log(
|
|
312
|
+
'AI Brain local opt-out already has no configured account; no provider call was made.',
|
|
313
|
+
);
|
|
314
|
+
return true;
|
|
315
|
+
}
|
|
316
|
+
const root = await ensureStateRoot();
|
|
317
|
+
const observation = claudeObservationSelection(args, previous);
|
|
318
|
+
const telemetry = telemetrySelection(args, previous);
|
|
319
|
+
await atomicJson(`${root}/config.json`, {
|
|
320
|
+
...previous,
|
|
321
|
+
telemetry: {
|
|
322
|
+
enabled: telemetry.enabled,
|
|
323
|
+
disclosedAt: telemetry.disclosedAt,
|
|
324
|
+
},
|
|
325
|
+
claudeObservation: observation,
|
|
326
|
+
});
|
|
327
|
+
console.log(`Local observation settings updated in ${root}; no provider call was made.`);
|
|
328
|
+
return true;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/** Store the AISAC Engineering pack language; local only, no network call. @param {'pt-BR' | 'en'} locale */
|
|
332
|
+
async function setPackLocale(locale) {
|
|
333
|
+
const root = await ensureStateRoot();
|
|
334
|
+
await writeStoredLocale(root, locale);
|
|
335
|
+
console.log(
|
|
336
|
+
`AISAC Engineering pack language set to ${locale} for future launches; no network call was made.`,
|
|
337
|
+
);
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/** Offline view of the pack language and the last launch (status, doctor). */
|
|
341
|
+
async function engineeringPackState() {
|
|
342
|
+
const root = stateRoot();
|
|
343
|
+
const stored = await readStoredLocale(root);
|
|
344
|
+
return {
|
|
345
|
+
locale: resolvePackLocale(stored),
|
|
346
|
+
localeSource: stored === null ? 'system' : 'setup',
|
|
347
|
+
lastLaunch: await readLastLaunch(root),
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/** @param {string} endpoint */
|
|
352
|
+
function validateEndpoint(endpoint) {
|
|
353
|
+
if (endpoint.length > 2048) throw new Error('endpoint_too_long');
|
|
354
|
+
let parsed;
|
|
355
|
+
try {
|
|
356
|
+
parsed = new URL(endpoint);
|
|
357
|
+
} catch {
|
|
358
|
+
throw new Error('endpoint_invalid');
|
|
359
|
+
}
|
|
360
|
+
if (
|
|
361
|
+
parsed.protocol !== 'https:' &&
|
|
362
|
+
!(
|
|
363
|
+
parsed.protocol === 'http:' &&
|
|
364
|
+
['127.0.0.1', 'localhost', '::1', '[::1]'].includes(parsed.hostname)
|
|
365
|
+
)
|
|
366
|
+
)
|
|
367
|
+
throw new Error('endpoint_must_use_https');
|
|
368
|
+
if (parsed.username || parsed.password || parsed.hash || parsed.search)
|
|
369
|
+
throw new Error('endpoint_credentials_query_or_fragment_rejected');
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/** @param {string[]} args @param {string} endpoint @param {import('./policy.mjs').ContextPolicy} policy @param {string} disclosureVersion @param {boolean} telemetryEnabled @param {boolean} shadowEnabled @param {boolean} diagnosticsEnabled */
|
|
373
|
+
async function disclosureAccepted(
|
|
374
|
+
args,
|
|
375
|
+
endpoint,
|
|
376
|
+
policy,
|
|
377
|
+
disclosureVersion,
|
|
378
|
+
telemetryEnabled,
|
|
379
|
+
shadowEnabled,
|
|
380
|
+
diagnosticsEnabled,
|
|
381
|
+
) {
|
|
382
|
+
const telemetryDisclosure = telemetryEnabled
|
|
383
|
+
? ' Operational telemetry is enabled: only a hashed native session key, random lifecycle identifiers, client version, phase, timestamps, numeric counts and allowed measurement/reason enums are sent for the authenticated Contexto dashboard. Prompts, notes, paths, tool names, credentials and raw errors are excluded; the dashboard shows a 30-day visible window and physical cleanup runs on the next successful daily cleanup; delivery failure does not affect compaction.'
|
|
384
|
+
: '';
|
|
385
|
+
const shadowDisclosure =
|
|
386
|
+
shadowEnabled || option(args, '--claude-shadow') === 'on'
|
|
387
|
+
? ' Claude shadow observation is enabled: bounded redacted task and tool metadata may be sent through AI Brain to the existing JEV selection service for hypothetical decisions; native Claude results remain unchanged and private diagnostics exclude prompts, paths, inputs, result bodies, credentials and raw errors.'
|
|
388
|
+
: '';
|
|
389
|
+
const diagnosticsDisclosure =
|
|
390
|
+
diagnosticsEnabled || option(args, '--claude-diagnostics') === 'on'
|
|
391
|
+
? ' Claude compact diagnostics are enabled locally: bounded stages, enums, pseudonymous identifiers, timestamps and numeric measurements are stored in private rotated logs; prompts, paths, inputs, result bodies, credentials and raw errors are excluded.'
|
|
392
|
+
: '';
|
|
393
|
+
const disclosure = `AI Brain sends selected task/message/tool-input projections through AI Brain to JEV/TypeSafe at https://api.typesafe.ai/v1/systemone. Retention profile: ${policy.profile}; compact at ${policy.compactAtPercent}%; keep threshold ${policy.keepThreshold}; recent messages ${policy.preserveRecentMessages}; Claude tool policy ${policy.toolPolicy}. Selected projections are bounded and filtered; private local recovery files remain on this machine. Hidden fields and redaction limits apply; no zero-retention or complete-redaction claim. Goal present: ${policy.goal !== undefined}.${telemetryDisclosure}${shadowDisclosure}${diagnosticsDisclosure} Endpoint: ${endpoint}. Disclosure: ${disclosureVersion}.`;
|
|
394
|
+
if (args.includes('--accept-disclosure')) {
|
|
395
|
+
console.log(disclosure);
|
|
396
|
+
return true;
|
|
397
|
+
}
|
|
398
|
+
if (!stdin.isTTY || !stdout.isTTY) throw new Error('explicit_disclosure_flag_required');
|
|
399
|
+
const rl = createInterface({ input: stdin, output: stdout });
|
|
400
|
+
try {
|
|
401
|
+
const answer = await rl.question(`${disclosure} Type ACCEPT to continue: `);
|
|
402
|
+
return answer.trim() === 'ACCEPT';
|
|
403
|
+
} finally {
|
|
404
|
+
rl.close();
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/** @param {string[]} args */
|
|
409
|
+
async function setup(args) {
|
|
410
|
+
if (args.includes('--yes')) throw new Error('explicit_disclosure_flag_required');
|
|
411
|
+
validateOptions(
|
|
412
|
+
args,
|
|
413
|
+
new Set([
|
|
414
|
+
'--client',
|
|
415
|
+
'--token-file',
|
|
416
|
+
'--accept-disclosure',
|
|
417
|
+
'--endpoint',
|
|
418
|
+
'--yes',
|
|
419
|
+
'--undo',
|
|
420
|
+
'--context-profile',
|
|
421
|
+
...POLICY_OPTION_NAMES,
|
|
422
|
+
'--goal',
|
|
423
|
+
'--telemetry',
|
|
424
|
+
'--claude-shadow',
|
|
425
|
+
'--claude-diagnostics',
|
|
426
|
+
'--lang',
|
|
427
|
+
]),
|
|
428
|
+
new Set([
|
|
429
|
+
'--client',
|
|
430
|
+
'--token-file',
|
|
431
|
+
'--endpoint',
|
|
432
|
+
'--context-profile',
|
|
433
|
+
...POLICY_OPTION_NAMES,
|
|
434
|
+
'--goal',
|
|
435
|
+
'--telemetry',
|
|
436
|
+
'--claude-shadow',
|
|
437
|
+
'--claude-diagnostics',
|
|
438
|
+
'--lang',
|
|
439
|
+
]),
|
|
440
|
+
);
|
|
441
|
+
if (args.includes('--undo') && args.length !== 1)
|
|
442
|
+
throw new Error('setup_undo_cannot_have_options');
|
|
443
|
+
const lang = option(args, '--lang');
|
|
444
|
+
if (lang !== undefined && !isPackLocale(lang)) throw new Error('invalid_lang');
|
|
445
|
+
if (lang !== undefined && args.length === 2) return setPackLocale(lang);
|
|
446
|
+
const previous = await readConfig();
|
|
447
|
+
if (await updateLocalOptOut(previous, args)) return;
|
|
448
|
+
const localOptOut =
|
|
449
|
+
option(args, '--telemetry') === 'off' &&
|
|
450
|
+
args.every((argument) => ['--telemetry', 'off', '--accept-disclosure'].includes(argument));
|
|
451
|
+
if (localOptOut) return disableTelemetryLocally(previous);
|
|
452
|
+
const platform = platformCheck();
|
|
453
|
+
if (!platform.ok) throw new Error(`${platform.code}:${platform.message}`);
|
|
454
|
+
const clients = option(args, '--client') ?? defaultClientSelection();
|
|
455
|
+
if (!['claude', 'codex', 'both'].includes(clients)) throw new Error('invalid_client');
|
|
456
|
+
if (clients !== 'claude') {
|
|
457
|
+
const codexPlatform = codexPlatformCheck();
|
|
458
|
+
if (!codexPlatform.ok) throw new Error(`${codexPlatform.code}:${codexPlatform.message}`);
|
|
459
|
+
}
|
|
460
|
+
if (
|
|
461
|
+
clients === 'codex' &&
|
|
462
|
+
(option(args, '--claude-shadow') !== undefined ||
|
|
463
|
+
option(args, '--claude-diagnostics') !== undefined)
|
|
464
|
+
)
|
|
465
|
+
throw new Error('claude_observation_requires_claude_client');
|
|
466
|
+
const endpoint = option(args, '--endpoint') ?? ENDPOINT;
|
|
467
|
+
validateEndpoint(endpoint);
|
|
468
|
+
const selection = selectedPolicy(args, previous);
|
|
469
|
+
const telemetry = telemetrySelection(args, previous);
|
|
470
|
+
const claudeObservation = claudeObservationSelection(args, previous);
|
|
471
|
+
const policy = selection.policy;
|
|
472
|
+
const disclosureVersion = selection.v2
|
|
473
|
+
? DISCLOSURE_VERSION
|
|
474
|
+
: (previous?.disclosureVersion ?? LEGACY_DISCLOSURE_VERSION);
|
|
475
|
+
if (selection.v2 && (clients === 'codex' || clients === 'both')) codexPolicyJson(policy);
|
|
476
|
+
console.log(`Effective context policy ${policySummary(policy)}`);
|
|
477
|
+
if (
|
|
478
|
+
!(await disclosureAccepted(
|
|
479
|
+
args,
|
|
480
|
+
endpoint,
|
|
481
|
+
policy,
|
|
482
|
+
disclosureVersion,
|
|
483
|
+
telemetry.enabled,
|
|
484
|
+
claudeObservation.shadowEnabled,
|
|
485
|
+
claudeObservation.diagnosticsEnabled,
|
|
486
|
+
))
|
|
487
|
+
)
|
|
488
|
+
throw new Error('disclosure_not_accepted');
|
|
489
|
+
const root = await ensureStateRoot();
|
|
490
|
+
const tokenPath = option(args, '--token-file');
|
|
491
|
+
let token = tokenPath ? await readPrivateToken(tokenPath) : await maskedPrompt();
|
|
492
|
+
token = token.trim();
|
|
493
|
+
if (!token) throw new Error('empty_token');
|
|
494
|
+
const claude = resolveNative('claude');
|
|
495
|
+
const codex = resolveNative('codex');
|
|
496
|
+
const node = resolveNative('node');
|
|
497
|
+
if ((clients === 'claude' || clients === 'both') && !claude) throw new Error('claude_not_found');
|
|
498
|
+
if ((clients === 'codex' || clients === 'both') && (!codex || !node))
|
|
499
|
+
throw new Error('codex_or_node_not_found');
|
|
500
|
+
const claudeCompatibility =
|
|
501
|
+
(clients === 'claude' || clients === 'both') && claude !== null
|
|
502
|
+
? await resolveClaudeCompatibility(claude, PACKAGE_ROOT)
|
|
503
|
+
: null;
|
|
504
|
+
if (claudeCompatibility?.status === 'rejected')
|
|
505
|
+
throw new Error(claudeCompatibilityError(claudeCompatibility));
|
|
506
|
+
const claudeVersion = claudeCompatibility?.version ?? (claude ? nativeVersion(claude) : null);
|
|
507
|
+
let codexCompatibility = null;
|
|
508
|
+
if (clients === 'codex' || clients === 'both') {
|
|
509
|
+
codexCompatibility = codex ? await resolveCodexCompatibility(codex) : null;
|
|
510
|
+
if (codexCompatibility?.status === 'rejected')
|
|
511
|
+
throw new Error(codexCompatibilityError(codexCompatibility));
|
|
512
|
+
}
|
|
513
|
+
const codexVersion = codexCompatibility?.version ?? (codex ? nativeVersion(codex) : null);
|
|
514
|
+
const config = {
|
|
515
|
+
schemaVersion: selection.v2 ? 2 : 1,
|
|
516
|
+
packageVersion: VERSION,
|
|
517
|
+
disclosureVersion,
|
|
518
|
+
disclosedAt: new Date().toISOString(),
|
|
519
|
+
endpoint,
|
|
520
|
+
clientSelection: clients,
|
|
521
|
+
claudeVersion,
|
|
522
|
+
codexVersion,
|
|
523
|
+
packageRoot: PACKAGE_ROOT,
|
|
524
|
+
...(selection.v2 ? { context: policy } : {}),
|
|
525
|
+
telemetry: {
|
|
526
|
+
enabled: telemetry.enabled,
|
|
527
|
+
disclosedAt: telemetry.enabled
|
|
528
|
+
? (telemetry.disclosedAt ?? new Date().toISOString())
|
|
529
|
+
: telemetry.disclosedAt,
|
|
530
|
+
},
|
|
531
|
+
claudeObservation,
|
|
532
|
+
};
|
|
533
|
+
let probe;
|
|
534
|
+
try {
|
|
535
|
+
probe = selection.v2
|
|
536
|
+
? await providerFreeProbe(endpoint, token, policy, clients)
|
|
537
|
+
: await providerFreeProbe(endpoint, token);
|
|
538
|
+
} catch (error) {
|
|
539
|
+
throw new Error(`provider_free_probe_failed:${errorMessage(error)}`);
|
|
540
|
+
}
|
|
541
|
+
try {
|
|
542
|
+
const configWithToken = { ...config, token, tokenSha256: await tokenDigest(token), probe };
|
|
543
|
+
if (!isValidConfig(configWithToken)) throw new Error('config_validation_failed');
|
|
544
|
+
await atomicJson(`${root}/config.json`, configWithToken);
|
|
545
|
+
} catch (error) {
|
|
546
|
+
throw new Error(`state_write_failed:${errorMessage(error)}`);
|
|
547
|
+
}
|
|
548
|
+
console.log(
|
|
549
|
+
`Configured ${clients} in ${root}. Provider-free access verified; no provider batch was used.`,
|
|
550
|
+
);
|
|
551
|
+
if (lang !== undefined) await setPackLocale(lang);
|
|
552
|
+
// Display only: the server decides again on every pack request (ADR-0047).
|
|
553
|
+
const line = licenseLine(await checkEngineeringLicense(endpoint, token));
|
|
554
|
+
if (line !== null) console.log(line);
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/** Extension state plus whether `format-on-edit` has a formatter in this folder (FR8). */
|
|
558
|
+
async function doctorExtensions() {
|
|
559
|
+
const summary = await extensionsSummary(stateRoot());
|
|
560
|
+
// A token server is skipped at launch when its variable is unset (names only).
|
|
561
|
+
const mcpMissingEnv = sessionServers(summary.mcp, 'claude', process.env).missingEnv.map(
|
|
562
|
+
(skipped) => skipped.id,
|
|
563
|
+
);
|
|
564
|
+
const formatOnEdit = !summary.hooks.includes('format-on-edit')
|
|
565
|
+
? 'off'
|
|
566
|
+
: (await anyFormatter(process.cwd()))
|
|
567
|
+
? 'ready'
|
|
568
|
+
: 'no_formatter_found';
|
|
569
|
+
return { ...summary, formatOnEdit, mcpMissingEnv };
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
/** @param {boolean} json */
|
|
573
|
+
async function doctor(json) {
|
|
574
|
+
const platform = platformCheck();
|
|
575
|
+
const config = await readConfig();
|
|
576
|
+
const policy =
|
|
577
|
+
config?.schemaVersion === 2 && config.context !== undefined
|
|
578
|
+
? config.context
|
|
579
|
+
: makePolicy('conservative');
|
|
580
|
+
let probe = null;
|
|
581
|
+
let probeError = null;
|
|
582
|
+
if (config) {
|
|
583
|
+
try {
|
|
584
|
+
probe =
|
|
585
|
+
config.schemaVersion === 2
|
|
586
|
+
? await providerFreeProbe(config.endpoint, config.token, policy, config.clientSelection)
|
|
587
|
+
: await providerFreeProbe(config.endpoint, config.token);
|
|
588
|
+
} catch (error) {
|
|
589
|
+
probeError = errorMessage(error);
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
const native = {
|
|
593
|
+
claude: resolveNative('claude'),
|
|
594
|
+
codex: resolveNative('codex'),
|
|
595
|
+
node: resolveNative('node'),
|
|
596
|
+
};
|
|
597
|
+
const claudeCompatibility =
|
|
598
|
+
native.claude !== null ? await resolveClaudeCompatibility(native.claude, PACKAGE_ROOT) : null;
|
|
599
|
+
const codexCompatibility =
|
|
600
|
+
native.codex !== null ? await resolveCodexCompatibility(native.codex) : null;
|
|
601
|
+
const rawNativeVersions = {
|
|
602
|
+
claude: claudeCompatibility?.version ?? '',
|
|
603
|
+
codex: native.codex ? nativeVersion(native.codex) : '',
|
|
604
|
+
};
|
|
605
|
+
const nativeVersions = {
|
|
606
|
+
...rawNativeVersions,
|
|
607
|
+
codex: codexCompatibility?.version ?? rawNativeVersions.codex,
|
|
608
|
+
};
|
|
609
|
+
// Optional capability: its state never changes doctor's exit code.
|
|
610
|
+
const engineering = config
|
|
611
|
+
? await checkEngineeringLicense(config.endpoint, config.token)
|
|
612
|
+
: unavailableLicense('not_configured');
|
|
613
|
+
const needsClaude = config?.clientSelection === 'claude' || config?.clientSelection === 'both';
|
|
614
|
+
const needsCodex = config?.clientSelection === 'codex' || config?.clientSelection === 'both';
|
|
615
|
+
const captureLockPlatform = needsCodex ? captureLockPlatformCheck() : null;
|
|
616
|
+
const nativeReady =
|
|
617
|
+
(!needsClaude ||
|
|
618
|
+
(native.claude !== null &&
|
|
619
|
+
(claudeCompatibility?.status === 'qualified' ||
|
|
620
|
+
claudeCompatibility?.status === 'host_checked'))) &&
|
|
621
|
+
(!needsCodex ||
|
|
622
|
+
(native.codex !== null &&
|
|
623
|
+
native.node !== null &&
|
|
624
|
+
captureLockPlatform?.ok === true &&
|
|
625
|
+
(codexCompatibility?.status === 'qualified' ||
|
|
626
|
+
codexCompatibility?.status === 'protocol_match')));
|
|
627
|
+
const result = {
|
|
628
|
+
version: VERSION,
|
|
629
|
+
platform: platform.ok ? process.platform : platform.code,
|
|
630
|
+
setup: config !== null,
|
|
631
|
+
disclosed:
|
|
632
|
+
config?.disclosureVersion === DISCLOSURE_VERSION ||
|
|
633
|
+
config?.disclosureVersion === LEGACY_DISCLOSURE_VERSION,
|
|
634
|
+
native: {
|
|
635
|
+
claude: native.claude !== null,
|
|
636
|
+
codex: native.codex !== null,
|
|
637
|
+
node: native.node !== null,
|
|
638
|
+
},
|
|
639
|
+
nativeVersions,
|
|
640
|
+
claudeCompatibility: claudeCompatibility?.status ?? 'unavailable',
|
|
641
|
+
claudeCompatibilityReason: claudeCompatibility?.reason ?? 'claude_not_found',
|
|
642
|
+
claudeCompatibilityVersion: claudeCompatibility?.version ?? null,
|
|
643
|
+
codexCompatibility: codexCompatibility?.status ?? 'unavailable',
|
|
644
|
+
codexCompatibilityReason: codexCompatibility?.reason ?? 'codex_not_found',
|
|
645
|
+
codexCompatibilityVersion: codexCompatibility?.version ?? null,
|
|
646
|
+
captureLockBackend:
|
|
647
|
+
captureLockPlatform?.ok === true
|
|
648
|
+
? 'available'
|
|
649
|
+
: (captureLockPlatform?.code ?? 'not_required'),
|
|
650
|
+
nativeReady,
|
|
651
|
+
context: publicPolicy(policy),
|
|
652
|
+
telemetry: {
|
|
653
|
+
enabled: config?.telemetry?.enabled === true,
|
|
654
|
+
disclosed:
|
|
655
|
+
config?.telemetry?.disclosedAt !== null && config?.telemetry?.disclosedAt !== undefined,
|
|
656
|
+
},
|
|
657
|
+
claudeObservation: {
|
|
658
|
+
shadowEnabled: config?.claudeObservation?.shadowEnabled === true,
|
|
659
|
+
diagnosticsEnabled: config?.claudeObservation?.diagnosticsEnabled === true,
|
|
660
|
+
disclosed:
|
|
661
|
+
config?.claudeObservation?.disclosedAt !== null &&
|
|
662
|
+
config?.claudeObservation?.disclosedAt !== undefined,
|
|
663
|
+
},
|
|
664
|
+
engineering,
|
|
665
|
+
engineeringPack: await engineeringPackState(),
|
|
666
|
+
extensions: await doctorExtensions(),
|
|
667
|
+
paidOrPilot: probe?.ok
|
|
668
|
+
? 'provider_free_probe_ok; paid entitlement or pilot invitation remains server-enforced'
|
|
669
|
+
: config
|
|
670
|
+
? `probe_failed:${probeError ?? 'not_run'}`
|
|
671
|
+
: 'not_configured',
|
|
672
|
+
};
|
|
673
|
+
if (json) console.log(JSON.stringify(result));
|
|
674
|
+
else console.log(result);
|
|
675
|
+
if (!platform.ok || !config || !probe?.ok || !nativeReady) process.exitCode = 1;
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
/** @param {boolean} json */
|
|
679
|
+
async function status(json) {
|
|
680
|
+
const config = await readConfig();
|
|
681
|
+
const policy =
|
|
682
|
+
config?.schemaVersion === 2 && config.context !== undefined
|
|
683
|
+
? config.context
|
|
684
|
+
: makePolicy('conservative');
|
|
685
|
+
const result = {
|
|
686
|
+
setup: config !== null,
|
|
687
|
+
disclosed: config?.disclosureVersion !== undefined,
|
|
688
|
+
schemaVersion: config?.schemaVersion ?? null,
|
|
689
|
+
context: publicPolicy(policy),
|
|
690
|
+
telemetry: {
|
|
691
|
+
enabled: config?.telemetry?.enabled === true,
|
|
692
|
+
disclosed:
|
|
693
|
+
config?.telemetry?.disclosedAt !== null && config?.telemetry?.disclosedAt !== undefined,
|
|
694
|
+
},
|
|
695
|
+
claudeObservation: {
|
|
696
|
+
shadowEnabled: config?.claudeObservation?.shadowEnabled === true,
|
|
697
|
+
diagnosticsEnabled: config?.claudeObservation?.diagnosticsEnabled === true,
|
|
698
|
+
disclosed:
|
|
699
|
+
config?.claudeObservation?.disclosedAt !== null &&
|
|
700
|
+
config?.claudeObservation?.disclosedAt !== undefined,
|
|
701
|
+
},
|
|
702
|
+
engineeringPack: await engineeringPackState(),
|
|
703
|
+
extensions: await extensionsSummary(stateRoot()),
|
|
704
|
+
monitoredSession: null,
|
|
705
|
+
monitoringStatus: 'not_observed',
|
|
706
|
+
};
|
|
707
|
+
if (json) console.log(JSON.stringify(result));
|
|
708
|
+
else console.log(result);
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
/** @param {string[]} argv */
|
|
712
|
+
async function main(argv) {
|
|
713
|
+
const [command, ...rest] = argv;
|
|
714
|
+
if (!command || command === '--help' || command === '-h') return usage();
|
|
715
|
+
if (command === '--version' || command === '-V') return version();
|
|
716
|
+
if (command === 'setup') {
|
|
717
|
+
if (rest.includes('--undo')) {
|
|
718
|
+
if (rest.length !== 1) throw new Error('setup_undo_cannot_have_options');
|
|
719
|
+
return removeOwnedSetup();
|
|
720
|
+
}
|
|
721
|
+
return setup(rest);
|
|
722
|
+
}
|
|
723
|
+
if (command === 'doctor') {
|
|
724
|
+
validateOptions(rest, new Set(['--json']), new Set());
|
|
725
|
+
return doctor(rest.includes('--json'));
|
|
726
|
+
}
|
|
727
|
+
if (command === 'status') {
|
|
728
|
+
validateOptions(rest, new Set(['--json']), new Set());
|
|
729
|
+
return status(rest.includes('--json'));
|
|
730
|
+
}
|
|
731
|
+
if (command === 'diagnostics') {
|
|
732
|
+
validateOptions(
|
|
733
|
+
rest,
|
|
734
|
+
new Set(['--client', '--tail', '--json']),
|
|
735
|
+
new Set(['--client', '--tail']),
|
|
736
|
+
);
|
|
737
|
+
const requestedClient = option(rest, '--client');
|
|
738
|
+
if (requestedClient !== undefined && !['claude', 'codex'].includes(requestedClient))
|
|
739
|
+
throw new Error('diagnostics_client_unsupported');
|
|
740
|
+
const tail = Number(option(rest, '--tail') ?? '20');
|
|
741
|
+
if (!Number.isSafeInteger(tail) || tail < 1 || tail > 100)
|
|
742
|
+
throw new Error('invalid_diagnostics_tail');
|
|
743
|
+
const client = requestedClient ?? 'claude';
|
|
744
|
+
const records =
|
|
745
|
+
client === 'codex'
|
|
746
|
+
? await readCodexDiagnostics(stateRoot(), tail)
|
|
747
|
+
: await readDiagnostics(stateRoot(), tail);
|
|
748
|
+
if (rest.includes('--json')) console.log(JSON.stringify({ client, records }));
|
|
749
|
+
else console.log(records);
|
|
750
|
+
return;
|
|
751
|
+
}
|
|
752
|
+
if (command === 'hooks') return hooksCommand(rest);
|
|
753
|
+
if (command === 'mcp') return mcpCommand(rest);
|
|
754
|
+
if (command === 'disable') {
|
|
755
|
+
if (rest.length > 0) throw new Error('disable_does_not_accept_options');
|
|
756
|
+
return removeOwnedSetup();
|
|
757
|
+
}
|
|
758
|
+
if (command === 'claude' || command === 'codex') {
|
|
759
|
+
const config = await readConfig();
|
|
760
|
+
if (!config || config.disclosedAt === undefined) throw new Error('setup_required');
|
|
761
|
+
if (config.schemaVersion === 2 && config.disclosureVersion !== DISCLOSURE_VERSION)
|
|
762
|
+
throw new Error('disclosure_outdated');
|
|
763
|
+
if (config.clientSelection !== command && config.clientSelection !== 'both')
|
|
764
|
+
throw new Error('client_not_configured');
|
|
765
|
+
// The native executable is authoritative. The stored setup version is
|
|
766
|
+
// metadata only, so patch updates do not block a fresh compatibility check.
|
|
767
|
+
if (command === 'codex' && typeof config.codexVersion !== 'string')
|
|
768
|
+
throw new Error('codex_version_unverified');
|
|
769
|
+
const root = stateRoot();
|
|
770
|
+
const result = await (command === 'claude'
|
|
771
|
+
? launchClaude(
|
|
772
|
+
{ ...config, packageRoot: PACKAGE_ROOT },
|
|
773
|
+
root,
|
|
774
|
+
rest[0] === '--' ? rest.slice(1) : rest,
|
|
775
|
+
)
|
|
776
|
+
: launchCodex(
|
|
777
|
+
{ ...config, packageRoot: PACKAGE_ROOT },
|
|
778
|
+
root,
|
|
779
|
+
rest[0] === '--' ? rest.slice(1) : rest,
|
|
780
|
+
));
|
|
781
|
+
process.exitCode = result;
|
|
782
|
+
return;
|
|
783
|
+
}
|
|
784
|
+
throw new Error('unknown_command');
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
const cliArgs = process.argv.slice(2);
|
|
788
|
+
main(cliArgs).catch((error) => {
|
|
789
|
+
if (cliArgs[0] === 'doctor' && cliArgs.includes('--json')) {
|
|
790
|
+
const platform = platformCheck();
|
|
791
|
+
console.log(
|
|
792
|
+
JSON.stringify({
|
|
793
|
+
version: VERSION,
|
|
794
|
+
platform: platform.ok ? process.platform : platform.code,
|
|
795
|
+
setup: false,
|
|
796
|
+
disclosed: false,
|
|
797
|
+
nativeReady: false,
|
|
798
|
+
error: 'CONFIG_UNAVAILABLE',
|
|
799
|
+
}),
|
|
800
|
+
);
|
|
801
|
+
} else {
|
|
802
|
+
console.error(`${COMMAND}: ${errorMessage(error)}`);
|
|
803
|
+
}
|
|
804
|
+
process.exitCode = 1;
|
|
805
|
+
});
|