@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.
- package/README.md +317 -279
- 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 +3 -3
- 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/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 +176 -11
- 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/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 +132 -9
- package/plugins-dist/tui/vendor.js +1388 -1088
- package/sdk/python/__pycache__/jade_plugin.cpython-312.pyc +0 -0
- package/src/api.ts +1 -1
- package/src/session.ts +57 -5
package/plugins/models/index.ts
CHANGED
|
@@ -6,12 +6,12 @@
|
|
|
6
6
|
|
|
7
7
|
import path from "node:path";
|
|
8
8
|
import type { ModelRequest, ModelResponse, Provider } from "uncarved";
|
|
9
|
-
import { definePlugin, type UI, type Updater } from "@uncarved/jade-api";
|
|
9
|
+
import { definePlugin, type Notice, type UI, type Updater } from "@uncarved/jade-api";
|
|
10
10
|
import type { Commands, Models } from "@uncarved/jade-api/services";
|
|
11
11
|
import { contextWindow } from "./context.ts";
|
|
12
12
|
import { envWithFile, hasProvider, parseTokens } from "./config.ts";
|
|
13
13
|
import { configurator } from "./configure.ts";
|
|
14
|
-
import { isBuiltinKind, listModels, MODEL_KEY, providerFromEnv, providerInfo, providerKind, RateGate, rpmFromEnv, visionFromEnv, withRetry, type RetriedResponse } from "./provider.ts";
|
|
14
|
+
import { isBuiltinKind, listModels, MODEL_KEY, providerFromEnv, providerInfo, providerKind, RateGate, rpmFromEnv, visionFromEnv, withRetry, type RetriedResponse, type RetryOptions } from "./provider.ts";
|
|
15
15
|
import { MODEL_SETTINGS, readSavedServices, type Env } from "./saved.ts";
|
|
16
16
|
|
|
17
17
|
/** 进程级的配置交给会话里的提示用:有没有配好模型、有没有 /model、.env 在哪 */
|
|
@@ -22,6 +22,11 @@ let hinted = false;
|
|
|
22
22
|
const countdowns = new Map<string, (ms: number, label: string) => void>();
|
|
23
23
|
/** 请求上记的会话 id(见 session() 里的 model.before) */
|
|
24
24
|
const sessionOf = (request: ModelRequest) => (request.ext?.["jade/models"] as { session?: string } | undefined)?.session;
|
|
25
|
+
type RetryInfo = Parameters<NonNullable<RetryOptions["onRetry"]>>[0];
|
|
26
|
+
/** 重试前在会话里怎么显示:会话 id → 显示这一次重试。找不到会话的(子会话、-p)直接 notify */
|
|
27
|
+
const retryShows = new Map<string, (info: RetryInfo) => void>();
|
|
28
|
+
/** 重试的提示;next 是接下来做什么("retrying in 5s") */
|
|
29
|
+
const retryText = ({ attempt, retries, error }: RetryInfo, next: string) => `model request failed (${error.message}); ${next} (retry ${attempt}, at most ${retries})`;
|
|
25
30
|
|
|
26
31
|
export default definePlugin({
|
|
27
32
|
async process(ctx) {
|
|
@@ -65,9 +70,10 @@ export default definePlugin({
|
|
|
65
70
|
return withRetry(await providerFromEnv(snapshot, { "user-agent": userAgent() }), {
|
|
66
71
|
gate,
|
|
67
72
|
onWait: ({ delayMs, request }) => countdowns.get(sessionOf(request) ?? "")?.(delayMs, "rate limited, sending in"),
|
|
68
|
-
onRetry: (
|
|
69
|
-
|
|
70
|
-
|
|
73
|
+
onRetry: (info) => {
|
|
74
|
+
const show = retryShows.get(sessionOf(info.request) ?? "");
|
|
75
|
+
if (show) show(info);
|
|
76
|
+
else ui()?.notify(retryText(info, `retrying in ${Math.round(info.delayMs / 1000)}s`), "warning");
|
|
71
77
|
},
|
|
72
78
|
});
|
|
73
79
|
})();
|
|
@@ -217,7 +223,7 @@ export default definePlugin({
|
|
|
217
223
|
}
|
|
218
224
|
},
|
|
219
225
|
});
|
|
220
|
-
//
|
|
226
|
+
// 限速排队时(还有前端不能改写提示时的重试前)状态栏倒计时,不然几十秒里只看到"在请求",像卡住了。子会话没有状态栏,不用做
|
|
221
227
|
let timer: ReturnType<typeof setInterval> | undefined;
|
|
222
228
|
const stopCountdown = () => {
|
|
223
229
|
if (timer === undefined) return;
|
|
@@ -225,9 +231,26 @@ export default definePlugin({
|
|
|
225
231
|
timer = undefined;
|
|
226
232
|
ctx.status?.(undefined);
|
|
227
233
|
};
|
|
234
|
+
const safe = (fn: () => void) => {
|
|
235
|
+
try {
|
|
236
|
+
fn();
|
|
237
|
+
} catch {
|
|
238
|
+
// 前端不在了
|
|
239
|
+
}
|
|
240
|
+
};
|
|
241
|
+
// 一个请求接连重试时只用一条提示(前端能原地改写时):倒计时、第几次重试都改在这一条上,
|
|
242
|
+
// 请求有了结果就停在结果上。之后的请求再重试是新的一条
|
|
243
|
+
let retry: { notice: Notice; info: RetryInfo; timer?: ReturnType<typeof setInterval> } | undefined;
|
|
244
|
+
const endRetry = (outcome: string, level: "info" | "warning") => {
|
|
245
|
+
const r = retry;
|
|
246
|
+
if (!r) return;
|
|
247
|
+
retry = undefined;
|
|
248
|
+
clearInterval(r.timer);
|
|
249
|
+
safe(() => r.notice.update(`model request failed (${r.info.error.message}); ${outcome}`, level));
|
|
250
|
+
};
|
|
228
251
|
if (ctx.status) {
|
|
229
252
|
const id = ctx.session.id;
|
|
230
|
-
|
|
253
|
+
const countdown = (ms: number, label: string) => {
|
|
231
254
|
stopCountdown();
|
|
232
255
|
const until = Date.now() + ms;
|
|
233
256
|
const tick = () => {
|
|
@@ -237,10 +260,40 @@ export default definePlugin({
|
|
|
237
260
|
};
|
|
238
261
|
timer = setInterval(tick, 1000);
|
|
239
262
|
tick();
|
|
263
|
+
};
|
|
264
|
+
countdowns.set(id, countdown);
|
|
265
|
+
retryShows.set(id, (info) => {
|
|
266
|
+
const until = Date.now() + info.delayMs;
|
|
267
|
+
const text = () => {
|
|
268
|
+
const left = Math.ceil((until - Date.now()) / 1000);
|
|
269
|
+
return retryText(info, left > 0 ? `retrying in ${left}s` : "retrying now");
|
|
270
|
+
};
|
|
271
|
+
let r = retry;
|
|
272
|
+
if (r) {
|
|
273
|
+
clearInterval(r.timer);
|
|
274
|
+
r.info = info;
|
|
275
|
+
const shown = r;
|
|
276
|
+
safe(() => shown.notice.update(text(), "warning"));
|
|
277
|
+
} else {
|
|
278
|
+
const notice = ui?.notice?.(text(), "warning");
|
|
279
|
+
// 前端不能改写:每次重试一条提示,倒计时放在状态栏上
|
|
280
|
+
if (!notice) {
|
|
281
|
+
ui?.notify(text(), "warning");
|
|
282
|
+
return countdown(info.delayMs, "retrying in");
|
|
283
|
+
}
|
|
284
|
+
r = retry = { notice, info };
|
|
285
|
+
}
|
|
286
|
+
const shown = r;
|
|
287
|
+
shown.timer = setInterval(() => {
|
|
288
|
+
if (Date.now() >= until) clearInterval(shown.timer);
|
|
289
|
+
safe(() => shown.notice.update(text(), "warning"));
|
|
290
|
+
}, 1000);
|
|
240
291
|
});
|
|
241
292
|
ctx.signal.addEventListener("abort", () => {
|
|
242
293
|
stopCountdown();
|
|
294
|
+
clearInterval(retry?.timer);
|
|
243
295
|
countdowns.delete(id);
|
|
296
|
+
retryShows.delete(id);
|
|
244
297
|
});
|
|
245
298
|
// ext[provider id] 由那个 provider 解释(4.7),这里的 provider 就是 jade/models,别的 provider 不看
|
|
246
299
|
ctx.kernel.hook({
|
|
@@ -253,7 +306,10 @@ export default definePlugin({
|
|
|
253
306
|
kind: "observe",
|
|
254
307
|
point: "event",
|
|
255
308
|
fn: (e) => {
|
|
256
|
-
if (e.type
|
|
309
|
+
if (e.type !== "turn.ended") return;
|
|
310
|
+
stopCountdown();
|
|
311
|
+
// 没等到成功这一轮就结束了(中断、重试次数用完):倒计时不再算数
|
|
312
|
+
endRetry("stopped retrying", "warning");
|
|
257
313
|
},
|
|
258
314
|
});
|
|
259
315
|
}
|
|
@@ -267,7 +323,9 @@ export default definePlugin({
|
|
|
267
323
|
if (!retries?.length) return;
|
|
268
324
|
// 重试中的提示只说了"在重试",成功了也要说一声,不然看起来像重试到一半没了
|
|
269
325
|
const waited = Math.round(retries.reduce((ms, r) => ms + r.delayMs, 0) / 1000);
|
|
270
|
-
|
|
326
|
+
const after = `${retries.length} ${retries.length === 1 ? "retry" : "retries"} (${waited}s of waiting)`;
|
|
327
|
+
if (retry) endRetry(`succeeded after ${after}`, "info");
|
|
328
|
+
else ui?.notify(`model request succeeded after ${after}`, "info");
|
|
271
329
|
await hook.emit("retried", { retries });
|
|
272
330
|
},
|
|
273
331
|
});
|
|
@@ -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
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
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
|
|
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:
|
|
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
|
-
/**
|
|
145
|
-
|
|
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
|
|
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
|
-
|
|
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.
|
|
187
|
+
this.#queue = turn.then(
|
|
188
|
+
() => {},
|
|
189
|
+
() => {},
|
|
190
|
+
);
|
|
156
191
|
// 排队时被取消的也要立即返回(I-9);轮到它时看到已取消,不会记成发出了请求
|
|
157
192
|
return new Promise((resolve, reject) => {
|
|
158
|
-
|
|
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
|
-
|
|
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((
|
|
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
|
-
|
|
228
|
+
/** 还要等多少毫秒;要等一个还没结束的请求时返回它结束的 Promise */
|
|
229
|
+
#delay(): number | Promise<void> {
|
|
188
230
|
const now = this.#now();
|
|
189
|
-
this.#
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
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,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 里记
|