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/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 +794 -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 +1750 -0
- package/dist/tui/browser.js +19 -0
- package/dist/tui/composer.js +47 -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,120 @@
|
|
|
1
|
+
import { defineDoc, defineExtension, defineTask, defineTool, ROOT_CONVERSATION_ID } from "@earendil-works/pi-durable";
|
|
2
|
+
import { obj, oneOf, opt, str } from "@earendil-works/pi-schema";
|
|
3
|
+
export const REMINDER_KIND = "durable-chat.reminder";
|
|
4
|
+
export const MAX_PENDING_REMINDERS = 100;
|
|
5
|
+
export const MAX_REMINDER_DELAY_MS = 365 * 24 * 60 * 60 * 1000;
|
|
6
|
+
/** Only undelivered reminders. Cancellation and delivery serialize on this document. */
|
|
7
|
+
export const PendingReminders = defineDoc({
|
|
8
|
+
kind: "durable-chat.pending-reminders",
|
|
9
|
+
version: 1,
|
|
10
|
+
scope: "session",
|
|
11
|
+
initial: () => ({ byId: {} }),
|
|
12
|
+
checkpointWhen: () => false,
|
|
13
|
+
});
|
|
14
|
+
export function normalizeReminder(at, message, now) {
|
|
15
|
+
// Require an explicit timezone; never interpret a model's date in the host's local timezone.
|
|
16
|
+
if (at === undefined || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})$/.test(at)) {
|
|
17
|
+
throw new Error("Provide at as an ISO timestamp with seconds and an explicit timezone (Z or ±HH:MM).");
|
|
18
|
+
}
|
|
19
|
+
const deadline = Date.parse(at);
|
|
20
|
+
const [hour, minute, second] = at.slice(11, 19).split(":").map(Number);
|
|
21
|
+
// Date.parse normalizes impossible month days; reject those instead of moving the reminder.
|
|
22
|
+
const [year, month, day] = at.slice(0, 10).split("-").map(Number);
|
|
23
|
+
const days = new Date(Date.UTC(year, month, 0)).getUTCDate();
|
|
24
|
+
if (!Number.isFinite(deadline) || hour > 23 || minute > 59 || second > 59 || month < 1 || month > 12 || day < 1 || day > days
|
|
25
|
+
|| deadline <= now || deadline - now > MAX_REMINDER_DELAY_MS) {
|
|
26
|
+
throw new Error("Reminder time must be valid, in the future, and within 365 days.");
|
|
27
|
+
}
|
|
28
|
+
const text = message?.trim() ?? "";
|
|
29
|
+
if (text.length === 0 || text.length > 4000)
|
|
30
|
+
throw new Error("Provide a reminder message of 1–4000 characters.");
|
|
31
|
+
return { at: deadline, message: text };
|
|
32
|
+
}
|
|
33
|
+
export async function createReminderInCommit(tx, reminder) {
|
|
34
|
+
const pending = await tx.doc(PendingReminders);
|
|
35
|
+
if (Object.keys(pending.byId).length >= MAX_PENDING_REMINDERS)
|
|
36
|
+
throw new Error("Too many pending reminders (limit 100). Cancel one first.");
|
|
37
|
+
const id = await tx.createTask(ReminderTask, reminder, {
|
|
38
|
+
ownership: { kind: "conversation" }, conversationId: ROOT_CONVERSATION_ID,
|
|
39
|
+
background: true, abandonOnRestart: false,
|
|
40
|
+
});
|
|
41
|
+
pending.byId[String(id)] = reminder;
|
|
42
|
+
return id;
|
|
43
|
+
}
|
|
44
|
+
export async function cancelReminderInCommit(tx, id) {
|
|
45
|
+
const pending = await tx.doc(PendingReminders);
|
|
46
|
+
if (pending.byId[id] === undefined)
|
|
47
|
+
return false;
|
|
48
|
+
delete pending.byId[id];
|
|
49
|
+
return true;
|
|
50
|
+
}
|
|
51
|
+
export const ReminderTask = defineTask({
|
|
52
|
+
name: REMINDER_KIND,
|
|
53
|
+
version: 1,
|
|
54
|
+
initial: () => ({ phase: "sleep" }),
|
|
55
|
+
phases: {
|
|
56
|
+
sleep: async (task, runtime, context) => {
|
|
57
|
+
await runtime.sleepUntil(task.input.at, { phase: "deliver" }, context);
|
|
58
|
+
},
|
|
59
|
+
deliver: async (task, runtime, context) => {
|
|
60
|
+
const main = await runtime.conversation(ROOT_CONVERSATION_ID, context);
|
|
61
|
+
if (main === undefined)
|
|
62
|
+
throw new Error("Main conversation is unavailable for reminder delivery.");
|
|
63
|
+
await runtime.commit(async (tx) => {
|
|
64
|
+
const pending = await tx.doc(PendingReminders);
|
|
65
|
+
const reminder = pending.byId[String(task.id)];
|
|
66
|
+
if (reminder !== undefined) {
|
|
67
|
+
// Admission, removal, and the terminal receipt are one durable transaction.
|
|
68
|
+
// followUp uses Main's inbox: never start a competing model turn or interrupt a tool.
|
|
69
|
+
await main.submit(tx, {
|
|
70
|
+
type: "input", whenBusy: "followUp", requestId: `reminder:${task.id}`,
|
|
71
|
+
content: `[host reminder #${task.id}; scheduled ${new Date(reminder.at).toISOString()}] ${reminder.message}`,
|
|
72
|
+
entry: { kind: "app.reminder", data: { id: Number(task.id), ...reminder } },
|
|
73
|
+
});
|
|
74
|
+
delete pending.byId[String(task.id)];
|
|
75
|
+
}
|
|
76
|
+
return { status: "terminal", outcome: { status: "completed", result: { status: reminder === undefined ? "cancelled" : "delivered" } } };
|
|
77
|
+
}, context);
|
|
78
|
+
},
|
|
79
|
+
},
|
|
80
|
+
abort: async (task, runtime, context) => {
|
|
81
|
+
await runtime.commit(async (tx) => {
|
|
82
|
+
await cancelReminderInCommit(tx, String(task.id));
|
|
83
|
+
return { status: "terminal", outcome: { status: "aborted", reason: "Reminder aborted.", result: { status: "cancelled" } } };
|
|
84
|
+
}, context);
|
|
85
|
+
},
|
|
86
|
+
});
|
|
87
|
+
const reply = (text, isError = false) => ({ output: [{ type: "text", text }], ...(isError ? { isError: true } : {}) });
|
|
88
|
+
export const ReminderTools = defineExtension({
|
|
89
|
+
name: "durable-chat.reminders",
|
|
90
|
+
tasks: [ReminderTask],
|
|
91
|
+
tools: [defineTool({
|
|
92
|
+
name: "reminder",
|
|
93
|
+
description: "Main only: schedule a one-shot future wake-up, returning immediately. Use action schedule with at (ISO timestamp with timezone) and message (what to check next). Main receives a host reminder through its normal inbox when due, or on next running session if offline. Do not wait or poll. list shows pending reminders; cancel with id suppresses an undelivered reminder but cannot retract an already queued input.",
|
|
94
|
+
parameters: obj({ action: oneOf(["schedule", "list", "cancel"]), at: opt(str()), message: opt(str({ maxLength: 4000 })), id: opt(str({ pattern: "^[1-9][0-9]*$" })) }),
|
|
95
|
+
replay: "unsafe",
|
|
96
|
+
execute: async (args, api, context) => {
|
|
97
|
+
if (api.conversationId !== ROOT_CONVERSATION_ID)
|
|
98
|
+
return reply("Only main may manage reminders.", true);
|
|
99
|
+
try {
|
|
100
|
+
if (args.action === "list") {
|
|
101
|
+
const pending = await api.snapshot(PendingReminders, context);
|
|
102
|
+
const items = Object.entries(pending?.byId ?? {}).sort((a, b) => a[1].at - b[1].at);
|
|
103
|
+
return reply(items.map(([id, item]) => `#${id} ${new Date(item.at).toISOString()} ${item.message}`).join("\n") || "No pending reminders.");
|
|
104
|
+
}
|
|
105
|
+
if (args.action === "cancel") {
|
|
106
|
+
if (args.id === undefined || !Number.isSafeInteger(Number(args.id)) || Number(args.id) <= 0)
|
|
107
|
+
return reply("Provide a valid reminder id.", true);
|
|
108
|
+
const cancelled = await api.commit((tx) => cancelReminderInCommit(tx, args.id), context);
|
|
109
|
+
return reply(cancelled ? `Cancelled reminder #${args.id}.` : `No pending reminder #${args.id}; it may already have been delivered.`, !cancelled);
|
|
110
|
+
}
|
|
111
|
+
const reminder = normalizeReminder(args.at, args.message, api.now());
|
|
112
|
+
const id = await api.commit((tx) => createReminderInCommit(tx, reminder), context);
|
|
113
|
+
return reply(`Scheduled reminder #${id} for ${new Date(reminder.at).toISOString()}. Return to the user now; do not wait or poll.`);
|
|
114
|
+
}
|
|
115
|
+
catch (error) {
|
|
116
|
+
return reply(error instanceof Error ? error.message : String(error), true);
|
|
117
|
+
}
|
|
118
|
+
},
|
|
119
|
+
})],
|
|
120
|
+
});
|
package/dist/rollback.js
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { chmodSync, lstatSync, mkdtempSync, readdirSync, realpathSync, renameSync, rmSync } from "node:fs";
|
|
2
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { DatabaseSync } from "node:sqlite";
|
|
5
|
+
/** Discovery is best-effort; explicit paths remain usable when archives cannot be listed. */
|
|
6
|
+
export function rollbackChoices(storePath, previousArchive) {
|
|
7
|
+
let discovered = [];
|
|
8
|
+
try {
|
|
9
|
+
discovered = readdirSync(dirname(storePath), { withFileTypes: true })
|
|
10
|
+
.filter((entry) => entry.isDirectory() && entry.name.startsWith(`${basename(storePath)}.reboot-`))
|
|
11
|
+
.map((entry) => join(dirname(storePath), entry.name, basename(storePath))).sort().reverse();
|
|
12
|
+
}
|
|
13
|
+
catch { /* The user can still enter an explicit path. */ }
|
|
14
|
+
return [...new Set([...(previousArchive === undefined ? [] : [previousArchive]), ...discovered])]
|
|
15
|
+
.filter((path) => {
|
|
16
|
+
try {
|
|
17
|
+
const stat = lstatSync(path);
|
|
18
|
+
return stat.isFile() && stat.nlink === 1 && realpathSync(path) !== realpathSync(storePath);
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
return false;
|
|
22
|
+
}
|
|
23
|
+
}).slice(0, 5);
|
|
24
|
+
}
|
|
25
|
+
export function rollbackSource(input, choices, storePath) {
|
|
26
|
+
let path = input.trim();
|
|
27
|
+
if (path.length === 0)
|
|
28
|
+
throw new Error("Choose an archive number or enter a database file path.");
|
|
29
|
+
if (/^[1-9][0-9]*$/.test(path)) {
|
|
30
|
+
const selected = choices[Number(path) - 1];
|
|
31
|
+
if (selected === undefined)
|
|
32
|
+
throw new Error("No archive with that number; choose a listed archive or enter a file path.");
|
|
33
|
+
path = selected;
|
|
34
|
+
}
|
|
35
|
+
else if ((path.startsWith('"') && path.endsWith('"')) || (path.startsWith("'") && path.endsWith("'"))) {
|
|
36
|
+
path = path.slice(1, -1);
|
|
37
|
+
}
|
|
38
|
+
if (path.startsWith("~/"))
|
|
39
|
+
path = join(homedir(), path.slice(2));
|
|
40
|
+
path = resolve(path);
|
|
41
|
+
const source = lstatSync(path);
|
|
42
|
+
if (!source.isFile() || source.nlink !== 1)
|
|
43
|
+
throw new Error("Choose a regular database file without symlinks or additional hard links.");
|
|
44
|
+
const current = lstatSync(storePath);
|
|
45
|
+
if (source.dev === current.dev && source.ino === current.ino)
|
|
46
|
+
throw new Error("That file is already the current state; choose another database.");
|
|
47
|
+
return realpathSync(path);
|
|
48
|
+
}
|
|
49
|
+
/** The target is the exclusively held, empty replacement file created by state rotation. */
|
|
50
|
+
export function installRollbackSnapshot(sourcePath, storePath) {
|
|
51
|
+
const target = lstatSync(storePath);
|
|
52
|
+
if (!target.isFile() || target.nlink !== 1 || target.size !== 0)
|
|
53
|
+
throw new Error("Refusing to replace a nonempty or aliased state file.");
|
|
54
|
+
const staging = mkdtempSync(join(dirname(storePath), ".state-rollback-"));
|
|
55
|
+
try {
|
|
56
|
+
const snapshot = join(staging, "snapshot.sqlite");
|
|
57
|
+
const source = new DatabaseSync(sourcePath, { readOnly: true });
|
|
58
|
+
try {
|
|
59
|
+
// A raw copy can miss committed WAL data. VACUUM INTO leaves the source database unchanged.
|
|
60
|
+
source.prepare("VACUUM INTO ?").run(snapshot);
|
|
61
|
+
}
|
|
62
|
+
finally {
|
|
63
|
+
source.close();
|
|
64
|
+
}
|
|
65
|
+
chmodSync(snapshot, target.mode & 0o777);
|
|
66
|
+
renameSync(snapshot, storePath);
|
|
67
|
+
}
|
|
68
|
+
finally {
|
|
69
|
+
// Only our unpublished staging files; selected and archived state are always retained.
|
|
70
|
+
rmSync(staging, { recursive: true, force: true });
|
|
71
|
+
}
|
|
72
|
+
}
|
package/dist/state.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { chmodSync, linkSync, lstatSync, mkdtempSync, readFileSync, renameSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { dirname, join, resolve } from "node:path";
|
|
3
|
+
import { DatabaseSync } from "node:sqlite";
|
|
4
|
+
import { localConfigPath, resolveConfig, setConfigValue } from "./config.js";
|
|
5
|
+
import { acquireStoreLock } from "./harness.js";
|
|
6
|
+
/** Snapshot the selected state without opening a Harness or resuming any work. */
|
|
7
|
+
export function forkLocalState(overrides = {}, env = process.env) {
|
|
8
|
+
const sourcePath = resolveConfig(overrides, env).storePath;
|
|
9
|
+
const storePath = resolve(".durable-chat/store.sqlite");
|
|
10
|
+
const configPath = localConfigPath();
|
|
11
|
+
if (sourcePath === storePath)
|
|
12
|
+
throw new Error("The selected state is already folder-local; select another source with --store <path>.");
|
|
13
|
+
if (lstatSync(sourcePath, { throwIfNoEntry: false }) === undefined)
|
|
14
|
+
throw new Error(`Source state does not exist: ${sourcePath}`);
|
|
15
|
+
const release = acquireStoreLock(storePath);
|
|
16
|
+
let staging;
|
|
17
|
+
try {
|
|
18
|
+
for (const path of [storePath, `${storePath}-wal`, `${storePath}-shm`]) {
|
|
19
|
+
if (lstatSync(path, { throwIfNoEntry: false }) !== undefined)
|
|
20
|
+
throw new Error(`Refusing to overwrite existing local state: ${path}`);
|
|
21
|
+
}
|
|
22
|
+
const originalConfig = lstatSync(configPath, { throwIfNoEntry: false }) === undefined ? undefined : readFileSync(configPath);
|
|
23
|
+
staging = mkdtempSync(join(dirname(storePath), ".state-fork-"));
|
|
24
|
+
const stagedConfig = join(staging, "config.yaml");
|
|
25
|
+
if (originalConfig !== undefined)
|
|
26
|
+
writeFileSync(stagedConfig, originalConfig);
|
|
27
|
+
setConfigValue(stagedConfig, "store", ".durable-chat/store.sqlite");
|
|
28
|
+
chmodSync(stagedConfig, 0o600);
|
|
29
|
+
const snapshot = join(staging, "store.sqlite");
|
|
30
|
+
const source = new DatabaseSync(sourcePath, { readOnly: true });
|
|
31
|
+
try {
|
|
32
|
+
// VACUUM INTO is a consistent SQLite snapshot, including committed WAL data.
|
|
33
|
+
// A raw file copy can silently omit that data while the source is open.
|
|
34
|
+
source.prepare("VACUUM INTO ?").run(snapshot);
|
|
35
|
+
}
|
|
36
|
+
finally {
|
|
37
|
+
source.close();
|
|
38
|
+
}
|
|
39
|
+
chmodSync(snapshot, 0o600);
|
|
40
|
+
const currentConfig = lstatSync(configPath, { throwIfNoEntry: false }) === undefined ? undefined : readFileSync(configPath);
|
|
41
|
+
if (originalConfig === undefined ? currentConfig !== undefined : currentConfig === undefined || !originalConfig.equals(currentConfig)) {
|
|
42
|
+
throw new Error(`Local config changed while forking; retry: ${configPath}`);
|
|
43
|
+
}
|
|
44
|
+
// Hard-link publication is exclusive: even a competing creator cannot be overwritten.
|
|
45
|
+
linkSync(snapshot, storePath);
|
|
46
|
+
try {
|
|
47
|
+
renameSync(stagedConfig, configPath);
|
|
48
|
+
}
|
|
49
|
+
catch (error) {
|
|
50
|
+
unlinkSync(storePath);
|
|
51
|
+
throw error;
|
|
52
|
+
}
|
|
53
|
+
return { sourcePath, storePath, configPath };
|
|
54
|
+
}
|
|
55
|
+
finally {
|
|
56
|
+
try {
|
|
57
|
+
if (staging !== undefined)
|
|
58
|
+
rmSync(staging, { recursive: true, force: true });
|
|
59
|
+
}
|
|
60
|
+
finally {
|
|
61
|
+
release();
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
package/dist/tags.js
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { defineDoc } from "@earendil-works/pi-durable";
|
|
2
|
+
import { JOB_KIND } from "./tasks.js";
|
|
3
|
+
/** Labels outlive job tasks; the session index is their single mutable source of truth. */
|
|
4
|
+
export const JobTags = defineDoc({
|
|
5
|
+
kind: "durable-chat.job-tags", version: 1, scope: "session",
|
|
6
|
+
initial: () => ({ byJob: {} }), checkpointWhen: () => false,
|
|
7
|
+
});
|
|
8
|
+
export function normalizeTags(tags) {
|
|
9
|
+
const normalized = [...new Set(tags.map((tag) => tag.trim().toLowerCase()))];
|
|
10
|
+
if (normalized.length > 8 || normalized.some((tag) => !/^[a-z0-9][a-z0-9._-]{0,47}$/.test(tag))) {
|
|
11
|
+
throw new Error("Use at most 8 tags, each 1–48 letters/digits with optional dots, hyphens, or underscores.");
|
|
12
|
+
}
|
|
13
|
+
return normalized;
|
|
14
|
+
}
|
|
15
|
+
/** For a just-created or already validated job; performs only document writes. */
|
|
16
|
+
export async function writeJobTags(tx, id, tags) {
|
|
17
|
+
const labels = await tx.doc(JobTags);
|
|
18
|
+
if (tags.length === 0)
|
|
19
|
+
delete labels.byJob[String(id)];
|
|
20
|
+
else
|
|
21
|
+
labels.byJob[String(id)] = [...tags];
|
|
22
|
+
}
|
|
23
|
+
export async function setJobTags(tx, id, tags) {
|
|
24
|
+
const normalized = normalizeTags(tags);
|
|
25
|
+
if ((await tx.task(id))?.kind !== JOB_KIND)
|
|
26
|
+
throw new Error(`No job #${id}.`);
|
|
27
|
+
await writeJobTags(tx, id, normalized);
|
|
28
|
+
return normalized;
|
|
29
|
+
}
|
|
30
|
+
export function taggedJob(record, index) {
|
|
31
|
+
return { ...record, tags: [...(index?.byJob[String(record.id)] ?? [])] };
|
|
32
|
+
}
|
|
33
|
+
/** Resolve at call time. Ambiguity is explicit rather than silently choosing a different prepared context. */
|
|
34
|
+
export function resolveTaggedSource(source, index) {
|
|
35
|
+
if (!source.startsWith("tag:"))
|
|
36
|
+
return source;
|
|
37
|
+
const tag = normalizeTags([source.slice(4)])[0];
|
|
38
|
+
const matches = Object.entries(index?.byJob ?? {}).filter(([, tags]) => tags.includes(tag)).map(([id]) => id);
|
|
39
|
+
if (matches.length === 0)
|
|
40
|
+
throw new Error(`No job has tag ${tag}.`);
|
|
41
|
+
if (matches.length > 1)
|
|
42
|
+
throw new Error(`Tag ${tag} matches jobs ${matches.map((id) => `#${id}`).join(", ")}. Choose an id or make the tag unique.`);
|
|
43
|
+
return matches[0];
|
|
44
|
+
}
|