sakuracode 0.0.0-stage → 0.1.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 +256 -2
- package/README.zh-CN.md +257 -0
- package/dist/LICENSE +21 -0
- package/dist/THIRD_PARTY_NOTICES.md +13 -0
- package/dist/code/bin/sakuracode.mjs +5 -0
- package/dist/code/src/agent-session.js +41 -0
- package/dist/code/src/ansi.js +220 -0
- package/dist/code/src/cli.js +211 -0
- package/dist/code/src/config.js +183 -0
- package/dist/code/src/exec-mode.js +84 -0
- package/dist/code/src/framework-testing.js +2 -0
- package/dist/code/src/framework.js +3 -0
- package/dist/code/src/idle-compaction.js +38 -0
- package/dist/code/src/images.js +18 -0
- package/dist/code/src/invocation.js +39 -0
- package/dist/code/src/markdown.js +383 -0
- package/dist/code/src/mentions.js +22 -0
- package/dist/code/src/permissions.js +31 -0
- package/dist/code/src/providers.js +56 -0
- package/dist/code/src/reports.js +81 -0
- package/dist/code/src/run-driver.js +76 -0
- package/dist/code/src/session-controller.js +405 -0
- package/dist/code/src/session-store.js +92 -0
- package/dist/code/src/shell.js +36 -0
- package/dist/code/src/slash-commands.js +83 -0
- package/dist/code/src/status-line.js +26 -0
- package/dist/code/src/toml.js +256 -0
- package/dist/code/src/transcript.js +288 -0
- package/dist/code/src/tui/app.js +267 -0
- package/dist/code/src/tui/keys.js +151 -0
- package/dist/code/src/tui/line-editor.js +324 -0
- package/dist/code/src/tui/live-region.js +71 -0
- package/dist/code/src/tui/screen.js +69 -0
- package/dist/code/src/tui/transcript-view.js +102 -0
- package/dist/licenses/codex-Apache-2.0.txt +201 -0
- package/dist/licenses/gitleaks-MIT.txt +21 -0
- package/dist/licenses/pi-mono-MIT.txt +21 -0
- package/dist/packages/agent/src/compose.js +91 -0
- package/dist/packages/agent/src/index.js +161 -0
- package/dist/packages/agent/src/restrict-tools.js +11 -0
- package/dist/packages/agent/src/system-prompt.js +49 -0
- package/dist/packages/agent/src/wake.js +71 -0
- package/dist/packages/env/src/confine.js +40 -0
- package/dist/packages/env/src/connect-ssh.js +242 -0
- package/dist/packages/env/src/index.js +4 -0
- package/dist/packages/env/src/local.js +206 -0
- package/dist/packages/env/src/remote-stream.js +143 -0
- package/dist/packages/env/src/remote-types.js +10 -0
- package/dist/packages/env/src/remote.js +183 -0
- package/dist/packages/evals/src/bfcl.js +71 -0
- package/dist/packages/evals/src/index.js +2 -0
- package/dist/packages/evals/src/png.js +30 -0
- package/dist/packages/evals/src/pool.js +22 -0
- package/dist/packages/evals/src/providers.js +23 -0
- package/dist/packages/kernel/src/channel.js +34 -0
- package/dist/packages/kernel/src/compaction.js +86 -0
- package/dist/packages/kernel/src/constants.js +5 -0
- package/dist/packages/kernel/src/goal.js +65 -0
- package/dist/packages/kernel/src/hooks.js +153 -0
- package/dist/packages/kernel/src/index.js +4 -0
- package/dist/packages/kernel/src/loop.js +556 -0
- package/dist/packages/kernel/src/prompts.js +99 -0
- package/dist/packages/kernel/src/system.js +49 -0
- package/dist/packages/kernel/src/types.js +23 -0
- package/dist/packages/kernel/src/usage.js +16 -0
- package/dist/packages/llm/src/chat/compat.js +16 -0
- package/dist/packages/llm/src/chat/errors.js +61 -0
- package/dist/packages/llm/src/chat/request.js +109 -0
- package/dist/packages/llm/src/chat/retry.js +57 -0
- package/dist/packages/llm/src/chat/stream.js +122 -0
- package/dist/packages/llm/src/index.js +120 -0
- package/dist/packages/plugins/agents/src/index.js +206 -0
- package/dist/packages/plugins/agents/src/view.js +60 -0
- package/dist/packages/plugins/context/src/index.js +67 -0
- package/dist/packages/plugins/limits/src/cost.js +3 -0
- package/dist/packages/plugins/limits/src/index.js +31 -0
- package/dist/packages/plugins/redaction/src/engine.js +110 -0
- package/dist/packages/plugins/redaction/src/index.js +69 -0
- package/dist/packages/plugins/redaction/src/restore.js +44 -0
- package/dist/packages/plugins/redaction/src/rules.gen.js +2059 -0
- package/dist/packages/plugins/resilience/src/index.js +86 -0
- package/dist/packages/plugins/review/src/chain.js +27 -0
- package/dist/packages/plugins/review/src/hard-rules.js +156 -0
- package/dist/packages/plugins/review/src/index.js +93 -0
- package/dist/packages/plugins/review/src/policy.js +65 -0
- package/dist/packages/plugins/review/src/reviewer.js +207 -0
- package/dist/packages/plugins/review/src/shell.js +124 -0
- package/dist/packages/plugins/tools/src/artifacts.js +61 -0
- package/dist/packages/plugins/tools/src/builtin/args.js +46 -0
- package/dist/packages/plugins/tools/src/builtin/bash.js +110 -0
- package/dist/packages/plugins/tools/src/builtin/edit.js +71 -0
- package/dist/packages/plugins/tools/src/builtin/image.js +84 -0
- package/dist/packages/plugins/tools/src/builtin/read.js +89 -0
- package/dist/packages/plugins/tools/src/builtin/write.js +35 -0
- package/dist/packages/plugins/tools/src/edit-match.js +159 -0
- package/dist/packages/plugins/tools/src/fold.js +65 -0
- package/dist/packages/plugins/tools/src/index.js +10 -0
- package/dist/packages/plugins/toolset/src/bm25.js +35 -0
- package/dist/packages/plugins/toolset/src/codemode.js +226 -0
- package/dist/packages/plugins/toolset/src/index.js +3 -0
- package/dist/packages/plugins/toolset/src/mcp.js +173 -0
- package/dist/packages/plugins/toolset/src/search.js +57 -0
- package/dist/packages/plugins/trace/src/index.js +29 -0
- package/dist/packages/plugins/trace/src/modules.js +28 -0
- package/dist/packages/session/src/file-log.js +144 -0
- package/dist/packages/session/src/fork.js +70 -0
- package/dist/packages/session/src/index.js +3 -0
- package/dist/packages/session/src/log-core.js +47 -0
- package/dist/packages/session/src/memory-log.js +7 -0
- package/dist/packages/session/src/projection.js +107 -0
- package/dist/packages/session/src/tree.js +35 -0
- package/dist/packages/testing/src/faux.js +69 -0
- package/dist/packages/testing/src/index.js +2 -0
- package/dist/packages/testing/src/rng.js +17 -0
- package/dist/sdk/index.js +10 -0
- package/dist/sdk/testing.js +2 -0
- package/package.json +54 -4
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
const OUTPUT_LINES = 8;
|
|
2
|
+
/** The assistant message the kernel appends when a request is cancelled before it was answered. */
|
|
3
|
+
export const INTERRUPTED_NOTE = "[The user interrupted this request before it was answered.]";
|
|
4
|
+
/** Added after a prompt that contains @paths (see mentions.ts); the view does not show it. */
|
|
5
|
+
export const MENTION_NOTE = "\n\nThe user pointed at these paths with @; look at them as needed:\n";
|
|
6
|
+
function withoutNote(text) {
|
|
7
|
+
// a canned prompt of a slash command starts with its name in brackets; the view shows only the name
|
|
8
|
+
const command = /^\[(\/[a-z]+)\] /.exec(text);
|
|
9
|
+
if (command)
|
|
10
|
+
return command[1];
|
|
11
|
+
const end = text.indexOf(MENTION_NOTE);
|
|
12
|
+
return end === -1 ? text : text.slice(0, end);
|
|
13
|
+
}
|
|
14
|
+
export function createTranscript() {
|
|
15
|
+
let blocks = [];
|
|
16
|
+
let running = new Map();
|
|
17
|
+
let compactionMuted = false;
|
|
18
|
+
let pending = "";
|
|
19
|
+
let streamedCommitted = 0;
|
|
20
|
+
let firstOfReply = true;
|
|
21
|
+
let working = false;
|
|
22
|
+
const reviews = new Map();
|
|
23
|
+
let reasoning = "";
|
|
24
|
+
const listeners = new Set();
|
|
25
|
+
const notify = (change) => {
|
|
26
|
+
for (const listener of listeners)
|
|
27
|
+
listener(change);
|
|
28
|
+
};
|
|
29
|
+
const commit = (block) => {
|
|
30
|
+
blocks.push(block);
|
|
31
|
+
notify({ type: "commit", block });
|
|
32
|
+
};
|
|
33
|
+
function commitAssistant(text) {
|
|
34
|
+
if (text.trim() === "")
|
|
35
|
+
return;
|
|
36
|
+
commit({ kind: "assistant", text, first: firstOfReply });
|
|
37
|
+
firstOfReply = false;
|
|
38
|
+
}
|
|
39
|
+
function streamText(delta) {
|
|
40
|
+
pending += delta;
|
|
41
|
+
const { done, rest } = splitCommittable(pending);
|
|
42
|
+
for (const chunk of done) {
|
|
43
|
+
streamedCommitted += chunk.length;
|
|
44
|
+
commitAssistant(chunk);
|
|
45
|
+
}
|
|
46
|
+
pending = rest;
|
|
47
|
+
notify({ type: "state" });
|
|
48
|
+
}
|
|
49
|
+
function endAssistant(message) {
|
|
50
|
+
reasoning = "";
|
|
51
|
+
const full = textOf(message.content);
|
|
52
|
+
if (full === INTERRUPTED_NOTE)
|
|
53
|
+
return; // the kernel's marker for a cancelled request; "Run cancelled." already says it
|
|
54
|
+
const alreadyShown = full.startsWith(textOfStreamed()) ? streamedCommitted : 0;
|
|
55
|
+
const remainder = full.slice(alreadyShown);
|
|
56
|
+
pending = "";
|
|
57
|
+
streamedCommitted = 0;
|
|
58
|
+
commitAssistant(remainder);
|
|
59
|
+
firstOfReply = true; // the next message (after tool calls) starts with a mark again
|
|
60
|
+
if (message.stop === "length")
|
|
61
|
+
commit({ kind: "notice", level: "warn", text: "The reply was cut off because the output limit was reached." });
|
|
62
|
+
notify({ type: "state" });
|
|
63
|
+
}
|
|
64
|
+
// the part of the message that was committed from the stream, kept to compare with the final text
|
|
65
|
+
let streamedPrefix = "";
|
|
66
|
+
const textOfStreamed = () => streamedPrefix;
|
|
67
|
+
function toolStart(call) {
|
|
68
|
+
const block = newToolBlock(call);
|
|
69
|
+
const review = reviews.get(call.id);
|
|
70
|
+
if (review) {
|
|
71
|
+
block.review = review;
|
|
72
|
+
reviews.delete(call.id);
|
|
73
|
+
}
|
|
74
|
+
reasoning = "";
|
|
75
|
+
running.set(call.id, block);
|
|
76
|
+
notify({ type: "state" });
|
|
77
|
+
}
|
|
78
|
+
function toolEnd(call, result) {
|
|
79
|
+
const block = running.get(call.id) ?? newToolBlock(call);
|
|
80
|
+
running.delete(call.id);
|
|
81
|
+
const text = textOf(result.content);
|
|
82
|
+
const denied = result.isError === true && text.startsWith("Not allowed:");
|
|
83
|
+
block.status = denied ? "denied" : result.isError ? "error" : "ok";
|
|
84
|
+
if (denied) {
|
|
85
|
+
const note = reviews.get(call.id);
|
|
86
|
+
if (note)
|
|
87
|
+
block.review = note;
|
|
88
|
+
reviews.delete(call.id);
|
|
89
|
+
}
|
|
90
|
+
const exit = /Command exited with code (\d+)\./.exec(text);
|
|
91
|
+
if (exit)
|
|
92
|
+
block.exitCode = Number.parseInt(exit[1], 10);
|
|
93
|
+
const { lines, hidden } = excerpt(text, OUTPUT_LINES);
|
|
94
|
+
block.output = lines;
|
|
95
|
+
block.hidden = hidden;
|
|
96
|
+
commit(block);
|
|
97
|
+
notify({ type: "state" });
|
|
98
|
+
}
|
|
99
|
+
return {
|
|
100
|
+
apply(event) {
|
|
101
|
+
switch (event.type) {
|
|
102
|
+
case "run_start":
|
|
103
|
+
working = true;
|
|
104
|
+
firstOfReply = true;
|
|
105
|
+
notify({ type: "state" });
|
|
106
|
+
break;
|
|
107
|
+
case "run_end":
|
|
108
|
+
working = false;
|
|
109
|
+
reasoning = "";
|
|
110
|
+
pending = "";
|
|
111
|
+
streamedCommitted = 0;
|
|
112
|
+
streamedPrefix = "";
|
|
113
|
+
running = new Map();
|
|
114
|
+
if (event.reason === "cancelled")
|
|
115
|
+
commit({ kind: "notice", level: "warn", text: "Run cancelled." });
|
|
116
|
+
notify({ type: "state" });
|
|
117
|
+
break;
|
|
118
|
+
case "reasoning_update":
|
|
119
|
+
reasoning = (reasoning + event.delta).slice(-400);
|
|
120
|
+
notify({ type: "state" });
|
|
121
|
+
break;
|
|
122
|
+
case "message_update":
|
|
123
|
+
if (event.delta.type === "text") {
|
|
124
|
+
streamedPrefix += event.delta.text;
|
|
125
|
+
streamText(event.delta.text);
|
|
126
|
+
}
|
|
127
|
+
break;
|
|
128
|
+
case "message_reset":
|
|
129
|
+
if (streamedCommitted > 0)
|
|
130
|
+
commit({ kind: "notice", level: "warn", text: "The connection dropped and the reply was started again." });
|
|
131
|
+
pending = "";
|
|
132
|
+
streamedCommitted = 0;
|
|
133
|
+
streamedPrefix = "";
|
|
134
|
+
notify({ type: "state" });
|
|
135
|
+
break;
|
|
136
|
+
case "message_end":
|
|
137
|
+
if (event.message.role === "user") {
|
|
138
|
+
const attached = event.message.content.flatMap((part) => (part.type === "image" ? [`[image: ${part.ref.split("/").pop()}]`] : []));
|
|
139
|
+
const text = [withoutNote(textOf(event.message.content)), ...attached].filter((part) => part.trim() !== "").join("\n");
|
|
140
|
+
if (text.trim() !== "")
|
|
141
|
+
commit({ kind: "user", text });
|
|
142
|
+
firstOfReply = true;
|
|
143
|
+
}
|
|
144
|
+
else if (event.message.role === "assistant") {
|
|
145
|
+
endAssistant(event.message);
|
|
146
|
+
streamedPrefix = "";
|
|
147
|
+
}
|
|
148
|
+
break;
|
|
149
|
+
case "tool_start":
|
|
150
|
+
toolStart(event.call);
|
|
151
|
+
break;
|
|
152
|
+
case "tool_end":
|
|
153
|
+
toolEnd(event.call, event.result);
|
|
154
|
+
break;
|
|
155
|
+
case "compaction":
|
|
156
|
+
if (!compactionMuted)
|
|
157
|
+
commit({ kind: "compaction", tokensBefore: event.tokensBefore });
|
|
158
|
+
break;
|
|
159
|
+
case "paused":
|
|
160
|
+
commit({ kind: "notice", level: "warn", text: `Run paused: ${event.reason}.` });
|
|
161
|
+
break;
|
|
162
|
+
case "goal":
|
|
163
|
+
commit({ kind: "notice", level: "info", text: `Goal is ${event.status}.` });
|
|
164
|
+
break;
|
|
165
|
+
case "plugin":
|
|
166
|
+
applyPluginEvent(event.name, event.data);
|
|
167
|
+
break;
|
|
168
|
+
default:
|
|
169
|
+
break;
|
|
170
|
+
}
|
|
171
|
+
},
|
|
172
|
+
add: commit,
|
|
173
|
+
state: () => ({ running: [...running.values()], pending, working, reasoning }),
|
|
174
|
+
blocks: () => blocks,
|
|
175
|
+
subscribe(listener) {
|
|
176
|
+
listeners.add(listener);
|
|
177
|
+
return () => listeners.delete(listener);
|
|
178
|
+
},
|
|
179
|
+
muteCompaction(muted) {
|
|
180
|
+
compactionMuted = muted;
|
|
181
|
+
},
|
|
182
|
+
reset() {
|
|
183
|
+
blocks = [];
|
|
184
|
+
running = new Map();
|
|
185
|
+
pending = "";
|
|
186
|
+
streamedCommitted = 0;
|
|
187
|
+
streamedPrefix = "";
|
|
188
|
+
reviews.clear();
|
|
189
|
+
notify({ type: "state" });
|
|
190
|
+
},
|
|
191
|
+
};
|
|
192
|
+
function applyPluginEvent(name, data) {
|
|
193
|
+
if (name === "review" && isRecord(data) && data.kind === "review") {
|
|
194
|
+
reviews.set(String(data.callId), { outcome: data.outcome === "deny" ? "deny" : "allow", decidedBy: String(data.decidedBy ?? ""), reason: String(data.reason ?? "") });
|
|
195
|
+
}
|
|
196
|
+
else if (isRecord(data) && typeof data.error === "string" && typeof data.hook === "string") {
|
|
197
|
+
commit({ kind: "notice", level: "warn", text: `Plugin ${name} failed in ${data.hook}: ${data.error}` });
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
const isRecord = (value) => typeof value === "object" && value !== null;
|
|
202
|
+
export function textOf(content) {
|
|
203
|
+
return content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("");
|
|
204
|
+
}
|
|
205
|
+
/** Splits streamed text into finished blocks (ended by a blank line outside a code fence) and the unfinished rest. */
|
|
206
|
+
export function splitCommittable(text) {
|
|
207
|
+
const done = [];
|
|
208
|
+
let start = 0;
|
|
209
|
+
let fence;
|
|
210
|
+
let lineStart = 0;
|
|
211
|
+
while (lineStart < text.length) {
|
|
212
|
+
const newline = text.indexOf("\n", lineStart);
|
|
213
|
+
if (newline === -1)
|
|
214
|
+
break;
|
|
215
|
+
const line = text.slice(lineStart, newline);
|
|
216
|
+
const marker = /^\s{0,3}(`{3,}|~{3,})/.exec(line);
|
|
217
|
+
if (marker) {
|
|
218
|
+
if (fence === undefined)
|
|
219
|
+
fence = marker[1][0];
|
|
220
|
+
else if (marker[1][0] === fence)
|
|
221
|
+
fence = undefined;
|
|
222
|
+
}
|
|
223
|
+
const next = text.indexOf("\n", newline + 1);
|
|
224
|
+
const blankFollows = fence === undefined && next !== -1 && text.slice(newline + 1, next).trim() === "" && line.trim() !== "";
|
|
225
|
+
if (blankFollows) {
|
|
226
|
+
done.push(text.slice(start, next + 1));
|
|
227
|
+
start = next + 1;
|
|
228
|
+
lineStart = next + 1;
|
|
229
|
+
continue;
|
|
230
|
+
}
|
|
231
|
+
lineStart = newline + 1;
|
|
232
|
+
}
|
|
233
|
+
return { done, rest: text.slice(start) };
|
|
234
|
+
}
|
|
235
|
+
export function excerpt(text, limit) {
|
|
236
|
+
const lines = text.replace(/\s+$/, "").split("\n");
|
|
237
|
+
if (lines.length === 1 && lines[0] === "")
|
|
238
|
+
return { lines: [], hidden: 0 };
|
|
239
|
+
if (lines.length <= limit)
|
|
240
|
+
return { lines, hidden: 0 };
|
|
241
|
+
return { lines: lines.slice(0, limit), hidden: lines.length - limit };
|
|
242
|
+
}
|
|
243
|
+
function newToolBlock(call) {
|
|
244
|
+
const { summary, diff } = describeCall(call);
|
|
245
|
+
return { kind: "tool", id: call.id, name: call.name, summary, status: "running", output: [], hidden: 0, ...(diff ? { diff } : {}) };
|
|
246
|
+
}
|
|
247
|
+
function describeCall(call) {
|
|
248
|
+
const args = isRecord(call.args) ? call.args : {};
|
|
249
|
+
const str = (key) => (typeof args[key] === "string" ? args[key] : undefined);
|
|
250
|
+
if (call.name === "bash")
|
|
251
|
+
return { summary: (str("command") ?? "").split("\n")[0] + ((str("command") ?? "").includes("\n") ? " …" : "") };
|
|
252
|
+
if (call.name === "read")
|
|
253
|
+
return { summary: str("path") ?? "" };
|
|
254
|
+
if (call.name === "write")
|
|
255
|
+
return { summary: `${str("path") ?? ""} (${(str("content") ?? "").split("\n").length} lines)` };
|
|
256
|
+
if (call.name === "edit") {
|
|
257
|
+
const edits = Array.isArray(args.edits) ? args.edits.filter(isRecord) : [];
|
|
258
|
+
const diff = edits.slice(0, 3).flatMap((edit) => [...String(edit.oldText ?? "").split("\n").slice(0, 4).map((line) => `- ${line}`), ...String(edit.newText ?? "").split("\n").slice(0, 4).map((line) => `+ ${line}`)]);
|
|
259
|
+
return { summary: `${str("path") ?? ""} (${edits.length} edit${edits.length === 1 ? "" : "s"})`, diff };
|
|
260
|
+
}
|
|
261
|
+
const json = JSON.stringify(call.args ?? {});
|
|
262
|
+
return { summary: json.length > 100 ? `${json.slice(0, 99)}…` : json };
|
|
263
|
+
}
|
|
264
|
+
/** Rebuilds blocks from a session log, so that a resumed session shows what was said before. */
|
|
265
|
+
export function replayLog(transcript, entries) {
|
|
266
|
+
const calls = new Map();
|
|
267
|
+
for (const entry of entries) {
|
|
268
|
+
if (entry.type === "compaction") {
|
|
269
|
+
transcript.apply({ type: "compaction", tokensBefore: entry.tokensBefore });
|
|
270
|
+
continue;
|
|
271
|
+
}
|
|
272
|
+
if (entry.type !== "message")
|
|
273
|
+
continue;
|
|
274
|
+
const message = entry.message;
|
|
275
|
+
if (message.role === "user")
|
|
276
|
+
transcript.apply({ type: "message_end", message });
|
|
277
|
+
else if (message.role === "assistant") {
|
|
278
|
+
transcript.apply({ type: "message_end", message });
|
|
279
|
+
for (const part of message.content)
|
|
280
|
+
if (part.type === "tool_call")
|
|
281
|
+
calls.set(part.id, { id: part.id, name: part.name, args: part.args });
|
|
282
|
+
}
|
|
283
|
+
else if (message.role === "tool" && message.toolCallId) {
|
|
284
|
+
const call = calls.get(message.toolCallId) ?? { id: message.toolCallId, name: message.toolName ?? "tool", args: {} };
|
|
285
|
+
transcript.apply({ type: "tool_end", call, result: { content: message.content, ...(message.isError ? { isError: true } : {}) } });
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
}
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
// The interactive session: connects the terminal (keys in, painted lines out) to the session controller.
|
|
2
|
+
// Everything that decides what a line means lives in the controller; everything about how it looks lives in the views.
|
|
3
|
+
import { pastedImagePath } from "../images.js";
|
|
4
|
+
import { complete } from "../slash-commands.js";
|
|
5
|
+
import { createController } from "../session-controller.js";
|
|
6
|
+
import { formatStatusLine } from "../status-line.js";
|
|
7
|
+
import { createTranscript } from "../transcript.js";
|
|
8
|
+
import { createKeyDecoder } from "./keys.js";
|
|
9
|
+
import { createLineEditor } from "./line-editor.js";
|
|
10
|
+
import { createIdleCompaction } from "../idle-compaction.js";
|
|
11
|
+
import { createLiveRegion } from "./live-region.js";
|
|
12
|
+
import { composeLive } from "./screen.js";
|
|
13
|
+
import { renderBanner, renderBlock, spacingBetween } from "./transcript-view.js";
|
|
14
|
+
const EXIT_CONFIRM_MS = 2000;
|
|
15
|
+
export async function runTui(options) {
|
|
16
|
+
const { stdin, stdout, color } = options;
|
|
17
|
+
const transcript = createTranscript();
|
|
18
|
+
const live = createLiveRegion(stdout, { pinned: true });
|
|
19
|
+
const editor = createLineEditor();
|
|
20
|
+
const decoder = createKeyDecoder();
|
|
21
|
+
const width = () => Math.max(30, stdout.columns ?? 80);
|
|
22
|
+
let picker;
|
|
23
|
+
let popupIndex = 0;
|
|
24
|
+
let popupDismissedFor;
|
|
25
|
+
let hint;
|
|
26
|
+
let hintTimer;
|
|
27
|
+
let frame = 0;
|
|
28
|
+
let workStartedAt = Date.now();
|
|
29
|
+
let lastCtrlC = 0;
|
|
30
|
+
let lastEscape = 0;
|
|
31
|
+
let paintTimer;
|
|
32
|
+
let finished = false;
|
|
33
|
+
let finish;
|
|
34
|
+
const done = new Promise((resolve) => (finish = resolve));
|
|
35
|
+
let lastPrinted;
|
|
36
|
+
const surface = {
|
|
37
|
+
changed: () => schedulePaint(),
|
|
38
|
+
pickSession(sessions) {
|
|
39
|
+
return new Promise((resolve) => {
|
|
40
|
+
picker = { title: "Resume a session", items: sessions, index: 0, resolve };
|
|
41
|
+
schedulePaint();
|
|
42
|
+
});
|
|
43
|
+
},
|
|
44
|
+
clearScreen() {
|
|
45
|
+
stdout.write("\u001b[2J\u001b[3J\u001b[H");
|
|
46
|
+
live.cleared();
|
|
47
|
+
lastPrinted = undefined;
|
|
48
|
+
},
|
|
49
|
+
prefill: (text) => editor.set(text),
|
|
50
|
+
exit: () => finish(0),
|
|
51
|
+
};
|
|
52
|
+
const controller = createController({ ...options.controller, transcript, surface });
|
|
53
|
+
// ----- painting -----
|
|
54
|
+
const popupCommands = () => {
|
|
55
|
+
const value = editor.value();
|
|
56
|
+
return picker || value === popupDismissedFor ? [] : complete(value);
|
|
57
|
+
};
|
|
58
|
+
function paint() {
|
|
59
|
+
paintTimer = undefined;
|
|
60
|
+
if (finished)
|
|
61
|
+
return;
|
|
62
|
+
const state = transcript.state();
|
|
63
|
+
const commands = popupCommands();
|
|
64
|
+
popupIndex = Math.min(popupIndex, Math.max(0, commands.length - 1));
|
|
65
|
+
const view = composeLive({
|
|
66
|
+
width: width(),
|
|
67
|
+
color,
|
|
68
|
+
composer: editor.layout(width() - 3),
|
|
69
|
+
statusLine: formatStatusLine(controller.statusInfo(), width() - 2, color),
|
|
70
|
+
working: controller.driver.working,
|
|
71
|
+
elapsedSeconds: Math.floor((Date.now() - workStartedAt) / 1000),
|
|
72
|
+
frame,
|
|
73
|
+
runningTools: state.running,
|
|
74
|
+
streamingTail: state.pending,
|
|
75
|
+
reasoning: state.reasoning,
|
|
76
|
+
pending: controller.pending(),
|
|
77
|
+
popup: commands.length > 0 ? { commands, index: popupIndex } : undefined,
|
|
78
|
+
picker,
|
|
79
|
+
hint,
|
|
80
|
+
maxComposerRows: Math.max(3, Math.min(8, Math.floor((stdout.rows ?? 24) / 3))),
|
|
81
|
+
});
|
|
82
|
+
live.setLive(view.lines, view.cursor);
|
|
83
|
+
}
|
|
84
|
+
function schedulePaint() {
|
|
85
|
+
paintTimer ??= setTimeout(paint, 16);
|
|
86
|
+
}
|
|
87
|
+
function printBlock(block) {
|
|
88
|
+
const spacing = spacingBetween(lastPrinted, block);
|
|
89
|
+
lastPrinted = block;
|
|
90
|
+
live.print([...Array(spacing).fill(""), ...renderBlock(block, { width: width(), color, cwd: options.controller.cwd })]);
|
|
91
|
+
}
|
|
92
|
+
const { settings } = options.controller;
|
|
93
|
+
const idle = createIdleCompaction({
|
|
94
|
+
enabled: settings.autoCompactIdle,
|
|
95
|
+
idleMs: settings.cacheTtlMinutes * 60_000,
|
|
96
|
+
retryMs: Math.min(30_000, settings.cacheTtlMinutes * 60_000),
|
|
97
|
+
busy: () => controller.driver.working,
|
|
98
|
+
typing: () => editor.value() !== "" || picker !== undefined,
|
|
99
|
+
compact: () => controller.compactIdle(settings.autoCompactMinTokens, settings.cacheTtlMinutes),
|
|
100
|
+
});
|
|
101
|
+
idle.touch();
|
|
102
|
+
controller.driver.onChange(() => {
|
|
103
|
+
if (controller.driver.working)
|
|
104
|
+
workStartedAt = Date.now();
|
|
105
|
+
idle.touch();
|
|
106
|
+
schedulePaint();
|
|
107
|
+
});
|
|
108
|
+
const spinner = setInterval(() => {
|
|
109
|
+
if (!controller.driver.working)
|
|
110
|
+
return;
|
|
111
|
+
frame += 1;
|
|
112
|
+
schedulePaint();
|
|
113
|
+
}, 100);
|
|
114
|
+
function showHint(text) {
|
|
115
|
+
hint = text;
|
|
116
|
+
clearTimeout(hintTimer);
|
|
117
|
+
hintTimer = setTimeout(() => {
|
|
118
|
+
hint = undefined;
|
|
119
|
+
schedulePaint();
|
|
120
|
+
}, EXIT_CONFIRM_MS);
|
|
121
|
+
schedulePaint();
|
|
122
|
+
}
|
|
123
|
+
// ----- keys -----
|
|
124
|
+
function submitLine(mode) {
|
|
125
|
+
let text = editor.value();
|
|
126
|
+
const commands = popupCommands();
|
|
127
|
+
if (commands.length > 0 && text !== `/${commands[popupIndex].name}`)
|
|
128
|
+
text = `/${commands[popupIndex].name}`;
|
|
129
|
+
if (text.trim() === "")
|
|
130
|
+
return;
|
|
131
|
+
const typed = text === editor.value();
|
|
132
|
+
const toSend = typed ? editor.expanded() : text;
|
|
133
|
+
if (mode === "queue" && !controller.driver.working)
|
|
134
|
+
mode = "steer";
|
|
135
|
+
editor.remember(text);
|
|
136
|
+
editor.clear();
|
|
137
|
+
popupIndex = 0;
|
|
138
|
+
void controller.submit(toSend, mode).catch((error) => transcript.add({ kind: "notice", level: "error", text: error.message }));
|
|
139
|
+
}
|
|
140
|
+
function onPickerKey(key) {
|
|
141
|
+
const current = picker;
|
|
142
|
+
if (key.name === "up")
|
|
143
|
+
current.index = Math.max(0, current.index - 1);
|
|
144
|
+
else if (key.name === "down")
|
|
145
|
+
current.index = Math.min(current.items.length - 1, current.index + 1);
|
|
146
|
+
else if (key.name === "enter") {
|
|
147
|
+
picker = undefined;
|
|
148
|
+
current.resolve(current.items[current.index]);
|
|
149
|
+
}
|
|
150
|
+
else if (key.name === "escape" || (key.name === "c" && key.ctrl)) {
|
|
151
|
+
picker = undefined;
|
|
152
|
+
current.resolve(undefined);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
function onKey(key) {
|
|
156
|
+
if (picker)
|
|
157
|
+
return onPickerKey(key);
|
|
158
|
+
const commands = popupCommands();
|
|
159
|
+
if (commands.length > 0 && (key.name === "up" || key.name === "down")) {
|
|
160
|
+
popupIndex = (popupIndex + (key.name === "down" ? 1 : commands.length - 1)) % commands.length;
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
// a dropped or pasted image file becomes an @mention, which attaches it
|
|
164
|
+
const dropped = key.name === "paste" ? pastedImagePath(key.text ?? "", options.controller.cwd) : undefined;
|
|
165
|
+
const action = editor.handle(dropped ? { name: "paste", text: `@${dropped} ` } : key);
|
|
166
|
+
if (action !== "none")
|
|
167
|
+
popupIndex = action === "tab" ? popupIndex : 0;
|
|
168
|
+
if (action === "submit")
|
|
169
|
+
submitLine("steer");
|
|
170
|
+
else if (action === "tab") {
|
|
171
|
+
if (commands.length > 0)
|
|
172
|
+
editor.set(`/${commands[popupIndex].name} `);
|
|
173
|
+
else if (controller.driver.working && editor.value().trim() !== "")
|
|
174
|
+
submitLine("queue");
|
|
175
|
+
}
|
|
176
|
+
else if (action === "escape") {
|
|
177
|
+
if (controller.driver.working)
|
|
178
|
+
controller.cancel();
|
|
179
|
+
else if (commands.length > 0)
|
|
180
|
+
popupDismissedFor = editor.value();
|
|
181
|
+
else if (editor.value() === "") {
|
|
182
|
+
// Esc twice on an empty prompt goes back to before the last message, as in Codex
|
|
183
|
+
if (Date.now() - lastEscape < 800) {
|
|
184
|
+
lastEscape = 0;
|
|
185
|
+
void controller.submit("/undo");
|
|
186
|
+
}
|
|
187
|
+
else {
|
|
188
|
+
lastEscape = Date.now();
|
|
189
|
+
showHint("Press Esc again to edit your previous message.");
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
else if (action === "interrupt") {
|
|
194
|
+
if (controller.driver.working)
|
|
195
|
+
controller.cancel();
|
|
196
|
+
else if (editor.value() !== "")
|
|
197
|
+
editor.clear();
|
|
198
|
+
else if (Date.now() - lastCtrlC < EXIT_CONFIRM_MS)
|
|
199
|
+
finish(0);
|
|
200
|
+
else {
|
|
201
|
+
lastCtrlC = Date.now();
|
|
202
|
+
showHint("Press Ctrl-C again to leave.");
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
else if (action === "eof")
|
|
206
|
+
finish(0);
|
|
207
|
+
}
|
|
208
|
+
// ----- lifecycle -----
|
|
209
|
+
function restoreTerminal() {
|
|
210
|
+
stdout.write("\u001b[?2004l\u001b[?25h");
|
|
211
|
+
stdin.setRawMode?.(false);
|
|
212
|
+
stdin.pause?.();
|
|
213
|
+
}
|
|
214
|
+
try {
|
|
215
|
+
await controller.start(options.start);
|
|
216
|
+
}
|
|
217
|
+
catch (error) {
|
|
218
|
+
clearInterval(spinner);
|
|
219
|
+
stdout.write(`${error.message}\n`);
|
|
220
|
+
return 1;
|
|
221
|
+
}
|
|
222
|
+
transcript.subscribe((change) => (change.type === "commit" ? printBlock(change.block) : schedulePaint()));
|
|
223
|
+
stdin.setEncoding?.("utf8");
|
|
224
|
+
stdin.setRawMode?.(true);
|
|
225
|
+
stdin.resume?.();
|
|
226
|
+
stdout.write("\u001b[?2004h");
|
|
227
|
+
stdin.on("data", (chunk) => {
|
|
228
|
+
if (finished)
|
|
229
|
+
return;
|
|
230
|
+
idle.touch();
|
|
231
|
+
for (const key of decoder.push(chunk.toString()))
|
|
232
|
+
onKey(key);
|
|
233
|
+
schedulePaint();
|
|
234
|
+
});
|
|
235
|
+
stdout.on?.("resize", () => {
|
|
236
|
+
live.forget();
|
|
237
|
+
schedulePaint();
|
|
238
|
+
});
|
|
239
|
+
const info = controller.statusInfo();
|
|
240
|
+
const meta = controller.currentMeta();
|
|
241
|
+
live.print(renderBanner({ version: options.version, model: info.model, provider: info.provider, cwd: info.cwd, permissions: info.permissions, resumed: options.start.resume !== undefined ? meta?.title ?? meta?.id.slice(0, 8) : undefined }, { width: width(), color }));
|
|
242
|
+
if (options.start.resume !== undefined) {
|
|
243
|
+
for (const block of transcript.blocks())
|
|
244
|
+
printBlock(block);
|
|
245
|
+
}
|
|
246
|
+
paint();
|
|
247
|
+
if (options.initialPrompt)
|
|
248
|
+
void controller.submit(options.initialPrompt).catch((error) => transcript.add({ kind: "notice", level: "error", text: error.message }));
|
|
249
|
+
const code = await done;
|
|
250
|
+
finished = true;
|
|
251
|
+
clearInterval(spinner);
|
|
252
|
+
clearTimeout(paintTimer);
|
|
253
|
+
clearTimeout(hintTimer);
|
|
254
|
+
idle.stop();
|
|
255
|
+
if (controller.driver.working) {
|
|
256
|
+
controller.cancel();
|
|
257
|
+
for (let waited = 0; controller.driver.working && waited < 3000; waited += 50)
|
|
258
|
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
259
|
+
}
|
|
260
|
+
live.clear();
|
|
261
|
+
restoreTerminal();
|
|
262
|
+
const saved = controller.currentMeta();
|
|
263
|
+
await controller.close();
|
|
264
|
+
if (saved?.title !== undefined)
|
|
265
|
+
stdout.write(`\nSession saved. Resume it with:\n sakuracode resume ${saved.id}\n`);
|
|
266
|
+
return code;
|
|
267
|
+
}
|