durable-chat 0.0.0-stage → 1.0.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/dist/cli.js ADDED
@@ -0,0 +1,519 @@
1
+ #!/usr/bin/env node
2
+ import { parseArgs } from "node:util";
3
+ import { createInterface } from "node:readline/promises";
4
+ import { withCancel } from "@earendil-works/chord/context";
5
+ import { openRuntime, StoreInUseError } from "./harness.js";
6
+ import { focusExistingSession } from "./existing-session.js";
7
+ import { askMain, attachStreamer } from "./chat.js";
8
+ import { cancelJob, compactJob, compactMain, followAll, listJobs, printHelp, printInfo, resetJob, resetMain, sendJob, showJob, showLog, startJob, } from "./commands.js";
9
+ import { scanJobs } from "./jobs.js";
10
+ import { runConfigCommand, printConfigHelp } from "./config-commands.js";
11
+ import { JOB_KIND } from "./tasks.js";
12
+ import { selectModel } from "./models.js";
13
+ import { rollbackChoices, rollbackSource } from "./rollback.js";
14
+ import { forkLocalState } from "./state.js";
15
+ const OPTIONS = {
16
+ store: { type: "string" },
17
+ provider: { type: "string" },
18
+ model: { type: "string" },
19
+ config: { type: "string" },
20
+ force: { type: "boolean", default: false },
21
+ local: { type: "boolean", default: false },
22
+ plain: { type: "boolean", default: false },
23
+ steer: { type: "boolean", default: false },
24
+ follow: { type: "boolean", default: false },
25
+ detach: { type: "boolean", default: false },
26
+ wait: { type: "boolean", default: false },
27
+ verbose: { type: "boolean", default: false },
28
+ "no-mcp": { type: "boolean", default: false },
29
+ help: { type: "boolean", short: "h", default: false },
30
+ };
31
+ async function readStdin() {
32
+ const chunks = [];
33
+ for await (const chunk of process.stdin)
34
+ chunks.push(String(chunk));
35
+ return chunks.join("").trim();
36
+ }
37
+ function textOf(positionals, from) {
38
+ return positionals.slice(from).join(" ").trim();
39
+ }
40
+ function banner(runtime) {
41
+ process.stdout.write(`durable-chat — ${runtime.modelLabel} — ${runtime.storePath}\n`);
42
+ const mcp = runtime.mcpAttempted ? (runtime.mcpConnected ? "Substrate MCP connected" : "Substrate MCP unavailable") : "MCP disabled";
43
+ if (runtime.previousStateArchive !== undefined)
44
+ process.stdout.write(`Previous state archive: ${runtime.previousStateArchive}\n`);
45
+ if (runtime.restoredFrom !== undefined)
46
+ process.stdout.write(`Restored from: ${runtime.restoredFrom}\n`);
47
+ process.stdout.write(`jobs: ${mcp} · /help for commands\n\n`);
48
+ }
49
+ async function slash(runtime, input, state) {
50
+ const [command, ...rest] = input.slice(1).trim().split(/\s+/);
51
+ const tail = input.slice(1 + (command?.length ?? 0)).trim();
52
+ switch (command) {
53
+ case "help":
54
+ printHelp();
55
+ return true;
56
+ case "model": {
57
+ const id = await state.requestModel(tail);
58
+ if (id === undefined)
59
+ return true;
60
+ state.exit = { modelId: id };
61
+ return false;
62
+ }
63
+ case "provider": {
64
+ const entries = runtime.config.providers;
65
+ if (rest[0] === undefined) {
66
+ process.stdout.write(`Providers: ${entries.map((entry) => `${entry.name}${entry.name === runtime.config.provider ? " (current)" : ""}`).join(", ")} — the config file decides the next run\n`);
67
+ return true;
68
+ }
69
+ state.exit = { provider: rest[0] };
70
+ return false;
71
+ }
72
+ case "thinking": {
73
+ if (rest[0] === undefined) {
74
+ process.stdout.write(`thinking: ${runtime.thinkingLevel} (session override; the config file decides the next run)\n`);
75
+ return true;
76
+ }
77
+ process.stdout.write(`thinking level: ${await runtime.setThinkingLevel(rest[0])}\n`);
78
+ return true;
79
+ }
80
+ case "rollback": {
81
+ const source = await state.requestRollback(tail);
82
+ if (source === undefined)
83
+ return true;
84
+ state.exit = { rollbackFrom: source };
85
+ return false;
86
+ }
87
+ case "reboot":
88
+ if (tail.length > 0)
89
+ throw new Error("Usage: /reboot");
90
+ if (!(await state.confirmReboot()))
91
+ return true;
92
+ state.exit = "reboot";
93
+ return false;
94
+ case "quit":
95
+ case "exit":
96
+ return false;
97
+ case "tasks":
98
+ await listJobs(runtime);
99
+ return true;
100
+ case "task":
101
+ case "show":
102
+ if (rest[0] === undefined)
103
+ return true;
104
+ await showJob(runtime, rest[0]);
105
+ return true;
106
+ case "log":
107
+ if (rest[0] === undefined)
108
+ return true;
109
+ await showLog(runtime, rest[0]);
110
+ return true;
111
+ case "new":
112
+ if (tail.length === 0) {
113
+ process.stdout.write("Usage: /new <brief>\n");
114
+ return true;
115
+ }
116
+ await startJob(runtime, tail, { detach: true, resume: true });
117
+ return true;
118
+ case "send":
119
+ case "steer": {
120
+ const [id, ...message] = tail.split(/\s+/);
121
+ if (id === undefined || message.length === 0) {
122
+ process.stdout.write(`Usage: /${command} <id> <message>\n`);
123
+ return true;
124
+ }
125
+ await sendJob(runtime, id, message.join(" "), { steer: command === "steer" });
126
+ return true;
127
+ }
128
+ case "cancel":
129
+ if (rest[0] !== undefined)
130
+ await cancelJob(runtime, rest[0]);
131
+ return true;
132
+ case "compact":
133
+ await compactMain(runtime, tail.length === 0 ? undefined : tail);
134
+ return true;
135
+ case "reset":
136
+ await resetMain(runtime, tail.length === 0 ? undefined : tail);
137
+ return true;
138
+ case "wait": {
139
+ const controller = new AbortController();
140
+ state.cancelWait = () => controller.abort();
141
+ try {
142
+ const { followJobs } = await import("./watch.js");
143
+ await followJobs(runtime, { signal: controller.signal });
144
+ }
145
+ finally {
146
+ state.cancelWait = undefined;
147
+ }
148
+ return true;
149
+ }
150
+ case "info":
151
+ await printInfo(runtime);
152
+ return true;
153
+ default:
154
+ process.stdout.write(`Unknown command /${command ?? ""}. /help lists commands.\n`);
155
+ return true;
156
+ }
157
+ }
158
+ async function interactive(runtime, notice) {
159
+ const rl = createInterface({ input: process.stdin, output: process.stdout, terminal: process.stdin.isTTY === true });
160
+ const streamer = process.stdout.isTTY === true
161
+ ? await attachStreamer(runtime.root, runtime.context, { enabled: true })
162
+ : undefined;
163
+ const state = {
164
+ confirmReboot: async () => (await rl.question(`Archive all conversations, jobs and tags at ${runtime.storePath} and start fresh? Durable work pauses; project files and worktrees remain. [y/N] `)).trim().toLowerCase() === "y",
165
+ requestModel: async (choice) => {
166
+ const choices = await runtime.listModels();
167
+ if (choices.warning !== undefined)
168
+ process.stdout.write(`${choices.warning}\n`);
169
+ if (choice.length === 0) {
170
+ process.stdout.write(`Models for ${runtime.model.provider} — main and all jobs, this session only:\n`);
171
+ process.stdout.write(`${choices.items.map((model, index) => `${index + 1}. ${model.id}${model.id === runtime.model.modelId ? " (current)" : ""}`).join("\n")}\n`);
172
+ choice = (await rl.question("Model number or ID (Enter cancels)> ")).trim();
173
+ if (choice.length === 0)
174
+ return undefined;
175
+ }
176
+ return selectModel(choice, choices.items).lookup;
177
+ },
178
+ requestRollback: async (choice) => {
179
+ const choices = rollbackChoices(runtime.storePath, runtime.previousStateArchive);
180
+ if (choice.length === 0) {
181
+ process.stdout.write(choices.length === 0 ? "No recent archives; enter a database file path.\n" : `${choices.map((path, index) => `${index + 1}. ${path}`).join("\n")}\n`);
182
+ choice = (await rl.question("Rollback file or number (Enter cancels)> ")).trim();
183
+ if (choice.length === 0)
184
+ return undefined;
185
+ }
186
+ const source = rollbackSource(choice, choices, runtime.storePath);
187
+ const answer = await rl.question(`Restore from ${source}? Current state will be archived; the selected file stays unchanged. Restored jobs resume; project files/worktrees remain. [y/N] `);
188
+ return answer.trim().toLowerCase() === "y" ? source : undefined;
189
+ },
190
+ };
191
+ const pendingNotes = [];
192
+ let busy = false;
193
+ const note = (text) => {
194
+ if (busy)
195
+ pendingNotes.push(text);
196
+ else
197
+ process.stdout.write(`· ${text}\n`);
198
+ };
199
+ const graph = await runtime.harness.watchTaskGraph(runtime.context);
200
+ let previous = new Map();
201
+ graph.start(async (call) => {
202
+ if (call.kind !== "value")
203
+ return;
204
+ const nodes = Object.values(call.value.tasks).filter((node) => node.kind === JOB_KIND);
205
+ const next = new Map(nodes.map((node) => [String(node.id), node.state.status]));
206
+ for (const [id, status] of next) {
207
+ const before = previous.get(id);
208
+ if (before !== status)
209
+ note(`job #${id} ${status}`);
210
+ }
211
+ for (const id of previous.keys()) {
212
+ if (!next.has(id))
213
+ note(`job #${id} finished — /task ${id} for the answer`);
214
+ }
215
+ previous = next;
216
+ });
217
+ let closed = false;
218
+ rl.on("close", () => {
219
+ closed = true;
220
+ });
221
+ rl.on("SIGINT", () => {
222
+ if (state.cancelWait !== undefined) {
223
+ state.cancelWait();
224
+ process.stdout.write("\n(stopped waiting; durable work continues)\n");
225
+ return;
226
+ }
227
+ process.stdout.write("\n(leaving; live jobs keep their durable state)\n");
228
+ rl.close();
229
+ });
230
+ banner(runtime);
231
+ if (notice !== undefined)
232
+ (notice.error === true ? process.stderr : process.stdout).write(`${notice.text}\n`);
233
+ while (!closed) {
234
+ let line;
235
+ try {
236
+ line = await rl.question("you> ");
237
+ }
238
+ catch {
239
+ break;
240
+ }
241
+ const text = line.trim();
242
+ if (text.length === 0)
243
+ continue;
244
+ if (text.startsWith("/")) {
245
+ try {
246
+ if (!(await slash(runtime, text, state)))
247
+ break;
248
+ }
249
+ catch (error) {
250
+ process.stderr.write(`error: ${error instanceof Error ? error.message : String(error)}\n`);
251
+ }
252
+ continue;
253
+ }
254
+ const turn = withCancel(runtime.context);
255
+ state.cancelWait = () => turn.cancel(new Error("interrupted"));
256
+ busy = true;
257
+ try {
258
+ const result = await askMain(runtime, text, streamer, turn.context);
259
+ if (!result.ok)
260
+ process.stdout.write(`(run failed: ${result.reason})\n`);
261
+ }
262
+ catch (error) {
263
+ const message = error instanceof Error ? error.message : String(error);
264
+ if (message.includes("interrupted"))
265
+ process.stdout.write("(stopped waiting; the run may still finish)\n");
266
+ else
267
+ process.stderr.write(`error: ${message}\n`);
268
+ }
269
+ finally {
270
+ state.cancelWait = undefined;
271
+ busy = false;
272
+ for (const line of pendingNotes.splice(0))
273
+ process.stdout.write(`· ${line}\n`);
274
+ }
275
+ try {
276
+ const jobs = await scanJobs(runtime.harness, runtime.context);
277
+ const live = jobs.filter((record) => record.state.status !== "terminal");
278
+ if (live.length > 0) {
279
+ process.stdout.write(`· ${live.length} live job${live.length === 1 ? "" : "s"} — /tasks\n`);
280
+ }
281
+ }
282
+ catch {
283
+ // A failed read must not end the chat.
284
+ }
285
+ }
286
+ await graph.stop();
287
+ await streamer?.stop();
288
+ rl.close();
289
+ return state.exit ?? "quit";
290
+ }
291
+ async function runTui(runtime, notice) {
292
+ const { runTui: start } = await import("./tui/main.js");
293
+ return start(runtime, notice);
294
+ }
295
+ async function main() {
296
+ let parsed;
297
+ try {
298
+ parsed = parseArgs({ args: process.argv.slice(2), allowPositionals: true, options: OPTIONS });
299
+ }
300
+ catch (error) {
301
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
302
+ printHelp();
303
+ process.exitCode = 2;
304
+ return;
305
+ }
306
+ const { values, positionals } = parsed;
307
+ if (values.help === true || positionals[0] === "help") {
308
+ printHelp();
309
+ printConfigHelp();
310
+ return;
311
+ }
312
+ const command = positionals[0];
313
+ if (command === "config") {
314
+ runConfigCommand(positionals.slice(1), {
315
+ ...(values.config === undefined ? {} : { configPath: values.config }),
316
+ force: values.force === true,
317
+ local: values.local === true,
318
+ });
319
+ return;
320
+ }
321
+ if (values.local === true)
322
+ throw new Error("--local is only supported by config commands.");
323
+ const sub = positionals[1];
324
+ if (command === "state") {
325
+ if (sub !== "fork" || positionals.length !== 2)
326
+ throw new Error("Usage: dchat state fork [--store <source.sqlite>]");
327
+ if (values.force === true)
328
+ throw new Error("State forks never overwrite existing local state; --force is not supported.");
329
+ const fork = forkLocalState({
330
+ ...(values.store === undefined ? {} : { store: values.store }),
331
+ ...(values.config === undefined ? {} : { configPath: values.config }),
332
+ ...(values.provider === undefined ? {} : { provider: values.provider }),
333
+ ...(values.model === undefined ? {} : { model: values.model }),
334
+ });
335
+ process.stdout.write(`Forked state:\n from: ${fork.sourcePath}\n to: ${fork.storePath}\nLocal config: ${fork.configPath}\n`);
336
+ process.stdout.write("Run dchat in this folder to continue the fork. The source is unchanged.\n");
337
+ process.stdout.write("Pending work is copied too; running both copies can repeat external actions. Existing jobs keep their saved working directories.\n");
338
+ for (const name of ["DURABLE_STORE", "DURABLE_CHAT_CONFIG"]) {
339
+ if ((process.env[name]?.trim() ?? "") !== "")
340
+ process.stdout.write(`note: unset ${name} to let the new folder-local config select its database.\n`);
341
+ }
342
+ return;
343
+ }
344
+ const noMcp = values["no-mcp"] === true;
345
+ const readOnly = command === "tasks"
346
+ || (command === "task" && (sub === "show" || sub === "log" || sub === "get" || (sub !== undefined && /^[0-9]+$/.test(sub))));
347
+ let runtime;
348
+ try {
349
+ runtime = await openRuntime({
350
+ ...(values.store === undefined ? {} : { storePath: values.store }),
351
+ ...(values.provider === undefined ? {} : { provider: values.provider }),
352
+ ...(values.model === undefined ? {} : { model: values.model }),
353
+ ...(values.config === undefined ? {} : { configPath: values.config }),
354
+ verbose: values.verbose === true,
355
+ ...(readOnly || noMcp ? { withMcp: false } : {}),
356
+ });
357
+ }
358
+ catch (error) {
359
+ if (error instanceof StoreInUseError && await focusExistingSession(error.pid, { command })) {
360
+ process.stdout.write("dchat is already running for this store; focused its existing Ghostty terminal.\n");
361
+ return;
362
+ }
363
+ throw error;
364
+ }
365
+ const runInteractive = async (mode) => {
366
+ let notice;
367
+ for (;;) {
368
+ const exit = await (mode === "plain" ? interactive(runtime, notice) : runTui(runtime, notice));
369
+ notice = undefined;
370
+ if (exit === "quit")
371
+ return;
372
+ if (exit === "reboot")
373
+ runtime = await runtime.reboot();
374
+ else if ("rollbackFrom" in exit)
375
+ runtime = await runtime.rollback(exit.rollbackFrom);
376
+ else if ("provider" in exit) {
377
+ const result = await runtime.switchProvider(exit.provider);
378
+ runtime = result.runtime;
379
+ notice = result.error === undefined ? { text: `Provider: ${runtime.modelLabel} (all agents, this session)` } : { text: result.error, error: true };
380
+ }
381
+ else {
382
+ const result = await runtime.switchModel(exit.modelId);
383
+ runtime = result.runtime;
384
+ notice = result.error === undefined ? { text: `Model: ${runtime.modelLabel} (all agents, this session)` } : { text: result.error, error: true };
385
+ }
386
+ }
387
+ };
388
+ try {
389
+ switch (command) {
390
+ case undefined:
391
+ if (process.stdin.isTTY !== true) {
392
+ process.stderr.write("Interactive mode needs a TTY; use `durable-chat ask <text>`.\n");
393
+ process.exitCode = 2;
394
+ return;
395
+ }
396
+ if (values.plain === true) {
397
+ await runInteractive("plain");
398
+ return;
399
+ }
400
+ await runInteractive("tui");
401
+ return;
402
+ case "tui":
403
+ await runInteractive("tui");
404
+ return;
405
+ case "chat":
406
+ if (process.stdin.isTTY !== true) {
407
+ process.stderr.write("Interactive mode needs a TTY; use `durable-chat ask <text>`.\n");
408
+ process.exitCode = 2;
409
+ return;
410
+ }
411
+ await runInteractive("plain");
412
+ return;
413
+ case "ask": {
414
+ const text = textOf(positionals, 1) || (process.stdin.isTTY === true ? "" : await readStdin());
415
+ if (text.length === 0) {
416
+ process.stderr.write("Usage: durable-chat ask <text>\n");
417
+ process.exitCode = 2;
418
+ return;
419
+ }
420
+ const streamer = process.stdout.isTTY === true
421
+ ? await attachStreamer(runtime.root, runtime.context, { enabled: true })
422
+ : undefined;
423
+ let result;
424
+ try {
425
+ result = await askMain(runtime, text, streamer);
426
+ }
427
+ finally {
428
+ await streamer?.stop();
429
+ }
430
+ if (!result.ok)
431
+ process.stderr.write(`run failed: ${result.reason}\n`);
432
+ if (values.wait === true)
433
+ await followAll(runtime, false);
434
+ const jobs = await scanJobs(runtime.harness, runtime.context);
435
+ const live = jobs.filter((record) => record.state.status !== "terminal");
436
+ if (live.length > 0) {
437
+ process.stdout.write(`· ${live.length} live job${live.length === 1 ? "" : "s"}; follow with \`durable-chat watch\`.\n`);
438
+ }
439
+ return;
440
+ }
441
+ case "tasks":
442
+ await listJobs(runtime);
443
+ return;
444
+ case "task": {
445
+ if (sub === undefined) {
446
+ await listJobs(runtime);
447
+ return;
448
+ }
449
+ if (/^[0-9]+$/.test(sub)) {
450
+ await showJob(runtime, sub);
451
+ return;
452
+ }
453
+ switch (sub) {
454
+ case "add":
455
+ case "new": {
456
+ const brief = textOf(positionals, 2) || (process.stdin.isTTY === true ? "" : await readStdin());
457
+ if (brief.length === 0) {
458
+ process.stderr.write("Usage: durable-chat task add <brief>\n");
459
+ process.exitCode = 2;
460
+ return;
461
+ }
462
+ await startJob(runtime, brief, { detach: values.detach === true });
463
+ return;
464
+ }
465
+ case "show":
466
+ case "get":
467
+ await showJob(runtime, required(positionals[2], "task show <id>"));
468
+ return;
469
+ case "log":
470
+ await showLog(runtime, required(positionals[2], "task log <id>"));
471
+ return;
472
+ case "send":
473
+ await sendJob(runtime, required(positionals[2], "task send <id> <message>"), required(textOf(positionals, 3), "task send <id> <message>"), { steer: values.steer === true });
474
+ return;
475
+ case "cancel":
476
+ await cancelJob(runtime, required(positionals[2], "task cancel <id>"));
477
+ return;
478
+ case "compact":
479
+ await compactJob(runtime, required(positionals[2], "task compact <id> [focus]"), textOf(positionals, 3) || undefined);
480
+ return;
481
+ case "reset":
482
+ await resetJob(runtime, required(positionals[2], "task reset <id> [handoff]"), textOf(positionals, 3) || undefined);
483
+ return;
484
+ default:
485
+ printHelp("jobs");
486
+ return;
487
+ }
488
+ }
489
+ case "watch":
490
+ await followAll(runtime, values.follow === true);
491
+ return;
492
+ case "compact":
493
+ await compactMain(runtime, textOf(positionals, 1) || undefined);
494
+ return;
495
+ case "reset":
496
+ await resetMain(runtime, textOf(positionals, 1) || undefined);
497
+ return;
498
+ case "info":
499
+ await printInfo(runtime);
500
+ return;
501
+ default:
502
+ process.stderr.write(`Unknown command "${command}".\n`);
503
+ printHelp();
504
+ process.exitCode = 2;
505
+ }
506
+ }
507
+ finally {
508
+ await runtime.close();
509
+ }
510
+ }
511
+ function required(value, usage) {
512
+ if (value === undefined || value.length === 0)
513
+ throw new Error(`Usage: durable-chat ${usage}`);
514
+ return value;
515
+ }
516
+ main().catch((error) => {
517
+ process.stderr.write(`error: ${error instanceof Error ? error.message : String(error)}\n`);
518
+ process.exitCode = 1;
519
+ });
@@ -0,0 +1,23 @@
1
+ import { CodemodeSandbox } from "@earendil-works/pi-codemode";
2
+ import { createCodemodeExtension } from "@earendil-works/pi-durable/codemode";
3
+ /**
4
+ * One QuickJS sandbox per runtime. It runs scripts on a worker thread, so a spinning script
5
+ * cannot block the TUI's event loop.
6
+ *
7
+ * The VM fingerprint records the memory limit and the interrupt budget, and a script interrupted
8
+ * by a restart only replays when that fingerprint still matches, so these stay constants here
9
+ * rather than config keys. Closing the sandbox is not a script outcome: the script resumes in the
10
+ * next runtime's sandbox from its journal.
11
+ */
12
+ const MEMORY_LIMIT_BYTES = 128 * 1024 * 1024;
13
+ const SCRIPT_TIMEOUT_MS = 300_000;
14
+ /** MCP tools are named `mcp__<server>__<tool>`, so the codemode section groups them by server. */
15
+ const NAMESPACES = [{ name: "mcp", prefix: "mcp__" }];
16
+ /** The codemode extension: the tool, its prompt section, and the sandbox that runs scripts. */
17
+ export function openCodemode() {
18
+ const sandbox = new CodemodeSandbox({ memoryLimitBytes: MEMORY_LIMIT_BYTES, timeoutMs: SCRIPT_TIMEOUT_MS });
19
+ return {
20
+ extension: createCodemodeExtension({ sandbox, namespaces: NAMESPACES }),
21
+ close: () => sandbox.close(),
22
+ };
23
+ }