@kingcrab/pi-imessage 1.2.3 → 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));
@@ -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
+ }
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(
@@ -739,6 +760,32 @@ function renderTasks() {
739
760
  }
740
761
  }
741
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
+
742
789
  function setupToolbar() {
743
790
  if (page === "/chat" || page === "/tasks") {
744
791
  if (conversationId) {
@@ -746,7 +793,9 @@ function setupToolbar() {
746
793
  toolbar.append(page === "/chat" ? link("< Messages", "/") : link("< Recent conversations", "/tasks"));
747
794
  }
748
795
  } else if (page === "/memory") {
749
- 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 || [];
750
799
  const form = element("form", undefined, "toolbar");
751
800
  const searchLabel = element("label", "Search text / subjects / sources", "search");
752
801
  const search = element("input");
@@ -800,8 +849,10 @@ async function render() {
800
849
  Array.from(view.querySelectorAll(".card"), (card) => [card.id, card.scrollTop]),
801
850
  );
802
851
  if (page === "/chat") await loadChats();
803
- else if (page === "/memory") renderMemory();
804
- else if (page === "/settings") renderSettings();
852
+ else if (page === "/memory") {
853
+ if (memoryTab === "records") renderMemory();
854
+ else renderPrompt();
855
+ } else if (page === "/settings") renderSettings();
805
856
  else if (page === "/chats") renderChatSettings();
806
857
  else if (page === "/logs") renderLogs();
807
858
  else if (page === "/tasks") renderTasks();
@@ -820,8 +871,9 @@ async function refresh() {
820
871
  const query = new URLSearchParams(location.search);
821
872
  if (page === "/chat") query.set("view", conversationId ? "display" : "overview");
822
873
  if (page === "/memory") {
823
- query.set("view", "records");
824
- 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));
825
877
  }
826
878
  data = await fetchData(`${page}/data?${query}`);
827
879
  state.textContent = JSON.stringify(data, null, 2);
@@ -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;
@@ -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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kingcrab/pi-imessage",
3
- "version": "1.2.3",
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": {