@uncarved/jade 0.4.1 → 0.4.3

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 (52) hide show
  1. package/README.md +3 -3
  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 +4 -4
  7. package/plugins/budget/index.ts +54 -4
  8. package/plugins/budget/plugin.json +1 -1
  9. package/plugins/mentions/candidates.ts +14 -0
  10. package/plugins/mentions/index.ts +2 -2
  11. package/plugins/models/configure.ts +25 -1
  12. package/plugins/models/index.ts +62 -5
  13. package/plugins/models/plugin.json +1 -1
  14. package/plugins/models/provider.ts +31 -9
  15. package/plugins/models/saved.ts +1 -1
  16. package/plugins/prompts/prompts.ts +1 -0
  17. package/plugins/screenshot/browser.ts +1 -1
  18. package/plugins/screenshot/index.ts +2 -1
  19. package/plugins/screenshot/tool.ts +1 -1
  20. package/plugins/shell/shell.ts +33 -7
  21. package/plugins/steer/index.ts +1 -1
  22. package/plugins/todo/index.ts +6 -10
  23. package/plugins/tui/frontend.ts +6 -2
  24. package/plugins/tui/markdown.ts +10 -8
  25. package/plugins/tui/mentions.ts +10 -0
  26. package/plugins/tui/transcript.ts +14 -17
  27. package/plugins/tui/tui.ts +36 -18
  28. package/plugins/tui/width.ts +240 -0
  29. package/plugins-dist/budget/index.js +43 -2
  30. package/plugins-dist/budget/plugin.json +1 -1
  31. package/plugins-dist/mentions/candidates.js +6 -0
  32. package/plugins-dist/mentions/index.js +2 -2
  33. package/plugins-dist/models/configure.js +22 -1
  34. package/plugins-dist/models/index.js +58 -4
  35. package/plugins-dist/models/plugin.json +2 -1
  36. package/plugins-dist/models/provider.js +23 -8
  37. package/plugins-dist/models/saved.js +1 -1
  38. package/plugins-dist/prompts/prompts.js +1 -0
  39. package/plugins-dist/screenshot/browser.js +1 -1
  40. package/plugins-dist/screenshot/index.js +1 -1
  41. package/plugins-dist/screenshot/tool.js +1 -1
  42. package/plugins-dist/shell/shell.js +21 -7
  43. package/plugins-dist/steer/index.js +1 -1
  44. package/plugins-dist/todo/index.js +3 -8
  45. package/plugins-dist/tui/frontend.js +5 -2
  46. package/plugins-dist/tui/markdown.js +11 -9
  47. package/plugins-dist/tui/mentions.js +6 -0
  48. package/plugins-dist/tui/transcript.js +9 -12
  49. package/plugins-dist/tui/tui.js +23 -13
  50. package/plugins-dist/tui/width.js +219 -0
  51. package/src/api.ts +1 -1
  52. package/src/session.ts +5 -0
@@ -1,6 +1,6 @@
1
1
  // Provider:按环境变量选择,外面包一层重试(4.7:重试是包装 Provider 的事)。
2
2
 
3
- import { ProviderError, type ModelResponse, type Provider } from "uncarved";
3
+ import { ProviderError, type ModelRequest, type ModelResponse, type Provider } from "uncarved";
4
4
  import { parseTokens } from "./config.ts";
5
5
 
6
6
  /** 默认的重试等待:一次比一次久,最长 3 分钟 */
@@ -20,8 +20,10 @@ export interface RetryOptions {
20
20
  gate?: RateGate;
21
21
  /** 每次真正发出请求前(排完队、等完重试之后)通知宿主 */
22
22
  onRequest?: (attempt: number) => void;
23
+ /** 这个请求要在限速里排队等一段时间才能发时通知宿主(显示用) */
24
+ onWait?: (info: { delayMs: number; request: ModelRequest }) => void;
23
25
  /** 每次重试前通知宿主(显示用) */
24
- onRetry?: (info: { attempt: number; retries: number; delayMs: number; error: ProviderError }) => void;
26
+ onRetry?: (info: { attempt: number; retries: number; delayMs: number; error: ProviderError; request: ModelRequest }) => void;
25
27
  }
26
28
 
27
29
  /** 是不是被限流了(429,或者错误信息里这么说) */
@@ -60,7 +62,7 @@ export function withRetry(inner: Provider, opts: RetryOptions = {}): Provider {
60
62
  const failures: RetryRecord[] = [];
61
63
  for (let attempt = 1; ; attempt++) {
62
64
  let streamed = false;
63
- await opts.gate?.acquire(options.signal);
65
+ await opts.gate?.acquire(options.signal, opts.onWait && ((delayMs) => opts.onWait!({ delayMs, request })));
64
66
  opts.onRequest?.(attempt);
65
67
  try {
66
68
  const res = await inner.complete(request, {
@@ -95,7 +97,7 @@ export function withRetry(inner: Provider, opts: RetryOptions = {}): Provider {
95
97
  // 失败的这次已经推送过增量的,先让订阅者作废它们(4.7)
96
98
  if (streamed) options.onDelta?.({ kind: "reset" });
97
99
  failures.push({ attempt, delayMs, error: err.message, ...(err.status !== undefined ? { status: err.status } : {}), ...(streamed ? { discarded: true as const } : {}) });
98
- opts.onRetry?.({ attempt, retries, delayMs, error: err });
100
+ opts.onRetry?.({ attempt, retries, delayMs, error: err, request });
99
101
  await sleep(delayMs, options.signal);
100
102
  }
101
103
  }
@@ -139,12 +141,13 @@ export class RateGate {
139
141
  return this.#rpm;
140
142
  }
141
143
 
142
- /** 等到可以发下一个请求,并记下这个请求。排队的请求按先来后到 */
143
- acquire(signal: AbortSignal): Promise<void> {
144
+ /** 等到可以发下一个请求,并记下这个请求。排队的请求按先来后到;轮到它但还要等时调用 onWait(只告诉这个请求的调用方) */
145
+ acquire(signal: AbortSignal, onWait?: (ms: number) => void): Promise<void> {
144
146
  const turn = this.#queue.then(async () => {
145
147
  signal.throwIfAborted();
146
148
  for (let wait = this.#delay(); wait > 0; wait = this.#delay()) {
147
149
  this.#opts.onWait?.(wait);
150
+ onWait?.(wait);
148
151
  await sleep(wait, signal);
149
152
  }
150
153
  this.#sent.push(this.#now());
@@ -280,6 +283,18 @@ export function fallbacksFromEnv(env: Env = process.env): boolean {
280
283
  throw new Error(`JADE_FALLBACKS must be on or off, got ${JSON.stringify(env.JADE_FALLBACKS)}`);
281
284
  }
282
285
 
286
+ /**
287
+ * JADE_THINKING:Anthropic 格式的请求里带不带 thinking(adaptive)。不设时带;
288
+ * off 给见到 thinking 字段就拒绝请求的服务用(例如基元律动的 egg-alpha-004,不带时它照样思考)
289
+ */
290
+ export function thinkingFromEnv(env: Env = process.env): boolean {
291
+ const text = env.JADE_THINKING?.trim().toLowerCase();
292
+ if (!text) return true;
293
+ if (["1", "true", "on", "yes"].includes(text)) return true;
294
+ if (["0", "false", "off", "no"].includes(text)) return false;
295
+ throw new Error(`JADE_THINKING must be on or off, got ${JSON.stringify(env.JADE_THINKING)}`);
296
+ }
297
+
283
298
  /** JADE_EFFORT;不设时 Claude 用 high,OpenAI 用服务端默认值 */
284
299
  export function effortFromEnv(env: Env = process.env): string | undefined {
285
300
  const effort = env.JADE_EFFORT;
@@ -327,9 +342,11 @@ export function providerInfo(env: Env = process.env): ProviderInfo {
327
342
  * JADE_IDLE_TIMEOUT 是等模型服务回数据的时限,见 idleTimeoutFromEnv
328
343
  * JADE_VISION 是模型能不能看图片,见 visionFromEnv
329
344
  * JADE_FALLBACKS 是 Claude 被安全策略拒绝时要不要服务端换模型重试,见 fallbacksFromEnv
330
- * 只导入用到的那个服务的包:Anthropic 的 SDK 加载要一百多毫秒,拖慢启动
345
+ * JADE_THINKING 是 Anthropic 格式的请求里带不带 thinking,见 thinkingFromEnv
346
+ * 只导入用到的那个服务的包:Anthropic 的 SDK 加载要一百多毫秒,拖慢启动。
347
+ * headers 合并进每次请求(User-Agent 标明是 jade:有的服务按它在用量里区分客户端)
331
348
  */
332
- export async function providerFromEnv(env: Env = process.env): Promise<Provider> {
349
+ export async function providerFromEnv(env: Env = process.env, headers?: Record<string, string>): Promise<Provider> {
333
350
  const kind = providerKind(env);
334
351
  if (!isBuiltinKind(kind)) throw new Error(`JADE_PROVIDER must be one of ${PROVIDER_KINDS.join(", ")}, got ${JSON.stringify(kind)}`);
335
352
  const maxTokens = env.JADE_MAX_TOKENS ? parseTokens("JADE_MAX_TOKENS", env.JADE_MAX_TOKENS) : undefined;
@@ -351,6 +368,7 @@ export async function providerFromEnv(env: Env = process.env): Promise<Provider>
351
368
  reasoning: effort ? { effort: effort as "minimal" | "low" | "medium" | "high", summary: "auto" } : undefined,
352
369
  idleTimeoutMs,
353
370
  toolResultImages,
371
+ headers,
354
372
  });
355
373
  }
356
374
  if (kind === "openai-compat") {
@@ -365,6 +383,7 @@ export async function providerFromEnv(env: Env = process.env): Promise<Provider>
365
383
  extraBody: env.OPENAI_COMPAT_EXTRA_BODY ? jsonObject("OPENAI_COMPAT_EXTRA_BODY", env.OPENAI_COMPAT_EXTRA_BODY) : undefined,
366
384
  idleTimeoutMs,
367
385
  toolResultImages,
386
+ headers,
368
387
  });
369
388
  }
370
389
  const { anthropicProvider } = await import("@uncarved/provider-anthropic");
@@ -373,9 +392,12 @@ export async function providerFromEnv(env: Env = process.env): Promise<Provider>
373
392
  apiKey: env.ANTHROPIC_API_KEY,
374
393
  baseURL: env.ANTHROPIC_BASE_URL ?? "https://api.anthropic.com",
375
394
  model: env.ANTHROPIC_MODEL,
376
- effort: (effort ?? "high") as "low" | "medium" | "high" | "xhigh" | "max",
395
+ // 不设时 provider 用 high;JADE_THINKING=off 且没设时不发 effort
396
+ effort: effort as "low" | "medium" | "high" | "xhigh" | "max" | undefined,
377
397
  maxTokens,
378
398
  fallbacks: fallbacksFromEnv(env),
399
+ thinking: thinkingFromEnv(env),
400
+ headers,
379
401
  });
380
402
  }
381
403
 
@@ -8,7 +8,7 @@ import path from "node:path";
8
8
  export type Env = Record<string, string | undefined>;
9
9
 
10
10
  /** 每个模型自己的设置:切换模型时一起换掉 */
11
- export const MODEL_SETTINGS = ["JADE_MAX_TOKENS", "JADE_EFFORT", "JADE_CONTEXT_WINDOW", "JADE_RPM", "JADE_VISION", "JADE_FALLBACKS", "OPENAI_COMPAT_EXTRA_BODY"];
11
+ export const MODEL_SETTINGS = ["JADE_MAX_TOKENS", "JADE_EFFORT", "JADE_CONTEXT_WINDOW", "JADE_RPM", "JADE_VISION", "JADE_FALLBACKS", "JADE_THINKING", "OPENAI_COMPAT_EXTRA_BODY"];
12
12
 
13
13
  export interface SavedModel {
14
14
  name: string;
@@ -52,6 +52,7 @@ const HOW: Line[] = [
52
52
  tools: ["bash"],
53
53
  without: "- There is no shell in this session (no bash tool), so you cannot run commands. After changing code, tell the user which commands would verify it.",
54
54
  },
55
+ { text: "- If the user says not to test or check the result, do not: no tests, builds, screenshots or other checks of any kind. Finish the work and reply." },
55
56
  { text: "- Use the task tool for broad searches so that only conclusions come back into this conversation.", tools: ["task"] },
56
57
  {
57
58
  text: "- Do not guess about things outside the repository that may have changed (library APIs, versions, error messages): look them up with the web tools.",
@@ -13,7 +13,7 @@ import path from "node:path";
13
13
  import { spawn, type Proc } from "./sys.ts";
14
14
 
15
15
  /** 浏览器启动到能连接的最长时间 */
16
- const READY_MS = 10_000;
16
+ const READY_MS = 30_000;
17
17
  /** 等页面 load 事件的最长时间;到时间还没有就按当时的样子截 */
18
18
  const LOAD_MS = 15_000;
19
19
  /** load 之后等网络安静下来(脚本、图片、字体)的最长时间 */
@@ -8,7 +8,8 @@ import { findBrowser, screenshotTool } from "./tool.ts";
8
8
 
9
9
  /** 提示词里的一段:有截图工具时才加 */
10
10
  const NOTE =
11
- "- When the work is visual (a page, a drawing, styles), take a screenshot of the result and look at it instead of guessing from the source. " +
11
+ "- When the work is visual (a page, a drawing, styles), take a screenshot of the result and look at it instead of guessing from the source, unless the user said not to test or check it. " +
12
+ "A few looks are enough: fix what is clearly broken, then reply; do not keep polishing details the user did not ask for. " +
12
13
  "If screenshots keep failing, or keep showing something you cannot explain after a couple of attempts, stop changing code to chase it: tell the user what you see and let them look.";
13
14
 
14
15
  export default definePlugin({
@@ -67,7 +67,7 @@ export function screenshotTool(opts: ScreenshotOptions): Tool | undefined {
67
67
  name: "screenshot",
68
68
  description:
69
69
  "Render a local file (HTML, SVG, image) or a web page in a headless browser and return a screenshot, so you can see how it actually looks. " +
70
- "Give either path or url. Use it to check visual work (layout, colors, drawings) instead of guessing from the source. " +
70
+ "Give either path or url. Use it to check visual work (layout, colors, drawings) instead of guessing from the source; skip it when the user said not to test or check. " +
71
71
  `The viewport defaults to ${DEFAULT_WIDTH}x${DEFAULT_HEIGHT}; only what fits in it is captured. ` +
72
72
  "To see a part further down a long page, give scroll_to (a CSS selector, or some text that appears there) instead of a very tall viewport. " +
73
73
  "Narrow widths are laid out as given, so use the real device width to check a mobile layout. " +
@@ -112,6 +112,7 @@ export function shellTools(opts: ShellOptions): ShellTools {
112
112
  `Run a shell command with ${shell} -c in the working directory and return its exit code, stdout and stderr. ` +
113
113
  `Each call starts a fresh shell: cd and environment variables do not persist. ` +
114
114
  `Default timeout ${DEFAULT_TIMEOUT_MS / 1000}s (timeout_ms, max ${MAX_TIMEOUT_MS / 1000}s). ` +
115
+ `Output beyond ${MAX_OUTPUT_CHARS} characters (stdout and stderr together) keeps only the start and end. ` +
115
116
  "Set run_in_background for servers, watchers and other long-running commands: it returns an id at once, " +
116
117
  "then read new output with bash_output and stop it with kill_shell. " +
117
118
  "Never start interactive programs. Prefer read_file/grep/glob over cat/grep/find.",
@@ -145,12 +146,13 @@ export function shellTools(opts: ShellOptions): ShellTools {
145
146
  };
146
147
  signal.addEventListener("abort", kill, { once: true });
147
148
  try {
148
- const [stdout, stderr, code] = await Promise.all([
149
+ const [out, err, code] = await Promise.all([
149
150
  collect(proc.stdout, (text) => progress({ kind: "output", stream: "stdout", text }), true, killed.done),
150
151
  collect(proc.stderr, (text) => progress({ kind: "output", stream: "stderr", text }), true, killed.done),
151
152
  Promise.race([proc.exited, killed.done.then(() => null)]),
152
153
  ]);
153
154
  signal.throwIfAborted();
155
+ const [stdout, stderr] = clipStreams(out, err);
154
156
  const parts = [
155
157
  timedOut
156
158
  ? `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.`
@@ -269,12 +271,13 @@ export async function capture(executable: string, env: NodeJS.ProcessEnv | undef
269
271
  }, opts.timeoutMs);
270
272
  opts.signal?.addEventListener("abort", kill, { once: true });
271
273
  try {
272
- const [stdout, stderr, code] = await Promise.all([
274
+ const [out, err, code] = await Promise.all([
273
275
  collect(proc.stdout, onOutput, true, killed.done),
274
276
  collect(proc.stderr, onOutput, true, killed.done),
275
277
  Promise.race([proc.exited, killed.done.then(() => null)]),
276
278
  ]);
277
279
  opts.signal?.throwIfAborted();
280
+ const [stdout, stderr] = clipStreams(out, err);
278
281
  return { code: timedOut ? null : code, output: [stdout, stderr].filter(Boolean).join("\n"), timedOut };
279
282
  } finally {
280
283
  clearTimeout(timer);
@@ -396,11 +399,18 @@ function giveUp(): { start(): void; done: Promise<void> } {
396
399
  return { start, done };
397
400
  }
398
401
 
402
+ /** 读到的输出:total 不超过 MAX_OUTPUT_CHARS 时 head + tail 就是全部,否则 head 是开头一半、tail 至少是结尾一半 */
403
+ interface Collected {
404
+ head: string;
405
+ tail: string;
406
+ total: number;
407
+ }
408
+
399
409
  /**
400
- * 返回截好的输出:超过 MAX_OUTPUT_CHARS 时保留开头和结尾各一半,中间截掉。
401
- * 边读边截,输出再多也只占几倍 MAX_OUTPUT_CHARS 的内存。keep 为 false 时只推给 onChunk,不累积,返回空串
410
+ * 边读边截,输出再多也只占几倍 MAX_OUTPUT_CHARS 的内存;最后截成多长由 clipStreams 按 stdout、stderr 合计决定。
411
+ * keep 为 false 时只推给 onChunk,不累积
402
412
  */
403
- async function collect(stream: AsyncIterable<Uint8Array>, onChunk: (text: string) => void, keep = true, stop?: Promise<void>): Promise<string> {
413
+ async function collect(stream: AsyncIterable<Uint8Array>, onChunk: (text: string) => void, keep = true, stop?: Promise<void>): Promise<Collected> {
404
414
  const half = MAX_OUTPUT_CHARS / 2;
405
415
  const decoder = new TextDecoder();
406
416
  let head = "";
@@ -434,8 +444,24 @@ async function collect(stream: AsyncIterable<Uint8Array>, onChunk: (text: string
434
444
  }
435
445
  const rest = decoder.decode();
436
446
  if (rest) add(rest);
437
- if (total <= MAX_OUTPUT_CHARS) return (head + tail).trimEnd();
438
- return `${head}\n… (${total - MAX_OUTPUT_CHARS} characters omitted) …\n${tail.slice(-half)}`.trimEnd();
447
+ return { head, tail, total };
448
+ }
449
+
450
+ /** 截到最多 limit 个字符:保留开头和结尾各一半,中间截掉 */
451
+ function clipCollected(c: Collected, limit: number): string {
452
+ const full = c.total <= MAX_OUTPUT_CHARS ? c.head + c.tail : undefined;
453
+ if (c.total <= limit) return full!.trimEnd();
454
+ const half = Math.floor(limit / 2);
455
+ const head = (full ?? c.head).slice(0, half);
456
+ const tail = half > 0 ? (full ?? c.tail).slice(-half) : "";
457
+ return `${head}\n… (${c.total - 2 * half} characters omitted) …\n${tail}`.trimEnd();
458
+ }
459
+
460
+ /** stdout、stderr 合计最多 MAX_OUTPUT_CHARS:短的那路最多占一半,剩下的都给另一路 */
461
+ function clipStreams(out: Collected, err: Collected): [string, string] {
462
+ const small = Math.min(out.total, err.total, MAX_OUTPUT_CHARS / 2);
463
+ const outLimit = out.total <= err.total ? small : MAX_OUTPUT_CHARS - small;
464
+ return [clipCollected(out, outLimit), clipCollected(err, MAX_OUTPUT_CHARS - outLimit)];
439
465
  }
440
466
 
441
467
  /** 保留开头和结尾,中间截掉 */
@@ -93,7 +93,7 @@ export default definePlugin({
93
93
  pending: [],
94
94
  running() {
95
95
  try {
96
- const phase = ctx.session.state().phase;
96
+ const phase = ctx.session.phase();
97
97
  return phase !== "new" && phase !== "idle" && phase !== "ended";
98
98
  } catch {
99
99
  // 会话还没建好,或者已经关了
@@ -39,7 +39,7 @@ export function todoTool(onChange?: (todos: Todo[]) => void): Tool {
39
39
  description:
40
40
  "Maintain a task list for multi-step work. Each call replaces the whole list. " +
41
41
  "Use it when a task has three or more steps: write the plan, mark one item in_progress while working on it, " +
42
- "and mark items completed as soon as they are done. Skip it for simple tasks.",
42
+ "and mark items completed as soon as they are done, including the last one before you reply. Skip it for simple tasks.",
43
43
  inputSchema: {
44
44
  type: "object",
45
45
  properties: {
@@ -88,7 +88,7 @@ const bold = (text: string): Span => ({ text, style: "bold" });
88
88
  const args = (input: unknown) => (input !== null && typeof input === "object" ? input : {}) as Record<string, unknown>;
89
89
  const list = (input: unknown) => (Array.isArray(args(input).todos) ? (args(input).todos as Todo[]) : []);
90
90
 
91
- // 完整的清单常驻在输入框上方(ctx.panel),对话里每次更新只占一行,展开(ctrl+o、点击)看当时的完整清单。
91
+ // 这一轮跑的时候完整的清单在输入框上方(ctx.panel),对话里每次更新只占一行,展开(ctrl+o、点击)看当时的完整清单。
92
92
  // 前端没有那个位置时,对话里的一行照样能展开
93
93
  export const todoRenderer: ToolRenderer = {
94
94
  tool: "todo_write",
@@ -99,7 +99,7 @@ export const todoRenderer: ToolRenderer = {
99
99
  result: ({ isError }) => (isError ? undefined : null),
100
100
  };
101
101
 
102
- /** 输入框上方的一块:还有没做完的项时显示,全部做完或清空时去掉 */
102
+ /** 输入框上方的一块:还有没做完的项时显示,全部做完或清空时去掉(一轮结束时也去掉) */
103
103
  export function todoPanel(todos: Todo[]): Text | undefined {
104
104
  if (todos.every((t) => t?.status === "completed")) return undefined;
105
105
  const p = progressOf(todos);
@@ -112,12 +112,8 @@ export default definePlugin({
112
112
  },
113
113
  session(ctx) {
114
114
  ctx.kernel.tool(todoTool((todos) => ctx.panel?.(todoPanel(todos))));
115
- // 恢复的、/rewind 复制出的会话:历史里最后一份清单接着显示
116
- if (ctx.panel) {
117
- ctx.session.afterTurn(() => {
118
- const todos = latestTodos(ctx.session.state().messages);
119
- if (Array.isArray(todos)) ctx.panel?.(todoPanel(todos));
120
- });
121
- }
115
+ // 清单只在这一轮跑的时候显示:模型做完常常不再把最后一项标完成,留着就一直挡在输入框上方。
116
+ // 一轮结束就收起,完整清单在对话里那一行展开看
117
+ if (ctx.panel) ctx.session.afterTurn(() => ctx.panel?.(undefined));
122
118
  },
123
119
  });
@@ -374,7 +374,7 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
374
374
  },
375
375
  // 打了补全的触发字符(例如 @)时向登记它的插件要候选
376
376
  completions: completionList,
377
- complete: async (trigger) => (await completions?.list().find((c) => c.completion.trigger === trigger)?.completion.candidates()) ?? [],
377
+ complete: async (trigger, dir) => (await completions?.list().find((c) => c.completion.trigger === trigger)?.completion.candidates(dir)) ?? [],
378
378
  interrupt: () => ready && interrupt(),
379
379
  unqueue: () => takeBack(),
380
380
  exit: () => void quit(0),
@@ -405,7 +405,11 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
405
405
 
406
406
  let current: Session | undefined;
407
407
  let unsubscribe: (() => void) | undefined;
408
- const canRetry = () => current?.state.phase === "idle" && current.state.messages.at(-1)?.role === "user";
408
+ const canRetry = () => {
409
+ // state 每次都拷贝整段历史,只取一次
410
+ const state = current?.state;
411
+ return state?.phase === "idle" && state.messages.at(-1)?.role === "user";
412
+ };
409
413
 
410
414
  const view: Transcript = transcript({
411
415
  screen,
@@ -2,7 +2,7 @@
2
2
  // 回复是流式到达的,按完整的行逐行处理:代码块要记住是否在块里,表格要攒齐所有行才能算列宽,
3
3
  // 所以做成有状态的 markdownStream。表格和分隔线跟终端宽度有关,交出去的是按宽度现排的函数。
4
4
 
5
- import stringWidth from "string-width";
5
+ import { visibleWidth, wrapLines, wrapText } from "./width.ts";
6
6
  import wrapAnsi from "wrap-ansi";
7
7
  import { bold, cyan, dim, italic, strike, underline } from "./screen.ts";
8
8
 
@@ -128,12 +128,14 @@ const WRAP = { hard: true, trim: false } as const;
128
128
  */
129
129
  export function wrapRows(text: string, width: number): string[] {
130
130
  const expanded = expandTabs(text);
131
+ const grouped = wrapLines(expanded, width);
132
+ if (grouped) return grouped.flatMap((rows) => rows.map((r, i) => (i === 0 ? r : softRow(r))));
131
133
  // 整段一起折:颜色可能跨行,分开折会丢掉后面几行的颜色
132
134
  const rows = wrapAnsi(expanded, width, WRAP).split("\n");
133
135
  const logical = expanded.split("\n");
134
136
  if (rows.length === logical.length) return rows;
135
137
  // 每个原来的行占了几行:放得下的占一行,放不下的单独折一次数出来(颜色不占宽度,不影响在哪里折)
136
- const counts = logical.map((l) => (stringWidth(l) <= width ? 1 : wrapAnsi(l, width, WRAP).split("\n").length));
138
+ const counts = logical.map((l) => (visibleWidth(l) <= width ? 1 : wrapAnsi(l, width, WRAP).split("\n").length));
137
139
  if (counts.reduce((a, b) => a + b, 0) !== rows.length) return rows;
138
140
  let at = 0;
139
141
  for (const n of counts) {
@@ -196,7 +198,7 @@ export function expandTabs(text: string, stop = 4): string {
196
198
  const parts = line.split("\t");
197
199
  parts.forEach((p, i) => {
198
200
  out += p;
199
- col += stringWidth(p);
201
+ col += visibleWidth(p);
200
202
  if (i < parts.length - 1) {
201
203
  const n = stop - (col % stop);
202
204
  out += " ".repeat(n);
@@ -209,12 +211,12 @@ export function expandTabs(text: string, stop = 4): string {
209
211
  }
210
212
 
211
213
  /** 折行时续行缩进到 head 之后(列表项的正文、代码块的竖线);rest 是续行开头显示的内容,宽度和 head 相同 */
212
- function hanging(head: string, body: string, rest = " ".repeat(stringWidth(head))): MdLine {
214
+ function hanging(head: string, body: string, rest = " ".repeat(visibleWidth(head))): MdLine {
213
215
  return {
214
216
  render: (width) => {
215
- const indent = stringWidth(head);
217
+ const indent = visibleWidth(head);
216
218
  const room = Math.max(1, width - indent);
217
- const rows = wrapAnsi(expandTabs(body), room, WRAP).split("\n");
219
+ const rows = wrapText(expandTabs(body), room);
218
220
  // 折行处留下的行尾空格看不见,去掉免得多占一列;去掉了几个记在续行的记号里,复制时补回去
219
221
  return rows.map((r, i) => (i === 0 ? head + r.trimEnd() : softRow(rest + r.trimEnd(), rows[i - 1]!.length - rows[i - 1]!.trimEnd().length, indent)));
220
222
  },
@@ -263,7 +265,7 @@ function tableLine(rows: string[][], align: Align[]): MdLine {
263
265
  function renderTable(rows: string[][], align: Align[], width: number): string[] {
264
266
  const n = Math.max(...rows.map((r) => r.length));
265
267
  const grid = rows.map((r) => Array.from({ length: n }, (_, i) => r[i] ?? ""));
266
- const natural = Array.from({ length: n }, (_, i) => Math.max(1, ...grid.map((r) => stringWidth(r[i]!))));
268
+ const natural = Array.from({ length: n }, (_, i) => Math.max(1, ...grid.map((r) => visibleWidth(r[i]!))));
267
269
  const room = width - (3 * n + 1);
268
270
  if (room < 3 * n) {
269
271
  const [head, ...body] = grid;
@@ -285,7 +287,7 @@ function renderTable(rows: string[][], align: Align[], width: number): string[]
285
287
  }
286
288
  }
287
289
  const pad = (s: string, w: number, a: Align) => {
288
- const gap = w - stringWidth(s);
290
+ const gap = w - visibleWidth(s);
289
291
  if (a === "right") return " ".repeat(gap) + s;
290
292
  if (a === "center") return " ".repeat(Math.floor(gap / 2)) + s + " ".repeat(Math.ceil(gap / 2));
291
293
  return s + " ".repeat(gap);
@@ -10,6 +10,16 @@ export function mentionAt(value: string, cursor: number, triggers: readonly stri
10
10
  return { trigger: m[1]!, start: cursor - m[2]!.length - m[1]!.length, query: m[2]!.replace(/^"/, "") };
11
11
  }
12
12
 
13
+ /**
14
+ * 输入的是 ../、./、~/、/ 或盘符开头的路径时,最后一个 / 之前的部分(含 /,反斜杠换成 /):候选改成现列这个目录下一层。
15
+ * 预先列好的候选只有工作目录里的相对路径,这些路径在里面找不到。其他情况返回 undefined
16
+ */
17
+ export function mentionDir(query: string): string | undefined {
18
+ const q = query.replaceAll("\\", "/");
19
+ if (!/^(\.{1,2}\/|~\/|\/|[A-Za-z]:\/)/.test(q)) return undefined;
20
+ return q.slice(0, q.lastIndexOf("/") + 1);
21
+ }
22
+
13
23
  /** 补全后的文本:触发字符加候选,含空白的加引号 */
14
24
  export const mentionText = (trigger: string, p: string) => (/\s/.test(p) ? `${trigger}"${p}"` : `${trigger}${p}`);
15
25
 
@@ -13,8 +13,6 @@ export type Notice = Parameters<Parameters<Runtime["subscribe"]>[0]>[0];
13
13
  export interface TranscriptOptions {
14
14
  screen: Screen;
15
15
  cwd: string;
16
- /** 子 Agent 的用量在它自己的日志里,从这里读;不给就不统计子 Agent 的用量 */
17
- readLog?(sessionId: string): Promise<LogEvent[]>;
18
16
  /** 模型的上下文窗口(状态栏显示用) */
19
17
  contextWindow(): number;
20
18
  /** 每次回复的输出上限(回复被截断时的提示用);没有时说是服务的默认值 */
@@ -80,16 +78,12 @@ export function transcript(opts: TranscriptOptions): Transcript {
80
78
  if (u) screen.status({ spent: { input: usage.inputTokens, output: usage.outputTokens } });
81
79
  };
82
80
  /**
83
- * 一个事件带来的用量:模型回复;插件事件 data 里的 usage(压缩时的总结调用、auto 模式的审查这类插件自己发的请求);
84
- * 子 Agent 的用量在它自己的日志里(读不到时不算,不让一个读失败变成没人处理的 rejection)
81
+ * 一个事件带来的用量:模型回复;插件事件 data 里的 usage(压缩时的总结调用、auto 模式的审查这类插件自己发的请求,
82
+ * 还有 jade/task 记下的子 Agent 的用量)
85
83
  */
86
- async function countUsage(e: LogEvent) {
84
+ function countUsage(e: LogEvent) {
87
85
  if (e.type === "model.responded") addUsage((e as LogEvent<"model.responded">).data.usage);
88
86
  else if (e.origin.by === "plugin") addUsage(usageOf((e.data as { usage?: unknown } | null)?.usage));
89
- else if (e.type === "tool.completed") {
90
- const child = (e as LogEvent<"tool.completed">).data.child;
91
- if (child && opts.readLog) for (const c of await opts.readLog(child.sessionId).catch(() => [])) await countUsage(c);
92
- }
93
87
  }
94
88
 
95
89
  /**
@@ -220,10 +214,14 @@ export function transcript(opts: TranscriptOptions): Transcript {
220
214
  const shown = (t: string) => (t.startsWith("/") ? cyan(`› ${t}`) : `\n${bold(`› ${t.replace(/\n/g, "\n ")}`)}`);
221
215
  // 很长的输入(粘贴的日志)只显示开头几行,其余折叠起来,点击或 ctrl+o 展开
222
216
  const lines = text.split("\n");
223
- if (lines.length <= MAX_ECHO_LINES) return screen.log(shown(text));
224
- // 展开时接着显示其余的行
225
- const rest = lines.slice(ECHO_HEAD_LINES);
226
- screen.log(`${shown(lines.slice(0, ECHO_HEAD_LINES).join("\n"))}\n ${dim(`… +${rest.length} lines`)}`, { details: rest.map((l) => ` ${l}`).join("\n") });
217
+ if (lines.length <= MAX_ECHO_LINES) screen.log(shown(text));
218
+ else {
219
+ // 展开时接着显示其余的行
220
+ const rest = lines.slice(ECHO_HEAD_LINES);
221
+ screen.log(`${shown(lines.slice(0, ECHO_HEAD_LINES).join("\n"))}\n ${dim(`… +${rest.length} lines`)}`, { details: rest.map((l) => ` ${l}`).join("\n") });
222
+ }
223
+ // 消息前后都空一行,和上一段、下一段回复分开(只空前面的话,消息看起来像是下面回复的标题)
224
+ if (!text.startsWith("/")) screen.log("");
227
225
  },
228
226
  reset() {
229
227
  for (const k of Object.keys(usage) as (keyof Usage)[]) usage[k] = 0;
@@ -307,7 +305,7 @@ export function transcript(opts: TranscriptOptions): Transcript {
307
305
  return;
308
306
  case "model.responded": {
309
307
  const d = e.data as EventDataMap["model.responded"];
310
- void countUsage(e);
308
+ countUsage(e);
311
309
  showContext(e as LogEvent<"model.responded">);
312
310
  if (!replaying) finishSpeed(d.usage);
313
311
  for (const b of d.content) if (b.kind === "tool_use") toolNames.set(b.id, b.name);
@@ -366,7 +364,6 @@ export function transcript(opts: TranscriptOptions): Transcript {
366
364
  }
367
365
  case "tool.completed": {
368
366
  const d = e.data as EventDataMap["tool.completed"];
369
- void countUsage(e);
370
367
  activity("Working");
371
368
  doneProgress(d.toolUseId);
372
369
  const call = calls.get(d.toolUseId);
@@ -437,7 +434,7 @@ export function transcript(opts: TranscriptOptions): Transcript {
437
434
  */
438
435
  function renderPluginEvent(e: LogEvent) {
439
436
  if (e.origin.by !== "plugin") return;
440
- void countUsage(e);
437
+ countUsage(e);
441
438
  const found = opts.eventRenderer?.(e.type);
442
439
  if (!found) return renderPluginNotice(e);
443
440
  let shown: ReturnType<EventRenderer["render"]>;
@@ -463,7 +460,7 @@ export function transcript(opts: TranscriptOptions): Transcript {
463
460
  async function replay(events: LogEvent[], show: boolean) {
464
461
  if (!show) {
465
462
  for (const e of events) {
466
- await countUsage(e);
463
+ countUsage(e);
467
464
  if (e.type === "model.responded") showContext(e as LogEvent<"model.responded">);
468
465
  }
469
466
  return;
@@ -24,8 +24,8 @@ import {
24
24
  useState,
25
25
  useSyncExternalStore,
26
26
  } from "./vendor.ts";
27
- import stringWidth from "string-width";
28
- import { mentionAt, mentionText, rankPaths } from "./mentions.ts";
27
+ import { visibleWidth } from "./width.ts";
28
+ import { mentionAt, mentionDir, mentionText, rankPaths } from "./mentions.ts";
29
29
  import { charWidth, edit, empty, layout, moveRow, offsetAt, type EditState } from "./editor.ts";
30
30
  import { expandTabs, markdownStream, softInfo, visibleRow, wrapRows, type MdLine } from "./markdown.ts";
31
31
  import { cells, FRAME_MS, Mascot, moodOf, nextChange, title } from "./mascot.ts";
@@ -58,7 +58,7 @@ const RESIZE_SETTLE_MS = 100;
58
58
  const RESIZE_FRAME_MS = 200;
59
59
  /**
60
60
  * 整帧重画之前先停这么久不画:要比 Ink 的帧间隔(30fps,约 33ms)长,
61
- * 重画那次提交才会马上画出来(节流的第一下),而不是被推迟、和下一次提交合并掉
61
+ * 重画那次提交多半能马上画出来(节流的第一下)。停的时候别的组件照样可能提交,所以不能靠它保证画出来(见 Store.drawn)
62
62
  */
63
63
  const REPAINT_GAP_MS = 40;
64
64
  /** 宽度变了之后在后台重新折行,每批折这么多项 */
@@ -75,8 +75,8 @@ export interface TuiHandlers {
75
75
  exit(): void;
76
76
  /** 登记了的补全(completions@1):触发字符、占位提示里的说明、候选菜单下的说明;每次渲染时取 */
77
77
  completions?(): CompletionInfo[];
78
- /** 打了触发字符时的候选(像路径一样用 / 分层,目录以 / 结尾);每次开始输入一段新的补全时取一次 */
79
- complete?(trigger: string): Promise<string[]>;
78
+ /** 打了触发字符时的候选(像路径一样用 / 分层,目录以 / 结尾);每次开始输入一段新的补全时取一次,dir 见 mentionDir */
79
+ complete?(trigger: string, dir?: string): Promise<string[]>;
80
80
  /** 输入框有焦点时按下 jade 自己不用的 ctrl+<字母>、alt+<字母或数字>、shift+tab(见 keySpec);返回 true 表示有插件处理了 */
81
81
  key?(spec: string): boolean;
82
82
  }
@@ -187,12 +187,12 @@ const elapsed = (t: Thinking) =>
187
187
 
188
188
  /** 按显示宽度取 text 末尾最多 cols 列;截掉了开头时以 … 开头 */
189
189
  export function tail(text: string, cols: number): string {
190
- if (stringWidth(text) <= cols) return text;
190
+ if (visibleWidth(text) <= cols) return text;
191
191
  const chars = [...text];
192
192
  let out = "";
193
193
  let w = 1;
194
194
  for (let i = chars.length - 1; i >= 0; i--) {
195
- const cw = stringWidth(chars[i]!);
195
+ const cw = visibleWidth(chars[i]!);
196
196
  if (w + cw > cols) break;
197
197
  out = chars[i] + out;
198
198
  w += cw;
@@ -213,7 +213,7 @@ function thinkingRow(t: Thinking, width: number): string {
213
213
  ?.trim()
214
214
  .replace(/\s+/g, " ");
215
215
  // 留出 " · "、" ▸" 和一列余量
216
- const room = width - stringWidth(label) - 6;
216
+ const room = width - visibleWidth(label) - 6;
217
217
  return dim(latest && room >= 8 ? `${label} · ${tail(latest, room)}` : `${label}…`);
218
218
  }
219
219
 
@@ -328,6 +328,25 @@ export class Store {
328
328
  this.update({ ...patch, repaint: true }, true);
329
329
  }
330
330
 
331
+ /** 已经提交给 Ink、还没画出来的界面里有整帧重画(App 渲染时标上) */
332
+ #repaintPending = false;
333
+ repaintInTree() {
334
+ this.#repaintPending = true;
335
+ }
336
+
337
+ /**
338
+ * Ink 画了一帧(render 的 onRender,算好输出、写出去之前)。画的是比终端高的那次,就可以恢复了。
339
+ * 不能在提交之后马上恢复:Ink 每 33ms 最多画一帧,这次提交可能还压在节流里,
340
+ * 恢复的提交赶在它画出来之前,Ink 就只画恢复后的样子,等于没重画。
341
+ * 光靠重画前停一下(REPAINT_GAP_MS)躲不开:停的时候别的组件自己的状态变了照样会提交、照样占着节流。
342
+ * 恢复不马上画:这一轮里别的组件跟着改的状态(量出来的高度)和恢复合在同一次提交里,不会再画一帧比终端高的
343
+ */
344
+ drawn = () => {
345
+ if (!this.#repaintPending) return;
346
+ this.#repaintPending = false;
347
+ this.update({ repaint: false });
348
+ };
349
+
331
350
  /** 追加普通的行;带 item 时 texts 合成一项(可折叠、可以之后补充),texts 是收起时显示的部分 */
332
351
  append(texts: string[], item?: Omit<Line, "text">) {
333
352
  if (texts.length === 0) return;
@@ -682,6 +701,7 @@ export function tuiScreen(opts: TuiOptions): Screen {
682
701
  alternateScreen: true,
683
702
  // 全屏每帧只重写变化的行
684
703
  incrementalRendering: true,
704
+ onRender: store.drawn,
685
705
  ...(opts.io
686
706
  ? { ...opts.io, interactive: true, patchConsole: false }
687
707
  : {}),
@@ -1136,11 +1156,8 @@ function App({
1136
1156
  // 窗口停止缩放后和按 Ctrl+L 时整帧重画一次(见 Store.repaint)。
1137
1157
  // 启动时不重画:第一帧之前已经清屏、光标在左上角;整帧重画在不支持同步输出的终端上(Windows 上常见)看得出闪一下
1138
1158
  const repaint = state.repaint === true;
1139
- // 整帧重画那次提交已经马上画出来了(见 Store.repaint),下一次提交就恢复;
1140
- // 这一轮里别的组件跟着改的状态(量出来的高度)和恢复合在同一次提交里,不会再画一帧比终端高的
1141
- useEffect(() => {
1142
- if (repaint) store.update({ repaint: false });
1143
- }, [repaint]);
1159
+ // 这次提交的界面比终端高;等 Ink 真的把它画出来再恢复(见 Store.drawn)
1160
+ if (repaint) store.repaintInTree();
1144
1161
 
1145
1162
  useInput((input, key) => {
1146
1163
  if (key.ctrl && input === "l") return store.repaint();
@@ -1405,7 +1422,7 @@ const TONE: Record<NonNullable<StatusSegment["tone"]>, string> = { ok: "green",
1405
1422
  export function fitSegments(segments: Segment[], width: number): Segment[] {
1406
1423
  const kept = segments.map((s) => ({ ...s }));
1407
1424
  const total = () =>
1408
- kept.reduce((n, s, i) => n + stringWidth(s.text) + (i ? 3 : 0), 0);
1425
+ kept.reduce((n, s, i) => n + visibleWidth(s.text) + (i ? 3 : 0), 0);
1409
1426
  const steps = kept
1410
1427
  .flatMap((s) => [
1411
1428
  ...(s.short !== undefined && s.shortAt !== undefined
@@ -1500,7 +1517,7 @@ function StatusBar({ status, width }: { status: StatusInfo; width: number }) {
1500
1517
  /** 一行提示:按宽度选第一个放得下的写法,都放不下时用最后一个并截断 */
1501
1518
  function Hint({ variants, width }: { variants: string[]; width: number }) {
1502
1519
  const text =
1503
- variants.find((v) => stringWidth(v) <= width) ?? variants.at(-1)!;
1520
+ variants.find((v) => visibleWidth(v) <= width) ?? variants.at(-1)!;
1504
1521
  return h(Text, { dimColor: true, wrap: "truncate-end" }, text);
1505
1522
  }
1506
1523
 
@@ -1825,19 +1842,20 @@ function Prompt({
1825
1842
  const notice = getNotice();
1826
1843
 
1827
1844
  const mentioning = mention?.trigger;
1828
- // 每次开始输入一段新的补全时重新取一次:候选可能已经变了(例如文件)
1845
+ const mentionScope = mention ? mentionDir(mention.query) : undefined;
1846
+ // 每次开始输入一段新的补全、或者在工作目录外换了目录时重新取一次:候选可能已经变了(例如文件)
1829
1847
  useEffect(() => {
1830
1848
  if (mentioning === undefined || !handlers.complete) return;
1831
1849
  let live = true;
1832
1850
  setPaths([]);
1833
- handlers.complete(mentioning).then(
1851
+ handlers.complete(mentioning, mentionScope).then(
1834
1852
  (p) => void (live && setPaths(p)),
1835
1853
  () => {},
1836
1854
  );
1837
1855
  return () => {
1838
1856
  live = false;
1839
1857
  };
1840
- }, [mentioning]);
1858
+ }, [mentioning, mentionScope]);
1841
1859
  const completion = completions.find((c) => c.trigger === mentioning);
1842
1860
  // 结果多时只显示选中项附近的几条
1843
1861
  const first = around(hit, results.length, menuRows);