@ai-launchpad-v1/expert-code 0.1.1 → 0.2.1

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.
Files changed (3) hide show
  1. package/README.md +38 -4
  2. package/dist/index.js +755 -66
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -67,14 +67,38 @@ expert --manual # approve every write/edit/command (default: auto)
67
67
  Type a task at the `›` prompt in plain English — the agent explores, edits, and runs
68
68
  commands, showing diffs and live output.
69
69
 
70
+ At the prompt:
71
+
72
+ - **↑ / ↓** — recall your previous tasks.
73
+ - **Tab** — complete a `/command`, or (at an empty prompt) accept the agent's suggested
74
+ next step, shown as a dim `next:` hint after a task finishes.
75
+ - **`@path`** — attach a file to the task, e.g. `explain @src/auth.ts and compare the
76
+ layout to @design/home.png`. Images and PDFs are read natively; text files are
77
+ inlined. A mention that isn't a real file is left as plain text.
78
+
79
+ In-session commands:
80
+
70
81
  - **`/init`** — have it generate an `EXPERT.md` (project orientation it auto-loads on
71
82
  every future task). Run once per project.
83
+ - **`/model [provider] [model]`** — show or switch the BYOK provider/model without
84
+ restarting; **`/login`** / **`/logout`** — switch to or from the managed lane.
85
+ - **`/diff`** — review the file changes applied this task; **`/revert`** — undo the most
86
+ recent one (restores the file, or deletes it if the change created it).
87
+ - **`/compact`** — summarize the conversation into a compact briefing to shrink the
88
+ context (the task continues; applied changes are kept). Optionally focus it:
89
+ `/compact keep the auth refactor details`.
90
+ - **`/clear`** — start a fresh task and clear the screen.
91
+ - **`/status`** — workspace, model, autonomy, change count, and token usage.
72
92
  - **Approvals** (`auto` mode, the default): reads and file edits apply automatically;
73
93
  risky/unknown commands pause — press `y` (run), `n` (skip), `a` (always allow this
74
94
  exact command this session), or type a note to reject with guidance.
75
95
  - **`--manual`** / `/manual` — approve *every* write, edit, and command.
76
96
  - **Ctrl-C** once — stop the current task and return to the prompt.
77
- - Other commands: `/auto`, `/clear` (fresh conversation), `/help`, `/exit`.
97
+ - Also: `/auto`, `/help`, `/exit`.
98
+
99
+ Token usage (estimated) is shown after each task — `~N task · ~N session` — and in the
100
+ prompt frame and `/status`. It's a ~4-chars-per-token estimate across both lanes, for
101
+ gauging context size and cost, not exact billing.
78
102
 
79
103
  ## Commands
80
104
 
@@ -84,9 +108,19 @@ commands, showing diffs and live output.
84
108
  | `expert setup` | Configure BYOK (your own provider key) |
85
109
  | `expert login` / `expert logout` | Managed sign-in / sign-out |
86
110
  | `expert whoami` | Show sign-in and active inference lane |
87
- | `expert config [set <k> <v>]` | Show or edit config (`apiBase`, `provider`) |
111
+ | `expert config [set <k> <v>]` | Show or edit config (`apiBase`, `provider`, `autoUpdate`) |
112
+ | `expert update` | Update to the latest version now |
88
113
  | `expert --version` / `--help` | Version / help |
89
114
 
115
+ ## Staying up to date
116
+
117
+ Expert Code updates itself. On startup it checks the npm registry (at most once a
118
+ day) and, when a newer version is published, installs it in the background so the
119
+ **next** time you run `expert` you're on the latest — no manual `npm i -g`. Force an
120
+ update any time with `expert update`, or turn the automatic check off with
121
+ `expert config set autoUpdate false` (also honoured: `EXPERT_NO_UPDATE`,
122
+ `NO_UPDATE_NOTIFIER`, and `CI`).
123
+
90
124
  ## Safety
91
125
 
92
126
  Every file operation is confined to the workspace root — checked lexically and after
@@ -102,5 +136,5 @@ be overridden with `EXPERT_SUPABASE_URL` / `EXPERT_SUPABASE_ANON_KEY`.
102
136
 
103
137
  ## Not yet included
104
138
 
105
- Session persistence/resume, MCP tools, "get a human code review", and chat
106
- attachments (all present in the ExpertAI desktop app).
139
+ Session persistence/resume, MCP tools, and "get a human code review" (all present in
140
+ the ExpertAI desktop app).
package/dist/index.js CHANGED
@@ -1342,6 +1342,13 @@ async function writeFile(relPath, content) {
1342
1342
  await mkdir(dirname(file), { recursive: true });
1343
1343
  await fsWriteFile(file, content, "utf8");
1344
1344
  }
1345
+ async function deleteFile(relPath) {
1346
+ const file = resolveInRoot(relPath, { write: true });
1347
+ const info = await stat(file).catch(() => null);
1348
+ if (!info) return;
1349
+ if (!info.isFile()) throw new Error("Not a file");
1350
+ await unlink(file);
1351
+ }
1345
1352
  function countOccurrences(haystack, needle) {
1346
1353
  if (!needle) return 0;
1347
1354
  let n = 0;
@@ -1728,7 +1735,7 @@ async function login(ask) {
1728
1735
  options: { shouldCreateUser: true }
1729
1736
  });
1730
1737
  if (otpErr) throw new Error(otpErr.message);
1731
- const code = (await ask(" Enter the 6-digit code we emailed you: ")).trim();
1738
+ const code = (await ask(" Enter the code we emailed you: ")).trim();
1732
1739
  if (!code) throw new Error("No code entered.");
1733
1740
  const { data, error } = await sb.auth.verifyOtp({ email, token: code, type: "email" });
1734
1741
  if (error) throw new Error(error.message);
@@ -1943,6 +1950,35 @@ function touchedPath(t) {
1943
1950
  return null;
1944
1951
  }
1945
1952
 
1953
+ // tokens.ts
1954
+ init_esm_shims();
1955
+ var CHARS_PER_TOKEN = 4;
1956
+ var MEDIA_TOKENS = 1500;
1957
+ function estimateTokens(s) {
1958
+ return Math.ceil(s.length / CHARS_PER_TOKEN);
1959
+ }
1960
+ function estimateMessagesTokens(messages) {
1961
+ let total = 0;
1962
+ for (const m of messages) {
1963
+ if (typeof m.content === "string") {
1964
+ total += estimateTokens(m.content);
1965
+ continue;
1966
+ }
1967
+ for (const b of m.content) {
1968
+ if (b.type === "text") total += estimateTokens(b.text);
1969
+ else if (b.type === "tool_use") total += estimateTokens(JSON.stringify(b.input ?? ""));
1970
+ else if (b.type === "tool_result") total += estimateTokens(b.content);
1971
+ else if (b.type === "image" || b.type === "document") total += MEDIA_TOKENS;
1972
+ }
1973
+ }
1974
+ return total;
1975
+ }
1976
+ function humanizeTokens(n) {
1977
+ if (n < 1e3) return `${n}`;
1978
+ if (n < 1e6) return `${(n / 1e3).toFixed(n < 1e4 ? 1 : 0)}k`;
1979
+ return `${(n / 1e6).toFixed(1)}M`;
1980
+ }
1981
+
1946
1982
  // ../apps/desktop/src/lib/approval.ts
1947
1983
  init_esm_shims();
1948
1984
  var RISKY_COMMAND = /(\brm\b|\brmdir\b|\bdel\b|\brd\b|remove-item|\bmv\b|\bdd\b|\bmkfs\b|\bchmod\b|\bchown\b|\bsudo\b|\bshutdown\b|\breboot\b|:\(\)\s*\{|git\s+reset\s+--hard|git\s+clean|git\s+checkout\s+--|git\s+push|--force|force-with-lease|\bnpm\s+(i|install|ci|publish)\b|\byarn\s+(add|install)\b|\bpnpm\s+(add|install|i)\b|\bpip\s+install|\bpoetry\s+add|\bgem\s+install|\bcargo\s+add|\bgo\s+get\b|\bbrew\s+install|\bapt(-get)?\b|\bnpx\b|\bcurl\b|\bwget\b|\bssh\b|\bscp\b|\btelnet\b|\bnc\b|\bvercel\b|\bdeploy\b|\btee\b)/i;
@@ -1997,14 +2033,14 @@ function isRetryableStatus(status) {
1997
2033
  return status === 0 || status === 429 || status >= 500;
1998
2034
  }
1999
2035
  function sleep(ms, signal) {
2000
- return new Promise((resolve2) => {
2001
- if (signal.aborted) return resolve2();
2002
- const t = setTimeout(resolve2, ms);
2036
+ return new Promise((resolve3) => {
2037
+ if (signal.aborted) return resolve3();
2038
+ const t = setTimeout(resolve3, ms);
2003
2039
  signal.addEventListener(
2004
2040
  "abort",
2005
2041
  () => {
2006
2042
  clearTimeout(t);
2007
- resolve2();
2043
+ resolve3();
2008
2044
  },
2009
2045
  { once: true }
2010
2046
  );
@@ -2049,6 +2085,13 @@ async function runAgentTask(transcript, callbacks, signal, model) {
2049
2085
  return { transcript: messages, finalText, stopped: "error", error: errorMessage(e) };
2050
2086
  }
2051
2087
  if (signal.aborted) return { transcript: messages, finalText, stopped: "aborted" };
2088
+ if (callbacks.onTurnUsage) {
2089
+ const outputText = turn.text + turn.toolUses.map((t) => JSON.stringify(t.input ?? "")).join("");
2090
+ callbacks.onTurnUsage({
2091
+ inputTokens: estimateMessagesTokens(messages),
2092
+ outputTokens: estimateTokens(outputText)
2093
+ });
2094
+ }
2052
2095
  if (turn.toolUses.length > MAX_TOOL_USES_PER_TURN) {
2053
2096
  return {
2054
2097
  transcript: messages,
@@ -2127,6 +2170,124 @@ function errorMessage(e) {
2127
2170
  return msg || "The coding agent is unavailable right now.";
2128
2171
  }
2129
2172
 
2173
+ // attachments.ts
2174
+ init_esm_shims();
2175
+ import { readFile as readFile2, stat as stat2 } from "fs/promises";
2176
+ import { resolve as resolve2, basename as basename2, extname } from "path";
2177
+ var IMAGE_TYPES = {
2178
+ ".png": "image/png",
2179
+ ".jpg": "image/jpeg",
2180
+ ".jpeg": "image/jpeg",
2181
+ ".webp": "image/webp",
2182
+ ".gif": "image/gif"
2183
+ };
2184
+ var MAX_MEDIA_BASE64 = 8 * 1024 * 1024;
2185
+ var MAX_FILE_BYTES2 = 5 * 1024 * 1024;
2186
+ var MAX_TEXT_BYTES = 256 * 1024;
2187
+ var TEXT_EXTS = /* @__PURE__ */ new Set([
2188
+ ".txt",
2189
+ ".md",
2190
+ ".markdown",
2191
+ ".csv",
2192
+ ".tsv",
2193
+ ".json",
2194
+ ".yaml",
2195
+ ".yml",
2196
+ ".log"
2197
+ ]);
2198
+ function extractMentions(text) {
2199
+ const out2 = [];
2200
+ const seen = /* @__PURE__ */ new Set();
2201
+ const re = /(?:^|[\s(])@([^\s()]+)/g;
2202
+ let m;
2203
+ while ((m = re.exec(text)) !== null) {
2204
+ const raw = m[1].replace(/[.,;:]+$/, "");
2205
+ if (raw && !seen.has(raw)) {
2206
+ seen.add(raw);
2207
+ out2.push(raw);
2208
+ }
2209
+ }
2210
+ return out2;
2211
+ }
2212
+ function mediaTypeForPath(path2) {
2213
+ const ext = extname(path2).toLowerCase();
2214
+ if (ext === ".pdf") return "application/pdf";
2215
+ return IMAGE_TYPES[ext] ?? null;
2216
+ }
2217
+ function isInlineText(path2) {
2218
+ return TEXT_EXTS.has(extname(path2).toLowerCase());
2219
+ }
2220
+ async function buildTaskContent(text, cwd) {
2221
+ const mentions = extractMentions(text);
2222
+ if (mentions.length === 0) return { content: text, notes: [] };
2223
+ const blocks = [];
2224
+ const inlined = [];
2225
+ const notes = [];
2226
+ let mediaBase64 = 0;
2227
+ for (const mention of mentions) {
2228
+ const abs = resolve2(cwd, mention);
2229
+ let bytes;
2230
+ try {
2231
+ const info = await stat2(abs);
2232
+ if (!info.isFile()) continue;
2233
+ bytes = await readFile2(abs);
2234
+ } catch {
2235
+ continue;
2236
+ }
2237
+ const name = basename2(abs);
2238
+ const mediaType = mediaTypeForPath(abs);
2239
+ if (mediaType) {
2240
+ if (bytes.length > MAX_FILE_BYTES2) {
2241
+ notes.push(`skipped ${name} (too large, limit ${Math.round(MAX_FILE_BYTES2 / 1024 / 1024)}MB)`);
2242
+ continue;
2243
+ }
2244
+ const data = bytes.toString("base64");
2245
+ if (mediaBase64 + data.length > MAX_MEDIA_BASE64) {
2246
+ notes.push(`skipped ${name} (attachment budget exceeded)`);
2247
+ continue;
2248
+ }
2249
+ mediaBase64 += data.length;
2250
+ blocks.push({
2251
+ type: mediaType === "application/pdf" ? "document" : "image",
2252
+ source: { type: "base64", media_type: mediaType, data }
2253
+ });
2254
+ notes.push(`attached ${name}`);
2255
+ } else if (isInlineText(abs)) {
2256
+ if (bytes.length > MAX_TEXT_BYTES) {
2257
+ notes.push(`skipped ${name} (text too large, limit ${Math.round(MAX_TEXT_BYTES / 1024)}KB)`);
2258
+ continue;
2259
+ }
2260
+ const lang = extname(abs).slice(1);
2261
+ inlined.push(`
2262
+
2263
+ --- ${mention} ---
2264
+ \`\`\`${lang}
2265
+ ${bytes.toString("utf8")}
2266
+ \`\`\``);
2267
+ notes.push(`inlined ${name}`);
2268
+ }
2269
+ }
2270
+ const fullText = inlined.length ? text + inlined.join("") : text;
2271
+ if (blocks.length === 0) return { content: fullText, notes };
2272
+ return { content: [{ type: "text", text: fullText }, ...blocks], notes };
2273
+ }
2274
+ function stripStaleMedia(messages) {
2275
+ const lastWithMedia = (() => {
2276
+ for (let i = messages.length - 1; i >= 0; i--) {
2277
+ const c2 = messages[i].content;
2278
+ if (Array.isArray(c2) && c2.some((b) => b.type === "image" || b.type === "document")) return i;
2279
+ }
2280
+ return -1;
2281
+ })();
2282
+ if (lastWithMedia === -1) return messages;
2283
+ return messages.map((msg, i) => {
2284
+ if (i === lastWithMedia || typeof msg.content === "string") return msg;
2285
+ if (!msg.content.some((b) => b.type === "image" || b.type === "document")) return msg;
2286
+ const kept = msg.content.filter((b) => b.type !== "image" && b.type !== "document");
2287
+ return { ...msg, content: kept };
2288
+ });
2289
+ }
2290
+
2130
2291
  // ui.ts
2131
2292
  init_esm_shims();
2132
2293
  var useColor = process.stdout.isTTY && !process.env.NO_COLOR;
@@ -2155,12 +2316,68 @@ var c = {
2155
2316
  function wordmark(suffix, prefix = "Expert") {
2156
2317
  return c.bold(prefix) + c.bold(c.orange(suffix));
2157
2318
  }
2319
+ function clean(s) {
2320
+ return s.replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g, "");
2321
+ }
2158
2322
  function out(s = "") {
2159
2323
  process.stdout.write(s);
2160
2324
  }
2161
2325
  function line(s = "") {
2162
2326
  process.stdout.write(s + "\n");
2163
2327
  }
2328
+ function termWidth() {
2329
+ const cols = process.stdout.columns || 0;
2330
+ if (!cols) return 64;
2331
+ return Math.max(32, Math.min(cols - 1, 80));
2332
+ }
2333
+ var PROMPT = useColor ? `${c.dim("\u2502")} ${c.bold(c.orange("\u203A"))} ` : "> ";
2334
+ function promptTop(right = "") {
2335
+ const w = termWidth();
2336
+ const head = "\u256D\u2500 ";
2337
+ const label = "you";
2338
+ const rightText = right ? ` ${right} ` : "";
2339
+ const used = head.length + label.length + 1 + rightText.length;
2340
+ const fill = Math.max(0, w - used);
2341
+ const bar = head + label + " " + "\u2500".repeat(fill) + rightText;
2342
+ line(useColor ? c.dim(bar.slice(0, bar.length - rightText.length)) + c.gray(rightText) : bar);
2343
+ }
2344
+ function promptBottom() {
2345
+ line(c.dim("\u2570" + "\u2500".repeat(Math.max(1, termWidth() - 1))));
2346
+ }
2347
+ function createSpinner() {
2348
+ const frames = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
2349
+ let i = 0;
2350
+ let timer = null;
2351
+ let text = "working";
2352
+ return {
2353
+ start(label = "working") {
2354
+ if (!useColor || timer) return;
2355
+ text = label;
2356
+ process.stdout.write("\x1B[?25l");
2357
+ const render = () => {
2358
+ i = (i + 1) % frames.length;
2359
+ process.stdout.write(`\r ${c.orange(frames[i])} ${c.dim(text + "\u2026")}\x1B[K`);
2360
+ };
2361
+ render();
2362
+ timer = setInterval(render, 90);
2363
+ },
2364
+ stop() {
2365
+ if (!timer) return;
2366
+ clearInterval(timer);
2367
+ timer = null;
2368
+ process.stdout.write("\r\x1B[2K\x1B[?25h");
2369
+ }
2370
+ };
2371
+ }
2372
+ function showCursor() {
2373
+ if (useColor) process.stdout.write("\x1B[?25h");
2374
+ }
2375
+ function clearScreen() {
2376
+ if (process.stdout.isTTY) process.stdout.write("\x1B[2J\x1B[3J\x1B[H");
2377
+ }
2378
+ function notice(s) {
2379
+ line(c.dim(" " + s));
2380
+ }
2164
2381
  var PLAN_GLYPH = {
2165
2382
  pending: "\u25CB",
2166
2383
  in_progress: "\u25D0",
@@ -2168,7 +2385,7 @@ var PLAN_GLYPH = {
2168
2385
  };
2169
2386
  function toolStartLine(t) {
2170
2387
  const label = c.orange(labelForTool(t.name).padEnd(6));
2171
- const desc = describeToolUse(t);
2388
+ const desc = clean(describeToolUse(t));
2172
2389
  return `${c.orange("\xB7")} ${label} ${c.gray(desc)}`;
2173
2390
  }
2174
2391
  function printToolResult(t, r) {
@@ -2176,7 +2393,8 @@ function printToolResult(t, r) {
2176
2393
  const steps = parsePlan(t) ?? [];
2177
2394
  for (const s of steps) {
2178
2395
  const g = s.status === "done" ? c.green(PLAN_GLYPH.done) : s.status === "in_progress" ? c.yellow(PLAN_GLYPH.in_progress) : c.gray(PLAN_GLYPH.pending);
2179
- line(` ${g} ${s.status === "done" ? c.dim(s.title) : s.title}`);
2396
+ const title = clean(s.title);
2397
+ line(` ${g} ${s.status === "done" ? c.dim(title) : title}`);
2180
2398
  }
2181
2399
  return;
2182
2400
  }
@@ -2185,11 +2403,11 @@ function printToolResult(t, r) {
2185
2403
  return;
2186
2404
  }
2187
2405
  if (r.isError) {
2188
- line(` ${c.red("\u2717")} ${c.red(firstLine(r.content))}`);
2406
+ line(` ${c.red("\u2717")} ${c.red(clean(firstLine(r.content)))}`);
2189
2407
  return;
2190
2408
  }
2191
2409
  const summary = resultSummary(t, r.content);
2192
- if (summary) line(` ${c.gray(summary)}`);
2410
+ if (summary) line(` ${c.gray(clean(summary))}`);
2193
2411
  }
2194
2412
  function firstLine(s) {
2195
2413
  const i = s.indexOf("\n");
@@ -2212,12 +2430,11 @@ var MAX_DIFF_LINES = 80;
2212
2430
  function printDiff(change) {
2213
2431
  const beforeLines = change.before === null ? [] : change.before.split("\n");
2214
2432
  const afterLines = change.after.split("\n");
2433
+ const path2 = clean(change.path);
2215
2434
  if (change.before === null) {
2216
- line(
2217
- ` ${c.green("+")} ${c.bold(change.path)} ${c.dim(`(new file, ${afterLines.length} lines)`)}`
2218
- );
2435
+ line(` ${c.green("+")} ${c.bold(path2)} ${c.dim(`(new file, ${afterLines.length} lines)`)}`);
2219
2436
  } else {
2220
- line(` ${c.dim("\xB1")} ${c.bold(change.path)}`);
2437
+ line(` ${c.dim("\xB1")} ${c.bold(path2)}`);
2221
2438
  }
2222
2439
  let p = 0;
2223
2440
  while (p < beforeLines.length && p < afterLines.length && beforeLines[p] === afterLines[p]) p++;
@@ -2232,7 +2449,7 @@ function printDiff(change) {
2232
2449
  line(` ${c.dim("\u2026")}`);
2233
2450
  break;
2234
2451
  }
2235
- line(` ${c.red("- " + l)}`);
2452
+ line(` ${c.red("- " + clean(l))}`);
2236
2453
  }
2237
2454
  shown = 0;
2238
2455
  for (const l of added) {
@@ -2240,20 +2457,21 @@ function printDiff(change) {
2240
2457
  line(` ${c.dim("\u2026")}`);
2241
2458
  break;
2242
2459
  }
2243
- line(` ${c.green("+ " + l)}`);
2460
+ line(` ${c.green("+ " + clean(l))}`);
2244
2461
  }
2245
2462
  }
2246
2463
  function printApprovalRequest(t) {
2247
2464
  line();
2248
2465
  line(c.yellow(c.bold(" \u26A0 Approval needed")));
2466
+ const desc = clean(describeToolUse(t));
2249
2467
  if (t.name === "run_command") {
2250
- line(` ${c.bold("run")} ${c.orange(describeToolUse(t))}`);
2468
+ line(` ${c.bold("run")} ${c.orange(desc)}`);
2251
2469
  } else if (t.name === "write_file") {
2252
- line(` ${c.bold("write")} ${c.orange(describeToolUse(t))}`);
2470
+ line(` ${c.bold("write")} ${c.orange(desc)}`);
2253
2471
  } else if (t.name === "edit_file") {
2254
- line(` ${c.bold("edit")} ${c.orange(describeToolUse(t))}`);
2472
+ line(` ${c.bold("edit")} ${c.orange(desc)}`);
2255
2473
  } else {
2256
- line(` ${c.bold(labelForTool(t.name))} ${c.orange(describeToolUse(t))}`);
2474
+ line(` ${c.bold(labelForTool(t.name))} ${c.orange(desc)}`);
2257
2475
  }
2258
2476
  }
2259
2477
  function masthead() {
@@ -2268,9 +2486,8 @@ function banner(root, name, laneLabel, mode) {
2268
2486
  line(c.dim(` model ${laneLabel}`));
2269
2487
  line(c.dim(` autonomy ${mode}`));
2270
2488
  line();
2271
- line(
2272
- c.dim(" Type a task and press Enter. Commands: /help /init /auto /manual /clear /exit")
2273
- );
2489
+ line(c.dim(" Type a task and press Enter. \u2191 recalls past tasks \xB7 Tab completes \xB7 @path attaches"));
2490
+ line(c.dim(" Commands: /help /init /model /diff /compact /clear /status /exit"));
2274
2491
  line();
2275
2492
  }
2276
2493
  function help() {
@@ -2278,11 +2495,23 @@ function help() {
2278
2495
  line(c.bold(" Commands"));
2279
2496
  line(` ${c.orange("/help")} show this help`);
2280
2497
  line(` ${c.orange("/init")} explore the project and write (or refresh) its EXPERT.md`);
2498
+ line(` ${c.orange("/model")} show or switch the BYOK provider \u2014 /model <provider> [model]`);
2499
+ line(` ${c.orange("/login")} sign in to the hosted backend (managed lane)`);
2500
+ line(` ${c.orange("/logout")} sign out and switch back to your own key (BYOK)`);
2501
+ line(` ${c.orange("/diff")} review the file changes applied this task`);
2502
+ line(` ${c.orange("/revert")} undo the most recent applied change`);
2503
+ line(` ${c.orange("/status")} show workspace, model, autonomy, changes and token usage`);
2281
2504
  line(` ${c.orange("/auto")} autonomy: auto \u2014 safe reads + edits run; risky commands ask`);
2282
2505
  line(` ${c.orange("/manual")} autonomy: manual \u2014 every write/edit/command asks first`);
2283
- line(` ${c.orange("/clear")} start a fresh task (drop the current conversation)`);
2506
+ line(` ${c.orange("/compact")} summarize the conversation to shrink the context (keeps the task)`);
2507
+ line(` ${c.orange("/clear")} start a fresh task and clear the screen`);
2284
2508
  line(` ${c.orange("/exit")} quit (or Ctrl-D)`);
2285
2509
  line();
2510
+ line(c.bold(" At the prompt"));
2511
+ line(c.dim(" \u2191 / \u2193 recall previous tasks"));
2512
+ line(c.dim(" Tab complete a /command, or accept the agent\u2019s suggested next step"));
2513
+ line(c.dim(" @path attach a file to the task (image/PDF read natively; text inlined)"));
2514
+ line();
2286
2515
  line(c.dim(" During a task, press Ctrl-C once to stop it and return to the prompt."));
2287
2516
  line(c.dim(" At an approval prompt: y = run, n = skip, a = always allow this exact command,"));
2288
2517
  line(c.dim(" or type a note to reject with guidance for the agent."));
@@ -2297,6 +2526,11 @@ function withExpertMd(expertMd, task) {
2297
2526
 
2298
2527
  ${expertMd}${EXPERT_MD_TASK_MARKER}${task}`;
2299
2528
  }
2529
+ function applyPreamble(content, expertMd, isFirst) {
2530
+ if (!isFirst || !expertMd) return content;
2531
+ if (typeof content === "string") return withExpertMd(expertMd, content);
2532
+ return content.map((b) => b.type === "text" ? { ...b, text: withExpertMd(expertMd, b.text) } : b);
2533
+ }
2300
2534
  function extractNextAction(text) {
2301
2535
  const lines = text.split("\n");
2302
2536
  let last = lines.length - 1;
@@ -2305,65 +2539,102 @@ function extractNextAction(text) {
2305
2539
  const m = lines[last].match(/^NEXT:\s*(.+)$/);
2306
2540
  return { next: m ? m[1].trim() : null };
2307
2541
  }
2308
- async function runRepl({ model, workspace, manual }) {
2542
+ var SLASH_COMMANDS = [
2543
+ "/help",
2544
+ "/init",
2545
+ "/auto",
2546
+ "/manual",
2547
+ "/clear",
2548
+ "/compact",
2549
+ "/login",
2550
+ "/logout",
2551
+ "/model",
2552
+ "/diff",
2553
+ "/revert",
2554
+ "/status",
2555
+ "/exit"
2556
+ ];
2557
+ async function runRepl({ lane, workspace, manual }) {
2309
2558
  let mode = manual ? "manual" : "auto";
2310
2559
  const alwaysAllow = /* @__PURE__ */ new Set();
2311
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
2560
+ const changes = [];
2561
+ let pendingNext = null;
2562
+ let taskTokens = 0;
2563
+ let sessionTokens = 0;
2564
+ const completer = (lineStr) => {
2565
+ if (lineStr === "" && pendingNext) return [[pendingNext], ""];
2566
+ if (lineStr.startsWith("/")) {
2567
+ const hits = SLASH_COMMANDS.filter((cmd) => cmd.startsWith(lineStr));
2568
+ return [hits.length ? hits : SLASH_COMMANDS, lineStr];
2569
+ }
2570
+ return [[], lineStr];
2571
+ };
2572
+ const rl = readline.createInterface({
2573
+ input: process.stdin,
2574
+ output: process.stdout,
2575
+ completer,
2576
+ historySize: 100,
2577
+ removeHistoryDuplicates: true
2578
+ });
2312
2579
  const ask = (q) => new Promise((res) => rl.question(q, (a) => res(a)));
2580
+ const askTransient = async (q) => {
2581
+ const a = await ask(q);
2582
+ const h = rl.history;
2583
+ if (h && h.length && h[0] === a) h.shift();
2584
+ return a;
2585
+ };
2586
+ const spinner = createSpinner();
2313
2587
  let activeAbort = null;
2314
2588
  rl.on("SIGINT", () => {
2315
2589
  if (activeAbort) {
2316
2590
  activeAbort.abort();
2317
2591
  killAllCommands();
2592
+ spinner.stop();
2318
2593
  line(c.yellow("\n Stopping the current task\u2026"));
2319
2594
  } else {
2595
+ showCursor();
2320
2596
  line();
2321
2597
  rl.close();
2322
2598
  }
2323
2599
  });
2324
2600
  rl.on("close", () => {
2601
+ spinner.stop();
2602
+ showCursor();
2325
2603
  line(c.dim("\n Bye."));
2326
2604
  process.exit(0);
2327
2605
  });
2328
- banner(workspace.root, workspace.name, model.label, mode);
2606
+ banner(workspace.root, workspace.name, lane.client.label, mode);
2329
2607
  let expertMd = await readExpertMd();
2330
2608
  if (expertMd) line(c.dim(" Loaded EXPERT.md for project context.\n"));
2331
2609
  else line(c.dim(" No EXPERT.md yet \u2014 type /init to generate one for this project.\n"));
2332
2610
  let transcript = [];
2333
2611
  for (; ; ) {
2334
- const input = (await ask(c.bold(c.orange("\u203A ")))).trim();
2612
+ promptTop(sessionTokens ? `${mode} \xB7 ~${humanizeTokens(sessionTokens)} tok` : mode);
2613
+ const input = (await ask(PROMPT)).trim();
2614
+ promptBottom();
2615
+ pendingNext = null;
2335
2616
  if (!input) continue;
2336
- if (input === "/exit" || input === "/quit") {
2337
- rl.close();
2338
- return;
2339
- }
2340
- if (input === "/help") {
2341
- help();
2342
- continue;
2343
- }
2344
- if (input === "/auto") {
2345
- mode = "auto";
2346
- line(c.dim(" autonomy: auto\n"));
2347
- continue;
2348
- }
2349
- if (input === "/manual") {
2350
- mode = "manual";
2351
- line(c.dim(" autonomy: manual\n"));
2352
- continue;
2353
- }
2354
- if (input === "/clear") {
2355
- transcript = [];
2356
- line(c.dim(" Started a fresh task.\n"));
2357
- continue;
2358
- }
2359
- const isInit = input === "/init";
2360
- if (!isInit && input.startsWith("/")) {
2617
+ if (input.startsWith("/") && input !== "/init") {
2618
+ const [cmd, ...rest] = input.split(/\s+/);
2619
+ const handled = await handleSlash(cmd, rest);
2620
+ if (handled === "exit") return;
2621
+ if (handled) continue;
2361
2622
  line(c.yellow(` Unknown command: ${input}. Try /help
2362
2623
  `));
2363
2624
  continue;
2364
2625
  }
2365
- const taskText = isInit ? buildInitTask(expertMd) : transcript.length === 0 ? withExpertMd(expertMd, input) : input;
2366
- transcript.push({ role: "user", content: taskText });
2626
+ const isInit = input === "/init";
2627
+ const isFirst = transcript.length === 0;
2628
+ let content;
2629
+ if (isInit) {
2630
+ content = buildInitTask(expertMd);
2631
+ } else {
2632
+ const built = await buildTaskContent(input, workspace.root);
2633
+ if (built.notes.length) notice(built.notes.join(" \xB7 "));
2634
+ content = applyPreamble(built.content, expertMd, isFirst);
2635
+ }
2636
+ transcript = stripStaleMedia(transcript);
2637
+ transcript.push({ role: "user", content });
2367
2638
  const abort = new AbortController();
2368
2639
  activeAbort = abort;
2369
2640
  let streaming = false;
@@ -2373,20 +2644,24 @@ async function runRepl({ model, workspace, manual }) {
2373
2644
  streaming = false;
2374
2645
  }
2375
2646
  };
2647
+ spinner.start("working");
2376
2648
  const result = await runAgentTask(
2377
2649
  transcript,
2378
2650
  {
2379
2651
  onAssistantTextDelta: (delta) => {
2652
+ spinner.stop();
2380
2653
  streaming = true;
2381
- out(delta);
2654
+ out(clean(delta));
2382
2655
  },
2383
2656
  onAssistantTextReset: () => {
2657
+ spinner.stop();
2384
2658
  if (streaming) {
2385
2659
  out("\n");
2386
2660
  streaming = false;
2387
2661
  }
2388
2662
  },
2389
2663
  onAssistantText: () => {
2664
+ spinner.stop();
2390
2665
  endStream();
2391
2666
  },
2392
2667
  requiresApproval: (tool) => {
@@ -2398,18 +2673,23 @@ async function runRepl({ model, workspace, manual }) {
2398
2673
  return true;
2399
2674
  },
2400
2675
  onToolStart: (tool) => {
2676
+ spinner.stop();
2401
2677
  endStream();
2402
2678
  line(toolStartLine(tool));
2403
2679
  },
2404
2680
  requestApproval: (tool) => {
2681
+ spinner.stop();
2405
2682
  endStream();
2406
2683
  return promptApproval(tool);
2407
2684
  },
2408
2685
  onCommandData: (_tool, _stream, chunk) => {
2409
- out(c.gray(chunk));
2686
+ spinner.stop();
2687
+ out(c.gray(clean(chunk)));
2410
2688
  },
2411
2689
  onToolResult: (tool, r) => {
2412
2690
  printToolResult(tool, r);
2691
+ if (r.change) changes.push(r.change);
2692
+ spinner.start("working");
2413
2693
  },
2414
2694
  onFileTouched: (path2) => {
2415
2695
  if (path2 === "EXPERT.md") {
@@ -2418,11 +2698,17 @@ async function runRepl({ model, workspace, manual }) {
2418
2698
  }).catch(() => {
2419
2699
  });
2420
2700
  }
2701
+ },
2702
+ onTurnUsage: (u) => {
2703
+ const t = u.inputTokens + u.outputTokens;
2704
+ taskTokens += t;
2705
+ sessionTokens += t;
2421
2706
  }
2422
2707
  },
2423
2708
  abort.signal,
2424
- model
2709
+ lane.client
2425
2710
  );
2711
+ spinner.stop();
2426
2712
  endStream();
2427
2713
  activeAbort = null;
2428
2714
  transcript = result.transcript;
@@ -2442,20 +2728,228 @@ async function runRepl({ model, workspace, manual }) {
2442
2728
  );
2443
2729
  } else {
2444
2730
  const { next } = extractNextAction(result.finalText);
2445
- if (next) line(c.dim(`
2731
+ if (next) {
2732
+ pendingNext = next;
2733
+ line(c.dim(`
2446
2734
  next: ${next}`));
2735
+ line(c.dim(" (press Tab at the prompt to accept)"));
2736
+ }
2447
2737
  line();
2448
2738
  }
2739
+ if (taskTokens > 0) {
2740
+ notice(
2741
+ `tokens ~${humanizeTokens(taskTokens)} task \xB7 ~${humanizeTokens(sessionTokens)} session
2742
+ `
2743
+ );
2744
+ }
2449
2745
  }
2450
2746
  function commandOf2(tool) {
2451
2747
  const rec = tool.input && typeof tool.input === "object" ? tool.input : {};
2452
2748
  return typeof rec.command === "string" ? rec.command : "";
2453
2749
  }
2750
+ async function handleSlash(cmd, rest) {
2751
+ switch (cmd) {
2752
+ case "/exit":
2753
+ case "/quit":
2754
+ rl.close();
2755
+ return "exit";
2756
+ case "/help":
2757
+ help();
2758
+ return true;
2759
+ case "/auto":
2760
+ mode = "auto";
2761
+ notice("autonomy: auto\n");
2762
+ return true;
2763
+ case "/manual":
2764
+ mode = "manual";
2765
+ notice("autonomy: manual\n");
2766
+ return true;
2767
+ case "/clear":
2768
+ transcript = [];
2769
+ changes.length = 0;
2770
+ taskTokens = 0;
2771
+ clearScreen();
2772
+ banner(workspace.root, workspace.name, lane.client.label, mode);
2773
+ notice("Started a fresh task (screen cleared).\n");
2774
+ return true;
2775
+ case "/compact":
2776
+ await doCompact(rest);
2777
+ return true;
2778
+ case "/status":
2779
+ printStatus();
2780
+ return true;
2781
+ case "/diff":
2782
+ showDiff();
2783
+ return true;
2784
+ case "/revert":
2785
+ await revertLast();
2786
+ return true;
2787
+ case "/login":
2788
+ await doLogin();
2789
+ return true;
2790
+ case "/logout":
2791
+ doLogout();
2792
+ return true;
2793
+ case "/model":
2794
+ doModel(rest);
2795
+ return true;
2796
+ default:
2797
+ return false;
2798
+ }
2799
+ }
2800
+ function printStatus() {
2801
+ line();
2802
+ notice(`workspace ${workspace.name}`);
2803
+ notice(`model ${lane.client.label}`);
2804
+ notice(`autonomy ${mode}`);
2805
+ notice(`changes ${changes.length} applied this task`);
2806
+ notice(`context ~${humanizeTokens(estimateMessagesTokens(transcript))} tokens in the conversation`);
2807
+ notice(`tokens ~${humanizeTokens(taskTokens)} task \xB7 ~${humanizeTokens(sessionTokens)} session (estimated)`);
2808
+ line();
2809
+ }
2810
+ function showDiff() {
2811
+ if (changes.length === 0) {
2812
+ notice("No file changes applied yet this task.\n");
2813
+ return;
2814
+ }
2815
+ line();
2816
+ line(c.bold(` Applied changes (${changes.length})`));
2817
+ for (const ch of changes) printDiff(ch);
2818
+ line(c.dim("\n Use /revert to undo the most recent one.\n"));
2819
+ }
2820
+ async function revertLast() {
2821
+ const ch = changes.pop();
2822
+ if (!ch) {
2823
+ notice("Nothing to revert.\n");
2824
+ return;
2825
+ }
2826
+ try {
2827
+ if (ch.before === null) {
2828
+ await deleteFile(ch.path);
2829
+ notice(`Reverted: deleted ${ch.path} (it was newly created).
2830
+ `);
2831
+ } else {
2832
+ await writeFile(ch.path, ch.before);
2833
+ notice(`Reverted ${ch.path} to its previous contents.
2834
+ `);
2835
+ }
2836
+ notice("(the agent is not told; a later turn just sees the reverted file)\n");
2837
+ } catch (e) {
2838
+ changes.push(ch);
2839
+ line(c.red(` Could not revert ${ch.path}: ${e instanceof Error ? e.message : "failed"}
2840
+ `));
2841
+ }
2842
+ }
2843
+ async function doCompact(rest) {
2844
+ if (transcript.length === 0) {
2845
+ notice("Nothing to compact yet.\n");
2846
+ return;
2847
+ }
2848
+ const before = estimateMessagesTokens(transcript);
2849
+ const extra = rest.join(" ").trim();
2850
+ const instruction = "Summarize our conversation so far into a compact briefing I can use to continue this task with much less context. Cover: the goal, what has been done, key files and decisions, and what remains. Be thorough but concise. Reply with the summary text only \u2014 do not call any tools." + (extra ? ` Pay special attention to: ${extra}.` : "");
2851
+ const probe = [...transcript, { role: "user", content: instruction }];
2852
+ const abort = new AbortController();
2853
+ activeAbort = abort;
2854
+ line(c.bold("\n Compacting the conversation\u2026\n"));
2855
+ spinner.start("summarizing");
2856
+ let summary = "";
2857
+ try {
2858
+ const turn = await lane.client.runTurn(
2859
+ probe,
2860
+ (d) => {
2861
+ spinner.stop();
2862
+ out(clean(d));
2863
+ summary += d;
2864
+ },
2865
+ abort.signal
2866
+ );
2867
+ summary = turn.text || summary;
2868
+ } catch (e) {
2869
+ spinner.stop();
2870
+ activeAbort = null;
2871
+ if (abort.signal.aborted) {
2872
+ line(c.yellow("\n Compaction stopped.\n"));
2873
+ return;
2874
+ }
2875
+ line(c.red(`
2876
+ Compaction failed: ${e instanceof Error ? e.message : "error"}
2877
+ `));
2878
+ return;
2879
+ }
2880
+ spinner.stop();
2881
+ activeAbort = null;
2882
+ out("\n");
2883
+ if (!summary.trim()) {
2884
+ notice("The model returned no summary; the conversation is unchanged.\n");
2885
+ return;
2886
+ }
2887
+ transcript = [
2888
+ {
2889
+ role: "user",
2890
+ content: `Summary of the earlier conversation (compacted to save context):
2891
+
2892
+ ${summary.trim()}`
2893
+ }
2894
+ ];
2895
+ const after = estimateMessagesTokens(transcript);
2896
+ const used = estimateMessagesTokens(probe) + estimateTokens(summary);
2897
+ taskTokens += used;
2898
+ sessionTokens += used;
2899
+ notice(`
2900
+ Compacted: context ~${humanizeTokens(before)} \u2192 ~${humanizeTokens(after)} tokens.
2901
+ `);
2902
+ }
2903
+ async function doLogin() {
2904
+ if (!lane.managedAvailable()) {
2905
+ notice("Managed sign-in is not available in this build. Use BYOK (`expert setup`).\n");
2906
+ return;
2907
+ }
2908
+ line();
2909
+ line(" " + c.bold("Expert") + " " + c.bold(c.orange("Code")) + c.dim(" \u2014 sign in"));
2910
+ line(c.dim(" We will email you a one-time code.\n"));
2911
+ try {
2912
+ const email = await lane.loginInteractive(askTransient);
2913
+ line(c.green(`
2914
+ Signed in as ${email}. Now using the hosted backend.`));
2915
+ notice("(managed inference requires a Premium account)\n");
2916
+ } catch (e) {
2917
+ line(c.red(`
2918
+ ${e instanceof Error ? e.message : "Sign-in failed."}
2919
+ `));
2920
+ }
2921
+ }
2922
+ function doLogout() {
2923
+ try {
2924
+ const label = lane.logout();
2925
+ notice(`Signed out. Now using ${label}.
2926
+ `);
2927
+ } catch (e) {
2928
+ line(c.red(` ${e instanceof Error ? e.message : "Could not switch to BYOK."}
2929
+ `));
2930
+ }
2931
+ }
2932
+ function doModel(rest) {
2933
+ if (rest.length === 0) {
2934
+ line();
2935
+ for (const l of lane.status()) notice(l);
2936
+ notice("Switch with: /model <anthropic|openai|gemini|groq|openrouter> [model]\n");
2937
+ return;
2938
+ }
2939
+ try {
2940
+ const label = lane.setProvider(rest[0], rest[1]);
2941
+ notice(`Now using ${label}.
2942
+ `);
2943
+ } catch (e) {
2944
+ line(c.red(` ${e instanceof Error ? e.message : "Could not switch model."}
2945
+ `));
2946
+ }
2947
+ }
2454
2948
  async function promptApproval(tool) {
2455
2949
  printApprovalRequest(tool);
2456
2950
  const allowAlways = tool.name === "run_command";
2457
2951
  const hint = allowAlways ? " [y]es / [n]o / [a]lways allow this command, or type a note to reject: " : " [y]es / [n]o, or type a note to reject: ";
2458
- const answer = (await ask(c.dim(hint))).trim();
2952
+ const answer = (await askTransient(c.dim(hint))).trim();
2459
2953
  const lower = answer.toLowerCase();
2460
2954
  if (lower === "y" || lower === "yes" || answer === "") {
2461
2955
  line();
@@ -2475,8 +2969,92 @@ async function runRepl({ model, workspace, manual }) {
2475
2969
  }
2476
2970
  }
2477
2971
 
2972
+ // update.ts
2973
+ init_esm_shims();
2974
+ import { spawn as spawn2 } from "child_process";
2975
+ var PKG = "@ai-launchpad-v1/expert-code";
2976
+ var REGISTRY = "https://registry.npmjs.org";
2977
+ var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
2978
+ function compareSemver(a, b) {
2979
+ const pa = a.split("-")[0].split(".").map((n) => parseInt(n, 10) || 0);
2980
+ const pb = b.split("-")[0].split(".").map((n) => parseInt(n, 10) || 0);
2981
+ for (let i = 0; i < 3; i++) {
2982
+ const d = (pa[i] || 0) - (pb[i] || 0);
2983
+ if (d !== 0) return d;
2984
+ }
2985
+ return 0;
2986
+ }
2987
+ async function fetchLatestVersion(timeoutMs) {
2988
+ try {
2989
+ const ctrl = new AbortController();
2990
+ const timer = setTimeout(() => ctrl.abort(), timeoutMs);
2991
+ const res = await fetch(`${REGISTRY}/${PKG}/latest`, {
2992
+ signal: ctrl.signal,
2993
+ headers: { accept: "application/json" }
2994
+ });
2995
+ clearTimeout(timer);
2996
+ if (!res.ok) return null;
2997
+ const data = await res.json();
2998
+ return typeof data.version === "string" ? data.version : null;
2999
+ } catch {
3000
+ return null;
3001
+ }
3002
+ }
3003
+ function npmInstall(spec, foreground) {
3004
+ return spawn2("npm", ["install", "-g", spec], {
3005
+ detached: !foreground,
3006
+ stdio: foreground ? "inherit" : "ignore",
3007
+ shell: process.platform === "win32"
3008
+ });
3009
+ }
3010
+ function autoUpdateDisabled(cfg) {
3011
+ return cfg.autoUpdate === false || Boolean(process.env.EXPERT_NO_UPDATE) || Boolean(process.env.NO_UPDATE_NOTIFIER) || Boolean(process.env.CI);
3012
+ }
3013
+ async function maybeAutoUpdate(current, cfg) {
3014
+ if (current === "dev" || autoUpdateDisabled(cfg)) return;
3015
+ const now = Date.now();
3016
+ if (now - (cfg.lastUpdateCheck ?? 0) < CHECK_INTERVAL_MS) return;
3017
+ cfg.lastUpdateCheck = now;
3018
+ saveConfig(cfg);
3019
+ const latest = await fetchLatestVersion(2e3);
3020
+ if (!latest || compareSemver(latest, current) <= 0) return;
3021
+ line(
3022
+ c.dim(
3023
+ ` Updating Expert Code ${current} \u2192 ${latest} in the background \u2014 restart to use it.`
3024
+ )
3025
+ );
3026
+ try {
3027
+ npmInstall(`${PKG}@latest`, false).unref();
3028
+ } catch {
3029
+ }
3030
+ }
3031
+ async function forceUpdate(current) {
3032
+ line(c.dim(`
3033
+ Current version: ${current}`));
3034
+ const latest = await fetchLatestVersion(5e3);
3035
+ if (latest && compareSemver(latest, current) <= 0) {
3036
+ line(c.green(` You're on the latest version.
3037
+ `));
3038
+ return;
3039
+ }
3040
+ line(` Installing ${c.orange(`${PKG}@latest`)}\u2026
3041
+ `);
3042
+ const code = await new Promise((resolve3) => {
3043
+ const child = npmInstall(`${PKG}@latest`, true);
3044
+ child.on("close", (c2) => resolve3(c2 ?? 1));
3045
+ child.on("error", () => resolve3(1));
3046
+ });
3047
+ const fresh = loadConfig();
3048
+ fresh.lastUpdateCheck = Date.now();
3049
+ saveConfig(fresh);
3050
+ if (code === 0) line(c.green("\n Updated. Restart `expert` to use the new version.\n"));
3051
+ else line(c.red(`
3052
+ Update failed (npm exited ${code}). Try: npm i -g ${PKG}
3053
+ `));
3054
+ }
3055
+
2478
3056
  // index.ts
2479
- var VERSION = true ? "0.1.1" : "dev";
3057
+ var VERSION = true ? "0.2.1" : "dev";
2480
3058
  function withReadline(fn) {
2481
3059
  const rl = readline2.createInterface({ input: process.stdin, output: process.stdout });
2482
3060
  const ask = (q) => new Promise((res) => rl.question(q, (a) => res(a)));
@@ -2508,8 +3086,67 @@ function resolveModelClient(cfg) {
2508
3086
  printMissingKey(provider);
2509
3087
  return null;
2510
3088
  }
3089
+ return createByokClient(byokLabel(provider, cfg));
3090
+ }
3091
+ function byokLabel(provider, cfg) {
2511
3092
  const model = resolveModel(provider, cfg);
2512
- return createByokClient(`${provider}${model ? ` (${model})` : " (provider default)"}`);
3093
+ return `${provider}${model ? ` (${model})` : " (provider default)"}`;
3094
+ }
3095
+ function createLaneController(cfg, initial) {
3096
+ let client7 = initial;
3097
+ return {
3098
+ get client() {
3099
+ return client7;
3100
+ },
3101
+ managedAvailable: () => managedConfigured(),
3102
+ async loginInteractive(ask) {
3103
+ if (!managedConfigured()) throw new Error("Managed sign-in is not available in this build.");
3104
+ const email = await login(ask);
3105
+ client7 = createManagedClient({ apiBase: resolveApiBase(cfg), getToken: getAccessToken });
3106
+ return email;
3107
+ },
3108
+ logout() {
3109
+ logout();
3110
+ cfg.session = void 0;
3111
+ const provider = resolveProvider(cfg);
3112
+ if (!resolveKey(provider, cfg)) {
3113
+ throw new Error("Signed out, but no BYOK key is configured. Run `expert setup`.");
3114
+ }
3115
+ client7 = createByokClient(byokLabel(provider, cfg));
3116
+ return client7.label;
3117
+ },
3118
+ setProvider(providerArg, modelArg) {
3119
+ const provider = providerArg.toLowerCase();
3120
+ if (!PROVIDERS.includes(provider)) {
3121
+ throw new Error(`Unknown provider "${providerArg}". One of: ${PROVIDERS.join(", ")}`);
3122
+ }
3123
+ const p = provider;
3124
+ const key = resolveKey(p, cfg);
3125
+ if (!key) {
3126
+ throw new Error(
3127
+ `No API key for ${PROVIDER_LABELS[p]}. Run \`expert setup\` or set ${KEY_ENV[p]}.`
3128
+ );
3129
+ }
3130
+ cfg.provider = p;
3131
+ if (modelArg) cfg.models = { ...cfg.models, [p]: modelArg };
3132
+ saveConfig(cfg);
3133
+ process.env.CODE_AI_PROVIDER = p;
3134
+ process.env[`CODE_${KEY_ENV[p]}`] = key;
3135
+ const model = modelArg || resolveModel(p, cfg);
3136
+ if (model) process.env[`CODE_${MODEL_ENV[p]}`] = model;
3137
+ client7 = createByokClient(byokLabel(p, cfg));
3138
+ return client7.label;
3139
+ },
3140
+ status() {
3141
+ const lines = [`current model ${client7.label}`];
3142
+ const provider = resolveProvider(cfg);
3143
+ const keyed = PROVIDERS.map(
3144
+ (p) => `${p}${resolveKey(p, cfg) ? "" : " (no key)"}${p === provider ? " \u2190" : ""}`
3145
+ );
3146
+ lines.push(`providers ${keyed.join(", ")}`);
3147
+ return lines;
3148
+ }
3149
+ };
2513
3150
  }
2514
3151
  function saveByok(provider, key, model) {
2515
3152
  const cfg = loadConfig();
@@ -2616,9 +3253,14 @@ async function cmdConfig(args, cfg) {
2616
3253
  const v = args[2] ?? "";
2617
3254
  if (k === "apiBase") cfg.apiBase = v;
2618
3255
  else if (k === "provider" && PROVIDERS.includes(v)) cfg.provider = v;
3256
+ else if (k === "autoUpdate") cfg.autoUpdate = !/^(false|0|off|no)$/i.test(v);
2619
3257
  else {
2620
3258
  line(c.red(` Unknown or invalid config key: ${k}`));
2621
- line(c.dim(" Settable: apiBase <url>, provider <anthropic|openai|gemini|groq|openrouter>\n"));
3259
+ line(
3260
+ c.dim(
3261
+ " Settable: apiBase <url>, provider <anthropic|openai|gemini|groq|openrouter>, autoUpdate <true|false>\n"
3262
+ )
3263
+ );
2622
3264
  return;
2623
3265
  }
2624
3266
  saveConfig(cfg);
@@ -2633,7 +3275,39 @@ async function cmdConfig(args, cfg) {
2633
3275
  line(` signed in: ${isLoggedIn(cfg) ? cfg.session?.email ?? "yes" : "no"}`);
2634
3276
  const keyed = PROVIDERS.filter((p) => cfg.keys?.[p]);
2635
3277
  line(` keys : ${keyed.length ? keyed.join(", ") + " (stored)" : "none stored"}`);
2636
- line(c.dim("\n Edit: expert config set apiBase <url> | expert config set provider <name>\n"));
3278
+ line(` autoUpdate: ${cfg.autoUpdate === false ? "off" : "on"}`);
3279
+ line(
3280
+ c.dim(
3281
+ "\n Edit: expert config set apiBase <url> | provider <name> | autoUpdate <true|false>\n"
3282
+ )
3283
+ );
3284
+ }
3285
+ function hasCredential(cfg) {
3286
+ if (chosenLane(cfg) === "managed") return managedConfigured() && isLoggedIn(cfg);
3287
+ return Boolean(resolveKey(resolveProvider(cfg), cfg));
3288
+ }
3289
+ async function onboard() {
3290
+ const options = [];
3291
+ if (managedConfigured()) {
3292
+ options.push({
3293
+ label: "Sign in to the hosted backend \u2014 no API key needed (Premium)",
3294
+ run: () => cmdLogin()
3295
+ });
3296
+ }
3297
+ options.push({ label: "Use your own provider API key (BYOK)", run: () => cmdSetup([]) });
3298
+ line();
3299
+ line(" " + c.bold("Expert") + " " + c.bold(c.orange("Code")) + c.dim(" \u2014 get started"));
3300
+ line(c.dim(" Choose how to run the AI:") + "\n");
3301
+ options.forEach((o, i) => line(` ${c.orange(String(i + 1))}. ${o.label}`));
3302
+ line();
3303
+ const pick = (await withReadline((ask) => ask(` Select [1-${options.length}, default 1]: `))).trim();
3304
+ const chosen = options[pick ? parseInt(pick, 10) - 1 : 0];
3305
+ if (!chosen) {
3306
+ line(c.red("\n Invalid choice. Run `expert` again to retry.\n"));
3307
+ return false;
3308
+ }
3309
+ await chosen.run();
3310
+ return hasCredential(loadConfig());
2637
3311
  }
2638
3312
  async function cmdRun(args) {
2639
3313
  let manual = false;
@@ -2642,6 +3316,7 @@ async function cmdRun(args) {
2642
3316
  if (a === "--manual") manual = true;
2643
3317
  else if (!a.startsWith("-")) dirArg = a;
2644
3318
  }
3319
+ await maybeAutoUpdate(VERSION, loadConfig());
2645
3320
  let workspace;
2646
3321
  try {
2647
3322
  workspace = setWorkspace(dirArg ?? process.cwd());
@@ -2650,13 +3325,23 @@ async function cmdRun(args) {
2650
3325
  process.exitCode = 1;
2651
3326
  return;
2652
3327
  }
2653
- const cfg = loadConfig();
3328
+ let cfg = loadConfig();
3329
+ if (!hasCredential(cfg)) {
3330
+ const ready = await onboard();
3331
+ if (!ready) {
3332
+ process.exitCode = 1;
3333
+ return;
3334
+ }
3335
+ cfg = loadConfig();
3336
+ applyConfigToEnv(cfg);
3337
+ }
2654
3338
  const model = resolveModelClient(cfg);
2655
3339
  if (!model) {
2656
3340
  process.exitCode = 1;
2657
3341
  return;
2658
3342
  }
2659
- await runRepl({ model, workspace, manual });
3343
+ const lane = createLaneController(cfg, model);
3344
+ await runRepl({ lane, workspace, manual });
2660
3345
  }
2661
3346
  function printUsage() {
2662
3347
  masthead();
@@ -2667,8 +3352,10 @@ function printUsage() {
2667
3352
  line(" expert login | logout managed sign-in (no API key needed)");
2668
3353
  line(" expert whoami show sign-in + active inference lane");
2669
3354
  line(" expert config [set <k> <v>] show or edit config");
3355
+ line(" expert update update to the latest version now");
2670
3356
  line(" expert --version | --help");
2671
3357
  line();
3358
+ line(c.dim(" Expert Code keeps itself up to date automatically (disable: config set autoUpdate false)."));
2672
3359
  line(c.dim(" Inference: signed in \u2192 hosted backend; otherwise your own key (BYOK)."));
2673
3360
  line(c.dim(" Get started: `expert setup` (BYOK) or `expert login` (managed), then `expert`."));
2674
3361
  line();
@@ -2684,7 +3371,7 @@ function printMissingKey(provider) {
2684
3371
  line(c.dim(` \u2026or set ${provider.toUpperCase()}_API_KEY in your environment for this session.`));
2685
3372
  line();
2686
3373
  }
2687
- var SUBCOMMANDS = /* @__PURE__ */ new Set(["setup", "login", "logout", "whoami", "config"]);
3374
+ var SUBCOMMANDS = /* @__PURE__ */ new Set(["setup", "login", "logout", "whoami", "config", "update"]);
2688
3375
  async function main() {
2689
3376
  const argv = process.argv.slice(2);
2690
3377
  if (argv.includes("--version") || argv.includes("-v")) {
@@ -2711,6 +3398,8 @@ async function main() {
2711
3398
  return cmdWhoami(cfg);
2712
3399
  case "config":
2713
3400
  return cmdConfig(rest, cfg);
3401
+ case "update":
3402
+ return forceUpdate(VERSION);
2714
3403
  }
2715
3404
  }
2716
3405
  return cmdRun(argv);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-launchpad-v1/expert-code",
3
- "version": "0.1.1",
3
+ "version": "0.2.1",
4
4
  "description": "Expert Code — an autonomous coding agent in your terminal. BYOK (your own AI provider key) or managed hosted sign-in.",
5
5
  "type": "module",
6
6
  "bin": {