your-cto-jev 0.2.3 → 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 CHANGED
@@ -77,21 +77,20 @@ 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 it in the terminal:
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 coding agents should get command interception?
84
- Claude Code (detected) [Y/n]
85
- Cursor (detected) [Y/n]
86
- Gemini CLI [y/N]
87
- Codex CLI (detected) [Y/n]
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
 
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
+
95
94
  Then restart your agent session so it picks up the new hooks, and check that everything really works:
96
95
 
97
96
  ```sh
@@ -104,7 +103,6 @@ Other forms:
104
103
 
105
104
  ```sh
106
105
  cto setup --agents claude,cursor --yes # non-interactive (scripts, CI)
107
- cto setup --keys # change keys later
108
106
  cto setup --uninstall # remove every cto hook again
109
107
  cto doctor # is it actually working?
110
108
  ```
@@ -128,14 +126,15 @@ Codex only runs project hooks after you trust the project. Teammates who have no
128
126
 
129
127
  ## API keys
130
128
 
131
- 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:
132
130
 
133
131
  | Provider | Keys | Notes |
134
132
  |---|---|---|
135
133
  | [OpenRouter](https://openrouter.ai) | `OPENROUTER_API_KEY` | Easiest way to start |
136
- | [Cloudflare Workers AI](https://developers.cloudflare.com/ai/models/typesafe/jev/) | `CLOUDFLARE_API_TOKEN`, `CLOUDFLARE_ACCOUNT_ID` | Tried first when set. Your account's default AI Gateway must have **Authenticated Gateway** on and Unified Billing credits, or every call returns `403` |
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 |
137
136
 
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.
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.
139
138
 
140
139
  **Where keys live.** Environment variables win. Otherwise `cto` reads a per-user file that `setup` writes:
141
140
 
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
- /** Ordered provider names honoring CTO_PROVIDER. */
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 order = env.CTO_PROVIDER ? [env.CTO_PROVIDER] : Object.keys(providers);
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
@@ -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(c, null, 2) + '\n', { mode: 0o600 });
96
+ writeFileSync(path, JSON.stringify(data, null, 2) + '\n', { mode: 0o600 });
77
97
  return path;
78
98
  }
79
99
  /**
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 { agentNames, agents } from './agents.js';
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 = KEYS[name].filter((k) => !process.env[k]);
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 = KEYS[name].every((k) => file[k] && file[k] === process.env[k]);
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 = agentNames.filter((n) => {
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/i18n.js CHANGED
@@ -1,4 +1,5 @@
1
- /** CTO_LANG > LC_ALL / LANG > OS locale via Intl (Windows has no LANG) > en. zh-* maps to zh-TW. */
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,26 +64,46 @@ 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
- wiz_save_anyway: () => ' 仍要儲存這組 key 嗎?[y/N] ',
83
- wiz_saved: (v) => `[cto] key 已儲存到 ${v.path}`,
84
- wiz_no_keys: () => '[cto] 沒有設定任何 key,cto 會全部放行,之後可執行 cto setup --keys 補上。',
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: () => '已離開,沒有修改任何設定。',
85
107
  doc_version: (v) => `cto ${v.v}`,
86
108
  doc_keys: () => 'Jev API key(每個都用一次真實請求驗證):',
87
109
  doc_not_set: (v) => `未設定(缺 ${v.keys})`,
@@ -92,7 +114,7 @@ const messages = {
92
114
  doc_fail: (v) => `失敗 (${v.status})`,
93
115
  doc_hint_cf_401: () => 'token 無效或缺少權限:Account > Workers AI > Read',
94
116
  doc_hint_cf_403: () => '到 AI > AI Gateway > default > Settings 開啟 Authenticated Gateway',
95
- doc_hint_401: () => 'key 無效或已撤銷,請重新產生後執行 cto setup --keys',
117
+ doc_hint_401: () => 'key 無效或已撤銷,請重新產生後執行 cto setup',
96
118
  doc_hint_402: () => '額度不足,請到 provider 後台儲值',
97
119
  doc_hint_network: () => '連不上或太慢,檢查網路或稍後再試',
98
120
  doc_hint_other: () => '非預期的回應,請回報到 github.com/rainday/your-cto-jev/issues',
@@ -112,7 +134,7 @@ const messages = {
112
134
  doc_bad: () => '[cto] 有問題需要處理:',
113
135
  update_available: (v) => `[cto] 有新版 ${v.latest}(目前 ${v.current}),執行 cto update 更新`,
114
136
  update_done: () => '[cto] 已更新。已設定過的專案不用重跑 cto setup。',
115
- usage: () => '用法:cto doctor | cto update | cto --version | cto setup [--agents claude,cursor,gemini,codex] [--keys] [--yes] [--uninstall] | cto --hook <git-commit|AGENT-pre|AGENT-post>',
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>',
116
138
  },
117
139
  en: {
118
140
  reason_402: () => 'out of credits',
@@ -146,26 +168,46 @@ const messages = {
146
168
  setup_agent: (v) => `[cto] ${v.label} hooks written to ${v.path}`,
147
169
  uninstall_agent: (v) => `[cto] Removed ${v.label} hooks from ${v.path}`,
148
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.',
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
171
  wiz_checking: (v) => ` Verifying ${v.name} with one real request...`,
164
172
  wiz_ok: (v) => ` ${v.name} OK`,
165
173
  wiz_fail: (v) => ` ${v.name} failed (${v.status}) ${v.msg}`,
166
- wiz_save_anyway: () => ' Save this key anyway? [y/N] ',
167
- wiz_saved: (v) => `[cto] Keys saved to ${v.path}`,
168
- wiz_no_keys: () => '[cto] No key set, so cto lets everything through. Run cto setup --keys later.',
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.',
169
211
  doc_version: (v) => `cto ${v.v}`,
170
212
  doc_keys: () => 'Jev API keys (each verified with one real request):',
171
213
  doc_not_set: (v) => `not set (missing ${v.keys})`,
@@ -176,7 +218,7 @@ const messages = {
176
218
  doc_fail: (v) => `failed (${v.status})`,
177
219
  doc_hint_cf_401: () => 'Token invalid or missing the Account > Workers AI > Read permission',
178
220
  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 --keys',
221
+ doc_hint_401: () => 'Key invalid or revoked. Create a new one and run cto setup',
180
222
  doc_hint_402: () => 'Out of credits. Top up in the provider dashboard',
181
223
  doc_hint_network: () => 'Unreachable or too slow. Check your network or try again later',
182
224
  doc_hint_other: () => 'Unexpected response. Please report it at github.com/rainday/your-cto-jev/issues',
@@ -196,7 +238,7 @@ const messages = {
196
238
  doc_bad: () => '[cto] Needs attention:',
197
239
  update_available: (v) => `[cto] Version ${v.latest} is available (you have ${v.current}). Run cto update`,
198
240
  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] [--keys] [--yes] [--uninstall] | cto --hook <git-commit|AGENT-pre|AGENT-post>',
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>',
200
242
  },
201
243
  };
202
244
  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';
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';
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 '';
@@ -82,25 +82,39 @@ if (args[0] === '--hook' && args[1]) {
82
82
  else if (args[0] === 'setup') {
83
83
  const uninstall = args.includes('--uninstall');
84
84
  let chosen;
85
+ let goal;
86
+ const root = gitRoot(process.cwd());
85
87
  const list = flag('--agents');
86
88
  if (list)
87
89
  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
- const { ask, close } = terminalAsk();
90
- try {
91
- chosen = await wizard(ask, lang, detectAgents(), (s) => console.log(s), args.includes('--keys'));
92
- }
93
- catch {
94
- process.exit(130); // Ctrl+C or closed input: stop quietly, nothing has been written yet
95
- }
96
- finally {
97
- close();
98
- }
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;
99
111
  }
100
112
  else if (!uninstall) {
101
113
  chosen = detectAgents();
102
114
  }
103
115
  const r = setup(process.cwd(), lang, { uninstall, agents: chosen });
116
+ if (!r.code && root && goal !== undefined)
117
+ setSprintGoal(root, goal);
104
118
  const latest = r.code ? undefined : await checkUpdate();
105
119
  if (latest)
106
120
  r.lines.push(t(lang, 'update_available', { latest, current: currentVersion() }));
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
- const targets = opts.uninstall ? agentNames : (opts.agents ?? []);
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
+ }
@@ -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.2.3",
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
- }