@uncarved/jade 0.4.0 → 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 (58) hide show
  1. package/README.md +279 -278
  2. package/dist/api.d.ts +1 -1
  3. package/dist/api.js +1 -1
  4. package/dist/session.js +16 -3
  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 +61 -3
  10. package/plugins/models/index.ts +62 -5
  11. package/plugins/models/plugin.json +1 -1
  12. package/plugins/models/provider.ts +55 -9
  13. package/plugins/models/saved.ts +1 -1
  14. package/plugins/prompts/index.ts +0 -0
  15. package/plugins/schedule/index.ts +3 -1
  16. package/plugins/screenshot/browser.ts +1 -1
  17. package/plugins/shell/index.ts +8 -4
  18. package/plugins/shell/plugin.json +2 -1
  19. package/plugins/shell/shell.ts +33 -7
  20. package/plugins/steer/index.ts +1 -1
  21. package/plugins/todo/index.ts +6 -10
  22. package/plugins/tui/frontend.ts +6 -2
  23. package/plugins/tui/markdown.ts +10 -8
  24. package/plugins/tui/mentions.ts +10 -0
  25. package/plugins/tui/transcript.ts +14 -17
  26. package/plugins/tui/tui.ts +13 -12
  27. package/plugins/tui/width.ts +240 -0
  28. package/plugins/undo/checkpoint.ts +3 -1
  29. package/plugins/undo/index.ts +132 -22
  30. package/plugins/undo/plugin.json +1 -0
  31. package/plugins/undo/snapshot.ts +87 -14
  32. package/plugins-dist/mentions/candidates.js +6 -0
  33. package/plugins-dist/mentions/index.js +2 -2
  34. package/plugins-dist/models/configure.js +51 -2
  35. package/plugins-dist/models/index.js +58 -4
  36. package/plugins-dist/models/plugin.json +2 -1
  37. package/plugins-dist/models/provider.js +43 -8
  38. package/plugins-dist/models/saved.js +1 -1
  39. package/plugins-dist/prompts/index.js +6 -1
  40. package/plugins-dist/schedule/index.js +1 -0
  41. package/plugins-dist/screenshot/browser.js +1 -1
  42. package/plugins-dist/shell/index.js +12 -10
  43. package/plugins-dist/shell/plugin.json +2 -1
  44. package/plugins-dist/shell/shell.js +21 -7
  45. package/plugins-dist/steer/index.js +1 -1
  46. package/plugins-dist/todo/index.js +3 -8
  47. package/plugins-dist/tui/frontend.js +5 -2
  48. package/plugins-dist/tui/markdown.js +11 -9
  49. package/plugins-dist/tui/mentions.js +6 -0
  50. package/plugins-dist/tui/transcript.js +9 -12
  51. package/plugins-dist/tui/tui.js +10 -9
  52. package/plugins-dist/tui/width.js +219 -0
  53. package/plugins-dist/undo/checkpoint.js +3 -1
  54. package/plugins-dist/undo/index.js +111 -15
  55. package/plugins-dist/undo/plugin.json +3 -0
  56. package/plugins-dist/undo/snapshot.js +62 -11
  57. package/src/api.ts +1 -1
  58. package/src/session.ts +13 -3
@@ -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());
@@ -258,6 +261,40 @@ export function visionFromEnv(env: Env = process.env): boolean {
258
261
  throw new Error(`JADE_VISION must be on or off, got ${JSON.stringify(env.JADE_VISION)}`);
259
262
  }
260
263
 
264
+ /** 地址是不是 Anthropic 官方的(没设地址时用的也是官方的) */
265
+ export function isOfficialAnthropic(baseURL: string | undefined): boolean {
266
+ if (!baseURL?.trim()) return true;
267
+ try {
268
+ return new URL(baseURL).host === "api.anthropic.com";
269
+ } catch {
270
+ return false;
271
+ }
272
+ }
273
+
274
+ /**
275
+ * JADE_FALLBACKS:Claude 因安全策略拒绝时,由服务端换模型重试。不设时只对官方地址开启:
276
+ * 中转站多半不认这个字段,整个请求返回 400
277
+ */
278
+ export function fallbacksFromEnv(env: Env = process.env): boolean {
279
+ const text = env.JADE_FALLBACKS?.trim().toLowerCase();
280
+ if (!text) return isOfficialAnthropic(env.ANTHROPIC_BASE_URL);
281
+ if (["1", "true", "on", "yes"].includes(text)) return true;
282
+ if (["0", "false", "off", "no"].includes(text)) return false;
283
+ throw new Error(`JADE_FALLBACKS must be on or off, got ${JSON.stringify(env.JADE_FALLBACKS)}`);
284
+ }
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
+
261
298
  /** JADE_EFFORT;不设时 Claude 用 high,OpenAI 用服务端默认值 */
262
299
  export function effortFromEnv(env: Env = process.env): string | undefined {
263
300
  const effort = env.JADE_EFFORT;
@@ -304,9 +341,12 @@ export function providerInfo(env: Env = process.env): ProviderInfo {
304
341
  * JADE_RPM 是每分钟最多发几个请求,见 rpmFromEnv(限速在 withRetry 的 gate 里做)
305
342
  * JADE_IDLE_TIMEOUT 是等模型服务回数据的时限,见 idleTimeoutFromEnv
306
343
  * JADE_VISION 是模型能不能看图片,见 visionFromEnv
307
- * 只导入用到的那个服务的包:Anthropic 的 SDK 加载要一百多毫秒,拖慢启动
344
+ * JADE_FALLBACKS 是 Claude 被安全策略拒绝时要不要服务端换模型重试,见 fallbacksFromEnv
345
+ * JADE_THINKING 是 Anthropic 格式的请求里带不带 thinking,见 thinkingFromEnv
346
+ * 只导入用到的那个服务的包:Anthropic 的 SDK 加载要一百多毫秒,拖慢启动。
347
+ * headers 合并进每次请求(User-Agent 标明是 jade:有的服务按它在用量里区分客户端)
308
348
  */
309
- 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> {
310
350
  const kind = providerKind(env);
311
351
  if (!isBuiltinKind(kind)) throw new Error(`JADE_PROVIDER must be one of ${PROVIDER_KINDS.join(", ")}, got ${JSON.stringify(kind)}`);
312
352
  const maxTokens = env.JADE_MAX_TOKENS ? parseTokens("JADE_MAX_TOKENS", env.JADE_MAX_TOKENS) : undefined;
@@ -328,6 +368,7 @@ export async function providerFromEnv(env: Env = process.env): Promise<Provider>
328
368
  reasoning: effort ? { effort: effort as "minimal" | "low" | "medium" | "high", summary: "auto" } : undefined,
329
369
  idleTimeoutMs,
330
370
  toolResultImages,
371
+ headers,
331
372
  });
332
373
  }
333
374
  if (kind === "openai-compat") {
@@ -342,6 +383,7 @@ export async function providerFromEnv(env: Env = process.env): Promise<Provider>
342
383
  extraBody: env.OPENAI_COMPAT_EXTRA_BODY ? jsonObject("OPENAI_COMPAT_EXTRA_BODY", env.OPENAI_COMPAT_EXTRA_BODY) : undefined,
343
384
  idleTimeoutMs,
344
385
  toolResultImages,
386
+ headers,
345
387
  });
346
388
  }
347
389
  const { anthropicProvider } = await import("@uncarved/provider-anthropic");
@@ -350,8 +392,12 @@ export async function providerFromEnv(env: Env = process.env): Promise<Provider>
350
392
  apiKey: env.ANTHROPIC_API_KEY,
351
393
  baseURL: env.ANTHROPIC_BASE_URL ?? "https://api.anthropic.com",
352
394
  model: env.ANTHROPIC_MODEL,
353
- 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,
354
397
  maxTokens,
398
+ fallbacks: fallbacksFromEnv(env),
399
+ thinking: thinkingFromEnv(env),
400
+ headers,
355
401
  });
356
402
  }
357
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", "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;
Binary file
@@ -285,7 +285,9 @@ export default definePlugin({
285
285
  .finally(() => running.delete(t.id));
286
286
  }
287
287
  };
288
- // 不在这里立即检查:session() 执行时会话还没建好,这时 send 会失败,认领了的任务就丢了
288
+ // 会话建好就先检查一次:jade 没开着的时候到期的任务不用等第一个间隔。
289
+ // 不直接在这里检查:会话没能打开时排着的 send 被拒绝,认领了的任务就丢了;afterTurn 等会话建好才执行
290
+ ctx.session.afterTurn(() => void check());
289
291
  await ctx.effect(() => {
290
292
  const timer = setInterval(() => void check(), every);
291
293
  return () => clearInterval(timer);
@@ -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 之后等网络安静下来(脚本、图片、字体)的最长时间 */
@@ -2,7 +2,7 @@
2
2
  // 后台命令自己结束时告诉用户,并给模型留一句说明(不用它一直轮询);/shells 给用户看和停掉后台命令。
3
3
 
4
4
  import { definePlugin, type Span, type UI } from "@uncarved/jade-api";
5
- import type { Commands, Prompts, Renderers } from "@uncarved/jade-api/services";
5
+ import type { Commands, Prompts, Renderers, Undo } from "@uncarved/jade-api/services";
6
6
  import { shellRenderers } from "./renderers.ts";
7
7
  import { shellService } from "./service.ts";
8
8
  import { shellTools, type ShellTools } from "./shell.ts";
@@ -50,8 +50,9 @@ export default definePlugin({
50
50
  let live = "";
51
51
  let r: { code: number | null; output: string; timedOut: boolean };
52
52
  let stopped = false;
53
- try {
54
- r = await shell.run(command, {
53
+ const session = manager.current;
54
+ const exec = () =>
55
+ shell.run(command, {
55
56
  cwd: ctx.cwd,
56
57
  timeoutMs: SH_TIMEOUT_MS,
57
58
  signal,
@@ -60,6 +61,10 @@ export default definePlugin({
60
61
  progress?.(live);
61
62
  },
62
63
  });
64
+ // 有 undo@1 时这条命令改的文件能用 /undo 撤销(单独算一步)
65
+ const undo = ctx.service<Undo>("undo@1");
66
+ try {
67
+ r = session && undo ? await undo.track(session.id, `$ ${firstLine(command)}`, exec) : await exec();
63
68
  } catch (e) {
64
69
  if (!signal.aborted) throw e;
65
70
  stopped = true;
@@ -73,7 +78,6 @@ export default definePlugin({
73
78
  const more = lines.length > 1 ? ` (+${lines.length - 1} lines)` : "";
74
79
  const folded = lines.length > 1 || first.length > SH_SUMMARY;
75
80
  print(shade(failed, `⎿ ${first.length > SH_SUMMARY ? `${first.slice(0, SH_SUMMARY)}…` : first}${more}`), folded ? { details: r.output.replace(/^/gm, " ") } : undefined);
76
- const session = manager.current;
77
81
  if (!stopped && session && session.state.messages.length > 0) return { prompt: `I ran this shell command myself (${status}):\n$ ${command}\n${r.output}` };
78
82
  if (session) ctx.service<Prompts>("prompts@1")?.note(session.id, `The user ran this shell command themselves (${status}):\n$ ${command}\n${r.output}`);
79
83
  },
@@ -8,7 +8,8 @@
8
8
  "ui@1",
9
9
  "prompts@1",
10
10
  "renderers@1",
11
- "commands@1"
11
+ "commands@1",
12
+ "undo@1"
12
13
  ],
13
14
  "config": {
14
15
  "shell": {
@@ -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";
@@ -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
 
@@ -1405,7 +1405,7 @@ const TONE: Record<NonNullable<StatusSegment["tone"]>, string> = { ok: "green",
1405
1405
  export function fitSegments(segments: Segment[], width: number): Segment[] {
1406
1406
  const kept = segments.map((s) => ({ ...s }));
1407
1407
  const total = () =>
1408
- kept.reduce((n, s, i) => n + stringWidth(s.text) + (i ? 3 : 0), 0);
1408
+ kept.reduce((n, s, i) => n + visibleWidth(s.text) + (i ? 3 : 0), 0);
1409
1409
  const steps = kept
1410
1410
  .flatMap((s) => [
1411
1411
  ...(s.short !== undefined && s.shortAt !== undefined
@@ -1500,7 +1500,7 @@ function StatusBar({ status, width }: { status: StatusInfo; width: number }) {
1500
1500
  /** 一行提示:按宽度选第一个放得下的写法,都放不下时用最后一个并截断 */
1501
1501
  function Hint({ variants, width }: { variants: string[]; width: number }) {
1502
1502
  const text =
1503
- variants.find((v) => stringWidth(v) <= width) ?? variants.at(-1)!;
1503
+ variants.find((v) => visibleWidth(v) <= width) ?? variants.at(-1)!;
1504
1504
  return h(Text, { dimColor: true, wrap: "truncate-end" }, text);
1505
1505
  }
1506
1506
 
@@ -1825,19 +1825,20 @@ function Prompt({
1825
1825
  const notice = getNotice();
1826
1826
 
1827
1827
  const mentioning = mention?.trigger;
1828
- // 每次开始输入一段新的补全时重新取一次:候选可能已经变了(例如文件)
1828
+ const mentionScope = mention ? mentionDir(mention.query) : undefined;
1829
+ // 每次开始输入一段新的补全、或者在工作目录外换了目录时重新取一次:候选可能已经变了(例如文件)
1829
1830
  useEffect(() => {
1830
1831
  if (mentioning === undefined || !handlers.complete) return;
1831
1832
  let live = true;
1832
1833
  setPaths([]);
1833
- handlers.complete(mentioning).then(
1834
+ handlers.complete(mentioning, mentionScope).then(
1834
1835
  (p) => void (live && setPaths(p)),
1835
1836
  () => {},
1836
1837
  );
1837
1838
  return () => {
1838
1839
  live = false;
1839
1840
  };
1840
- }, [mentioning]);
1841
+ }, [mentioning, mentionScope]);
1841
1842
  const completion = completions.find((c) => c.trigger === mentioning);
1842
1843
  // 结果多时只显示选中项附近的几条
1843
1844
  const first = around(hit, results.length, menuRows);