durable-chat 0.0.0-stage → 1.0.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/LICENSE +21 -0
- package/LICENSES/mcp-sdk-MIT.txt +21 -0
- package/LICENSES/pi-MIT.txt +21 -0
- package/LICENSES/typebox-MIT.txt +23 -0
- package/LICENSES/yaml-ISC.txt +13 -0
- package/README.md +779 -2
- package/THIRD_PARTY_NOTICES.md +46 -0
- package/dist/agent-instructions.js +176 -0
- package/dist/auth.js +91 -0
- package/dist/chat.js +121 -0
- package/dist/cli.js +519 -0
- package/dist/codemode.js +23 -0
- package/dist/commands.js +227 -0
- package/dist/config-commands.js +142 -0
- package/dist/config.js +567 -0
- package/dist/context-usage.js +48 -0
- package/dist/existing-session.js +52 -0
- package/dist/faux.js +89 -0
- package/dist/forks.js +33 -0
- package/dist/format.js +144 -0
- package/dist/handoff.js +56 -0
- package/dist/harness.js +446 -0
- package/dist/images.js +64 -0
- package/dist/jobs.js +274 -0
- package/dist/mcp.js +231 -0
- package/dist/models.js +64 -0
- package/dist/reboot.js +70 -0
- package/dist/reminders.js +120 -0
- package/dist/rollback.js +72 -0
- package/dist/state.js +64 -0
- package/dist/tags.js +44 -0
- package/dist/tasks.js +466 -0
- package/dist/tool.js +205 -0
- package/dist/tui/app.js +1695 -0
- package/dist/tui/browser.js +19 -0
- package/dist/tui/dialog.js +39 -0
- package/dist/tui/format.js +223 -0
- package/dist/tui/main.js +83 -0
- package/dist/tui/selection.js +161 -0
- package/dist/tui/state.js +98 -0
- package/dist/tui/transcript.js +151 -0
- package/dist/watch.js +134 -0
- package/dist/workspaces.js +106 -0
- package/package.json +57 -4
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import childProcess from "node:child_process";
|
|
2
|
+
/** Open an explicitly activated web link without passing transcript content through a shell. */
|
|
3
|
+
export async function openBrowser(address, platform = process.platform) {
|
|
4
|
+
if (/[\u0000-\u001f\u007f]/.test(address))
|
|
5
|
+
throw new Error("Invalid web link.");
|
|
6
|
+
const url = new URL(address);
|
|
7
|
+
if (url.protocol !== "https:" && url.protocol !== "http:")
|
|
8
|
+
throw new Error("Only HTTP and HTTPS links can be opened.");
|
|
9
|
+
const command = platform === "darwin" ? "open" : platform === "win32" ? "rundll32.exe" : "xdg-open";
|
|
10
|
+
const args = platform === "win32" ? ["url.dll,FileProtocolHandler", url.href] : [url.href];
|
|
11
|
+
await new Promise((resolve, reject) => {
|
|
12
|
+
childProcess.execFile(command, args, { windowsHide: true }, (error) => {
|
|
13
|
+
if (error)
|
|
14
|
+
reject(error);
|
|
15
|
+
else
|
|
16
|
+
resolve();
|
|
17
|
+
});
|
|
18
|
+
});
|
|
19
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { compositeTuiLine, truncateToWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
|
|
2
|
+
import { bold, dim } from "./format.js";
|
|
3
|
+
/** A content-sized dialog composited over a dashboard frame, without owning input. */
|
|
4
|
+
export function overlayDialog(frame, width, title, body, hint) {
|
|
5
|
+
if (frame.length === 0 || width < 1)
|
|
6
|
+
return [...frame];
|
|
7
|
+
const boxWidth = Math.min(60, width >= 24 ? width - 4 : width);
|
|
8
|
+
if (boxWidth < 5 || frame.length < 4) {
|
|
9
|
+
return frame.map((line, index) => index === 0 ? truncateToWidth(`${title} ${hint}`, width, "", true) : line);
|
|
10
|
+
}
|
|
11
|
+
const inner = boxWidth - 4;
|
|
12
|
+
const footer = wrapTextWithAnsi(dim(hint), inner).slice(0, frame.length - 3);
|
|
13
|
+
const available = frame.length - 3 - footer.length;
|
|
14
|
+
const gaps = available >= 4;
|
|
15
|
+
const details = wrapTextWithAnsi(body, inner);
|
|
16
|
+
const capacity = Math.max(0, available - (gaps ? 2 : 0));
|
|
17
|
+
const shown = details.slice(0, capacity);
|
|
18
|
+
if (details.length > capacity && shown.length > 0) {
|
|
19
|
+
shown[shown.length - 1] = `${truncateToWidth(shown[shown.length - 1], inner - 1, "", true)}…`;
|
|
20
|
+
}
|
|
21
|
+
const content = [
|
|
22
|
+
bold(title),
|
|
23
|
+
...(gaps ? [""] : []),
|
|
24
|
+
...shown,
|
|
25
|
+
...(gaps ? [""] : []),
|
|
26
|
+
...footer,
|
|
27
|
+
];
|
|
28
|
+
const dialog = [
|
|
29
|
+
dim(`┌${"─".repeat(boxWidth - 2)}┐`),
|
|
30
|
+
...content.map((line) => `${dim("│")} ${truncateToWidth(line, inner, "", true)} ${dim("│")}`),
|
|
31
|
+
dim(`└${"─".repeat(boxWidth - 2)}┘`),
|
|
32
|
+
];
|
|
33
|
+
const left = Math.floor((width - boxWidth) / 2);
|
|
34
|
+
const top = Math.floor((frame.length - dialog.length) / 2);
|
|
35
|
+
return frame.map((line, index) => {
|
|
36
|
+
const overlay = dialog[index - top];
|
|
37
|
+
return overlay === undefined ? line : compositeTuiLine(line, overlay, left, boxWidth, width);
|
|
38
|
+
});
|
|
39
|
+
}
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
import { homedir } from "node:os";
|
|
2
|
+
import { isAbsolute, relative, sep } from "node:path";
|
|
3
|
+
import { backgroundAnsi, indexedColor, Markdown, styleText, truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
|
|
4
|
+
import { formatDuration } from "../format.js";
|
|
5
|
+
/** Display paths beneath home with `~`, keeping sibling directories and other roots absolute. */
|
|
6
|
+
export function shortenHome(path, home = homedir()) {
|
|
7
|
+
const suffix = relative(home, path);
|
|
8
|
+
if (suffix === "")
|
|
9
|
+
return "~";
|
|
10
|
+
return suffix === ".." || suffix.startsWith(`..${sep}`) || isAbsolute(suffix) ? path : `~${sep}${suffix}`;
|
|
11
|
+
}
|
|
12
|
+
const MODE = "256color";
|
|
13
|
+
export const ACCENT = 39;
|
|
14
|
+
export const GREEN = 76;
|
|
15
|
+
export const YELLOW = 214;
|
|
16
|
+
export const RED = 203;
|
|
17
|
+
export const MUTED = 245;
|
|
18
|
+
export const BORDER = 240;
|
|
19
|
+
export const TEXT = 250;
|
|
20
|
+
export const COMPOSER_BG = 235;
|
|
21
|
+
export const TRANSCRIPT_BG = 16;
|
|
22
|
+
export function fg(text, color, attributes = {}) {
|
|
23
|
+
return styleText(text, { fg: indexedColor(color), ...attributes }, MODE);
|
|
24
|
+
}
|
|
25
|
+
/** Fill the entire row and keep its background through nested Markdown/Input resets. */
|
|
26
|
+
export function backgroundLine(text, width, color) {
|
|
27
|
+
const background = backgroundAnsi(indexedColor(color), MODE);
|
|
28
|
+
const line = truncateToWidth(text, width, "", true).replace(/\x1b\[(?:0|49)?m/g, (reset) => reset + background);
|
|
29
|
+
return styleText(line, { bg: indexedColor(color) }, MODE);
|
|
30
|
+
}
|
|
31
|
+
export function dim(text) {
|
|
32
|
+
return fg(text, MUTED, { dim: true });
|
|
33
|
+
}
|
|
34
|
+
export function bold(text) {
|
|
35
|
+
return fg(text, TEXT, { bold: true });
|
|
36
|
+
}
|
|
37
|
+
export function statusColor(status) {
|
|
38
|
+
if (status.includes("failed") || status.includes("faulted") || status.includes("blocked"))
|
|
39
|
+
return RED;
|
|
40
|
+
if (status.includes("aborted"))
|
|
41
|
+
return YELLOW;
|
|
42
|
+
if (status.includes("completed") || status.includes("answered") || status.includes("handed off") || status.includes("done") || status.includes("handoff"))
|
|
43
|
+
return GREEN;
|
|
44
|
+
if (status.includes("running"))
|
|
45
|
+
return ACCENT;
|
|
46
|
+
if (status.includes("pending") || status.includes("waiting") || status.includes("sleeping"))
|
|
47
|
+
return YELLOW;
|
|
48
|
+
return MUTED;
|
|
49
|
+
}
|
|
50
|
+
export function statusText(status) {
|
|
51
|
+
return fg(status, statusColor(status));
|
|
52
|
+
}
|
|
53
|
+
function blockText(content) {
|
|
54
|
+
if (typeof content === "string")
|
|
55
|
+
return content;
|
|
56
|
+
if (!Array.isArray(content))
|
|
57
|
+
return "";
|
|
58
|
+
return content.flatMap((block) => {
|
|
59
|
+
if (typeof block !== "object" || block === null)
|
|
60
|
+
return [];
|
|
61
|
+
const value = block;
|
|
62
|
+
if (value.type === "text" && typeof value.text === "string")
|
|
63
|
+
return [value.text];
|
|
64
|
+
if (value.type === "toolCall") {
|
|
65
|
+
const name = typeof value.name === "string" ? value.name : "tool";
|
|
66
|
+
const args = value.arguments;
|
|
67
|
+
const compact = typeof args === "object" && args !== null ? JSON.stringify(args) : String(args ?? "");
|
|
68
|
+
return [`→ ${name} ${compact.length > 120 ? `${compact.slice(0, 119)}…` : compact}`];
|
|
69
|
+
}
|
|
70
|
+
if (value.type === "image")
|
|
71
|
+
return ["[image]"];
|
|
72
|
+
return [];
|
|
73
|
+
}).join("\n");
|
|
74
|
+
}
|
|
75
|
+
const TRANSCRIPT_MARKDOWN_THEME = {
|
|
76
|
+
heading: (text) => fg(text, TEXT),
|
|
77
|
+
link: (text) => fg(text, ACCENT),
|
|
78
|
+
linkUrl: dim,
|
|
79
|
+
code: (text) => fg(text, ACCENT),
|
|
80
|
+
codeBlock: (text) => fg(text, TEXT),
|
|
81
|
+
codeBlockBorder: dim,
|
|
82
|
+
quote: dim,
|
|
83
|
+
quoteBorder: dim,
|
|
84
|
+
hr: dim,
|
|
85
|
+
listBullet: dim,
|
|
86
|
+
bold: (text) => styleText(text, { bold: true }, MODE),
|
|
87
|
+
italic: (text) => styleText(text, { italic: true }, MODE),
|
|
88
|
+
strikethrough: (text) => styleText(text, { strikethrough: true }, MODE),
|
|
89
|
+
underline: (text) => styleText(text, { underline: true }, MODE),
|
|
90
|
+
};
|
|
91
|
+
function prefixLines(text, prefix, width, color) {
|
|
92
|
+
const inner = Math.max(1, width - visibleWidth(prefix));
|
|
93
|
+
const markdown = new Markdown(text, 0, 0, TRANSCRIPT_MARKDOWN_THEME, { color: (value) => fg(value, color) }, { renderLatex: false });
|
|
94
|
+
const rendered = markdown.render(inner);
|
|
95
|
+
const lines = rendered.length === 0 ? [""] : rendered;
|
|
96
|
+
const pad = " ".repeat(visibleWidth(prefix));
|
|
97
|
+
return lines.map((line, index) => fg(index === 0 ? prefix : pad, color) + line);
|
|
98
|
+
}
|
|
99
|
+
function rule(label, width) {
|
|
100
|
+
const text = `── ${label} `;
|
|
101
|
+
return fg(truncateToWidth(text, width, ""), BORDER);
|
|
102
|
+
}
|
|
103
|
+
function ruleWithText(label, body, width, color = MUTED) {
|
|
104
|
+
const lines = [rule(label, width)];
|
|
105
|
+
if (body.trim().length > 0)
|
|
106
|
+
lines.push(...prefixLines(body.trimEnd(), " ", width, color));
|
|
107
|
+
return lines;
|
|
108
|
+
}
|
|
109
|
+
function toolResultLines(message, width, expanded) {
|
|
110
|
+
const name = message.toolName ?? "tool";
|
|
111
|
+
const mark = message.isError === true ? "✗" : "✓";
|
|
112
|
+
const ms = message.durationMs === undefined ? "" : ` · ${formatDuration(message.durationMs)}`;
|
|
113
|
+
const body = blockText(message.content).replace(/\s+/g, " ").trim();
|
|
114
|
+
const summary = body.length > 140 ? `${body.slice(0, 139)}…` : body;
|
|
115
|
+
const head = fg(` ↳ ${mark} ${name}${ms}`, message.isError === true ? RED : GREEN);
|
|
116
|
+
const lines = [truncateToWidth(`${head}${summary.length === 0 ? "" : dim(` ${summary}`)}`, width, "")];
|
|
117
|
+
if (expanded) {
|
|
118
|
+
const indent = " ".repeat(Math.min(10, width - 1));
|
|
119
|
+
const full = blockText(message.content).trimEnd();
|
|
120
|
+
const shown = full.split("\n").slice(0, 12);
|
|
121
|
+
for (const line of shown) {
|
|
122
|
+
for (const wrapped of wrapTextWithAnsi(line, width - indent.length)) {
|
|
123
|
+
lines.push(dim(`${indent}${wrapped}`));
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
if (full.split("\n").length > shown.length)
|
|
127
|
+
lines.push(dim(`${indent}…`));
|
|
128
|
+
}
|
|
129
|
+
return lines;
|
|
130
|
+
}
|
|
131
|
+
/** One immutable transcript entry to display lines. */
|
|
132
|
+
export function formatEntry(entry, options) {
|
|
133
|
+
const width = Math.max(8, options.width);
|
|
134
|
+
const messages = (entry.model ?? []);
|
|
135
|
+
if (entry.kind === "pi.user") {
|
|
136
|
+
return messages.flatMap((message) => prefixLines(blockText(message.content), " you ", width, ACCENT));
|
|
137
|
+
}
|
|
138
|
+
if (entry.kind === "pi.assistant") {
|
|
139
|
+
const lines = [];
|
|
140
|
+
for (const message of messages) {
|
|
141
|
+
const text = blockText(message.content).trimEnd();
|
|
142
|
+
if (text.length > 0)
|
|
143
|
+
lines.push(...prefixLines(text, " ai ", width, GREEN));
|
|
144
|
+
if (message.stopReason === "aborted" && text.length === 0)
|
|
145
|
+
lines.push(fg(" [aborted attempt]", MUTED, { dim: true }));
|
|
146
|
+
}
|
|
147
|
+
return lines;
|
|
148
|
+
}
|
|
149
|
+
if (entry.kind === "pi.tool-result") {
|
|
150
|
+
return messages.flatMap((message) => toolResultLines(message, width, options.toolsExpanded));
|
|
151
|
+
}
|
|
152
|
+
if (entry.kind === "pi.reset") {
|
|
153
|
+
const handoff = messages.map((message) => blockText(message.content)).join("\n").trim();
|
|
154
|
+
return ruleWithText("reset", handoff, width, MUTED);
|
|
155
|
+
}
|
|
156
|
+
if (entry.kind === "pi.compaction") {
|
|
157
|
+
const summary = messages.map((message) => blockText(message.content)).join("\n").trim();
|
|
158
|
+
return ruleWithText("compacted context", options.toolsExpanded ? summary : "summary retained in history", width, MUTED);
|
|
159
|
+
}
|
|
160
|
+
if (entry.kind === "pi.system") {
|
|
161
|
+
return options.showSystem === true ? [dim(truncateToWidth("── system prompt updated", width, ""))] : [];
|
|
162
|
+
}
|
|
163
|
+
if (entry.kind === "app.job-handoff") {
|
|
164
|
+
const data = entry.data;
|
|
165
|
+
const body = messages.map((message) => blockText(message.content)).join(" ").trim();
|
|
166
|
+
return ruleWithText(`job #${data?.fromJob ?? "?"} handoff → main`, body, width, MUTED);
|
|
167
|
+
}
|
|
168
|
+
if (entry.kind === "app.job-notice") {
|
|
169
|
+
const data = entry.data;
|
|
170
|
+
const body = messages.map((message) => blockText(message.content)).join(" ").replace(/^\[host\]\s*/, "").trim();
|
|
171
|
+
const lines = ruleWithText(`host · job #${data?.taskId ?? "?"} ${data?.phase ?? "notice"}`, body, width, MUTED);
|
|
172
|
+
if (body.length > 0)
|
|
173
|
+
lines.splice(1, 0, "");
|
|
174
|
+
return lines;
|
|
175
|
+
}
|
|
176
|
+
if (entry.kind.startsWith("app."))
|
|
177
|
+
return [];
|
|
178
|
+
return options.showSystem === true ? [dim(truncateToWidth(`── ${entry.kind}`, width, ""))] : [];
|
|
179
|
+
}
|
|
180
|
+
/** Streaming partial answer and tool slots below the committed transcript. */
|
|
181
|
+
export function formatLive(live, width) {
|
|
182
|
+
if (live === undefined)
|
|
183
|
+
return [];
|
|
184
|
+
const lines = [];
|
|
185
|
+
const text = blockText(live.generation?.message?.content).trimEnd();
|
|
186
|
+
if (text.length > 0)
|
|
187
|
+
lines.push(...prefixLines(text, " ai ", width, GREEN));
|
|
188
|
+
// Completed slots already have committed tool-result entries; only show current work.
|
|
189
|
+
const active = (live.tools ?? []).filter((slot) => slot.status !== "done").slice(0, 8);
|
|
190
|
+
for (const slot of active) {
|
|
191
|
+
const status = slot.status ?? "pending";
|
|
192
|
+
lines.push(fg(` ${status === "running" ? "▸" : "·"} ${slot.name ?? "tool"} ${status}`, YELLOW));
|
|
193
|
+
}
|
|
194
|
+
if (live.runFailure !== undefined) {
|
|
195
|
+
const detail = live.runFailure.detail === undefined ? "" : `: ${live.runFailure.detail}`;
|
|
196
|
+
lines.push(fg(` run failed: ${live.runFailure.reason ?? "unknown"}${detail}`, RED));
|
|
197
|
+
}
|
|
198
|
+
return lines;
|
|
199
|
+
}
|
|
200
|
+
export function usageTotals(usage) {
|
|
201
|
+
let tokens = 0;
|
|
202
|
+
let cost = 0;
|
|
203
|
+
if (usage === undefined)
|
|
204
|
+
return { tokens, cost };
|
|
205
|
+
for (const bucket of [...Object.values(usage.models), ...Object.values(usage.tools)]) {
|
|
206
|
+
const value = bucket;
|
|
207
|
+
if (typeof value.totalTokens === "number")
|
|
208
|
+
tokens += value.totalTokens;
|
|
209
|
+
const costs = value.cost;
|
|
210
|
+
if (typeof costs === "object" && costs !== null && !Array.isArray(costs)) {
|
|
211
|
+
const total = costs.total;
|
|
212
|
+
if (typeof total === "number")
|
|
213
|
+
cost += total;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
return { tokens, cost };
|
|
217
|
+
}
|
|
218
|
+
export function padLines(lines, height, width) {
|
|
219
|
+
const out = lines.slice(0, height).map((line) => truncateToWidth(line, width, "", true));
|
|
220
|
+
while (out.length < height)
|
|
221
|
+
out.push(" ".repeat(width));
|
|
222
|
+
return out;
|
|
223
|
+
}
|
package/dist/tui/main.js
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { ProcessTerminal, TuiAltScreen } from "@earendil-works/pi-tui";
|
|
2
|
+
import { resolveConfig } from "../config.js";
|
|
3
|
+
import { runConfigCommand } from "../config-commands.js";
|
|
4
|
+
import { Dashboard } from "./app.js";
|
|
5
|
+
import { shortenHome } from "./format.js";
|
|
6
|
+
import { openBrowser } from "./browser.js";
|
|
7
|
+
/** Stop all UI observers before returning a lifecycle request. The caller owns the runtime. */
|
|
8
|
+
export async function runTui(runtime, notice) {
|
|
9
|
+
if (process.stdin.isTTY !== true || process.stdout.isTTY !== true) {
|
|
10
|
+
throw new Error("The TUI needs an interactive terminal; use `durable-chat chat` or `ask`.");
|
|
11
|
+
}
|
|
12
|
+
const terminal = new ProcessTerminal();
|
|
13
|
+
const title = `durable-chat — ${shortenHome(runtime.cwd)}`;
|
|
14
|
+
const ui = new TuiAltScreen(terminal, false, undefined, {
|
|
15
|
+
openUrl: (url) => {
|
|
16
|
+
void openBrowser(url).catch((error) => ui.flash(`Could not open link: ${error instanceof Error ? error.message : String(error)}`));
|
|
17
|
+
},
|
|
18
|
+
});
|
|
19
|
+
const quit = Promise.withResolvers();
|
|
20
|
+
const app = new Dashboard({
|
|
21
|
+
runtime,
|
|
22
|
+
openUrl: (url) => {
|
|
23
|
+
void openBrowser(url).catch((error) => ui.flash(`Could not open link: ${error instanceof Error ? error.message : String(error)}`));
|
|
24
|
+
},
|
|
25
|
+
rows: () => terminal.rows || process.stdout.rows || 24,
|
|
26
|
+
requestRender: () => ui.requestRender(),
|
|
27
|
+
onQuit: () => quit.resolve("quit"),
|
|
28
|
+
onReboot: () => quit.resolve("reboot"),
|
|
29
|
+
onRollback: (source) => quit.resolve({ rollbackFrom: source }),
|
|
30
|
+
onModel: (id) => quit.resolve({ modelId: id }),
|
|
31
|
+
onProvider: (name) => quit.resolve({ provider: name }),
|
|
32
|
+
...(notice === undefined ? {} : { notice }),
|
|
33
|
+
onEditConfig: async () => {
|
|
34
|
+
ui.stop();
|
|
35
|
+
const previousExit = process.exitCode;
|
|
36
|
+
try {
|
|
37
|
+
const overrides = runtime.config.explicitConfigPath === undefined ? {} : { configPath: runtime.config.explicitConfigPath };
|
|
38
|
+
runConfigCommand(["edit"], overrides);
|
|
39
|
+
try {
|
|
40
|
+
resolveConfig(overrides);
|
|
41
|
+
return "config edited; restart durable-chat to apply it";
|
|
42
|
+
}
|
|
43
|
+
catch (error) {
|
|
44
|
+
return `config invalid: ${error instanceof Error ? error.message : String(error)}`;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
catch (error) {
|
|
48
|
+
return `config edit failed: ${error instanceof Error ? error.message : String(error)}`;
|
|
49
|
+
}
|
|
50
|
+
finally {
|
|
51
|
+
process.exitCode = previousExit;
|
|
52
|
+
ui.start();
|
|
53
|
+
terminal.setTitle(title);
|
|
54
|
+
ui.setLayoutRoot(app);
|
|
55
|
+
ui.setFocus(app);
|
|
56
|
+
ui.requestRender();
|
|
57
|
+
}
|
|
58
|
+
},
|
|
59
|
+
});
|
|
60
|
+
// Let the terminal retain both titles; querying the previous title is unnecessary.
|
|
61
|
+
terminal.write("\x1b[22;0t");
|
|
62
|
+
try {
|
|
63
|
+
await app.start();
|
|
64
|
+
ui.setLayoutRoot(app);
|
|
65
|
+
ui.setFocus(app);
|
|
66
|
+
ui.start();
|
|
67
|
+
terminal.setTitle(title);
|
|
68
|
+
return await quit.promise;
|
|
69
|
+
}
|
|
70
|
+
finally {
|
|
71
|
+
try {
|
|
72
|
+
try {
|
|
73
|
+
ui.stop();
|
|
74
|
+
}
|
|
75
|
+
finally {
|
|
76
|
+
await app.stop();
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
finally {
|
|
80
|
+
terminal.write("\x1b[23;0t");
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { getOsc8LinkAtColumn, sliceByColumn, stripTerminalSequences, visibleWidth } from "@earendil-works/pi-tui";
|
|
2
|
+
const graphemes = new Intl.Segmenter(undefined, { granularity: "grapheme" });
|
|
3
|
+
const words = new Intl.Segmenter(undefined, { granularity: "word" });
|
|
4
|
+
const wordJoiners = new Set(["/", "-", "+", "\\", "~", "_", "."]);
|
|
5
|
+
/** Selection uses transcript-local cells, never the composited dashboard rows. */
|
|
6
|
+
export class TranscriptSelection {
|
|
7
|
+
frame;
|
|
8
|
+
anchor;
|
|
9
|
+
focus;
|
|
10
|
+
pressed = false;
|
|
11
|
+
dragged = false;
|
|
12
|
+
version = 0;
|
|
13
|
+
copy;
|
|
14
|
+
notify;
|
|
15
|
+
render;
|
|
16
|
+
open;
|
|
17
|
+
constructor(copy, notify, render, open) {
|
|
18
|
+
this.copy = copy;
|
|
19
|
+
this.notify = notify;
|
|
20
|
+
this.render = render;
|
|
21
|
+
this.open = open;
|
|
22
|
+
}
|
|
23
|
+
reset() {
|
|
24
|
+
this.anchor = this.focus = undefined;
|
|
25
|
+
this.pressed = this.dragged = false;
|
|
26
|
+
this.version++;
|
|
27
|
+
}
|
|
28
|
+
update(frame) {
|
|
29
|
+
const old = this.frame;
|
|
30
|
+
if (!old || !frame || old.source !== frame.source || old.x !== frame.x || old.y !== frame.y || old.width !== frame.width
|
|
31
|
+
|| old.lines.length !== frame.lines.length || old.lines.some((line, index) => line !== frame.lines[index]))
|
|
32
|
+
this.reset();
|
|
33
|
+
this.frame = frame;
|
|
34
|
+
}
|
|
35
|
+
point(event) {
|
|
36
|
+
const frame = this.frame;
|
|
37
|
+
return { row: Math.max(0, Math.min(frame.lines.length - 1, event.y - frame.y)), col: Math.max(0, Math.min(frame.width - 1, event.x - frame.x)) };
|
|
38
|
+
}
|
|
39
|
+
cell(row, col) {
|
|
40
|
+
let start = 0;
|
|
41
|
+
for (const { segment } of graphemes.segment(stripTerminalSequences(this.frame.lines[row]))) {
|
|
42
|
+
const end = start + visibleWidth(segment);
|
|
43
|
+
if (end > col)
|
|
44
|
+
return { start, end };
|
|
45
|
+
start = end;
|
|
46
|
+
}
|
|
47
|
+
return { start: col, end: col + 1 };
|
|
48
|
+
}
|
|
49
|
+
columns(row) {
|
|
50
|
+
if (!this.anchor || !this.focus)
|
|
51
|
+
return;
|
|
52
|
+
const before = this.anchor.row < this.focus.row || (this.anchor.row === this.focus.row && this.anchor.col <= this.focus.col);
|
|
53
|
+
const start = before ? this.anchor : this.focus;
|
|
54
|
+
const end = before ? this.focus : this.anchor;
|
|
55
|
+
if (row < start.row || row > end.row)
|
|
56
|
+
return;
|
|
57
|
+
return { start: row === start.row ? this.cell(row, start.col).start : 0,
|
|
58
|
+
end: row === end.row ? this.cell(row, end.col).end : this.frame.width };
|
|
59
|
+
}
|
|
60
|
+
lines() {
|
|
61
|
+
return this.frame?.lines.map((line, row) => {
|
|
62
|
+
const columns = this.columns(row);
|
|
63
|
+
if (!columns || (!this.dragged && this.pressed))
|
|
64
|
+
return line;
|
|
65
|
+
const { start, end } = columns;
|
|
66
|
+
const selected = sliceByColumn(line, start, end - start);
|
|
67
|
+
// Nested Markdown resets must not end the selection highlight early.
|
|
68
|
+
const highlighted = `\x1b[7m${selected.replace(/\x1b\[[0-9;:]*m/g, "$&\x1b[7m")}\x1b[27m`;
|
|
69
|
+
return sliceByColumn(line, 0, start) + highlighted + sliceByColumn(line, end, this.frame.width - end) + "\x1b]8;;\x1b\\\x1b[0m";
|
|
70
|
+
}) ?? [];
|
|
71
|
+
}
|
|
72
|
+
async copySelection() {
|
|
73
|
+
const text = this.frame.lines.flatMap((line, row) => {
|
|
74
|
+
const columns = this.columns(row);
|
|
75
|
+
return columns ? [stripTerminalSequences(sliceByColumn(line, columns.start, columns.end - columns.start)).trimEnd()] : [];
|
|
76
|
+
}).join("\n");
|
|
77
|
+
if (!text)
|
|
78
|
+
return;
|
|
79
|
+
const version = this.version;
|
|
80
|
+
let result;
|
|
81
|
+
try {
|
|
82
|
+
result = await this.copy(text);
|
|
83
|
+
}
|
|
84
|
+
catch (error) {
|
|
85
|
+
result = error instanceof Error ? error.message : String(error);
|
|
86
|
+
}
|
|
87
|
+
if (version !== this.version)
|
|
88
|
+
return; // An old clipboard completion must not erase a newer gesture.
|
|
89
|
+
if (result === true)
|
|
90
|
+
this.reset();
|
|
91
|
+
this.notify(result);
|
|
92
|
+
this.render();
|
|
93
|
+
}
|
|
94
|
+
handle(event) {
|
|
95
|
+
const frame = this.frame;
|
|
96
|
+
if (!frame)
|
|
97
|
+
return;
|
|
98
|
+
const inside = event.x >= frame.x && event.x < frame.x + frame.width && event.y >= frame.y && event.y < frame.y + frame.lines.length;
|
|
99
|
+
if (event.type === "press") {
|
|
100
|
+
this.reset();
|
|
101
|
+
if (event.button !== "left" || !inside)
|
|
102
|
+
return;
|
|
103
|
+
this.anchor = this.focus = this.point(event);
|
|
104
|
+
this.pressed = true;
|
|
105
|
+
}
|
|
106
|
+
else if (event.type === "drag" && this.pressed) {
|
|
107
|
+
this.focus = this.point(event);
|
|
108
|
+
this.dragged = true;
|
|
109
|
+
}
|
|
110
|
+
else if (event.type === "release" && this.pressed) {
|
|
111
|
+
this.focus = this.point(event);
|
|
112
|
+
this.dragged ||= this.anchor.row !== this.focus.row || this.anchor.col !== this.focus.col;
|
|
113
|
+
this.pressed = false;
|
|
114
|
+
if (this.dragged)
|
|
115
|
+
void this.copySelection();
|
|
116
|
+
else
|
|
117
|
+
this.anchor = this.focus = undefined;
|
|
118
|
+
}
|
|
119
|
+
else if (event.type === "click" && inside && event.button === "left") {
|
|
120
|
+
const point = this.point(event);
|
|
121
|
+
const line = frame.lines[point.row];
|
|
122
|
+
if ((event.clickCount ?? 1) === 1) {
|
|
123
|
+
const url = getOsc8LinkAtColumn(line, point.col);
|
|
124
|
+
if (url) {
|
|
125
|
+
try {
|
|
126
|
+
this.open(url);
|
|
127
|
+
}
|
|
128
|
+
catch { /* Link activation is best-effort, as in the toolkit. */ }
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
else {
|
|
132
|
+
this.version++;
|
|
133
|
+
let start = 0;
|
|
134
|
+
let end = frame.width;
|
|
135
|
+
if (event.clickCount === 2) {
|
|
136
|
+
// Keep terminal-style word boundaries, including path/identifier joiners.
|
|
137
|
+
let column = 0;
|
|
138
|
+
const segments = [...words.segment(stripTerminalSequences(line))].map((segment) => {
|
|
139
|
+
const start = column;
|
|
140
|
+
column += visibleWidth(segment.segment);
|
|
141
|
+
const joiner = wordJoiners.has(segment.segment);
|
|
142
|
+
return { start, end: column, joiner, selectable: segment.isWordLike || joiner };
|
|
143
|
+
});
|
|
144
|
+
const index = segments.findIndex((segment) => point.col >= segment.start && point.col < segment.end);
|
|
145
|
+
if (index >= 0) {
|
|
146
|
+
const joins = (left, right) => left.selectable && right.selectable && (left.joiner || right.joiner);
|
|
147
|
+
start = segments[index].start;
|
|
148
|
+
end = segments[index].end;
|
|
149
|
+
for (let i = index; i > 0 && joins(segments[i - 1], segments[i]); i--)
|
|
150
|
+
start = segments[i - 1].start;
|
|
151
|
+
for (let i = index; i + 1 < segments.length && joins(segments[i], segments[i + 1]); i++)
|
|
152
|
+
end = segments[i + 1].end;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
this.anchor = { row: point.row, col: start };
|
|
156
|
+
this.focus = { row: point.row, col: Math.max(start, end - 1) };
|
|
157
|
+
void this.copySelection();
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { jobView } from "../format.js";
|
|
2
|
+
import { JOB_KIND } from "../tasks.js";
|
|
3
|
+
/** Merge durable job records with the live task graph, then sort live first and finished newest first. */
|
|
4
|
+
export function buildJobRows(records, nodes) {
|
|
5
|
+
const byId = new Map();
|
|
6
|
+
for (const record of records) {
|
|
7
|
+
const view = jobView(record);
|
|
8
|
+
byId.set(view.id, {
|
|
9
|
+
id: view.id,
|
|
10
|
+
brief: view.brief,
|
|
11
|
+
status: view.status,
|
|
12
|
+
live: false,
|
|
13
|
+
tags: view.tags,
|
|
14
|
+
...(view.fork === undefined ? {} : { fork: view.fork }),
|
|
15
|
+
...(view.workspace === undefined ? {} : { workspace: view.workspace }),
|
|
16
|
+
...(view.conversationId === undefined ? {} : { conversationId: view.conversationId }),
|
|
17
|
+
...(view.answer === undefined ? {} : { answer: view.answer }),
|
|
18
|
+
...(view.startedAt === undefined ? {} : { startedAt: view.startedAt }),
|
|
19
|
+
...(view.endedAt === undefined ? {} : { endedAt: view.endedAt }),
|
|
20
|
+
...(view.reason === undefined ? {} : { error: view.reason }),
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
for (const node of nodes) {
|
|
24
|
+
if (node.kind !== JOB_KIND)
|
|
25
|
+
continue;
|
|
26
|
+
const id = Number(node.id);
|
|
27
|
+
const existing = byId.get(id);
|
|
28
|
+
byId.set(id, {
|
|
29
|
+
id,
|
|
30
|
+
brief: existing?.brief ?? "(starting)",
|
|
31
|
+
status: node.blocked === undefined ? node.state.status : `blocked: ${node.blocked}`,
|
|
32
|
+
live: true,
|
|
33
|
+
tags: existing?.tags ?? [],
|
|
34
|
+
...(existing?.fork === undefined ? {} : { fork: existing.fork }),
|
|
35
|
+
...(existing?.workspace === undefined ? {} : { workspace: existing.workspace }),
|
|
36
|
+
...(node.blocked === undefined ? {} : { blocked: node.blocked }),
|
|
37
|
+
...(existing?.conversationId === undefined ? {} : { conversationId: existing.conversationId }),
|
|
38
|
+
...(existing?.startedAt === undefined ? {} : { startedAt: existing.startedAt }),
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
const rows = [...byId.values()];
|
|
42
|
+
const live = rows.filter((row) => row.live).sort((a, b) => a.id - b.id);
|
|
43
|
+
const finished = rows.filter((row) => !row.live).sort((a, b) => b.id - a.id);
|
|
44
|
+
return [...live, ...finished];
|
|
45
|
+
}
|
|
46
|
+
export function filterJobs(rows, query, showFinished) {
|
|
47
|
+
const needle = query.trim().toLowerCase();
|
|
48
|
+
return rows.filter((row) => {
|
|
49
|
+
if (!showFinished && !row.live)
|
|
50
|
+
return false;
|
|
51
|
+
if (needle.length === 0)
|
|
52
|
+
return true;
|
|
53
|
+
return String(row.id).includes(needle)
|
|
54
|
+
|| row.brief.toLowerCase().includes(needle)
|
|
55
|
+
|| row.status.toLowerCase().includes(needle)
|
|
56
|
+
|| (row.tags?.some((tag) => tag.includes(needle)) ?? false)
|
|
57
|
+
|| (row.fork !== undefined && `fork ${row.fork.jobId === undefined ? "main" : `#${row.fork.jobId}`}`.includes(needle))
|
|
58
|
+
|| (row.workspace?.cwd.toLowerCase().includes(needle) ?? false)
|
|
59
|
+
|| (row.workspace?.kind === "worktree" && row.workspace.branch.toLowerCase().includes(needle));
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
/** Follow new arrivals on main, but preserve manual browsing between arrivals and pinned-job selection. */
|
|
63
|
+
export function reconcileJobSelection(rows, previousRows, target, selectedId) {
|
|
64
|
+
const newest = rows.reduce((id, row) => id === undefined || row.id > id ? row.id : id, undefined);
|
|
65
|
+
const previousNewest = previousRows.reduce((id, row) => id === undefined || row.id > id ? row.id : id, undefined);
|
|
66
|
+
if (target.kind === "main" && newest !== undefined && (previousNewest === undefined || newest > previousNewest))
|
|
67
|
+
return newest;
|
|
68
|
+
if (rows.some((row) => row.id === selectedId))
|
|
69
|
+
return selectedId;
|
|
70
|
+
return target.kind === "main" ? newest : rows[0]?.id;
|
|
71
|
+
}
|
|
72
|
+
export function moveSelection(rows, selectedId, delta) {
|
|
73
|
+
if (rows.length === 0)
|
|
74
|
+
return undefined;
|
|
75
|
+
const current = rows.findIndex((row) => row.id === selectedId);
|
|
76
|
+
const next = current === -1 ? 0 : Math.max(0, Math.min(rows.length - 1, current + delta));
|
|
77
|
+
return rows[next]?.id;
|
|
78
|
+
}
|
|
79
|
+
export function nextFocus(focus, backwards = false) {
|
|
80
|
+
const order = ["composer", "jobs", "transcript"];
|
|
81
|
+
const index = order.indexOf(focus);
|
|
82
|
+
return order[(index + (backwards ? order.length - 1 : 1)) % order.length];
|
|
83
|
+
}
|
|
84
|
+
/** Toggle main/job target. `preferredJobId` is the highlighted row, used when the target is main. */
|
|
85
|
+
export function toggleTarget(target, preferredJobId) {
|
|
86
|
+
if (target.kind === "job")
|
|
87
|
+
return { kind: "main" };
|
|
88
|
+
if (preferredJobId !== undefined)
|
|
89
|
+
return { kind: "job", id: preferredJobId };
|
|
90
|
+
return { kind: "main" };
|
|
91
|
+
}
|
|
92
|
+
export function targetLabel(target) {
|
|
93
|
+
return target.kind === "main" ? "main" : `job #${target.id}`;
|
|
94
|
+
}
|
|
95
|
+
export function clampScroll(offset, totalLines, height) {
|
|
96
|
+
const max = Math.max(0, totalLines - height);
|
|
97
|
+
return Math.max(0, Math.min(offset, max));
|
|
98
|
+
}
|