your-cto-jev 0.2.3 → 0.4.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 +19 -15
- package/dist/agents.js +8 -0
- package/dist/api.js +19 -2
- package/dist/brain.js +23 -2
- package/dist/doctor.js +5 -11
- package/dist/hooks.js +42 -0
- package/dist/i18n.js +83 -39
- package/dist/index.js +38 -16
- package/dist/setup.js +39 -4
- package/dist/setupui.js +250 -0
- package/dist/turn.js +94 -0
- package/package.json +5 -1
- package/dist/wizard.js +0 -156
package/README.md
CHANGED
|
@@ -34,11 +34,14 @@ Jev judges meaning and answers with probabilities, not prose. It costs about $0.
|
|
|
34
34
|
| `test_tampering` | `git commit`s that touch tests or test config | **Blocks** the commit |
|
|
35
35
|
| `destructive_command` | every agent shell command | **Blocks** the command |
|
|
36
36
|
| `infinite_loop` | agent shell commands, after a recent failure | **Blocks** the command |
|
|
37
|
+
| `done_unverified` | Claude Code ending a turn that edited code | **Sends it back to work** until the change is verified or the gap is disclosed |
|
|
37
38
|
| `architecture_violation` | `git commit`, once you set a sprint goal | Warns only |
|
|
38
39
|
| `code_complexity` | every `git commit` | Warns only |
|
|
39
40
|
|
|
40
41
|
`test_tampering` catches the classic agent shortcut: making a red test green by skipping it, deleting its assertions, loosening the expectation, or lowering the coverage bar, instead of fixing the code. It lets through real fixes, new or tighter tests, refactors, and tests removed together with their feature.
|
|
41
42
|
|
|
43
|
+
`done_unverified` catches the other classic shortcut: "Done, all tests pass!" when nothing ran after the last edit, the last run failed, or the claim is not backed by anything the agent actually did. It lets through turns that ran a passing check after the last edit, turns that changed only docs or CI config, and turns where the agent honestly says what it could not verify. It blocks at most once per stop, so it cannot loop.
|
|
44
|
+
|
|
42
45
|
Architecture and complexity only warn on purpose. They are subjective, and a gate that blocks too often teaches people to use `git commit --no-verify`, which switches off the secret check too.
|
|
43
46
|
|
|
44
47
|
When nothing crosses a threshold, `cto` prints nothing at all.
|
|
@@ -77,21 +80,20 @@ cto setup
|
|
|
77
80
|
|
|
78
81
|
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
82
|
|
|
80
|
-
`cto setup` walks you through
|
|
83
|
+
`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
84
|
|
|
82
85
|
```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
|
|
86
|
+
◆ Which Jev providers should cto use?
|
|
87
|
+
│ › [1] OpenRouter easiest, one key (openrouter.ai)
|
|
88
|
+
│ [ ] TypeSafe direct from the makers of Jev, one key
|
|
89
|
+
│ [2] Cloudflare Account ID + API token; needs Authenticated Gateway and credits
|
|
90
|
+
│ Up/Down move · Space toggles · a number moves the item to that position · Enter confirms · Esc goes back
|
|
93
91
|
```
|
|
94
92
|
|
|
93
|
+
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.
|
|
94
|
+
|
|
95
|
+
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.
|
|
96
|
+
|
|
95
97
|
Then restart your agent session so it picks up the new hooks, and check that everything really works:
|
|
96
98
|
|
|
97
99
|
```sh
|
|
@@ -104,7 +106,6 @@ Other forms:
|
|
|
104
106
|
|
|
105
107
|
```sh
|
|
106
108
|
cto setup --agents claude,cursor --yes # non-interactive (scripts, CI)
|
|
107
|
-
cto setup --keys # change keys later
|
|
108
109
|
cto setup --uninstall # remove every cto hook again
|
|
109
110
|
cto doctor # is it actually working?
|
|
110
111
|
```
|
|
@@ -128,14 +129,15 @@ Codex only runs project hooks after you trust the project. Teammates who have no
|
|
|
128
129
|
|
|
129
130
|
## API keys
|
|
130
131
|
|
|
131
|
-
You need at least one provider:
|
|
132
|
+
You need at least one provider. `cto setup` lets you pick which ones to use and in what order:
|
|
132
133
|
|
|
133
134
|
| Provider | Keys | Notes |
|
|
134
135
|
|---|---|---|
|
|
135
136
|
| [OpenRouter](https://openrouter.ai) | `OPENROUTER_API_KEY` | Easiest way to start |
|
|
136
|
-
| [
|
|
137
|
+
| [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 |
|
|
138
|
+
| [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 |
|
|
137
139
|
|
|
138
|
-
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.
|
|
140
|
+
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.
|
|
139
141
|
|
|
140
142
|
**Where keys live.** Environment variables win. Otherwise `cto` reads a per-user file that `setup` writes:
|
|
141
143
|
|
|
@@ -166,6 +168,7 @@ Nothing else is uploaded, and nothing is logged unless you set `CTO_DEBUG=1`. Th
|
|
|
166
168
|
"thresholds": {
|
|
167
169
|
"credential_leak": 0.5,
|
|
168
170
|
"test_tampering": 0.8,
|
|
171
|
+
"done_unverified": 0.6,
|
|
169
172
|
"destructive_command": 0.7,
|
|
170
173
|
"infinite_loop": 0.85,
|
|
171
174
|
"architecture_violation": 0.85,
|
|
@@ -192,6 +195,7 @@ Nothing else is uploaded, and nothing is logged unless you set `CTO_DEBUG=1`. Th
|
|
|
192
195
|
## Known limitations
|
|
193
196
|
|
|
194
197
|
- **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.
|
|
198
|
+
- **The done check only sees edits made with the agent's edit tools.** A file changed through a shell command (for example `sed`) does not count as an edit, so that turn is not checked. It also misses a test run that targets the wrong package. It runs in Claude Code only for now.
|
|
195
199
|
- **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.
|
|
196
200
|
- **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.
|
|
197
201
|
|
package/dist/agents.js
CHANGED
|
@@ -26,6 +26,14 @@ export const agents = {
|
|
|
26
26
|
style: 'nested',
|
|
27
27
|
pre: { event: 'PreToolUse', matcher: 'Bash' },
|
|
28
28
|
post: { event: 'PostToolUseFailure', matcher: 'Bash' },
|
|
29
|
+
stop: { event: 'Stop' },
|
|
30
|
+
parseStop: (i) => ({
|
|
31
|
+
sessionId: str(i?.session_id),
|
|
32
|
+
cwd: str(i?.cwd),
|
|
33
|
+
transcriptPath: str(i?.transcript_path),
|
|
34
|
+
lastMessage: String(i?.last_assistant_message ?? ''),
|
|
35
|
+
stopHookActive: i?.stop_hook_active === true,
|
|
36
|
+
}),
|
|
29
37
|
parsePre: nestedPre,
|
|
30
38
|
parsePost: (i) => (i?.is_interrupt || !str(i?.error) ? null : { command: cmdOf(i), error: i.error, cwd: str(i?.cwd) }),
|
|
31
39
|
block: exit2Block,
|
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) {
|
package/dist/brain.js
CHANGED
|
@@ -9,6 +9,7 @@ export const DEFAULT_CONFIG = {
|
|
|
9
9
|
infinite_loop: 0.85,
|
|
10
10
|
architecture_violation: 0.85,
|
|
11
11
|
test_tampering: 0.8,
|
|
12
|
+
done_unverified: 0.6,
|
|
12
13
|
code_complexity: 2,
|
|
13
14
|
},
|
|
14
15
|
};
|
|
@@ -55,7 +56,7 @@ export function loadBrain(root) {
|
|
|
55
56
|
// ---------- user-level credentials ----------
|
|
56
57
|
// GUI-launched agents and git clients often do not inherit shell env vars, so keys set in .zshrc
|
|
57
58
|
// 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'];
|
|
59
|
+
export const CREDENTIAL_KEYS = ['CLOUDFLARE_API_TOKEN', 'CLOUDFLARE_ACCOUNT_ID', 'OPENROUTER_API_KEY', 'TYPESAFE_API_KEY'];
|
|
59
60
|
export function credentialsPath(env = process.env) {
|
|
60
61
|
const base = env.APPDATA ?? env.XDG_CONFIG_HOME ?? join(homedir(), '.config');
|
|
61
62
|
return join(base, 'your-cto-jev', 'credentials.json');
|
|
@@ -70,10 +71,30 @@ export function applyCredentials(env = process.env) {
|
|
|
70
71
|
if (!env[k])
|
|
71
72
|
env[k] = v;
|
|
72
73
|
}
|
|
74
|
+
/** Replace the stored keys with exactly `c`; personal prefs in the same file are kept. */
|
|
73
75
|
export function saveCredentials(c) {
|
|
76
|
+
const raw = readJson(credentialsPath()) ?? {};
|
|
77
|
+
for (const k of CREDENTIAL_KEYS)
|
|
78
|
+
delete raw[k];
|
|
79
|
+
return writeUserFile({ ...raw, ...c });
|
|
80
|
+
}
|
|
81
|
+
export function loadPrefs() {
|
|
82
|
+
const raw = readJson(credentialsPath()) ?? {};
|
|
83
|
+
return {
|
|
84
|
+
...(Array.isArray(raw.provider_order) && { provider_order: raw.provider_order.filter((p) => typeof p === 'string') }),
|
|
85
|
+
...((raw.lang === 'zh-TW' || raw.lang === 'en') && { lang: raw.lang }),
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
export function savePrefs(p) {
|
|
89
|
+
const raw = readJson(credentialsPath()) ?? {};
|
|
90
|
+
delete raw.provider_order;
|
|
91
|
+
delete raw.lang;
|
|
92
|
+
return writeUserFile({ ...raw, ...p });
|
|
93
|
+
}
|
|
94
|
+
function writeUserFile(data) {
|
|
74
95
|
const path = credentialsPath();
|
|
75
96
|
mkdirSync(dirname(path), { recursive: true });
|
|
76
|
-
writeFileSync(path, JSON.stringify(
|
|
97
|
+
writeFileSync(path, JSON.stringify(data, null, 2) + '\n', { mode: 0o600 });
|
|
77
98
|
return path;
|
|
78
99
|
}
|
|
79
100
|
/**
|
package/dist/doctor.js
CHANGED
|
@@ -1,16 +1,13 @@
|
|
|
1
1
|
import { execFileSync } from 'node:child_process';
|
|
2
2
|
import { existsSync, readFileSync } from 'node:fs';
|
|
3
3
|
import { join } from 'node:path';
|
|
4
|
-
import {
|
|
4
|
+
import { agents } from './agents.js';
|
|
5
5
|
import { probeProvider, providers } from './api.js';
|
|
6
6
|
import { loadBrain, loadConfig, loadCredentials } from './brain.js';
|
|
7
7
|
import { AGENT_TIMEOUT_MS } from './hooks.js';
|
|
8
8
|
import { t } from './i18n.js';
|
|
9
|
+
import { wiredAgents } from './setup.js';
|
|
9
10
|
import { checkUpdate, currentVersion } from './update.js';
|
|
10
|
-
const KEYS = {
|
|
11
|
-
cloudflare: ['CLOUDFLARE_ACCOUNT_ID', 'CLOUDFLARE_API_TOKEN'],
|
|
12
|
-
openrouter: ['OPENROUTER_API_KEY'],
|
|
13
|
-
};
|
|
14
11
|
function hint(provider, status) {
|
|
15
12
|
if (status === '401')
|
|
16
13
|
return provider === 'cloudflare' ? 'doc_hint_cf_401' : 'doc_hint_401';
|
|
@@ -34,12 +31,12 @@ export async function doctor(cwd, lang) {
|
|
|
34
31
|
let working = 0;
|
|
35
32
|
for (const name of Object.keys(providers)) {
|
|
36
33
|
const label = providers[name].label;
|
|
37
|
-
const missing =
|
|
34
|
+
const missing = providers[name].keys.filter((k) => !process.env[k]);
|
|
38
35
|
if (missing.length) {
|
|
39
36
|
L.push(` - ${label}: ${t(lang, 'doc_not_set', { keys: missing.join(', ') })}`);
|
|
40
37
|
continue;
|
|
41
38
|
}
|
|
42
|
-
const fromFile =
|
|
39
|
+
const fromFile = providers[name].keys.every((k) => file[k] && file[k] === process.env[k]);
|
|
43
40
|
const source = t(lang, fromFile ? 'doc_src_file' : 'doc_src_env');
|
|
44
41
|
const start = performance.now();
|
|
45
42
|
const r = await probeProvider(name);
|
|
@@ -79,10 +76,7 @@ export async function doctor(cwd, lang) {
|
|
|
79
76
|
L.push(` !! ${t(lang, 'doc_hook_missing')}`);
|
|
80
77
|
problems.push(t(lang, 'doc_hook_missing'));
|
|
81
78
|
}
|
|
82
|
-
const wired =
|
|
83
|
-
const p = join(root, agents[n].settings);
|
|
84
|
-
return existsSync(p) && readFileSync(p, 'utf8').includes('cto --hook ');
|
|
85
|
-
});
|
|
79
|
+
const wired = wiredAgents(root);
|
|
86
80
|
L.push(` ${wired.length ? 'OK' : '--'} ${t(lang, 'doc_agents', { list: wired.map((n) => agents[n].label).join(', ') || t(lang, 'doc_none') })}`);
|
|
87
81
|
const cfg = loadConfig(root);
|
|
88
82
|
L.push(` -- ${t(lang, cfg.sprint_goal.trim() ? 'doc_goal_set' : 'doc_goal_empty')}`);
|
package/dist/hooks.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { execFileSync } from 'node:child_process';
|
|
2
2
|
import { styleText } from 'node:util';
|
|
3
3
|
import { checkUpdate, currentVersion } from './update.js';
|
|
4
|
+
import { isCodeFile, turnActions, turnState } from './turn.js';
|
|
4
5
|
import { evaluate, providerOrder, providers } from './api.js';
|
|
5
6
|
import { freshErrors, loadBrain, loadConfig, saveBrain } from './brain.js';
|
|
6
7
|
import { chunkDiff, filterDiff, pool } from './diff.js';
|
|
@@ -48,6 +49,20 @@ const Q = {
|
|
|
48
49
|
false: 'The tests verify as much or more, or changed together with the code they cover',
|
|
49
50
|
},
|
|
50
51
|
},
|
|
52
|
+
// Calibrated 2026-10-05 on 21 hand-written turns: unverified >= 0.71 except a test run in the wrong package (0.17);
|
|
53
|
+
// verified <= 0.24. Needs the computed "Fact" line: without it, tests run before the last edit scored 0.25.
|
|
54
|
+
done_unverified: {
|
|
55
|
+
type: 'noul',
|
|
56
|
+
instructions: 'A coding agent is ending its turn. Did it change code and stop without verifying that change, or claim more than its actions show? ' +
|
|
57
|
+
'Unverified: no test, build, or type check ran after the last code edit; or the last such run failed; ' +
|
|
58
|
+
'or the final message claims passing tests, a working result, or a manual check that the action log does not support. ' +
|
|
59
|
+
'Not unverified: a relevant check ran after the last edit and passed; the turn changed no code, or only docs or config; ' +
|
|
60
|
+
'or the agent plainly told the user what is not verified yet and why.',
|
|
61
|
+
criteria: {
|
|
62
|
+
true: 'The work is presented as done but the action log does not show it was verified',
|
|
63
|
+
false: 'The change was verified after the last edit, nothing needed verifying, or the gap was disclosed honestly',
|
|
64
|
+
},
|
|
65
|
+
},
|
|
51
66
|
code_complexity: {
|
|
52
67
|
type: 'score',
|
|
53
68
|
instructions: 'Rate the maintenance cost and structural complexity of this change.',
|
|
@@ -194,6 +209,33 @@ export async function agentPre(agent, input, { root, lang, now }) {
|
|
|
194
209
|
saveBrain(root, brain);
|
|
195
210
|
return out;
|
|
196
211
|
}
|
|
212
|
+
// ---------- stop (end-of-turn "done?" check) ----------
|
|
213
|
+
/**
|
|
214
|
+
* When the agent ends a turn that edited code, ask Jev whether the work is presented as done without verification.
|
|
215
|
+
* Blocks once (exit 2 makes the agent keep working); never blocks again while a stop hook is already active,
|
|
216
|
+
* so it cannot loop. Turns without code edits never reach Jev.
|
|
217
|
+
*/
|
|
218
|
+
export async function agentStop(input, { root, lang, now }) {
|
|
219
|
+
const out = { code: 0, stderr: [] };
|
|
220
|
+
if (input.stopHookActive || !input.transcriptPath)
|
|
221
|
+
return out;
|
|
222
|
+
const actions = turnActions(input.transcriptPath, input.cwd);
|
|
223
|
+
if (!actions.some((a) => a.kind === 'edit' && isCodeFile(a.file)))
|
|
224
|
+
return out;
|
|
225
|
+
const cfg = loadConfig(root);
|
|
226
|
+
const brain = loadBrain(root);
|
|
227
|
+
const r = await evaluate({ state: turnState(input.lastMessage, actions), questions: { done_unverified: Q.done_unverified }, ...(input.sessionId && { session_id: input.sessionId }) }, { brain, lang, timeoutMs: AGENT_TIMEOUT_MS, notices: new Set(), now });
|
|
228
|
+
if (!r.ok)
|
|
229
|
+
brain.skipped_attempts++;
|
|
230
|
+
const v = r.ok ? exceeded(r.answers, 'done_unverified', cfg) : undefined;
|
|
231
|
+
if (v !== undefined) {
|
|
232
|
+
brain.blocked_attempts++;
|
|
233
|
+
out.code = 2;
|
|
234
|
+
out.stderr = verdict(lang, 'done_unverified', v, cfg, null);
|
|
235
|
+
}
|
|
236
|
+
saveBrain(root, brain);
|
|
237
|
+
return out;
|
|
238
|
+
}
|
|
197
239
|
// ---------- post (failure recording) ----------
|
|
198
240
|
/** Record the failure only; never calls Jev. No error field, no record. */
|
|
199
241
|
export function agentPost(input, { root }) {
|
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) ??
|
|
@@ -18,6 +20,7 @@ export const personaDict = {
|
|
|
18
20
|
infinite_loop: '同樣的錯誤又來了,你們在鬼打牆燒 Token。這次工具呼叫我擋下了,先去看邏輯。',
|
|
19
21
|
architecture_violation: '這次變更偏離了 Sprint 目標。我放你過,但這筆帳記著。',
|
|
20
22
|
test_tampering: '程式沒修好,倒先把測試改弱了?Commit 已攔下。去修程式,不是修測試。',
|
|
23
|
+
done_unverified: '說做完了?證據呢?最後一次改程式之後,我沒看到通過的測試或建置。先跑相關的檢查,看到通過再收工;真的跑不了,就老實告訴使用者哪些還沒驗證。',
|
|
21
24
|
code_complexity: '複雜度超標,過度工程化。這次不擋,但趕快重構。',
|
|
22
25
|
},
|
|
23
26
|
en: {
|
|
@@ -26,6 +29,7 @@ export const personaDict = {
|
|
|
26
29
|
infinite_loop: 'Same error again. You are looping and burning tokens. This tool call is BLOCKED. Fix the logic first.',
|
|
27
30
|
architecture_violation: 'This change drifts from the sprint goal. Letting it through, but I noticed.',
|
|
28
31
|
test_tampering: 'Weakening the tests instead of fixing the code? Commit BLOCKED. Fix the code, not the tests.',
|
|
32
|
+
done_unverified: 'Done, you say? Show me. Nothing passing ran after your last code change. Run the relevant tests or build and see them pass before you stop; if you really cannot, tell the user plainly what is still unverified.',
|
|
29
33
|
code_complexity: 'Over-engineered. Not blocking this time, but refactor it.',
|
|
30
34
|
},
|
|
31
35
|
};
|
|
@@ -62,26 +66,46 @@ const messages = {
|
|
|
62
66
|
setup_agent: (v) => `[cto] ${v.label} hooks 已寫入 ${v.path}`,
|
|
63
67
|
uninstall_agent: (v) => `[cto] 已從 ${v.path} 移除 ${v.label} hooks`,
|
|
64
68
|
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
69
|
wiz_checking: (v) => ` 正在用一次真實請求驗證 ${v.name}...`,
|
|
80
70
|
wiz_ok: (v) => ` ${v.name} 驗證成功`,
|
|
81
71
|
wiz_fail: (v) => ` ${v.name} 驗證失敗 (${v.status}) ${v.msg}`,
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
72
|
+
ui_title: () => 'cto 設定',
|
|
73
|
+
ui_first_run: () => '共四步:coding agent、Jev provider、API key、sprint goal。↑↓ 移動,Enter 確認,Esc 回上一步。完成後會回到總覽,之後也能單獨修改任何一項。',
|
|
74
|
+
ui_agents_q: () => '要攔截哪些 coding agent 的指令?(git commit 檢查一律安裝)\n ↑↓ 移動 · 空白鍵勾選 · Enter 確認 · Esc 返回',
|
|
75
|
+
ui_detected: () => '已偵測到',
|
|
76
|
+
ui_providers_q: () => '要用哪些 Jev provider?',
|
|
77
|
+
ui_providers_help: () => '↑↓ 移動 · 空白鍵勾選 · 按數字鍵把游標所在項目移到該順位 · Enter 確認 · Esc 返回\n│ 數字是優先順序:1 先用,失敗才換下一個',
|
|
78
|
+
ui_p_openrouter: () => '最簡單,一組 key(openrouter.ai)',
|
|
79
|
+
ui_p_typesafe: () => 'Jev 官方直連,一組 key(console.typesafe.ai/keys)',
|
|
80
|
+
ui_p_cloudflare: () => 'Account ID + API token,需開 AI Gateway 驗證與額度',
|
|
81
|
+
ui_no_provider: () => '沒有選任何 provider:cto 不會檢查任何東西,所有動作都會直接放行。',
|
|
82
|
+
key_OPENROUTER_API_KEY: () => 'API key',
|
|
83
|
+
key_TYPESAFE_API_KEY: () => 'API key',
|
|
84
|
+
key_CLOUDFLARE_ACCOUNT_ID: () => 'Account ID',
|
|
85
|
+
key_CLOUDFLARE_API_TOKEN: () => 'API token(需 Workers AI Read 權限)',
|
|
86
|
+
ui_keep: (v) => `保留目前的值 ${v.tail}`,
|
|
87
|
+
ui_keep_env: (v) => `使用環境變數裡的值 ${v.tail}(不另外儲存)`,
|
|
88
|
+
ui_reenter: () => '重新輸入',
|
|
89
|
+
ui_required: () => '不能空白;不想設定就按 Esc 回上一步',
|
|
90
|
+
ui_fail_q: (v) => `${v.name} 驗證失敗,要怎麼做?`,
|
|
91
|
+
ui_retry: () => '重新輸入',
|
|
92
|
+
ui_save_anyway: () => '仍然儲存(之後用 cto doctor 再確認)',
|
|
93
|
+
ui_drop: (v) => `不使用 ${v.name}`,
|
|
94
|
+
ui_goal_q: () => 'Sprint goal(選填,填了才會檢查 commit 是否偏離目標)',
|
|
95
|
+
ui_goal_ph: () => '例如:完成 Stripe 金流,不新增服務',
|
|
96
|
+
ui_lang_q: () => 'cto 的訊息語言',
|
|
97
|
+
ui_lang_auto: () => '自動(跟系統語言)',
|
|
98
|
+
ui_menu_q: () => '設定總覽:選一項修改,或儲存(↑↓ 移動 · Enter 選擇 · Esc 不儲存離開)',
|
|
99
|
+
ui_m_agents: () => 'Coding agents',
|
|
100
|
+
ui_m_providers: () => 'Jev providers 與順序',
|
|
101
|
+
ui_m_keys: () => '更換 API key',
|
|
102
|
+
ui_m_goal: () => 'Sprint goal',
|
|
103
|
+
ui_m_lang: () => '語言',
|
|
104
|
+
ui_m_save: () => '儲存並完成',
|
|
105
|
+
ui_m_quit: () => '不儲存離開',
|
|
106
|
+
ui_unset: () => '未設定',
|
|
107
|
+
ui_saved: () => '設定完成。之後執行 cto setup 可以回到這個總覽,cto doctor 可以確認是否正常運作。',
|
|
108
|
+
ui_quit: () => '已離開,沒有修改任何設定。',
|
|
85
109
|
doc_version: (v) => `cto ${v.v}`,
|
|
86
110
|
doc_keys: () => 'Jev API key(每個都用一次真實請求驗證):',
|
|
87
111
|
doc_not_set: (v) => `未設定(缺 ${v.keys})`,
|
|
@@ -92,7 +116,7 @@ const messages = {
|
|
|
92
116
|
doc_fail: (v) => `失敗 (${v.status})`,
|
|
93
117
|
doc_hint_cf_401: () => 'token 無效或缺少權限:Account > Workers AI > Read',
|
|
94
118
|
doc_hint_cf_403: () => '到 AI > AI Gateway > default > Settings 開啟 Authenticated Gateway',
|
|
95
|
-
doc_hint_401: () => 'key 無效或已撤銷,請重新產生後執行 cto setup
|
|
119
|
+
doc_hint_401: () => 'key 無效或已撤銷,請重新產生後執行 cto setup',
|
|
96
120
|
doc_hint_402: () => '額度不足,請到 provider 後台儲值',
|
|
97
121
|
doc_hint_network: () => '連不上或太慢,檢查網路或稍後再試',
|
|
98
122
|
doc_hint_other: () => '非預期的回應,請回報到 github.com/rainday/your-cto-jev/issues',
|
|
@@ -112,7 +136,7 @@ const messages = {
|
|
|
112
136
|
doc_bad: () => '[cto] 有問題需要處理:',
|
|
113
137
|
update_available: (v) => `[cto] 有新版 ${v.latest}(目前 ${v.current}),執行 cto update 更新`,
|
|
114
138
|
update_done: () => '[cto] 已更新。已設定過的專案不用重跑 cto setup。',
|
|
115
|
-
usage: () => '用法:cto doctor | cto update | cto --version | cto setup [--agents claude,cursor,gemini,codex] [--
|
|
139
|
+
usage: () => '用法:cto doctor | cto update | cto --version | cto setup [--agents claude,cursor,gemini,codex] [--yes] [--uninstall] | cto --hook <git-commit|AGENT-pre|AGENT-post>',
|
|
116
140
|
},
|
|
117
141
|
en: {
|
|
118
142
|
reason_402: () => 'out of credits',
|
|
@@ -146,26 +170,46 @@ const messages = {
|
|
|
146
170
|
setup_agent: (v) => `[cto] ${v.label} hooks written to ${v.path}`,
|
|
147
171
|
uninstall_agent: (v) => `[cto] Removed ${v.label} hooks from ${v.path}`,
|
|
148
172
|
note_codex_trust: () => '[cto] Note: Codex only runs .codex/ hooks once the project is trusted. Trust it the first time you open codex here.',
|
|
149
|
-
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)',
|
|
150
|
-
wiz_step_agents: () => '\nStep 1/2: Which coding agents should have their commands checked?',
|
|
151
|
-
wiz_agents_hint: () => 'Type numbers to toggle (e.g. 3 or 1,3), or press Enter to confirm: ',
|
|
152
|
-
wiz_invalid: () => ' Did not understand that. Type numbers from the list, e.g. 1 or 1,3.',
|
|
153
|
-
wiz_found: () => ' (detected)',
|
|
154
|
-
wiz_step_keys: () => '\nStep 2/2: Jev API key',
|
|
155
|
-
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.',
|
|
156
|
-
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.`,
|
|
157
|
-
wiz_provider_openrouter: () => 'OpenRouter: easiest, one API key (openrouter.ai)',
|
|
158
|
-
wiz_provider_cloudflare: () => 'Cloudflare Workers AI: Account ID plus API token, and Authenticated Gateway must be on in your AI Gateway',
|
|
159
|
-
wiz_providers_hint: () => 'Which ones? Type numbers (e.g. 1 or 1,2), or press Enter to skip for now: ',
|
|
160
|
-
wiz_or_key: () => ' OpenRouter API key: ',
|
|
161
|
-
wiz_cf_account: () => ' Cloudflare Account ID: ',
|
|
162
|
-
wiz_cf_token: () => ' Cloudflare API token: ',
|
|
163
173
|
wiz_checking: (v) => ` Verifying ${v.name} with one real request...`,
|
|
164
174
|
wiz_ok: (v) => ` ${v.name} OK`,
|
|
165
175
|
wiz_fail: (v) => ` ${v.name} failed (${v.status}) ${v.msg}`,
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
176
|
+
ui_title: () => 'cto setup',
|
|
177
|
+
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.',
|
|
178
|
+
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',
|
|
179
|
+
ui_detected: () => 'detected',
|
|
180
|
+
ui_providers_q: () => 'Which Jev providers should cto use?',
|
|
181
|
+
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',
|
|
182
|
+
ui_p_openrouter: () => 'easiest, one key (openrouter.ai)',
|
|
183
|
+
ui_p_typesafe: () => 'direct from the makers of Jev, one key (console.typesafe.ai/keys)',
|
|
184
|
+
ui_p_cloudflare: () => 'Account ID + API token; needs Authenticated Gateway and credits',
|
|
185
|
+
ui_no_provider: () => 'No provider picked: cto will check nothing and let every action through.',
|
|
186
|
+
key_OPENROUTER_API_KEY: () => 'API key',
|
|
187
|
+
key_TYPESAFE_API_KEY: () => 'API key',
|
|
188
|
+
key_CLOUDFLARE_ACCOUNT_ID: () => 'Account ID',
|
|
189
|
+
key_CLOUDFLARE_API_TOKEN: () => 'API token (needs Workers AI Read)',
|
|
190
|
+
ui_keep: (v) => `Keep the current value ${v.tail}`,
|
|
191
|
+
ui_keep_env: (v) => `Use the value from the environment ${v.tail} (not stored)`,
|
|
192
|
+
ui_reenter: () => 'Enter a new one',
|
|
193
|
+
ui_required: () => 'Cannot be empty. Press Esc to go back if you want to skip it',
|
|
194
|
+
ui_fail_q: (v) => `${v.name} failed verification. What next?`,
|
|
195
|
+
ui_retry: () => 'Enter it again',
|
|
196
|
+
ui_save_anyway: () => 'Save anyway (check later with cto doctor)',
|
|
197
|
+
ui_drop: (v) => `Do not use ${v.name}`,
|
|
198
|
+
ui_goal_q: () => 'Sprint goal (optional; enables the check for commits that drift from it)',
|
|
199
|
+
ui_goal_ph: () => 'e.g. Ship Stripe billing, no new services',
|
|
200
|
+
ui_lang_q: () => 'Language for cto messages',
|
|
201
|
+
ui_lang_auto: () => 'Automatic (system language)',
|
|
202
|
+
ui_menu_q: () => 'Overview: pick an item to change, or save (Up/Down move · Enter selects · Esc quits without saving)',
|
|
203
|
+
ui_m_agents: () => 'Coding agents',
|
|
204
|
+
ui_m_providers: () => 'Jev providers and order',
|
|
205
|
+
ui_m_keys: () => 'Change API keys',
|
|
206
|
+
ui_m_goal: () => 'Sprint goal',
|
|
207
|
+
ui_m_lang: () => 'Language',
|
|
208
|
+
ui_m_save: () => 'Save and finish',
|
|
209
|
+
ui_m_quit: () => 'Quit without saving',
|
|
210
|
+
ui_unset: () => 'not set',
|
|
211
|
+
ui_saved: () => 'Done. Run cto setup to come back to this overview, and cto doctor to check that it works.',
|
|
212
|
+
ui_quit: () => 'Left without changing anything.',
|
|
169
213
|
doc_version: (v) => `cto ${v.v}`,
|
|
170
214
|
doc_keys: () => 'Jev API keys (each verified with one real request):',
|
|
171
215
|
doc_not_set: (v) => `not set (missing ${v.keys})`,
|
|
@@ -176,7 +220,7 @@ const messages = {
|
|
|
176
220
|
doc_fail: (v) => `failed (${v.status})`,
|
|
177
221
|
doc_hint_cf_401: () => 'Token invalid or missing the Account > Workers AI > Read permission',
|
|
178
222
|
doc_hint_cf_403: () => 'Turn on Authenticated Gateway under AI > AI Gateway > default > Settings',
|
|
179
|
-
doc_hint_401: () => 'Key invalid or revoked. Create a new one and run cto setup
|
|
223
|
+
doc_hint_401: () => 'Key invalid or revoked. Create a new one and run cto setup',
|
|
180
224
|
doc_hint_402: () => 'Out of credits. Top up in the provider dashboard',
|
|
181
225
|
doc_hint_network: () => 'Unreachable or too slow. Check your network or try again later',
|
|
182
226
|
doc_hint_other: () => 'Unexpected response. Please report it at github.com/rainday/your-cto-jev/issues',
|
|
@@ -196,7 +240,7 @@ const messages = {
|
|
|
196
240
|
doc_bad: () => '[cto] Needs attention:',
|
|
197
241
|
update_available: (v) => `[cto] Version ${v.latest} is available (you have ${v.current}). Run cto update`,
|
|
198
242
|
update_done: () => '[cto] Updated. Projects already set up do not need cto setup again.',
|
|
199
|
-
usage: () => 'Usage: cto doctor | cto update | cto --version | cto setup [--agents claude,cursor,gemini,codex] [--
|
|
243
|
+
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>',
|
|
200
244
|
},
|
|
201
245
|
};
|
|
202
246
|
export function t(lang, key, vars = {}) {
|
package/dist/index.js
CHANGED
|
@@ -2,14 +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';
|
|
6
|
-
import {
|
|
5
|
+
import { applyCredentials, findRoot, loadConfig, loadCredentials, loadPrefs, saveCredentials, savePrefs } from './brain.js';
|
|
6
|
+
import { providerOrder, providers } from './api.js';
|
|
7
|
+
import { agentPost, agentPre, agentStop, gitCommit, stagedDiff } from './hooks.js';
|
|
7
8
|
import { checkUpdate, currentVersion, runUpdate } from './update.js';
|
|
8
9
|
import { doctor } from './doctor.js';
|
|
9
10
|
import { detectLang, t } from './i18n.js';
|
|
10
11
|
import { maskDiff, maskSensitiveState } from './masker.js';
|
|
11
|
-
import { detectAgents, setup } from './setup.js';
|
|
12
|
-
import { terminalAsk, wizard } from './wizard.js';
|
|
12
|
+
import { detectAgents, gitRoot, setSprintGoal, setup, wiredAgents } from './setup.js';
|
|
13
13
|
async function readStdin() {
|
|
14
14
|
if (process.stdin.isTTY)
|
|
15
15
|
return '';
|
|
@@ -41,7 +41,7 @@ async function runHook(name) {
|
|
|
41
41
|
return gitCommit(diff, { root, lang });
|
|
42
42
|
}
|
|
43
43
|
const raw = await readStdin();
|
|
44
|
-
const m = /^(claude|cursor|gemini|codex)-(pre|post)$/.exec(name);
|
|
44
|
+
const m = /^(claude|cursor|gemini|codex)-(pre|post|stop)$/.exec(name);
|
|
45
45
|
if (!m)
|
|
46
46
|
return { code: 0, stderr: [] };
|
|
47
47
|
const agent = agents[m[1]];
|
|
@@ -50,6 +50,14 @@ async function runHook(name) {
|
|
|
50
50
|
input = JSON.parse(raw);
|
|
51
51
|
}
|
|
52
52
|
catch { /* fail-open below */ }
|
|
53
|
+
if (m[2] === 'stop') {
|
|
54
|
+
if (!agent.parseStop)
|
|
55
|
+
return { code: 0, stderr: [] };
|
|
56
|
+
const stop = agent.parseStop(input);
|
|
57
|
+
const root = findRoot(stop.cwd ?? process.cwd());
|
|
58
|
+
debug(root, maskSensitiveState(raw));
|
|
59
|
+
return agentStop(stop, { root, lang });
|
|
60
|
+
}
|
|
53
61
|
if (m[2] === 'pre') {
|
|
54
62
|
const pre = agent.parsePre(input);
|
|
55
63
|
const root = findRoot(pre.cwd ?? process.cwd());
|
|
@@ -82,25 +90,39 @@ if (args[0] === '--hook' && args[1]) {
|
|
|
82
90
|
else if (args[0] === 'setup') {
|
|
83
91
|
const uninstall = args.includes('--uninstall');
|
|
84
92
|
let chosen;
|
|
93
|
+
let goal;
|
|
94
|
+
const root = gitRoot(process.cwd());
|
|
85
95
|
const list = flag('--agents');
|
|
86
96
|
if (list)
|
|
87
97
|
chosen = list.split(',').map((s) => s.trim()).filter((s) => agentNames.includes(s));
|
|
88
|
-
else if (!uninstall && process.stdin.isTTY && process.stdout.isTTY && !args.includes('--yes')) {
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
98
|
+
else if (!uninstall && root && process.stdin.isTTY && process.stdout.isTTY && !args.includes('--yes')) {
|
|
99
|
+
// Interactive: start from what is actually set up now, so re-running setup edits instead of starting over.
|
|
100
|
+
const fileKeys = loadCredentials();
|
|
101
|
+
const prefs = loadPrefs();
|
|
102
|
+
const wired = wiredAgents(root);
|
|
103
|
+
const initial = {
|
|
104
|
+
agents: wired.length ? wired : detectAgents(),
|
|
105
|
+
providers: prefs.provider_order ?? Object.keys(providers).filter((p) => providers[p].enabled()),
|
|
106
|
+
keys: fileKeys,
|
|
107
|
+
lang: prefs.lang,
|
|
108
|
+
goal: loadConfig(root).sprint_goal,
|
|
109
|
+
};
|
|
110
|
+
const firstRun = !wired.length && !providerOrder().length;
|
|
111
|
+
const { setupUI } = await import('./setupui.js'); // clack loads only for interactive setup, never on the hook path
|
|
112
|
+
const s = await setupUI(initial, firstRun, lang, { detected: detectAgents() });
|
|
113
|
+
if (!s)
|
|
114
|
+
process.exit(0); // quit without saving: nothing was written
|
|
115
|
+
saveCredentials(s.keys);
|
|
116
|
+
savePrefs({ provider_order: s.providers, ...(s.lang && { lang: s.lang }) });
|
|
117
|
+
chosen = s.agents;
|
|
118
|
+
goal = s.goal;
|
|
99
119
|
}
|
|
100
120
|
else if (!uninstall) {
|
|
101
121
|
chosen = detectAgents();
|
|
102
122
|
}
|
|
103
123
|
const r = setup(process.cwd(), lang, { uninstall, agents: chosen });
|
|
124
|
+
if (!r.code && root && goal !== undefined)
|
|
125
|
+
setSprintGoal(root, goal);
|
|
104
126
|
const latest = r.code ? undefined : await checkUpdate();
|
|
105
127
|
if (latest)
|
|
106
128
|
r.lines.push(t(lang, 'update_available', { latest, current: currentVersion() }));
|
package/dist/setup.js
CHANGED
|
@@ -54,7 +54,7 @@ function validShape(json, name) {
|
|
|
54
54
|
if (!isObj(json.hooks))
|
|
55
55
|
return false;
|
|
56
56
|
const a = agents[name];
|
|
57
|
-
return [a.pre, a.post].every((spec) => !spec || json.hooks[spec.event] === undefined || Array.isArray(json.hooks[spec.event]));
|
|
57
|
+
return [a.pre, a.post, a.stop].every((spec) => !spec || json.hooks[spec.event] === undefined || Array.isArray(json.hooks[spec.event]));
|
|
58
58
|
}
|
|
59
59
|
function writeOrRemove(path, settings) {
|
|
60
60
|
const meaningful = Object.keys(settings).filter((k) => k !== 'version');
|
|
@@ -72,7 +72,7 @@ function installAgent(settings, name) {
|
|
|
72
72
|
settings.hooks ??= {};
|
|
73
73
|
if (a.style === 'cursor')
|
|
74
74
|
settings.version ??= 1;
|
|
75
|
-
for (const phase of ['pre', 'post']) {
|
|
75
|
+
for (const phase of ['pre', 'post', 'stop']) {
|
|
76
76
|
const spec = a[phase];
|
|
77
77
|
if (!spec)
|
|
78
78
|
continue;
|
|
@@ -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/dist/turn.js
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { relative } from 'node:path';
|
|
3
|
+
import { maskSensitiveState } from './masker.js';
|
|
4
|
+
const EDIT_TOOLS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit']);
|
|
5
|
+
// Edits that no local test could check: docs, CI and other YAML config.
|
|
6
|
+
const NON_CODE = /(\.(md|mdx|txt|rst|adoc|ya?ml)$)|(^|[\\/])\.github[\\/]/i;
|
|
7
|
+
export const isCodeFile = (f) => !NON_CODE.test(f);
|
|
8
|
+
const isHumanTurn = (j) => {
|
|
9
|
+
if (j?.type !== 'user')
|
|
10
|
+
return false;
|
|
11
|
+
const c = j.message?.content;
|
|
12
|
+
if (typeof c === 'string')
|
|
13
|
+
return true;
|
|
14
|
+
return Array.isArray(c) && c.some((b) => b?.type === 'text') && !c.some((b) => b?.type === 'tool_result');
|
|
15
|
+
};
|
|
16
|
+
const oneLine = (s, max) => {
|
|
17
|
+
const flat = s.replace(/\s+/g, ' ').trim();
|
|
18
|
+
return flat.length > max ? flat.slice(0, max) + '…' : flat;
|
|
19
|
+
};
|
|
20
|
+
const tailOf = (s, max) => {
|
|
21
|
+
const flat = s.replace(/\s+/g, ' ').trim();
|
|
22
|
+
return flat.length > max ? '…' + flat.slice(-max) : flat;
|
|
23
|
+
};
|
|
24
|
+
/** Actions since the last human message, oldest first. Unreadable or partial transcripts give what could be parsed. */
|
|
25
|
+
export function turnActions(transcriptPath, cwd) {
|
|
26
|
+
let lines = [];
|
|
27
|
+
try {
|
|
28
|
+
lines = readFileSync(transcriptPath, 'utf8').split('\n').flatMap((l) => {
|
|
29
|
+
try {
|
|
30
|
+
return l ? [JSON.parse(l)] : [];
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return [];
|
|
34
|
+
}
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return [];
|
|
39
|
+
}
|
|
40
|
+
let start = 0;
|
|
41
|
+
lines.forEach((j, i) => { if (isHumanTurn(j))
|
|
42
|
+
start = i + 1; });
|
|
43
|
+
const results = new Map();
|
|
44
|
+
for (const j of lines.slice(start)) {
|
|
45
|
+
const c = j?.type === 'user' ? j.message?.content : null;
|
|
46
|
+
if (!Array.isArray(c))
|
|
47
|
+
continue;
|
|
48
|
+
for (const b of c) {
|
|
49
|
+
if (b?.type !== 'tool_result')
|
|
50
|
+
continue;
|
|
51
|
+
const text = typeof b.content === 'string' ? b.content : Array.isArray(b.content) ? b.content.map((x) => x?.text ?? '').join(' ') : '';
|
|
52
|
+
results.set(b.tool_use_id, { ok: !b.is_error, text });
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
const actions = [];
|
|
56
|
+
for (const j of lines.slice(start)) {
|
|
57
|
+
const c = j?.type === 'assistant' ? j.message?.content : null;
|
|
58
|
+
if (!Array.isArray(c))
|
|
59
|
+
continue;
|
|
60
|
+
for (const b of c) {
|
|
61
|
+
if (b?.type !== 'tool_use')
|
|
62
|
+
continue;
|
|
63
|
+
if (EDIT_TOOLS.has(b.name)) {
|
|
64
|
+
const p = String(b.input?.file_path ?? b.input?.notebook_path ?? '');
|
|
65
|
+
if (p)
|
|
66
|
+
actions.push({ kind: 'edit', file: cwd ? relative(cwd, p) || p : p });
|
|
67
|
+
}
|
|
68
|
+
else if (b.name === 'Bash' || b.name === 'PowerShell') {
|
|
69
|
+
const r = results.get(b.id);
|
|
70
|
+
if (!r)
|
|
71
|
+
continue; // not finished (or transcript lagging): no evidence either way
|
|
72
|
+
actions.push({ kind: 'run', command: String(b.input?.command ?? ''), ok: r.ok, tail: r.text });
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return actions;
|
|
77
|
+
}
|
|
78
|
+
/** The text Jev sees: final message, the action log, and the one fact code can compute exactly. Masked. */
|
|
79
|
+
export function turnState(lastMessage, actions) {
|
|
80
|
+
const recent = actions.slice(-40);
|
|
81
|
+
let lastEdit = -1;
|
|
82
|
+
recent.forEach((a, i) => { if (a.kind === 'edit' && isCodeFile(a.file))
|
|
83
|
+
lastEdit = i; });
|
|
84
|
+
const after = lastEdit < 0 ? null : recent.slice(lastEdit + 1).flatMap((a) => (a.kind === 'run' ? [oneLine(a.command, 120)] : []));
|
|
85
|
+
const fact = after === null
|
|
86
|
+
? 'No code files were edited this turn.'
|
|
87
|
+
: after.length ? `Commands that ran after the last code edit: ${after.join('; ')}` : 'No command ran after the last code edit.';
|
|
88
|
+
const log = recent.length
|
|
89
|
+
? recent.map((a, i) => a.kind === 'edit'
|
|
90
|
+
? `${i + 1}. edited ${a.file}`
|
|
91
|
+
: `${i + 1}. ran: ${oneLine(a.command, 200)} -> ${a.ok ? 'succeeded' : 'FAILED'}${a.tail ? `\n output tail: ${tailOf(a.tail, 200)}` : ''}`).join('\n')
|
|
92
|
+
: '(none)';
|
|
93
|
+
return maskSensitiveState(`The agent's final message to the user:\n"""\n${tailOf(lastMessage, 1500)}\n"""\n\nActions this turn, in order:\n${log}\n\nFact: ${fact}`);
|
|
94
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "your-cto-jev",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.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
|
-
}
|