@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,5 +1,6 @@
1
1
  import { execFile } from "node:child_process";
2
2
  import { readdir } from "node:fs/promises";
3
+ import os from "node:os";
3
4
  import path from "node:path";
4
5
  import { display } from "./attach.js";
5
6
  const MAX_CANDIDATES = 20000;
@@ -22,6 +23,11 @@ export async function mentionCandidates(cwd, signal = AbortSignal.timeout(5000))
22
23
  } catch {}
23
24
  return [...dirs, ...files];
24
25
  }
26
+ export async function dirCandidates(cwd, dir) {
27
+ const full = path.resolve(cwd, dir.replace(/^~(?=\/)/, os.homedir()));
28
+ const entries = await readdir(full, { withFileTypes: true }).catch(() => []);
29
+ return entries.filter((e) => e.isDirectory() || e.isFile()).slice(0, MAX_CANDIDATES).map((e) => `${dir}${e.name}${e.isDirectory() ? "/" : ""}`);
30
+ }
25
31
  const SKIP_DIRS = new Set([".git", "node_modules"]);
26
32
  function gitFiles(root) {
27
33
  return new Promise((resolve) => {
@@ -1,6 +1,6 @@
1
1
  import { definePlugin } from "@uncarved/jade-api";
2
2
  import { attachMentions } from "./attach.js";
3
- import { mentionCandidates } from "./candidates.js";
3
+ import { dirCandidates, mentionCandidates } from "./candidates.js";
4
4
  import { clip, dim, lines as joinLines, warn } from "./style.js";
5
5
  export const attachedKey = (plugin, i) => `${plugin}/${i}`;
6
6
  const READ_TIMEOUT_MS = 30000;
@@ -12,7 +12,7 @@ export default definePlugin({
12
12
  trigger: "@",
13
13
  label: "files",
14
14
  hint: "the file's content is sent with the message",
15
- candidates: () => mentionCandidates(ctx.cwd)
15
+ candidates: (dir) => dir ? dirCandidates(ctx.cwd, dir) : mentionCandidates(ctx.cwd)
16
16
  });
17
17
  const renderers = ctx.service("renderers@1");
18
18
  renderers?.event({
@@ -1,7 +1,7 @@
1
1
  import { readFile, rm, writeFile } from "node:fs/promises";
2
2
  import { hasProvider, parseTokens } from "./config.js";
3
3
  import { contextWindow } from "./context.js";
4
- import { EFFORTS, isBuiltinKind, jsonObject, KEY_KEY, listModels, MODEL_KEY, providerInfo, providerKind, rpmFromEnv, URL_KEY, visionFromEnv } from "./provider.js";
4
+ import { EFFORTS, fallbacksFromEnv, isBuiltinKind, isOfficialAnthropic, jsonObject, KEY_KEY, listModels, MODEL_KEY, providerInfo, providerKind, rpmFromEnv, thinkingFromEnv, URL_KEY, visionFromEnv } from "./provider.js";
5
5
  import { MODEL_SETTINGS, readSavedServices, updateEnvFile, writeSavedServices } from "./saved.js";
6
6
  const PROVIDERS = [
7
7
  { kind: "openai-compat", label: "OpenAI-compatible service", hint: "any /chat/completions endpoint" },
@@ -21,6 +21,28 @@ function visionHint(env, kind) {
21
21
  const v = visionSetting(env);
22
22
  return v === undefined ? `${isBuiltinKind(kind) && kind !== "openai-compat" ? "yes" : "no"} (default)` : v ? "yes" : "no";
23
23
  }
24
+ function fallbacksSetting(env) {
25
+ if (!env.JADE_FALLBACKS?.trim())
26
+ return;
27
+ try {
28
+ return fallbacksFromEnv({ JADE_FALLBACKS: env.JADE_FALLBACKS });
29
+ } catch {
30
+ return;
31
+ }
32
+ }
33
+ function fallbacksHint(env, baseURL) {
34
+ const v = fallbacksSetting(env);
35
+ return v === undefined ? `${isOfficialAnthropic(baseURL) ? "on" : "off"} (default)` : v ? "on" : "off";
36
+ }
37
+ function thinkingSetting(env) {
38
+ if (!env.JADE_THINKING?.trim())
39
+ return;
40
+ try {
41
+ return thinkingFromEnv({ JADE_THINKING: env.JADE_THINKING });
42
+ } catch {
43
+ return;
44
+ }
45
+ }
24
46
  const serviceKeys = (kind) => ["JADE_PROVIDER", URL_KEY[kind], KEY_KEY[kind]];
25
47
  const pick = (env, keys) => {
26
48
  const out = {};
@@ -229,7 +251,7 @@ export function configurator(opts) {
229
251
  return applyConfig(updates, rekeyed ? currentId : undefined);
230
252
  }
231
253
  async function configureSettings(target) {
232
- const { title, kind, model } = target;
254
+ const { title, kind, model, baseURL } = target;
233
255
  const efforts = isBuiltinKind(kind) ? EFFORTS[kind] : undefined;
234
256
  while (true) {
235
257
  const env = await target.read();
@@ -241,6 +263,8 @@ export function configurator(opts) {
241
263
  { label: "Context window", value: "window", hint: `${contextWindow(model, env)} tokens${env.JADE_CONTEXT_WINDOW ? "" : " (default)"}` },
242
264
  { label: "Requests per minute", value: "rpm", hint: env.JADE_RPM ? `${env.JADE_RPM}/min` : "no limit (slows down after being rate limited)" },
243
265
  { label: "Can see images", value: "vision", hint: visionHint(env, kind) },
266
+ ...kind === "anthropic" ? [{ label: "Server-side fallback", value: "fallbacks", hint: fallbacksHint(env, baseURL) }] : [],
267
+ ...kind === "anthropic" ? [{ label: "Send thinking settings", value: "thinking", hint: thinkingSetting(env) === false ? "off" : `on${env.JADE_THINKING ? "" : " (default)"}` }] : [],
244
268
  ...kind === "openai-compat" ? [{ label: "Extra request body", value: "extra", hint: env.OPENAI_COMPAT_EXTRA_BODY ? shorten(env.OPENAI_COMPAT_EXTRA_BODY) : "none" }] : [],
245
269
  { label: "Back", value: "back" }
246
270
  ]
@@ -287,6 +311,30 @@ export function configurator(opts) {
287
311
  const on = choice === DEFAULT ? isBuiltinKind(kind) && kind !== "openai-compat" : choice === "on";
288
312
  report(on ? "Images will be sent to the model." : "Images will be replaced with a note.");
289
313
  }
314
+ } else if (action === "fallbacks" && kind === "anthropic") {
315
+ const DEFAULT = "\x00default";
316
+ const current = fallbacksSetting(env);
317
+ const choice = await ui.select({
318
+ title: "Retry with another model on the service side when Claude refuses for safety reasons?",
319
+ options: [
320
+ { label: "On", value: "on", hint: current === true ? "current" : "official API only; most relays reject it" },
321
+ { label: "Off", value: "off", hint: current === false ? "current" : "the field is not sent" },
322
+ { label: "Default", value: DEFAULT, hint: isOfficialAnthropic(baseURL) ? "on (official API)" : "off (not the official API)" }
323
+ ]
324
+ }, opts.signal);
325
+ if (choice !== undefined)
326
+ await target.update({ JADE_FALLBACKS: choice === DEFAULT ? undefined : choice });
327
+ } else if (action === "thinking" && kind === "anthropic") {
328
+ const current = thinkingSetting(env);
329
+ const choice = await ui.select({
330
+ title: "Send thinking and effort settings with each request?",
331
+ options: [
332
+ { label: "On", value: "on", hint: current !== false ? "current" : "adaptive thinking, effort high unless set" },
333
+ { label: "Off", value: "off", hint: current === false ? "current" : "for services that reject the thinking field; the model decides itself" }
334
+ ]
335
+ }, opts.signal);
336
+ if (choice !== undefined)
337
+ await target.update({ JADE_THINKING: choice === "on" ? undefined : choice });
290
338
  } else if (action === "window") {
291
339
  const n = await ui.input({ title: "Context window in tokens, e.g. 128000, 512K, 1M (empty to infer it from the model name, or 256K if unknown)", initial: env.JADE_CONTEXT_WINDOW ?? "" }, opts.signal);
292
340
  if (n !== undefined && tokensInput("Context window", n))
@@ -351,6 +399,7 @@ export function configurator(opts) {
351
399
  title: o.model.name,
352
400
  kind,
353
401
  model: o.model.name,
402
+ baseURL: providerInfo(o.service.env).baseURL,
354
403
  read,
355
404
  update: (updates) => isCurrent ? applyConfig(updates) : writeSavedModel(o.service, o.model, updates)
356
405
  });
@@ -7,6 +7,8 @@ import { isBuiltinKind, listModels, MODEL_KEY, providerFromEnv, providerInfo, pr
7
7
  import { MODEL_SETTINGS, readSavedServices } from "./saved.js";
8
8
  let setup;
9
9
  let hinted = false;
10
+ const countdowns = new Map;
11
+ const sessionOf = (request) => request.ext?.["jade/models"]?.session;
10
12
  export default definePlugin({
11
13
  async process(ctx) {
12
14
  const envFile = path.join(ctx.home, ".env");
@@ -15,6 +17,10 @@ export default definePlugin({
15
17
  hinted = false;
16
18
  setup = { configured: () => hasProvider(env), command: false, envFile };
17
19
  const ui = () => ctx.service("ui@1");
20
+ const userAgent = () => {
21
+ const version = ctx.service("update@1")?.version;
22
+ return version ? `jade/${version}` : "jade";
23
+ };
18
24
  const watchers = new Set;
19
25
  const notify = () => {
20
26
  for (const fn of watchers) {
@@ -31,9 +37,13 @@ export default definePlugin({
31
37
  const build = (snapshot) => {
32
38
  return (async () => {
33
39
  const gate = new RateGate({ rpm: rpmFromEnv(snapshot), onLearn: (rpm) => ui()?.notify(`rate limited: spacing requests to ${rpm} per minute from now on`, "warning") });
34
- return withRetry(await providerFromEnv(snapshot), {
40
+ return withRetry(await providerFromEnv(snapshot, { "user-agent": userAgent() }), {
35
41
  gate,
36
- onRetry: ({ attempt, retries, delayMs, error }) => ui()?.notify(`model request failed (${error.message}); retry ${attempt} of ${retries} in ${Math.round(delayMs / 1000)}s`, "warning")
42
+ onWait: ({ delayMs, request }) => countdowns.get(sessionOf(request) ?? "")?.(delayMs, "rate limited, sending in"),
43
+ onRetry: ({ attempt, retries, delayMs, error, request }) => {
44
+ ui()?.notify(`model request failed (${error.message}); retrying in ${Math.round(delayMs / 1000)}s (retry ${attempt}, at most ${retries})`, "warning");
45
+ countdowns.get(sessionOf(request) ?? "")?.(delayMs, "retrying in");
46
+ }
37
47
  });
38
48
  })();
39
49
  };
@@ -170,13 +180,57 @@ export default definePlugin({
170
180
  }
171
181
  }
172
182
  });
183
+ let timer;
184
+ const stopCountdown = () => {
185
+ if (timer === undefined)
186
+ return;
187
+ clearInterval(timer);
188
+ timer = undefined;
189
+ ctx.status?.(undefined);
190
+ };
191
+ if (ctx.status) {
192
+ const id = ctx.session.id;
193
+ countdowns.set(id, (ms, label) => {
194
+ stopCountdown();
195
+ const until = Date.now() + ms;
196
+ const tick = () => {
197
+ const left = Math.ceil((until - Date.now()) / 1000);
198
+ if (left <= 0)
199
+ return stopCountdown();
200
+ ctx.status?.({ text: `${label} ${left}s`, tone: "warn" });
201
+ };
202
+ timer = setInterval(tick, 1000);
203
+ tick();
204
+ });
205
+ ctx.signal.addEventListener("abort", () => {
206
+ stopCountdown();
207
+ countdowns.delete(id);
208
+ });
209
+ ctx.kernel.hook({
210
+ kind: "transform",
211
+ point: "model.before",
212
+ fn: (req) => ({ ...req, ext: { ...req.ext, "jade/models": { session: id } } })
213
+ });
214
+ ctx.kernel.hook({
215
+ kind: "observe",
216
+ point: "event",
217
+ fn: (e) => {
218
+ if (e.type === "turn.ended")
219
+ stopCountdown();
220
+ }
221
+ });
222
+ }
173
223
  ctx.kernel.hook({
174
224
  kind: "observe",
175
225
  point: "model.after",
176
226
  fn: async (res, hook) => {
227
+ stopCountdown();
177
228
  const retries = res.retries;
178
- if (retries?.length)
179
- await hook.emit("retried", { retries });
229
+ if (!retries?.length)
230
+ return;
231
+ const waited = Math.round(retries.reduce((ms, r) => ms + r.delayMs, 0) / 1000);
232
+ ui?.notify(`model request succeeded after ${retries.length} ${retries.length === 1 ? "retry" : "retries"} (${waited}s of waiting)`, "info");
233
+ await hook.emit("retried", { retries });
180
234
  }
181
235
  });
182
236
  }
@@ -9,6 +9,7 @@
9
9
  ],
10
10
  "optional": [
11
11
  "ui@1",
12
- "commands@1"
12
+ "commands@1",
13
+ "update@1"
13
14
  ]
14
15
  }
@@ -15,7 +15,7 @@ export function withRetry(inner, opts = {}) {
15
15
  const failures = [];
16
16
  for (let attempt = 1;; attempt++) {
17
17
  let streamed = false;
18
- await opts.gate?.acquire(options.signal);
18
+ await opts.gate?.acquire(options.signal, opts.onWait && ((delayMs) => opts.onWait({ delayMs, request })));
19
19
  opts.onRequest?.(attempt);
20
20
  try {
21
21
  const res = await inner.complete(request, {
@@ -47,7 +47,7 @@ export function withRetry(inner, opts = {}) {
47
47
  if (streamed)
48
48
  options.onDelta?.({ kind: "reset" });
49
49
  failures.push({ attempt, delayMs, error: err.message, ...err.status !== undefined ? { status: err.status } : {}, ...streamed ? { discarded: true } : {} });
50
- opts.onRetry?.({ attempt, retries, delayMs, error: err });
50
+ opts.onRetry?.({ attempt, retries, delayMs, error: err, request });
51
51
  await sleep(delayMs, options.signal);
52
52
  }
53
53
  }
@@ -72,11 +72,12 @@ export class RateGate {
72
72
  get rpm() {
73
73
  return this.#rpm;
74
74
  }
75
- acquire(signal) {
75
+ acquire(signal, onWait) {
76
76
  const turn = this.#queue.then(async () => {
77
77
  signal.throwIfAborted();
78
78
  for (let wait = this.#delay();wait > 0; wait = this.#delay()) {
79
79
  this.#opts.onWait?.(wait);
80
+ onWait?.(wait);
80
81
  await sleep(wait, signal);
81
82
  }
82
83
  this.#sent.push(this.#now());
@@ -170,6 +171,35 @@ export function visionFromEnv(env = process.env) {
170
171
  return false;
171
172
  throw new Error(`JADE_VISION must be on or off, got ${JSON.stringify(env.JADE_VISION)}`);
172
173
  }
174
+ export function isOfficialAnthropic(baseURL) {
175
+ if (!baseURL?.trim())
176
+ return true;
177
+ try {
178
+ return new URL(baseURL).host === "api.anthropic.com";
179
+ } catch {
180
+ return false;
181
+ }
182
+ }
183
+ export function fallbacksFromEnv(env = process.env) {
184
+ const text = env.JADE_FALLBACKS?.trim().toLowerCase();
185
+ if (!text)
186
+ return isOfficialAnthropic(env.ANTHROPIC_BASE_URL);
187
+ if (["1", "true", "on", "yes"].includes(text))
188
+ return true;
189
+ if (["0", "false", "off", "no"].includes(text))
190
+ return false;
191
+ throw new Error(`JADE_FALLBACKS must be on or off, got ${JSON.stringify(env.JADE_FALLBACKS)}`);
192
+ }
193
+ export function thinkingFromEnv(env = process.env) {
194
+ const text = env.JADE_THINKING?.trim().toLowerCase();
195
+ if (!text)
196
+ return true;
197
+ if (["1", "true", "on", "yes"].includes(text))
198
+ return true;
199
+ if (["0", "false", "off", "no"].includes(text))
200
+ return false;
201
+ throw new Error(`JADE_THINKING must be on or off, got ${JSON.stringify(env.JADE_THINKING)}`);
202
+ }
173
203
  export function effortFromEnv(env = process.env) {
174
204
  const effort = env.JADE_EFFORT;
175
205
  if (!effort)
@@ -202,7 +232,7 @@ export function providerInfo(env = process.env) {
202
232
  return { kind, model: env.OPENAI_COMPAT_MODEL ?? "", baseURL: env.OPENAI_COMPAT_BASE_URL };
203
233
  return { kind, model: env.ANTHROPIC_MODEL ?? "claude-opus-5-5", baseURL: env.ANTHROPIC_BASE_URL };
204
234
  }
205
- export async function providerFromEnv(env = process.env) {
235
+ export async function providerFromEnv(env = process.env, headers) {
206
236
  const kind = providerKind(env);
207
237
  if (!isBuiltinKind(kind))
208
238
  throw new Error(`JADE_PROVIDER must be one of ${PROVIDER_KINDS.join(", ")}, got ${JSON.stringify(kind)}`);
@@ -222,7 +252,8 @@ export async function providerFromEnv(env = process.env) {
222
252
  maxTokens,
223
253
  reasoning: effort ? { effort, summary: "auto" } : undefined,
224
254
  idleTimeoutMs,
225
- toolResultImages
255
+ toolResultImages,
256
+ headers
226
257
  });
227
258
  }
228
259
  if (kind === "openai-compat") {
@@ -238,7 +269,8 @@ export async function providerFromEnv(env = process.env) {
238
269
  maxTokens,
239
270
  extraBody: env.OPENAI_COMPAT_EXTRA_BODY ? jsonObject("OPENAI_COMPAT_EXTRA_BODY", env.OPENAI_COMPAT_EXTRA_BODY) : undefined,
240
271
  idleTimeoutMs,
241
- toolResultImages
272
+ toolResultImages,
273
+ headers
242
274
  });
243
275
  }
244
276
  const { anthropicProvider } = await import("@uncarved/provider-anthropic");
@@ -246,8 +278,11 @@ export async function providerFromEnv(env = process.env) {
246
278
  apiKey: env.ANTHROPIC_API_KEY,
247
279
  baseURL: env.ANTHROPIC_BASE_URL ?? "https://api.anthropic.com",
248
280
  model: env.ANTHROPIC_MODEL,
249
- effort: effort ?? "high",
250
- maxTokens
281
+ effort,
282
+ maxTokens,
283
+ fallbacks: fallbacksFromEnv(env),
284
+ thinking: thinkingFromEnv(env),
285
+ headers
251
286
  });
252
287
  }
253
288
  export async function listModels(env = process.env, fetchImpl = fetch) {
@@ -1,6 +1,6 @@
1
1
  import { mkdir, readFile, writeFile } from "node:fs/promises";
2
2
  import path from "node:path";
3
- export const MODEL_SETTINGS = ["JADE_MAX_TOKENS", "JADE_EFFORT", "JADE_CONTEXT_WINDOW", "JADE_RPM", "JADE_VISION", "OPENAI_COMPAT_EXTRA_BODY"];
3
+ export const MODEL_SETTINGS = ["JADE_MAX_TOKENS", "JADE_EFFORT", "JADE_CONTEXT_WINDOW", "JADE_RPM", "JADE_VISION", "JADE_FALLBACKS", "JADE_THINKING", "OPENAI_COMPAT_EXTRA_BODY"];
4
4
  const strings = (v) => typeof v === "object" && v !== null ? Object.fromEntries(Object.entries(v).filter(([, x]) => typeof x === "string")) : {};
5
5
  export async function readSavedServices(file) {
6
6
  try {
@@ -8,6 +8,7 @@ const ID = "jade/prompts";
8
8
  const sections = [];
9
9
  const loaded = new Map;
10
10
  const notes = new Notes;
11
+ const gathered = new Map;
11
12
  function segment(text, trust = "trusted", stability = "stable", by = ID, source) {
12
13
  return { text, stability, origin: { by: "plugin", id: by, ...source ? { source } : {} }, trust };
13
14
  }
@@ -44,7 +45,11 @@ export default definePlugin({
44
45
  },
45
46
  async session(ctx) {
46
47
  const models = ctx.service("models@1");
47
- const [env, instructions] = await Promise.all([environment(ctx.cwd), allInstructions(ctx.home, ctx.cwd, ctx.config.claudeInstructions === false ? null : os.homedir())]);
48
+ const parent = ctx.session.parent?.sessionId;
49
+ const mine = (parent !== undefined ? gathered.get(parent) : undefined) ?? Promise.all([environment(ctx.cwd), allInstructions(ctx.home, ctx.cwd, ctx.config.claudeInstructions === false ? null : os.homedir())]);
50
+ gathered.set(ctx.session.id, mine);
51
+ await ctx.effect(() => () => void gathered.delete(ctx.session.id));
52
+ const [env, instructions] = await mine;
48
53
  loaded.set(ctx.session.id, instructions.map(({ text, trust, source }) => ({ text, trust, source })));
49
54
  await ctx.effect(() => () => void loaded.delete(ctx.session.id));
50
55
  const fixed = [segment(env), ...instructions.map((i) => segment(i.text, i.trust, "stable", ID, i.source))];
@@ -255,6 +255,7 @@ ${describe(t, ctx.cwd)}`;
255
255
  ctx.session.send(delivery(t)).catch((e) => ctx.signal.aborted || ui.notify(`scheduled task ${t.id} failed: ${err(e)}`, "error")).finally(() => running.delete(t.id));
256
256
  }
257
257
  };
258
+ ctx.session.afterTurn(() => void check());
258
259
  await ctx.effect(() => {
259
260
  const timer = setInterval(() => void check(), every);
260
261
  return () => clearInterval(timer);
@@ -1,7 +1,7 @@
1
1
  import { readFile } from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { spawn } from "./sys.js";
4
- const READY_MS = 1e4;
4
+ const READY_MS = 30000;
5
5
  const LOAD_MS = 15000;
6
6
  const SETTLE_MS = 3000;
7
7
  const CLOSE_MS = 5000;
@@ -36,16 +36,19 @@ export default definePlugin({
36
36
  let live = "";
37
37
  let r;
38
38
  let stopped = false;
39
+ const session = manager.current;
40
+ const exec = () => shell.run(command, {
41
+ cwd: ctx.cwd,
42
+ timeoutMs: SH_TIMEOUT_MS,
43
+ signal,
44
+ onOutput(text) {
45
+ live = (live + text).slice(-SH_LIVE_CHARS);
46
+ progress?.(live);
47
+ }
48
+ });
49
+ const undo = ctx.service("undo@1");
39
50
  try {
40
- r = await shell.run(command, {
41
- cwd: ctx.cwd,
42
- timeoutMs: SH_TIMEOUT_MS,
43
- signal,
44
- onOutput(text) {
45
- live = (live + text).slice(-SH_LIVE_CHARS);
46
- progress?.(live);
47
- }
48
- });
51
+ r = session && undo ? await undo.track(session.id, `$ ${firstLine(command)}`, exec) : await exec();
49
52
  } catch (e) {
50
53
  if (!signal.aborted)
51
54
  throw e;
@@ -60,7 +63,6 @@ export default definePlugin({
60
63
  const more = lines.length > 1 ? ` (+${lines.length - 1} lines)` : "";
61
64
  const folded = lines.length > 1 || first.length > SH_SUMMARY;
62
65
  print(shade(failed, `⎿ ${first.length > SH_SUMMARY ? `${first.slice(0, SH_SUMMARY)}…` : first}${more}`), folded ? { details: r.output.replace(/^/gm, " ") } : undefined);
63
- const session = manager.current;
64
66
  if (!stopped && session && session.state.messages.length > 0)
65
67
  return { prompt: `I ran this shell command myself (${status}):
66
68
  $ ${command}
@@ -10,7 +10,8 @@
10
10
  "ui@1",
11
11
  "prompts@1",
12
12
  "renderers@1",
13
- "commands@1"
13
+ "commands@1",
14
+ "undo@1"
14
15
  ],
15
16
  "config": {
16
17
  "shell": {
@@ -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) {