@uncarved/jade 0.4.3 → 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 (39) hide show
  1. package/README.md +317 -279
  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 +3 -3
  8. package/plugins/keys/index.ts +2 -2
  9. package/plugins/memory/index.ts +6 -4
  10. package/plugins/memory/memory.ts +101 -31
  11. package/plugins/models/index.ts +67 -9
  12. package/plugins/models/provider.ts +81 -24
  13. package/plugins/serve/index.ts +229 -0
  14. package/plugins/serve/plugin.json +8 -0
  15. package/plugins/shell/index.ts +35 -1
  16. package/plugins/shell/shell.ts +5 -0
  17. package/plugins/task/index.ts +3 -1
  18. package/plugins/task/subagent.ts +49 -3
  19. package/plugins/tui/frontend.ts +73 -4
  20. package/plugins/tui/screen.ts +23 -0
  21. package/plugins/tui/tui.ts +176 -11
  22. package/plugins-dist/keys/index.js +1 -1
  23. package/plugins-dist/memory/index.js +7 -3
  24. package/plugins-dist/memory/memory.js +81 -34
  25. package/plugins-dist/models/index.js +62 -7
  26. package/plugins-dist/models/provider.js +47 -14
  27. package/plugins-dist/serve/index.js +238 -0
  28. package/plugins-dist/serve/plugin.json +14 -0
  29. package/plugins-dist/shell/index.js +33 -0
  30. package/plugins-dist/shell/shell.js +3 -0
  31. package/plugins-dist/task/index.js +3 -1
  32. package/plugins-dist/task/subagent.js +47 -2
  33. package/plugins-dist/tui/frontend.js +67 -3
  34. package/plugins-dist/tui/screen.js +3 -0
  35. package/plugins-dist/tui/tui.js +132 -9
  36. package/plugins-dist/tui/vendor.js +1388 -1088
  37. package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
  38. package/src/api.ts +1 -1
  39. package/src/session.ts +57 -5
@@ -0,0 +1,238 @@
1
+ import { createInterface } from "node:readline";
2
+ import { stripVTControlCharacters } from "node:util";
3
+ import { definePlugin } from "@uncarved/jade-api";
4
+ const USAGE = `usage: jade --serve
5
+
6
+ Runs until stdin closes, with any number of sessions at once. One JSON object per line.
7
+ Requests (stdin); "id" is optional and is copied into the reply:
8
+ {"type":"open", "id"?, "resume"?: "<session id>"} -> {"type":"opened", "id"?, "session"}
9
+ {"type":"send", "id"?, "session", "text"} -> {"type":"done", "id"?, "session", "reason", "error"?} when that turn
10
+ has ended, however it ended (reason as in turn_end: "end", "aborted",
11
+ "error", ...); "error" only if the message never started a turn
12
+ {"type":"abort", "session"} stops the running turn
13
+ {"type":"close", "id"?, "session"} -> {"type":"closed", "id"?, "session"} (it can be resumed later)
14
+ Events (stdout), each with "session":
15
+ {"type":"text", "text"} reply text as it is written
16
+ {"type":"tool_use", "name", "input"}
17
+ {"type":"tool_error", "message"} / {"type":"denied", "reason"?}
18
+ {"type":"turn_end", "reason", "error"?, "result", "usage"} result is the turn's final reply
19
+ A request that cannot be carried out gets {"type":"error", "id"?, "session"?, "error"} instead of its reply.
20
+ When a resumed session's unfinished work fails, its turn_end says so; a failure before any turn ran is an
21
+ {"type":"error", "session", "error"} without "id" (the open was already answered with "opened").
22
+ Notices from plugins go to stderr. Exit code: 0 when stdin closes, 130 when interrupted.
23
+ Nobody can answer approval questions here, so calls that need approval are denied: in the default "ask" mode that
24
+ includes writing files. To let it change files in the working directory, put {"jade/approval": {"mode": "auto"}}
25
+ in $JADE_HOME/config.json.`;
26
+ export const ui = {
27
+ interactive: false,
28
+ notify(message, level = "info") {
29
+ process.stderr.write(`${level === "info" ? "" : `[${level}] `}${stripVTControlCharacters(String(message))}
30
+ `);
31
+ },
32
+ select: async () => {
33
+ return;
34
+ },
35
+ input: async () => {
36
+ return;
37
+ }
38
+ };
39
+ const emit = (event) => {
40
+ process.stdout.write(`${JSON.stringify(event)}
41
+ `);
42
+ };
43
+ const frontend = {
44
+ async run({ argv, sessions }) {
45
+ if (argv.includes("-h") || argv.includes("--help")) {
46
+ process.stdout.write(`${USAGE}
47
+ `);
48
+ return 0;
49
+ }
50
+ const extra = argv.filter((a) => a !== "--serve");
51
+ if (extra.length > 0) {
52
+ process.stderr.write(`unknown argument ${extra[0]}
53
+
54
+ ${USAGE}
55
+ `);
56
+ return 2;
57
+ }
58
+ const start = sessions.start?.bind(sessions);
59
+ if (!start) {
60
+ process.stderr.write(`jade: this jade cannot run several sessions at once
61
+ `);
62
+ return 1;
63
+ }
64
+ const open = new Map;
65
+ const ended = new Map;
66
+ const pending = new Set;
67
+ const track = (p) => {
68
+ pending.add(p);
69
+ p.finally(() => pending.delete(p));
70
+ };
71
+ const attach = (s) => {
72
+ const session = s.id;
73
+ let result = "";
74
+ let used = { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 };
75
+ let streamed = false;
76
+ s.subscribe((n) => {
77
+ if (n.type === "delta" && n.delta.kind === "text") {
78
+ streamed = true;
79
+ emit({ type: "text", session, text: n.delta.text });
80
+ }
81
+ if (n.type !== "event")
82
+ return;
83
+ const e = n.event;
84
+ if (e.type === "model.responded") {
85
+ const { content, usage } = e.data;
86
+ const text = content.flatMap((b) => b.kind === "text" ? [b.text] : []).join(`
87
+ `);
88
+ if (text)
89
+ result = text;
90
+ for (const k of Object.keys(used))
91
+ used[k] += usage?.[k] ?? 0;
92
+ if (!streamed && text)
93
+ emit({ type: "text", session, text });
94
+ streamed = false;
95
+ for (const b of content)
96
+ if (b.kind === "tool_use")
97
+ emit({ type: "tool_use", session, name: b.name, input: b.input });
98
+ }
99
+ if (e.type === "tool.decided") {
100
+ const d = e.data;
101
+ if (d.decision === "deny")
102
+ emit({ type: "denied", session, ...d.reason ? { reason: stripVTControlCharacters(d.reason) } : {} });
103
+ }
104
+ if (e.type === "tool.completed") {
105
+ const d = e.data;
106
+ if (d.isError)
107
+ emit({ type: "tool_error", session, message: stripVTControlCharacters(firstLine(d.content)) });
108
+ }
109
+ if (e.type === "turn.ended") {
110
+ const d = e.data;
111
+ emit({ type: "turn_end", session, reason: d.reason, ...d.error ? { error: d.error } : {}, result, usage: used });
112
+ ended.set(session, { count: (ended.get(session)?.count ?? 0) + 1, reason: d.reason, ...d.error ? { error: d.error } : {} });
113
+ result = "";
114
+ used = { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 };
115
+ }
116
+ });
117
+ };
118
+ const handle = async (req) => {
119
+ const id = req.id !== undefined ? { id: req.id } : {};
120
+ const fail = (e, session) => emit({ type: "error", ...id, ...session ? { session } : {}, error: errorText(e) });
121
+ const target = () => {
122
+ const s = typeof req.session === "string" ? open.get(req.session) : undefined;
123
+ if (!s)
124
+ fail(new Error(typeof req.session === "string" ? `no open session ${req.session}` : `"session" is missing`), typeof req.session === "string" ? req.session : undefined);
125
+ return s;
126
+ };
127
+ switch (req.type) {
128
+ case "open": {
129
+ if (req.resume !== undefined && typeof req.resume !== "string")
130
+ return fail(new Error(`"resume" must be a session id`));
131
+ let s;
132
+ try {
133
+ s = await start(typeof req.resume === "string" ? { resume: req.resume } : {});
134
+ } catch (e) {
135
+ return fail(e);
136
+ }
137
+ open.set(s.id, s);
138
+ attach(s);
139
+ emit({ type: "opened", ...id, session: s.id });
140
+ if (typeof req.resume === "string") {
141
+ const before = ended.get(s.id)?.count ?? 0;
142
+ await s.recover().catch((e) => {
143
+ if ((ended.get(s.id)?.count ?? 0) === before)
144
+ emit({ type: "error", session: s.id, error: errorText(e) });
145
+ });
146
+ }
147
+ return;
148
+ }
149
+ case "send": {
150
+ if (typeof req.text !== "string" || !req.text)
151
+ return fail(new Error(`"text" must be a non-empty string`), typeof req.session === "string" ? req.session : undefined);
152
+ const s = target();
153
+ if (!s)
154
+ return;
155
+ const before = ended.get(s.id)?.count ?? 0;
156
+ const done = () => {
157
+ const last = ended.get(s.id);
158
+ if (!last || last.count === before)
159
+ return false;
160
+ emit({ type: "done", ...id, session: s.id, reason: last.reason, ...last.error ? { error: last.error } : {} });
161
+ return true;
162
+ };
163
+ try {
164
+ await s.send({ kind: "message", content: [{ kind: "text", text: req.text, origin: { by: "user" }, trust: "trusted" }] });
165
+ if (!done())
166
+ emit({ type: "done", ...id, session: s.id, reason: "end" });
167
+ } catch (e) {
168
+ if (!done())
169
+ fail(e, s.id);
170
+ }
171
+ return;
172
+ }
173
+ case "abort": {
174
+ target()?.abort(new Error("aborted by the client"));
175
+ return;
176
+ }
177
+ case "close": {
178
+ const s = target();
179
+ if (!s)
180
+ return;
181
+ open.delete(s.id);
182
+ await s.close();
183
+ emit({ type: "closed", ...id, session: s.id });
184
+ return;
185
+ }
186
+ default:
187
+ return fail(new Error(`unknown request type ${JSON.stringify(req.type)}`));
188
+ }
189
+ };
190
+ let interrupted = false;
191
+ const rl = createInterface({ input: process.stdin, crlfDelay: 1 / 0 });
192
+ const interrupt = () => {
193
+ interrupted = true;
194
+ for (const s of open.values())
195
+ s.abort(new Error("interrupted"));
196
+ rl.close();
197
+ };
198
+ process.once("SIGINT", interrupt);
199
+ try {
200
+ for await (const line of rl) {
201
+ if (!line.trim())
202
+ continue;
203
+ let req;
204
+ try {
205
+ req = JSON.parse(line);
206
+ if (typeof req !== "object" || req === null || Array.isArray(req))
207
+ throw new Error("a request must be a JSON object");
208
+ } catch (e) {
209
+ emit({ type: "error", error: `bad request: ${errorText(e)}` });
210
+ continue;
211
+ }
212
+ track(handle(req));
213
+ }
214
+ while (pending.size > 0)
215
+ await Promise.allSettled([...pending]);
216
+ for (const s of open.values())
217
+ await s.close();
218
+ } finally {
219
+ process.off("SIGINT", interrupt);
220
+ }
221
+ return interrupted ? 130 : 0;
222
+ }
223
+ };
224
+ export default definePlugin({
225
+ process(ctx) {
226
+ ctx.provide("ui@1", ui);
227
+ ctx.provide("frontend@1", frontend);
228
+ }
229
+ });
230
+ function errorText(e) {
231
+ const cause = e instanceof Error && e.cause instanceof Error ? e.cause : e;
232
+ return cause instanceof Error ? cause.message : String(cause);
233
+ }
234
+ function firstLine(content) {
235
+ const text = content.find((b) => b.kind === "text");
236
+ return text && "text" in text ? text.text.split(`
237
+ `)[0] : "(no message)";
238
+ }
@@ -0,0 +1,14 @@
1
+ {
2
+ "id": "jade/serve",
3
+ "version": "0.1.0",
4
+ "api": "^1",
5
+ "entry": "./index.js",
6
+ "provides": [
7
+ "frontend@1",
8
+ "ui@1"
9
+ ],
10
+ "frontend": {
11
+ "name": "serve",
12
+ "flag": "--serve"
13
+ }
14
+ }
@@ -11,6 +11,7 @@ const firstLine = (command) => {
11
11
  const SH_TIMEOUT_MS = 600000;
12
12
  const SH_LIVE_CHARS = 4000;
13
13
  const SH_SUMMARY = 160;
14
+ const MAX_FINISHED_JOBS = 10;
14
15
  const shade = (failed, text) => ({ text, style: failed ? "error" : "dim" });
15
16
  export default definePlugin({
16
17
  process(ctx) {
@@ -94,6 +95,9 @@ ${r.output}`);
94
95
  async session(ctx) {
95
96
  const shell = typeof ctx.config.shell === "string" ? ctx.config.shell : undefined;
96
97
  const id = ctx.session.id;
98
+ const jobs = new Set;
99
+ const stoppedByUser = new Set;
100
+ const finished = [];
97
101
  const { tools, executable, unavailable, shutdown, list, kill } = shellTools({
98
102
  cwd: ctx.cwd,
99
103
  ...shell ? { shell } : {},
@@ -101,6 +105,33 @@ ${r.output}`);
101
105
  const what = `Background shell ${bg.id} (${firstLine(bg.command)}) exited with code ${bg.exitCode}`;
102
106
  ctx.service("ui@1")?.notify(what, bg.exitCode === 0 ? "info" : "warning");
103
107
  ctx.service("prompts@1")?.note(id, `${what}. Read its remaining output with bash_output.`);
108
+ },
109
+ onBackground(bg) {
110
+ const job = ctx.service("ui@1")?.job?.({
111
+ session: id,
112
+ kind: "shell",
113
+ title: `${bg.id} ${firstLine(bg.command)}`,
114
+ async stop() {
115
+ stoppedByUser.add(bg.id);
116
+ if (await kill(bg.id))
117
+ ctx.service("prompts@1")?.note(id, `The user stopped background shell ${bg.id} (${firstLine(bg.command)}).`);
118
+ }
119
+ });
120
+ if (!job)
121
+ return;
122
+ jobs.add(job);
123
+ job.status("running");
124
+ return {
125
+ output: (text) => job.append(text),
126
+ exit: (code, killed) => {
127
+ job.status(stoppedByUser.has(bg.id) ? "stopped by you" : killed ? "stopped" : `exited with code ${code}`, true);
128
+ finished.push(job);
129
+ for (const old of finished.splice(0, Math.max(0, finished.length - MAX_FINISHED_JOBS))) {
130
+ old.dispose();
131
+ jobs.delete(old);
132
+ }
133
+ }
134
+ };
104
135
  }
105
136
  });
106
137
  sessions.set(id, { list, kill });
@@ -125,6 +156,8 @@ ${r.output}`);
125
156
  await ctx.effect(() => () => {
126
157
  sessions.delete(id);
127
158
  shutdown();
159
+ for (const job of jobs)
160
+ job.dispose();
128
161
  });
129
162
  }
130
163
  });
@@ -26,7 +26,9 @@ export function shellTools(opts) {
26
26
  async function startBackground(command) {
27
27
  const id = `bg${nextId++}`;
28
28
  const bg = { id, command, proc: await spawn(command), unread: "", dropped: 0 };
29
+ const watcher = opts.onBackground?.({ id, command });
29
30
  const append = (text) => {
31
+ watcher?.output(text);
30
32
  bg.unread += text;
31
33
  if (bg.unread.length > MAX_BUFFER_CHARS) {
32
34
  bg.dropped += bg.unread.length - MAX_BUFFER_CHARS;
@@ -36,6 +38,7 @@ export function shellTools(opts) {
36
38
  Promise.all([collect(bg.proc.stdout, append, false), collect(bg.proc.stderr, append, false)]).catch(() => {});
37
39
  bg.proc.exited.then((code) => {
38
40
  bg.exitCode = code;
41
+ watcher?.exit(code, bg.killed === true);
39
42
  if (!bg.killed)
40
43
  opts.onExit?.({ id, command, exitCode: code });
41
44
  });
@@ -80,7 +80,9 @@ export default definePlugin({
80
80
  controls.set(child, control);
81
81
  return () => void controls.delete(child);
82
82
  },
83
- usage: (toolUseId, u) => void usage.set(toolUseId, u)
83
+ usage: (toolUseId, u) => void usage.set(toolUseId, u),
84
+ job: (description, stop) => ctx.service("ui@1")?.job?.({ session: ctx.session.id, kind: "agent", title: description, stop }),
85
+ describe: (name, input) => ctx.service("renderers@1")?.forTool(name)?.renderer.summary?.(input) ?? clip(JSON.stringify(input) ?? "", 120)
84
86
  }));
85
87
  ctx.kernel.hook({
86
88
  kind: "transform",
@@ -6,6 +6,8 @@ export const CHARS_PER_TOKEN = 4;
6
6
  export const OMITTED = "[Output omitted to fit the context window. Use what you noted from it in your later messages.]";
7
7
  export const WRAP_UP = "You have reached your step limit. Do not call any more tools: write your report now from what you have found so far, " + "and say what you could not check.";
8
8
  export const READ_ONLY_REASON = (name) => `${name}: sub-agents can only run read-only commands inside the working directory (for example git log, git diff, ls, rg). Describe anything else in your report instead.`;
9
+ export const STOPPED = "The user stopped this sub-agent before it finished. Do not start it again unless the user asks.";
10
+ const JOB_RESULT_CHARS = 160;
9
11
  const MAX_REPORT_CHARS = 20000;
10
12
  export function subagentPrompt(steps, write) {
11
13
  return `You are a ${write ? "" : "read-only "}research sub-agent for a coding agent. Investigate the task you are given, then reply with a concise report: the answer first, then the evidence as path:line references (or URLs for web pages).
@@ -76,24 +78,54 @@ export function taskTool(opts) {
76
78
  const unregister = opts.register(child.id, control);
77
79
  const progress = (p) => ctx.progress(p);
78
80
  progress({ kind: "task-start", sessionId: child.id, description });
81
+ let stopped = false;
82
+ const job = opts.job?.(description, () => {
83
+ stopped = true;
84
+ child.abort("stopped by the user");
85
+ });
86
+ job?.status("starting");
87
+ const describe = (name, input) => opts.describe?.(name, input) ?? clipText(JSON.stringify(input) ?? "", JOB_RESULT_CHARS);
79
88
  const names = new Map;
80
89
  const unsubscribe = child.subscribe((n) => {
81
90
  if (n.type !== "event")
82
91
  return;
83
92
  if (n.event.type === "model.requested") {
84
93
  progress({ kind: "task-model" });
94
+ job?.status("thinking");
85
95
  } else if (n.event.type === "model.responded") {
86
96
  const data = n.event.data;
87
97
  for (const b of data.content)
88
98
  if (b.kind === "tool_use")
89
99
  names.set(b.id, b.name);
100
+ const said = data.content.flatMap((b) => b.kind === "text" && b.text.trim() ? [b.text.trim()] : []).join(`
101
+ `);
102
+ if (said)
103
+ job?.append(`${said}
104
+
105
+ `);
90
106
  for (const k of Object.keys(used))
91
107
  used[k] += data.usage?.[k] ?? 0;
92
108
  if (data.usage)
93
109
  control.lastTokens = (data.usage.inputTokens ?? 0) + (data.usage.outputTokens ?? 0);
94
110
  } else if (n.event.type === "tool.decided") {
95
111
  const d = n.event.data;
96
- progress({ kind: "task-tool", name: names.get(d.toolUseId) ?? "?", input: d.input, decision: d.decision });
112
+ const name = names.get(d.toolUseId) ?? "?";
113
+ progress({ kind: "task-tool", name, input: d.input, decision: d.decision });
114
+ if (job) {
115
+ const call = [`● ${name}(`, describe(name, d.input), ")"];
116
+ job.status(`${name}(${plain(describe(name, d.input))})`);
117
+ job.append(d.decision === "deny" ? [call, { text: ` ✗ denied${d.reason ? `: ${d.reason}` : ""}`, style: "error" }, `
118
+ `] : [call, `
119
+ `]);
120
+ }
121
+ } else if (n.event.type === "tool.completed" && job) {
122
+ const d = n.event.data;
123
+ const out = d.content.flatMap((b) => b.kind === "text" ? [b.text] : []).join(`
124
+ `).trim().split(`
125
+ `);
126
+ const more = out.length > 1 ? ` (+${out.length - 1} lines)` : "";
127
+ job.append([{ text: ` ⎿ ${clipText(out[0] ?? "", JOB_RESULT_CHARS)}${more}`, style: d.isError ? "error" : "dim" }, `
128
+ `]);
97
129
  }
98
130
  });
99
131
  const forward = () => child.abort(String(ctx.signal.reason ?? "aborted"));
@@ -114,7 +146,7 @@ export function taskTool(opts) {
114
146
  }
115
147
  const cause = unwrap(failure);
116
148
  const exhausted = cause instanceof ProviderError && cause.retryable;
117
- if (!ctx.signal.aborted && !exhausted && !lastText(child.state.messages)) {
149
+ if (!ctx.signal.aborted && !stopped && !exhausted && !lastText(child.state.messages)) {
118
150
  control.wrapUp = true;
119
151
  try {
120
152
  await turn(WRAP_UP);
@@ -133,12 +165,17 @@ export function taskTool(opts) {
133
165
  return;
134
166
  });
135
167
  unregister();
168
+ job?.dispose();
136
169
  opts.usage?.(ctx.toolUseId, used);
137
170
  }
138
171
  if (ctx.signal.aborted)
139
172
  throw failure ?? ctx.signal.reason;
140
173
  const linked = ref ? { child: ref } : {};
141
174
  const text = clip(lastText(messages) || allText(messages));
175
+ if (stopped && failure)
176
+ return { content: `${STOPPED}${text ? `
177
+ What it had written so far:
178
+ ${text}` : ""}`, isError: true, ...linked };
142
179
  if (failure) {
143
180
  const msg = failure instanceof Error ? failure.message : String(failure);
144
181
  return { content: `Sub-agent failed: ${msg}${text ? `
@@ -170,6 +207,14 @@ function allText(messages) {
170
207
 
171
208
  `);
172
209
  }
210
+ const clipText = (s, n) => s.length > n ? `${s.slice(0, n)}…` : s;
211
+ function plain(t) {
212
+ if (typeof t === "string")
213
+ return t;
214
+ if (Array.isArray(t))
215
+ return t.map(plain).join("");
216
+ return String(t.text ?? "");
217
+ }
173
218
  function clip(s) {
174
219
  return s.length > MAX_REPORT_CHARS ? `${s.slice(0, MAX_REPORT_CHARS)}
175
220
  … (report truncated: ${s.length - MAX_REPORT_CHARS} more characters)` : s;
@@ -24,6 +24,7 @@ Run one prompt without the interface: jade -p <prompt> (jade -p --help for more)
24
24
  jade's own commands (plugins, update, --safe): jade help`;
25
25
  const OWN = [
26
26
  { name: "help", about: "list the commands and keys" },
27
+ { name: "tasks", about: "list sub-agents and background commands (same as ctrl+t)" },
27
28
  { name: "exit", about: "quit (the session stays resumable)" }
28
29
  ];
29
30
  const KEYS = [
@@ -31,7 +32,7 @@ const KEYS = [
31
32
  " send enter send · ctrl+j, alt+enter or \\ then enter: new line · tab completes /commands",
32
33
  " input ↑↓ history · ctrl+r search history · ↑ on the first line edits queued messages · esc twice or ctrl+c clears the input",
33
34
  " editing ctrl+←/→ or alt+b/f move by words · ctrl+w or alt+backspace delete a word · ctrl+a/e line start/end · ctrl+u/k delete to start/end",
34
- " running esc interrupt (twice to also move queued messages back to the input) · ctrl+c twice to exit",
35
+ " running esc interrupt (twice to also move queued messages back to the input) · ctrl+c twice to exit · ctrl+t, /tasks or a click on the status bar lists sub-agents and background commands",
35
36
  " transcript pgup/pgdn scroll · ctrl+home/end top/bottom · ctrl+o expands the latest item, a click the one under it · drag to select and copy · ctrl+l redraw"
36
37
  ].join(`
37
38
  `);
@@ -93,10 +94,14 @@ export class ScreenBridge {
93
94
  #segments = new Map;
94
95
  #panels = new Map;
95
96
  #session;
97
+ #notices = 0;
98
+ #jobs = [];
99
+ #nextJob = 0;
100
+ #jobTimer;
96
101
  ui = {
97
102
  interactive: true,
98
103
  notify: (message, level = "info") => {
99
- const text = level === "error" ? red(`[error] ${message}`) : level === "warning" ? yellow(`[warning] ${message}`) : dim(message);
104
+ const text = noticeText(message, level);
100
105
  if (this.#held)
101
106
  this.#held.push(text);
102
107
  else if (this.screen)
@@ -107,6 +112,13 @@ export class ScreenBridge {
107
112
  else
108
113
  this.#early.push(text);
109
114
  },
115
+ notice: (message, level = "info") => {
116
+ if (this.#held || !this.screen?.note)
117
+ return;
118
+ const id = `\x00notice-${++this.#notices}`;
119
+ this.screen.note(id, noticeText(message, level));
120
+ return { update: (m, l = "info") => this.screen?.note?.(id, noticeText(m, l)) };
121
+ },
110
122
  select: async (req, signal) => {
111
123
  if (!this.screen)
112
124
  return;
@@ -124,7 +136,8 @@ export class ScreenBridge {
124
136
  return true;
125
137
  },
126
138
  suspend: async (fn) => this.screen?.suspend ? this.screen.suspend(fn) : fn(),
127
- session: ({ session, plugin }) => this.#sessionUI(session, plugin)
139
+ session: ({ session, plugin }) => this.#sessionUI(session, plugin),
140
+ job: (req) => this.#job(req)
128
141
  };
129
142
  attach(screen) {
130
143
  this.screen = screen;
@@ -145,12 +158,53 @@ export class ScreenBridge {
145
158
  }
146
159
  }
147
160
  detach() {
161
+ clearTimeout(this.#jobTimer);
148
162
  this.screen = undefined;
149
163
  this.#closed = true;
150
164
  }
151
165
  show(session) {
152
166
  this.#session = session;
153
167
  this.#apply();
168
+ this.#applyJobs();
169
+ }
170
+ #job(req) {
171
+ const entry = {
172
+ id: ++this.#nextJob,
173
+ session: String(req.session),
174
+ kind: String(req.kind),
175
+ title: String(req.title),
176
+ status: "",
177
+ done: false,
178
+ output: "",
179
+ ...req.stop ? { stop: () => req.stop() } : {}
180
+ };
181
+ this.#jobs = [...this.#jobs, { ...entry }];
182
+ this.#applyJobs();
183
+ const update = (patch, soon = false) => {
184
+ if (!this.#jobs.some((j) => j.id === entry.id))
185
+ return;
186
+ Object.assign(entry, patch);
187
+ this.#jobs = this.#jobs.map((j) => j.id === entry.id ? { ...entry } : j);
188
+ if (soon)
189
+ this.#jobTimer ??= setTimeout(() => this.#applyJobs(), JOB_REDRAW_MS);
190
+ else
191
+ this.#applyJobs();
192
+ };
193
+ return {
194
+ append: (text) => update({ output: (entry.output + ansi(text)).slice(-MAX_JOB_OUTPUT) }, true),
195
+ status: (text, done) => update({ status: String(text), done: done === true }),
196
+ dispose: () => {
197
+ const before = this.#jobs.length;
198
+ this.#jobs = this.#jobs.filter((j) => j.id !== entry.id);
199
+ if (this.#jobs.length !== before)
200
+ this.#applyJobs();
201
+ }
202
+ };
203
+ }
204
+ #applyJobs() {
205
+ clearTimeout(this.#jobTimer);
206
+ this.#jobTimer = undefined;
207
+ this.screen?.jobs?.(this.#jobs.filter((j) => j.session === this.#session));
154
208
  }
155
209
  #apply() {
156
210
  if (!this.screen)
@@ -204,6 +258,9 @@ export class ScreenBridge {
204
258
  };
205
259
  }
206
260
  }
261
+ const MAX_JOB_OUTPUT = 1e5;
262
+ const JOB_REDRAW_MS = 100;
263
+ const noticeText = (message, level) => level === "error" ? red(`[error] ${message}`) : level === "warning" ? yellow(`[warning] ${message}`) : dim(message);
207
264
  function clipPanel(text) {
208
265
  const lines = String(text).replace(/\r\n?/g, `
209
266
  `).replace(/\n+$/, "").split(`
@@ -544,6 +601,13 @@ ${USAGE}
544
601
  const rest = input.slice(1).replace(/^\S+\s*/, "");
545
602
  if (name === "exit" || name === "quit")
546
603
  return false;
604
+ if (name === "tasks") {
605
+ if (screen.showJobs)
606
+ screen.showJobs();
607
+ else
608
+ screen.log(dim("[background tasks are only listed in the terminal interface]"));
609
+ return true;
610
+ }
547
611
  if (name === "help") {
548
612
  const extras = [
549
613
  ...commands.list().flatMap((c) => c.prefix ? [`${c.prefix}${c.args ?? ""} is /${c.name}`] : []),
@@ -66,6 +66,9 @@ export function safeScreen(screen) {
66
66
  interactive: screen.interactive,
67
67
  log: (text, o) => screen.log(s(text), o && { ...o, details: opt(o.details) }),
68
68
  amend: (id, text, o) => screen.amend(id, s(text), o && { ...o, details: opt(o.details) }),
69
+ ...screen.note ? { note: (id, text) => screen.note(id, s(text)) } : {},
70
+ ...screen.jobs ? { jobs: (jobs) => screen.jobs(jobs.map((j) => ({ ...j, title: s(j.title), status: s(j.status), output: s(j.output) }))) } : {},
71
+ ...screen.showJobs ? { showJobs: () => screen.showJobs() } : {},
69
72
  progress: (id, line, o) => screen.progress(id, opt(line), o),
70
73
  stream: (kind, text) => {
71
74
  if (held && held.kind !== kind)