@kingcrab/pi-imessage 1.2.2 → 1.2.4

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.
@@ -1,20 +1,28 @@
1
+ import { existsSync } from "node:fs";
1
2
  import { mkdir, open, unlink } from "node:fs/promises";
2
3
  import { join } from "node:path";
3
4
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
4
5
  import { createRegistry, Harness } from "@earendil-works/pi-durable";
5
6
  import { NodeExecutionEnv } from "@earendil-works/pi-durable/env/node";
6
- import { openNodeJsonlStorage } from "@earendil-works/pi-durable/storage/jsonl/node";
7
+ import { openNodeSqliteStorage } from "@earendil-works/pi-durable/storage/sqlite/node";
7
8
  import { chatBehavior } from "./behavior.js";
9
+ import { migrateJsonlToSqlite } from "./migrate-jsonl.js";
8
10
  import { RunExtension } from "./run.js";
9
11
  export async function openHarness(workingDir, models, extensions, policy) {
10
12
  const directory = join(workingDir, "durable");
11
13
  await mkdir(directory, { recursive: true });
14
+ const sqlitePath = join(directory, "pi.sqlite");
15
+ // JSONL recovery holds the whole journal in the heap. Migrate before taking the
16
+ // owner lock so a crash here does not leave a lock the next start must not steal.
17
+ if (!existsSync(sqlitePath) && existsSync(join(directory, "main.jsonl"))) {
18
+ await migrateJsonlToSqlite(directory, sqlitePath);
19
+ }
12
20
  const lockPath = join(directory, "owner.lock");
13
21
  // Never steal a lock: after an unclean exit the operator must confirm its owner is dead.
14
22
  const lock = await open(lockPath, "wx");
15
23
  try {
16
24
  await lock.writeFile(`${process.pid}\n`);
17
- const storage = await openNodeJsonlStorage(directory, BACKGROUND_CONTEXT, { fsync: true });
25
+ const storage = await openNodeSqliteStorage(sqlitePath);
18
26
  try {
19
27
  const registry = createRegistry();
20
28
  registry.install(chatBehavior(storage));
@@ -8,15 +8,17 @@ export const Sessions = defineDoc({
8
8
  initial: () => ({ items: [] }),
9
9
  checkpointWhen: () => false,
10
10
  });
11
- /** Explicit health checks reuse one tool-less conversation and never deliver to a chat. */
11
+ /** Explicit health checks create a fresh tool-less conversation each time and never deliver to a chat. */
12
12
  export async function submitHealth(harness, defaults) {
13
13
  const key = JSON.stringify(["health", "model-health"]);
14
14
  const id = await harness.commit(async (tx) => {
15
15
  const sessions = await tx.doc(Sessions);
16
- const found = sessions.items.find((item) => item.key === key);
17
- const id = found?.conversationId ?? (await tx.createConversation({ ownership: { kind: "ownerless" } })).id;
16
+ const id = (await tx.createConversation({ ownership: { kind: "ownerless" } })).id;
18
17
  await configure(tx, id, { ...defaults, tools: [], instructions: "Reply OK. Do not use tools." });
19
- if (!found)
18
+ const found = sessions.items.find((item) => item.key === key);
19
+ if (found)
20
+ found.conversationId = id;
21
+ else
20
22
  sessions.items.push({
21
23
  key,
22
24
  label: "model-health",
@@ -0,0 +1,239 @@
1
+ import { createReadStream } from "node:fs";
2
+ import { open, readdir, rename, rm, stat } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { createInterface } from "node:readline";
5
+ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
6
+ import { openNodeSqliteStorage } from "@earendil-works/pi-durable/storage/sqlite/node";
7
+ const BATCH_WRITES = 200;
8
+ const BATCH_BYTES = 4_000_000;
9
+ function isCurrentOnly(record) {
10
+ return record.scope.kind !== "conversation" || record.history === "latest";
11
+ }
12
+ function keyOf(file, seq, ordinal) {
13
+ return `${file}\t${seq}\t${ordinal}`;
14
+ }
15
+ async function indexSidecars(directory) {
16
+ const index = new Map();
17
+ const names = (await readdir(directory)).filter((name) => (name.startsWith("doc-") || name.startsWith("task-")) && name.endsWith(".jsonl"));
18
+ for (const name of names) {
19
+ const path = join(directory, name);
20
+ let offset = 0;
21
+ const lines = createInterface({ input: createReadStream(path), crlfDelay: Infinity });
22
+ for await (const line of lines) {
23
+ const bytes = Buffer.byteLength(line);
24
+ if (line.length > 0) {
25
+ const header = /^\{"format":1,"type":"record","seq":(\d+),"ordinal":(\d+),/.exec(line.slice(0, 96));
26
+ if (!header)
27
+ throw new Error(`Unreadable sidecar record in ${name}`);
28
+ index.set(keyOf(name, Number(header[1]), Number(header[2])), { path, offset, length: bytes });
29
+ }
30
+ offset += bytes + 1;
31
+ }
32
+ }
33
+ return index;
34
+ }
35
+ async function payload(index, handles, file, seq, ordinal) {
36
+ const location = index.get(keyOf(file, seq, ordinal));
37
+ if (!location)
38
+ return undefined;
39
+ let handle = handles.get(location.path);
40
+ if (!handle) {
41
+ handle = await open(location.path, "r");
42
+ handles.set(location.path, handle);
43
+ }
44
+ const buffer = Buffer.alloc(location.length);
45
+ const read = await handle.read(buffer, 0, location.length, location.offset);
46
+ if (read.bytesRead !== location.length)
47
+ throw new Error(`Short sidecar read of ${file} at sequence ${seq}`);
48
+ const record = JSON.parse(buffer.toString("utf8"));
49
+ return record.payload;
50
+ }
51
+ async function contentKind(index, handles, file, seq, ordinal) {
52
+ const body = (await payload(index, handles, file, seq, ordinal));
53
+ return body?.content?.kind;
54
+ }
55
+ async function scanMarkers(mainPath, index, handles, state) {
56
+ const lines = createInterface({ input: createReadStream(mainPath), crlfDelay: Infinity });
57
+ for await (const line of lines) {
58
+ if (line.length === 0)
59
+ continue;
60
+ const marker = JSON.parse(line);
61
+ for (const write of marker.writes) {
62
+ if (write.type === "document.create" && write.record && isCurrentOnly(write.record)) {
63
+ state.currentOnly.add(write.record.id);
64
+ }
65
+ else if (write.type === "document.retire" && write.id !== undefined) {
66
+ state.retired.add(write.id);
67
+ }
68
+ else if (write.type === "task" && write.value && "id" in write.value) {
69
+ state.taskLive.set(Number(write.value.id), false);
70
+ }
71
+ else if (write.type === "task.sidecar" && write.id !== undefined && write.ordinal !== undefined) {
72
+ state.taskLive.set(write.id, true);
73
+ state.lastLive.set(write.id, { seq: marker.seq, ordinal: write.ordinal });
74
+ }
75
+ if ((write.type === "document.create" || write.type === "document.change") &&
76
+ write.ordinal !== undefined) {
77
+ const id = write.type === "document.create" ? write.record?.id : write.id;
78
+ if (id === undefined || !state.currentOnly.has(id))
79
+ continue;
80
+ const kind = await contentKind(index, handles, `doc-${id}.jsonl`, marker.seq, write.ordinal);
81
+ if (kind !== "base")
82
+ continue;
83
+ const previous = state.latestBase.get(id);
84
+ const point = { seq: marker.seq, ordinal: write.ordinal };
85
+ if (previous === undefined ||
86
+ point.seq > previous.seq ||
87
+ (point.seq === previous.seq && point.ordinal > previous.ordinal)) {
88
+ state.latestBase.set(id, point);
89
+ }
90
+ }
91
+ }
92
+ }
93
+ }
94
+ function beforeLatestBase(state, id, seq, ordinal) {
95
+ const base = state.latestBase.get(id);
96
+ return base !== undefined && (seq < base.seq || (seq === base.seq && ordinal < base.ordinal));
97
+ }
98
+ async function writesFor(marker, state, index, handles) {
99
+ const writes = [];
100
+ for (const write of marker.writes) {
101
+ switch (write.type) {
102
+ case "conversation":
103
+ case "entry":
104
+ case "submission":
105
+ case "document.retire":
106
+ writes.push(write);
107
+ break;
108
+ case "task":
109
+ writes.push(write);
110
+ break;
111
+ case "task.sidecar": {
112
+ if (write.id === undefined || write.ordinal === undefined) {
113
+ throw new Error(`Task sidecar marker at sequence ${marker.seq} has no id`);
114
+ }
115
+ const live = state.taskLive.get(write.id) === true;
116
+ const last = state.lastLive.get(write.id);
117
+ if (!live || last?.seq !== marker.seq || last.ordinal !== write.ordinal)
118
+ break;
119
+ const body = (await payload(index, handles, `task-${write.id}.jsonl`, marker.seq, write.ordinal));
120
+ if (body?.type !== "task" || body?.value === undefined) {
121
+ throw new Error(`Missing live task sidecar ${write.id} at sequence ${marker.seq}`);
122
+ }
123
+ writes.push({ type: "task", value: body.value });
124
+ break;
125
+ }
126
+ case "document.create":
127
+ case "document.change": {
128
+ if (write.ordinal === undefined)
129
+ throw new Error(`Document marker at sequence ${marker.seq} has no ordinal`);
130
+ const id = write.type === "document.create" ? write.record?.id : write.id;
131
+ if (id === undefined)
132
+ throw new Error(`Document marker at sequence ${marker.seq} has no id`);
133
+ const reclaimed = (state.retired.has(id) && state.currentOnly.has(id)) ||
134
+ beforeLatestBase(state, id, marker.seq, write.ordinal);
135
+ const body = (await payload(index, handles, `doc-${id}.jsonl`, marker.seq, write.ordinal));
136
+ if (body === undefined && !reclaimed) {
137
+ throw new Error(`Missing document sidecar ${id} at sequence ${marker.seq}`);
138
+ }
139
+ if (body !== undefined &&
140
+ (body.type !== "document" || body.id !== id || body.content === undefined)) {
141
+ throw new Error(`Document sidecar ${id} does not match commit ${marker.seq}`);
142
+ }
143
+ if (write.type === "document.create") {
144
+ if (body?.content !== undefined && body.content.kind !== "base") {
145
+ throw new Error(`Document creation lacks a base in commit ${marker.seq}`);
146
+ }
147
+ if (!write.record)
148
+ throw new Error(`Document creation at sequence ${marker.seq} has no record`);
149
+ const content = reclaimed || body?.content === undefined
150
+ ? { kind: "base", version: 1, value: {} }
151
+ : body.content;
152
+ writes.push({ type: "document.create", record: write.record, content });
153
+ }
154
+ else if (!reclaimed && body?.content !== undefined) {
155
+ writes.push({ type: "document.change", id, content: body.content });
156
+ }
157
+ break;
158
+ }
159
+ default:
160
+ throw new Error(`Unsupported journal write ${write.type} at sequence ${marker.seq}`);
161
+ }
162
+ }
163
+ return writes;
164
+ }
165
+ /** Copy one JSONL durable directory into `sqlitePath`. Leaves the JSONL files in place. */
166
+ export async function migrateJsonlToSqlite(directory, sqlitePath) {
167
+ const mainPath = join(directory, "main.jsonl");
168
+ await stat(mainPath);
169
+ const partial = `${sqlitePath}.migrating`;
170
+ await rm(partial, { force: true });
171
+ await rm(`${partial}-wal`, { force: true });
172
+ await rm(`${partial}-shm`, { force: true });
173
+ const started = Date.now();
174
+ console.error(new Date().toISOString(), "Migrating JSONL durable storage to SQLite");
175
+ const index = await indexSidecars(directory);
176
+ const handles = new Map();
177
+ const state = {
178
+ currentOnly: new Set(),
179
+ retired: new Set(),
180
+ taskLive: new Map(),
181
+ lastLive: new Map(),
182
+ latestBase: new Map(),
183
+ };
184
+ try {
185
+ await scanMarkers(mainPath, index, handles, state);
186
+ const storage = await openNodeSqliteStorage(partial);
187
+ const pending = [];
188
+ let pendingBytes = 0;
189
+ let stored = 0;
190
+ let seen = 0;
191
+ const flush = async () => {
192
+ if (pending.length === 0)
193
+ return;
194
+ const batch = pending.splice(0, pending.length);
195
+ pendingBytes = 0;
196
+ const result = await storage.commit(batch, () => { }, BACKGROUND_CONTEXT);
197
+ if (result.refused !== undefined || result.stored !== batch.length) {
198
+ throw new Error(`SQLite refused a migrated commit after ${stored} stored`, {
199
+ cause: result.refused,
200
+ });
201
+ }
202
+ stored += result.stored;
203
+ };
204
+ const lines = createInterface({ input: createReadStream(mainPath), crlfDelay: Infinity });
205
+ try {
206
+ for await (const line of lines) {
207
+ if (line.length === 0)
208
+ continue;
209
+ seen += 1;
210
+ const writes = await writesFor(JSON.parse(line), state, index, handles);
211
+ if (writes.length === 0)
212
+ continue;
213
+ const bytes = Buffer.byteLength(line);
214
+ if (pending.length > 0 && (pending.length >= BATCH_WRITES || pendingBytes + bytes > BATCH_BYTES)) {
215
+ await flush();
216
+ }
217
+ pending.push(writes);
218
+ pendingBytes += bytes;
219
+ if (bytes > BATCH_BYTES)
220
+ await flush();
221
+ if (seen % 50000 === 0) {
222
+ console.error(new Date().toISOString(), `Migration progress ${seen} journal commits, ${stored} stored`);
223
+ }
224
+ }
225
+ await flush();
226
+ }
227
+ finally {
228
+ await storage.close(BACKGROUND_CONTEXT);
229
+ }
230
+ await rename(partial, sqlitePath);
231
+ console.error(new Date().toISOString(), `Migrated ${seen} journal commits into ${stored} SQLite commits in ${Math.round((Date.now() - started) / 1000)}s`);
232
+ }
233
+ finally {
234
+ await Promise.all([...handles.values()].map((handle) => handle.close()));
235
+ await rm(partial, { force: true });
236
+ await rm(`${partial}-wal`, { force: true });
237
+ await rm(`${partial}-shm`, { force: true });
238
+ }
239
+ }
@@ -1,4 +1,5 @@
1
- import { basename, dirname } from "node:path";
1
+ import { readFile } from "node:fs/promises";
2
+ import { basename, dirname, join } from "node:path";
2
3
  import { DefaultPackageManager, loadProjectContextFiles, loadSkills, SettingsManager, } from "@earendil-works/pi-coding-agent";
3
4
  import { defineExtension, section } from "@earendil-works/pi-durable";
4
5
  import { TOOL_SEARCH_TOOL_NAME } from "@earendil-works/pi-durable/tool-search";
@@ -13,7 +14,7 @@ function preamble(workingDir) {
13
14
  - The final reply is ONLY the message to the user. Never include planning, reasoning, analysis or meta-commentary in it.
14
15
 
15
16
  ## Environment
16
- You run directly on the host machine; be careful with system modifications. Bash working directory: ${workingDir}. It holds settings.json, extensions/<name>/, skills/, attachments/<chat>/ (files users shared) and durable/ (all conversations as JSONL; grep it for old messages).
17
+ You run directly on the host machine; be careful with system modifications. Bash working directory: ${workingDir}. It holds settings.json, extensions/<name>/, skills/, attachments/<chat>/ (files users shared) and durable/pi.sqlite (conversations and history; query it read-only with sqlite3). JSONL files beside it are the pre-migration archive.
17
18
 
18
19
  ## Messaging
19
20
  Your final answer is sent to the chat automatically. Use the send_message tool for files or extra messages.
@@ -42,11 +43,7 @@ function skillCatalog(skills) {
42
43
  ...[...groups].map(([location, lines]) => `${location}:\n${lines.join("\n")}`),
43
44
  ].join("\n\n");
44
45
  }
45
- /**
46
- * The system prompt: product instructions, AGENTS files and skills, read once per load.
47
- * `/reload` builds it again; the same extension name replaces the old one in place.
48
- */
49
- export async function loadPrompt(workingDir, agentDir) {
46
+ async function promptPieces(workingDir, agentDir) {
50
47
  const settings = SettingsManager.create(workingDir, agentDir, { projectTrusted: false });
51
48
  const packages = new DefaultPackageManager({ cwd: workingDir, agentDir, settingsManager: settings });
52
49
  // Discover installed user resources only; never install packages or execute SDK extensions headlessly.
@@ -68,18 +65,26 @@ export async function loadPrompt(workingDir, agentDir) {
68
65
  // settings.json hiddenSkills keeps rarely used skills out of the catalog; their files stay readable.
69
66
  const hidden = new Set((await readSettings(workingDir)).hiddenSkills);
70
67
  const skills = skillCatalog(loadedSkills.skills.filter((skill) => !hidden.has(skill.name)));
71
- const text = preamble(workingDir);
68
+ const project = agents.length === 0
69
+ ? undefined
70
+ : [
71
+ "Project-specific instructions and guidelines:",
72
+ ...agents.map(({ path, content }) => `<project_instructions path="${path}">\n${content}\n</project_instructions>`),
73
+ ].join("\n\n");
74
+ return { agents, preamble: preamble(workingDir), project, skills };
75
+ }
76
+ /**
77
+ * The system prompt: product instructions, AGENTS files and skills, read once per load.
78
+ * `/reload` builds it again; the same extension name replaces the old one in place.
79
+ */
80
+ export async function loadPrompt(workingDir, agentDir) {
81
+ const pieces = await promptPieces(workingDir, agentDir);
72
82
  return defineExtension({
73
83
  name: "prompt",
74
84
  sections: [
75
- section("preamble", () => text, { tag: false }),
76
- section("project_context", () => agents.length === 0
77
- ? undefined
78
- : [
79
- "Project-specific instructions and guidelines:",
80
- ...agents.map(({ path, content }) => `<project_instructions path="${path}">\n${content}\n</project_instructions>`),
81
- ].join("\n\n")),
82
- section("skills", (input) => input.agent.tools.some((tool) => tool.name === "read") ? skills : undefined),
85
+ section("preamble", () => pieces.preamble, { tag: false }),
86
+ section("project_context", () => pieces.project),
87
+ section("skills", (input) => input.agent.tools.some((tool) => tool.name === "read") ? pieces.skills : undefined),
83
88
  // Names only: the full set stays constant as tools load, so the section never changes mid-conversation.
84
89
  section("deferred-tools", ({ agent }) => {
85
90
  if (!agent.tools.some((tool) => tool.name === TOOL_SEARCH_TOOL_NAME))
@@ -94,3 +99,28 @@ export async function loadPrompt(workingDir, agentDir) {
94
99
  ],
95
100
  });
96
101
  }
102
+ /** Read-only view of the files and static prompt text. Re-read on each request; nothing is cached or written. */
103
+ export async function readPromptSources(workingDir, agentDir) {
104
+ const pieces = await promptPieces(workingDir, agentDir);
105
+ const corePath = join(workingDir, "skills", "file-memory", "core.md");
106
+ let core = null;
107
+ try {
108
+ core = { path: corePath, content: await readFile(corePath, "utf8") };
109
+ }
110
+ catch (error) {
111
+ if (error.code !== "ENOENT")
112
+ throw error;
113
+ }
114
+ const sections = [{ name: "preamble", text: pieces.preamble }];
115
+ if (pieces.project)
116
+ sections.push({ name: "project_context", text: pieces.project });
117
+ if (pieces.skills)
118
+ sections.push({ name: "skills", text: pieces.skills });
119
+ return {
120
+ view: "sources",
121
+ agents: pieces.agents,
122
+ core,
123
+ sections,
124
+ omitted: "Static text from the prompt extension, read again on each request. Deferred tool names, other extension sections, and per-turn host rules are not included.",
125
+ };
126
+ }
@@ -11,6 +11,11 @@ export const WebResults = defineDoc({
11
11
  initial: () => ({ queries: {} }),
12
12
  checkpointWhen: () => false,
13
13
  });
14
+ const FETCH_CONTENT_HEADERS = {
15
+ "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
16
+ Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
17
+ "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
18
+ };
14
19
  async function fetchBounded(url, options = {}) {
15
20
  const parsed = new URL(url);
16
21
  if (!["http:", "https:"].includes(parsed.protocol) || parsed.username || parsed.password)
@@ -75,7 +80,10 @@ export function webExtension(apiKey = process.env.BRAVE_API_KEY ?? process.env.B
75
80
  parameters: Type.Object({ url: Type.String() }),
76
81
  replay: "safe",
77
82
  async execute(args, _api, context) {
78
- const result = await fetchBounded(args.url, { signal: context.abortSignal });
83
+ const result = await fetchBounded(args.url, {
84
+ headers: FETCH_CONTENT_HEADERS,
85
+ signal: context.abortSignal,
86
+ });
79
87
  const text = result.type.includes("pdf")
80
88
  ? (await extractText(new Uint8Array(result.bytes), { mergePages: true })).text
81
89
  : result.type.includes("html")
package/dist/main.js CHANGED
@@ -386,6 +386,9 @@ reloadHttpTransport) {
386
386
  deliver() {
387
387
  return track(async () => {
388
388
  const settings = await readSettings(options.workingDir);
389
+ // Interim sends are queued on commit. SQLite commits return before that microtask
390
+ // writes the direct-send record, so settle them before deciding the final reply.
391
+ await progress.flush();
389
392
  await deliverReplies(harness, storage, async (chatGuid, text) => {
390
393
  await progress.flush();
391
394
  await options.send(chatGuid, text, settings.richText);
@@ -567,6 +570,7 @@ export async function startApplication(options) {
567
570
  if (options.web !== false) {
568
571
  web = await startWeb({
569
572
  workingDir: options.workingDir,
573
+ agentDir: options.agentDir,
570
574
  agent: messaging,
571
575
  ...options.web,
572
576
  });
package/dist/web/app.js CHANGED
@@ -10,6 +10,8 @@ document.getElementById("connection")?.remove();
10
10
  let data = JSON.parse(state.textContent);
11
11
  let chats = [];
12
12
  let memoryQuery = { q: "", namespace: "", kind: "", status: "active", page: 1 };
13
+ let memoryTab = new URLSearchParams(location.search).get("tab");
14
+ if (memoryTab !== "agents" && memoryTab !== "prompt") memoryTab = "records";
13
15
  let refreshing = false;
14
16
 
15
17
  document.body.classList.add(`page-${page.slice(1)}`);
@@ -383,6 +385,25 @@ function renderMemory() {
383
385
  view.append(pagination);
384
386
  }
385
387
 
388
+ function renderPrompt() {
389
+ toolbar.replaceChildren();
390
+ setupToolbar();
391
+ view.replaceChildren(element("p", data.omitted || "Read-only.", "muted"));
392
+ const files =
393
+ memoryTab === "agents"
394
+ ? [
395
+ ...(data.agents || []).map((file) => [file.path, file.content]),
396
+ ...(data.core ? [[data.core.path, data.core.content]] : []),
397
+ ]
398
+ : (data.sections || []).map((section) => [section.name, section.text]);
399
+ if (!files.length) view.append(element("p", "Nothing to show.", "empty"));
400
+ for (const [title, text] of files) {
401
+ const block = element("section", undefined, "prompt-block");
402
+ block.append(element("h2", title), element("pre", text));
403
+ view.append(block);
404
+ }
405
+ }
406
+
386
407
  function renderSettings() {
387
408
  view.replaceChildren(
388
409
  element(
@@ -590,22 +611,30 @@ function renderScheduled() {
590
611
  if (!runs.length) body.append(element("p", "No executions yet.", "empty"));
591
612
  return body;
592
613
  }
593
- for (const job of data.jobs || []) {
614
+ function formatTokens(count) {
615
+ if (typeof count !== "number" || count <= 0) return "0 tok";
616
+ if (count >= 1_000_000) return `${(count / 1_000_000).toFixed(1)}M tok`;
617
+ if (count >= 1_000) return `${(count / 1_000).toFixed(1)}k tok`;
618
+ return `${count} tok`;
619
+ }
620
+ const jobs = (data.jobs || [])
621
+ .filter((job) => job.enabled)
622
+ .toSorted((a, b) => (b.tokens || 0) - (a.tokens || 0));
623
+ for (const job of jobs) {
594
624
  const details = element("details", undefined, "schedule-row");
595
625
  details.id = `schedule-history-${job.id}`;
596
626
  const latest = job.runs?.[0];
597
- const status = !job.enabled
598
- ? "disabled"
599
- : ["aborted", "faulted", "failed", "missing"].includes(job.status)
600
- ? job.status
601
- : latest
602
- ? [latest.status, latest.delivery].filter(Boolean).join(" / ")
603
- : "enabled";
627
+ const status = ["aborted", "faulted", "failed", "missing"].includes(job.status)
628
+ ? job.status
629
+ : latest
630
+ ? [latest.status, latest.delivery].filter(Boolean).join(" / ")
631
+ : "enabled";
604
632
  const lastRun = latest ? time(latest.input?.startedAt, job.timezone) : "No executions yet";
605
633
  const cadence = job.time !== undefined ? `daily ${job.time}` : `every ${job.intervalMs / 3600000}h`;
606
634
  const summary = element("summary", undefined, "schedule-summary");
607
635
  summary.append(
608
636
  element("span", job.name, "schedule-name"),
637
+ element("span", formatTokens(job.tokens), "schedule-tokens"),
609
638
  element(
610
639
  "span",
611
640
  `${cadence} / Next: ${time(job.nextAt, job.timezone)} (${job.timezone})`,
@@ -617,7 +646,7 @@ function renderScheduled() {
617
646
  details.append(summary, history(job.runs || [], job.conversationId, job.timezone));
618
647
  view.append(details);
619
648
  }
620
- if (!data.jobs?.length) view.append(element("p", "No scheduled tasks.", "empty"));
649
+ if (!jobs.length) view.append(element("p", "No scheduled tasks.", "empty"));
621
650
  }
622
651
 
623
652
  function renderTasks() {
@@ -731,6 +760,32 @@ function renderTasks() {
731
760
  }
732
761
  }
733
762
 
763
+ function memoryTabs() {
764
+ const nav = element("nav", undefined, "memory-tabs");
765
+ nav.setAttribute("aria-label", "Memory views");
766
+ for (const [id, label] of [
767
+ ["records", "Records"],
768
+ ["agents", "AGENTS"],
769
+ ["prompt", "System prompt"],
770
+ ]) {
771
+ const button = element("button", label);
772
+ button.type = "button";
773
+ if (memoryTab === id) button.setAttribute("aria-current", "page");
774
+ button.addEventListener("click", () => {
775
+ if (memoryTab === id) return;
776
+ memoryTab = id;
777
+ const url = new URL(location.href);
778
+ if (id === "records") url.searchParams.delete("tab");
779
+ else url.searchParams.set("tab", id);
780
+ history.replaceState(null, "", url);
781
+ void refresh();
782
+ main.scrollTop = 0;
783
+ });
784
+ nav.append(button);
785
+ }
786
+ return nav;
787
+ }
788
+
734
789
  function setupToolbar() {
735
790
  if (page === "/chat" || page === "/tasks") {
736
791
  if (conversationId) {
@@ -738,7 +793,9 @@ function setupToolbar() {
738
793
  toolbar.append(page === "/chat" ? link("< Messages", "/") : link("< Recent conversations", "/tasks"));
739
794
  }
740
795
  } else if (page === "/memory") {
741
- const records = Array.isArray(data) ? memoryRows() : data.records;
796
+ toolbar.append(memoryTabs());
797
+ if (memoryTab !== "records") return;
798
+ const records = Array.isArray(data) ? memoryRows() : data.records || [];
742
799
  const form = element("form", undefined, "toolbar");
743
800
  const searchLabel = element("label", "Search text / subjects / sources", "search");
744
801
  const search = element("input");
@@ -792,8 +849,10 @@ async function render() {
792
849
  Array.from(view.querySelectorAll(".card"), (card) => [card.id, card.scrollTop]),
793
850
  );
794
851
  if (page === "/chat") await loadChats();
795
- else if (page === "/memory") renderMemory();
796
- else if (page === "/settings") renderSettings();
852
+ else if (page === "/memory") {
853
+ if (memoryTab === "records") renderMemory();
854
+ else renderPrompt();
855
+ } else if (page === "/settings") renderSettings();
797
856
  else if (page === "/chats") renderChatSettings();
798
857
  else if (page === "/logs") renderLogs();
799
858
  else if (page === "/tasks") renderTasks();
@@ -812,8 +871,9 @@ async function refresh() {
812
871
  const query = new URLSearchParams(location.search);
813
872
  if (page === "/chat") query.set("view", conversationId ? "display" : "overview");
814
873
  if (page === "/memory") {
815
- query.set("view", "records");
816
- for (const [key, value] of Object.entries(memoryQuery)) query.set(key, String(value));
874
+ query.set("view", memoryTab === "records" ? "records" : "sources");
875
+ if (memoryTab === "records")
876
+ for (const [key, value] of Object.entries(memoryQuery)) query.set(key, String(value));
817
877
  }
818
878
  data = await fetchData(`${page}/data?${query}`);
819
879
  state.textContent = JSON.stringify(data, null, 2);
@@ -1,11 +1,49 @@
1
1
  import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
2
+ import { UsageDoc, } from "@earendil-works/pi-durable";
2
3
  import { DirectSends } from "../agent/direct-send.js";
3
4
  import { EXECUTION_KIND, Schedules } from "../agent/scheduling.js";
5
+ function sumUsageTokens(usage) {
6
+ let total = 0;
7
+ for (const bucket of [usage.models, usage.tools]) {
8
+ for (const item of Object.values(bucket)) {
9
+ total += item.totalTokens || item.input + item.output + item.cacheRead + item.cacheWrite;
10
+ }
11
+ }
12
+ return total;
13
+ }
4
14
  /** Native occurrence tasks are the execution history; this view keeps no parallel log. */
5
- export function readSchedules(harness) {
6
- return harness.commit(async (tx) => {
15
+ export async function readSchedules(harness) {
16
+ const { jobs, conversationsByRoot } = await harness.commit(async (tx) => {
7
17
  const schedules = await tx.doc(Schedules);
8
18
  const sends = await tx.doc(DirectSends);
19
+ const roots = new Set(schedules.items.map((schedule) => schedule.conversationId));
20
+ const conversationsByRoot = new Map(schedules.items.map((schedule) => [schedule.conversationId, [schedule.conversationId]]));
21
+ if (roots.size > 0) {
22
+ const ownerOf = new Map();
23
+ let cursor;
24
+ do {
25
+ const page = await tx.scanConversations({}, 500, cursor);
26
+ for (const conversation of page.items) {
27
+ if (conversation.owner)
28
+ ownerOf.set(conversation.id, conversation.owner.conversationId);
29
+ }
30
+ cursor = page.next;
31
+ } while (cursor);
32
+ for (const id of ownerOf.keys()) {
33
+ if (roots.has(id))
34
+ continue;
35
+ const seen = new Set([id]);
36
+ let current = ownerOf.get(id);
37
+ while (current !== undefined && !seen.has(current)) {
38
+ if (roots.has(current)) {
39
+ conversationsByRoot.get(current)?.push(id);
40
+ break;
41
+ }
42
+ seen.add(current);
43
+ current = ownerOf.get(current);
44
+ }
45
+ }
46
+ }
9
47
  const jobs = [];
10
48
  for (const schedule of schedules.items) {
11
49
  const task = await tx.task(schedule.taskId);
@@ -49,15 +87,27 @@ export function readSchedules(harness) {
49
87
  status: task?.state.outcome?.status ?? task?.state.status ?? "missing",
50
88
  phase: state?.phase,
51
89
  nextAt: state?.phase === "sleep" ? state.at : undefined,
90
+ tokens: 0,
52
91
  runs,
53
92
  });
54
93
  }
55
- return {
56
- jobs,
57
- recent: jobs
58
- .flatMap((job) => job.runs.map((run) => ({ ...run, jobId: job.id, name: job.name })))
59
- .sort((a, b) => b.id - a.id)
60
- .slice(0, 10),
61
- };
94
+ return { jobs, conversationsByRoot };
62
95
  }, BACKGROUND_CONTEXT);
96
+ for (const job of jobs) {
97
+ let tokens = 0;
98
+ for (const id of conversationsByRoot.get(job.conversationId) ?? [job.conversationId]) {
99
+ const state = await harness.snapshot(UsageDoc, id, BACKGROUND_CONTEXT);
100
+ if (state)
101
+ tokens += sumUsageTokens(state);
102
+ }
103
+ job.tokens = tokens;
104
+ }
105
+ jobs.sort((a, b) => b.tokens - a.tokens);
106
+ return {
107
+ jobs,
108
+ recent: jobs
109
+ .flatMap((job) => job.runs.map((run) => ({ ...run, jobId: job.id, name: job.name })))
110
+ .sort((a, b) => b.id - a.id)
111
+ .slice(0, 10),
112
+ };
63
113
  }
@@ -9,6 +9,7 @@ import { LiveDoc, } from "@earendil-works/pi-durable";
9
9
  import { Chats, interimEnabled, progressEnabled } from "../agent/chats.js";
10
10
  import { DirectSends } from "../agent/direct-send.js";
11
11
  import { Sessions } from "../agent/health.js";
12
+ import { readPromptSources } from "../agent/prompt.js";
12
13
  import { Deliveries } from "../agent/replies.js";
13
14
  import { Schedules } from "../agent/scheduling.js";
14
15
  import { isReplyEnabled, readSettings } from "../config/settings.js";
@@ -344,7 +345,15 @@ export async function startWeb(options) {
344
345
  throw error;
345
346
  });
346
347
  const namespaces = files.filter((file) => file.endsWith(".jsonl")).sort();
347
- if (!url.pathname.endsWith("/data") || url.searchParams.get("view") === "records") {
348
+ const tab = url.searchParams.get("tab");
349
+ const sources = url.searchParams.get("view") === "sources" ||
350
+ (!url.pathname.endsWith("/data") && (tab === "agents" || tab === "prompt"));
351
+ if (sources) {
352
+ if (!options.agentDir)
353
+ throw new Error("agentDir is required");
354
+ value = await readPromptSources(options.workingDir, options.agentDir);
355
+ }
356
+ else if (!url.pathname.endsWith("/data") || url.searchParams.get("view") === "records") {
348
357
  const records = await Promise.all(namespaces.map(async (file) => parseMemoryFile(await readFile(join(root, file), "utf8"), file.slice(0, -6))));
349
358
  value = memoryPage(records, url.searchParams);
350
359
  compact = true;
@@ -313,6 +313,24 @@ pre {
313
313
  margin: 16px 0;
314
314
  }
315
315
 
316
+ .memory-tabs {
317
+ display: flex;
318
+ gap: 8px;
319
+ margin: 0 0 16px;
320
+ }
321
+
322
+ .memory-tabs button[aria-current="page"] {
323
+ border-color: #ccc;
324
+ }
325
+
326
+ .prompt-block {
327
+ margin: 0 0 20px;
328
+ }
329
+
330
+ .prompt-block h2 {
331
+ margin-bottom: 8px;
332
+ }
333
+
316
334
  .memory-record {
317
335
  max-height: min(560px, 70dvh);
318
336
  overflow: auto;
@@ -447,8 +465,11 @@ body.page-logs .native-state {
447
465
 
448
466
  .schedule-summary {
449
467
  display: grid;
450
- grid-template-columns: 16px minmax(160px, 1fr) minmax(400px, 2fr) minmax(240px, 1.2fr) minmax(100px, 0.6fr);
451
- min-width: 980px;
468
+ grid-template-columns: 16px minmax(160px, 1fr) minmax(88px, 0.5fr) minmax(380px, 2fr) minmax(220px, 1.2fr) minmax(
469
+ 100px,
470
+ 0.6fr
471
+ );
472
+ min-width: 1060px;
452
473
  align-items: center;
453
474
  gap: 10px;
454
475
  padding: 12px 16px;
@@ -469,6 +490,7 @@ body.page-logs .native-state {
469
490
  }
470
491
 
471
492
  .schedule-name,
493
+ .schedule-tokens,
472
494
  .schedule-next,
473
495
  .schedule-last,
474
496
  .schedule-status {
@@ -478,6 +500,7 @@ body.page-logs .native-state {
478
500
  white-space: nowrap;
479
501
  }
480
502
 
503
+ .schedule-tokens,
481
504
  .schedule-next,
482
505
  .schedule-last,
483
506
  .schedule-status {
@@ -485,6 +508,10 @@ body.page-logs .native-state {
485
508
  white-space: nowrap;
486
509
  }
487
510
 
511
+ .schedule-tokens {
512
+ text-align: right;
513
+ }
514
+
488
515
  [hidden] {
489
516
  display: none;
490
517
  }
@@ -100,7 +100,7 @@ agent/chats.ts
100
100
  Save row cursor after acceptance; steer if busy
101
101
  |
102
102
  v
103
- Pi Durable Harness <--------> durable/ (JSONL)
103
+ Pi Durable Harness <--------> durable/pi.sqlite
104
104
  | |
105
105
  | final answer +--> web/ (history and live state)
106
106
  v
@@ -113,8 +113,10 @@ agent/deliver.ts
113
113
 
114
114
  ### Inside the Harness
115
115
 
116
- These concepts and files are native to Pi Durable's JSONL storage.
117
- Paths are relative to `WORKING_DIR/durable/`.
116
+ Runtime storage is SQLite at `WORKING_DIR/durable/pi.sqlite` (since 2026-11-27).
117
+ Startup reads live rows, not the whole history. A JSONL directory left beside
118
+ the database is the archive from before that migration and is not opened.
119
+ The table lists the logical records. The file column is the old JSONL layout.
118
120
 
119
121
  | Member | Role | File |
120
122
  |---|---|---|
package/docs/install.md CHANGED
@@ -97,6 +97,11 @@ temporary HOME/workspace without models or Messages.
97
97
  `.github/workflows/publish.yml` uses the existing npm trusted publisher with
98
98
  GitHub OIDC, Node 24 and `id-token: write`; no local npm login or token is needed.
99
99
  It runs the full checks, tests and package smoke before publishing with provenance.
100
+ After `npm publish` succeeds, a separate `release` job with `contents: write`
101
+ creates the GitHub Release as `github-actions[bot]` if it does not already exist,
102
+ using the annotated tag message when present (create annotated tags with
103
+ `--cleanup=verbatim` so Markdown headings are preserved) or GitHub's generated
104
+ notes otherwise.
100
105
  Future releases push a matching `v<package-version>` tag. To publish an existing
101
106
  version after fixing packaging, dispatch the workflow on main with that exact
102
107
  version; never move an already published GitHub tag.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kingcrab/pi-imessage",
3
- "version": "1.2.2",
3
+ "version": "1.2.4",
4
4
  "description": "A minimal, self-managing iMessage bot powered by Pi Durable",
5
5
  "license": "MIT",
6
6
  "repository": {