@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
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,11 +161,27 @@ 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;
|
|
167
173
|
this.update({ ...patch, repaint: true }, true);
|
|
168
174
|
}
|
|
175
|
+
#repaintPending = false;
|
|
176
|
+
repaintInTree() {
|
|
177
|
+
this.#repaintPending = true;
|
|
178
|
+
}
|
|
179
|
+
drawn = () => {
|
|
180
|
+
if (!this.#repaintPending)
|
|
181
|
+
return;
|
|
182
|
+
this.#repaintPending = false;
|
|
183
|
+
this.update({ repaint: false });
|
|
184
|
+
};
|
|
169
185
|
append(texts, item) {
|
|
170
186
|
if (texts.length === 0)
|
|
171
187
|
return;
|
|
@@ -447,6 +463,7 @@ export function tuiScreen(opts) {
|
|
|
447
463
|
exitOnCtrlC: false,
|
|
448
464
|
alternateScreen: true,
|
|
449
465
|
incrementalRendering: true,
|
|
466
|
+
onRender: store.drawn,
|
|
450
467
|
...opts.io ? { ...opts.io, interactive: true, patchConsole: false } : {}
|
|
451
468
|
});
|
|
452
469
|
for (const l of stdout.listeners("resize"))
|
|
@@ -483,6 +500,13 @@ export function tuiScreen(opts) {
|
|
|
483
500
|
if (!found)
|
|
484
501
|
store.append([` ${text}`], o?.details !== undefined ? { details: o.details } : undefined);
|
|
485
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
|
+
},
|
|
486
510
|
progress(id, line) {
|
|
487
511
|
const rest = store.state.progress.filter((p) => p.id !== id);
|
|
488
512
|
store.update({
|
|
@@ -542,6 +566,10 @@ export function tuiScreen(opts) {
|
|
|
542
566
|
queued(items) {
|
|
543
567
|
store.update({ queued: [...items] });
|
|
544
568
|
},
|
|
569
|
+
jobs(jobs) {
|
|
570
|
+
store.update({ jobs });
|
|
571
|
+
},
|
|
572
|
+
showJobs: () => store.openJobs(),
|
|
545
573
|
draft: {
|
|
546
574
|
text: () => draft.current?.get() ?? "",
|
|
547
575
|
insert: (text) => draft.current?.apply((s) => edit.insert(s, text.replace(/\r\n?/g, `
|
|
@@ -704,9 +732,10 @@ function App({
|
|
|
704
732
|
draft
|
|
705
733
|
}) {
|
|
706
734
|
const state = useSyncExternalStore(store.subscribe, store.get);
|
|
707
|
-
const dialog = state.dialogs[0];
|
|
735
|
+
const dialog = state.dialogs.find((d) => d.kind !== "jobs") ?? state.dialogs[0];
|
|
708
736
|
const columns = Math.max(1, state.size.columns - 1);
|
|
709
737
|
const rows = state.size.rows;
|
|
738
|
+
const statusWidth = Math.max(10, columns - 2);
|
|
710
739
|
const compact = rows < COMPACT_ROWS;
|
|
711
740
|
const [ticks, tickNow] = useReducer((n) => n + 1, 0);
|
|
712
741
|
const tick = () => store.paused || tickNow();
|
|
@@ -718,7 +747,7 @@ function App({
|
|
|
718
747
|
return () => clearInterval(t);
|
|
719
748
|
}, [busy]);
|
|
720
749
|
const now = Date.now();
|
|
721
|
-
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);
|
|
722
751
|
const mascot = useRef(undefined);
|
|
723
752
|
mascot.current ??= new Mascot;
|
|
724
753
|
const showBot = !compact && columns >= 50;
|
|
@@ -796,17 +825,22 @@ function App({
|
|
|
796
825
|
copiedTimer.current = setTimeout(() => setCopied(undefined), COPIED_MS);
|
|
797
826
|
};
|
|
798
827
|
const repaint = state.repaint === true;
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
store.update({ repaint: false });
|
|
802
|
-
}, [repaint]);
|
|
828
|
+
if (repaint)
|
|
829
|
+
store.repaintInTree();
|
|
803
830
|
useInput((input, key) => {
|
|
804
831
|
if (key.ctrl && input === "l")
|
|
805
832
|
return store.repaint();
|
|
806
833
|
if (key.ctrl && input === "o")
|
|
807
834
|
return store.toggleLatest(start, view);
|
|
835
|
+
if (key.ctrl && input === "t")
|
|
836
|
+
return store.openJobs();
|
|
808
837
|
const mouse = mouseEvent(input);
|
|
809
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
|
+
}
|
|
810
844
|
const at = (clamp) => {
|
|
811
845
|
const i = mouse.y - top;
|
|
812
846
|
if (!clamp && (i < 0 || i >= shown.length))
|
|
@@ -864,7 +898,7 @@ function App({
|
|
|
864
898
|
pressed.current = undefined;
|
|
865
899
|
setSelection(undefined);
|
|
866
900
|
}
|
|
867
|
-
if (dialog?.kind === "select")
|
|
901
|
+
if (dialog?.kind === "select" || dialog?.kind === "jobs")
|
|
868
902
|
return;
|
|
869
903
|
if (key.pageUp)
|
|
870
904
|
store.scrollBy(page, max);
|
|
@@ -894,7 +928,7 @@ function App({
|
|
|
894
928
|
const cols = selection && selectedCols(selection, start + i - front);
|
|
895
929
|
return h(Text, { key: i, wrap: "truncate-end" }, cols ? highlight(l || " ", ...cols) : l || " ");
|
|
896
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(`
|
|
897
|
-
`).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, {
|
|
898
932
|
commands,
|
|
899
933
|
handlers,
|
|
900
934
|
history,
|
|
@@ -908,7 +942,7 @@ function App({
|
|
|
908
942
|
flash: copied,
|
|
909
943
|
place: inputPlace,
|
|
910
944
|
onCopy: copyText
|
|
911
|
-
}), h(StatusBar, { status: state.status,
|
|
945
|
+
}), h(StatusBar, { status: state.status, jobs: state.jobs, width: statusWidth }))))));
|
|
912
946
|
}
|
|
913
947
|
function Bot({ pixels }) {
|
|
914
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)))));
|
|
@@ -962,7 +996,7 @@ export function fitSegments(segments, width) {
|
|
|
962
996
|
}
|
|
963
997
|
return kept;
|
|
964
998
|
}
|
|
965
|
-
function
|
|
999
|
+
function statusSegments(status, jobs, width) {
|
|
966
1000
|
const ctx = status.context;
|
|
967
1001
|
const pct = ctx ? Math.round(ctx.used / ctx.limit * 100) : 0;
|
|
968
1002
|
const nearFull = pct >= 80;
|
|
@@ -978,8 +1012,10 @@ function StatusBar({ status, width }) {
|
|
|
978
1012
|
};
|
|
979
1013
|
const kept = (status.plugins ?? []).filter((p) => typeof p.text !== "string" && p.text.keep);
|
|
980
1014
|
const others = (status.plugins ?? []).filter((p) => !kept.includes(p));
|
|
1015
|
+
const running = runningJobs(jobs);
|
|
981
1016
|
const segments = [
|
|
982
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 }] : [],
|
|
983
1019
|
ctx ? {
|
|
984
1020
|
text: `ctx ${tokens(ctx.used)}/${tokens(ctx.limit)} (${pct}%)`,
|
|
985
1021
|
short: `ctx ${pct}%`,
|
|
@@ -994,7 +1030,7 @@ function StatusBar({ status, width }) {
|
|
|
994
1030
|
dim: true
|
|
995
1031
|
}
|
|
996
1032
|
] : [],
|
|
997
|
-
...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 }] : [],
|
|
998
1034
|
...status.spent ? [
|
|
999
1035
|
{
|
|
1000
1036
|
text: `session ${tokens(status.spent.input)} in / ${tokens(status.spent.output)} out`,
|
|
@@ -1013,7 +1049,22 @@ function StatusBar({ status, width }) {
|
|
|
1013
1049
|
dim: true
|
|
1014
1050
|
}
|
|
1015
1051
|
];
|
|
1016
|
-
|
|
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);
|
|
1017
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)))));
|
|
1018
1069
|
}
|
|
1019
1070
|
function Hint({ variants, width }) {
|
|
@@ -1634,6 +1685,87 @@ function SelectDialog({
|
|
|
1634
1685
|
variants: filtering ? ["↑↓ select · type to filter · enter confirm · esc clear/cancel", "↑↓ · enter · esc"] : ["↑↓ select · enter confirm · esc cancel", "↑↓ · enter · esc"]
|
|
1635
1686
|
}));
|
|
1636
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
|
+
}
|
|
1637
1769
|
function InputDialog({
|
|
1638
1770
|
dialog
|
|
1639
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/session.ts
CHANGED
|
@@ -35,6 +35,7 @@ import {
|
|
|
35
35
|
type Session,
|
|
36
36
|
type SessionContext,
|
|
37
37
|
type SessionManager,
|
|
38
|
+
type StartedSession,
|
|
38
39
|
type SessionTool,
|
|
39
40
|
type SessionUI,
|
|
40
41
|
type SpawnOptions,
|
|
@@ -441,6 +442,8 @@ class LiveSession implements Session {
|
|
|
441
442
|
export class Sessions implements SessionManager {
|
|
442
443
|
readonly #host: SessionHost;
|
|
443
444
|
#current: LiveSession | undefined;
|
|
445
|
+
/** start 开的会话和交出去的句柄 */
|
|
446
|
+
#started = new Map<LiveSession, StartedSession>();
|
|
444
447
|
#store: LogStore | undefined;
|
|
445
448
|
/** 换会话串行进行 */
|
|
446
449
|
#switching: Promise<unknown> = Promise.resolve();
|
|
@@ -469,15 +472,68 @@ export class Sessions implements SessionManager {
|
|
|
469
472
|
return run;
|
|
470
473
|
}
|
|
471
474
|
|
|
472
|
-
/** 当前会话离开(detach
|
|
475
|
+
/** 当前会话离开(detach,仍可恢复);start 开的会话一并离开 */
|
|
473
476
|
async close(): Promise<void> {
|
|
474
477
|
await this.#switching;
|
|
475
478
|
const old = this.#current;
|
|
476
479
|
this.#current = undefined;
|
|
477
480
|
if (old) await this.#leave(old);
|
|
481
|
+
for (const h of [...this.#started.values()]) await h.close();
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/** 和当前会话并存的会话(无头前端同时跑多个会话):不成为当前会话,各自 close */
|
|
485
|
+
start(opts: OpenOptions = {}): Promise<StartedSession> {
|
|
486
|
+
const run = this.#switching.then(() => this.#start(opts));
|
|
487
|
+
this.#switching = run.catch(() => {});
|
|
488
|
+
return run;
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
async #start(opts: OpenOptions): Promise<StartedSession> {
|
|
492
|
+
// 同一个会话的日志不能同时挂两个 Runtime
|
|
493
|
+
if (opts.resume !== undefined && (opts.resume === this.#current?.id || this.#isStarted(opts.resume))) {
|
|
494
|
+
throw new Error(`session ${opts.resume} is already open`);
|
|
495
|
+
}
|
|
496
|
+
const s = await this.#build(opts);
|
|
497
|
+
let closing: Promise<void> | undefined;
|
|
498
|
+
const handle: StartedSession = {
|
|
499
|
+
id: s.id,
|
|
500
|
+
get state() {
|
|
501
|
+
return s.state;
|
|
502
|
+
},
|
|
503
|
+
send: (input) => s.send(input),
|
|
504
|
+
idle: () => s.idle(),
|
|
505
|
+
recover: () => s.recover(),
|
|
506
|
+
abort: (reason) => s.abort(reason),
|
|
507
|
+
subscribe: (fn) => s.subscribe(fn),
|
|
508
|
+
history: () => s.history(),
|
|
509
|
+
tool: (name) => s.tool(name),
|
|
510
|
+
close: () =>
|
|
511
|
+
(closing ??= (async () => {
|
|
512
|
+
this.#started.delete(s);
|
|
513
|
+
await this.#leave(s);
|
|
514
|
+
})()),
|
|
515
|
+
};
|
|
516
|
+
this.#started.set(s, handle);
|
|
517
|
+
return handle;
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
#isStarted(id: string): boolean {
|
|
521
|
+
return [...this.#started.keys()].some((s) => s.id === id);
|
|
478
522
|
}
|
|
479
523
|
|
|
480
524
|
async #open(opts: OpenOptions): Promise<Session> {
|
|
525
|
+
// 同一个会话的日志不能同时挂两个 Runtime:start 开着的不能再成为当前会话
|
|
526
|
+
if (opts.resume !== undefined && this.#isStarted(opts.resume)) throw new Error(`session ${opts.resume} is already open`);
|
|
527
|
+
const s = await this.#build(opts);
|
|
528
|
+
// 提交:新会话成为当前会话,然后旧会话离开
|
|
529
|
+
const old = this.#current;
|
|
530
|
+
this.#current = s;
|
|
531
|
+
if (old) await this.#leave(old);
|
|
532
|
+
return s;
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/** 建好一个会话(全部插件加入、Runtime 建好)。任何一步失败,新会话的作用域全部撤销 */
|
|
536
|
+
async #build(opts: OpenOptions): Promise<LiveSession> {
|
|
481
537
|
const host = this.#host;
|
|
482
538
|
const provider = host.service<Provider>("provider@1", host.core);
|
|
483
539
|
if (!provider) throw new ServiceUnavailable("provider@1", "(none): no active plugin provides a model");
|
|
@@ -508,10 +564,6 @@ export class Sessions implements SessionManager {
|
|
|
508
564
|
s.subscribe((n) => {
|
|
509
565
|
if (n.type === "hook-error") host.report(`plugin ${n.info.plugin} failed at ${n.info.point}: ${n.info.error instanceof Error ? n.info.error.message : String(n.info.error)}`);
|
|
510
566
|
});
|
|
511
|
-
// 提交:新会话成为当前会话,然后旧会话离开
|
|
512
|
-
const old = this.#current;
|
|
513
|
-
this.#current = s;
|
|
514
|
-
if (old) await this.#leave(old);
|
|
515
567
|
return s;
|
|
516
568
|
}
|
|
517
569
|
|