@uncarved/jade 0.4.2 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +39 -1
  2. package/dist/api.d.ts +1 -1
  3. package/dist/api.js +1 -1
  4. package/dist/session.d.ts +4 -2
  5. package/dist/session.js +54 -6
  6. package/dist/session.js.map +1 -1
  7. package/package.json +4 -4
  8. package/plugins/budget/index.ts +54 -4
  9. package/plugins/budget/plugin.json +1 -1
  10. package/plugins/keys/index.ts +2 -2
  11. package/plugins/memory/index.ts +6 -4
  12. package/plugins/memory/memory.ts +101 -31
  13. package/plugins/models/index.ts +67 -9
  14. package/plugins/models/provider.ts +81 -24
  15. package/plugins/prompts/prompts.ts +1 -0
  16. package/plugins/screenshot/index.ts +2 -1
  17. package/plugins/screenshot/tool.ts +1 -1
  18. package/plugins/serve/index.ts +229 -0
  19. package/plugins/serve/plugin.json +8 -0
  20. package/plugins/shell/index.ts +35 -1
  21. package/plugins/shell/shell.ts +5 -0
  22. package/plugins/task/index.ts +3 -1
  23. package/plugins/task/subagent.ts +49 -3
  24. package/plugins/tui/frontend.ts +73 -4
  25. package/plugins/tui/screen.ts +23 -0
  26. package/plugins/tui/tui.ts +199 -17
  27. package/plugins-dist/budget/index.js +43 -2
  28. package/plugins-dist/budget/plugin.json +1 -1
  29. package/plugins-dist/keys/index.js +1 -1
  30. package/plugins-dist/memory/index.js +7 -3
  31. package/plugins-dist/memory/memory.js +81 -34
  32. package/plugins-dist/models/index.js +62 -7
  33. package/plugins-dist/models/provider.js +47 -14
  34. package/plugins-dist/prompts/prompts.js +1 -0
  35. package/plugins-dist/screenshot/index.js +1 -1
  36. package/plugins-dist/screenshot/tool.js +1 -1
  37. package/plugins-dist/serve/index.js +238 -0
  38. package/plugins-dist/serve/plugin.json +14 -0
  39. package/plugins-dist/shell/index.js +33 -0
  40. package/plugins-dist/shell/shell.js +3 -0
  41. package/plugins-dist/task/index.js +3 -1
  42. package/plugins-dist/task/subagent.js +47 -2
  43. package/plugins-dist/tui/frontend.js +67 -3
  44. package/plugins-dist/tui/screen.js +3 -0
  45. package/plugins-dist/tui/tui.js +145 -13
  46. package/src/api.ts +1 -1
  47. package/src/session.ts +57 -5
@@ -49,6 +49,20 @@ export interface CompletionInfo {
49
49
  hint?: string;
50
50
  }
51
51
 
52
+ /** 后台的一件事(UI.job 登记的子 Agent、后台命令) */
53
+ export interface JobInfo {
54
+ id: number;
55
+ kind: string;
56
+ title: string;
57
+ status: string;
58
+ /** 不再在运行 */
59
+ done: boolean;
60
+ /** 输出的末尾一段,可以带 ANSI 颜色 */
61
+ output: string;
62
+ /** 用户停掉它;没有时不能停 */
63
+ stop?(): void;
64
+ }
65
+
52
66
  export interface Screen {
53
67
  /** 能向用户提问;为 false 时 select / input 直接返回 undefined */
54
68
  readonly interactive: boolean;
@@ -63,6 +77,8 @@ export interface Screen {
63
77
  * 纯文本输出另起一行缩进显示。找不到那一项时也是另起一行
64
78
  */
65
79
  amend(id: string, text: string, opts?: { details?: string }): void;
80
+ /** 能改写的一行:第一次用这个 id 时追加,之后用同一个 id 原地改写成 text。只有终端界面有 */
81
+ note?(id: string, text: string): void;
66
82
  /**
67
83
  * 正在运行的工具 id 的一行进度(已经排好版);undefined 表示工具结束了。
68
84
  * 终端界面只在对话最后显示每个工具最新的一行,结束时去掉;纯文本输出逐行打印。
@@ -84,6 +100,10 @@ export interface Screen {
84
100
  input(title: string, opts?: { initial?: string; mask?: boolean; placeholder?: string; signal?: AbortSignal }): Promise<string | undefined>;
85
101
  /** 输入框里还没提交的文字和灰色提示(插件的 ctx.input 用);只有终端界面有 */
86
102
  readonly draft?: { text(): string; insert(text: string): void; set(text: string): void; hint(text: string | undefined): void };
103
+ /** 后台的事(当前会话的全部,按登记的先后);只有终端界面有 */
104
+ jobs?(jobs: JobInfo[]): void;
105
+ /** 打开后台的事的列表(同 ctrl+t);只有终端界面有 */
106
+ showJobs?(): void;
87
107
  /** 把文字放进系统剪贴板(OSC 52);只有终端界面有 */
88
108
  copy?(text: string): void;
89
109
  /** 把终端让出来执行 fn(例如启动 $EDITOR),结束后重新接管、重画界面;只有终端界面有 */
@@ -178,6 +198,9 @@ export function safeScreen(screen: Screen): Screen {
178
198
  interactive: screen.interactive,
179
199
  log: (text, o) => screen.log(s(text), o && { ...o, details: opt(o.details) }),
180
200
  amend: (id, text, o) => screen.amend(id, s(text), o && { ...o, details: opt(o.details) }),
201
+ ...(screen.note ? { note: (id: string, text: string) => screen.note!(id, s(text)) } : {}),
202
+ ...(screen.jobs ? { jobs: (jobs: JobInfo[]) => screen.jobs!(jobs.map((j) => ({ ...j, title: s(j.title), status: s(j.status), output: s(j.output) }))) } : {}),
203
+ ...(screen.showJobs ? { showJobs: () => screen.showJobs!() } : {}),
181
204
  progress: (id, line, o) => screen.progress(id, opt(line), o),
182
205
  stream: (kind, text) => {
183
206
  // 上一段末尾没完的转义序列接到这一段前面再过滤,不然它被拆成两半,后一半当成文字显示出来
@@ -34,6 +34,7 @@ import {
34
34
  type Choice,
35
35
  type CommandInfo,
36
36
  type CompletionInfo,
37
+ type JobInfo,
37
38
  type Screen,
38
39
  type StatusInfo,
39
40
  } from "./screen.ts";
@@ -58,7 +59,7 @@ const RESIZE_SETTLE_MS = 100;
58
59
  const RESIZE_FRAME_MS = 200;
59
60
  /**
60
61
  * 整帧重画之前先停这么久不画:要比 Ink 的帧间隔(30fps,约 33ms)长,
61
- * 重画那次提交才会马上画出来(节流的第一下),而不是被推迟、和下一次提交合并掉
62
+ * 重画那次提交多半能马上画出来(节流的第一下)。停的时候别的组件照样可能提交,所以不能靠它保证画出来(见 Store.drawn)
62
63
  */
63
64
  const REPAINT_GAP_MS = 40;
64
65
  /** 宽度变了之后在后台重新折行,每批折这么多项 */
@@ -108,7 +109,9 @@ type Dialog =
108
109
  mask?: boolean;
109
110
  placeholder?: string;
110
111
  resolve(v: string | undefined): void;
111
- };
112
+ }
113
+ /** 后台的事的列表(ctrl+t):不是提问,别的对话框来了先让给它们 */
114
+ | { kind: "jobs"; resolve(v: unknown): void };
112
115
 
113
116
  interface UiState {
114
117
  /** 对话内容变化时递增,让界面重画 */
@@ -124,6 +127,8 @@ interface UiState {
124
127
  progress: { id: string; line: string }[];
125
128
  queued: string[];
126
129
  dialogs: Dialog[];
130
+ /** 后台的事(子 Agent、后台命令),ctrl+t 打开列表 */
131
+ jobs: JobInfo[];
127
132
  status: StatusInfo;
128
133
  /** 插件设置的灰色提示(ctx.input.hint):输入框为空时显示,Tab 或 → 接受 */
129
134
  hint?: string;
@@ -278,7 +283,7 @@ export class Store {
278
283
  paused = false;
279
284
 
280
285
  constructor(status: StatusInfo, size: Size) {
281
- this.state = { version: 0, scroll: 0, progress: [], queued: [], dialogs: [], status, size };
286
+ this.state = { version: 0, scroll: 0, progress: [], queued: [], dialogs: [], jobs: [], status, size };
282
287
  }
283
288
 
284
289
  subscribe = (fn: () => void) => {
@@ -322,12 +327,38 @@ export class Store {
322
327
  this.#repaintTimer = setTimeout(() => this.#repaintNow(), REPAINT_GAP_MS);
323
328
  }
324
329
 
330
+ /** 打开后台的事的列表(ctrl+t、点状态栏、/tasks);已经开着对话框时不开 */
331
+ openJobs() {
332
+ if (this.state.dialogs.length) return;
333
+ const d: Dialog = { kind: "jobs", resolve: () => this.update({ dialogs: this.state.dialogs.filter((x) => x !== d) }, true) };
334
+ this.update({ dialogs: [...this.state.dialogs, d] }, true);
335
+ }
336
+
325
337
  #repaintNow(patch: Partial<UiState> = {}) {
326
338
  clearTimeout(this.#repaintTimer);
327
339
  this.paused = false;
328
340
  this.update({ ...patch, repaint: true }, true);
329
341
  }
330
342
 
343
+ /** 已经提交给 Ink、还没画出来的界面里有整帧重画(App 渲染时标上) */
344
+ #repaintPending = false;
345
+ repaintInTree() {
346
+ this.#repaintPending = true;
347
+ }
348
+
349
+ /**
350
+ * Ink 画了一帧(render 的 onRender,算好输出、写出去之前)。画的是比终端高的那次,就可以恢复了。
351
+ * 不能在提交之后马上恢复:Ink 每 33ms 最多画一帧,这次提交可能还压在节流里,
352
+ * 恢复的提交赶在它画出来之前,Ink 就只画恢复后的样子,等于没重画。
353
+ * 光靠重画前停一下(REPAINT_GAP_MS)躲不开:停的时候别的组件自己的状态变了照样会提交、照样占着节流。
354
+ * 恢复不马上画:这一轮里别的组件跟着改的状态(量出来的高度)和恢复合在同一次提交里,不会再画一帧比终端高的
355
+ */
356
+ drawn = () => {
357
+ if (!this.#repaintPending) return;
358
+ this.#repaintPending = false;
359
+ this.update({ repaint: false });
360
+ };
361
+
331
362
  /** 追加普通的行;带 item 时 texts 合成一项(可折叠、可以之后补充),texts 是收起时显示的部分 */
332
363
  append(texts: string[], item?: Omit<Line, "text">) {
333
364
  if (texts.length === 0) return;
@@ -682,6 +713,7 @@ export function tuiScreen(opts: TuiOptions): Screen {
682
713
  alternateScreen: true,
683
714
  // 全屏每帧只重写变化的行
684
715
  incrementalRendering: true,
716
+ onRender: store.drawn,
685
717
  ...(opts.io
686
718
  ? { ...opts.io, interactive: true, patchConsole: false }
687
719
  : {}),
@@ -731,6 +763,12 @@ export function tuiScreen(opts: TuiOptions): Screen {
731
763
  o?.details !== undefined ? { details: o.details } : undefined,
732
764
  );
733
765
  },
766
+ note(id, text) {
767
+ if (store.amend(id, (l) => void (l.text = text))) return;
768
+ flushLive(true);
769
+ store.update({ live: undefined });
770
+ store.append([text], { id });
771
+ },
734
772
  progress(id, line) {
735
773
  const rest = store.state.progress.filter((p) => p.id !== id);
736
774
  store.update({
@@ -786,6 +824,10 @@ export function tuiScreen(opts: TuiOptions): Screen {
786
824
  queued(items) {
787
825
  store.update({ queued: [...items] });
788
826
  },
827
+ jobs(jobs) {
828
+ store.update({ jobs });
829
+ },
830
+ showJobs: () => store.openJobs(),
789
831
  draft: {
790
832
  text: () => draft.current?.get() ?? "",
791
833
  insert: (text) => draft.current?.apply((s) => edit.insert(s, text.replace(/\r\n?/g, "\n"))),
@@ -1023,9 +1065,11 @@ function App({
1023
1065
  draft: DraftBridge;
1024
1066
  }) {
1025
1067
  const state = useSyncExternalStore(store.subscribe, store.get);
1026
- const dialog = state.dialogs[0];
1068
+ // 后台的事的列表只是查看:提问(审批之类)来了先显示提问
1069
+ const dialog = state.dialogs.find((d) => d.kind !== "jobs") ?? state.dialogs[0];
1027
1070
  const columns = Math.max(1, state.size.columns - 1);
1028
1071
  const rows = state.size.rows;
1072
+ const statusWidth = Math.max(10, columns - 2);
1029
1073
  const compact = rows < COMPACT_ROWS;
1030
1074
  // 运行中每一帧(FRAME_MS)整体重画一次,推动转圈和吉祥物的动画。不能让 Spinner、吉祥物自己重画:
1031
1075
  // Ink 只在输入框也跟着提交的那一帧保留光标,否则把光标藏起来,运行中光标就不见了。
@@ -1039,7 +1083,7 @@ function App({
1039
1083
  return () => clearInterval(t);
1040
1084
  }, [busy]);
1041
1085
  const now = Date.now();
1042
- const mood = moodOf({ busy: state.busy?.label, asking: dialog !== undefined, doneAt: state.doneAt }, now);
1086
+ const mood = moodOf({ busy: state.busy?.label, asking: dialog !== undefined && dialog.kind !== "jobs", doneAt: state.doneAt }, now);
1043
1087
  const mascot = useRef<Mascot>(undefined);
1044
1088
  mascot.current ??= new Mascot();
1045
1089
  const showBot = !compact && columns >= 50;
@@ -1136,18 +1180,22 @@ function App({
1136
1180
  // 窗口停止缩放后和按 Ctrl+L 时整帧重画一次(见 Store.repaint)。
1137
1181
  // 启动时不重画:第一帧之前已经清屏、光标在左上角;整帧重画在不支持同步输出的终端上(Windows 上常见)看得出闪一下
1138
1182
  const repaint = state.repaint === true;
1139
- // 整帧重画那次提交已经马上画出来了(见 Store.repaint),下一次提交就恢复;
1140
- // 这一轮里别的组件跟着改的状态(量出来的高度)和恢复合在同一次提交里,不会再画一帧比终端高的
1141
- useEffect(() => {
1142
- if (repaint) store.update({ repaint: false });
1143
- }, [repaint]);
1183
+ // 这次提交的界面比终端高;等 Ink 真的把它画出来再恢复(见 Store.drawn)
1184
+ if (repaint) store.repaintInTree();
1144
1185
 
1145
1186
  useInput((input, key) => {
1146
1187
  if (key.ctrl && input === "l") return store.repaint();
1147
1188
  // 展开或收起最近的一项(工具结果、思考、检查报告),鼠标点不了时也能看完整内容
1148
1189
  if (key.ctrl && input === "o") return store.toggleLatest(start, view);
1190
+ // 后台的事的列表
1191
+ if (key.ctrl && input === "t") return store.openJobs();
1149
1192
  const mouse = mouseEvent(input);
1150
1193
  if (mouse) {
1194
+ // 点状态栏(界面的最后一行,比终端少一行)里后台的事那一段也能打开列表:终端自己占用了 ctrl+t 时用
1195
+ if (mouse.button === 0 && mouse.press && mouse.y === rows - 2) {
1196
+ const cols = jobsColumns(statusSegments(state.status, state.jobs, statusWidth));
1197
+ if (cols && mouse.x >= cols[0] && mouse.x <= cols[1]) return store.openJobs();
1198
+ }
1151
1199
  // 对话区里的位置;clamp 时拖出对话区停在第一行或最后一行,否则在对话区外返回 undefined
1152
1200
  const at = (clamp: boolean): Point | undefined => {
1153
1201
  const i = mouse.y - top;
@@ -1200,8 +1248,8 @@ function App({
1200
1248
  pressed.current = undefined;
1201
1249
  setSelection(undefined);
1202
1250
  }
1203
- // 选择框自己用 PgUp/PgDn 翻选项
1204
- if (dialog?.kind === "select") return;
1251
+ // 选择框自己用 PgUp/PgDn 翻选项,后台的事的列表用它翻输出
1252
+ if (dialog?.kind === "select" || dialog?.kind === "jobs") return;
1205
1253
  if (key.pageUp) store.scrollBy(page, max);
1206
1254
  else if (key.pageDown) store.scrollBy(-page, max);
1207
1255
  else if (key.ctrl && key.home) store.scrollBy(max, max);
@@ -1269,7 +1317,9 @@ function App({
1269
1317
  dialog
1270
1318
  ? dialog.kind === "select"
1271
1319
  ? h(SelectDialog, { key: dialogKey(dialog), dialog })
1272
- : h(InputDialog, { key: dialogKey(dialog), dialog })
1320
+ : dialog.kind === "jobs"
1321
+ ? h(JobsDialog, { key: dialogKey(dialog), dialog, jobs: state.jobs })
1322
+ : h(InputDialog, { key: dialogKey(dialog), dialog })
1273
1323
  : null,
1274
1324
  h(Prompt, {
1275
1325
  commands,
@@ -1286,7 +1336,7 @@ function App({
1286
1336
  place: inputPlace,
1287
1337
  onCopy: copyText,
1288
1338
  }),
1289
- h(StatusBar, { status: state.status, width: Math.max(10, columns - 2) }),
1339
+ h(StatusBar, { status: state.status, jobs: state.jobs, width: statusWidth }),
1290
1340
  ),
1291
1341
  ),
1292
1342
  ),
@@ -1396,6 +1446,8 @@ interface Segment {
1396
1446
  dropAt?: number;
1397
1447
  color?: string;
1398
1448
  dim?: boolean;
1449
+ /** 后台的事的那一段:点一下打开列表 */
1450
+ jobs?: boolean;
1399
1451
  }
1400
1452
 
1401
1453
  /** 插件段落的语义颜色怎么画 */
@@ -1422,7 +1474,8 @@ export function fitSegments(segments: Segment[], width: number): Segment[] {
1422
1474
  return kept;
1423
1475
  }
1424
1476
 
1425
- function StatusBar({ status, width }: { status: StatusInfo; width: number }) {
1477
+ /** 状态栏的内容,已经按宽度缩短 */
1478
+ function statusSegments(status: StatusInfo, jobs: JobInfo[], width: number): Segment[] {
1426
1479
  const ctx = status.context;
1427
1480
  const pct = ctx ? Math.round((ctx.used / ctx.limit) * 100) : 0;
1428
1481
  const nearFull = pct >= 80;
@@ -1440,8 +1493,11 @@ function StatusBar({ status, width }: { status: StatusInfo; width: number }) {
1440
1493
  const kept = (status.plugins ?? []).filter((p) => typeof p.text !== "string" && p.text.keep);
1441
1494
  const others = (status.plugins ?? []).filter((p) => !kept.includes(p));
1442
1495
  // 窄的时候依次:提示变短、去掉提示、用量变短、去掉缓存、模式变短、去掉用量、上下文变短、去掉速度
1496
+ const running = runningJobs(jobs);
1443
1497
  const segments: Segment[] = [
1444
1498
  ...kept.map((p) => plugin(p, true)),
1499
+ // 在后台运行的事:一直留着,窄的时候去掉按键说明
1500
+ ...(running ? [{ text: `${running} · click or ctrl+t to view`, short: running, shortAt: 6.5, color: "cyan", jobs: true }] : []),
1445
1501
  ctx
1446
1502
  ? {
1447
1503
  text: `ctx ${tokens(ctx.used)}/${tokens(ctx.limit)} (${pct}%)`,
@@ -1461,7 +1517,7 @@ function StatusBar({ status, width }: { status: StatusInfo; width: number }) {
1461
1517
  ]
1462
1518
  : []),
1463
1519
  ...(status.cache !== undefined
1464
- ? [{ text: `cache ${Math.round(status.cache * 100)}%`, dropAt: 7, dim: true }]
1520
+ ? [{ text: `cache ${Math.round(status.cache * 1000) / 10}%`, dropAt: 7, dim: true }]
1465
1521
  : []),
1466
1522
  ...(status.spent
1467
1523
  ? [
@@ -1483,7 +1539,27 @@ function StatusBar({ status, width }: { status: StatusInfo; width: number }) {
1483
1539
  dim: true,
1484
1540
  },
1485
1541
  ];
1486
- const shown = fitSegments(segments, width);
1542
+ return fitSegments(segments, width);
1543
+ }
1544
+
1545
+ /**
1546
+ * 状态栏里后台的事那一段占的列(从 0 数,含两端);没有这一段时是 undefined。
1547
+ * 照着 StatusBar 的画法算(左右各空一列、段落间是 " · "),点击的行是界面最后一行(App 里的 rows - 2):
1548
+ * 改了状态栏的位置或画法要跟着改,tui-ui 测试里点状态栏的那一条会发现
1549
+ */
1550
+ function jobsColumns(segments: Segment[]): [number, number] | undefined {
1551
+ let x = 1;
1552
+ for (const [i, s] of segments.entries()) {
1553
+ if (i) x += 3;
1554
+ const w = visibleWidth(s.text);
1555
+ if (s.jobs) return [x, x + w - 1];
1556
+ x += w;
1557
+ }
1558
+ return undefined;
1559
+ }
1560
+
1561
+ function StatusBar({ status, jobs, width }: { status: StatusInfo; jobs: JobInfo[]; width: number }) {
1562
+ const shown = statusSegments(status, jobs, width);
1487
1563
  return h(
1488
1564
  Box,
1489
1565
  { paddingX: 1 },
@@ -2416,6 +2492,112 @@ function SelectDialog({
2416
2492
  );
2417
2493
  }
2418
2494
 
2495
+ /** 还在运行的后台的事按种类计数,例如 "2 agents · 1 shell";没有时是空字符串 */
2496
+ export function runningJobs(jobs: readonly JobInfo[]): string {
2497
+ const counts = new Map<string, number>();
2498
+ for (const j of jobs) if (!j.done) counts.set(j.kind, (counts.get(j.kind) ?? 0) + 1);
2499
+ return [...counts].map(([kind, n]) => `${n} ${kind}${n > 1 ? "s" : ""}`).join(" · ");
2500
+ }
2501
+
2502
+ /** 查看一件后台的事时,输出只折最后这么多行 */
2503
+ const JOB_TAIL_LINES = 2000;
2504
+
2505
+ /**
2506
+ * 后台的事(ctrl+t):列表里选一件,enter 看它的输出(跟着最新的,PgUp/PgDn 翻看),x 停掉,esc 返回、关掉。
2507
+ * 正在看的那件被去掉了(子 Agent 交了报告)时回到列表
2508
+ */
2509
+ function JobsDialog({ dialog, jobs }: { dialog: Extract<Dialog, { kind: "jobs" }>; jobs: JobInfo[] }) {
2510
+ const selection = useContext(SelectionContext);
2511
+ const [getSelected, setSelected] = useLive(0);
2512
+ const [getViewing, setViewing] = useLive<number | undefined>(undefined);
2513
+ /** 看输出时离底部翻上去了多少行 */
2514
+ const [getBack, setBack] = useLive(0);
2515
+ const { rows, columns } = useScreenSize();
2516
+ const width = Math.max(10, columns - 4);
2517
+ const viewing = jobs.find((j) => j.id === getViewing());
2518
+ const selected = Math.min(getSelected(), Math.max(0, jobs.length - 1));
2519
+ const room = Math.max(3, rows - 14);
2520
+ // 输出折好行,只显示末尾 room 行(往上翻了 back 行)
2521
+ const lines = viewing ? wrap(viewing.output.replace(/\n+$/, "").split("\n").slice(-JOB_TAIL_LINES).join("\n"), width).map(visibleRow) : [];
2522
+ const maxBack = Math.max(0, lines.length - room);
2523
+ const back = Math.min(getBack(), maxBack);
2524
+ const scrolling = useRef({ maxBack, room });
2525
+ scrolling.current = { maxBack, room };
2526
+ useInput((input, key) => {
2527
+ if (key.ctrl && input === "c" && selection.active()) return selection.clear();
2528
+ const current = jobs.find((j) => j.id === getViewing());
2529
+ const target = current ?? jobs[Math.min(getSelected(), jobs.length - 1)];
2530
+ if (input === "x" && target && !target.done && target.stop) return target.stop();
2531
+ if (current) {
2532
+ const { maxBack, room } = scrolling.current;
2533
+ const by = (n: number) => setBack(Math.max(0, Math.min(maxBack, Math.min(getBack(), maxBack) + n)));
2534
+ if (key.pageUp) return by(room - 1);
2535
+ if (key.pageDown) return by(-(room - 1));
2536
+ if (key.upArrow || input === "k") return by(1);
2537
+ if (key.downArrow || input === "j") return by(-1);
2538
+ if (key.escape || key.leftArrow || (key.ctrl && input === "c")) {
2539
+ setBack(0);
2540
+ return setViewing(undefined);
2541
+ }
2542
+ return;
2543
+ }
2544
+ const n = jobs.length;
2545
+ if (key.upArrow || input === "k") return n && setSelected((Math.min(getSelected(), n - 1) - 1 + n) % n);
2546
+ if (key.downArrow || input === "j") return n && setSelected((Math.min(getSelected(), n - 1) + 1) % n);
2547
+ if ((key.return || key.rightArrow) && target) {
2548
+ setBack(0);
2549
+ return setViewing(target.id);
2550
+ }
2551
+ if (key.escape || (key.ctrl && input === "c")) return dialog.resolve(undefined);
2552
+ });
2553
+ const mark = (j: JobInfo) => (j.done ? h(Text, { dimColor: true }, "○ ") : h(Text, { color: "green" }, "● "));
2554
+ const canStop = (j: JobInfo | undefined) => j !== undefined && !j.done && j.stop !== undefined;
2555
+ const frame = { flexDirection: "column", borderStyle: "round", borderColor: "cyan", paddingX: 1, marginTop: 1 } as const;
2556
+ if (viewing) {
2557
+ const shown = lines.slice(lines.length - room - back, lines.length - back);
2558
+ return h(
2559
+ Box,
2560
+ frame,
2561
+ h(Text, { wrap: "truncate-end" }, mark(viewing), h(Text, { bold: true }, `${viewing.kind} · ${viewing.title}`), viewing.status ? h(Text, { dimColor: true }, ` · ${viewing.status}`) : null),
2562
+ lines.length > room + back ? h(Text, { dimColor: true }, ` ↑ ${lines.length - room - back} more lines`) : null,
2563
+ lines.length === 0 ? h(Text, { dimColor: true }, " (no output yet)") : null,
2564
+ shown.map((l, i) => h(Text, { key: i, wrap: "truncate-end" }, l || " ")),
2565
+ back > 0 ? h(Text, { dimColor: true }, ` ↓ ${back} more lines`) : null,
2566
+ h(Hint, {
2567
+ width,
2568
+ variants: [`PgUp/PgDn ↑↓ scroll${canStop(viewing) ? " · x stop" : ""} · esc back`, `↑↓${canStop(viewing) ? " · x" : ""} · esc`],
2569
+ }),
2570
+ );
2571
+ }
2572
+ const visible = roomFor(rows, VISIBLE);
2573
+ const start = around(selected, jobs.length, visible);
2574
+ return h(
2575
+ Box,
2576
+ frame,
2577
+ h(Text, { bold: true }, "Background tasks"),
2578
+ jobs.length === 0 ? h(Text, { dimColor: true }, "Nothing is running in the background.") : null,
2579
+ start > 0 ? h(Text, { dimColor: true }, ` ↑ ${start} more`) : null,
2580
+ jobs.slice(start, start + visible).map((j, k) => {
2581
+ const on = start + k === selected;
2582
+ return h(
2583
+ Text,
2584
+ { key: j.id, wrap: "truncate-end" },
2585
+ h(Text, { color: on ? "cyan" : undefined, bold: on }, on ? "❯ " : " "),
2586
+ mark(j),
2587
+ h(Text, { color: on ? "cyan" : undefined, bold: on }, `${j.kind} · ${j.title}`),
2588
+ j.status ? h(Text, { dimColor: true }, ` · ${j.status}`) : null,
2589
+ );
2590
+ }),
2591
+ start + visible < jobs.length ? h(Text, { dimColor: true }, ` ↓ ${jobs.length - start - visible} more`) : null,
2592
+ h(Hint, {
2593
+ width,
2594
+ variants: jobs.length
2595
+ ? [`↑↓ select · enter view output${canStop(jobs[selected]) ? " · x stop" : ""} · esc close`, `↑↓ · enter${canStop(jobs[selected]) ? " · x" : ""} · esc`]
2596
+ : ["esc close"],
2597
+ }),
2598
+ );
2599
+ }
2600
+
2419
2601
  function InputDialog({
2420
2602
  dialog,
2421
2603
  }: {
@@ -1,5 +1,8 @@
1
1
  import { definePlugin } from "@uncarved/jade-api";
2
2
  const DEFAULT_STEPS = 100;
3
+ const WRAP_UP_STEPS = 2;
4
+ export const WRAP_UP_NOTE = "You have reached the step limit for this turn. Do not call any more tools. " + "Reply to the user now: summarize what you did, the current state of any files you changed (including anything left half-done), and what remains.";
5
+ export const WRAP_UP_TOOL_REASON = "The step limit for this turn has been reached; tools are disabled. Reply to the user with your summary instead.";
3
6
  export function stepsThisTurn(s) {
4
7
  let steps = 0;
5
8
  for (let i = s.messages.length - 1;i >= 0; i--) {
@@ -19,15 +22,53 @@ export default definePlugin({
19
22
  max = raw;
20
23
  else if (raw !== undefined)
21
24
  ctx.service("ui@1")?.notify(`jade/budget: maxSteps must be a positive integer, got ${JSON.stringify(raw)}; using ${DEFAULT_STEPS}`, "warning");
25
+ let stopped = false;
26
+ let pending;
27
+ let wrappingUp = false;
22
28
  ctx.kernel.hook({
23
29
  kind: "gate",
24
30
  point: "turn.continue",
25
31
  fn: async (s, hook) => {
26
- if (stepsThisTurn(s) < max)
32
+ if (stepsThisTurn(s) < (wrappingUp ? WRAP_UP_STEPS : max))
27
33
  return { decision: "abstain" };
28
- await hook.emit("notice", { text: `stopped after ${max} model responses in this turn (config maxSteps); send a message to continue`, level: "warning" });
34
+ if (!wrappingUp) {
35
+ stopped = true;
36
+ await hook.emit("notice", { text: `stopped after ${max} model responses in this turn (config maxSteps); asking the model to summarize. Send a message to continue`, level: "warning" });
37
+ }
29
38
  return { decision: "deny" };
30
39
  }
31
40
  });
41
+ ctx.kernel.hook({
42
+ kind: "gate",
43
+ point: "tool.gate",
44
+ fn: () => wrappingUp ? { decision: "deny", reason: WRAP_UP_TOOL_REASON } : { decision: "abstain" }
45
+ });
46
+ ctx.kernel.hook({
47
+ kind: "observe",
48
+ point: "event",
49
+ fn: (e) => {
50
+ if (e.type === "input.received") {
51
+ const input = e.data;
52
+ if (input.kind !== "message")
53
+ return;
54
+ const b = input.content[0];
55
+ wrappingUp = pending !== undefined && input.content.length === 1 && b.origin.by === "plugin" && b.origin.id === ctx.plugin;
56
+ if (wrappingUp)
57
+ pending = undefined;
58
+ return;
59
+ }
60
+ if (e.type !== "turn.ended")
61
+ return;
62
+ const ask = stopped && e.data.reason === "stopped";
63
+ stopped = false;
64
+ wrappingUp = false;
65
+ if (!ask)
66
+ return;
67
+ ctx.session.afterTurn(() => {
68
+ pending = { kind: "text", text: `[Note from jade] ${WRAP_UP_NOTE}`, origin: { by: "plugin", id: ctx.plugin }, trust: "trusted" };
69
+ ctx.session.send({ kind: "message", content: [pending] }).catch(() => {});
70
+ });
71
+ }
72
+ });
32
73
  }
33
74
  });
@@ -9,7 +9,7 @@
9
9
  "config": {
10
10
  "maxSteps": {
11
11
  "default": 100,
12
- "description": "the most model responses in one turn (after one user message); the turn stops when it is reached"
12
+ "description": "the most model responses in one turn (after one user message); when it is reached the turn stops and the model is asked, with tools disabled, to summarize for the user"
13
13
  }
14
14
  }
15
15
  }
@@ -1,6 +1,6 @@
1
1
  import { definePlugin } from "@uncarved/jade-api";
2
2
  export const KEY_SPEC = /^(ctrl\+[a-z]|alt\+[a-z0-9]|shift\+tab)$/;
3
- export const RESERVED_KEYS = new Set([..."acdehijklmoruw"].map((c) => `ctrl+${c}`).concat("alt+f", "alt+b"));
3
+ export const RESERVED_KEYS = new Set([..."acdehijklmortuw"].map((c) => `ctrl+${c}`).concat("alt+f", "alt+b"));
4
4
  const registry = new Map;
5
5
  export default definePlugin({
6
6
  process(ctx) {
@@ -13,6 +13,9 @@ export default definePlugin({
13
13
  },
14
14
  preview: (input) => {
15
15
  const i = args(input);
16
+ if (i.action === "replace")
17
+ return [error("- "), String(i.old ?? ""), `
18
+ `, success("+ "), String(i.text ?? "")];
16
19
  return [i.action === "remove" ? error("- ") : success("+ "), String(i.text ?? "")];
17
20
  }
18
21
  });
@@ -29,15 +32,16 @@ export default definePlugin({
29
32
  };
30
33
  let text = input.trim();
31
34
  if (!text) {
32
- const entries = (await Promise.all(MEMORY_SCOPES.map(async (scope) => (await memory.list(scope)).map((t) => ({ scope, text: t }))))).flat();
35
+ const entries = (await Promise.all(MEMORY_SCOPES.map(async (scope) => (await memory.entries(scope)).map((e) => ({ scope, ...e }))))).flat();
36
+ const label = (e) => e.date ? `${e.scope}, ${e.date}` : e.scope;
33
37
  if (!ui.interactive)
34
- return entries.length ? entries.map((e) => `${e.scope}: ${e.text}`).join(`
38
+ return entries.length ? entries.map((e) => `${label(e)}: ${e.text}`).join(`
35
39
  `) : "jade does not remember anything yet";
36
40
  const choice = await ui.select({
37
41
  title: entries.length ? "Memory: choose an entry to remove it, or add one" : "jade does not remember anything yet",
38
42
  detail: dim(`user (all projects): ${memory.files.user}
39
43
  project: ${memory.files.project}`),
40
- options: [{ label: "Add a memory…", value: "add" }, ...entries.map((e, i) => ({ label: e.text, value: String(i), hint: e.scope }))]
44
+ options: [{ label: "Add a memory…", value: "add" }, ...entries.map((e, i) => ({ label: e.text, value: String(i), hint: label(e) }))]
41
45
  }, signal);
42
46
  if (!choice)
43
47
  return;