@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.
- package/README.md +39 -1
- package/dist/api.d.ts +1 -1
- package/dist/api.js +1 -1
- package/dist/membrane.d.ts +5 -2
- package/dist/membrane.js +8 -3
- package/dist/membrane.js.map +1 -1
- package/dist/session.d.ts +14 -3
- package/dist/session.js +164 -22
- package/dist/session.js.map +1 -1
- package/package.json +4 -4
- 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 +236 -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 +244 -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/src/api.ts +1 -1
- package/src/membrane.ts +8 -3
- package/src/session.ts +181 -25
|
@@ -11,6 +11,7 @@ const firstLine = (command) => {
|
|
|
11
11
|
const SH_TIMEOUT_MS = 600000;
|
|
12
12
|
const SH_LIVE_CHARS = 4000;
|
|
13
13
|
const SH_SUMMARY = 160;
|
|
14
|
+
const MAX_FINISHED_JOBS = 10;
|
|
14
15
|
const shade = (failed, text) => ({ text, style: failed ? "error" : "dim" });
|
|
15
16
|
export default definePlugin({
|
|
16
17
|
process(ctx) {
|
|
@@ -94,6 +95,9 @@ ${r.output}`);
|
|
|
94
95
|
async session(ctx) {
|
|
95
96
|
const shell = typeof ctx.config.shell === "string" ? ctx.config.shell : undefined;
|
|
96
97
|
const id = ctx.session.id;
|
|
98
|
+
const jobs = new Set;
|
|
99
|
+
const stoppedByUser = new Set;
|
|
100
|
+
const finished = [];
|
|
97
101
|
const { tools, executable, unavailable, shutdown, list, kill } = shellTools({
|
|
98
102
|
cwd: ctx.cwd,
|
|
99
103
|
...shell ? { shell } : {},
|
|
@@ -101,6 +105,33 @@ ${r.output}`);
|
|
|
101
105
|
const what = `Background shell ${bg.id} (${firstLine(bg.command)}) exited with code ${bg.exitCode}`;
|
|
102
106
|
ctx.service("ui@1")?.notify(what, bg.exitCode === 0 ? "info" : "warning");
|
|
103
107
|
ctx.service("prompts@1")?.note(id, `${what}. Read its remaining output with bash_output.`);
|
|
108
|
+
},
|
|
109
|
+
onBackground(bg) {
|
|
110
|
+
const job = ctx.service("ui@1")?.job?.({
|
|
111
|
+
session: id,
|
|
112
|
+
kind: "shell",
|
|
113
|
+
title: `${bg.id} ${firstLine(bg.command)}`,
|
|
114
|
+
async stop() {
|
|
115
|
+
stoppedByUser.add(bg.id);
|
|
116
|
+
if (await kill(bg.id))
|
|
117
|
+
ctx.service("prompts@1")?.note(id, `The user stopped background shell ${bg.id} (${firstLine(bg.command)}).`);
|
|
118
|
+
}
|
|
119
|
+
});
|
|
120
|
+
if (!job)
|
|
121
|
+
return;
|
|
122
|
+
jobs.add(job);
|
|
123
|
+
job.status("running");
|
|
124
|
+
return {
|
|
125
|
+
output: (text) => job.append(text),
|
|
126
|
+
exit: (code, killed) => {
|
|
127
|
+
job.status(stoppedByUser.has(bg.id) ? "stopped by you" : killed ? "stopped" : `exited with code ${code}`, true);
|
|
128
|
+
finished.push(job);
|
|
129
|
+
for (const old of finished.splice(0, Math.max(0, finished.length - MAX_FINISHED_JOBS))) {
|
|
130
|
+
old.dispose();
|
|
131
|
+
jobs.delete(old);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
};
|
|
104
135
|
}
|
|
105
136
|
});
|
|
106
137
|
sessions.set(id, { list, kill });
|
|
@@ -125,6 +156,8 @@ ${r.output}`);
|
|
|
125
156
|
await ctx.effect(() => () => {
|
|
126
157
|
sessions.delete(id);
|
|
127
158
|
shutdown();
|
|
159
|
+
for (const job of jobs)
|
|
160
|
+
job.dispose();
|
|
128
161
|
});
|
|
129
162
|
}
|
|
130
163
|
});
|
|
@@ -26,7 +26,9 @@ export function shellTools(opts) {
|
|
|
26
26
|
async function startBackground(command) {
|
|
27
27
|
const id = `bg${nextId++}`;
|
|
28
28
|
const bg = { id, command, proc: await spawn(command), unread: "", dropped: 0 };
|
|
29
|
+
const watcher = opts.onBackground?.({ id, command });
|
|
29
30
|
const append = (text) => {
|
|
31
|
+
watcher?.output(text);
|
|
30
32
|
bg.unread += text;
|
|
31
33
|
if (bg.unread.length > MAX_BUFFER_CHARS) {
|
|
32
34
|
bg.dropped += bg.unread.length - MAX_BUFFER_CHARS;
|
|
@@ -36,6 +38,7 @@ export function shellTools(opts) {
|
|
|
36
38
|
Promise.all([collect(bg.proc.stdout, append, false), collect(bg.proc.stderr, append, false)]).catch(() => {});
|
|
37
39
|
bg.proc.exited.then((code) => {
|
|
38
40
|
bg.exitCode = code;
|
|
41
|
+
watcher?.exit(code, bg.killed === true);
|
|
39
42
|
if (!bg.killed)
|
|
40
43
|
opts.onExit?.({ id, command, exitCode: code });
|
|
41
44
|
});
|
|
@@ -80,7 +80,9 @@ export default definePlugin({
|
|
|
80
80
|
controls.set(child, control);
|
|
81
81
|
return () => void controls.delete(child);
|
|
82
82
|
},
|
|
83
|
-
usage: (toolUseId, u) => void usage.set(toolUseId, u)
|
|
83
|
+
usage: (toolUseId, u) => void usage.set(toolUseId, u),
|
|
84
|
+
job: (description, stop) => ctx.service("ui@1")?.job?.({ session: ctx.session.id, kind: "agent", title: description, stop }),
|
|
85
|
+
describe: (name, input) => ctx.service("renderers@1")?.forTool(name)?.renderer.summary?.(input) ?? clip(JSON.stringify(input) ?? "", 120)
|
|
84
86
|
}));
|
|
85
87
|
ctx.kernel.hook({
|
|
86
88
|
kind: "transform",
|
|
@@ -6,6 +6,8 @@ export const CHARS_PER_TOKEN = 4;
|
|
|
6
6
|
export const OMITTED = "[Output omitted to fit the context window. Use what you noted from it in your later messages.]";
|
|
7
7
|
export const WRAP_UP = "You have reached your step limit. Do not call any more tools: write your report now from what you have found so far, " + "and say what you could not check.";
|
|
8
8
|
export const READ_ONLY_REASON = (name) => `${name}: sub-agents can only run read-only commands inside the working directory (for example git log, git diff, ls, rg). Describe anything else in your report instead.`;
|
|
9
|
+
export const STOPPED = "The user stopped this sub-agent before it finished. Do not start it again unless the user asks.";
|
|
10
|
+
const JOB_RESULT_CHARS = 160;
|
|
9
11
|
const MAX_REPORT_CHARS = 20000;
|
|
10
12
|
export function subagentPrompt(steps, write) {
|
|
11
13
|
return `You are a ${write ? "" : "read-only "}research sub-agent for a coding agent. Investigate the task you are given, then reply with a concise report: the answer first, then the evidence as path:line references (or URLs for web pages).
|
|
@@ -76,24 +78,54 @@ export function taskTool(opts) {
|
|
|
76
78
|
const unregister = opts.register(child.id, control);
|
|
77
79
|
const progress = (p) => ctx.progress(p);
|
|
78
80
|
progress({ kind: "task-start", sessionId: child.id, description });
|
|
81
|
+
let stopped = false;
|
|
82
|
+
const job = opts.job?.(description, () => {
|
|
83
|
+
stopped = true;
|
|
84
|
+
child.abort("stopped by the user");
|
|
85
|
+
});
|
|
86
|
+
job?.status("starting");
|
|
87
|
+
const describe = (name, input) => opts.describe?.(name, input) ?? clipText(JSON.stringify(input) ?? "", JOB_RESULT_CHARS);
|
|
79
88
|
const names = new Map;
|
|
80
89
|
const unsubscribe = child.subscribe((n) => {
|
|
81
90
|
if (n.type !== "event")
|
|
82
91
|
return;
|
|
83
92
|
if (n.event.type === "model.requested") {
|
|
84
93
|
progress({ kind: "task-model" });
|
|
94
|
+
job?.status("thinking");
|
|
85
95
|
} else if (n.event.type === "model.responded") {
|
|
86
96
|
const data = n.event.data;
|
|
87
97
|
for (const b of data.content)
|
|
88
98
|
if (b.kind === "tool_use")
|
|
89
99
|
names.set(b.id, b.name);
|
|
100
|
+
const said = data.content.flatMap((b) => b.kind === "text" && b.text.trim() ? [b.text.trim()] : []).join(`
|
|
101
|
+
`);
|
|
102
|
+
if (said)
|
|
103
|
+
job?.append(`${said}
|
|
104
|
+
|
|
105
|
+
`);
|
|
90
106
|
for (const k of Object.keys(used))
|
|
91
107
|
used[k] += data.usage?.[k] ?? 0;
|
|
92
108
|
if (data.usage)
|
|
93
109
|
control.lastTokens = (data.usage.inputTokens ?? 0) + (data.usage.outputTokens ?? 0);
|
|
94
110
|
} else if (n.event.type === "tool.decided") {
|
|
95
111
|
const d = n.event.data;
|
|
96
|
-
|
|
112
|
+
const name = names.get(d.toolUseId) ?? "?";
|
|
113
|
+
progress({ kind: "task-tool", name, input: d.input, decision: d.decision });
|
|
114
|
+
if (job) {
|
|
115
|
+
const call = [`● ${name}(`, describe(name, d.input), ")"];
|
|
116
|
+
job.status(`${name}(${plain(describe(name, d.input))})`);
|
|
117
|
+
job.append(d.decision === "deny" ? [call, { text: ` ✗ denied${d.reason ? `: ${d.reason}` : ""}`, style: "error" }, `
|
|
118
|
+
`] : [call, `
|
|
119
|
+
`]);
|
|
120
|
+
}
|
|
121
|
+
} else if (n.event.type === "tool.completed" && job) {
|
|
122
|
+
const d = n.event.data;
|
|
123
|
+
const out = d.content.flatMap((b) => b.kind === "text" ? [b.text] : []).join(`
|
|
124
|
+
`).trim().split(`
|
|
125
|
+
`);
|
|
126
|
+
const more = out.length > 1 ? ` (+${out.length - 1} lines)` : "";
|
|
127
|
+
job.append([{ text: ` ⎿ ${clipText(out[0] ?? "", JOB_RESULT_CHARS)}${more}`, style: d.isError ? "error" : "dim" }, `
|
|
128
|
+
`]);
|
|
97
129
|
}
|
|
98
130
|
});
|
|
99
131
|
const forward = () => child.abort(String(ctx.signal.reason ?? "aborted"));
|
|
@@ -114,7 +146,7 @@ export function taskTool(opts) {
|
|
|
114
146
|
}
|
|
115
147
|
const cause = unwrap(failure);
|
|
116
148
|
const exhausted = cause instanceof ProviderError && cause.retryable;
|
|
117
|
-
if (!ctx.signal.aborted && !exhausted && !lastText(child.state.messages)) {
|
|
149
|
+
if (!ctx.signal.aborted && !stopped && !exhausted && !lastText(child.state.messages)) {
|
|
118
150
|
control.wrapUp = true;
|
|
119
151
|
try {
|
|
120
152
|
await turn(WRAP_UP);
|
|
@@ -133,12 +165,17 @@ export function taskTool(opts) {
|
|
|
133
165
|
return;
|
|
134
166
|
});
|
|
135
167
|
unregister();
|
|
168
|
+
job?.dispose();
|
|
136
169
|
opts.usage?.(ctx.toolUseId, used);
|
|
137
170
|
}
|
|
138
171
|
if (ctx.signal.aborted)
|
|
139
172
|
throw failure ?? ctx.signal.reason;
|
|
140
173
|
const linked = ref ? { child: ref } : {};
|
|
141
174
|
const text = clip(lastText(messages) || allText(messages));
|
|
175
|
+
if (stopped && failure)
|
|
176
|
+
return { content: `${STOPPED}${text ? `
|
|
177
|
+
What it had written so far:
|
|
178
|
+
${text}` : ""}`, isError: true, ...linked };
|
|
142
179
|
if (failure) {
|
|
143
180
|
const msg = failure instanceof Error ? failure.message : String(failure);
|
|
144
181
|
return { content: `Sub-agent failed: ${msg}${text ? `
|
|
@@ -170,6 +207,14 @@ function allText(messages) {
|
|
|
170
207
|
|
|
171
208
|
`);
|
|
172
209
|
}
|
|
210
|
+
const clipText = (s, n) => s.length > n ? `${s.slice(0, n)}…` : s;
|
|
211
|
+
function plain(t) {
|
|
212
|
+
if (typeof t === "string")
|
|
213
|
+
return t;
|
|
214
|
+
if (Array.isArray(t))
|
|
215
|
+
return t.map(plain).join("");
|
|
216
|
+
return String(t.text ?? "");
|
|
217
|
+
}
|
|
173
218
|
function clip(s) {
|
|
174
219
|
return s.length > MAX_REPORT_CHARS ? `${s.slice(0, MAX_REPORT_CHARS)}
|
|
175
220
|
… (report truncated: ${s.length - MAX_REPORT_CHARS} more characters)` : s;
|
|
@@ -24,6 +24,7 @@ Run one prompt without the interface: jade -p <prompt> (jade -p --help for more)
|
|
|
24
24
|
jade's own commands (plugins, update, --safe): jade help`;
|
|
25
25
|
const OWN = [
|
|
26
26
|
{ name: "help", about: "list the commands and keys" },
|
|
27
|
+
{ name: "tasks", about: "list sub-agents and background commands (same as ctrl+t)" },
|
|
27
28
|
{ name: "exit", about: "quit (the session stays resumable)" }
|
|
28
29
|
];
|
|
29
30
|
const KEYS = [
|
|
@@ -31,7 +32,7 @@ const KEYS = [
|
|
|
31
32
|
" send enter send · ctrl+j, alt+enter or \\ then enter: new line · tab completes /commands",
|
|
32
33
|
" input ↑↓ history · ctrl+r search history · ↑ on the first line edits queued messages · esc twice or ctrl+c clears the input",
|
|
33
34
|
" editing ctrl+←/→ or alt+b/f move by words · ctrl+w or alt+backspace delete a word · ctrl+a/e line start/end · ctrl+u/k delete to start/end",
|
|
34
|
-
" running esc interrupt (twice to also move queued messages back to the input) · ctrl+c twice to exit",
|
|
35
|
+
" running esc interrupt (twice to also move queued messages back to the input) · ctrl+c twice to exit · ctrl+t, /tasks or a click on the status bar lists sub-agents and background commands",
|
|
35
36
|
" transcript pgup/pgdn scroll · ctrl+home/end top/bottom · ctrl+o expands the latest item, a click the one under it · drag to select and copy · ctrl+l redraw"
|
|
36
37
|
].join(`
|
|
37
38
|
`);
|
|
@@ -93,10 +94,14 @@ export class ScreenBridge {
|
|
|
93
94
|
#segments = new Map;
|
|
94
95
|
#panels = new Map;
|
|
95
96
|
#session;
|
|
97
|
+
#notices = 0;
|
|
98
|
+
#jobs = [];
|
|
99
|
+
#nextJob = 0;
|
|
100
|
+
#jobTimer;
|
|
96
101
|
ui = {
|
|
97
102
|
interactive: true,
|
|
98
103
|
notify: (message, level = "info") => {
|
|
99
|
-
const text =
|
|
104
|
+
const text = noticeText(message, level);
|
|
100
105
|
if (this.#held)
|
|
101
106
|
this.#held.push(text);
|
|
102
107
|
else if (this.screen)
|
|
@@ -107,6 +112,13 @@ export class ScreenBridge {
|
|
|
107
112
|
else
|
|
108
113
|
this.#early.push(text);
|
|
109
114
|
},
|
|
115
|
+
notice: (message, level = "info") => {
|
|
116
|
+
if (this.#held || !this.screen?.note)
|
|
117
|
+
return;
|
|
118
|
+
const id = `\x00notice-${++this.#notices}`;
|
|
119
|
+
this.screen.note(id, noticeText(message, level));
|
|
120
|
+
return { update: (m, l = "info") => this.screen?.note?.(id, noticeText(m, l)) };
|
|
121
|
+
},
|
|
110
122
|
select: async (req, signal) => {
|
|
111
123
|
if (!this.screen)
|
|
112
124
|
return;
|
|
@@ -124,7 +136,8 @@ export class ScreenBridge {
|
|
|
124
136
|
return true;
|
|
125
137
|
},
|
|
126
138
|
suspend: async (fn) => this.screen?.suspend ? this.screen.suspend(fn) : fn(),
|
|
127
|
-
session: ({ session, plugin }) => this.#sessionUI(session, plugin)
|
|
139
|
+
session: ({ session, plugin }) => this.#sessionUI(session, plugin),
|
|
140
|
+
job: (req) => this.#job(req)
|
|
128
141
|
};
|
|
129
142
|
attach(screen) {
|
|
130
143
|
this.screen = screen;
|
|
@@ -145,12 +158,53 @@ export class ScreenBridge {
|
|
|
145
158
|
}
|
|
146
159
|
}
|
|
147
160
|
detach() {
|
|
161
|
+
clearTimeout(this.#jobTimer);
|
|
148
162
|
this.screen = undefined;
|
|
149
163
|
this.#closed = true;
|
|
150
164
|
}
|
|
151
165
|
show(session) {
|
|
152
166
|
this.#session = session;
|
|
153
167
|
this.#apply();
|
|
168
|
+
this.#applyJobs();
|
|
169
|
+
}
|
|
170
|
+
#job(req) {
|
|
171
|
+
const entry = {
|
|
172
|
+
id: ++this.#nextJob,
|
|
173
|
+
session: String(req.session),
|
|
174
|
+
kind: String(req.kind),
|
|
175
|
+
title: String(req.title),
|
|
176
|
+
status: "",
|
|
177
|
+
done: false,
|
|
178
|
+
output: "",
|
|
179
|
+
...req.stop ? { stop: () => req.stop() } : {}
|
|
180
|
+
};
|
|
181
|
+
this.#jobs = [...this.#jobs, { ...entry }];
|
|
182
|
+
this.#applyJobs();
|
|
183
|
+
const update = (patch, soon = false) => {
|
|
184
|
+
if (!this.#jobs.some((j) => j.id === entry.id))
|
|
185
|
+
return;
|
|
186
|
+
Object.assign(entry, patch);
|
|
187
|
+
this.#jobs = this.#jobs.map((j) => j.id === entry.id ? { ...entry } : j);
|
|
188
|
+
if (soon)
|
|
189
|
+
this.#jobTimer ??= setTimeout(() => this.#applyJobs(), JOB_REDRAW_MS);
|
|
190
|
+
else
|
|
191
|
+
this.#applyJobs();
|
|
192
|
+
};
|
|
193
|
+
return {
|
|
194
|
+
append: (text) => update({ output: (entry.output + ansi(text)).slice(-MAX_JOB_OUTPUT) }, true),
|
|
195
|
+
status: (text, done) => update({ status: String(text), done: done === true }),
|
|
196
|
+
dispose: () => {
|
|
197
|
+
const before = this.#jobs.length;
|
|
198
|
+
this.#jobs = this.#jobs.filter((j) => j.id !== entry.id);
|
|
199
|
+
if (this.#jobs.length !== before)
|
|
200
|
+
this.#applyJobs();
|
|
201
|
+
}
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
#applyJobs() {
|
|
205
|
+
clearTimeout(this.#jobTimer);
|
|
206
|
+
this.#jobTimer = undefined;
|
|
207
|
+
this.screen?.jobs?.(this.#jobs.filter((j) => j.session === this.#session));
|
|
154
208
|
}
|
|
155
209
|
#apply() {
|
|
156
210
|
if (!this.screen)
|
|
@@ -204,6 +258,9 @@ export class ScreenBridge {
|
|
|
204
258
|
};
|
|
205
259
|
}
|
|
206
260
|
}
|
|
261
|
+
const MAX_JOB_OUTPUT = 1e5;
|
|
262
|
+
const JOB_REDRAW_MS = 100;
|
|
263
|
+
const noticeText = (message, level) => level === "error" ? red(`[error] ${message}`) : level === "warning" ? yellow(`[warning] ${message}`) : dim(message);
|
|
207
264
|
function clipPanel(text) {
|
|
208
265
|
const lines = String(text).replace(/\r\n?/g, `
|
|
209
266
|
`).replace(/\n+$/, "").split(`
|
|
@@ -544,6 +601,13 @@ ${USAGE}
|
|
|
544
601
|
const rest = input.slice(1).replace(/^\S+\s*/, "");
|
|
545
602
|
if (name === "exit" || name === "quit")
|
|
546
603
|
return false;
|
|
604
|
+
if (name === "tasks") {
|
|
605
|
+
if (screen.showJobs)
|
|
606
|
+
screen.showJobs();
|
|
607
|
+
else
|
|
608
|
+
screen.log(dim("[background tasks are only listed in the terminal interface]"));
|
|
609
|
+
return true;
|
|
610
|
+
}
|
|
547
611
|
if (name === "help") {
|
|
548
612
|
const extras = [
|
|
549
613
|
...commands.list().flatMap((c) => c.prefix ? [`${c.prefix}${c.args ?? ""} is /${c.name}`] : []),
|
|
@@ -66,6 +66,9 @@ export function safeScreen(screen) {
|
|
|
66
66
|
interactive: screen.interactive,
|
|
67
67
|
log: (text, o) => screen.log(s(text), o && { ...o, details: opt(o.details) }),
|
|
68
68
|
amend: (id, text, o) => screen.amend(id, s(text), o && { ...o, details: opt(o.details) }),
|
|
69
|
+
...screen.note ? { note: (id, text) => screen.note(id, s(text)) } : {},
|
|
70
|
+
...screen.jobs ? { jobs: (jobs) => screen.jobs(jobs.map((j) => ({ ...j, title: s(j.title), status: s(j.status), output: s(j.output) }))) } : {},
|
|
71
|
+
...screen.showJobs ? { showJobs: () => screen.showJobs() } : {},
|
|
69
72
|
progress: (id, line, o) => screen.progress(id, opt(line), o),
|
|
70
73
|
stream: (kind, text) => {
|
|
71
74
|
if (held && held.kind !== kind)
|
package/plugins-dist/tui/tui.js
CHANGED
|
@@ -128,7 +128,7 @@ export class Store {
|
|
|
128
128
|
#repaintTimer;
|
|
129
129
|
paused = false;
|
|
130
130
|
constructor(status, size) {
|
|
131
|
-
this.state = { version: 0, scroll: 0, progress: [], queued: [], dialogs: [], status, size };
|
|
131
|
+
this.state = { version: 0, scroll: 0, progress: [], queued: [], dialogs: [], jobs: [], status, size };
|
|
132
132
|
}
|
|
133
133
|
subscribe = (fn) => {
|
|
134
134
|
this.#listeners.add(fn);
|
|
@@ -161,6 +161,12 @@ export class Store {
|
|
|
161
161
|
this.paused = true;
|
|
162
162
|
this.#repaintTimer = setTimeout(() => this.#repaintNow(), REPAINT_GAP_MS);
|
|
163
163
|
}
|
|
164
|
+
openJobs() {
|
|
165
|
+
if (this.state.dialogs.length)
|
|
166
|
+
return;
|
|
167
|
+
const d = { kind: "jobs", resolve: () => this.update({ dialogs: this.state.dialogs.filter((x) => x !== d) }, true) };
|
|
168
|
+
this.update({ dialogs: [...this.state.dialogs, d] }, true);
|
|
169
|
+
}
|
|
164
170
|
#repaintNow(patch = {}) {
|
|
165
171
|
clearTimeout(this.#repaintTimer);
|
|
166
172
|
this.paused = false;
|
|
@@ -494,6 +500,13 @@ export function tuiScreen(opts) {
|
|
|
494
500
|
if (!found)
|
|
495
501
|
store.append([` ${text}`], o?.details !== undefined ? { details: o.details } : undefined);
|
|
496
502
|
},
|
|
503
|
+
note(id, text) {
|
|
504
|
+
if (store.amend(id, (l) => void (l.text = text)))
|
|
505
|
+
return;
|
|
506
|
+
flushLive(true);
|
|
507
|
+
store.update({ live: undefined });
|
|
508
|
+
store.append([text], { id });
|
|
509
|
+
},
|
|
497
510
|
progress(id, line) {
|
|
498
511
|
const rest = store.state.progress.filter((p) => p.id !== id);
|
|
499
512
|
store.update({
|
|
@@ -553,6 +566,10 @@ export function tuiScreen(opts) {
|
|
|
553
566
|
queued(items) {
|
|
554
567
|
store.update({ queued: [...items] });
|
|
555
568
|
},
|
|
569
|
+
jobs(jobs) {
|
|
570
|
+
store.update({ jobs });
|
|
571
|
+
},
|
|
572
|
+
showJobs: () => store.openJobs(),
|
|
556
573
|
draft: {
|
|
557
574
|
text: () => draft.current?.get() ?? "",
|
|
558
575
|
insert: (text) => draft.current?.apply((s) => edit.insert(s, text.replace(/\r\n?/g, `
|
|
@@ -715,9 +732,10 @@ function App({
|
|
|
715
732
|
draft
|
|
716
733
|
}) {
|
|
717
734
|
const state = useSyncExternalStore(store.subscribe, store.get);
|
|
718
|
-
const dialog = state.dialogs[0];
|
|
735
|
+
const dialog = state.dialogs.find((d) => d.kind !== "jobs") ?? state.dialogs[0];
|
|
719
736
|
const columns = Math.max(1, state.size.columns - 1);
|
|
720
737
|
const rows = state.size.rows;
|
|
738
|
+
const statusWidth = Math.max(10, columns - 2);
|
|
721
739
|
const compact = rows < COMPACT_ROWS;
|
|
722
740
|
const [ticks, tickNow] = useReducer((n) => n + 1, 0);
|
|
723
741
|
const tick = () => store.paused || tickNow();
|
|
@@ -729,7 +747,7 @@ function App({
|
|
|
729
747
|
return () => clearInterval(t);
|
|
730
748
|
}, [busy]);
|
|
731
749
|
const now = Date.now();
|
|
732
|
-
const mood = moodOf({ busy: state.busy?.label, asking: dialog !== undefined, doneAt: state.doneAt }, now);
|
|
750
|
+
const mood = moodOf({ busy: state.busy?.label, asking: dialog !== undefined && dialog.kind !== "jobs", doneAt: state.doneAt }, now);
|
|
733
751
|
const mascot = useRef(undefined);
|
|
734
752
|
mascot.current ??= new Mascot;
|
|
735
753
|
const showBot = !compact && columns >= 50;
|
|
@@ -814,8 +832,15 @@ function App({
|
|
|
814
832
|
return store.repaint();
|
|
815
833
|
if (key.ctrl && input === "o")
|
|
816
834
|
return store.toggleLatest(start, view);
|
|
835
|
+
if (key.ctrl && input === "t")
|
|
836
|
+
return store.openJobs();
|
|
817
837
|
const mouse = mouseEvent(input);
|
|
818
838
|
if (mouse) {
|
|
839
|
+
if (mouse.button === 0 && mouse.press && mouse.y === rows - 2) {
|
|
840
|
+
const cols = jobsColumns(statusSegments(state.status, state.jobs, statusWidth));
|
|
841
|
+
if (cols && mouse.x >= cols[0] && mouse.x <= cols[1])
|
|
842
|
+
return store.openJobs();
|
|
843
|
+
}
|
|
819
844
|
const at = (clamp) => {
|
|
820
845
|
const i = mouse.y - top;
|
|
821
846
|
if (!clamp && (i < 0 || i >= shown.length))
|
|
@@ -873,7 +898,7 @@ function App({
|
|
|
873
898
|
pressed.current = undefined;
|
|
874
899
|
setSelection(undefined);
|
|
875
900
|
}
|
|
876
|
-
if (dialog?.kind === "select")
|
|
901
|
+
if (dialog?.kind === "select" || dialog?.kind === "jobs")
|
|
877
902
|
return;
|
|
878
903
|
if (key.pageUp)
|
|
879
904
|
store.scrollBy(page, max);
|
|
@@ -903,7 +928,7 @@ function App({
|
|
|
903
928
|
const cols = selection && selectedCols(selection, start + i - front);
|
|
904
929
|
return h(Text, { key: i, wrap: "truncate-end" }, cols ? highlight(l || " ", ...cols) : l || " ");
|
|
905
930
|
}), scrolled ? h(Text, { dimColor: true, wrap: "truncate-end" }, `── ↓ ${scroll} more lines · wheel / PgDn to scroll · ctrl+end to jump to the bottom ──`) : null), h(Box, { flexDirection: "column", flexShrink: 0 }, state.busy && !dialog ? h(Spinner, { label: state.busy.label, since: state.busy.since }) : null, dialog ? null : (state.status.panels ?? []).flatMap((p) => p.text.split(`
|
|
906
|
-
`).map((l, i) => h(Text, { key: `${p.plugin}:${i}`, wrap: "truncate-end" }, " ", l || " "))), state.queued.map((q, i) => h(Text, { key: i, dimColor: true, wrap: "truncate-end" }, " ↳ queued: ", q.replace(/\s+/g, " "))), dialog ? dialog.kind === "select" ? h(SelectDialog, { key: dialogKey(dialog), dialog }) : h(InputDialog, { key: dialogKey(dialog), dialog }) : null, h(Prompt, {
|
|
931
|
+
`).map((l, i) => h(Text, { key: `${p.plugin}:${i}`, wrap: "truncate-end" }, " ", l || " "))), state.queued.map((q, i) => h(Text, { key: i, dimColor: true, wrap: "truncate-end" }, " ↳ queued: ", q.replace(/\s+/g, " "))), dialog ? dialog.kind === "select" ? h(SelectDialog, { key: dialogKey(dialog), dialog }) : dialog.kind === "jobs" ? h(JobsDialog, { key: dialogKey(dialog), dialog, jobs: state.jobs }) : h(InputDialog, { key: dialogKey(dialog), dialog }) : null, h(Prompt, {
|
|
907
932
|
commands,
|
|
908
933
|
handlers,
|
|
909
934
|
history,
|
|
@@ -917,7 +942,7 @@ function App({
|
|
|
917
942
|
flash: copied,
|
|
918
943
|
place: inputPlace,
|
|
919
944
|
onCopy: copyText
|
|
920
|
-
}), h(StatusBar, { status: state.status,
|
|
945
|
+
}), h(StatusBar, { status: state.status, jobs: state.jobs, width: statusWidth }))))));
|
|
921
946
|
}
|
|
922
947
|
function Bot({ pixels }) {
|
|
923
948
|
return h(Box, { flexDirection: "column", flexShrink: 0, marginRight: 1 }, ...cells(pixels).map((row, i) => h(Text, { key: i }, ...row.map((r, j) => h(Text, { key: j, color: r.fg, backgroundColor: r.bg }, r.text)))));
|
|
@@ -971,7 +996,7 @@ export function fitSegments(segments, width) {
|
|
|
971
996
|
}
|
|
972
997
|
return kept;
|
|
973
998
|
}
|
|
974
|
-
function
|
|
999
|
+
function statusSegments(status, jobs, width) {
|
|
975
1000
|
const ctx = status.context;
|
|
976
1001
|
const pct = ctx ? Math.round(ctx.used / ctx.limit * 100) : 0;
|
|
977
1002
|
const nearFull = pct >= 80;
|
|
@@ -987,8 +1012,10 @@ function StatusBar({ status, width }) {
|
|
|
987
1012
|
};
|
|
988
1013
|
const kept = (status.plugins ?? []).filter((p) => typeof p.text !== "string" && p.text.keep);
|
|
989
1014
|
const others = (status.plugins ?? []).filter((p) => !kept.includes(p));
|
|
1015
|
+
const running = runningJobs(jobs);
|
|
990
1016
|
const segments = [
|
|
991
1017
|
...kept.map((p) => plugin(p, true)),
|
|
1018
|
+
...running ? [{ text: `${running} · click or ctrl+t to view`, short: running, shortAt: 6.5, color: "cyan", jobs: true }] : [],
|
|
992
1019
|
ctx ? {
|
|
993
1020
|
text: `ctx ${tokens(ctx.used)}/${tokens(ctx.limit)} (${pct}%)`,
|
|
994
1021
|
short: `ctx ${pct}%`,
|
|
@@ -1003,7 +1030,7 @@ function StatusBar({ status, width }) {
|
|
|
1003
1030
|
dim: true
|
|
1004
1031
|
}
|
|
1005
1032
|
] : [],
|
|
1006
|
-
...status.cache !== undefined ? [{ text: `cache ${Math.round(status.cache *
|
|
1033
|
+
...status.cache !== undefined ? [{ text: `cache ${Math.round(status.cache * 1000) / 10}%`, dropAt: 7, dim: true }] : [],
|
|
1007
1034
|
...status.spent ? [
|
|
1008
1035
|
{
|
|
1009
1036
|
text: `session ${tokens(status.spent.input)} in / ${tokens(status.spent.output)} out`,
|
|
@@ -1022,7 +1049,22 @@ function StatusBar({ status, width }) {
|
|
|
1022
1049
|
dim: true
|
|
1023
1050
|
}
|
|
1024
1051
|
];
|
|
1025
|
-
|
|
1052
|
+
return fitSegments(segments, width);
|
|
1053
|
+
}
|
|
1054
|
+
function jobsColumns(segments) {
|
|
1055
|
+
let x = 1;
|
|
1056
|
+
for (const [i, s] of segments.entries()) {
|
|
1057
|
+
if (i)
|
|
1058
|
+
x += 3;
|
|
1059
|
+
const w = visibleWidth(s.text);
|
|
1060
|
+
if (s.jobs)
|
|
1061
|
+
return [x, x + w - 1];
|
|
1062
|
+
x += w;
|
|
1063
|
+
}
|
|
1064
|
+
return;
|
|
1065
|
+
}
|
|
1066
|
+
function StatusBar({ status, jobs, width }) {
|
|
1067
|
+
const shown = statusSegments(status, jobs, width);
|
|
1026
1068
|
return h(Box, { paddingX: 1 }, h(Text, { wrap: "truncate-end" }, shown.map((s, i) => h(Text, { key: i }, i ? h(Text, { dimColor: true }, " · ") : null, h(Text, { color: s.color, dimColor: s.dim }, s.text)))));
|
|
1027
1069
|
}
|
|
1028
1070
|
function Hint({ variants, width }) {
|
|
@@ -1643,6 +1685,87 @@ function SelectDialog({
|
|
|
1643
1685
|
variants: filtering ? ["↑↓ select · type to filter · enter confirm · esc clear/cancel", "↑↓ · enter · esc"] : ["↑↓ select · enter confirm · esc cancel", "↑↓ · enter · esc"]
|
|
1644
1686
|
}));
|
|
1645
1687
|
}
|
|
1688
|
+
export function runningJobs(jobs) {
|
|
1689
|
+
const counts = new Map;
|
|
1690
|
+
for (const j of jobs)
|
|
1691
|
+
if (!j.done)
|
|
1692
|
+
counts.set(j.kind, (counts.get(j.kind) ?? 0) + 1);
|
|
1693
|
+
return [...counts].map(([kind, n]) => `${n} ${kind}${n > 1 ? "s" : ""}`).join(" · ");
|
|
1694
|
+
}
|
|
1695
|
+
const JOB_TAIL_LINES = 2000;
|
|
1696
|
+
function JobsDialog({ dialog, jobs }) {
|
|
1697
|
+
const selection = useContext(SelectionContext);
|
|
1698
|
+
const [getSelected, setSelected] = useLive(0);
|
|
1699
|
+
const [getViewing, setViewing] = useLive(undefined);
|
|
1700
|
+
const [getBack, setBack] = useLive(0);
|
|
1701
|
+
const { rows, columns } = useScreenSize();
|
|
1702
|
+
const width = Math.max(10, columns - 4);
|
|
1703
|
+
const viewing = jobs.find((j) => j.id === getViewing());
|
|
1704
|
+
const selected = Math.min(getSelected(), Math.max(0, jobs.length - 1));
|
|
1705
|
+
const room = Math.max(3, rows - 14);
|
|
1706
|
+
const lines = viewing ? wrap(viewing.output.replace(/\n+$/, "").split(`
|
|
1707
|
+
`).slice(-JOB_TAIL_LINES).join(`
|
|
1708
|
+
`), width).map(visibleRow) : [];
|
|
1709
|
+
const maxBack = Math.max(0, lines.length - room);
|
|
1710
|
+
const back = Math.min(getBack(), maxBack);
|
|
1711
|
+
const scrolling = useRef({ maxBack, room });
|
|
1712
|
+
scrolling.current = { maxBack, room };
|
|
1713
|
+
useInput((input, key) => {
|
|
1714
|
+
if (key.ctrl && input === "c" && selection.active())
|
|
1715
|
+
return selection.clear();
|
|
1716
|
+
const current = jobs.find((j) => j.id === getViewing());
|
|
1717
|
+
const target = current ?? jobs[Math.min(getSelected(), jobs.length - 1)];
|
|
1718
|
+
if (input === "x" && target && !target.done && target.stop)
|
|
1719
|
+
return target.stop();
|
|
1720
|
+
if (current) {
|
|
1721
|
+
const { maxBack, room } = scrolling.current;
|
|
1722
|
+
const by = (n) => setBack(Math.max(0, Math.min(maxBack, Math.min(getBack(), maxBack) + n)));
|
|
1723
|
+
if (key.pageUp)
|
|
1724
|
+
return by(room - 1);
|
|
1725
|
+
if (key.pageDown)
|
|
1726
|
+
return by(-(room - 1));
|
|
1727
|
+
if (key.upArrow || input === "k")
|
|
1728
|
+
return by(1);
|
|
1729
|
+
if (key.downArrow || input === "j")
|
|
1730
|
+
return by(-1);
|
|
1731
|
+
if (key.escape || key.leftArrow || key.ctrl && input === "c") {
|
|
1732
|
+
setBack(0);
|
|
1733
|
+
return setViewing(undefined);
|
|
1734
|
+
}
|
|
1735
|
+
return;
|
|
1736
|
+
}
|
|
1737
|
+
const n = jobs.length;
|
|
1738
|
+
if (key.upArrow || input === "k")
|
|
1739
|
+
return n && setSelected((Math.min(getSelected(), n - 1) - 1 + n) % n);
|
|
1740
|
+
if (key.downArrow || input === "j")
|
|
1741
|
+
return n && setSelected((Math.min(getSelected(), n - 1) + 1) % n);
|
|
1742
|
+
if ((key.return || key.rightArrow) && target) {
|
|
1743
|
+
setBack(0);
|
|
1744
|
+
return setViewing(target.id);
|
|
1745
|
+
}
|
|
1746
|
+
if (key.escape || key.ctrl && input === "c")
|
|
1747
|
+
return dialog.resolve(undefined);
|
|
1748
|
+
});
|
|
1749
|
+
const mark = (j) => j.done ? h(Text, { dimColor: true }, "○ ") : h(Text, { color: "green" }, "● ");
|
|
1750
|
+
const canStop = (j) => j !== undefined && !j.done && j.stop !== undefined;
|
|
1751
|
+
const frame = { flexDirection: "column", borderStyle: "round", borderColor: "cyan", paddingX: 1, marginTop: 1 };
|
|
1752
|
+
if (viewing) {
|
|
1753
|
+
const shown = lines.slice(lines.length - room - back, lines.length - back);
|
|
1754
|
+
return h(Box, frame, h(Text, { wrap: "truncate-end" }, mark(viewing), h(Text, { bold: true }, `${viewing.kind} · ${viewing.title}`), viewing.status ? h(Text, { dimColor: true }, ` · ${viewing.status}`) : null), lines.length > room + back ? h(Text, { dimColor: true }, ` ↑ ${lines.length - room - back} more lines`) : null, lines.length === 0 ? h(Text, { dimColor: true }, " (no output yet)") : null, shown.map((l, i) => h(Text, { key: i, wrap: "truncate-end" }, l || " ")), back > 0 ? h(Text, { dimColor: true }, ` ↓ ${back} more lines`) : null, h(Hint, {
|
|
1755
|
+
width,
|
|
1756
|
+
variants: [`PgUp/PgDn ↑↓ scroll${canStop(viewing) ? " · x stop" : ""} · esc back`, `↑↓${canStop(viewing) ? " · x" : ""} · esc`]
|
|
1757
|
+
}));
|
|
1758
|
+
}
|
|
1759
|
+
const visible = roomFor(rows, VISIBLE);
|
|
1760
|
+
const start = around(selected, jobs.length, visible);
|
|
1761
|
+
return h(Box, frame, h(Text, { bold: true }, "Background tasks"), jobs.length === 0 ? h(Text, { dimColor: true }, "Nothing is running in the background.") : null, start > 0 ? h(Text, { dimColor: true }, ` ↑ ${start} more`) : null, jobs.slice(start, start + visible).map((j, k) => {
|
|
1762
|
+
const on = start + k === selected;
|
|
1763
|
+
return h(Text, { key: j.id, wrap: "truncate-end" }, h(Text, { color: on ? "cyan" : undefined, bold: on }, on ? "❯ " : " "), mark(j), h(Text, { color: on ? "cyan" : undefined, bold: on }, `${j.kind} · ${j.title}`), j.status ? h(Text, { dimColor: true }, ` · ${j.status}`) : null);
|
|
1764
|
+
}), start + visible < jobs.length ? h(Text, { dimColor: true }, ` ↓ ${jobs.length - start - visible} more`) : null, h(Hint, {
|
|
1765
|
+
width,
|
|
1766
|
+
variants: jobs.length ? [`↑↓ select · enter view output${canStop(jobs[selected]) ? " · x stop" : ""} · esc close`, `↑↓ · enter${canStop(jobs[selected]) ? " · x" : ""} · esc`] : ["esc close"]
|
|
1767
|
+
}));
|
|
1768
|
+
}
|
|
1646
1769
|
function InputDialog({
|
|
1647
1770
|
dialog
|
|
1648
1771
|
}) {
|
package/src/api.ts
CHANGED
|
@@ -5,7 +5,7 @@ import type { PluginLayer } from "@uncarved/jade-api";
|
|
|
5
5
|
export * from "@uncarved/jade-api";
|
|
6
6
|
|
|
7
7
|
/** 插件 API 的版本,插件在 plugin.json 的 api 字段里用 ^ 范围声明。和 @uncarved/jade-api 的版本一致 */
|
|
8
|
-
export const API_VERSION = "1.
|
|
8
|
+
export const API_VERSION = "1.6.0";
|
|
9
9
|
|
|
10
10
|
/** 来源层级,后面的层级更高(3.3) */
|
|
11
11
|
export const LAYERS: readonly PluginLayer[] = ["bundled", "user", "project"];
|
package/src/membrane.ts
CHANGED
|
@@ -31,8 +31,11 @@ export class Scope {
|
|
|
31
31
|
this.#disposers.push(owner ? { d, owner } : { d });
|
|
32
32
|
}
|
|
33
33
|
|
|
34
|
-
/**
|
|
35
|
-
|
|
34
|
+
/**
|
|
35
|
+
* 中止 signal,逆序执行清理函数;每个最多等 timeoutMs,到了 deadline(Date.now() 的时刻)以后不再等。
|
|
36
|
+
* 每个清理函数都会被调用,没等到的在后台接着跑。返回清理时的错误,不抛出
|
|
37
|
+
*/
|
|
38
|
+
async close(timeoutMs = DISPOSE_TIMEOUT_MS, deadline = Infinity): Promise<unknown[]> {
|
|
36
39
|
if (this.#closed) return [];
|
|
37
40
|
this.#closed = true;
|
|
38
41
|
this.#ctrl.abort(new StaleContext(this.plugin));
|
|
@@ -42,8 +45,10 @@ export class Scope {
|
|
|
42
45
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
43
46
|
try {
|
|
44
47
|
const done = ambient.run(owner, d);
|
|
48
|
+
const wait = Math.max(0, Math.min(timeoutMs, deadline - Date.now()));
|
|
45
49
|
const timeout = new Promise<never>((_, reject) => {
|
|
46
|
-
|
|
50
|
+
const why = wait < timeoutMs ? "dispose did not finish before the close deadline" : `dispose timed out after ${timeoutMs} ms`;
|
|
51
|
+
timer = setTimeout(() => reject(new Error(why)), wait);
|
|
47
52
|
});
|
|
48
53
|
await Promise.race([done, timeout]);
|
|
49
54
|
} catch (e) {
|