@uncarved/jade 0.4.2 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +39 -1
- package/dist/api.d.ts +1 -1
- package/dist/api.js +1 -1
- package/dist/session.d.ts +4 -2
- package/dist/session.js +54 -6
- package/dist/session.js.map +1 -1
- package/package.json +4 -4
- package/plugins/budget/index.ts +54 -4
- package/plugins/budget/plugin.json +1 -1
- package/plugins/keys/index.ts +2 -2
- package/plugins/memory/index.ts +6 -4
- package/plugins/memory/memory.ts +101 -31
- package/plugins/models/index.ts +67 -9
- package/plugins/models/provider.ts +81 -24
- package/plugins/prompts/prompts.ts +1 -0
- package/plugins/screenshot/index.ts +2 -1
- package/plugins/screenshot/tool.ts +1 -1
- package/plugins/serve/index.ts +229 -0
- package/plugins/serve/plugin.json +8 -0
- package/plugins/shell/index.ts +35 -1
- package/plugins/shell/shell.ts +5 -0
- package/plugins/task/index.ts +3 -1
- package/plugins/task/subagent.ts +49 -3
- package/plugins/tui/frontend.ts +73 -4
- package/plugins/tui/screen.ts +23 -0
- package/plugins/tui/tui.ts +199 -17
- package/plugins-dist/budget/index.js +43 -2
- package/plugins-dist/budget/plugin.json +1 -1
- package/plugins-dist/keys/index.js +1 -1
- package/plugins-dist/memory/index.js +7 -3
- package/plugins-dist/memory/memory.js +81 -34
- package/plugins-dist/models/index.js +62 -7
- package/plugins-dist/models/provider.js +47 -14
- package/plugins-dist/prompts/prompts.js +1 -0
- package/plugins-dist/screenshot/index.js +1 -1
- package/plugins-dist/screenshot/tool.js +1 -1
- package/plugins-dist/serve/index.js +238 -0
- package/plugins-dist/serve/plugin.json +14 -0
- package/plugins-dist/shell/index.js +33 -0
- package/plugins-dist/shell/shell.js +3 -0
- package/plugins-dist/task/index.js +3 -1
- package/plugins-dist/task/subagent.js +47 -2
- package/plugins-dist/tui/frontend.js +67 -3
- package/plugins-dist/tui/screen.js +3 -0
- package/plugins-dist/tui/tui.js +145 -13
- package/src/api.ts +1 -1
- package/src/session.ts +57 -5
|
@@ -0,0 +1,229 @@
|
|
|
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
|
+
Events (stdout), each with "session":
|
|
20
|
+
{"type":"text", "text"} reply text as it is written
|
|
21
|
+
{"type":"tool_use", "name", "input"}
|
|
22
|
+
{"type":"tool_error", "message"} / {"type":"denied", "reason"?}
|
|
23
|
+
{"type":"turn_end", "reason", "error"?, "result", "usage"} result is the turn's final reply
|
|
24
|
+
A request that cannot be carried out gets {"type":"error", "id"?, "session"?, "error"} instead of its reply.
|
|
25
|
+
When a resumed session's unfinished work fails, its turn_end says so; a failure before any turn ran is an
|
|
26
|
+
{"type":"error", "session", "error"} without "id" (the open was already answered with "opened").
|
|
27
|
+
Notices from plugins go to stderr. Exit code: 0 when stdin closes, 130 when interrupted.
|
|
28
|
+
Nobody can answer approval questions here, so calls that need approval are denied: in the default "ask" mode that
|
|
29
|
+
includes writing files. To let it change files in the working directory, put {"jade/approval": {"mode": "auto"}}
|
|
30
|
+
in $JADE_HOME/config.json.`;
|
|
31
|
+
|
|
32
|
+
/** --serve 的 ui@1(导出给测试) */
|
|
33
|
+
export const ui: UI = {
|
|
34
|
+
interactive: false,
|
|
35
|
+
notify(message, level = "info") {
|
|
36
|
+
process.stderr.write(`${level === "info" ? "" : `[${level}] `}${stripVTControlCharacters(String(message))}\n`);
|
|
37
|
+
},
|
|
38
|
+
select: async () => undefined,
|
|
39
|
+
input: async () => undefined,
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
type Request = { type?: unknown; id?: unknown; session?: unknown; text?: unknown; resume?: unknown };
|
|
43
|
+
|
|
44
|
+
const emit = (event: Record<string, unknown>): void => {
|
|
45
|
+
process.stdout.write(`${JSON.stringify(event)}\n`);
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
const frontend: Frontend = {
|
|
49
|
+
async run({ argv, sessions }) {
|
|
50
|
+
if (argv.includes("-h") || argv.includes("--help")) {
|
|
51
|
+
process.stdout.write(`${USAGE}\n`);
|
|
52
|
+
return 0;
|
|
53
|
+
}
|
|
54
|
+
const extra = argv.filter((a) => a !== "--serve");
|
|
55
|
+
if (extra.length > 0) {
|
|
56
|
+
process.stderr.write(`unknown argument ${extra[0]}\n\n${USAGE}\n`);
|
|
57
|
+
return 2;
|
|
58
|
+
}
|
|
59
|
+
const start = sessions.start?.bind(sessions);
|
|
60
|
+
if (!start) {
|
|
61
|
+
process.stderr.write("jade: this jade cannot run several sessions at once\n");
|
|
62
|
+
return 1;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const open = new Map<string, StartedSession>();
|
|
66
|
+
/** 每个会话结束了几轮、最近一轮怎么结束的:send 的回复据此判断这一轮跑没跑 */
|
|
67
|
+
const ended = new Map<string, { count: number; reason: string; error?: string }>();
|
|
68
|
+
/** 还没处理完的请求:stdin 关了以后等它们 */
|
|
69
|
+
const pending = new Set<Promise<void>>();
|
|
70
|
+
const track = (p: Promise<void>) => {
|
|
71
|
+
pending.add(p);
|
|
72
|
+
void p.finally(() => pending.delete(p));
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
const attach = (s: StartedSession) => {
|
|
76
|
+
const session = s.id;
|
|
77
|
+
let result = "";
|
|
78
|
+
let used: Required<Usage> = { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 };
|
|
79
|
+
/** 这次模型调用推送过文字增量;没推送的(不流式的服务),回复到了再一次写出 */
|
|
80
|
+
let streamed = false;
|
|
81
|
+
s.subscribe((n: RuntimeNotice) => {
|
|
82
|
+
if (n.type === "delta" && n.delta.kind === "text") {
|
|
83
|
+
streamed = true;
|
|
84
|
+
emit({ type: "text", session, text: n.delta.text });
|
|
85
|
+
}
|
|
86
|
+
if (n.type !== "event") return;
|
|
87
|
+
const e = n.event as LogEvent;
|
|
88
|
+
if (e.type === "model.responded") {
|
|
89
|
+
const { content, usage } = e.data as { content: Block[]; usage?: Usage };
|
|
90
|
+
const text = content.flatMap((b) => (b.kind === "text" ? [b.text] : [])).join("\n");
|
|
91
|
+
if (text) result = text;
|
|
92
|
+
for (const k of Object.keys(used) as (keyof Usage)[]) used[k] += usage?.[k] ?? 0;
|
|
93
|
+
if (!streamed && text) emit({ type: "text", session, text });
|
|
94
|
+
streamed = false;
|
|
95
|
+
for (const b of content) if (b.kind === "tool_use") emit({ type: "tool_use", session, name: b.name, input: b.input });
|
|
96
|
+
}
|
|
97
|
+
if (e.type === "tool.decided") {
|
|
98
|
+
const d = e.data as { decision: string; reason?: string };
|
|
99
|
+
if (d.decision === "deny") emit({ type: "denied", session, ...(d.reason ? { reason: stripVTControlCharacters(d.reason) } : {}) });
|
|
100
|
+
}
|
|
101
|
+
if (e.type === "tool.completed") {
|
|
102
|
+
const d = e.data as { isError: boolean; content: Block[] };
|
|
103
|
+
if (d.isError) emit({ type: "tool_error", session, message: stripVTControlCharacters(firstLine(d.content)) });
|
|
104
|
+
}
|
|
105
|
+
if (e.type === "turn.ended") {
|
|
106
|
+
const d = e.data as { reason: string; error?: string };
|
|
107
|
+
emit({ type: "turn_end", session, reason: d.reason, ...(d.error ? { error: d.error } : {}), result, usage: used });
|
|
108
|
+
ended.set(session, { count: (ended.get(session)?.count ?? 0) + 1, reason: d.reason, ...(d.error ? { error: d.error } : {}) });
|
|
109
|
+
result = "";
|
|
110
|
+
used = { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 };
|
|
111
|
+
}
|
|
112
|
+
});
|
|
113
|
+
};
|
|
114
|
+
|
|
115
|
+
const handle = async (req: Request) => {
|
|
116
|
+
const id = req.id !== undefined ? { id: req.id } : {};
|
|
117
|
+
const fail = (e: unknown, session?: string) => emit({ type: "error", ...id, ...(session ? { session } : {}), error: errorText(e) });
|
|
118
|
+
const target = (): StartedSession | undefined => {
|
|
119
|
+
const s = typeof req.session === "string" ? open.get(req.session) : undefined;
|
|
120
|
+
if (!s) fail(new Error(typeof req.session === "string" ? `no open session ${req.session}` : `"session" is missing`), typeof req.session === "string" ? req.session : undefined);
|
|
121
|
+
return s;
|
|
122
|
+
};
|
|
123
|
+
switch (req.type) {
|
|
124
|
+
case "open": {
|
|
125
|
+
if (req.resume !== undefined && typeof req.resume !== "string") return fail(new Error(`"resume" must be a session id`));
|
|
126
|
+
let s: StartedSession;
|
|
127
|
+
try {
|
|
128
|
+
s = await start(typeof req.resume === "string" ? { resume: req.resume } : {});
|
|
129
|
+
} catch (e) {
|
|
130
|
+
return fail(e);
|
|
131
|
+
}
|
|
132
|
+
open.set(s.id, s);
|
|
133
|
+
attach(s);
|
|
134
|
+
emit({ type: "opened", ...id, session: s.id });
|
|
135
|
+
// 恢复的会话:先把日志里没做完的工作做完(排在之后发来的消息前面)
|
|
136
|
+
// 补跑的轮次出错时已经有 turn_end;open 已经回过 opened,没跑起来的错误也不再带 id
|
|
137
|
+
if (typeof req.resume === "string") {
|
|
138
|
+
const before = ended.get(s.id)?.count ?? 0;
|
|
139
|
+
await s.recover().catch((e) => {
|
|
140
|
+
if ((ended.get(s.id)?.count ?? 0) === before) emit({ type: "error", session: s.id, error: errorText(e) });
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
case "send": {
|
|
146
|
+
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);
|
|
147
|
+
const s = target();
|
|
148
|
+
if (!s) return;
|
|
149
|
+
const before = ended.get(s.id)?.count ?? 0;
|
|
150
|
+
// 中止、模型出错的轮次 send 会 reject;跑过的轮次一律回 done,带着结束原因。没跑起来的才回 error
|
|
151
|
+
const done = () => {
|
|
152
|
+
const last = ended.get(s.id);
|
|
153
|
+
if (!last || last.count === before) return false;
|
|
154
|
+
emit({ type: "done", ...id, session: s.id, reason: last.reason, ...(last.error ? { error: last.error } : {}) });
|
|
155
|
+
return true;
|
|
156
|
+
};
|
|
157
|
+
try {
|
|
158
|
+
await s.send({ kind: "message", content: [{ kind: "text", text: req.text, origin: { by: "user" }, trust: "trusted" }] });
|
|
159
|
+
if (!done()) emit({ type: "done", ...id, session: s.id, reason: "end" });
|
|
160
|
+
} catch (e) {
|
|
161
|
+
if (!done()) fail(e, s.id);
|
|
162
|
+
}
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
case "abort": {
|
|
166
|
+
target()?.abort(new Error("aborted by the client"));
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
case "close": {
|
|
170
|
+
const s = target();
|
|
171
|
+
if (!s) return;
|
|
172
|
+
open.delete(s.id);
|
|
173
|
+
await s.close();
|
|
174
|
+
emit({ type: "closed", ...id, session: s.id });
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
default:
|
|
178
|
+
return fail(new Error(`unknown request type ${JSON.stringify(req.type)}`));
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
let interrupted = false;
|
|
183
|
+
const rl = createInterface({ input: process.stdin, crlfDelay: Infinity });
|
|
184
|
+
const interrupt = () => {
|
|
185
|
+
interrupted = true;
|
|
186
|
+
for (const s of open.values()) s.abort(new Error("interrupted"));
|
|
187
|
+
rl.close();
|
|
188
|
+
};
|
|
189
|
+
process.once("SIGINT", interrupt);
|
|
190
|
+
try {
|
|
191
|
+
for await (const line of rl) {
|
|
192
|
+
if (!line.trim()) continue;
|
|
193
|
+
let req: Request;
|
|
194
|
+
try {
|
|
195
|
+
req = JSON.parse(line) as Request;
|
|
196
|
+
if (typeof req !== "object" || req === null || Array.isArray(req)) throw new Error("a request must be a JSON object");
|
|
197
|
+
} catch (e) {
|
|
198
|
+
emit({ type: "error", error: `bad request: ${errorText(e)}` });
|
|
199
|
+
continue;
|
|
200
|
+
}
|
|
201
|
+
track(handle(req));
|
|
202
|
+
}
|
|
203
|
+
// stdin 关了:等发出的请求做完,再让会话离开
|
|
204
|
+
while (pending.size > 0) await Promise.allSettled([...pending]);
|
|
205
|
+
for (const s of open.values()) await s.close();
|
|
206
|
+
} finally {
|
|
207
|
+
process.off("SIGINT", interrupt);
|
|
208
|
+
}
|
|
209
|
+
return interrupted ? 130 : 0;
|
|
210
|
+
},
|
|
211
|
+
};
|
|
212
|
+
|
|
213
|
+
export default definePlugin({
|
|
214
|
+
process(ctx) {
|
|
215
|
+
ctx.provide("ui@1", ui);
|
|
216
|
+
ctx.provide("frontend@1", frontend);
|
|
217
|
+
},
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
/** 经过膜的错误包成了 PluginError,带着插件名;调用方要看的是原因 */
|
|
221
|
+
function errorText(e: unknown): string {
|
|
222
|
+
const cause = e instanceof Error && e.cause instanceof Error ? e.cause : e;
|
|
223
|
+
return cause instanceof Error ? cause.message : String(cause);
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function firstLine(content: Block[]): string {
|
|
227
|
+
const text = content.find((b) => b.kind === "text");
|
|
228
|
+
return text && "text" in text ? text.text.split("\n")[0]! : "(no message)";
|
|
229
|
+
}
|
package/plugins/shell/index.ts
CHANGED
|
@@ -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
|
});
|
package/plugins/shell/shell.ts
CHANGED
|
@@ -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);
|
package/plugins/task/index.ts
CHANGED
|
@@ -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 里记
|
package/plugins/task/subagent.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
}
|
package/plugins/tui/frontend.ts
CHANGED
|
@@ -10,10 +10,10 @@ import { readFileSync } from "node:fs";
|
|
|
10
10
|
import os from "node:os";
|
|
11
11
|
import path from "node:path";
|
|
12
12
|
import type { Block } from "uncarved";
|
|
13
|
-
import type { Frontend, OpenOptions, Session, SessionManager, SessionUI, StatusSegment, Text, UI } from "@uncarved/jade-api";
|
|
13
|
+
import type { Frontend, Job, JobRequest, OpenOptions, Session, SessionManager, SessionUI, StatusSegment, Text, UI } from "@uncarved/jade-api";
|
|
14
14
|
import type { CommandContext, Commands, Completions, EventRenderer, Keys, Models, Renderers, SessionIndex, Steer, ToolRenderer } from "@uncarved/jade-api/services";
|
|
15
15
|
import { InputHistory } from "./history.ts";
|
|
16
|
-
import { ansi, dim, red, safeScreen, yellow, type CommandInfo, type CompletionInfo, type Screen } from "./screen.ts";
|
|
16
|
+
import { ansi, dim, red, safeScreen, yellow, type CommandInfo, type CompletionInfo, type JobInfo, type Screen } from "./screen.ts";
|
|
17
17
|
import { transcript, type Transcript } from "./transcript.ts";
|
|
18
18
|
|
|
19
19
|
/**
|
|
@@ -45,6 +45,7 @@ jade's own commands (plugins, update, --safe): jade help`;
|
|
|
45
45
|
/** 前端自己的命令:帮助和退出。其余命令都来自 commands@1 */
|
|
46
46
|
const OWN: CommandInfo[] = [
|
|
47
47
|
{ name: "help", about: "list the commands and keys" },
|
|
48
|
+
{ name: "tasks", about: "list sub-agents and background commands (same as ctrl+t)" },
|
|
48
49
|
{ name: "exit", about: "quit (the session stays resumable)" },
|
|
49
50
|
];
|
|
50
51
|
|
|
@@ -53,7 +54,7 @@ const KEYS = [
|
|
|
53
54
|
" send enter send · ctrl+j, alt+enter or \\ then enter: new line · tab completes /commands",
|
|
54
55
|
" input ↑↓ history · ctrl+r search history · ↑ on the first line edits queued messages · esc twice or ctrl+c clears the input",
|
|
55
56
|
" 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",
|
|
56
|
-
" running esc interrupt (twice to also move queued messages back to the input) · ctrl+c twice to exit",
|
|
57
|
+
" 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",
|
|
57
58
|
" 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",
|
|
58
59
|
].join("\n");
|
|
59
60
|
|
|
@@ -155,16 +156,30 @@ export class ScreenBridge {
|
|
|
155
156
|
#panels = new Map<string, Map<string, string>>();
|
|
156
157
|
/** 界面现在显示哪个会话;换会话时由前端调用 show */
|
|
157
158
|
#session: string | undefined;
|
|
159
|
+
/** UI.notice 给每条提示编号,作为它在界面里的 id */
|
|
160
|
+
#notices = 0;
|
|
161
|
+
/** UI.job 登记的事(所有会话的);界面只显示正在显示的会话的 */
|
|
162
|
+
#jobs: (JobInfo & { session: string })[] = [];
|
|
163
|
+
#nextJob = 0;
|
|
164
|
+
/** 输出攒一小段时间再交给界面,后台命令输出很快时不至于每一块都重画 */
|
|
165
|
+
#jobTimer: ReturnType<typeof setTimeout> | undefined;
|
|
158
166
|
|
|
159
167
|
readonly ui: UI = {
|
|
160
168
|
interactive: true,
|
|
161
169
|
notify: (message, level = "info") => {
|
|
162
|
-
const text =
|
|
170
|
+
const text = noticeText(message, level);
|
|
163
171
|
if (this.#held) this.#held.push(text);
|
|
164
172
|
else if (this.screen) this.screen.log(text);
|
|
165
173
|
else if (this.#closed) process.stderr.write(`jade: ${message}\n`);
|
|
166
174
|
else this.#early.push(text);
|
|
167
175
|
},
|
|
176
|
+
// 只有终端界面能原地改写;攒着提示(正在打开会话)时也不行,调用方改用 notify
|
|
177
|
+
notice: (message, level = "info") => {
|
|
178
|
+
if (this.#held || !this.screen?.note) return undefined;
|
|
179
|
+
const id = `\0notice-${++this.#notices}`;
|
|
180
|
+
this.screen.note(id, noticeText(message, level));
|
|
181
|
+
return { update: (m, l = "info") => this.screen?.note?.(id, noticeText(m, l)) };
|
|
182
|
+
},
|
|
168
183
|
select: async (req, signal) => {
|
|
169
184
|
if (!this.screen) return undefined;
|
|
170
185
|
return this.screen.select(req.title, req.options.map((o) => ({ label: o.label, value: o.value, ...(o.hint ? { hint: o.hint } : {}) })), { ...(req.detail ? { body: ansi(req.detail) } : {}), ...(signal ? { signal } : {}) });
|
|
@@ -181,6 +196,7 @@ export class ScreenBridge {
|
|
|
181
196
|
// 界面没有占着终端(不是终端界面、还没起来)时没有什么要让的,直接执行
|
|
182
197
|
suspend: async (fn) => (this.screen?.suspend ? this.screen.suspend(fn) : fn()),
|
|
183
198
|
session: ({ session, plugin }) => this.#sessionUI(session, plugin),
|
|
199
|
+
job: (req) => this.#job(req),
|
|
184
200
|
};
|
|
185
201
|
|
|
186
202
|
attach(screen: Screen): void {
|
|
@@ -204,6 +220,7 @@ export class ScreenBridge {
|
|
|
204
220
|
}
|
|
205
221
|
|
|
206
222
|
detach(): void {
|
|
223
|
+
clearTimeout(this.#jobTimer);
|
|
207
224
|
this.screen = undefined;
|
|
208
225
|
this.#closed = true;
|
|
209
226
|
}
|
|
@@ -212,6 +229,45 @@ export class ScreenBridge {
|
|
|
212
229
|
show(session: string | undefined): void {
|
|
213
230
|
this.#session = session;
|
|
214
231
|
this.#apply();
|
|
232
|
+
this.#applyJobs();
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
#job(req: JobRequest): Job {
|
|
236
|
+
const entry: JobInfo & { session: string } = {
|
|
237
|
+
id: ++this.#nextJob,
|
|
238
|
+
session: String(req.session),
|
|
239
|
+
kind: String(req.kind),
|
|
240
|
+
title: String(req.title),
|
|
241
|
+
status: "",
|
|
242
|
+
done: false,
|
|
243
|
+
output: "",
|
|
244
|
+
...(req.stop ? { stop: () => req.stop!() } : {}),
|
|
245
|
+
};
|
|
246
|
+
this.#jobs = [...this.#jobs, { ...entry }];
|
|
247
|
+
this.#applyJobs();
|
|
248
|
+
// entry 是最新的值;列表里每次换成它的一份新拷贝,界面按引用判断哪一项变了。已经去掉的不再更新
|
|
249
|
+
const update = (patch: Partial<JobInfo>, soon = false) => {
|
|
250
|
+
if (!this.#jobs.some((j) => j.id === entry.id)) return;
|
|
251
|
+
Object.assign(entry, patch);
|
|
252
|
+
this.#jobs = this.#jobs.map((j) => (j.id === entry.id ? { ...entry } : j));
|
|
253
|
+
if (soon) this.#jobTimer ??= setTimeout(() => this.#applyJobs(), JOB_REDRAW_MS);
|
|
254
|
+
else this.#applyJobs();
|
|
255
|
+
};
|
|
256
|
+
return {
|
|
257
|
+
append: (text) => update({ output: (entry.output + ansi(text)).slice(-MAX_JOB_OUTPUT) }, true),
|
|
258
|
+
status: (text, done) => update({ status: String(text), done: done === true }),
|
|
259
|
+
dispose: () => {
|
|
260
|
+
const before = this.#jobs.length;
|
|
261
|
+
this.#jobs = this.#jobs.filter((j) => j.id !== entry.id);
|
|
262
|
+
if (this.#jobs.length !== before) this.#applyJobs();
|
|
263
|
+
},
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
#applyJobs(): void {
|
|
268
|
+
clearTimeout(this.#jobTimer);
|
|
269
|
+
this.#jobTimer = undefined;
|
|
270
|
+
this.screen?.jobs?.(this.#jobs.filter((j) => j.session === this.#session));
|
|
215
271
|
}
|
|
216
272
|
|
|
217
273
|
#apply(): void {
|
|
@@ -264,6 +320,14 @@ export class ScreenBridge {
|
|
|
264
320
|
}
|
|
265
321
|
}
|
|
266
322
|
|
|
323
|
+
/** 每件后台的事最多留这么多个字符的输出 */
|
|
324
|
+
const MAX_JOB_OUTPUT = 100_000;
|
|
325
|
+
/** 后台的事的输出攒这么久交给界面一次 */
|
|
326
|
+
const JOB_REDRAW_MS = 100;
|
|
327
|
+
|
|
328
|
+
const noticeText = (message: string, level: "info" | "warning" | "error") =>
|
|
329
|
+
level === "error" ? red(`[error] ${message}`) : level === "warning" ? yellow(`[warning] ${message}`) : dim(message);
|
|
330
|
+
|
|
267
331
|
/** 输入框上方的一块最多这么多行,多出的最后一行写成还有几行;每行在界面里按宽度截断 */
|
|
268
332
|
function clipPanel(text: string): string {
|
|
269
333
|
const lines = String(text).replace(/\r\n?/g, "\n").replace(/\n+$/, "").split("\n");
|
|
@@ -630,6 +694,11 @@ async function run(services: FrontendServices, bridge: ScreenBridge, opts: Param
|
|
|
630
694
|
const name = input.slice(1).split(/\s+/)[0]!.toLowerCase();
|
|
631
695
|
const rest = input.slice(1).replace(/^\S+\s*/, "");
|
|
632
696
|
if (name === "exit" || name === "quit") return false;
|
|
697
|
+
if (name === "tasks") {
|
|
698
|
+
if (screen.showJobs) screen.showJobs();
|
|
699
|
+
else screen.log(dim("[background tasks are only listed in the terminal interface]"));
|
|
700
|
+
return true;
|
|
701
|
+
}
|
|
633
702
|
if (name === "help") {
|
|
634
703
|
// 快捷键在前、命令在后:屏幕放不下时,紧挨着输入框的命令列表还看得见
|
|
635
704
|
// 命令的简写、输入框的补全来自插件,跟着列出来
|