@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
@@ -53,7 +53,7 @@ export function shellTools(opts) {
53
53
  const bash = {
54
54
  name: "bash",
55
55
  meta: { shell: "command" },
56
- description: `Run a shell command with ${shell} -c in the working directory and return its exit code, stdout and stderr. ` + `Each call starts a fresh shell: cd and environment variables do not persist. ` + `Default timeout ${DEFAULT_TIMEOUT_MS / 1000}s (timeout_ms, max ${MAX_TIMEOUT_MS / 1000}s). ` + "Set run_in_background for servers, watchers and other long-running commands: it returns an id at once, " + "then read new output with bash_output and stop it with kill_shell. " + "Never start interactive programs. Prefer read_file/grep/glob over cat/grep/find.",
56
+ description: `Run a shell command with ${shell} -c in the working directory and return its exit code, stdout and stderr. ` + `Each call starts a fresh shell: cd and environment variables do not persist. ` + `Default timeout ${DEFAULT_TIMEOUT_MS / 1000}s (timeout_ms, max ${MAX_TIMEOUT_MS / 1000}s). ` + `Output beyond ${MAX_OUTPUT_CHARS} characters (stdout and stderr together) keeps only the start and end. ` + "Set run_in_background for servers, watchers and other long-running commands: it returns an id at once, " + "then read new output with bash_output and stop it with kill_shell. " + "Never start interactive programs. Prefer read_file/grep/glob over cat/grep/find.",
57
57
  inputSchema: {
58
58
  type: "object",
59
59
  properties: { command: { type: "string" }, timeout_ms: { type: "integer" }, run_in_background: { type: "boolean" } },
@@ -84,12 +84,13 @@ export function shellTools(opts) {
84
84
  };
85
85
  signal.addEventListener("abort", kill, { once: true });
86
86
  try {
87
- const [stdout, stderr, code] = await Promise.all([
87
+ const [out, err, code] = await Promise.all([
88
88
  collect(proc.stdout, (text) => progress({ kind: "output", stream: "stdout", text }), true, killed.done),
89
89
  collect(proc.stderr, (text) => progress({ kind: "output", stream: "stderr", text }), true, killed.done),
90
90
  Promise.race([proc.exited, killed.done.then(() => null)])
91
91
  ]);
92
92
  signal.throwIfAborted();
93
+ const [stdout, stderr] = clipStreams(out, err);
93
94
  const parts = [
94
95
  timedOut ? `Timed out after ${timeout}ms (killed). If it needs longer, raise timeout_ms (max ${MAX_TIMEOUT_MS / 1000}s); for servers and watchers use run_in_background.` : `Exit code ${code}`
95
96
  ];
@@ -206,12 +207,13 @@ export async function capture(executable, env, command, opts) {
206
207
  }, opts.timeoutMs);
207
208
  opts.signal?.addEventListener("abort", kill, { once: true });
208
209
  try {
209
- const [stdout, stderr, code] = await Promise.all([
210
+ const [out, err, code] = await Promise.all([
210
211
  collect(proc.stdout, onOutput, true, killed.done),
211
212
  collect(proc.stderr, onOutput, true, killed.done),
212
213
  Promise.race([proc.exited, killed.done.then(() => null)])
213
214
  ]);
214
215
  opts.signal?.throwIfAborted();
216
+ const [stdout, stderr] = clipStreams(out, err);
215
217
  return { code: timedOut ? null : code, output: [stdout, stderr].filter(Boolean).join(`
216
218
  `), timedOut };
217
219
  } finally {
@@ -326,11 +328,23 @@ async function collect(stream, onChunk, keep = true, stop) {
326
328
  const rest = decoder.decode();
327
329
  if (rest)
328
330
  add(rest);
329
- if (total <= MAX_OUTPUT_CHARS)
330
- return (head + tail).trimEnd();
331
+ return { head, tail, total };
332
+ }
333
+ function clipCollected(c, limit) {
334
+ const full = c.total <= MAX_OUTPUT_CHARS ? c.head + c.tail : undefined;
335
+ if (c.total <= limit)
336
+ return full.trimEnd();
337
+ const half = Math.floor(limit / 2);
338
+ const head = (full ?? c.head).slice(0, half);
339
+ const tail = half > 0 ? (full ?? c.tail).slice(-half) : "";
331
340
  return `${head}
332
- … (${total - MAX_OUTPUT_CHARS} characters omitted) …
333
- ${tail.slice(-half)}`.trimEnd();
341
+ … (${c.total - 2 * half} characters omitted) …
342
+ ${tail}`.trimEnd();
343
+ }
344
+ function clipStreams(out, err) {
345
+ const small = Math.min(out.total, err.total, MAX_OUTPUT_CHARS / 2);
346
+ const outLimit = out.total <= err.total ? small : MAX_OUTPUT_CHARS - small;
347
+ return [clipCollected(out, outLimit), clipCollected(err, MAX_OUTPUT_CHARS - outLimit)];
334
348
  }
335
349
  function clip(s) {
336
350
  if (s.length <= MAX_OUTPUT_CHARS)
@@ -68,7 +68,7 @@ export default definePlugin({
68
68
  pending: [],
69
69
  running() {
70
70
  try {
71
- const phase = ctx.session.state().phase;
71
+ const phase = ctx.session.phase();
72
72
  return phase !== "new" && phase !== "idle" && phase !== "ended";
73
73
  } catch {
74
74
  return false;
@@ -15,7 +15,7 @@ function progressLine(todos) {
15
15
  export function todoTool(onChange) {
16
16
  return {
17
17
  name: "todo_write",
18
- description: "Maintain a task list for multi-step work. Each call replaces the whole list. " + "Use it when a task has three or more steps: write the plan, mark one item in_progress while working on it, " + "and mark items completed as soon as they are done. Skip it for simple tasks.",
18
+ description: "Maintain a task list for multi-step work. Each call replaces the whole list. " + "Use it when a task has three or more steps: write the plan, mark one item in_progress while working on it, " + "and mark items completed as soon as they are done, including the last one before you reply. Skip it for simple tasks.",
19
19
  inputSchema: {
20
20
  type: "object",
21
21
  properties: {
@@ -82,12 +82,7 @@ export default definePlugin({
82
82
  },
83
83
  session(ctx) {
84
84
  ctx.kernel.tool(todoTool((todos) => ctx.panel?.(todoPanel(todos))));
85
- if (ctx.panel) {
86
- ctx.session.afterTurn(() => {
87
- const todos = latestTodos(ctx.session.state().messages);
88
- if (Array.isArray(todos))
89
- ctx.panel?.(todoPanel(todos));
90
- });
91
- }
85
+ if (ctx.panel)
86
+ ctx.session.afterTurn(() => ctx.panel?.(undefined));
92
87
  }
93
88
  });
@@ -315,7 +315,7 @@ ${USAGE}
315
315
  early.push(text);
316
316
  },
317
317
  completions: completionList,
318
- complete: async (trigger) => await completions?.list().find((c) => c.completion.trigger === trigger)?.completion.candidates() ?? [],
318
+ complete: async (trigger, dir) => await completions?.list().find((c) => c.completion.trigger === trigger)?.completion.candidates(dir) ?? [],
319
319
  interrupt: () => ready && interrupt(),
320
320
  unqueue: () => takeBack(),
321
321
  exit: () => void quit(0),
@@ -338,7 +338,10 @@ ${USAGE}
338
338
  const offModel = models?.subscribe?.(() => screen.status({ model: models.current()?.model ?? "(no model)" }));
339
339
  let current;
340
340
  let unsubscribe;
341
- const canRetry = () => current?.state.phase === "idle" && current.state.messages.at(-1)?.role === "user";
341
+ const canRetry = () => {
342
+ const state = current?.state;
343
+ return state?.phase === "idle" && state.messages.at(-1)?.role === "user";
344
+ };
342
345
  const view = transcript({
343
346
  screen,
344
347
  cwd,
@@ -1,4 +1,4 @@
1
- import stringWidth from "string-width";
1
+ import { visibleWidth, wrapLines, wrapText } from "./width.js";
2
2
  import wrapAnsi from "wrap-ansi";
3
3
  import { bold, cyan, dim, italic, strike, underline } from "./screen.js";
4
4
  const FENCE = /^\s*(`{3,}|~{3,})\s*([^`\s]*)/;
@@ -85,13 +85,16 @@ export function softInfo(row) {
85
85
  const WRAP = { hard: true, trim: false };
86
86
  export function wrapRows(text, width) {
87
87
  const expanded = expandTabs(text);
88
+ const grouped = wrapLines(expanded, width);
89
+ if (grouped)
90
+ return grouped.flatMap((rows) => rows.map((r, i) => i === 0 ? r : softRow(r)));
88
91
  const rows = wrapAnsi(expanded, width, WRAP).split(`
89
92
  `);
90
93
  const logical = expanded.split(`
91
94
  `);
92
95
  if (rows.length === logical.length)
93
96
  return rows;
94
- const counts = logical.map((l) => stringWidth(l) <= width ? 1 : wrapAnsi(l, width, WRAP).split(`
97
+ const counts = logical.map((l) => visibleWidth(l) <= width ? 1 : wrapAnsi(l, width, WRAP).split(`
95
98
  `).length);
96
99
  if (counts.reduce((a, b) => a + b, 0) !== rows.length)
97
100
  return rows;
@@ -140,7 +143,7 @@ export function expandTabs(text, stop = 4) {
140
143
  const parts = line.split("\t");
141
144
  parts.forEach((p, i) => {
142
145
  out += p;
143
- col += stringWidth(p);
146
+ col += visibleWidth(p);
144
147
  if (i < parts.length - 1) {
145
148
  const n = stop - col % stop;
146
149
  out += " ".repeat(n);
@@ -151,13 +154,12 @@ export function expandTabs(text, stop = 4) {
151
154
  }).join(`
152
155
  `);
153
156
  }
154
- function hanging(head, body, rest = " ".repeat(stringWidth(head))) {
157
+ function hanging(head, body, rest = " ".repeat(visibleWidth(head))) {
155
158
  return {
156
159
  render: (width) => {
157
- const indent = stringWidth(head);
160
+ const indent = visibleWidth(head);
158
161
  const room = Math.max(1, width - indent);
159
- const rows = wrapAnsi(expandTabs(body), room, WRAP).split(`
160
- `);
162
+ const rows = wrapText(expandTabs(body), room);
161
163
  return rows.map((r, i) => i === 0 ? head + r.trimEnd() : softRow(rest + r.trimEnd(), rows[i - 1].length - rows[i - 1].trimEnd().length, indent));
162
164
  }
163
165
  };
@@ -198,7 +200,7 @@ function tableLine(rows, align) {
198
200
  function renderTable(rows, align, width) {
199
201
  const n = Math.max(...rows.map((r) => r.length));
200
202
  const grid = rows.map((r) => Array.from({ length: n }, (_, i) => r[i] ?? ""));
201
- const natural = Array.from({ length: n }, (_, i) => Math.max(1, ...grid.map((r) => stringWidth(r[i]))));
203
+ const natural = Array.from({ length: n }, (_, i) => Math.max(1, ...grid.map((r) => visibleWidth(r[i]))));
202
204
  const room = width - (3 * n + 1);
203
205
  if (room < 3 * n) {
204
206
  const [head, ...body] = grid;
@@ -220,7 +222,7 @@ function renderTable(rows, align, width) {
220
222
  }
221
223
  }
222
224
  const pad = (s, w, a) => {
223
- const gap = w - stringWidth(s);
225
+ const gap = w - visibleWidth(s);
224
226
  if (a === "right")
225
227
  return " ".repeat(gap) + s;
226
228
  if (a === "center")
@@ -7,6 +7,12 @@ export function mentionAt(value, cursor, triggers) {
7
7
  return;
8
8
  return { trigger: m[1], start: cursor - m[2].length - m[1].length, query: m[2].replace(/^"/, "") };
9
9
  }
10
+ export function mentionDir(query) {
11
+ const q = query.replaceAll("\\", "/");
12
+ if (!/^(\.{1,2}\/|~\/|\/|[A-Za-z]:\/)/.test(q))
13
+ return;
14
+ return q.slice(0, q.lastIndexOf("/") + 1);
15
+ }
10
16
  export const mentionText = (trigger, p) => /\s/.test(p) ? `${trigger}"${p}"` : `${trigger}${p}`;
11
17
  const prepared = new WeakMap;
12
18
  function prepare(paths) {
@@ -26,17 +26,11 @@ export function transcript(opts) {
26
26
  if (u)
27
27
  screen.status({ spent: { input: usage.inputTokens, output: usage.outputTokens } });
28
28
  };
29
- async function countUsage(e) {
29
+ function countUsage(e) {
30
30
  if (e.type === "model.responded")
31
31
  addUsage(e.data.usage);
32
32
  else if (e.origin.by === "plugin")
33
33
  addUsage(usageOf(e.data?.usage));
34
- else if (e.type === "tool.completed") {
35
- const child = e.data.child;
36
- if (child && opts.readLog)
37
- for (const c of await opts.readLog(child.sessionId).catch(() => []))
38
- await countUsage(c);
39
- }
40
34
  }
41
35
  let reportsCache;
42
36
  function showContext(e) {
@@ -156,12 +150,16 @@ ${bold(`› ${t.replace(/\n/g, `
156
150
  const lines = text.split(`
157
151
  `);
158
152
  if (lines.length <= MAX_ECHO_LINES)
159
- return screen.log(shown(text));
160
- const rest = lines.slice(ECHO_HEAD_LINES);
161
- screen.log(`${shown(lines.slice(0, ECHO_HEAD_LINES).join(`
153
+ screen.log(shown(text));
154
+ else {
155
+ const rest = lines.slice(ECHO_HEAD_LINES);
156
+ screen.log(`${shown(lines.slice(0, ECHO_HEAD_LINES).join(`
162
157
  `))}
163
158
  ${dim(`… +${rest.length} lines`)}`, { details: rest.map((l) => ` ${l}`).join(`
164
159
  `) });
160
+ }
161
+ if (!text.startsWith("/"))
162
+ screen.log("");
165
163
  },
166
164
  reset() {
167
165
  for (const k of Object.keys(usage))
@@ -312,7 +310,6 @@ ${bold(`› ${t.replace(/\n/g, `
312
310
  }
313
311
  case "tool.completed": {
314
312
  const d = e.data;
315
- countUsage(e);
316
313
  activity("Working");
317
314
  doneProgress(d.toolUseId);
318
315
  const call = calls.get(d.toolUseId);
@@ -412,7 +409,7 @@ ${bold(`› ${t.replace(/\n/g, `
412
409
  async function replay(events, show) {
413
410
  if (!show) {
414
411
  for (const e of events) {
415
- await countUsage(e);
412
+ countUsage(e);
416
413
  if (e.type === "model.responded")
417
414
  showContext(e);
418
415
  }
@@ -16,8 +16,8 @@ import {
16
16
  useState,
17
17
  useSyncExternalStore
18
18
  } from "./vendor.js";
19
- import stringWidth from "string-width";
20
- import { mentionAt, mentionText, rankPaths } from "./mentions.js";
19
+ import { visibleWidth } from "./width.js";
20
+ import { mentionAt, mentionDir, mentionText, rankPaths } from "./mentions.js";
21
21
  import { charWidth, edit, empty, layout, moveRow, offsetAt } from "./editor.js";
22
22
  import { expandTabs, markdownStream, softInfo, visibleRow, wrapRows } from "./markdown.js";
23
23
  import { cells, FRAME_MS, Mascot, moodOf, nextChange, title } from "./mascot.js";
@@ -58,13 +58,13 @@ function foldable(l, width) {
58
58
  }
59
59
  const elapsed = (t) => `${Math.max(0, Math.round(((t.end ?? Date.now()) - t.start) / 1000))}s`;
60
60
  export function tail(text, cols) {
61
- if (stringWidth(text) <= cols)
61
+ if (visibleWidth(text) <= cols)
62
62
  return text;
63
63
  const chars = [...text];
64
64
  let out = "";
65
65
  let w = 1;
66
66
  for (let i = chars.length - 1;i >= 0; i--) {
67
- const cw = stringWidth(chars[i]);
67
+ const cw = visibleWidth(chars[i]);
68
68
  if (w + cw > cols)
69
69
  break;
70
70
  out = chars[i] + out;
@@ -78,7 +78,7 @@ function thinkingRow(t, width) {
78
78
  const label = `✻ Thinking ${elapsed(t)}`;
79
79
  const latest = t.text.split(`
80
80
  `).findLast((l) => l.trim())?.trim().replace(/\s+/g, " ");
81
- const room = width - stringWidth(label) - 6;
81
+ const room = width - visibleWidth(label) - 6;
82
82
  return dim(latest && room >= 8 ? `${label} · ${tail(latest, room)}` : `${label}…`);
83
83
  }
84
84
  function wrapLine(l, width) {
@@ -166,6 +166,16 @@ export class Store {
166
166
  this.paused = false;
167
167
  this.update({ ...patch, repaint: true }, true);
168
168
  }
169
+ #repaintPending = false;
170
+ repaintInTree() {
171
+ this.#repaintPending = true;
172
+ }
173
+ drawn = () => {
174
+ if (!this.#repaintPending)
175
+ return;
176
+ this.#repaintPending = false;
177
+ this.update({ repaint: false });
178
+ };
169
179
  append(texts, item) {
170
180
  if (texts.length === 0)
171
181
  return;
@@ -447,6 +457,7 @@ export function tuiScreen(opts) {
447
457
  exitOnCtrlC: false,
448
458
  alternateScreen: true,
449
459
  incrementalRendering: true,
460
+ onRender: store.drawn,
450
461
  ...opts.io ? { ...opts.io, interactive: true, patchConsole: false } : {}
451
462
  });
452
463
  for (const l of stdout.listeners("resize"))
@@ -796,10 +807,8 @@ function App({
796
807
  copiedTimer.current = setTimeout(() => setCopied(undefined), COPIED_MS);
797
808
  };
798
809
  const repaint = state.repaint === true;
799
- useEffect(() => {
800
- if (repaint)
801
- store.update({ repaint: false });
802
- }, [repaint]);
810
+ if (repaint)
811
+ store.repaintInTree();
803
812
  useInput((input, key) => {
804
813
  if (key.ctrl && input === "l")
805
814
  return store.repaint();
@@ -947,7 +956,7 @@ function Spinner({ label, since }) {
947
956
  const TONE = { ok: "green", warn: "yellow", error: "red", accent: "magenta" };
948
957
  export function fitSegments(segments, width) {
949
958
  const kept = segments.map((s) => ({ ...s }));
950
- const total = () => kept.reduce((n, s, i) => n + stringWidth(s.text) + (i ? 3 : 0), 0);
959
+ const total = () => kept.reduce((n, s, i) => n + visibleWidth(s.text) + (i ? 3 : 0), 0);
951
960
  const steps = kept.flatMap((s) => [
952
961
  ...s.short !== undefined && s.shortAt !== undefined ? [{ s, at: s.shortAt, drop: false }] : [],
953
962
  ...s.dropAt !== undefined ? [{ s, at: s.dropAt, drop: true }] : []
@@ -1017,7 +1026,7 @@ function StatusBar({ status, width }) {
1017
1026
  return h(Box, { paddingX: 1 }, h(Text, { wrap: "truncate-end" }, shown.map((s, i) => h(Text, { key: i }, i ? h(Text, { dimColor: true }, " · ") : null, h(Text, { color: s.color, dimColor: s.dim }, s.text)))));
1018
1027
  }
1019
1028
  function Hint({ variants, width }) {
1020
- const text = variants.find((v) => stringWidth(v) <= width) ?? variants.at(-1);
1029
+ const text = variants.find((v) => visibleWidth(v) <= width) ?? variants.at(-1);
1021
1030
  return h(Text, { dimColor: true, wrap: "truncate-end" }, text);
1022
1031
  }
1023
1032
  const tokens = (n) => n >= 1e6 ? `${(n / 1e6).toFixed(n >= 1e7 ? 0 : 1)}M` : n >= 1000 ? `${(n / 1000).toFixed(n >= 1e4 ? 0 : 1)}k` : String(n);
@@ -1196,16 +1205,17 @@ function Prompt({
1196
1205
  const { state, search, matches, pick, mention, found, file, results, hit } = derive();
1197
1206
  const notice = getNotice();
1198
1207
  const mentioning = mention?.trigger;
1208
+ const mentionScope = mention ? mentionDir(mention.query) : undefined;
1199
1209
  useEffect(() => {
1200
1210
  if (mentioning === undefined || !handlers.complete)
1201
1211
  return;
1202
1212
  let live = true;
1203
1213
  setPaths([]);
1204
- handlers.complete(mentioning).then((p) => void (live && setPaths(p)), () => {});
1214
+ handlers.complete(mentioning, mentionScope).then((p) => void (live && setPaths(p)), () => {});
1205
1215
  return () => {
1206
1216
  live = false;
1207
1217
  };
1208
- }, [mentioning]);
1218
+ }, [mentioning, mentionScope]);
1209
1219
  const completion = completions.find((c) => c.trigger === mentioning);
1210
1220
  const first = around(hit, results.length, menuRows);
1211
1221
  const firstMatch = around(Math.max(0, matches.indexOf(pick)), matches.length, menuRows);
@@ -0,0 +1,219 @@
1
+ import stringWidth from "string-width";
2
+ import wrapAnsi from "wrap-ansi";
3
+ export function standalone(c) {
4
+ if (c < 127)
5
+ return c >= 32;
6
+ if (c < 8208)
7
+ return c >= 160 && c <= 255 && c !== 173;
8
+ if (c <= 8231)
9
+ return true;
10
+ if (c >= 8240 && c <= 8286)
11
+ return true;
12
+ if (c >= 8592 && c <= 10175)
13
+ return c !== 9001 && c !== 9002;
14
+ if (c >= 11904 && c <= 12255)
15
+ return true;
16
+ if (c >= 12288 && c <= 12543)
17
+ return !(c >= 12330 && c <= 12335) && c !== 12441 && c !== 12442;
18
+ if (c >= 12544 && c <= 40959)
19
+ return true;
20
+ if (c >= 44032 && c <= 55203)
21
+ return true;
22
+ return c >= 65281 && c <= 65376 || c >= 65504 && c <= 65510;
23
+ }
24
+ const widths = new Uint8Array(65536);
25
+ function charWidth(c) {
26
+ let w = widths[c];
27
+ if (w === 0)
28
+ widths[c] = w = stringWidth(String.fromCharCode(c)) + 1;
29
+ return w - 1;
30
+ }
31
+ const SGR = /\x1b\[(\d{1,2})m/y;
32
+ function sgrAt(s, i) {
33
+ SGR.lastIndex = i;
34
+ const m = SGR.exec(s);
35
+ if (!m)
36
+ return;
37
+ const code = Number(m[1]);
38
+ return CLOSE_OF.has(code) || RESETS.has(code) ? { code, length: m[0].length } : undefined;
39
+ }
40
+ const CLOSE_OF = new Map([
41
+ [1, 22],
42
+ [2, 22],
43
+ [3, 23],
44
+ [4, 24],
45
+ [9, 29],
46
+ ...[30, 31, 32, 33, 34, 35, 36, 37, 90, 91, 92, 93, 94, 95, 96, 97].map((c) => [c, 39])
47
+ ]);
48
+ const RESETS = new Set([22, 23, 24, 29, 39]);
49
+ function fastWidth(s) {
50
+ let w = 0;
51
+ for (let i = 0;i < s.length; i++) {
52
+ const c = s.charCodeAt(i);
53
+ if (c === 27) {
54
+ const m = sgrAt(s, i);
55
+ if (!m)
56
+ return;
57
+ i += m.length - 1;
58
+ continue;
59
+ }
60
+ if (!standalone(c))
61
+ return;
62
+ w += c < 127 ? 1 : charWidth(c);
63
+ }
64
+ return w;
65
+ }
66
+ export function visibleWidth(s) {
67
+ return fastWidth(s) ?? stringWidth(s);
68
+ }
69
+ function words(line) {
70
+ let word = { tokens: [], value: "", width: 0 };
71
+ const out = [word];
72
+ for (let i = 0;i < line.length; i++) {
73
+ const c = line.charCodeAt(i);
74
+ if (c === 32) {
75
+ word = { tokens: [], value: "", width: 0 };
76
+ out.push(word);
77
+ continue;
78
+ }
79
+ let token;
80
+ if (c === 27) {
81
+ const m = sgrAt(line, i);
82
+ if (!m)
83
+ return;
84
+ token = { value: line.slice(i, i + m.length), width: 0 };
85
+ i += m.length - 1;
86
+ } else {
87
+ if (!standalone(c))
88
+ return;
89
+ token = { value: line[i], width: c < 127 ? 1 : charWidth(c) };
90
+ }
91
+ word.tokens.push(token);
92
+ word.value += token.value;
93
+ word.width += token.width;
94
+ }
95
+ return out;
96
+ }
97
+ function wrapWord(rows, tokens, columns, rowWidth) {
98
+ let visible = rowWidth;
99
+ tokens.forEach((t, i) => {
100
+ if (t.width > 0 && visible > 0 && visible + t.width > columns) {
101
+ rows.push("");
102
+ visible = 0;
103
+ }
104
+ rows[rows.length - 1] += t.value;
105
+ visible += t.width;
106
+ if (visible === columns && i < tokens.length - 1) {
107
+ rows.push("");
108
+ visible = 0;
109
+ }
110
+ });
111
+ if (!visible && rows.at(-1).length > 0 && rows.length > 1)
112
+ rows[rows.length - 2] += rows.pop();
113
+ return fastWidth(rows.at(-1));
114
+ }
115
+ function applySgr(code, active, resetsOnly = false) {
116
+ if (code === 39) {
117
+ const i = active.findIndex((s) => s.family === "foreground");
118
+ if (i !== -1)
119
+ active.splice(i, 1);
120
+ return;
121
+ }
122
+ if (RESETS.has(code)) {
123
+ for (let i = active.length - 1;i >= 0; i--)
124
+ if (active[i].family.startsWith("modifier-") && active[i].close === code)
125
+ active.splice(i, 1);
126
+ return;
127
+ }
128
+ if (resetsOnly)
129
+ return;
130
+ const close = CLOSE_OF.get(code);
131
+ const family = close === 39 ? "foreground" : `modifier-${code}`;
132
+ const i = active.findIndex((s) => s.family === family);
133
+ if (i !== -1)
134
+ active.splice(i, 1);
135
+ active.push({ family, open: code, close });
136
+ }
137
+ function restoreStyles(s) {
138
+ let out = "";
139
+ const active = [];
140
+ let copied = 0;
141
+ let i = 0;
142
+ while (i < s.length) {
143
+ const c = s.charCodeAt(i);
144
+ if (c === 27) {
145
+ const m = sgrAt(s, i);
146
+ applySgr(m.code, active);
147
+ i += m.length;
148
+ continue;
149
+ }
150
+ if (c !== 10) {
151
+ i++;
152
+ continue;
153
+ }
154
+ out += s.slice(copied, i);
155
+ if (i > copied)
156
+ out += [...active].reverse().map((st) => `\x1B[${st.close}m`).join("");
157
+ out += `
158
+ `;
159
+ copied = ++i;
160
+ if (i < s.length && s[i] !== `
161
+ `) {
162
+ const opening = [...active];
163
+ for (let j = i, m = sgrAt(s, j);m; j += m.length, m = sgrAt(s, j))
164
+ applySgr(m.code, opening, true);
165
+ out += opening.map((st) => `\x1B[${st.open}m`).join("");
166
+ }
167
+ }
168
+ return out + s.slice(copied);
169
+ }
170
+ function fastWrap(line, columns) {
171
+ const width = fastWidth(line);
172
+ if (width === undefined)
173
+ return;
174
+ if (width <= columns)
175
+ return [line];
176
+ const list = words(line);
177
+ const rows = [""];
178
+ let rowLength = 0;
179
+ list.forEach((word, k) => {
180
+ if (k > 0) {
181
+ if (rowLength >= columns) {
182
+ rows.push("");
183
+ rowLength = 0;
184
+ }
185
+ rows[rows.length - 1] += " ";
186
+ rowLength++;
187
+ }
188
+ if (word.width > columns) {
189
+ const remaining = columns - rowLength;
190
+ const thisLine = 1 + Math.floor((word.width - remaining - 1) / columns);
191
+ const nextLine = Math.floor((word.width - 1) / columns);
192
+ if (nextLine < thisLine) {
193
+ rows.push("");
194
+ rowLength = 0;
195
+ }
196
+ rowLength = wrapWord(rows, word.tokens, columns, rowLength);
197
+ return;
198
+ }
199
+ if (rowLength + word.width > columns && rowLength > 0 && word.width > 0) {
200
+ rows.push("");
201
+ rowLength = 0;
202
+ }
203
+ rows[rows.length - 1] += word.value;
204
+ rowLength += word.width;
205
+ });
206
+ return line.includes("\x1B") ? restoreStyles(rows.join(`
207
+ `)).split(`
208
+ `) : rows;
209
+ }
210
+ const WRAP = { hard: true, trim: false };
211
+ export function wrapLines(text, width) {
212
+ if (text.includes("\r"))
213
+ return;
214
+ return text.split(`
215
+ `).map((line) => fastWrap(line, width) ?? wrapAnsi(line, width, WRAP).split(`
216
+ `));
217
+ }
218
+ export const wrapText = (text, width) => wrapLines(text, width)?.flat() ?? wrapAnsi(text, width, WRAP).split(`
219
+ `);
package/src/api.ts CHANGED
@@ -5,7 +5,7 @@ import type { PluginLayer } from "@uncarved/jade-api";
5
5
  export * from "@uncarved/jade-api";
6
6
 
7
7
  /** 插件 API 的版本,插件在 plugin.json 的 api 字段里用 ^ 范围声明。和 @uncarved/jade-api 的版本一致 */
8
- export const API_VERSION = "1.4.0";
8
+ export const API_VERSION = "1.5.0";
9
9
 
10
10
  /** 来源层级,后面的层级更高(3.3) */
11
11
  export const LAYERS: readonly PluginLayer[] = ["bundled", "user", "project"];
package/src/session.ts CHANGED
@@ -766,6 +766,11 @@ export class Sessions implements SessionManager {
766
766
  if (!s.rt) throw new Error(`plugin ${id}: the session's state is not available while session() runs`);
767
767
  return s.rt.state;
768
768
  },
769
+ phase: () => {
770
+ if (scope.closed) throw new StaleContext(id);
771
+ if (!s.rt) throw new Error(`plugin ${id}: the session's phase is not available while session() runs`);
772
+ return s.rt.phase;
773
+ },
769
774
  subscribe: (fn) => {
770
775
  if (scope.closed) throw new StaleContext(id);
771
776
  const off = s.watch(fn, owner);