@uncarved/jade 0.4.1 → 0.4.2

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 (44) hide show
  1. package/README.md +279 -279
  2. package/dist/api.d.ts +1 -1
  3. package/dist/api.js +1 -1
  4. package/dist/session.js +7 -0
  5. package/dist/session.js.map +1 -1
  6. package/package.json +3 -3
  7. package/plugins/mentions/candidates.ts +14 -0
  8. package/plugins/mentions/index.ts +2 -2
  9. package/plugins/models/configure.ts +25 -1
  10. package/plugins/models/index.ts +62 -5
  11. package/plugins/models/plugin.json +1 -1
  12. package/plugins/models/provider.ts +31 -9
  13. package/plugins/models/saved.ts +1 -1
  14. package/plugins/screenshot/browser.ts +1 -1
  15. package/plugins/shell/shell.ts +33 -7
  16. package/plugins/steer/index.ts +1 -1
  17. package/plugins/todo/index.ts +6 -10
  18. package/plugins/tui/frontend.ts +6 -2
  19. package/plugins/tui/markdown.ts +10 -8
  20. package/plugins/tui/mentions.ts +10 -0
  21. package/plugins/tui/transcript.ts +14 -17
  22. package/plugins/tui/tui.ts +13 -12
  23. package/plugins/tui/width.ts +240 -0
  24. package/plugins-dist/mentions/candidates.js +6 -0
  25. package/plugins-dist/mentions/index.js +2 -2
  26. package/plugins-dist/models/configure.js +22 -1
  27. package/plugins-dist/models/index.js +58 -4
  28. package/plugins-dist/models/plugin.json +2 -1
  29. package/plugins-dist/models/provider.js +23 -8
  30. package/plugins-dist/models/saved.js +1 -1
  31. package/plugins-dist/screenshot/browser.js +1 -1
  32. package/plugins-dist/shell/shell.js +21 -7
  33. package/plugins-dist/steer/index.js +1 -1
  34. package/plugins-dist/todo/index.js +3 -8
  35. package/plugins-dist/tui/frontend.js +5 -2
  36. package/plugins-dist/tui/markdown.js +11 -9
  37. package/plugins-dist/tui/mentions.js +6 -0
  38. package/plugins-dist/tui/transcript.js +9 -12
  39. package/plugins-dist/tui/tui.js +10 -9
  40. package/plugins-dist/tui/vendor.js +1388 -1088
  41. package/plugins-dist/tui/width.js +219 -0
  42. package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
  43. package/src/api.ts +1 -1
  44. package/src/session.ts +5 -0
@@ -1,5 +1,6 @@
1
1
  import { execFile } from "node:child_process";
2
2
  import { readdir } from "node:fs/promises";
3
+ import os from "node:os";
3
4
  import path from "node:path";
4
5
  import { display } from "./attach.js";
5
6
  const MAX_CANDIDATES = 20000;
@@ -22,6 +23,11 @@ export async function mentionCandidates(cwd, signal = AbortSignal.timeout(5000))
22
23
  } catch {}
23
24
  return [...dirs, ...files];
24
25
  }
26
+ export async function dirCandidates(cwd, dir) {
27
+ const full = path.resolve(cwd, dir.replace(/^~(?=\/)/, os.homedir()));
28
+ const entries = await readdir(full, { withFileTypes: true }).catch(() => []);
29
+ return entries.filter((e) => e.isDirectory() || e.isFile()).slice(0, MAX_CANDIDATES).map((e) => `${dir}${e.name}${e.isDirectory() ? "/" : ""}`);
30
+ }
25
31
  const SKIP_DIRS = new Set([".git", "node_modules"]);
26
32
  function gitFiles(root) {
27
33
  return new Promise((resolve) => {
@@ -1,6 +1,6 @@
1
1
  import { definePlugin } from "@uncarved/jade-api";
2
2
  import { attachMentions } from "./attach.js";
3
- import { mentionCandidates } from "./candidates.js";
3
+ import { dirCandidates, mentionCandidates } from "./candidates.js";
4
4
  import { clip, dim, lines as joinLines, warn } from "./style.js";
5
5
  export const attachedKey = (plugin, i) => `${plugin}/${i}`;
6
6
  const READ_TIMEOUT_MS = 30000;
@@ -12,7 +12,7 @@ export default definePlugin({
12
12
  trigger: "@",
13
13
  label: "files",
14
14
  hint: "the file's content is sent with the message",
15
- candidates: () => mentionCandidates(ctx.cwd)
15
+ candidates: (dir) => dir ? dirCandidates(ctx.cwd, dir) : mentionCandidates(ctx.cwd)
16
16
  });
17
17
  const renderers = ctx.service("renderers@1");
18
18
  renderers?.event({
@@ -1,7 +1,7 @@
1
1
  import { readFile, rm, writeFile } from "node:fs/promises";
2
2
  import { hasProvider, parseTokens } from "./config.js";
3
3
  import { contextWindow } from "./context.js";
4
- import { EFFORTS, fallbacksFromEnv, isBuiltinKind, isOfficialAnthropic, jsonObject, KEY_KEY, listModels, MODEL_KEY, providerInfo, providerKind, rpmFromEnv, URL_KEY, visionFromEnv } from "./provider.js";
4
+ import { EFFORTS, fallbacksFromEnv, isBuiltinKind, isOfficialAnthropic, jsonObject, KEY_KEY, listModels, MODEL_KEY, providerInfo, providerKind, rpmFromEnv, thinkingFromEnv, URL_KEY, visionFromEnv } from "./provider.js";
5
5
  import { MODEL_SETTINGS, readSavedServices, updateEnvFile, writeSavedServices } from "./saved.js";
6
6
  const PROVIDERS = [
7
7
  { kind: "openai-compat", label: "OpenAI-compatible service", hint: "any /chat/completions endpoint" },
@@ -34,6 +34,15 @@ function fallbacksHint(env, baseURL) {
34
34
  const v = fallbacksSetting(env);
35
35
  return v === undefined ? `${isOfficialAnthropic(baseURL) ? "on" : "off"} (default)` : v ? "on" : "off";
36
36
  }
37
+ function thinkingSetting(env) {
38
+ if (!env.JADE_THINKING?.trim())
39
+ return;
40
+ try {
41
+ return thinkingFromEnv({ JADE_THINKING: env.JADE_THINKING });
42
+ } catch {
43
+ return;
44
+ }
45
+ }
37
46
  const serviceKeys = (kind) => ["JADE_PROVIDER", URL_KEY[kind], KEY_KEY[kind]];
38
47
  const pick = (env, keys) => {
39
48
  const out = {};
@@ -255,6 +264,7 @@ export function configurator(opts) {
255
264
  { label: "Requests per minute", value: "rpm", hint: env.JADE_RPM ? `${env.JADE_RPM}/min` : "no limit (slows down after being rate limited)" },
256
265
  { label: "Can see images", value: "vision", hint: visionHint(env, kind) },
257
266
  ...kind === "anthropic" ? [{ label: "Server-side fallback", value: "fallbacks", hint: fallbacksHint(env, baseURL) }] : [],
267
+ ...kind === "anthropic" ? [{ label: "Send thinking settings", value: "thinking", hint: thinkingSetting(env) === false ? "off" : `on${env.JADE_THINKING ? "" : " (default)"}` }] : [],
258
268
  ...kind === "openai-compat" ? [{ label: "Extra request body", value: "extra", hint: env.OPENAI_COMPAT_EXTRA_BODY ? shorten(env.OPENAI_COMPAT_EXTRA_BODY) : "none" }] : [],
259
269
  { label: "Back", value: "back" }
260
270
  ]
@@ -314,6 +324,17 @@ export function configurator(opts) {
314
324
  }, opts.signal);
315
325
  if (choice !== undefined)
316
326
  await target.update({ JADE_FALLBACKS: choice === DEFAULT ? undefined : choice });
327
+ } else if (action === "thinking" && kind === "anthropic") {
328
+ const current = thinkingSetting(env);
329
+ const choice = await ui.select({
330
+ title: "Send thinking and effort settings with each request?",
331
+ options: [
332
+ { label: "On", value: "on", hint: current !== false ? "current" : "adaptive thinking, effort high unless set" },
333
+ { label: "Off", value: "off", hint: current === false ? "current" : "for services that reject the thinking field; the model decides itself" }
334
+ ]
335
+ }, opts.signal);
336
+ if (choice !== undefined)
337
+ await target.update({ JADE_THINKING: choice === "on" ? undefined : choice });
317
338
  } else if (action === "window") {
318
339
  const n = await ui.input({ title: "Context window in tokens, e.g. 128000, 512K, 1M (empty to infer it from the model name, or 256K if unknown)", initial: env.JADE_CONTEXT_WINDOW ?? "" }, opts.signal);
319
340
  if (n !== undefined && tokensInput("Context window", n))
@@ -7,6 +7,8 @@ import { isBuiltinKind, listModels, MODEL_KEY, providerFromEnv, providerInfo, pr
7
7
  import { MODEL_SETTINGS, readSavedServices } from "./saved.js";
8
8
  let setup;
9
9
  let hinted = false;
10
+ const countdowns = new Map;
11
+ const sessionOf = (request) => request.ext?.["jade/models"]?.session;
10
12
  export default definePlugin({
11
13
  async process(ctx) {
12
14
  const envFile = path.join(ctx.home, ".env");
@@ -15,6 +17,10 @@ export default definePlugin({
15
17
  hinted = false;
16
18
  setup = { configured: () => hasProvider(env), command: false, envFile };
17
19
  const ui = () => ctx.service("ui@1");
20
+ const userAgent = () => {
21
+ const version = ctx.service("update@1")?.version;
22
+ return version ? `jade/${version}` : "jade";
23
+ };
18
24
  const watchers = new Set;
19
25
  const notify = () => {
20
26
  for (const fn of watchers) {
@@ -31,9 +37,13 @@ export default definePlugin({
31
37
  const build = (snapshot) => {
32
38
  return (async () => {
33
39
  const gate = new RateGate({ rpm: rpmFromEnv(snapshot), onLearn: (rpm) => ui()?.notify(`rate limited: spacing requests to ${rpm} per minute from now on`, "warning") });
34
- return withRetry(await providerFromEnv(snapshot), {
40
+ return withRetry(await providerFromEnv(snapshot, { "user-agent": userAgent() }), {
35
41
  gate,
36
- onRetry: ({ attempt, retries, delayMs, error }) => ui()?.notify(`model request failed (${error.message}); retry ${attempt} of ${retries} in ${Math.round(delayMs / 1000)}s`, "warning")
42
+ onWait: ({ delayMs, request }) => countdowns.get(sessionOf(request) ?? "")?.(delayMs, "rate limited, sending in"),
43
+ onRetry: ({ attempt, retries, delayMs, error, request }) => {
44
+ ui()?.notify(`model request failed (${error.message}); retrying in ${Math.round(delayMs / 1000)}s (retry ${attempt}, at most ${retries})`, "warning");
45
+ countdowns.get(sessionOf(request) ?? "")?.(delayMs, "retrying in");
46
+ }
37
47
  });
38
48
  })();
39
49
  };
@@ -170,13 +180,57 @@ export default definePlugin({
170
180
  }
171
181
  }
172
182
  });
183
+ let timer;
184
+ const stopCountdown = () => {
185
+ if (timer === undefined)
186
+ return;
187
+ clearInterval(timer);
188
+ timer = undefined;
189
+ ctx.status?.(undefined);
190
+ };
191
+ if (ctx.status) {
192
+ const id = ctx.session.id;
193
+ countdowns.set(id, (ms, label) => {
194
+ stopCountdown();
195
+ const until = Date.now() + ms;
196
+ const tick = () => {
197
+ const left = Math.ceil((until - Date.now()) / 1000);
198
+ if (left <= 0)
199
+ return stopCountdown();
200
+ ctx.status?.({ text: `${label} ${left}s`, tone: "warn" });
201
+ };
202
+ timer = setInterval(tick, 1000);
203
+ tick();
204
+ });
205
+ ctx.signal.addEventListener("abort", () => {
206
+ stopCountdown();
207
+ countdowns.delete(id);
208
+ });
209
+ ctx.kernel.hook({
210
+ kind: "transform",
211
+ point: "model.before",
212
+ fn: (req) => ({ ...req, ext: { ...req.ext, "jade/models": { session: id } } })
213
+ });
214
+ ctx.kernel.hook({
215
+ kind: "observe",
216
+ point: "event",
217
+ fn: (e) => {
218
+ if (e.type === "turn.ended")
219
+ stopCountdown();
220
+ }
221
+ });
222
+ }
173
223
  ctx.kernel.hook({
174
224
  kind: "observe",
175
225
  point: "model.after",
176
226
  fn: async (res, hook) => {
227
+ stopCountdown();
177
228
  const retries = res.retries;
178
- if (retries?.length)
179
- await hook.emit("retried", { retries });
229
+ if (!retries?.length)
230
+ return;
231
+ const waited = Math.round(retries.reduce((ms, r) => ms + r.delayMs, 0) / 1000);
232
+ ui?.notify(`model request succeeded after ${retries.length} ${retries.length === 1 ? "retry" : "retries"} (${waited}s of waiting)`, "info");
233
+ await hook.emit("retried", { retries });
180
234
  }
181
235
  });
182
236
  }
@@ -9,6 +9,7 @@
9
9
  ],
10
10
  "optional": [
11
11
  "ui@1",
12
- "commands@1"
12
+ "commands@1",
13
+ "update@1"
13
14
  ]
14
15
  }
@@ -15,7 +15,7 @@ export function withRetry(inner, opts = {}) {
15
15
  const failures = [];
16
16
  for (let attempt = 1;; attempt++) {
17
17
  let streamed = false;
18
- await opts.gate?.acquire(options.signal);
18
+ await opts.gate?.acquire(options.signal, opts.onWait && ((delayMs) => opts.onWait({ delayMs, request })));
19
19
  opts.onRequest?.(attempt);
20
20
  try {
21
21
  const res = await inner.complete(request, {
@@ -47,7 +47,7 @@ export function withRetry(inner, opts = {}) {
47
47
  if (streamed)
48
48
  options.onDelta?.({ kind: "reset" });
49
49
  failures.push({ attempt, delayMs, error: err.message, ...err.status !== undefined ? { status: err.status } : {}, ...streamed ? { discarded: true } : {} });
50
- opts.onRetry?.({ attempt, retries, delayMs, error: err });
50
+ opts.onRetry?.({ attempt, retries, delayMs, error: err, request });
51
51
  await sleep(delayMs, options.signal);
52
52
  }
53
53
  }
@@ -72,11 +72,12 @@ export class RateGate {
72
72
  get rpm() {
73
73
  return this.#rpm;
74
74
  }
75
- acquire(signal) {
75
+ acquire(signal, onWait) {
76
76
  const turn = this.#queue.then(async () => {
77
77
  signal.throwIfAborted();
78
78
  for (let wait = this.#delay();wait > 0; wait = this.#delay()) {
79
79
  this.#opts.onWait?.(wait);
80
+ onWait?.(wait);
80
81
  await sleep(wait, signal);
81
82
  }
82
83
  this.#sent.push(this.#now());
@@ -189,6 +190,16 @@ export function fallbacksFromEnv(env = process.env) {
189
190
  return false;
190
191
  throw new Error(`JADE_FALLBACKS must be on or off, got ${JSON.stringify(env.JADE_FALLBACKS)}`);
191
192
  }
193
+ export function thinkingFromEnv(env = process.env) {
194
+ const text = env.JADE_THINKING?.trim().toLowerCase();
195
+ if (!text)
196
+ return true;
197
+ if (["1", "true", "on", "yes"].includes(text))
198
+ return true;
199
+ if (["0", "false", "off", "no"].includes(text))
200
+ return false;
201
+ throw new Error(`JADE_THINKING must be on or off, got ${JSON.stringify(env.JADE_THINKING)}`);
202
+ }
192
203
  export function effortFromEnv(env = process.env) {
193
204
  const effort = env.JADE_EFFORT;
194
205
  if (!effort)
@@ -221,7 +232,7 @@ export function providerInfo(env = process.env) {
221
232
  return { kind, model: env.OPENAI_COMPAT_MODEL ?? "", baseURL: env.OPENAI_COMPAT_BASE_URL };
222
233
  return { kind, model: env.ANTHROPIC_MODEL ?? "claude-opus-5-5", baseURL: env.ANTHROPIC_BASE_URL };
223
234
  }
224
- export async function providerFromEnv(env = process.env) {
235
+ export async function providerFromEnv(env = process.env, headers) {
225
236
  const kind = providerKind(env);
226
237
  if (!isBuiltinKind(kind))
227
238
  throw new Error(`JADE_PROVIDER must be one of ${PROVIDER_KINDS.join(", ")}, got ${JSON.stringify(kind)}`);
@@ -241,7 +252,8 @@ export async function providerFromEnv(env = process.env) {
241
252
  maxTokens,
242
253
  reasoning: effort ? { effort, summary: "auto" } : undefined,
243
254
  idleTimeoutMs,
244
- toolResultImages
255
+ toolResultImages,
256
+ headers
245
257
  });
246
258
  }
247
259
  if (kind === "openai-compat") {
@@ -257,7 +269,8 @@ export async function providerFromEnv(env = process.env) {
257
269
  maxTokens,
258
270
  extraBody: env.OPENAI_COMPAT_EXTRA_BODY ? jsonObject("OPENAI_COMPAT_EXTRA_BODY", env.OPENAI_COMPAT_EXTRA_BODY) : undefined,
259
271
  idleTimeoutMs,
260
- toolResultImages
272
+ toolResultImages,
273
+ headers
261
274
  });
262
275
  }
263
276
  const { anthropicProvider } = await import("@uncarved/provider-anthropic");
@@ -265,9 +278,11 @@ export async function providerFromEnv(env = process.env) {
265
278
  apiKey: env.ANTHROPIC_API_KEY,
266
279
  baseURL: env.ANTHROPIC_BASE_URL ?? "https://api.anthropic.com",
267
280
  model: env.ANTHROPIC_MODEL,
268
- effort: effort ?? "high",
281
+ effort,
269
282
  maxTokens,
270
- fallbacks: fallbacksFromEnv(env)
283
+ fallbacks: fallbacksFromEnv(env),
284
+ thinking: thinkingFromEnv(env),
285
+ headers
271
286
  });
272
287
  }
273
288
  export async function listModels(env = process.env, fetchImpl = fetch) {
@@ -1,6 +1,6 @@
1
1
  import { mkdir, readFile, writeFile } from "node:fs/promises";
2
2
  import path from "node:path";
3
- export const MODEL_SETTINGS = ["JADE_MAX_TOKENS", "JADE_EFFORT", "JADE_CONTEXT_WINDOW", "JADE_RPM", "JADE_VISION", "JADE_FALLBACKS", "OPENAI_COMPAT_EXTRA_BODY"];
3
+ export const MODEL_SETTINGS = ["JADE_MAX_TOKENS", "JADE_EFFORT", "JADE_CONTEXT_WINDOW", "JADE_RPM", "JADE_VISION", "JADE_FALLBACKS", "JADE_THINKING", "OPENAI_COMPAT_EXTRA_BODY"];
4
4
  const strings = (v) => typeof v === "object" && v !== null ? Object.fromEntries(Object.entries(v).filter(([, x]) => typeof x === "string")) : {};
5
5
  export async function readSavedServices(file) {
6
6
  try {
@@ -1,7 +1,7 @@
1
1
  import { readFile } from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { spawn } from "./sys.js";
4
- const READY_MS = 1e4;
4
+ const READY_MS = 30000;
5
5
  const LOAD_MS = 15000;
6
6
  const SETTLE_MS = 3000;
7
7
  const CLOSE_MS = 5000;
@@ -53,7 +53,7 @@ export function shellTools(opts) {
53
53
  const bash = {
54
54
  name: "bash",
55
55
  meta: { shell: "command" },
56
- description: `Run a shell command with ${shell} -c in the working directory and return its exit code, stdout and stderr. ` + `Each call starts a fresh shell: cd and environment variables do not persist. ` + `Default timeout ${DEFAULT_TIMEOUT_MS / 1000}s (timeout_ms, max ${MAX_TIMEOUT_MS / 1000}s). ` + "Set run_in_background for servers, watchers and other long-running commands: it returns an id at once, " + "then read new output with bash_output and stop it with kill_shell. " + "Never start interactive programs. Prefer read_file/grep/glob over cat/grep/find.",
56
+ description: `Run a shell command with ${shell} -c in the working directory and return its exit code, stdout and stderr. ` + `Each call starts a fresh shell: cd and environment variables do not persist. ` + `Default timeout ${DEFAULT_TIMEOUT_MS / 1000}s (timeout_ms, max ${MAX_TIMEOUT_MS / 1000}s). ` + `Output beyond ${MAX_OUTPUT_CHARS} characters (stdout and stderr together) keeps only the start and end. ` + "Set run_in_background for servers, watchers and other long-running commands: it returns an id at once, " + "then read new output with bash_output and stop it with kill_shell. " + "Never start interactive programs. Prefer read_file/grep/glob over cat/grep/find.",
57
57
  inputSchema: {
58
58
  type: "object",
59
59
  properties: { command: { type: "string" }, timeout_ms: { type: "integer" }, run_in_background: { type: "boolean" } },
@@ -84,12 +84,13 @@ export function shellTools(opts) {
84
84
  };
85
85
  signal.addEventListener("abort", kill, { once: true });
86
86
  try {
87
- const [stdout, stderr, code] = await Promise.all([
87
+ const [out, err, code] = await Promise.all([
88
88
  collect(proc.stdout, (text) => progress({ kind: "output", stream: "stdout", text }), true, killed.done),
89
89
  collect(proc.stderr, (text) => progress({ kind: "output", stream: "stderr", text }), true, killed.done),
90
90
  Promise.race([proc.exited, killed.done.then(() => null)])
91
91
  ]);
92
92
  signal.throwIfAborted();
93
+ const [stdout, stderr] = clipStreams(out, err);
93
94
  const parts = [
94
95
  timedOut ? `Timed out after ${timeout}ms (killed). If it needs longer, raise timeout_ms (max ${MAX_TIMEOUT_MS / 1000}s); for servers and watchers use run_in_background.` : `Exit code ${code}`
95
96
  ];
@@ -206,12 +207,13 @@ export async function capture(executable, env, command, opts) {
206
207
  }, opts.timeoutMs);
207
208
  opts.signal?.addEventListener("abort", kill, { once: true });
208
209
  try {
209
- const [stdout, stderr, code] = await Promise.all([
210
+ const [out, err, code] = await Promise.all([
210
211
  collect(proc.stdout, onOutput, true, killed.done),
211
212
  collect(proc.stderr, onOutput, true, killed.done),
212
213
  Promise.race([proc.exited, killed.done.then(() => null)])
213
214
  ]);
214
215
  opts.signal?.throwIfAborted();
216
+ const [stdout, stderr] = clipStreams(out, err);
215
217
  return { code: timedOut ? null : code, output: [stdout, stderr].filter(Boolean).join(`
216
218
  `), timedOut };
217
219
  } finally {
@@ -326,11 +328,23 @@ async function collect(stream, onChunk, keep = true, stop) {
326
328
  const rest = decoder.decode();
327
329
  if (rest)
328
330
  add(rest);
329
- if (total <= MAX_OUTPUT_CHARS)
330
- return (head + tail).trimEnd();
331
+ return { head, tail, total };
332
+ }
333
+ function clipCollected(c, limit) {
334
+ const full = c.total <= MAX_OUTPUT_CHARS ? c.head + c.tail : undefined;
335
+ if (c.total <= limit)
336
+ return full.trimEnd();
337
+ const half = Math.floor(limit / 2);
338
+ const head = (full ?? c.head).slice(0, half);
339
+ const tail = half > 0 ? (full ?? c.tail).slice(-half) : "";
331
340
  return `${head}
332
- … (${total - MAX_OUTPUT_CHARS} characters omitted) …
333
- ${tail.slice(-half)}`.trimEnd();
341
+ … (${c.total - 2 * half} characters omitted) …
342
+ ${tail}`.trimEnd();
343
+ }
344
+ function clipStreams(out, err) {
345
+ const small = Math.min(out.total, err.total, MAX_OUTPUT_CHARS / 2);
346
+ const outLimit = out.total <= err.total ? small : MAX_OUTPUT_CHARS - small;
347
+ return [clipCollected(out, outLimit), clipCollected(err, MAX_OUTPUT_CHARS - outLimit)];
334
348
  }
335
349
  function clip(s) {
336
350
  if (s.length <= MAX_OUTPUT_CHARS)
@@ -68,7 +68,7 @@ export default definePlugin({
68
68
  pending: [],
69
69
  running() {
70
70
  try {
71
- const phase = ctx.session.state().phase;
71
+ const phase = ctx.session.phase();
72
72
  return phase !== "new" && phase !== "idle" && phase !== "ended";
73
73
  } catch {
74
74
  return false;
@@ -15,7 +15,7 @@ function progressLine(todos) {
15
15
  export function todoTool(onChange) {
16
16
  return {
17
17
  name: "todo_write",
18
- description: "Maintain a task list for multi-step work. Each call replaces the whole list. " + "Use it when a task has three or more steps: write the plan, mark one item in_progress while working on it, " + "and mark items completed as soon as they are done. Skip it for simple tasks.",
18
+ description: "Maintain a task list for multi-step work. Each call replaces the whole list. " + "Use it when a task has three or more steps: write the plan, mark one item in_progress while working on it, " + "and mark items completed as soon as they are done, including the last one before you reply. Skip it for simple tasks.",
19
19
  inputSchema: {
20
20
  type: "object",
21
21
  properties: {
@@ -82,12 +82,7 @@ export default definePlugin({
82
82
  },
83
83
  session(ctx) {
84
84
  ctx.kernel.tool(todoTool((todos) => ctx.panel?.(todoPanel(todos))));
85
- if (ctx.panel) {
86
- ctx.session.afterTurn(() => {
87
- const todos = latestTodos(ctx.session.state().messages);
88
- if (Array.isArray(todos))
89
- ctx.panel?.(todoPanel(todos));
90
- });
91
- }
85
+ if (ctx.panel)
86
+ ctx.session.afterTurn(() => ctx.panel?.(undefined));
92
87
  }
93
88
  });
@@ -315,7 +315,7 @@ ${USAGE}
315
315
  early.push(text);
316
316
  },
317
317
  completions: completionList,
318
- complete: async (trigger) => await completions?.list().find((c) => c.completion.trigger === trigger)?.completion.candidates() ?? [],
318
+ complete: async (trigger, dir) => await completions?.list().find((c) => c.completion.trigger === trigger)?.completion.candidates(dir) ?? [],
319
319
  interrupt: () => ready && interrupt(),
320
320
  unqueue: () => takeBack(),
321
321
  exit: () => void quit(0),
@@ -338,7 +338,10 @@ ${USAGE}
338
338
  const offModel = models?.subscribe?.(() => screen.status({ model: models.current()?.model ?? "(no model)" }));
339
339
  let current;
340
340
  let unsubscribe;
341
- const canRetry = () => current?.state.phase === "idle" && current.state.messages.at(-1)?.role === "user";
341
+ const canRetry = () => {
342
+ const state = current?.state;
343
+ return state?.phase === "idle" && state.messages.at(-1)?.role === "user";
344
+ };
342
345
  const view = transcript({
343
346
  screen,
344
347
  cwd,
@@ -1,4 +1,4 @@
1
- import stringWidth from "string-width";
1
+ import { visibleWidth, wrapLines, wrapText } from "./width.js";
2
2
  import wrapAnsi from "wrap-ansi";
3
3
  import { bold, cyan, dim, italic, strike, underline } from "./screen.js";
4
4
  const FENCE = /^\s*(`{3,}|~{3,})\s*([^`\s]*)/;
@@ -85,13 +85,16 @@ export function softInfo(row) {
85
85
  const WRAP = { hard: true, trim: false };
86
86
  export function wrapRows(text, width) {
87
87
  const expanded = expandTabs(text);
88
+ const grouped = wrapLines(expanded, width);
89
+ if (grouped)
90
+ return grouped.flatMap((rows) => rows.map((r, i) => i === 0 ? r : softRow(r)));
88
91
  const rows = wrapAnsi(expanded, width, WRAP).split(`
89
92
  `);
90
93
  const logical = expanded.split(`
91
94
  `);
92
95
  if (rows.length === logical.length)
93
96
  return rows;
94
- const counts = logical.map((l) => stringWidth(l) <= width ? 1 : wrapAnsi(l, width, WRAP).split(`
97
+ const counts = logical.map((l) => visibleWidth(l) <= width ? 1 : wrapAnsi(l, width, WRAP).split(`
95
98
  `).length);
96
99
  if (counts.reduce((a, b) => a + b, 0) !== rows.length)
97
100
  return rows;
@@ -140,7 +143,7 @@ export function expandTabs(text, stop = 4) {
140
143
  const parts = line.split("\t");
141
144
  parts.forEach((p, i) => {
142
145
  out += p;
143
- col += stringWidth(p);
146
+ col += visibleWidth(p);
144
147
  if (i < parts.length - 1) {
145
148
  const n = stop - col % stop;
146
149
  out += " ".repeat(n);
@@ -151,13 +154,12 @@ export function expandTabs(text, stop = 4) {
151
154
  }).join(`
152
155
  `);
153
156
  }
154
- function hanging(head, body, rest = " ".repeat(stringWidth(head))) {
157
+ function hanging(head, body, rest = " ".repeat(visibleWidth(head))) {
155
158
  return {
156
159
  render: (width) => {
157
- const indent = stringWidth(head);
160
+ const indent = visibleWidth(head);
158
161
  const room = Math.max(1, width - indent);
159
- const rows = wrapAnsi(expandTabs(body), room, WRAP).split(`
160
- `);
162
+ const rows = wrapText(expandTabs(body), room);
161
163
  return rows.map((r, i) => i === 0 ? head + r.trimEnd() : softRow(rest + r.trimEnd(), rows[i - 1].length - rows[i - 1].trimEnd().length, indent));
162
164
  }
163
165
  };
@@ -198,7 +200,7 @@ function tableLine(rows, align) {
198
200
  function renderTable(rows, align, width) {
199
201
  const n = Math.max(...rows.map((r) => r.length));
200
202
  const grid = rows.map((r) => Array.from({ length: n }, (_, i) => r[i] ?? ""));
201
- const natural = Array.from({ length: n }, (_, i) => Math.max(1, ...grid.map((r) => stringWidth(r[i]))));
203
+ const natural = Array.from({ length: n }, (_, i) => Math.max(1, ...grid.map((r) => visibleWidth(r[i]))));
202
204
  const room = width - (3 * n + 1);
203
205
  if (room < 3 * n) {
204
206
  const [head, ...body] = grid;
@@ -220,7 +222,7 @@ function renderTable(rows, align, width) {
220
222
  }
221
223
  }
222
224
  const pad = (s, w, a) => {
223
- const gap = w - stringWidth(s);
225
+ const gap = w - visibleWidth(s);
224
226
  if (a === "right")
225
227
  return " ".repeat(gap) + s;
226
228
  if (a === "center")
@@ -7,6 +7,12 @@ export function mentionAt(value, cursor, triggers) {
7
7
  return;
8
8
  return { trigger: m[1], start: cursor - m[2].length - m[1].length, query: m[2].replace(/^"/, "") };
9
9
  }
10
+ export function mentionDir(query) {
11
+ const q = query.replaceAll("\\", "/");
12
+ if (!/^(\.{1,2}\/|~\/|\/|[A-Za-z]:\/)/.test(q))
13
+ return;
14
+ return q.slice(0, q.lastIndexOf("/") + 1);
15
+ }
10
16
  export const mentionText = (trigger, p) => /\s/.test(p) ? `${trigger}"${p}"` : `${trigger}${p}`;
11
17
  const prepared = new WeakMap;
12
18
  function prepare(paths) {
@@ -26,17 +26,11 @@ export function transcript(opts) {
26
26
  if (u)
27
27
  screen.status({ spent: { input: usage.inputTokens, output: usage.outputTokens } });
28
28
  };
29
- async function countUsage(e) {
29
+ function countUsage(e) {
30
30
  if (e.type === "model.responded")
31
31
  addUsage(e.data.usage);
32
32
  else if (e.origin.by === "plugin")
33
33
  addUsage(usageOf(e.data?.usage));
34
- else if (e.type === "tool.completed") {
35
- const child = e.data.child;
36
- if (child && opts.readLog)
37
- for (const c of await opts.readLog(child.sessionId).catch(() => []))
38
- await countUsage(c);
39
- }
40
34
  }
41
35
  let reportsCache;
42
36
  function showContext(e) {
@@ -156,12 +150,16 @@ ${bold(`› ${t.replace(/\n/g, `
156
150
  const lines = text.split(`
157
151
  `);
158
152
  if (lines.length <= MAX_ECHO_LINES)
159
- return screen.log(shown(text));
160
- const rest = lines.slice(ECHO_HEAD_LINES);
161
- screen.log(`${shown(lines.slice(0, ECHO_HEAD_LINES).join(`
153
+ screen.log(shown(text));
154
+ else {
155
+ const rest = lines.slice(ECHO_HEAD_LINES);
156
+ screen.log(`${shown(lines.slice(0, ECHO_HEAD_LINES).join(`
162
157
  `))}
163
158
  ${dim(`… +${rest.length} lines`)}`, { details: rest.map((l) => ` ${l}`).join(`
164
159
  `) });
160
+ }
161
+ if (!text.startsWith("/"))
162
+ screen.log("");
165
163
  },
166
164
  reset() {
167
165
  for (const k of Object.keys(usage))
@@ -312,7 +310,6 @@ ${bold(`› ${t.replace(/\n/g, `
312
310
  }
313
311
  case "tool.completed": {
314
312
  const d = e.data;
315
- countUsage(e);
316
313
  activity("Working");
317
314
  doneProgress(d.toolUseId);
318
315
  const call = calls.get(d.toolUseId);
@@ -412,7 +409,7 @@ ${bold(`› ${t.replace(/\n/g, `
412
409
  async function replay(events, show) {
413
410
  if (!show) {
414
411
  for (const e of events) {
415
- await countUsage(e);
412
+ countUsage(e);
416
413
  if (e.type === "model.responded")
417
414
  showContext(e);
418
415
  }
@@ -16,8 +16,8 @@ import {
16
16
  useState,
17
17
  useSyncExternalStore
18
18
  } from "./vendor.js";
19
- import stringWidth from "string-width";
20
- import { mentionAt, mentionText, rankPaths } from "./mentions.js";
19
+ import { visibleWidth } from "./width.js";
20
+ import { mentionAt, mentionDir, mentionText, rankPaths } from "./mentions.js";
21
21
  import { charWidth, edit, empty, layout, moveRow, offsetAt } from "./editor.js";
22
22
  import { expandTabs, markdownStream, softInfo, visibleRow, wrapRows } from "./markdown.js";
23
23
  import { cells, FRAME_MS, Mascot, moodOf, nextChange, title } from "./mascot.js";
@@ -58,13 +58,13 @@ function foldable(l, width) {
58
58
  }
59
59
  const elapsed = (t) => `${Math.max(0, Math.round(((t.end ?? Date.now()) - t.start) / 1000))}s`;
60
60
  export function tail(text, cols) {
61
- if (stringWidth(text) <= cols)
61
+ if (visibleWidth(text) <= cols)
62
62
  return text;
63
63
  const chars = [...text];
64
64
  let out = "";
65
65
  let w = 1;
66
66
  for (let i = chars.length - 1;i >= 0; i--) {
67
- const cw = stringWidth(chars[i]);
67
+ const cw = visibleWidth(chars[i]);
68
68
  if (w + cw > cols)
69
69
  break;
70
70
  out = chars[i] + out;
@@ -78,7 +78,7 @@ function thinkingRow(t, width) {
78
78
  const label = `✻ Thinking ${elapsed(t)}`;
79
79
  const latest = t.text.split(`
80
80
  `).findLast((l) => l.trim())?.trim().replace(/\s+/g, " ");
81
- const room = width - stringWidth(label) - 6;
81
+ const room = width - visibleWidth(label) - 6;
82
82
  return dim(latest && room >= 8 ? `${label} · ${tail(latest, room)}` : `${label}…`);
83
83
  }
84
84
  function wrapLine(l, width) {
@@ -947,7 +947,7 @@ function Spinner({ label, since }) {
947
947
  const TONE = { ok: "green", warn: "yellow", error: "red", accent: "magenta" };
948
948
  export function fitSegments(segments, width) {
949
949
  const kept = segments.map((s) => ({ ...s }));
950
- const total = () => kept.reduce((n, s, i) => n + stringWidth(s.text) + (i ? 3 : 0), 0);
950
+ const total = () => kept.reduce((n, s, i) => n + visibleWidth(s.text) + (i ? 3 : 0), 0);
951
951
  const steps = kept.flatMap((s) => [
952
952
  ...s.short !== undefined && s.shortAt !== undefined ? [{ s, at: s.shortAt, drop: false }] : [],
953
953
  ...s.dropAt !== undefined ? [{ s, at: s.dropAt, drop: true }] : []
@@ -1017,7 +1017,7 @@ function StatusBar({ status, width }) {
1017
1017
  return h(Box, { paddingX: 1 }, h(Text, { wrap: "truncate-end" }, shown.map((s, i) => h(Text, { key: i }, i ? h(Text, { dimColor: true }, " · ") : null, h(Text, { color: s.color, dimColor: s.dim }, s.text)))));
1018
1018
  }
1019
1019
  function Hint({ variants, width }) {
1020
- const text = variants.find((v) => stringWidth(v) <= width) ?? variants.at(-1);
1020
+ const text = variants.find((v) => visibleWidth(v) <= width) ?? variants.at(-1);
1021
1021
  return h(Text, { dimColor: true, wrap: "truncate-end" }, text);
1022
1022
  }
1023
1023
  const tokens = (n) => n >= 1e6 ? `${(n / 1e6).toFixed(n >= 1e7 ? 0 : 1)}M` : n >= 1000 ? `${(n / 1000).toFixed(n >= 1e4 ? 0 : 1)}k` : String(n);
@@ -1196,16 +1196,17 @@ function Prompt({
1196
1196
  const { state, search, matches, pick, mention, found, file, results, hit } = derive();
1197
1197
  const notice = getNotice();
1198
1198
  const mentioning = mention?.trigger;
1199
+ const mentionScope = mention ? mentionDir(mention.query) : undefined;
1199
1200
  useEffect(() => {
1200
1201
  if (mentioning === undefined || !handlers.complete)
1201
1202
  return;
1202
1203
  let live = true;
1203
1204
  setPaths([]);
1204
- handlers.complete(mentioning).then((p) => void (live && setPaths(p)), () => {});
1205
+ handlers.complete(mentioning, mentionScope).then((p) => void (live && setPaths(p)), () => {});
1205
1206
  return () => {
1206
1207
  live = false;
1207
1208
  };
1208
- }, [mentioning]);
1209
+ }, [mentioning, mentionScope]);
1209
1210
  const completion = completions.find((c) => c.trigger === mentioning);
1210
1211
  const first = around(hit, results.length, menuRows);
1211
1212
  const firstMatch = around(Math.max(0, matches.indexOf(pick)), matches.length, menuRows);