your-cto-jev 0.2.2 → 0.3.0
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 +23 -17
- package/dist/api.js +27 -4
- package/dist/brain.js +22 -2
- package/dist/doctor.js +100 -0
- package/dist/hooks.js +4 -1
- package/dist/i18n.js +135 -37
- package/dist/index.js +34 -14
- package/dist/setup.js +37 -2
- package/dist/setupui.js +250 -0
- package/package.json +5 -1
- package/dist/wizard.js +0 -156
package/README.md
CHANGED
|
@@ -77,29 +77,34 @@ cto setup
|
|
|
77
77
|
|
|
78
78
|
To update later, run `cto update`. Projects you already set up pick up the new version automatically: every hook only calls `cto`, and all the logic lives in the package. `cto` checks npm for a new version at most once a day and mentions it in its once-per-session notice, never on its own.
|
|
79
79
|
|
|
80
|
-
`cto setup` walks you through
|
|
80
|
+
`cto setup` walks you through four steps with arrow keys: coding agents, Jev providers, API keys, and an optional sprint goal. Esc goes back a step. Providers are ticked in priority order, so the numbers you see are the failover order. Press a number to move the item under the cursor straight to that position:
|
|
81
81
|
|
|
82
82
|
```text
|
|
83
|
-
Which
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
Set up a Jev API key (at least one; press Enter to skip).
|
|
90
|
-
OpenRouter API key: ********
|
|
91
|
-
Verifying OpenRouter with one real request...
|
|
92
|
-
OpenRouter OK
|
|
83
|
+
◆ Which Jev providers should cto use?
|
|
84
|
+
│ › [1] OpenRouter easiest, one key (openrouter.ai)
|
|
85
|
+
│ [ ] TypeSafe direct from the makers of Jev, one key
|
|
86
|
+
│ [2] Cloudflare Account ID + API token; needs Authenticated Gateway and credits
|
|
87
|
+
│ Up/Down move · Space toggles · a number moves the item to that position · Enter confirms · Esc goes back
|
|
93
88
|
```
|
|
94
89
|
|
|
95
|
-
|
|
90
|
+
Each key is verified with one real request before it is saved. Keys you already stored are shown only by their last four characters, so you can keep them without pasting again.
|
|
91
|
+
|
|
92
|
+
Run `cto setup` again any time: it opens an overview of your current setup, and you can change one item without touching the rest. Changing only the order asks for nothing else; keys are asked only for newly added providers, and **Change API keys** in the overview replaces stored ones.
|
|
93
|
+
|
|
94
|
+
Then restart your agent session so it picks up the new hooks, and check that everything really works:
|
|
95
|
+
|
|
96
|
+
```sh
|
|
97
|
+
cto doctor
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
`cto doctor` sends one real request per provider, shows where each key comes from, checks the hooks in the current repo, and counts how often a check was blocked or let through unchecked. It exits non-zero when something needs attention. Run it whenever you are unsure whether `cto` is protecting you: because `cto` fails open, a broken key looks exactly like a clean pass.
|
|
96
101
|
|
|
97
102
|
Other forms:
|
|
98
103
|
|
|
99
104
|
```sh
|
|
100
105
|
cto setup --agents claude,cursor --yes # non-interactive (scripts, CI)
|
|
101
|
-
cto setup --keys # change keys later
|
|
102
106
|
cto setup --uninstall # remove every cto hook again
|
|
107
|
+
cto doctor # is it actually working?
|
|
103
108
|
```
|
|
104
109
|
|
|
105
110
|
`setup` appends marked blocks and merges JSON. It never overwrites your existing hooks or settings, and `--uninstall` puts them back exactly as they were. It never touches your shell rc files.
|
|
@@ -121,14 +126,15 @@ Codex only runs project hooks after you trust the project. Teammates who have no
|
|
|
121
126
|
|
|
122
127
|
## API keys
|
|
123
128
|
|
|
124
|
-
You need at least one provider:
|
|
129
|
+
You need at least one provider. `cto setup` lets you pick which ones to use and in what order:
|
|
125
130
|
|
|
126
131
|
| Provider | Keys | Notes |
|
|
127
132
|
|---|---|---|
|
|
128
133
|
| [OpenRouter](https://openrouter.ai) | `OPENROUTER_API_KEY` | Easiest way to start |
|
|
129
|
-
| [
|
|
134
|
+
| [TypeSafe](https://docs.typesafe.ai/introduction/quickstart) | `TYPESAFE_API_KEY` | Direct from the makers of Jev. Get a key at console.typesafe.ai/keys. Pinned to `jev-1.13.0`, the version the thresholds were calibrated on. Not yet tested with a live key |
|
|
135
|
+
| [Cloudflare Workers AI](https://developers.cloudflare.com/ai/models/typesafe/jev/) | `CLOUDFLARE_API_TOKEN`, `CLOUDFLARE_ACCOUNT_ID` | Token needs Account > Workers AI > Read. Your account's default AI Gateway must have **Authenticated Gateway** on and Unified Billing credits |
|
|
130
136
|
|
|
131
|
-
If the first provider fails, `cto` switches to the next one and tells you once. It retries the first provider later. A missing key, a timeout or an outage never blocks you: `cto` fails open and lets the action through. It only blocks when Jev answers and the answer crosses a threshold.
|
|
137
|
+
If the first provider fails, `cto` switches to the next one in your order and tells you once. It retries the first provider later. A missing key, a timeout or an outage never blocks you: `cto` fails open and lets the action through. It only blocks when Jev answers and the answer crosses a threshold.
|
|
132
138
|
|
|
133
139
|
**Where keys live.** Environment variables win. Otherwise `cto` reads a per-user file that `setup` writes:
|
|
134
140
|
|
|
@@ -186,7 +192,7 @@ Nothing else is uploaded, and nothing is logged unless you set `CTO_DEBUG=1`. Th
|
|
|
186
192
|
|
|
187
193
|
- **Git GUIs hide warnings.** VS Code, SourceTree and GitKraken usually hide hook output when the commit succeeds, so the architecture and complexity warnings are invisible there. Blocks still show.
|
|
188
194
|
- **A retry after a fix can look like a loop.** The loop check sees recent failures but not the edits you made since. Failures expire after 15 minutes. Raise `infinite_loop` if it gets in your way.
|
|
189
|
-
- **Each agent shell command waits about
|
|
195
|
+
- **Each agent shell command waits for one Jev request.** OpenRouter answered in about 0.3 s in our tests, Cloudflare in about 0.9 s with occasional spikes past 3 s. Agent checks wait up to 5 s before failing open.
|
|
190
196
|
|
|
191
197
|
## Development
|
|
192
198
|
|
package/dist/api.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { loadPrefs } from './brain.js';
|
|
1
2
|
import { t } from './i18n.js';
|
|
2
3
|
import { maskSensitiveState } from './masker.js';
|
|
3
4
|
const env = process.env;
|
|
@@ -7,6 +8,7 @@ const FIVE_MIN = 300_000;
|
|
|
7
8
|
export const providers = {
|
|
8
9
|
cloudflare: {
|
|
9
10
|
label: 'Cloudflare',
|
|
11
|
+
keys: ['CLOUDFLARE_ACCOUNT_ID', 'CLOUDFLARE_API_TOKEN'],
|
|
10
12
|
enabled: () => !!(env.CLOUDFLARE_API_TOKEN && env.CLOUDFLARE_ACCOUNT_ID),
|
|
11
13
|
url: () => `https://api.cloudflare.com/client/v4/accounts/${env.CLOUDFLARE_ACCOUNT_ID}/ai/run`,
|
|
12
14
|
headers: () => ({ Authorization: `Bearer ${env.CLOUDFLARE_API_TOKEN}` }),
|
|
@@ -15,15 +17,30 @@ export const providers = {
|
|
|
15
17
|
},
|
|
16
18
|
openrouter: {
|
|
17
19
|
label: 'OpenRouter',
|
|
20
|
+
keys: ['OPENROUTER_API_KEY'],
|
|
18
21
|
enabled: () => !!env.OPENROUTER_API_KEY,
|
|
19
22
|
url: () => 'https://openrouter.ai/api/alpha/decisions',
|
|
20
23
|
headers: () => ({ Authorization: `Bearer ${env.OPENROUTER_API_KEY}` }),
|
|
21
24
|
body: (req) => ({ model: 'typesafe/jev-1.13', ...req }),
|
|
22
25
|
},
|
|
26
|
+
// Direct from TypeSafe (docs.typesafe.ai/api). Pinned to the version our thresholds were calibrated on, as the
|
|
27
|
+
// docs advise; session_id is not a documented field, so it is not sent.
|
|
28
|
+
typesafe: {
|
|
29
|
+
label: 'TypeSafe',
|
|
30
|
+
keys: ['TYPESAFE_API_KEY'],
|
|
31
|
+
enabled: () => !!env.TYPESAFE_API_KEY,
|
|
32
|
+
url: () => 'https://api.typesafe.ai/v1/systemone',
|
|
33
|
+
headers: () => ({ Authorization: `Bearer ${env.TYPESAFE_API_KEY}` }),
|
|
34
|
+
body: ({ session_id: _, ...req }) => ({ model: 'jev-1.13.0', ...req }),
|
|
35
|
+
},
|
|
23
36
|
};
|
|
24
|
-
/**
|
|
37
|
+
/**
|
|
38
|
+
* Providers to try, in order: CTO_PROVIDER > the order picked in setup (only those) > every provider with a key.
|
|
39
|
+
* Keys of providers left out of the picked order stay stored, so re-enabling one later needs no re-entry.
|
|
40
|
+
*/
|
|
25
41
|
export function providerOrder() {
|
|
26
|
-
const
|
|
42
|
+
const picked = loadPrefs().provider_order;
|
|
43
|
+
const order = env.CTO_PROVIDER ? [env.CTO_PROVIDER] : picked?.length ? picked : Object.keys(providers);
|
|
27
44
|
return order.filter((n) => providers[n]?.enabled());
|
|
28
45
|
}
|
|
29
46
|
async function callOnce(name, req, timeoutMs) {
|
|
@@ -54,8 +71,14 @@ async function callOnce(name, req, timeoutMs) {
|
|
|
54
71
|
return { ok: false, kind: 'transient', status: '429', reason: 'reason_429', message };
|
|
55
72
|
return { ok: false, kind: 'transient', status: String(s), reason: 'reason_5xx', message };
|
|
56
73
|
}
|
|
57
|
-
//
|
|
58
|
-
|
|
74
|
+
// Docs say unwrapped, but Cloudflare actually returns {success, result: {state: "Completed", result: {answers}}}
|
|
75
|
+
// (verified 2026-10-02). Walk down "result" until the answers show up.
|
|
76
|
+
let out = json;
|
|
77
|
+
for (let i = 0; i < 3 && out && !out.answers && out.result; i++) {
|
|
78
|
+
if (out.state && out.state !== 'Completed')
|
|
79
|
+
break;
|
|
80
|
+
out = out.result;
|
|
81
|
+
}
|
|
59
82
|
if (!out?.answers || typeof out.answers !== 'object') {
|
|
60
83
|
return { ok: false, kind: 'transient', status: String(res.status), reason: 'reason_bad_response' };
|
|
61
84
|
}
|
package/dist/brain.js
CHANGED
|
@@ -55,7 +55,7 @@ export function loadBrain(root) {
|
|
|
55
55
|
// ---------- user-level credentials ----------
|
|
56
56
|
// GUI-launched agents and git clients often do not inherit shell env vars, so keys set in .zshrc
|
|
57
57
|
// never reach the hook. A per-user file outside every repo fixes that without touching rc files.
|
|
58
|
-
export const CREDENTIAL_KEYS = ['CLOUDFLARE_API_TOKEN', 'CLOUDFLARE_ACCOUNT_ID', 'OPENROUTER_API_KEY'];
|
|
58
|
+
export const CREDENTIAL_KEYS = ['CLOUDFLARE_API_TOKEN', 'CLOUDFLARE_ACCOUNT_ID', 'OPENROUTER_API_KEY', 'TYPESAFE_API_KEY'];
|
|
59
59
|
export function credentialsPath(env = process.env) {
|
|
60
60
|
const base = env.APPDATA ?? env.XDG_CONFIG_HOME ?? join(homedir(), '.config');
|
|
61
61
|
return join(base, 'your-cto-jev', 'credentials.json');
|
|
@@ -70,10 +70,30 @@ export function applyCredentials(env = process.env) {
|
|
|
70
70
|
if (!env[k])
|
|
71
71
|
env[k] = v;
|
|
72
72
|
}
|
|
73
|
+
/** Replace the stored keys with exactly `c`; personal prefs in the same file are kept. */
|
|
73
74
|
export function saveCredentials(c) {
|
|
75
|
+
const raw = readJson(credentialsPath()) ?? {};
|
|
76
|
+
for (const k of CREDENTIAL_KEYS)
|
|
77
|
+
delete raw[k];
|
|
78
|
+
return writeUserFile({ ...raw, ...c });
|
|
79
|
+
}
|
|
80
|
+
export function loadPrefs() {
|
|
81
|
+
const raw = readJson(credentialsPath()) ?? {};
|
|
82
|
+
return {
|
|
83
|
+
...(Array.isArray(raw.provider_order) && { provider_order: raw.provider_order.filter((p) => typeof p === 'string') }),
|
|
84
|
+
...((raw.lang === 'zh-TW' || raw.lang === 'en') && { lang: raw.lang }),
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
export function savePrefs(p) {
|
|
88
|
+
const raw = readJson(credentialsPath()) ?? {};
|
|
89
|
+
delete raw.provider_order;
|
|
90
|
+
delete raw.lang;
|
|
91
|
+
return writeUserFile({ ...raw, ...p });
|
|
92
|
+
}
|
|
93
|
+
function writeUserFile(data) {
|
|
74
94
|
const path = credentialsPath();
|
|
75
95
|
mkdirSync(dirname(path), { recursive: true });
|
|
76
|
-
writeFileSync(path, JSON.stringify(
|
|
96
|
+
writeFileSync(path, JSON.stringify(data, null, 2) + '\n', { mode: 0o600 });
|
|
77
97
|
return path;
|
|
78
98
|
}
|
|
79
99
|
/**
|
package/dist/doctor.js
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { agents } from './agents.js';
|
|
5
|
+
import { probeProvider, providers } from './api.js';
|
|
6
|
+
import { loadBrain, loadConfig, loadCredentials } from './brain.js';
|
|
7
|
+
import { AGENT_TIMEOUT_MS } from './hooks.js';
|
|
8
|
+
import { t } from './i18n.js';
|
|
9
|
+
import { wiredAgents } from './setup.js';
|
|
10
|
+
import { checkUpdate, currentVersion } from './update.js';
|
|
11
|
+
function hint(provider, status) {
|
|
12
|
+
if (status === '401')
|
|
13
|
+
return provider === 'cloudflare' ? 'doc_hint_cf_401' : 'doc_hint_401';
|
|
14
|
+
if (status === '403')
|
|
15
|
+
return provider === 'cloudflare' ? 'doc_hint_cf_403' : 'doc_hint_401';
|
|
16
|
+
if (status === '402')
|
|
17
|
+
return 'doc_hint_402';
|
|
18
|
+
if (status === 'timeout' || status === 'network')
|
|
19
|
+
return 'doc_hint_network';
|
|
20
|
+
return 'doc_hint_other';
|
|
21
|
+
}
|
|
22
|
+
/** One screen answering "is cto actually working here?". Exit 1 when it is not. */
|
|
23
|
+
export async function doctor(cwd, lang) {
|
|
24
|
+
const L = [];
|
|
25
|
+
const problems = [];
|
|
26
|
+
const latest = await checkUpdate();
|
|
27
|
+
L.push(t(lang, 'doc_version', { v: currentVersion() }) + (latest ? ' ' + t(lang, 'update_available', { latest, current: currentVersion() }) : ''));
|
|
28
|
+
// Keys and a live probe per provider
|
|
29
|
+
L.push('', t(lang, 'doc_keys'));
|
|
30
|
+
const file = loadCredentials();
|
|
31
|
+
let working = 0;
|
|
32
|
+
for (const name of Object.keys(providers)) {
|
|
33
|
+
const label = providers[name].label;
|
|
34
|
+
const missing = providers[name].keys.filter((k) => !process.env[k]);
|
|
35
|
+
if (missing.length) {
|
|
36
|
+
L.push(` - ${label}: ${t(lang, 'doc_not_set', { keys: missing.join(', ') })}`);
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
const fromFile = providers[name].keys.every((k) => file[k] && file[k] === process.env[k]);
|
|
40
|
+
const source = t(lang, fromFile ? 'doc_src_file' : 'doc_src_env');
|
|
41
|
+
const start = performance.now();
|
|
42
|
+
const r = await probeProvider(name);
|
|
43
|
+
const ms = Math.round(performance.now() - start);
|
|
44
|
+
if (r.ok) {
|
|
45
|
+
working++;
|
|
46
|
+
const slow = ms > AGENT_TIMEOUT_MS;
|
|
47
|
+
L.push(` ${slow ? '!!' : 'OK'} ${label} (${source}): ${t(lang, 'doc_ok', { ms })}${slow ? ' ' + t(lang, 'doc_slow', { limit: AGENT_TIMEOUT_MS / 1000 }) : ''}`);
|
|
48
|
+
if (slow)
|
|
49
|
+
problems.push(t(lang, 'doc_slow', { limit: AGENT_TIMEOUT_MS / 1000 }));
|
|
50
|
+
}
|
|
51
|
+
else {
|
|
52
|
+
L.push(` !! ${label} (${source}): ${t(lang, 'doc_fail', { status: r.status })} ${r.message ?? ''}`.trimEnd());
|
|
53
|
+
L.push(` ${t(lang, hint(name, r.status))}`);
|
|
54
|
+
problems.push(t(lang, 'doc_p_provider', { name: label }));
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
if (!working)
|
|
58
|
+
problems.unshift(t(lang, 'doc_p_no_provider'));
|
|
59
|
+
// Current repository
|
|
60
|
+
let root;
|
|
61
|
+
try {
|
|
62
|
+
root = execFileSync('git', ['rev-parse', '--show-toplevel'], { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
|
|
63
|
+
}
|
|
64
|
+
catch { /* not a repo */ }
|
|
65
|
+
if (!root) {
|
|
66
|
+
L.push('', t(lang, 'doc_no_repo'));
|
|
67
|
+
}
|
|
68
|
+
else {
|
|
69
|
+
L.push('', t(lang, 'doc_repo', { root }));
|
|
70
|
+
const hooksDir = execFileSync('git', ['rev-parse', '--path-format=absolute', '--git-path', 'hooks'], { cwd: root, encoding: 'utf8' }).trim();
|
|
71
|
+
const hookPath = join(hooksDir, 'pre-commit');
|
|
72
|
+
const hook = existsSync(hookPath) ? readFileSync(hookPath, 'utf8') : '';
|
|
73
|
+
if (hook.includes('YOUR CTO JEV START'))
|
|
74
|
+
L.push(` OK ${t(lang, 'doc_hook_ok', { path: hookPath })}`);
|
|
75
|
+
else {
|
|
76
|
+
L.push(` !! ${t(lang, 'doc_hook_missing')}`);
|
|
77
|
+
problems.push(t(lang, 'doc_hook_missing'));
|
|
78
|
+
}
|
|
79
|
+
const wired = wiredAgents(root);
|
|
80
|
+
L.push(` ${wired.length ? 'OK' : '--'} ${t(lang, 'doc_agents', { list: wired.map((n) => agents[n].label).join(', ') || t(lang, 'doc_none') })}`);
|
|
81
|
+
const cfg = loadConfig(root);
|
|
82
|
+
L.push(` -- ${t(lang, cfg.sprint_goal.trim() ? 'doc_goal_set' : 'doc_goal_empty')}`);
|
|
83
|
+
const brain = loadBrain(root);
|
|
84
|
+
L.push(` -- ${t(lang, 'doc_stats', { blocked: brain.blocked_attempts, skipped: brain.skipped_attempts })}`);
|
|
85
|
+
for (const [p, cd] of Object.entries(brain.provider_cooldown)) {
|
|
86
|
+
if (cd.until > Date.now())
|
|
87
|
+
L.push(` !! ${t(lang, 'doc_cooldown', { name: providers[p]?.label ?? p, status: cd.status, until: new Date(cd.until).toLocaleTimeString() })}`);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
L.push('');
|
|
91
|
+
if (problems.length) {
|
|
92
|
+
L.push(t(lang, 'doc_bad'));
|
|
93
|
+
for (const p of problems)
|
|
94
|
+
L.push(` - ${p}`);
|
|
95
|
+
}
|
|
96
|
+
else {
|
|
97
|
+
L.push(t(lang, 'doc_good'));
|
|
98
|
+
}
|
|
99
|
+
return { code: problems.length ? 1 : 0, lines: L };
|
|
100
|
+
}
|
package/dist/hooks.js
CHANGED
|
@@ -84,6 +84,9 @@ export const touchesTests = (diff) => TESTISH.test(diff);
|
|
|
84
84
|
// Pinned diff format: user config (noprefix, color.diff=always, external diff, textconv) would break parsing and masking.
|
|
85
85
|
export const DIFF_ARGS = ['diff', '--cached', '--no-color', '--no-ext-diff', '--no-textconv', '--src-prefix=a/', '--dst-prefix=b/'];
|
|
86
86
|
export const stagedDiff = (cwd) => execFileSync('git', DIFF_ARGS, { cwd, encoding: 'utf8', maxBuffer: 256 * 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore'] });
|
|
87
|
+
// Measured 2026-10-02: Cloudflare p50 0.9 s, p95 2.1 s, cold spikes to 3.2 s; OpenRouter p95 0.33 s.
|
|
88
|
+
// A timeout means "let it through unchecked", so wait as long as the git side does rather than fail open.
|
|
89
|
+
export const AGENT_TIMEOUT_MS = 5000;
|
|
87
90
|
// ---------- git-commit ----------
|
|
88
91
|
export async function gitCommit(rawDiff, { root, lang, now }) {
|
|
89
92
|
const cfg = loadConfig(root);
|
|
@@ -171,7 +174,7 @@ export async function agentPre(agent, input, { root, lang, now }) {
|
|
|
171
174
|
}
|
|
172
175
|
const notices = new Set();
|
|
173
176
|
const { sessionId } = input;
|
|
174
|
-
const r = await evaluate({ state, questions, ...(sessionId && { session_id: sessionId }) }, { brain, lang, timeoutMs:
|
|
177
|
+
const r = await evaluate({ state, questions, ...(sessionId && { session_id: sessionId }) }, { brain, lang, timeoutMs: AGENT_TIMEOUT_MS, notices, now });
|
|
175
178
|
if (!r.ok)
|
|
176
179
|
brain.skipped_attempts++;
|
|
177
180
|
await sessionNotice(brain, sessionId, lang, r, notices);
|
package/dist/i18n.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
|
|
1
|
+
import { loadPrefs } from './brain.js';
|
|
2
|
+
/** CTO_LANG > language picked in setup > LC_ALL / LANG > OS locale via Intl (Windows has no LANG) > en. zh-* maps to zh-TW. */
|
|
2
3
|
export function detectLang(env = process.env) {
|
|
3
4
|
const pick = (v) => {
|
|
4
5
|
if (!v || v === 'C' || v === 'POSIX')
|
|
@@ -6,6 +7,7 @@ export function detectLang(env = process.env) {
|
|
|
6
7
|
return v.toLowerCase().startsWith('zh') ? 'zh-TW' : v.toLowerCase().startsWith('en') ? 'en' : undefined;
|
|
7
8
|
};
|
|
8
9
|
return (pick(env.CTO_LANG) ??
|
|
10
|
+
loadPrefs().lang ??
|
|
9
11
|
pick(env.LC_ALL) ??
|
|
10
12
|
pick(env.LANG) ??
|
|
11
13
|
pick(Intl.DateTimeFormat().resolvedOptions().locale) ??
|
|
@@ -62,29 +64,77 @@ const messages = {
|
|
|
62
64
|
setup_agent: (v) => `[cto] ${v.label} hooks 已寫入 ${v.path}`,
|
|
63
65
|
uninstall_agent: (v) => `[cto] 已從 ${v.path} 移除 ${v.label} hooks`,
|
|
64
66
|
note_codex_trust: () => '[cto] 注意:Codex 只在專案被信任後才執行 .codex/ 的 hook,第一次在此目錄開 codex 時請選擇信任。',
|
|
65
|
-
wiz_intro: () => '\ncto 設定共兩步:1. 選擇要保護的 coding agent 2. 設定 Jev API key\n(git commit 檢查一律安裝,所有 agent 和手動 commit 共用)',
|
|
66
|
-
wiz_step_agents: () => '\n步驟 1/2:要攔截哪些 coding agent 的指令?',
|
|
67
|
-
wiz_agents_hint: () => '輸入編號切換勾選(例如 3 或 1,3),直接 Enter 確認:',
|
|
68
|
-
wiz_invalid: () => ' 看不懂這個輸入,請輸入清單上的編號,例如 1 或 1,3。',
|
|
69
|
-
wiz_found: () => '(已偵測到)',
|
|
70
|
-
wiz_step_keys: () => '\n步驟 2/2:Jev API key',
|
|
71
|
-
wiz_keys_present: () => '[cto] 已從環境變數或憑證檔找到 Jev API key,略過這步。要重設請執行 cto setup --keys',
|
|
72
|
-
wiz_keys: (v) => `可用的 provider 如下,至少要設定一個 cto 才會開始檢查。key 存在 ${v.path},只有你的帳號可讀,不會進 git。`,
|
|
73
|
-
wiz_provider_openrouter: () => 'OpenRouter:最簡單,只要一組 API key(openrouter.ai)',
|
|
74
|
-
wiz_provider_cloudflare: () => 'Cloudflare Workers AI:需要 Account ID 與 API token,且帳號的 AI Gateway 要開啟 Authenticated Gateway',
|
|
75
|
-
wiz_providers_hint: () => '要設定哪些?輸入編號(例如 1 或 1,2),直接 Enter 先跳過:',
|
|
76
|
-
wiz_or_key: () => ' OpenRouter API key: ',
|
|
77
|
-
wiz_cf_account: () => ' Cloudflare Account ID: ',
|
|
78
|
-
wiz_cf_token: () => ' Cloudflare API token: ',
|
|
79
67
|
wiz_checking: (v) => ` 正在用一次真實請求驗證 ${v.name}...`,
|
|
80
68
|
wiz_ok: (v) => ` ${v.name} 驗證成功`,
|
|
81
69
|
wiz_fail: (v) => ` ${v.name} 驗證失敗 (${v.status}) ${v.msg}`,
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
70
|
+
ui_title: () => 'cto 設定',
|
|
71
|
+
ui_first_run: () => '共四步:coding agent、Jev provider、API key、sprint goal。↑↓ 移動,Enter 確認,Esc 回上一步。完成後會回到總覽,之後也能單獨修改任何一項。',
|
|
72
|
+
ui_agents_q: () => '要攔截哪些 coding agent 的指令?(git commit 檢查一律安裝)\n ↑↓ 移動 · 空白鍵勾選 · Enter 確認 · Esc 返回',
|
|
73
|
+
ui_detected: () => '已偵測到',
|
|
74
|
+
ui_providers_q: () => '要用哪些 Jev provider?',
|
|
75
|
+
ui_providers_help: () => '↑↓ 移動 · 空白鍵勾選 · 按數字鍵把游標所在項目移到該順位 · Enter 確認 · Esc 返回\n│ 數字是優先順序:1 先用,失敗才換下一個',
|
|
76
|
+
ui_p_openrouter: () => '最簡單,一組 key(openrouter.ai)',
|
|
77
|
+
ui_p_typesafe: () => 'Jev 官方直連,一組 key(console.typesafe.ai/keys)',
|
|
78
|
+
ui_p_cloudflare: () => 'Account ID + API token,需開 AI Gateway 驗證與額度',
|
|
79
|
+
ui_no_provider: () => '沒有選任何 provider:cto 不會檢查任何東西,所有動作都會直接放行。',
|
|
80
|
+
key_OPENROUTER_API_KEY: () => 'API key',
|
|
81
|
+
key_TYPESAFE_API_KEY: () => 'API key',
|
|
82
|
+
key_CLOUDFLARE_ACCOUNT_ID: () => 'Account ID',
|
|
83
|
+
key_CLOUDFLARE_API_TOKEN: () => 'API token(需 Workers AI Read 權限)',
|
|
84
|
+
ui_keep: (v) => `保留目前的值 ${v.tail}`,
|
|
85
|
+
ui_keep_env: (v) => `使用環境變數裡的值 ${v.tail}(不另外儲存)`,
|
|
86
|
+
ui_reenter: () => '重新輸入',
|
|
87
|
+
ui_required: () => '不能空白;不想設定就按 Esc 回上一步',
|
|
88
|
+
ui_fail_q: (v) => `${v.name} 驗證失敗,要怎麼做?`,
|
|
89
|
+
ui_retry: () => '重新輸入',
|
|
90
|
+
ui_save_anyway: () => '仍然儲存(之後用 cto doctor 再確認)',
|
|
91
|
+
ui_drop: (v) => `不使用 ${v.name}`,
|
|
92
|
+
ui_goal_q: () => 'Sprint goal(選填,填了才會檢查 commit 是否偏離目標)',
|
|
93
|
+
ui_goal_ph: () => '例如:完成 Stripe 金流,不新增服務',
|
|
94
|
+
ui_lang_q: () => 'cto 的訊息語言',
|
|
95
|
+
ui_lang_auto: () => '自動(跟系統語言)',
|
|
96
|
+
ui_menu_q: () => '設定總覽:選一項修改,或儲存(↑↓ 移動 · Enter 選擇 · Esc 不儲存離開)',
|
|
97
|
+
ui_m_agents: () => 'Coding agents',
|
|
98
|
+
ui_m_providers: () => 'Jev providers 與順序',
|
|
99
|
+
ui_m_keys: () => '更換 API key',
|
|
100
|
+
ui_m_goal: () => 'Sprint goal',
|
|
101
|
+
ui_m_lang: () => '語言',
|
|
102
|
+
ui_m_save: () => '儲存並完成',
|
|
103
|
+
ui_m_quit: () => '不儲存離開',
|
|
104
|
+
ui_unset: () => '未設定',
|
|
105
|
+
ui_saved: () => '設定完成。之後執行 cto setup 可以回到這個總覽,cto doctor 可以確認是否正常運作。',
|
|
106
|
+
ui_quit: () => '已離開,沒有修改任何設定。',
|
|
107
|
+
doc_version: (v) => `cto ${v.v}`,
|
|
108
|
+
doc_keys: () => 'Jev API key(每個都用一次真實請求驗證):',
|
|
109
|
+
doc_not_set: (v) => `未設定(缺 ${v.keys})`,
|
|
110
|
+
doc_src_file: () => '來自憑證檔',
|
|
111
|
+
doc_src_env: () => '來自環境變數',
|
|
112
|
+
doc_ok: (v) => `可用,${v.ms} ms`,
|
|
113
|
+
doc_slow: (v) => `注意:超過 agent 端 ${v.limit} 秒逾時,這次在 agent 裡會被放行`,
|
|
114
|
+
doc_fail: (v) => `失敗 (${v.status})`,
|
|
115
|
+
doc_hint_cf_401: () => 'token 無效或缺少權限:Account > Workers AI > Read',
|
|
116
|
+
doc_hint_cf_403: () => '到 AI > AI Gateway > default > Settings 開啟 Authenticated Gateway',
|
|
117
|
+
doc_hint_401: () => 'key 無效或已撤銷,請重新產生後執行 cto setup',
|
|
118
|
+
doc_hint_402: () => '額度不足,請到 provider 後台儲值',
|
|
119
|
+
doc_hint_network: () => '連不上或太慢,檢查網路或稍後再試',
|
|
120
|
+
doc_hint_other: () => '非預期的回應,請回報到 github.com/rainday/your-cto-jev/issues',
|
|
121
|
+
doc_repo: (v) => `目前的 repo:${v.root}`,
|
|
122
|
+
doc_no_repo: () => '目前不在 git repo 裡,略過專案檢查。',
|
|
123
|
+
doc_hook_ok: (v) => `git pre-commit 已安裝(${v.path})`,
|
|
124
|
+
doc_hook_missing: () => 'git pre-commit 沒有 cto 區塊,請在此 repo 執行 cto setup',
|
|
125
|
+
doc_agents: (v) => `已接上的 agent:${v.list}`,
|
|
126
|
+
doc_none: () => '無',
|
|
127
|
+
doc_goal_set: () => 'sprint_goal 已設定,架構對齊檢查啟用中',
|
|
128
|
+
doc_goal_empty: () => 'sprint_goal 未設定,架構對齊檢查關閉(可在 .cto.json 填入)',
|
|
129
|
+
doc_stats: (v) => `累計:擋下 ${v.blocked} 次,因無法檢查而放行 ${v.skipped} 次`,
|
|
130
|
+
doc_cooldown: (v) => `${v.name} 冷卻中,原因 ${v.status},到 ${v.until} 才會重試`,
|
|
131
|
+
doc_p_no_provider: () => '沒有任何可用的 provider:現在所有檢查都會直接放行',
|
|
132
|
+
doc_p_provider: (v) => `${v.name} 無法使用`,
|
|
133
|
+
doc_good: () => '[cto] 一切正常,cto 正在保護這個 repo。',
|
|
134
|
+
doc_bad: () => '[cto] 有問題需要處理:',
|
|
85
135
|
update_available: (v) => `[cto] 有新版 ${v.latest}(目前 ${v.current}),執行 cto update 更新`,
|
|
86
136
|
update_done: () => '[cto] 已更新。已設定過的專案不用重跑 cto setup。',
|
|
87
|
-
usage: () => '用法:cto update | cto --version | cto setup [--agents claude,cursor,gemini,codex] [--
|
|
137
|
+
usage: () => '用法:cto doctor | cto update | cto --version | cto setup [--agents claude,cursor,gemini,codex] [--yes] [--uninstall] | cto --hook <git-commit|AGENT-pre|AGENT-post>',
|
|
88
138
|
},
|
|
89
139
|
en: {
|
|
90
140
|
reason_402: () => 'out of credits',
|
|
@@ -118,29 +168,77 @@ const messages = {
|
|
|
118
168
|
setup_agent: (v) => `[cto] ${v.label} hooks written to ${v.path}`,
|
|
119
169
|
uninstall_agent: (v) => `[cto] Removed ${v.label} hooks from ${v.path}`,
|
|
120
170
|
note_codex_trust: () => '[cto] Note: Codex only runs .codex/ hooks once the project is trusted. Trust it the first time you open codex here.',
|
|
121
|
-
wiz_intro: () => '\ncto setup has two steps: 1. pick the coding agents to protect 2. set up a Jev API key\n(the git commit check is always installed and covers every agent and manual commits)',
|
|
122
|
-
wiz_step_agents: () => '\nStep 1/2: Which coding agents should have their commands checked?',
|
|
123
|
-
wiz_agents_hint: () => 'Type numbers to toggle (e.g. 3 or 1,3), or press Enter to confirm: ',
|
|
124
|
-
wiz_invalid: () => ' Did not understand that. Type numbers from the list, e.g. 1 or 1,3.',
|
|
125
|
-
wiz_found: () => ' (detected)',
|
|
126
|
-
wiz_step_keys: () => '\nStep 2/2: Jev API key',
|
|
127
|
-
wiz_keys_present: () => '[cto] Found a Jev API key in env or the credentials file, skipping this step. Run cto setup --keys to change it.',
|
|
128
|
-
wiz_keys: (v) => `These providers are available. Set up at least one, or cto checks nothing. Keys are stored in ${v.path}, readable only by you, never in git.`,
|
|
129
|
-
wiz_provider_openrouter: () => 'OpenRouter: easiest, one API key (openrouter.ai)',
|
|
130
|
-
wiz_provider_cloudflare: () => 'Cloudflare Workers AI: Account ID plus API token, and Authenticated Gateway must be on in your AI Gateway',
|
|
131
|
-
wiz_providers_hint: () => 'Which ones? Type numbers (e.g. 1 or 1,2), or press Enter to skip for now: ',
|
|
132
|
-
wiz_or_key: () => ' OpenRouter API key: ',
|
|
133
|
-
wiz_cf_account: () => ' Cloudflare Account ID: ',
|
|
134
|
-
wiz_cf_token: () => ' Cloudflare API token: ',
|
|
135
171
|
wiz_checking: (v) => ` Verifying ${v.name} with one real request...`,
|
|
136
172
|
wiz_ok: (v) => ` ${v.name} OK`,
|
|
137
173
|
wiz_fail: (v) => ` ${v.name} failed (${v.status}) ${v.msg}`,
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
174
|
+
ui_title: () => 'cto setup',
|
|
175
|
+
ui_first_run: () => 'Four steps: coding agents, Jev providers, API keys, sprint goal. Up/Down to move, Enter to confirm, Esc to go back. You land on an overview at the end and can change any single item later.',
|
|
176
|
+
ui_agents_q: () => 'Which coding agents should have their commands checked? (the git commit check is always installed)\n Up/Down move · Space toggles · Enter confirms · Esc goes back',
|
|
177
|
+
ui_detected: () => 'detected',
|
|
178
|
+
ui_providers_q: () => 'Which Jev providers should cto use?',
|
|
179
|
+
ui_providers_help: () => 'Up/Down move · Space toggles · press a number to move the item under the cursor to that position · Enter confirms · Esc goes back\n│ Numbers are priority: 1 first, the next one only on failure',
|
|
180
|
+
ui_p_openrouter: () => 'easiest, one key (openrouter.ai)',
|
|
181
|
+
ui_p_typesafe: () => 'direct from the makers of Jev, one key (console.typesafe.ai/keys)',
|
|
182
|
+
ui_p_cloudflare: () => 'Account ID + API token; needs Authenticated Gateway and credits',
|
|
183
|
+
ui_no_provider: () => 'No provider picked: cto will check nothing and let every action through.',
|
|
184
|
+
key_OPENROUTER_API_KEY: () => 'API key',
|
|
185
|
+
key_TYPESAFE_API_KEY: () => 'API key',
|
|
186
|
+
key_CLOUDFLARE_ACCOUNT_ID: () => 'Account ID',
|
|
187
|
+
key_CLOUDFLARE_API_TOKEN: () => 'API token (needs Workers AI Read)',
|
|
188
|
+
ui_keep: (v) => `Keep the current value ${v.tail}`,
|
|
189
|
+
ui_keep_env: (v) => `Use the value from the environment ${v.tail} (not stored)`,
|
|
190
|
+
ui_reenter: () => 'Enter a new one',
|
|
191
|
+
ui_required: () => 'Cannot be empty. Press Esc to go back if you want to skip it',
|
|
192
|
+
ui_fail_q: (v) => `${v.name} failed verification. What next?`,
|
|
193
|
+
ui_retry: () => 'Enter it again',
|
|
194
|
+
ui_save_anyway: () => 'Save anyway (check later with cto doctor)',
|
|
195
|
+
ui_drop: (v) => `Do not use ${v.name}`,
|
|
196
|
+
ui_goal_q: () => 'Sprint goal (optional; enables the check for commits that drift from it)',
|
|
197
|
+
ui_goal_ph: () => 'e.g. Ship Stripe billing, no new services',
|
|
198
|
+
ui_lang_q: () => 'Language for cto messages',
|
|
199
|
+
ui_lang_auto: () => 'Automatic (system language)',
|
|
200
|
+
ui_menu_q: () => 'Overview: pick an item to change, or save (Up/Down move · Enter selects · Esc quits without saving)',
|
|
201
|
+
ui_m_agents: () => 'Coding agents',
|
|
202
|
+
ui_m_providers: () => 'Jev providers and order',
|
|
203
|
+
ui_m_keys: () => 'Change API keys',
|
|
204
|
+
ui_m_goal: () => 'Sprint goal',
|
|
205
|
+
ui_m_lang: () => 'Language',
|
|
206
|
+
ui_m_save: () => 'Save and finish',
|
|
207
|
+
ui_m_quit: () => 'Quit without saving',
|
|
208
|
+
ui_unset: () => 'not set',
|
|
209
|
+
ui_saved: () => 'Done. Run cto setup to come back to this overview, and cto doctor to check that it works.',
|
|
210
|
+
ui_quit: () => 'Left without changing anything.',
|
|
211
|
+
doc_version: (v) => `cto ${v.v}`,
|
|
212
|
+
doc_keys: () => 'Jev API keys (each verified with one real request):',
|
|
213
|
+
doc_not_set: (v) => `not set (missing ${v.keys})`,
|
|
214
|
+
doc_src_file: () => 'credentials file',
|
|
215
|
+
doc_src_env: () => 'environment',
|
|
216
|
+
doc_ok: (v) => `working, ${v.ms} ms`,
|
|
217
|
+
doc_slow: (v) => `warning: slower than the ${v.limit} s agent timeout, so this check would be skipped inside an agent`,
|
|
218
|
+
doc_fail: (v) => `failed (${v.status})`,
|
|
219
|
+
doc_hint_cf_401: () => 'Token invalid or missing the Account > Workers AI > Read permission',
|
|
220
|
+
doc_hint_cf_403: () => 'Turn on Authenticated Gateway under AI > AI Gateway > default > Settings',
|
|
221
|
+
doc_hint_401: () => 'Key invalid or revoked. Create a new one and run cto setup',
|
|
222
|
+
doc_hint_402: () => 'Out of credits. Top up in the provider dashboard',
|
|
223
|
+
doc_hint_network: () => 'Unreachable or too slow. Check your network or try again later',
|
|
224
|
+
doc_hint_other: () => 'Unexpected response. Please report it at github.com/rainday/your-cto-jev/issues',
|
|
225
|
+
doc_repo: (v) => `Current repo: ${v.root}`,
|
|
226
|
+
doc_no_repo: () => 'Not inside a git repo, skipping project checks.',
|
|
227
|
+
doc_hook_ok: (v) => `git pre-commit installed (${v.path})`,
|
|
228
|
+
doc_hook_missing: () => 'git pre-commit has no cto block. Run cto setup in this repo',
|
|
229
|
+
doc_agents: (v) => `Agents wired up: ${v.list}`,
|
|
230
|
+
doc_none: () => 'none',
|
|
231
|
+
doc_goal_set: () => 'sprint_goal set, architecture check on',
|
|
232
|
+
doc_goal_empty: () => 'sprint_goal empty, architecture check off (set it in .cto.json)',
|
|
233
|
+
doc_stats: (v) => `So far: blocked ${v.blocked}, let through unchecked ${v.skipped}`,
|
|
234
|
+
doc_cooldown: (v) => `${v.name} is cooling down after ${v.status}, retried after ${v.until}`,
|
|
235
|
+
doc_p_no_provider: () => 'No working provider: every check is currently let through',
|
|
236
|
+
doc_p_provider: (v) => `${v.name} is not working`,
|
|
237
|
+
doc_good: () => '[cto] All good. cto is protecting this repo.',
|
|
238
|
+
doc_bad: () => '[cto] Needs attention:',
|
|
141
239
|
update_available: (v) => `[cto] Version ${v.latest} is available (you have ${v.current}). Run cto update`,
|
|
142
240
|
update_done: () => '[cto] Updated. Projects already set up do not need cto setup again.',
|
|
143
|
-
usage: () => 'Usage: cto update | cto --version | cto setup [--agents claude,cursor,gemini,codex] [--
|
|
241
|
+
usage: () => 'Usage: cto doctor | cto update | cto --version | cto setup [--agents claude,cursor,gemini,codex] [--yes] [--uninstall] | cto --hook <git-commit|AGENT-pre|AGENT-post>',
|
|
144
242
|
},
|
|
145
243
|
};
|
|
146
244
|
export function t(lang, key, vars = {}) {
|
package/dist/index.js
CHANGED
|
@@ -2,13 +2,14 @@
|
|
|
2
2
|
import { writeFileSync } from 'node:fs';
|
|
3
3
|
import { join } from 'node:path';
|
|
4
4
|
import { agentNames, agents } from './agents.js';
|
|
5
|
-
import { applyCredentials, findRoot } from './brain.js';
|
|
5
|
+
import { applyCredentials, findRoot, loadConfig, loadCredentials, loadPrefs, saveCredentials, savePrefs } from './brain.js';
|
|
6
|
+
import { providerOrder, providers } from './api.js';
|
|
6
7
|
import { agentPost, agentPre, gitCommit, stagedDiff } from './hooks.js';
|
|
7
8
|
import { checkUpdate, currentVersion, runUpdate } from './update.js';
|
|
9
|
+
import { doctor } from './doctor.js';
|
|
8
10
|
import { detectLang, t } from './i18n.js';
|
|
9
11
|
import { maskDiff, maskSensitiveState } from './masker.js';
|
|
10
|
-
import { detectAgents, setup } from './setup.js';
|
|
11
|
-
import { terminalAsk, wizard } from './wizard.js';
|
|
12
|
+
import { detectAgents, gitRoot, setSprintGoal, setup, wiredAgents } from './setup.js';
|
|
12
13
|
async function readStdin() {
|
|
13
14
|
if (process.stdin.isTTY)
|
|
14
15
|
return '';
|
|
@@ -81,25 +82,39 @@ if (args[0] === '--hook' && args[1]) {
|
|
|
81
82
|
else if (args[0] === 'setup') {
|
|
82
83
|
const uninstall = args.includes('--uninstall');
|
|
83
84
|
let chosen;
|
|
85
|
+
let goal;
|
|
86
|
+
const root = gitRoot(process.cwd());
|
|
84
87
|
const list = flag('--agents');
|
|
85
88
|
if (list)
|
|
86
89
|
chosen = list.split(',').map((s) => s.trim()).filter((s) => agentNames.includes(s));
|
|
87
|
-
else if (!uninstall && process.stdin.isTTY && process.stdout.isTTY && !args.includes('--yes')) {
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
90
|
+
else if (!uninstall && root && process.stdin.isTTY && process.stdout.isTTY && !args.includes('--yes')) {
|
|
91
|
+
// Interactive: start from what is actually set up now, so re-running setup edits instead of starting over.
|
|
92
|
+
const fileKeys = loadCredentials();
|
|
93
|
+
const prefs = loadPrefs();
|
|
94
|
+
const wired = wiredAgents(root);
|
|
95
|
+
const initial = {
|
|
96
|
+
agents: wired.length ? wired : detectAgents(),
|
|
97
|
+
providers: prefs.provider_order ?? Object.keys(providers).filter((p) => providers[p].enabled()),
|
|
98
|
+
keys: fileKeys,
|
|
99
|
+
lang: prefs.lang,
|
|
100
|
+
goal: loadConfig(root).sprint_goal,
|
|
101
|
+
};
|
|
102
|
+
const firstRun = !wired.length && !providerOrder().length;
|
|
103
|
+
const { setupUI } = await import('./setupui.js'); // clack loads only for interactive setup, never on the hook path
|
|
104
|
+
const s = await setupUI(initial, firstRun, lang, { detected: detectAgents() });
|
|
105
|
+
if (!s)
|
|
106
|
+
process.exit(0); // quit without saving: nothing was written
|
|
107
|
+
saveCredentials(s.keys);
|
|
108
|
+
savePrefs({ provider_order: s.providers, ...(s.lang && { lang: s.lang }) });
|
|
109
|
+
chosen = s.agents;
|
|
110
|
+
goal = s.goal;
|
|
98
111
|
}
|
|
99
112
|
else if (!uninstall) {
|
|
100
113
|
chosen = detectAgents();
|
|
101
114
|
}
|
|
102
115
|
const r = setup(process.cwd(), lang, { uninstall, agents: chosen });
|
|
116
|
+
if (!r.code && root && goal !== undefined)
|
|
117
|
+
setSprintGoal(root, goal);
|
|
103
118
|
const latest = r.code ? undefined : await checkUpdate();
|
|
104
119
|
if (latest)
|
|
105
120
|
r.lines.push(t(lang, 'update_available', { latest, current: currentVersion() }));
|
|
@@ -111,6 +126,11 @@ else if (args[0] === 'update') {
|
|
|
111
126
|
if (!process.exitCode)
|
|
112
127
|
console.log(t(lang, 'update_done'));
|
|
113
128
|
}
|
|
129
|
+
else if (args[0] === 'doctor') {
|
|
130
|
+
const r = await doctor(process.cwd(), lang);
|
|
131
|
+
console.log(r.lines.join('\n'));
|
|
132
|
+
process.exitCode = r.code;
|
|
133
|
+
}
|
|
114
134
|
else if (args[0] === '--version' || args[0] === '-v') {
|
|
115
135
|
console.log(currentVersion());
|
|
116
136
|
}
|
package/dist/setup.js
CHANGED
|
@@ -126,7 +126,9 @@ export function setup(cwd, lang, opts = {}) {
|
|
|
126
126
|
}
|
|
127
127
|
const rel = (p) => relative(root, p) || p;
|
|
128
128
|
// Validate every config file we may touch before writing anything.
|
|
129
|
-
|
|
129
|
+
// Install touches every agent: chosen ones get hooks, the rest lose any cto hooks (the agent list is the full desired set).
|
|
130
|
+
const targets = opts.uninstall || opts.agents ? agentNames : [];
|
|
131
|
+
const chosen = new Set(opts.uninstall ? [] : (opts.agents ?? []));
|
|
130
132
|
const settings = new Map();
|
|
131
133
|
for (const name of targets) {
|
|
132
134
|
const path = join(root, agents[name].settings);
|
|
@@ -182,8 +184,15 @@ export function setup(cwd, lang, opts = {}) {
|
|
|
182
184
|
}
|
|
183
185
|
chmodSync(hookPath, 0o755);
|
|
184
186
|
lines.push(t(lang, 'setup_hook', { path: rel(hookPath) }));
|
|
185
|
-
// 2. Agent hooks: merge, keep everything else.
|
|
187
|
+
// 2. Agent hooks: merge, keep everything else. Agents not chosen lose their cto hooks only.
|
|
186
188
|
for (const [name, { path, json }] of settings) {
|
|
189
|
+
if (!chosen.has(name)) {
|
|
190
|
+
if (existsSync(path) && uninstallHooks(json)) {
|
|
191
|
+
writeOrRemove(path, json);
|
|
192
|
+
lines.push(t(lang, 'uninstall_agent', { label: agents[name].label, path: rel(path) }));
|
|
193
|
+
}
|
|
194
|
+
continue;
|
|
195
|
+
}
|
|
187
196
|
installAgent(json, name);
|
|
188
197
|
mkdirSync(dirname(path), { recursive: true });
|
|
189
198
|
writeFileSync(path, JSON.stringify(json, null, 2) + '\n');
|
|
@@ -213,3 +222,29 @@ export function setup(cwd, lang, opts = {}) {
|
|
|
213
222
|
lines.push(t(lang, 'setup_done'));
|
|
214
223
|
return { code: 0, lines };
|
|
215
224
|
}
|
|
225
|
+
/** Agents whose config in this repo currently calls cto. */
|
|
226
|
+
export function wiredAgents(root) {
|
|
227
|
+
return agentNames.filter((n) => {
|
|
228
|
+
const p = join(root, agents[n].settings);
|
|
229
|
+
return existsSync(p) && readFileSync(p, 'utf8').includes('cto --hook ');
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
/** Repo root, or undefined outside a git repo. */
|
|
233
|
+
export function gitRoot(cwd) {
|
|
234
|
+
try {
|
|
235
|
+
return git(cwd, 'rev-parse', '--show-toplevel');
|
|
236
|
+
}
|
|
237
|
+
catch {
|
|
238
|
+
return undefined;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
/** Set sprint_goal in .cto.json, keeping everything else in the file. */
|
|
242
|
+
export function setSprintGoal(root, goal) {
|
|
243
|
+
const path = join(root, '.cto.json');
|
|
244
|
+
let cfg = DEFAULT_CONFIG;
|
|
245
|
+
try {
|
|
246
|
+
cfg = JSON.parse(readFileSync(path, 'utf8'));
|
|
247
|
+
}
|
|
248
|
+
catch { /* create */ }
|
|
249
|
+
writeFileSync(path, JSON.stringify({ ...cfg, sprint_goal: goal }, null, 2) + '\n');
|
|
250
|
+
}
|
package/dist/setupui.js
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
import { MultiSelectPrompt } from '@clack/core';
|
|
2
|
+
import { S_BAR, S_BAR_END, S_STEP_ACTIVE, S_STEP_CANCEL, S_STEP_SUBMIT, intro, isCancel, log, multiselect, outro, password, select, spinner, text } from '@clack/prompts';
|
|
3
|
+
import { styleText } from 'node:util';
|
|
4
|
+
import { agentNames, agents } from './agents.js';
|
|
5
|
+
import { probeProvider, providers } from './api.js';
|
|
6
|
+
import { t } from './i18n.js';
|
|
7
|
+
const BACK = Symbol('back');
|
|
8
|
+
const PROVIDER_ORDER = ['openrouter', 'typesafe', 'cloudflare'];
|
|
9
|
+
const dim = (s) => styleText('dim', s);
|
|
10
|
+
const tail = (v) => `…${v.slice(-4)}`;
|
|
11
|
+
/** Terminal columns: CJK and full-width characters take two. */
|
|
12
|
+
const WIDE = /[\u1100-\u115f\u2e80-\ua4cf\uac00-\ud7a3\uf900-\ufaff\ufe30-\ufe4f\uff00-\uff60\uffe0-\uffe6]/;
|
|
13
|
+
export const displayWidth = (s) => [...s].reduce((w, ch) => w + (WIDE.test(ch) ? 2 : 1), 0);
|
|
14
|
+
const pad = (s, w) => s + ' '.repeat(Math.max(0, w - displayWidth(s)));
|
|
15
|
+
/**
|
|
16
|
+
* Interactive setup. First run walks agents -> providers -> keys -> sprint goal (Esc goes back one step), then
|
|
17
|
+
* shows the menu. Later runs open the menu directly, pre-filled with the current setup, so any single item can be
|
|
18
|
+
* changed without touching the rest. Returns the final state, or null if the user quits without saving.
|
|
19
|
+
*/
|
|
20
|
+
export async function setupUI(initial, firstRun, lang, o = {}) {
|
|
21
|
+
const io = { input: o.input, output: o.output };
|
|
22
|
+
const env = o.env ?? process.env;
|
|
23
|
+
const probe = o.probe ?? probeProvider;
|
|
24
|
+
const detected = o.detected ?? [];
|
|
25
|
+
let state = { ...initial, keys: { ...initial.keys } };
|
|
26
|
+
const agentsStep = async (s) => {
|
|
27
|
+
const r = await multiselect({
|
|
28
|
+
...io,
|
|
29
|
+
showInstructions: false,
|
|
30
|
+
message: t(lang, 'ui_agents_q'),
|
|
31
|
+
options: agentNames.map((n) => ({ value: n, label: agents[n].label, ...(detected.includes(n) && { hint: t(lang, 'ui_detected') }) })),
|
|
32
|
+
initialValues: s.agents,
|
|
33
|
+
required: false,
|
|
34
|
+
});
|
|
35
|
+
return isCancel(r) ? BACK : { ...s, agents: r };
|
|
36
|
+
};
|
|
37
|
+
const providersStep = async (s) => {
|
|
38
|
+
const r = await orderedMultiselect(lang, io, PROVIDER_ORDER, s.providers);
|
|
39
|
+
if (typeof r === 'symbol')
|
|
40
|
+
return BACK;
|
|
41
|
+
if (!r.length)
|
|
42
|
+
log.warn(t(lang, 'ui_no_provider'), io);
|
|
43
|
+
return { ...s, providers: r };
|
|
44
|
+
};
|
|
45
|
+
const hasKeys = (p, keys) => providers[p].keys.every((k) => keys[k] || env[k]);
|
|
46
|
+
/**
|
|
47
|
+
* Ask for keys. With `before` (the picks before this edit), only providers that are new or missing a key are asked;
|
|
48
|
+
* the rest are kept as they are, so changing the order alone asks nothing. Without it, every pick is asked (rotate keys).
|
|
49
|
+
*/
|
|
50
|
+
const keysStepFor = (before) => async (s) => {
|
|
51
|
+
const keys = { ...s.keys };
|
|
52
|
+
const kept = [];
|
|
53
|
+
for (const p of s.providers) {
|
|
54
|
+
if (before && before.includes(p) && hasKeys(p, keys)) {
|
|
55
|
+
kept.push(p);
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
const label = providers[p].label;
|
|
59
|
+
for (;;) {
|
|
60
|
+
const candidate = {};
|
|
61
|
+
for (const k of providers[p].keys) {
|
|
62
|
+
const stored = keys[k];
|
|
63
|
+
const fromEnv = !stored && env[k] ? env[k] : undefined;
|
|
64
|
+
if (stored || fromEnv) {
|
|
65
|
+
const keep = await select({
|
|
66
|
+
...io,
|
|
67
|
+
showInstructions: false,
|
|
68
|
+
message: `${label} ${t(lang, 'key_' + k)}`,
|
|
69
|
+
options: [
|
|
70
|
+
{ value: 'keep', label: t(lang, fromEnv ? 'ui_keep_env' : 'ui_keep', { tail: tail((stored ?? fromEnv)) }) },
|
|
71
|
+
{ value: 'new', label: t(lang, 'ui_reenter') },
|
|
72
|
+
],
|
|
73
|
+
});
|
|
74
|
+
if (isCancel(keep))
|
|
75
|
+
return BACK;
|
|
76
|
+
if (keep === 'keep') {
|
|
77
|
+
if (stored)
|
|
78
|
+
candidate[k] = stored;
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
const ask = k.endsWith('ACCOUNT_ID') ? text : password;
|
|
83
|
+
const v = await ask({ ...io, message: `${label} ${t(lang, 'key_' + k)}`, validate: (x) => (x?.trim() ? undefined : t(lang, 'ui_required')) });
|
|
84
|
+
if (isCancel(v))
|
|
85
|
+
return BACK;
|
|
86
|
+
candidate[k] = v.trim();
|
|
87
|
+
}
|
|
88
|
+
// Verify with one real request using exactly these values (env-only ones stay as they are).
|
|
89
|
+
const saved = Object.fromEntries(providers[p].keys.map((k) => [k, env[k]]));
|
|
90
|
+
Object.assign(env, candidate);
|
|
91
|
+
const sp = spinner(io);
|
|
92
|
+
sp.start(t(lang, 'wiz_checking', { name: label }));
|
|
93
|
+
const res = await probe(p);
|
|
94
|
+
for (const [k, v] of Object.entries(saved))
|
|
95
|
+
if (v === undefined)
|
|
96
|
+
delete env[k];
|
|
97
|
+
else
|
|
98
|
+
env[k] = v;
|
|
99
|
+
if (res.ok) {
|
|
100
|
+
sp.stop(t(lang, 'wiz_ok', { name: label }));
|
|
101
|
+
Object.assign(keys, candidate);
|
|
102
|
+
kept.push(p);
|
|
103
|
+
break;
|
|
104
|
+
}
|
|
105
|
+
sp.stop(t(lang, 'wiz_fail', { name: label, status: res.status, msg: res.message ?? '' }));
|
|
106
|
+
const next = await select({
|
|
107
|
+
...io,
|
|
108
|
+
showInstructions: false,
|
|
109
|
+
message: t(lang, 'ui_fail_q', { name: label }),
|
|
110
|
+
options: [
|
|
111
|
+
{ value: 'retry', label: t(lang, 'ui_retry') },
|
|
112
|
+
{ value: 'save', label: t(lang, 'ui_save_anyway') },
|
|
113
|
+
{ value: 'drop', label: t(lang, 'ui_drop', { name: label }) },
|
|
114
|
+
],
|
|
115
|
+
});
|
|
116
|
+
if (isCancel(next))
|
|
117
|
+
return BACK;
|
|
118
|
+
if (next === 'save') {
|
|
119
|
+
Object.assign(keys, candidate);
|
|
120
|
+
kept.push(p);
|
|
121
|
+
break;
|
|
122
|
+
}
|
|
123
|
+
if (next === 'drop')
|
|
124
|
+
break;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
return { ...s, keys: keys, providers: kept };
|
|
128
|
+
};
|
|
129
|
+
const goalStep = async (s) => {
|
|
130
|
+
const r = await text({ ...io, message: t(lang, 'ui_goal_q'), placeholder: t(lang, 'ui_goal_ph'), initialValue: s.goal });
|
|
131
|
+
return isCancel(r) ? BACK : { ...s, goal: (r ?? '').trim() };
|
|
132
|
+
};
|
|
133
|
+
const langStep = async (s) => {
|
|
134
|
+
const r = await select({
|
|
135
|
+
...io,
|
|
136
|
+
showInstructions: false,
|
|
137
|
+
message: t(lang, 'ui_lang_q'),
|
|
138
|
+
initialValue: s.lang ?? 'auto',
|
|
139
|
+
options: [{ value: 'auto', label: t(lang, 'ui_lang_auto') }, { value: 'zh-TW', label: '繁體中文' }, { value: 'en', label: 'English' }],
|
|
140
|
+
});
|
|
141
|
+
return isCancel(r) ? BACK : { ...s, lang: r === 'auto' ? undefined : r };
|
|
142
|
+
};
|
|
143
|
+
/** Run steps in order; Esc on a step goes back one. Returns BACK if the user backs out of the first step. */
|
|
144
|
+
const walk = async (steps) => {
|
|
145
|
+
let s = state;
|
|
146
|
+
for (let i = 0; i < steps.length;) {
|
|
147
|
+
const r = await steps[i](s);
|
|
148
|
+
if (r === BACK) {
|
|
149
|
+
if (i === 0)
|
|
150
|
+
return BACK;
|
|
151
|
+
i--;
|
|
152
|
+
}
|
|
153
|
+
else {
|
|
154
|
+
s = r;
|
|
155
|
+
i++;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return s;
|
|
159
|
+
};
|
|
160
|
+
intro(t(lang, 'ui_title'), io);
|
|
161
|
+
if (firstRun) {
|
|
162
|
+
log.info(t(lang, 'ui_first_run'), io);
|
|
163
|
+
const r = await walk([agentsStep, providersStep, keysStepFor(initial.providers), goalStep]);
|
|
164
|
+
if (r === BACK) {
|
|
165
|
+
outro(t(lang, 'ui_quit'), io);
|
|
166
|
+
return null;
|
|
167
|
+
}
|
|
168
|
+
state = r;
|
|
169
|
+
}
|
|
170
|
+
for (let first = firstRun;; first = false) {
|
|
171
|
+
const rows = [
|
|
172
|
+
['agents', t(lang, 'ui_m_agents'), state.agents.map((n) => agents[n].label).join(', ') || t(lang, 'doc_none')],
|
|
173
|
+
['providers', t(lang, 'ui_m_providers'), state.providers.map((p, i) => `${i + 1}. ${providers[p].label}`).join(' ') || t(lang, 'doc_none')],
|
|
174
|
+
['keys', t(lang, 'ui_m_keys'), state.providers.map((p) => { const v = providers[p].keys.map((k) => state.keys[k] ?? env[k]).filter(Boolean).pop(); return v ? `${providers[p].label} ${tail(v)}` : ''; }).filter(Boolean).join(' ') || t(lang, 'doc_none')],
|
|
175
|
+
['goal', t(lang, 'ui_m_goal'), state.goal || t(lang, 'ui_unset')],
|
|
176
|
+
['lang', t(lang, 'ui_m_lang'), state.lang ?? t(lang, 'ui_lang_auto')],
|
|
177
|
+
];
|
|
178
|
+
const width = Math.max(...rows.map(([, l]) => displayWidth(l)));
|
|
179
|
+
const choice = await select({
|
|
180
|
+
...io,
|
|
181
|
+
showInstructions: false,
|
|
182
|
+
message: t(lang, 'ui_menu_q'),
|
|
183
|
+
initialValue: first ? 'save' : 'agents',
|
|
184
|
+
options: [
|
|
185
|
+
...rows.map(([value, label, current]) => ({ value, label: `${pad(label, width)} ${dim(current)}` })),
|
|
186
|
+
{ value: 'save', label: t(lang, 'ui_m_save') },
|
|
187
|
+
{ value: 'quit', label: t(lang, 'ui_m_quit') },
|
|
188
|
+
],
|
|
189
|
+
});
|
|
190
|
+
if (isCancel(choice) || choice === 'quit') {
|
|
191
|
+
outro(t(lang, 'ui_quit'), io);
|
|
192
|
+
return null;
|
|
193
|
+
}
|
|
194
|
+
if (choice === 'save') {
|
|
195
|
+
outro(t(lang, 'ui_saved'), io);
|
|
196
|
+
return state;
|
|
197
|
+
}
|
|
198
|
+
const steps = {
|
|
199
|
+
agents: [agentsStep],
|
|
200
|
+
providers: [providersStep, keysStepFor(state.providers)],
|
|
201
|
+
keys: [keysStepFor(null)],
|
|
202
|
+
goal: [goalStep],
|
|
203
|
+
lang: [langStep],
|
|
204
|
+
};
|
|
205
|
+
const r = await walk(steps[choice]);
|
|
206
|
+
if (r !== BACK)
|
|
207
|
+
state = r;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Checkbox list whose marks are numbers: the order you tick items is their priority (failover order).
|
|
212
|
+
* Up/Down move, Space toggles, a digit moves the item under the cursor to that position (ticking it if needed),
|
|
213
|
+
* Enter confirms, Esc goes back.
|
|
214
|
+
*/
|
|
215
|
+
async function orderedMultiselect(lang, io, values, initial) {
|
|
216
|
+
const p = new MultiSelectPrompt({
|
|
217
|
+
...io,
|
|
218
|
+
options: values.map((v) => ({ value: v, label: providers[v].label })),
|
|
219
|
+
initialValues: initial.filter((v) => values.includes(v)),
|
|
220
|
+
required: false,
|
|
221
|
+
render() {
|
|
222
|
+
const head = t(lang, 'ui_providers_q');
|
|
223
|
+
const labelWidth = Math.max(...this.options.map((o) => o.label.length));
|
|
224
|
+
const picked = (this.value ?? []);
|
|
225
|
+
if (this.state === 'submit') {
|
|
226
|
+
const summary = picked.map((v) => providers[v].label).join(' → ') || t(lang, 'doc_none');
|
|
227
|
+
return `${S_STEP_SUBMIT} ${head}\n${S_BAR} ${dim(summary)}\n`;
|
|
228
|
+
}
|
|
229
|
+
if (this.state === 'cancel')
|
|
230
|
+
return `${S_STEP_CANCEL} ${head}\n${S_BAR}\n`;
|
|
231
|
+
const rows = this.options.map((opt, i) => {
|
|
232
|
+
const n = picked.indexOf(opt.value);
|
|
233
|
+
const box = n >= 0 ? `[${n + 1}]` : '[ ]';
|
|
234
|
+
const line = `${box} ${pad(opt.label, labelWidth)} ${dim(t(lang, 'ui_p_' + opt.value))}`;
|
|
235
|
+
return `${S_BAR} ${i === this.cursor ? styleText('cyan', '› ' + line) : ' ' + line}`;
|
|
236
|
+
});
|
|
237
|
+
return [`${S_STEP_ACTIVE} ${head}`, ...rows, `${S_BAR} ${dim(t(lang, 'ui_providers_help'))}`, S_BAR_END, ''].join('\n');
|
|
238
|
+
},
|
|
239
|
+
});
|
|
240
|
+
p.on('key', (char) => {
|
|
241
|
+
const d = Number(char);
|
|
242
|
+
if (!Number.isInteger(d) || d < 1 || d > values.length)
|
|
243
|
+
return;
|
|
244
|
+
const v = p.options[p.cursor].value;
|
|
245
|
+
const rest = (p.value ?? []).filter((x) => x !== v);
|
|
246
|
+
rest.splice(Math.min(d - 1, rest.length), 0, v);
|
|
247
|
+
p.value = rest;
|
|
248
|
+
});
|
|
249
|
+
return p.prompt();
|
|
250
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "your-cto-jev",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "A sharp-tongued CTO gatekeeper for AI coding agents: blocks leaked secrets in git commits and destructive shell commands in Claude Code, Cursor, Gemini CLI and Codex, using TypeSafe Jev.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"claude-code",
|
|
@@ -46,5 +46,9 @@
|
|
|
46
46
|
},
|
|
47
47
|
"publishConfig": {
|
|
48
48
|
"access": "public"
|
|
49
|
+
},
|
|
50
|
+
"dependencies": {
|
|
51
|
+
"@clack/core": "1.5.1",
|
|
52
|
+
"@clack/prompts": "1.8.1"
|
|
49
53
|
}
|
|
50
54
|
}
|
package/dist/wizard.js
DELETED
|
@@ -1,156 +0,0 @@
|
|
|
1
|
-
import { createInterface } from 'node:readline/promises';
|
|
2
|
-
import { agentNames, agents } from './agents.js';
|
|
3
|
-
import { probeProvider, providers } from './api.js';
|
|
4
|
-
import { credentialsPath, loadCredentials, saveCredentials } from './brain.js';
|
|
5
|
-
import { t } from './i18n.js';
|
|
6
|
-
/**
|
|
7
|
-
* Read a line without echoing it (for keys). Public APIs only: raw mode + our own key handling.
|
|
8
|
-
* Enter submits, Backspace deletes, Ctrl+C aborts; escape sequences such as bracketed paste markers are dropped.
|
|
9
|
-
*/
|
|
10
|
-
export function readHidden(q, input = process.stdin, output = process.stdout) {
|
|
11
|
-
return new Promise((resolve, reject) => {
|
|
12
|
-
output.write(q);
|
|
13
|
-
let buf = '';
|
|
14
|
-
const finish = (err) => {
|
|
15
|
-
input.removeListener('data', onData);
|
|
16
|
-
input.setRawMode?.(false);
|
|
17
|
-
input.pause();
|
|
18
|
-
output.write('\n');
|
|
19
|
-
if (err)
|
|
20
|
-
reject(err);
|
|
21
|
-
else
|
|
22
|
-
resolve(buf.trim());
|
|
23
|
-
};
|
|
24
|
-
const onData = (chunk) => {
|
|
25
|
-
const s = String(chunk).replace(/\x1b\[[0-9;]*[~A-Za-z]/g, '');
|
|
26
|
-
for (const ch of s) {
|
|
27
|
-
if (ch === '\r' || ch === '\n')
|
|
28
|
-
return finish();
|
|
29
|
-
if (ch === '\u0003')
|
|
30
|
-
return finish(new Error('aborted'));
|
|
31
|
-
if (ch === '\u007f' || ch === '\b')
|
|
32
|
-
buf = buf.slice(0, -1);
|
|
33
|
-
else if (ch >= ' ')
|
|
34
|
-
buf += ch;
|
|
35
|
-
}
|
|
36
|
-
};
|
|
37
|
-
input.setRawMode?.(true);
|
|
38
|
-
input.setEncoding('utf8');
|
|
39
|
-
input.on('data', onData);
|
|
40
|
-
input.resume();
|
|
41
|
-
});
|
|
42
|
-
}
|
|
43
|
-
/** Terminal prompts. A fresh readline per visible question, so it never fights raw-mode hidden input. */
|
|
44
|
-
export function terminalAsk() {
|
|
45
|
-
const ask = async (q, hidden = false) => {
|
|
46
|
-
if (hidden)
|
|
47
|
-
return readHidden(q);
|
|
48
|
-
const rl = createInterface({ input: process.stdin, output: process.stdout, terminal: true });
|
|
49
|
-
try {
|
|
50
|
-
return (await rl.question(q)).trim();
|
|
51
|
-
}
|
|
52
|
-
finally {
|
|
53
|
-
rl.close();
|
|
54
|
-
}
|
|
55
|
-
};
|
|
56
|
-
return { ask, close: () => process.stdin.pause() };
|
|
57
|
-
}
|
|
58
|
-
const yes = (ans, def) => (ans ? /^y/i.test(ans) : def);
|
|
59
|
-
/** Parse "1,3" or "1 3" into 0-based indexes; null if anything is not a number in range. */
|
|
60
|
-
export function parsePicks(input, n) {
|
|
61
|
-
const idx = input.split(/[\s,]+/).filter(Boolean).map((p) => Number(p) - 1);
|
|
62
|
-
return idx.every((i) => Number.isInteger(i) && i >= 0 && i < n) ? [...new Set(idx)] : null;
|
|
63
|
-
}
|
|
64
|
-
const PROVIDER_OPTIONS = ['openrouter', 'cloudflare'];
|
|
65
|
-
/**
|
|
66
|
-
* Interactive setup in two announced steps. Each step shows its full checklist first, so nobody misses an option:
|
|
67
|
-
* 1. Agents: detected ones pre-checked; type numbers to toggle, Enter to confirm.
|
|
68
|
-
* 2. API providers: type numbers to pick, Enter to skip. Keys are asked only for picked providers, then verified.
|
|
69
|
-
* Keys already present in env are kept as-is unless forceKeys.
|
|
70
|
-
*/
|
|
71
|
-
export async function wizard(ask, lang, detected, log, forceKeys = false) {
|
|
72
|
-
log(t(lang, 'wiz_intro'));
|
|
73
|
-
// Step 1: agents checklist
|
|
74
|
-
log(t(lang, 'wiz_step_agents'));
|
|
75
|
-
const picked = new Set(detected);
|
|
76
|
-
for (;;) {
|
|
77
|
-
agentNames.forEach((name, i) => {
|
|
78
|
-
const box = picked.has(name) ? '[x]' : '[ ]';
|
|
79
|
-
const found = detected.includes(name) ? t(lang, 'wiz_found') : '';
|
|
80
|
-
log(` ${box} ${i + 1}. ${agents[name].label}${found}`);
|
|
81
|
-
});
|
|
82
|
-
const ans = await ask(t(lang, 'wiz_agents_hint'));
|
|
83
|
-
if (!ans)
|
|
84
|
-
break;
|
|
85
|
-
const idx = parsePicks(ans, agentNames.length);
|
|
86
|
-
if (!idx) {
|
|
87
|
-
log(t(lang, 'wiz_invalid'));
|
|
88
|
-
continue;
|
|
89
|
-
}
|
|
90
|
-
for (const i of idx) {
|
|
91
|
-
const n = agentNames[i];
|
|
92
|
-
if (picked.has(n))
|
|
93
|
-
picked.delete(n);
|
|
94
|
-
else
|
|
95
|
-
picked.add(n);
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
const chosen = agentNames.filter((n) => picked.has(n));
|
|
99
|
-
// Step 2: API providers checklist
|
|
100
|
-
log(t(lang, 'wiz_step_keys'));
|
|
101
|
-
const env = process.env;
|
|
102
|
-
const hasKey = !!(env.OPENROUTER_API_KEY || (env.CLOUDFLARE_API_TOKEN && env.CLOUDFLARE_ACCOUNT_ID));
|
|
103
|
-
if (hasKey && !forceKeys) {
|
|
104
|
-
log(t(lang, 'wiz_keys_present'));
|
|
105
|
-
return chosen;
|
|
106
|
-
}
|
|
107
|
-
log(t(lang, 'wiz_keys', { path: credentialsPath() }));
|
|
108
|
-
PROVIDER_OPTIONS.forEach((p, i) => log(` ${i + 1}. ${t(lang, 'wiz_provider_' + p)}`));
|
|
109
|
-
let which = null;
|
|
110
|
-
while (!which) {
|
|
111
|
-
const ans = await ask(t(lang, 'wiz_providers_hint'));
|
|
112
|
-
which = ans ? parsePicks(ans, PROVIDER_OPTIONS.length) : [];
|
|
113
|
-
if (!which)
|
|
114
|
-
log(t(lang, 'wiz_invalid'));
|
|
115
|
-
}
|
|
116
|
-
const creds = { ...loadCredentials() };
|
|
117
|
-
const tryKey = async (provider, set) => {
|
|
118
|
-
const saved = { ...env };
|
|
119
|
-
Object.assign(env, set);
|
|
120
|
-
log(t(lang, 'wiz_checking', { name: providers[provider].label }));
|
|
121
|
-
const r = await probeProvider(provider);
|
|
122
|
-
if (r.ok) {
|
|
123
|
-
log(t(lang, 'wiz_ok', { name: providers[provider].label }));
|
|
124
|
-
Object.assign(creds, set);
|
|
125
|
-
return;
|
|
126
|
-
}
|
|
127
|
-
log(t(lang, 'wiz_fail', { name: providers[provider].label, status: r.status, msg: r.message ?? '' }));
|
|
128
|
-
if (yes(await ask(t(lang, 'wiz_save_anyway')), false))
|
|
129
|
-
Object.assign(creds, set);
|
|
130
|
-
else
|
|
131
|
-
for (const k of Object.keys(set)) {
|
|
132
|
-
if (saved[k] === undefined)
|
|
133
|
-
delete env[k];
|
|
134
|
-
else
|
|
135
|
-
env[k] = saved[k];
|
|
136
|
-
}
|
|
137
|
-
};
|
|
138
|
-
for (const i of which) {
|
|
139
|
-
if (PROVIDER_OPTIONS[i] === 'openrouter') {
|
|
140
|
-
const key = await ask(t(lang, 'wiz_or_key'), true);
|
|
141
|
-
if (key)
|
|
142
|
-
await tryKey('openrouter', { OPENROUTER_API_KEY: key });
|
|
143
|
-
}
|
|
144
|
-
else {
|
|
145
|
-
const acc = await ask(t(lang, 'wiz_cf_account'));
|
|
146
|
-
const tok = acc ? await ask(t(lang, 'wiz_cf_token'), true) : '';
|
|
147
|
-
if (acc && tok)
|
|
148
|
-
await tryKey('cloudflare', { CLOUDFLARE_ACCOUNT_ID: acc, CLOUDFLARE_API_TOKEN: tok });
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
if (Object.keys(creds).length)
|
|
152
|
-
log(t(lang, 'wiz_saved', { path: saveCredentials(creds) }));
|
|
153
|
-
else
|
|
154
|
-
log(t(lang, 'wiz_no_keys'));
|
|
155
|
-
return chosen;
|
|
156
|
-
}
|