@uncarved/jade 0.4.3 → 0.5.1

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 (41) 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/membrane.d.ts +5 -2
  5. package/dist/membrane.js +8 -3
  6. package/dist/membrane.js.map +1 -1
  7. package/dist/session.d.ts +14 -3
  8. package/dist/session.js +164 -22
  9. package/dist/session.js.map +1 -1
  10. package/package.json +4 -4
  11. package/plugins/keys/index.ts +2 -2
  12. package/plugins/memory/index.ts +6 -4
  13. package/plugins/memory/memory.ts +101 -31
  14. package/plugins/models/index.ts +67 -9
  15. package/plugins/models/provider.ts +81 -24
  16. package/plugins/serve/index.ts +236 -0
  17. package/plugins/serve/plugin.json +8 -0
  18. package/plugins/shell/index.ts +35 -1
  19. package/plugins/shell/shell.ts +5 -0
  20. package/plugins/task/index.ts +3 -1
  21. package/plugins/task/subagent.ts +49 -3
  22. package/plugins/tui/frontend.ts +73 -4
  23. package/plugins/tui/screen.ts +23 -0
  24. package/plugins/tui/tui.ts +176 -11
  25. package/plugins-dist/keys/index.js +1 -1
  26. package/plugins-dist/memory/index.js +7 -3
  27. package/plugins-dist/memory/memory.js +81 -34
  28. package/plugins-dist/models/index.js +62 -7
  29. package/plugins-dist/models/provider.js +47 -14
  30. package/plugins-dist/serve/index.js +244 -0
  31. package/plugins-dist/serve/plugin.json +14 -0
  32. package/plugins-dist/shell/index.js +33 -0
  33. package/plugins-dist/shell/shell.js +3 -0
  34. package/plugins-dist/task/index.js +3 -1
  35. package/plugins-dist/task/subagent.js +47 -2
  36. package/plugins-dist/tui/frontend.js +67 -3
  37. package/plugins-dist/tui/screen.js +3 -0
  38. package/plugins-dist/tui/tui.js +132 -9
  39. package/src/api.ts +1 -1
  40. package/src/membrane.ts +8 -3
  41. package/src/session.ts +181 -25
@@ -62,16 +62,19 @@ export function withRetry(inner: Provider, opts: RetryOptions = {}): Provider {
62
62
  const failures: RetryRecord[] = [];
63
63
  for (let attempt = 1; ; attempt++) {
64
64
  let streamed = false;
65
- await opts.gate?.acquire(options.signal, opts.onWait && ((delayMs) => opts.onWait!({ delayMs, request })));
65
+ const done = await opts.gate?.acquire(options.signal, opts.onWait && ((delayMs) => opts.onWait!({ delayMs, request })));
66
66
  opts.onRequest?.(attempt);
67
67
  try {
68
- const res = await inner.complete(request, {
69
- ...options,
70
- onDelta: (d) => {
71
- streamed = true;
72
- options.onDelta?.(d);
73
- },
74
- });
68
+ const res = await inner
69
+ .complete(request, {
70
+ ...options,
71
+ onDelta: (d) => {
72
+ streamed = true;
73
+ options.onDelta?.(d);
74
+ },
75
+ })
76
+ // 限速从请求结束算起(见 RateGate);失败的也要在下面推上限之前算结束
77
+ .finally(() => done?.());
75
78
  // 实际回复的是被包装者(4.7 第 3 款)
76
79
  return { ...res, provider: res.provider ?? inner.id, ...(failures.length > 0 ? { retries: failures } : {}) };
77
80
  } catch (err) {
@@ -115,15 +118,28 @@ export interface RateGateOptions {
115
118
  onLearn?: (rpm: number) => void;
116
119
  }
117
120
 
121
+ /** 限速窗口:一分钟,再留一点余量,免得正好卡在服务端窗口的边上 */
122
+ const WINDOW_MS = 60_000;
123
+ const WINDOW_MARGIN_MS = 1_000;
124
+
125
+ /** 经过限速发出的一个请求:at 是结束的时间,还没结束时是发出的时间 */
126
+ interface Sent {
127
+ at: number;
128
+ inFlight: boolean;
129
+ finished: Promise<void>;
130
+ }
131
+
118
132
  /**
119
133
  * 同一个服务的所有请求共用的限速。免费模型常常按每分钟请求数限流,主 Agent、并行的子 Agent、压缩各自重试会一起撞上去。
120
- * - 有上限(JADE_RPM,或者被限流后推出来的)时,相邻两个请求至少间隔 60s / 上限,平均分布在一分钟里
134
+ * - 有上限(JADE_RPM,或者被限流后推出来的)时按滑动窗口:最近一分钟里结束的请求(加上还没结束的)不到上限才发。
135
+ * 从请求结束算起:服务端常常在请求结束时才记一次,从发出时算、按 60s / 上限平均间隔的话,
136
+ * 每隔上限个请求就正好卡在窗口边上被拒,每次再白等一个 Retry-After
121
137
  * - 收到 429 后,所有请求都等到重试时间之后再发
122
138
  */
123
139
  export class RateGate {
124
140
  #rpm: number | undefined;
125
141
  readonly #explicit: boolean;
126
- #sent: number[] = [];
142
+ #sent: Sent[] = [];
127
143
  #until = 0;
128
144
  #queue: Promise<void> = Promise.resolve();
129
145
  readonly #now: () => number;
@@ -141,24 +157,48 @@ export class RateGate {
141
157
  return this.#rpm;
142
158
  }
143
159
 
144
- /** 等到可以发下一个请求,并记下这个请求。排队的请求按先来后到;轮到它但还要等时调用 onWait(只告诉这个请求的调用方) */
145
- acquire(signal: AbortSignal, onWait?: (ms: number) => void): Promise<void> {
160
+ /**
161
+ * 等到可以发下一个请求,并记下这个请求;返回的函数在请求结束(成功或失败)时调用。
162
+ * 排队的请求按先来后到;轮到它但还要等时调用 onWait(只告诉这个请求的调用方)
163
+ */
164
+ acquire(signal: AbortSignal, onWait?: (ms: number) => void): Promise<() => void> {
146
165
  const turn = this.#queue.then(async () => {
147
166
  signal.throwIfAborted();
148
- for (let wait = this.#delay(); wait > 0; wait = this.#delay()) {
167
+ for (let wait = this.#delay(); wait !== 0; wait = this.#delay()) {
168
+ // 挡路的请求还没结束:等它结束再算还要等多久
169
+ if (typeof wait !== "number") {
170
+ await untilSettled(wait, signal);
171
+ continue;
172
+ }
149
173
  this.#opts.onWait?.(wait);
150
174
  onWait?.(wait);
151
175
  await sleep(wait, signal);
152
176
  }
153
- this.#sent.push(this.#now());
177
+ let finish!: () => void;
178
+ const sent: Sent = { at: this.#now(), inFlight: true, finished: new Promise((r) => (finish = r)) };
179
+ this.#sent.push(sent);
180
+ return () => {
181
+ if (!sent.inFlight) return;
182
+ sent.inFlight = false;
183
+ sent.at = this.#now();
184
+ finish();
185
+ };
154
186
  });
155
- this.#queue = turn.catch(() => {});
187
+ this.#queue = turn.then(
188
+ () => {},
189
+ () => {},
190
+ );
156
191
  // 排队时被取消的也要立即返回(I-9);轮到它时看到已取消,不会记成发出了请求
157
192
  return new Promise((resolve, reject) => {
158
- const stop = () => reject(signal.reason);
193
+ let stopped = false;
194
+ const stop = () => {
195
+ stopped = true;
196
+ reject(signal.reason);
197
+ };
159
198
  if (signal.aborted) return stop();
160
199
  signal.addEventListener("abort", stop, { once: true });
161
- turn.then(resolve, reject).finally(() => signal.removeEventListener("abort", stop));
200
+ // 刚记下就被取消了:请求不会发,马上算它结束,不然它一直占着窗口
201
+ turn.then((done) => (stopped ? done() : resolve(done)), reject).finally(() => signal.removeEventListener("abort", stop));
162
202
  });
163
203
  }
164
204
 
@@ -179,21 +219,38 @@ export class RateGate {
179
219
  }
180
220
  }
181
221
 
222
+ /** 还算在窗口里的请求数:没结束的,和最近一分钟里结束的 */
182
223
  #recent(now: number): number {
183
- this.#sent = this.#sent.filter((t) => now - t < 60_000);
224
+ this.#sent = this.#sent.filter((s) => s.inFlight || now - s.at < WINDOW_MS + WINDOW_MARGIN_MS);
184
225
  return this.#sent.length;
185
226
  }
186
227
 
187
- #delay(): number {
228
+ /** 还要等多少毫秒;要等一个还没结束的请求时返回它结束的 Promise */
229
+ #delay(): number | Promise<void> {
188
230
  const now = this.#now();
189
- this.#recent(now);
190
- let wait = this.#until - now;
191
- const last = this.#sent.at(-1);
192
- if (this.#rpm !== undefined && last !== undefined) wait = Math.max(wait, last + 60_000 / this.#rpm - now);
193
- return Math.ceil(wait);
231
+ const wait = Math.max(0, this.#until - now);
232
+ if (this.#rpm === undefined || this.#recent(now) < this.#rpm) return Math.ceil(wait);
233
+ // 要等窗口里最早的几个出去,剩下的不到上限;没结束的最晚出去
234
+ const order = [...this.#sent].sort((a, b) => (a.inFlight ? Infinity : a.at) - (b.inFlight ? Infinity : b.at));
235
+ const blocker = order[order.length - this.#rpm]!;
236
+ if (blocker.inFlight) return blocker.finished;
237
+ return Math.ceil(Math.max(wait, blocker.at + WINDOW_MS + WINDOW_MARGIN_MS - now));
194
238
  }
195
239
  }
196
240
 
241
+ /** 等 p 完成;signal 中止时立即以它的原因失败 */
242
+ function untilSettled(p: Promise<void>, signal: AbortSignal): Promise<void> {
243
+ return new Promise((resolve, reject) => {
244
+ const stop = () => reject(signal.reason);
245
+ if (signal.aborted) return stop();
246
+ signal.addEventListener("abort", stop, { once: true });
247
+ p.then(() => {
248
+ signal.removeEventListener("abort", stop);
249
+ resolve();
250
+ });
251
+ });
252
+ }
253
+
197
254
  function sleep(ms: number, signal: AbortSignal): Promise<void> {
198
255
  return new Promise((resolve, reject) => {
199
256
  const done = () => {
@@ -0,0 +1,236 @@
1
+ // jade/serve:jade --serve,无头、常驻,一个进程同时跑多个会话。stdin 每行一个 JSON 请求,stdout 每行一个 JSON 事件;提示写到 stderr。
2
+ // 会话用核心的 sessions.start 开:彼此并存,没有"当前会话"。不能向用户提问:ui@1 的 select 总是返回 undefined,要审批的调用由审批插件拒绝。
3
+
4
+ import { createInterface } from "node:readline";
5
+ import { stripVTControlCharacters } from "node:util";
6
+ import type { Block, LogEvent, RuntimeNotice, Usage } from "uncarved";
7
+ import { definePlugin, type Frontend, type StartedSession, type UI } from "@uncarved/jade-api";
8
+
9
+ const USAGE = `usage: jade --serve
10
+
11
+ Runs until stdin closes, with any number of sessions at once. One JSON object per line.
12
+ Requests (stdin); "id" is optional and is copied into the reply:
13
+ {"type":"open", "id"?, "resume"?: "<session id>"} -> {"type":"opened", "id"?, "session"}
14
+ {"type":"send", "id"?, "session", "text"} -> {"type":"done", "id"?, "session", "reason", "error"?} when that turn
15
+ has ended, however it ended (reason as in turn_end: "end", "aborted",
16
+ "error", ...); "error" only if the message never started a turn
17
+ {"type":"abort", "session"} stops the running turn
18
+ {"type":"close", "id"?, "session"} -> {"type":"closed", "id"?, "session"} (it can be resumed later)
19
+ stops the running turn first; if it has not stopped within 10 s
20
+ (a tool ignoring the abort), it is closed anyway and that turn's
21
+ send gets "error" instead of "done"; plugin cleanup may then take
22
+ up to another 10 s. Set the wait with
23
+ {"jade/core": {"closeTimeoutMs": ...}} in $JADE_HOME/config.json
24
+ Events (stdout), each with "session":
25
+ {"type":"text", "text"} reply text as it is written
26
+ {"type":"tool_use", "name", "input"}
27
+ {"type":"tool_error", "message"} / {"type":"denied", "reason"?}
28
+ {"type":"turn_end", "reason", "error"?, "result", "usage"} result is the turn's final reply
29
+ A request that cannot be carried out gets {"type":"error", "id"?, "session"?, "error"} instead of its reply.
30
+ When a resumed session's unfinished work fails, its turn_end says so; a failure before any turn ran is an
31
+ {"type":"error", "session", "error"} without "id" (the open was already answered with "opened").
32
+ Notices from plugins go to stderr. Exit code: 0 when stdin closes, 130 when interrupted.
33
+ Nobody can answer approval questions here, so calls that need approval are denied: in the default "ask" mode that
34
+ includes writing files. To let it change files in the working directory, put {"jade/approval": {"mode": "auto"}}
35
+ in $JADE_HOME/config.json.`;
36
+
37
+ /** --serve 的 ui@1(导出给测试) */
38
+ export const ui: UI = {
39
+ interactive: false,
40
+ notify(message, level = "info") {
41
+ process.stderr.write(`${level === "info" ? "" : `[${level}] `}${stripVTControlCharacters(String(message))}\n`);
42
+ },
43
+ select: async () => undefined,
44
+ input: async () => undefined,
45
+ };
46
+
47
+ type Request = { type?: unknown; id?: unknown; session?: unknown; text?: unknown; resume?: unknown };
48
+
49
+ const emit = (event: Record<string, unknown>): void => {
50
+ process.stdout.write(`${JSON.stringify(event)}\n`);
51
+ };
52
+
53
+ const frontend: Frontend = {
54
+ async run({ argv, sessions }) {
55
+ if (argv.includes("-h") || argv.includes("--help")) {
56
+ process.stdout.write(`${USAGE}\n`);
57
+ return 0;
58
+ }
59
+ const extra = argv.filter((a) => a !== "--serve");
60
+ if (extra.length > 0) {
61
+ process.stderr.write(`unknown argument ${extra[0]}\n\n${USAGE}\n`);
62
+ return 2;
63
+ }
64
+ const start = sessions.start?.bind(sessions);
65
+ if (!start) {
66
+ process.stderr.write("jade: this jade cannot run several sessions at once\n");
67
+ return 1;
68
+ }
69
+
70
+ const open = new Map<string, StartedSession>();
71
+ /** 每个会话结束了几轮、最近一轮怎么结束的:send 的回复据此判断这一轮跑没跑 */
72
+ const ended = new Map<string, { count: number; reason: string; error?: string }>();
73
+ /** 还没处理完的请求:stdin 关了以后等它们 */
74
+ const pending = new Set<Promise<void>>();
75
+ const track = (p: Promise<void>) => {
76
+ pending.add(p);
77
+ void p.finally(() => pending.delete(p));
78
+ };
79
+
80
+ const attach = (s: StartedSession) => {
81
+ const session = s.id;
82
+ let result = "";
83
+ let used: Required<Usage> = { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 };
84
+ /** 这次模型调用推送过文字增量;没推送的(不流式的服务),回复到了再一次写出 */
85
+ let streamed = false;
86
+ s.subscribe((n: RuntimeNotice) => {
87
+ if (n.type === "delta" && n.delta.kind === "text") {
88
+ streamed = true;
89
+ emit({ type: "text", session, text: n.delta.text });
90
+ }
91
+ if (n.type !== "event") return;
92
+ const e = n.event as LogEvent;
93
+ if (e.type === "model.responded") {
94
+ const { content, usage } = e.data as { content: Block[]; usage?: Usage };
95
+ const text = content.flatMap((b) => (b.kind === "text" ? [b.text] : [])).join("\n");
96
+ if (text) result = text;
97
+ for (const k of Object.keys(used) as (keyof Usage)[]) used[k] += usage?.[k] ?? 0;
98
+ if (!streamed && text) emit({ type: "text", session, text });
99
+ streamed = false;
100
+ for (const b of content) if (b.kind === "tool_use") emit({ type: "tool_use", session, name: b.name, input: b.input });
101
+ }
102
+ if (e.type === "tool.decided") {
103
+ const d = e.data as { decision: string; reason?: string };
104
+ if (d.decision === "deny") emit({ type: "denied", session, ...(d.reason ? { reason: stripVTControlCharacters(d.reason) } : {}) });
105
+ }
106
+ if (e.type === "tool.completed") {
107
+ const d = e.data as { isError: boolean; content: Block[] };
108
+ if (d.isError) emit({ type: "tool_error", session, message: stripVTControlCharacters(firstLine(d.content)) });
109
+ }
110
+ if (e.type === "turn.ended") {
111
+ const d = e.data as { reason: string; error?: string };
112
+ emit({ type: "turn_end", session, reason: d.reason, ...(d.error ? { error: d.error } : {}), result, usage: used });
113
+ ended.set(session, { count: (ended.get(session)?.count ?? 0) + 1, reason: d.reason, ...(d.error ? { error: d.error } : {}) });
114
+ result = "";
115
+ used = { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 };
116
+ }
117
+ });
118
+ };
119
+
120
+ const handle = async (req: Request) => {
121
+ const id = req.id !== undefined ? { id: req.id } : {};
122
+ const fail = (e: unknown, session?: string) => emit({ type: "error", ...id, ...(session ? { session } : {}), error: errorText(e) });
123
+ const target = (): StartedSession | undefined => {
124
+ const s = typeof req.session === "string" ? open.get(req.session) : undefined;
125
+ if (!s) fail(new Error(typeof req.session === "string" ? `no open session ${req.session}` : `"session" is missing`), typeof req.session === "string" ? req.session : undefined);
126
+ return s;
127
+ };
128
+ switch (req.type) {
129
+ case "open": {
130
+ if (req.resume !== undefined && typeof req.resume !== "string") return fail(new Error(`"resume" must be a session id`));
131
+ let s: StartedSession;
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
+ // 恢复的会话:先把日志里没做完的工作做完(排在之后发来的消息前面)
141
+ // 补跑的轮次出错时已经有 turn_end;open 已经回过 opened,没跑起来的错误也不再带 id
142
+ if (typeof req.resume === "string") {
143
+ const before = ended.get(s.id)?.count ?? 0;
144
+ await s.recover().catch((e) => {
145
+ if ((ended.get(s.id)?.count ?? 0) === before) emit({ type: "error", session: s.id, error: errorText(e) });
146
+ });
147
+ }
148
+ return;
149
+ }
150
+ case "send": {
151
+ if (typeof req.text !== "string" || !req.text) 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) return;
154
+ const before = ended.get(s.id)?.count ?? 0;
155
+ // 中止、模型出错的轮次 send 会 reject;跑过的轮次一律回 done,带着结束原因。没跑起来的才回 error
156
+ const done = () => {
157
+ const last = ended.get(s.id);
158
+ if (!last || last.count === before) return false;
159
+ emit({ type: "done", ...id, session: s.id, reason: last.reason, ...(last.error ? { error: last.error } : {}) });
160
+ return true;
161
+ };
162
+ try {
163
+ await s.send({ kind: "message", content: [{ kind: "text", text: req.text, origin: { by: "user" }, trust: "trusted" }] });
164
+ if (!done()) emit({ type: "done", ...id, session: s.id, reason: "end" });
165
+ } catch (e) {
166
+ if (!done()) fail(e, s.id);
167
+ }
168
+ return;
169
+ }
170
+ case "abort": {
171
+ target()?.abort(new Error("aborted by the client"));
172
+ return;
173
+ }
174
+ case "close": {
175
+ const s = target();
176
+ if (!s) return;
177
+ open.delete(s.id);
178
+ await s.close();
179
+ // 关掉的会话不再有轮次;以后 resume 回来从头计数(send 只比较前后差值)
180
+ ended.delete(s.id);
181
+ emit({ type: "closed", ...id, session: s.id });
182
+ return;
183
+ }
184
+ default:
185
+ return fail(new Error(`unknown request type ${JSON.stringify(req.type)}`));
186
+ }
187
+ };
188
+
189
+ let interrupted = false;
190
+ const rl = createInterface({ input: process.stdin, crlfDelay: Infinity });
191
+ const interrupt = () => {
192
+ interrupted = true;
193
+ for (const s of open.values()) s.abort(new Error("interrupted"));
194
+ rl.close();
195
+ };
196
+ process.once("SIGINT", interrupt);
197
+ try {
198
+ for await (const line of rl) {
199
+ if (!line.trim()) continue;
200
+ let req: Request;
201
+ try {
202
+ req = JSON.parse(line) as Request;
203
+ if (typeof req !== "object" || req === null || Array.isArray(req)) throw new Error("a request must be a JSON object");
204
+ } catch (e) {
205
+ emit({ type: "error", error: `bad request: ${errorText(e)}` });
206
+ continue;
207
+ }
208
+ track(handle(req));
209
+ }
210
+ // stdin 关了:等发出的请求做完,再让会话离开
211
+ while (pending.size > 0) await Promise.allSettled([...pending]);
212
+ for (const s of open.values()) await s.close();
213
+ } finally {
214
+ process.off("SIGINT", interrupt);
215
+ }
216
+ return interrupted ? 130 : 0;
217
+ },
218
+ };
219
+
220
+ export default definePlugin({
221
+ process(ctx) {
222
+ ctx.provide("ui@1", ui);
223
+ ctx.provide("frontend@1", frontend);
224
+ },
225
+ });
226
+
227
+ /** 经过膜的错误包成了 PluginError,带着插件名;调用方要看的是原因 */
228
+ function errorText(e: unknown): string {
229
+ const cause = e instanceof Error && e.cause instanceof Error ? e.cause : e;
230
+ return cause instanceof Error ? cause.message : String(cause);
231
+ }
232
+
233
+ function firstLine(content: Block[]): string {
234
+ const text = content.find((b) => b.kind === "text");
235
+ return text && "text" in text ? text.text.split("\n")[0]! : "(no message)";
236
+ }
@@ -0,0 +1,8 @@
1
+ {
2
+ "id": "jade/serve",
3
+ "version": "0.1.0",
4
+ "api": "^1",
5
+ "entry": "./index.ts",
6
+ "provides": ["frontend@1", "ui@1"],
7
+ "frontend": { "name": "serve", "flag": "--serve" }
8
+ }
@@ -1,7 +1,7 @@
1
1
  // jade/shell:bash 工具,以及后台命令的 bash_output、kill_shell;shell@1 给其他插件执行命令。
2
2
  // 后台命令自己结束时告诉用户,并给模型留一句说明(不用它一直轮询);/shells 给用户看和停掉后台命令。
3
3
 
4
- import { definePlugin, type Span, type UI } from "@uncarved/jade-api";
4
+ import { definePlugin, type Job, type Span, type UI } from "@uncarved/jade-api";
5
5
  import type { Commands, Prompts, Renderers, Undo } from "@uncarved/jade-api/services";
6
6
  import { shellRenderers } from "./renderers.ts";
7
7
  import { shellService } from "./service.ts";
@@ -20,6 +20,8 @@ const SH_TIMEOUT_MS = 600_000;
20
20
  const SH_LIVE_CHARS = 4000;
21
21
  /** /sh 的结果收起时那一行最多这么多个字符 */
22
22
  const SH_SUMMARY = 160;
23
+ /** 后台列表里最多留这么多个已经结束的后台命令(每个都带着输出) */
24
+ const MAX_FINISHED_JOBS = 10;
23
25
  /** 结果的一行:失败的是错误,成功的是次要的(带语义样式的文字,怎么画由前端决定) */
24
26
  const shade = (failed: boolean, text: string): Span => ({ text, style: failed ? "error" : "dim" });
25
27
 
@@ -101,6 +103,12 @@ export default definePlugin({
101
103
  async session(ctx) {
102
104
  const shell = typeof ctx.config.shell === "string" ? ctx.config.shell : undefined;
103
105
  const id = ctx.session.id;
106
+ /** 前端后台列表里的后台命令(ctrl+t):用户能看输出、停掉;会话关闭时去掉 */
107
+ const jobs = new Set<Job>();
108
+ /** 用户在后台列表里停掉的 */
109
+ const stoppedByUser = new Set<string>();
110
+ /** 已经结束、还留在列表里的,先结束的在前;多于 MAX_FINISHED_JOBS 个时去掉最早的 */
111
+ const finished: Job[] = [];
104
112
  const { tools, executable, unavailable, shutdown, list, kill } = shellTools({
105
113
  cwd: ctx.cwd,
106
114
  ...(shell ? { shell } : {}),
@@ -109,6 +117,31 @@ export default definePlugin({
109
117
  ctx.service<UI>("ui@1")?.notify(what, bg.exitCode === 0 ? "info" : "warning");
110
118
  ctx.service<Prompts>("prompts@1")?.note(id, `${what}. Read its remaining output with bash_output.`);
111
119
  },
120
+ onBackground(bg) {
121
+ const job = ctx.service<UI>("ui@1")?.job?.({
122
+ session: id,
123
+ kind: "shell",
124
+ title: `${bg.id} ${firstLine(bg.command)}`,
125
+ async stop() {
126
+ stoppedByUser.add(bg.id);
127
+ if (await kill(bg.id)) ctx.service<Prompts>("prompts@1")?.note(id, `The user stopped background shell ${bg.id} (${firstLine(bg.command)}).`);
128
+ },
129
+ });
130
+ if (!job) return undefined;
131
+ jobs.add(job);
132
+ job.status("running");
133
+ return {
134
+ output: (text) => job.append(text),
135
+ exit: (code, killed) => {
136
+ job.status(stoppedByUser.has(bg.id) ? "stopped by you" : killed ? "stopped" : `exited with code ${code}`, true);
137
+ finished.push(job);
138
+ for (const old of finished.splice(0, Math.max(0, finished.length - MAX_FINISHED_JOBS))) {
139
+ old.dispose();
140
+ jobs.delete(old);
141
+ }
142
+ },
143
+ };
144
+ },
112
145
  });
113
146
  sessions.set(id, { list, kill });
114
147
  // 子会话(子 Agent)里的 bash 只收命令和时限,不能在后台跑:子 Agent 交了报告会话就结束,后台命令随之被杀掉
@@ -135,6 +168,7 @@ export default definePlugin({
135
168
  await ctx.effect(() => () => {
136
169
  sessions.delete(id);
137
170
  shutdown();
171
+ for (const job of jobs) job.dispose();
138
172
  });
139
173
  },
140
174
  });
@@ -22,6 +22,8 @@ export interface ShellOptions {
22
22
  shell?: string;
23
23
  /** 后台命令自己结束时调用(被 kill_shell、shutdown 停掉的不算) */
24
24
  onExit?(bg: { id: string; command: string; exitCode: number | null }): void;
25
+ /** 后台命令启动时调用,返回的 output 收到它的每一段输出,exit 在它结束时调用;killed 表示是被停掉的(kill_shell、shutdown) */
26
+ onBackground?(bg: { id: string; command: string }): { output(text: string): void; exit(code: number | null, killed: boolean): void } | undefined;
25
27
  }
26
28
 
27
29
  export interface ShellTools {
@@ -79,7 +81,9 @@ export function shellTools(opts: ShellOptions): ShellTools {
79
81
  async function startBackground(command: string): Promise<string> {
80
82
  const id = `bg${nextId++}`;
81
83
  const bg: Background = { id, command, proc: await spawn(command), unread: "", dropped: 0 };
84
+ const watcher = opts.onBackground?.({ id, command });
82
85
  const append = (text: string) => {
86
+ watcher?.output(text);
83
87
  bg.unread += text;
84
88
  if (bg.unread.length > MAX_BUFFER_CHARS) {
85
89
  bg.dropped += bg.unread.length - MAX_BUFFER_CHARS;
@@ -90,6 +94,7 @@ export function shellTools(opts: ShellOptions): ShellTools {
90
94
  void Promise.all([collect(bg.proc.stdout, append, false), collect(bg.proc.stderr, append, false)]).catch(() => {});
91
95
  void bg.proc.exited.then((code) => {
92
96
  bg.exitCode = code;
97
+ watcher?.exit(code, bg.killed === true);
93
98
  if (!bg.killed) opts.onExit?.({ id, command, exitCode: code });
94
99
  });
95
100
  background.set(id, bg);
@@ -4,7 +4,7 @@
4
4
  // 配置 write 为 true 时全部保留,写操作和主会话一样经过审批。子会话的日志存盘,父会话的工具结果带着它的引用。
5
5
 
6
6
  import type { Usage } from "uncarved";
7
- import { definePlugin, type SessionContext } from "@uncarved/jade-api";
7
+ import { definePlugin, type SessionContext, type UI } from "@uncarved/jade-api";
8
8
  import type { Approval, Models, Renderers } from "@uncarved/jade-api/services";
9
9
  import { CHARS_PER_TOKEN, FALLBACK_WINDOW, fitToolResults, READ_ONLY_REASON, REPORT_TOOL_SHARE, stepsThisTurn, subagentPrompt, taskTool, WRAP_UP_AT, type Control, type TaskProgress } from "./subagent.ts";
10
10
  import { clip, dim, error, lines as joinLines } from "./style.ts";
@@ -99,6 +99,8 @@ export default definePlugin({
99
99
  return () => void controls.delete(child);
100
100
  },
101
101
  usage: (toolUseId, u) => void usage.set(toolUseId, u),
102
+ job: (description, stop) => ctx.service<UI>("ui@1")?.job?.({ session: ctx.session.id, kind: "agent", title: description, stop }),
103
+ describe: (name, input) => ctx.service<Renderers>("renderers@1")?.forTool(name)?.renderer.summary?.(input) ?? clip(JSON.stringify(input) ?? "", 120),
102
104
  }),
103
105
  );
104
106
  // 子 Agent 的用量记成本插件的事件(和压缩、审查的用量一样),界面据此计入会话用量;只能在 hook 里记
@@ -6,7 +6,7 @@
6
6
 
7
7
  import type { Block, ChildRef, EventDataMap, Message, SessionRef, Tool, ToolResult, Usage } from "uncarved";
8
8
  import { ProviderError } from "uncarved";
9
- import type { ChildSession } from "@uncarved/jade-api";
9
+ import type { ChildSession, Job, Text } from "@uncarved/jade-api";
10
10
 
11
11
  /** ctx.progress 推送的内容 */
12
12
  export type TaskProgress =
@@ -38,6 +38,12 @@ export interface TaskOptions {
38
38
  register(child: string, control: Control): () => void;
39
39
  /** 子 Agent 跑完时(成功、失败、中止都算)调用,给出它这次调用模型的用量合计 */
40
40
  usage?(toolUseId: string, usage: Usage): void;
41
+ /**
42
+ * 把子 Agent 登记到前端的后台列表里(UI.job),用户能看它在做什么、单独停掉它;前端不支持时返回 undefined。
43
+ * describe 给出工具调用括号里的一行摘要
44
+ */
45
+ job?(description: string, stop: () => void): Job | undefined;
46
+ describe?(name: string, input: unknown): Text;
41
47
  }
42
48
 
43
49
  /** 历史到了上下文窗口的这个比例就停下来写报告:子 Agent 没有压缩,再读几个大文件就会超出窗口 */
@@ -60,6 +66,12 @@ export const WRAP_UP =
60
66
  export const READ_ONLY_REASON = (name: string) =>
61
67
  `${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.`;
62
68
 
69
+ /** 用户在后台列表里停掉子 Agent 时,task 的结果 */
70
+ export const STOPPED = "The user stopped this sub-agent before it finished. Do not start it again unless the user asks.";
71
+
72
+ /** 后台列表里工具结果只显示第一行,最多这么多个字符 */
73
+ const JOB_RESULT_CHARS = 160;
74
+
63
75
  /** 返回给主会话的报告上限,免得一个子 Agent 撑满主会话的上下文 */
64
76
  const MAX_REPORT_CHARS = 20_000;
65
77
 
@@ -145,20 +157,42 @@ export function taskTool(opts: TaskOptions): Tool {
145
157
  const unregister = opts.register(child.id, control);
146
158
  const progress = (p: TaskProgress) => ctx.progress(p);
147
159
  progress({ kind: "task-start", sessionId: child.id, description });
160
+ // 用户在后台列表里停掉它:只停这个子 Agent,主会话这一轮照常进行
161
+ let stopped = false;
162
+ const job = opts.job?.(description, () => {
163
+ stopped = true;
164
+ child.abort("stopped by the user");
165
+ });
166
+ job?.status("starting");
167
+ const describe = (name: string, input: unknown): Text => opts.describe?.(name, input) ?? clipText(JSON.stringify(input) ?? "", JOB_RESULT_CHARS);
148
168
  const names = new Map<string, string>();
149
169
  const unsubscribe = child.subscribe((n) => {
150
170
  if (n.type !== "event") return;
151
171
  if (n.event.type === "model.requested") {
152
172
  progress({ kind: "task-model" });
173
+ job?.status("thinking");
153
174
  } else if (n.event.type === "model.responded") {
154
175
  const data = n.event.data as EventDataMap["model.responded"];
155
176
  for (const b of data.content) if (b.kind === "tool_use") names.set(b.id, b.name);
177
+ const said = data.content.flatMap((b) => (b.kind === "text" && b.text.trim() ? [b.text.trim()] : [])).join("\n");
178
+ if (said) job?.append(`${said}\n\n`);
156
179
  for (const k of Object.keys(used) as (keyof Usage)[]) used[k] += data.usage?.[k] ?? 0;
157
180
  // 输入 token 已含缓存部分(各 provider 的 Usage 约定);这次的输出也会进下一次请求
158
181
  if (data.usage) control.lastTokens = (data.usage.inputTokens ?? 0) + (data.usage.outputTokens ?? 0);
159
182
  } else if (n.event.type === "tool.decided") {
160
183
  const d = n.event.data as EventDataMap["tool.decided"];
161
- progress({ kind: "task-tool", name: names.get(d.toolUseId) ?? "?", input: d.input, decision: d.decision });
184
+ const name = names.get(d.toolUseId) ?? "?";
185
+ progress({ kind: "task-tool", name, input: d.input, decision: d.decision });
186
+ if (job) {
187
+ const call: Text = [`● ${name}(`, describe(name, d.input), ")"];
188
+ job.status(`${name}(${plain(describe(name, d.input))})`);
189
+ job.append(d.decision === "deny" ? [call, { text: ` ✗ denied${d.reason ? `: ${d.reason}` : ""}`, style: "error" }, "\n"] : [call, "\n"]);
190
+ }
191
+ } else if (n.event.type === "tool.completed" && job) {
192
+ const d = n.event.data as EventDataMap["tool.completed"];
193
+ const out = d.content.flatMap((b) => (b.kind === "text" ? [b.text] : [])).join("\n").trim().split("\n");
194
+ const more = out.length > 1 ? ` (+${out.length - 1} lines)` : "";
195
+ job.append([{ text: ` ⎿ ${clipText(out[0] ?? "", JOB_RESULT_CHARS)}${more}`, style: d.isError ? "error" : "dim" }, "\n"]);
162
196
  }
163
197
  });
164
198
  const forward = () => child.abort(String(ctx.signal.reason ?? "aborted"));
@@ -179,7 +213,7 @@ export function taskTool(opts: TaskOptions): Tool {
179
213
  // 再要一次报告,否则前面的调研全白做了。重试已经用完的错误(限流、服务不可用)不再要:再试一次也一样,还要再等很久
180
214
  const cause = unwrap(failure);
181
215
  const exhausted = cause instanceof ProviderError && cause.retryable;
182
- if (!ctx.signal.aborted && !exhausted && !lastText(child.state.messages)) {
216
+ if (!ctx.signal.aborted && !stopped && !exhausted && !lastText(child.state.messages)) {
183
217
  control.wrapUp = true;
184
218
  try {
185
219
  await turn(WRAP_UP);
@@ -195,6 +229,7 @@ export function taskTool(opts: TaskOptions): Tool {
195
229
  messages = child.state.messages;
196
230
  ref = await child.close().catch(() => undefined);
197
231
  unregister();
232
+ job?.dispose();
198
233
  opts.usage?.(ctx.toolUseId, used);
199
234
  }
200
235
  if (ctx.signal.aborted) throw failure ?? ctx.signal.reason;
@@ -202,6 +237,8 @@ export function taskTool(opts: TaskOptions): Tool {
202
237
  const linked = ref ? { child: ref } : {};
203
238
  // 还是没有报告时,把它一路上说过的话都带回去
204
239
  const text = clip(lastText(messages) || allText(messages));
240
+ // 跑完以后才按的停(在关子会话时)不算:报告已经有了
241
+ if (stopped && failure) return { content: `${STOPPED}${text ? `\nWhat it had written so far:\n${text}` : ""}`, isError: true, ...linked };
205
242
  if (failure) {
206
243
  const msg = failure instanceof Error ? failure.message : String(failure);
207
244
  return { content: `Sub-agent failed: ${msg}${text ? `\nLast output:\n${text}` : ""}`, isError: true, ...linked };
@@ -239,6 +276,15 @@ function allText(messages: Message[]): string {
239
276
  .join("\n\n");
240
277
  }
241
278
 
279
+ const clipText = (s: string, n: number) => (s.length > n ? `${s.slice(0, n)}…` : s);
280
+
281
+ /** 带样式的文字只取字 */
282
+ function plain(t: Text): string {
283
+ if (typeof t === "string") return t;
284
+ if (Array.isArray(t)) return (t as readonly Text[]).map(plain).join("");
285
+ return String((t as { text?: unknown }).text ?? "");
286
+ }
287
+
242
288
  function clip(s: string): string {
243
289
  return s.length > MAX_REPORT_CHARS ? `${s.slice(0, MAX_REPORT_CHARS)}\n… (report truncated: ${s.length - MAX_REPORT_CHARS} more characters)` : s;
244
290
  }