@tenonai/yew 0.0.0-stage → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/CHANGELOG.md +296 -0
  2. package/LICENSE +21 -0
  3. package/README.md +55 -2
  4. package/THIRD-PARTY-NOTICES.md +122 -0
  5. package/bin/yew.js +9 -0
  6. package/dist/cli/app.js +198 -0
  7. package/dist/cli/export.js +57 -0
  8. package/dist/cli/io.js +65 -0
  9. package/dist/cli/key.js +113 -0
  10. package/dist/cli/main.js +44 -0
  11. package/dist/cli/mcp.js +76 -0
  12. package/dist/cli/remote.js +116 -0
  13. package/dist/cli/run.js +72 -0
  14. package/dist/cli/schedule.js +123 -0
  15. package/dist/cli/send.js +126 -0
  16. package/dist/cli/serve.js +301 -0
  17. package/dist/cli/service.js +241 -0
  18. package/dist/cli/system.js +44 -0
  19. package/dist/remote/access.js +107 -0
  20. package/dist/remote/connector.js +278 -0
  21. package/dist/remote/identity.js +71 -0
  22. package/dist/remote/noise.js +287 -0
  23. package/dist/remote/protocol.js +51 -0
  24. package/dist/remote/push.js +37 -0
  25. package/dist/server/agent/compaction.js +242 -0
  26. package/dist/server/agent/context.js +119 -0
  27. package/dist/server/agent/held.js +48 -0
  28. package/dist/server/agent/helper.js +122 -0
  29. package/dist/server/agent/mailroom.js +510 -0
  30. package/dist/server/agent/prompt.js +268 -0
  31. package/dist/server/agent/runner.js +1159 -0
  32. package/dist/server/artifacts.js +216 -0
  33. package/dist/server/budget.js +88 -0
  34. package/dist/server/data-export.js +105 -0
  35. package/dist/server/data-usage.js +143 -0
  36. package/dist/server/db/database.js +49 -0
  37. package/dist/server/db/migrations.js +347 -0
  38. package/dist/server/errors.js +16 -0
  39. package/dist/server/events.js +17 -0
  40. package/dist/server/export.js +378 -0
  41. package/dist/server/folder-picker.js +32 -0
  42. package/dist/server/from-jig.js +98 -0
  43. package/dist/server/http/agents.js +78 -0
  44. package/dist/server/http/api.js +468 -0
  45. package/dist/server/http/app.js +111 -0
  46. package/dist/server/http/artifacts.js +53 -0
  47. package/dist/server/http/data.js +54 -0
  48. package/dist/server/http/devices.js +47 -0
  49. package/dist/server/http/events.js +134 -0
  50. package/dist/server/http/idempotency.js +53 -0
  51. package/dist/server/http/input.js +106 -0
  52. package/dist/server/http/mail.js +52 -0
  53. package/dist/server/http/mcp.js +134 -0
  54. package/dist/server/http/notes.js +91 -0
  55. package/dist/server/http/problem.js +55 -0
  56. package/dist/server/http/providers.js +131 -0
  57. package/dist/server/http/schedules.js +58 -0
  58. package/dist/server/http/search.js +42 -0
  59. package/dist/server/http/security.js +168 -0
  60. package/dist/server/http/skills.js +53 -0
  61. package/dist/server/http/system.js +26 -0
  62. package/dist/server/ids.js +30 -0
  63. package/dist/server/keys.js +51 -0
  64. package/dist/server/mail/envelope.js +152 -0
  65. package/dist/server/mail/post.js +603 -0
  66. package/dist/server/mail/store.js +279 -0
  67. package/dist/server/manage.js +601 -0
  68. package/dist/server/mcp-builtin.js +179 -0
  69. package/dist/server/mcp-config.js +305 -0
  70. package/dist/server/mcp-oauth.js +448 -0
  71. package/dist/server/mcp.js +668 -0
  72. package/dist/server/model/gateway.js +410 -0
  73. package/dist/server/paths.js +34 -0
  74. package/dist/server/permissions/engine.js +249 -0
  75. package/dist/server/permissions/paths.js +93 -0
  76. package/dist/server/permissions/shell.js +635 -0
  77. package/dist/server/push.js +345 -0
  78. package/dist/server/reveal.js +36 -0
  79. package/dist/server/runtime.js +17 -0
  80. package/dist/server/schedules.js +356 -0
  81. package/dist/server/settings.js +80 -0
  82. package/dist/server/skills.js +262 -0
  83. package/dist/server/store.js +1077 -0
  84. package/dist/server/tools/files.js +318 -0
  85. package/dist/server/tools/html.js +221 -0
  86. package/dist/server/tools/jobs.js +38 -0
  87. package/dist/server/tools/mail.js +680 -0
  88. package/dist/server/tools/match.js +81 -0
  89. package/dist/server/tools/misc.js +253 -0
  90. package/dist/server/tools/process.js +128 -0
  91. package/dist/server/tools/read-state.js +40 -0
  92. package/dist/server/tools/registry.js +43 -0
  93. package/dist/server/tools/search.js +175 -0
  94. package/dist/server/tools/shell.js +124 -0
  95. package/dist/server/tools/types.js +43 -0
  96. package/dist/server/tools/web-search.js +198 -0
  97. package/dist/server/tools/web.js +240 -0
  98. package/dist/shared/cron.js +105 -0
  99. package/dist/shared/mcp-presets.js +170 -0
  100. package/dist/shared/messages.js +45 -0
  101. package/dist/shared/policy.js +42 -0
  102. package/dist/shared/types.js +34 -0
  103. package/dist/shared/version.js +8 -0
  104. package/mcp-builtin/package-lock.json +3398 -0
  105. package/mcp-builtin/package.json +14 -0
  106. package/mcp-builtin/presets/gitee/package-lock.json +105 -0
  107. package/mcp-builtin/presets/gitee/package.json +10 -0
  108. package/mcp-builtin/presets/notion/package-lock.json +2243 -0
  109. package/mcp-builtin/presets/notion/package.json +10 -0
  110. package/mcp-builtin/presets/sentry/package-lock.json +28 -0
  111. package/mcp-builtin/presets/sentry/package.json +10 -0
  112. package/package.json +75 -5
  113. package/web/dist/THIRD-PARTY-NOTICES.txt +1944 -0
  114. package/web/dist/assets/index-B9oWPSod.css +1 -0
  115. package/web/dist/assets/index-C5qBMzFX.js +68 -0
  116. package/web/dist/icons/app-icon.png +0 -0
  117. package/web/dist/icons/apple-touch-icon.png +0 -0
  118. package/web/dist/icons/favicon-16.png +0 -0
  119. package/web/dist/icons/favicon-32.png +0 -0
  120. package/web/dist/icons/favicon-64.png +0 -0
  121. package/web/dist/icons/tenon-mark.svg +1 -0
  122. package/web/dist/icons/yew-mark.svg +1 -0
  123. package/web/dist/index.html +18 -0
  124. package/web/dist/mascot/gift.webp +0 -0
  125. package/web/dist/mascot/greeting.webp +0 -0
  126. package/web/dist/mascot/happy.webp +0 -0
  127. package/web/dist/mascot/lost.webp +0 -0
  128. package/web/dist/mascot/shush.webp +0 -0
  129. package/web/dist/mascot/sleepy.webp +0 -0
  130. package/web/dist/mascot/sorry.webp +0 -0
  131. package/web/dist/mascot/thinking.webp +0 -0
  132. package/web/dist/mascot/waking.webp +0 -0
  133. package/web/dist/mascot/writing.webp +0 -0
@@ -0,0 +1,1077 @@
1
+ import { messageText } from "../shared/messages.js";
2
+ import { localDay } from "./budget.js";
3
+ import { json, transaction } from "./db/database.js";
4
+ import { conflict, invalid, notFound } from "./errors.js";
5
+ import { newId } from "./ids.js";
6
+ import { inheritableRules } from "./permissions/engine.js";
7
+ export const MATCH_START = "\u0002";
8
+ export const MATCH_END = "\u0003";
9
+ function usageTotals(row) {
10
+ return {
11
+ cost: row.cost,
12
+ input: row.input,
13
+ output: row.output,
14
+ cacheRead: row.cache_read,
15
+ cacheWrite: row.cache_write,
16
+ };
17
+ }
18
+ const MODEL_ROLES = "('system', 'user', 'assistant', 'toolResult')";
19
+ const NAME_MAX = 60;
20
+ function toSession(row) {
21
+ return {
22
+ id: row.id,
23
+ name: row.name,
24
+ kind: row.kind,
25
+ groupId: row.group_id,
26
+ responsibility: row.responsibility,
27
+ cwd: row.cwd,
28
+ provider: row.provider,
29
+ model: row.model,
30
+ thinking: row.thinking,
31
+ rules: json(row.rules, []),
32
+ options: json(row.options, {}),
33
+ todos: json(row.todos, []),
34
+ status: row.status,
35
+ statusDetail: row.status_detail,
36
+ pinned: row.pinned === 1,
37
+ unread: row.unread,
38
+ archivedAt: row.archived_at,
39
+ usage: {
40
+ input: row.usage_input,
41
+ output: row.usage_output,
42
+ cacheRead: row.usage_cache_read,
43
+ cacheWrite: row.usage_cache_write,
44
+ cost: row.usage_cost,
45
+ },
46
+ contextTokens: row.context_tokens,
47
+ eventSeq: row.event_seq,
48
+ parentId: row.parent_id,
49
+ outcome: row.outcome,
50
+ interventions: row.interventions,
51
+ lettersSent: row.letters_sent,
52
+ lastActivityAt: row.last_activity_at,
53
+ createdAt: row.created_at,
54
+ updatedAt: row.updated_at,
55
+ };
56
+ }
57
+ function toDevice(row) {
58
+ return {
59
+ id: row.id,
60
+ name: row.name,
61
+ publicKey: row.public_key,
62
+ push: row.push === 1,
63
+ canPush: row.push_token !== null,
64
+ createdAt: row.created_at,
65
+ lastSeenAt: row.last_seen_at,
66
+ };
67
+ }
68
+ function toGroup(row) {
69
+ return {
70
+ id: row.id,
71
+ name: row.name,
72
+ position: row.position,
73
+ createdAt: row.created_at,
74
+ updatedAt: row.updated_at,
75
+ };
76
+ }
77
+ function toEntry(row) {
78
+ const body = JSON.parse(row.body);
79
+ return {
80
+ ...body,
81
+ id: row.id,
82
+ sessionId: row.session_id,
83
+ seq: row.seq,
84
+ createdAt: row.created_at,
85
+ };
86
+ }
87
+ function toToolCall(row) {
88
+ return {
89
+ id: row.id,
90
+ sessionId: row.session_id,
91
+ messageId: row.message_id,
92
+ callId: row.call_id,
93
+ tool: row.tool,
94
+ args: JSON.parse(row.args),
95
+ status: row.status,
96
+ detail: json(row.detail, null),
97
+ resultMessageId: row.result_message_id,
98
+ startedAt: row.started_at,
99
+ finishedAt: row.finished_at,
100
+ createdAt: row.created_at,
101
+ };
102
+ }
103
+ function toApproval(row) {
104
+ return {
105
+ id: row.id,
106
+ sessionId: row.session_id,
107
+ toolCallId: row.tool_call_id,
108
+ kind: row.kind,
109
+ request: JSON.parse(row.request),
110
+ status: row.status,
111
+ response: json(row.response, null),
112
+ createdAt: row.created_at,
113
+ resolvedAt: row.resolved_at,
114
+ };
115
+ }
116
+ function toQueued(row) {
117
+ const body = JSON.parse(row.body);
118
+ return {
119
+ id: row.id,
120
+ sessionId: row.session_id,
121
+ text: body.text,
122
+ createdAt: row.created_at,
123
+ updatedAt: row.updated_at,
124
+ };
125
+ }
126
+ /** Text indexed for search: what people and the model wrote, not thinking or tool output. */
127
+ function searchableText(body) {
128
+ if (body.role === "user")
129
+ return messageText(body.message);
130
+ if (body.role === "assistant") {
131
+ return body.message.content
132
+ .filter((block) => block.type === "text")
133
+ .map((block) => block.text)
134
+ .join("\n");
135
+ }
136
+ return "";
137
+ }
138
+ export function validateSessionName(name) {
139
+ if (typeof name !== "string")
140
+ throw invalid("The name must be text.", "name");
141
+ const trimmed = name.trim();
142
+ if (trimmed.length === 0)
143
+ throw invalid("The name cannot be empty.", "name");
144
+ if ([...trimmed].length > NAME_MAX) {
145
+ throw invalid(`The name can be at most ${NAME_MAX} characters.`, "name");
146
+ }
147
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: rejecting control characters is the point
148
+ if (/[\u0000-\u001f\u007f@]/.test(trimmed)) {
149
+ throw invalid("The name cannot contain @ or control characters.", "name");
150
+ }
151
+ return trimmed;
152
+ }
153
+ /**
154
+ * All reads and writes of Yew's data. Every change to a session's transcript appends a durable event
155
+ * with the session's next sequence number; events are published on the bus only after the transaction
156
+ * that wrote them commits.
157
+ */
158
+ /** What a taken-back entry keeps: its role and time, without content (blueprint 6.11, item 42). */
159
+ const TAKEN_BACK = "json_object('role', role, 'content', json('[]'), 'timestamp', created_at)";
160
+ export class Store {
161
+ db;
162
+ #bus;
163
+ #statements = new Map();
164
+ #pending = null;
165
+ constructor(db, bus) {
166
+ this.db = db;
167
+ this.#bus = bus;
168
+ }
169
+ #q(sql) {
170
+ let statement = this.#statements.get(sql);
171
+ if (!statement) {
172
+ statement = this.db.prepare(sql);
173
+ this.#statements.set(sql, statement);
174
+ }
175
+ return statement;
176
+ }
177
+ /** One write transaction; bus events raised inside it go out after it commits. */
178
+ tx(fn) {
179
+ if (this.#pending)
180
+ return fn();
181
+ this.#pending = [];
182
+ let events = [];
183
+ try {
184
+ const result = transaction(this.db, fn);
185
+ events = this.#pending;
186
+ return result;
187
+ }
188
+ finally {
189
+ this.#pending = null;
190
+ for (const event of events)
191
+ this.#bus.publish(event);
192
+ }
193
+ }
194
+ #publish(event) {
195
+ if (this.#pending)
196
+ this.#pending.push(event);
197
+ else
198
+ this.#bus.publish(event);
199
+ }
200
+ /** Publishes a global event; inside a transaction it waits for the commit. */
201
+ publish(event) {
202
+ this.#publish({ scope: "global", event });
203
+ }
204
+ /** Publishes an ephemeral event right away (drafts, live tool output). */
205
+ live(sessionId, event) {
206
+ this.#bus.publish({ scope: "live", sessionId, event });
207
+ }
208
+ // --- events ---
209
+ appendEvent(sessionId, event) {
210
+ return this.tx(() => {
211
+ const row = this.#q("UPDATE sessions SET event_seq = event_seq + 1 WHERE id = ? RETURNING event_seq").get(sessionId);
212
+ if (!row)
213
+ throw notFound("Session", sessionId);
214
+ this.#q("INSERT INTO session_events (session_id, seq, type, data, created_at) VALUES (?, ?, ?, ?, ?)").run(sessionId, row.event_seq, event.type, JSON.stringify(event), Date.now());
215
+ this.#publish({ scope: "session", sessionId, seq: row.event_seq, event });
216
+ return row.event_seq;
217
+ });
218
+ }
219
+ /** Events after `seq`, oldest first. `complete` is false when older events were pruned. */
220
+ eventsAfter(sessionId, seq, limit = 1000) {
221
+ const oldest = this.#q("SELECT MIN(seq) AS seq FROM session_events WHERE session_id = ?").get(sessionId);
222
+ const rows = this.#q("SELECT seq, data FROM session_events WHERE session_id = ? AND seq > ? ORDER BY seq LIMIT ?").all(sessionId, seq, limit);
223
+ const complete = oldest.seq === null || oldest.seq <= seq + 1;
224
+ return {
225
+ events: rows.map((row) => ({ seq: row.seq, event: JSON.parse(row.data) })),
226
+ complete,
227
+ };
228
+ }
229
+ pruneEvents(olderThan) {
230
+ this.#q("DELETE FROM session_events WHERE created_at < ?").run(olderThan);
231
+ }
232
+ // --- devices (M3 plan, section 4) ---
233
+ listDevices() {
234
+ const rows = this.#q("SELECT * FROM devices ORDER BY created_at, id").all();
235
+ return rows.map(toDevice);
236
+ }
237
+ deviceByKey(publicKey) {
238
+ const row = this.#q("SELECT * FROM devices WHERE public_key = ?").get(publicKey);
239
+ return row ? toDevice(row) : null;
240
+ }
241
+ addDevice(name, publicKey) {
242
+ return this.tx(() => {
243
+ const id = newId();
244
+ const now = Date.now();
245
+ this.#q("INSERT INTO devices (id, name, public_key, created_at, last_seen_at) VALUES (?, ?, ?, ?, ?)").run(id, name, publicKey, now, now);
246
+ this.#devicesChanged();
247
+ return this.#device(id);
248
+ });
249
+ }
250
+ updateDevice(id, patch) {
251
+ return this.tx(() => {
252
+ const current = this.#device(id);
253
+ this.#q("UPDATE devices SET name = ?, push = ? WHERE id = ?").run(patch.name ?? current.name, (patch.push ?? current.push) ? 1 : 0, id);
254
+ if (patch.pushToken !== undefined) {
255
+ this.#q("UPDATE devices SET push_token = ? WHERE id = ?").run(patch.pushToken, id);
256
+ }
257
+ this.#devicesChanged();
258
+ return this.#device(id);
259
+ });
260
+ }
261
+ /** A paired phone connected; noted at most once a minute. */
262
+ touchDevice(id) {
263
+ const now = Date.now();
264
+ this.#q("UPDATE devices SET last_seen_at = ? WHERE id = ? AND (last_seen_at IS NULL OR last_seen_at < ?)").run(now, id, now - 60_000);
265
+ }
266
+ deleteDevice(id) {
267
+ this.tx(() => {
268
+ this.#device(id);
269
+ this.#q("DELETE FROM devices WHERE id = ?").run(id);
270
+ this.#devicesChanged();
271
+ });
272
+ }
273
+ /** Paired phones that take notifications and have given a token. */
274
+ pushTargets() {
275
+ const rows = this.#q("SELECT id, public_key, push_token FROM devices WHERE push = 1 AND push_token IS NOT NULL").all();
276
+ return rows.map((row) => ({ id: row.id, publicKey: row.public_key, token: row.push_token }));
277
+ }
278
+ /** Forgets a token Apple no longer knows. */
279
+ dropPushToken(token) {
280
+ this.tx(() => {
281
+ const changed = this.#q("UPDATE devices SET push_token = NULL WHERE push_token = ?").run(token);
282
+ if (changed.changes > 0)
283
+ this.#devicesChanged();
284
+ });
285
+ }
286
+ #device(id) {
287
+ const row = this.#q("SELECT * FROM devices WHERE id = ?").get(id);
288
+ if (!row)
289
+ throw notFound("Device", id);
290
+ return toDevice(row);
291
+ }
292
+ #devicesChanged() {
293
+ this.publish({ type: "devices", devices: this.listDevices() });
294
+ }
295
+ // --- groups ---
296
+ listGroups() {
297
+ const rows = this.#q("SELECT * FROM groups ORDER BY position, id").all();
298
+ return rows.map(toGroup);
299
+ }
300
+ getGroup(id) {
301
+ const row = this.#q("SELECT * FROM groups WHERE id = ?").get(id);
302
+ if (!row)
303
+ throw notFound("Group", id);
304
+ return toGroup(row);
305
+ }
306
+ createGroup(name) {
307
+ const clean = this.#groupName(name);
308
+ return this.tx(() => {
309
+ const now = Date.now();
310
+ const max = this.#q("SELECT MAX(position) AS p FROM groups").get();
311
+ const id = newId();
312
+ this.#q("INSERT INTO groups (id, name, position, created_at, updated_at) VALUES (?, ?, ?, ?, ?)").run(id, clean, (max.p ?? 0) + 1, now, now);
313
+ this.#publishGroups();
314
+ return this.getGroup(id);
315
+ });
316
+ }
317
+ updateGroup(id, patch) {
318
+ return this.tx(() => {
319
+ const group = this.getGroup(id);
320
+ const name = patch.name === undefined ? group.name : this.#groupName(patch.name);
321
+ const position = patch.position ?? group.position;
322
+ if (!Number.isFinite(position))
323
+ throw invalid("The position must be a number.", "position");
324
+ this.#q("UPDATE groups SET name = ?, position = ?, updated_at = ? WHERE id = ?").run(name, position, Date.now(), id);
325
+ this.#publishGroups();
326
+ return this.getGroup(id);
327
+ });
328
+ }
329
+ /** Deletes a group; its sessions stay and move to "no group". */
330
+ deleteGroup(id) {
331
+ this.tx(() => {
332
+ this.getGroup(id);
333
+ const members = this.#q("SELECT id FROM sessions WHERE group_id = ?").all(id);
334
+ this.#q("UPDATE sessions SET group_id = NULL, updated_at = ? WHERE group_id = ?").run(Date.now(), id);
335
+ this.#q("DELETE FROM groups WHERE id = ?").run(id);
336
+ for (const member of members)
337
+ this.#emitSession(member.id);
338
+ this.#publishGroups();
339
+ });
340
+ }
341
+ #groupName(name) {
342
+ if (typeof name !== "string" || name.trim().length === 0) {
343
+ throw invalid("The group name cannot be empty.", "name");
344
+ }
345
+ const trimmed = name.trim();
346
+ if ([...trimmed].length > NAME_MAX) {
347
+ throw invalid(`The group name can be at most ${NAME_MAX} characters.`, "name");
348
+ }
349
+ return trimmed;
350
+ }
351
+ #publishGroups() {
352
+ this.#publish({ scope: "global", event: { type: "groups", groups: this.listGroups() } });
353
+ }
354
+ // --- sessions ---
355
+ getSession(id) {
356
+ const row = this.#q("SELECT * FROM sessions WHERE id = ?").get(id);
357
+ if (!row)
358
+ throw notFound("Session", id);
359
+ return toSession(row);
360
+ }
361
+ findSessionByName(name) {
362
+ const row = this.#q("SELECT * FROM sessions WHERE name = ? COLLATE NOCASE").get(name);
363
+ return row ? toSession(row) : undefined;
364
+ }
365
+ listSessions(options) {
366
+ const archived = options.archived ? "archived_at IS NOT NULL" : "archived_at IS NULL";
367
+ const rows = this.#q(`SELECT * FROM sessions WHERE ${archived} AND id > ? ORDER BY id LIMIT ?`).all(options.cursor ?? "", options.limit + 1);
368
+ const more = rows.length > options.limit;
369
+ const items = rows.slice(0, options.limit).map(toSession);
370
+ return { items, nextCursor: more ? (items.at(-1)?.id ?? null) : null };
371
+ }
372
+ createSession(input) {
373
+ const name = validateSessionName(input.name);
374
+ return this.tx(() => {
375
+ if (this.findSessionByName(name)) {
376
+ throw conflict(`A session named "${name}" already exists.`, { field: "name" });
377
+ }
378
+ if (input.groupId)
379
+ this.getGroup(input.groupId);
380
+ if (input.parentId)
381
+ this.getSession(input.parentId);
382
+ const now = Date.now();
383
+ const id = newId();
384
+ this.#q(`INSERT INTO sessions (id, name, kind, group_id, responsibility, cwd, provider, model, thinking,
385
+ rules, options, parent_id, last_activity_at, created_at, updated_at)
386
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(id, name, input.kind, input.groupId ?? null, input.responsibility ?? "", input.cwd ?? null, input.provider, input.model, input.thinking ?? "medium", JSON.stringify(input.rules ?? []), JSON.stringify(input.options ?? {}), input.parentId ?? null, now, now, now);
387
+ return this.#emitSession(id);
388
+ });
389
+ }
390
+ /**
391
+ * Copies a session's history into another, new session: its entries up to and including
392
+ * `throughSeq` (all of them when null) with their sequence numbers, and the tool calls those
393
+ * entries made. Returns the sequence number of the last entry copied, 0 when there was none.
394
+ */
395
+ copyHistory(fromId, toId, throughSeq) {
396
+ return this.tx(() => this.#copyHistory(fromId, toId, throughSeq));
397
+ }
398
+ #copyHistory(fromId, toId, throughSeq) {
399
+ let last = 0;
400
+ const ids = new Map();
401
+ const rows = this.#q("SELECT * FROM messages WHERE session_id = ? AND seq <= ? AND rewound = 0 ORDER BY seq").all(fromId, throughSeq ?? Number.MAX_SAFE_INTEGER);
402
+ for (const row of rows) {
403
+ const entryId = newId();
404
+ ids.set(row.id, entryId);
405
+ last = row.seq;
406
+ this.#q("INSERT INTO messages (id, session_id, seq, role, body, created_at) VALUES (?, ?, ?, ?, ?, ?)").run(entryId, toId, row.seq, row.role, row.body, row.created_at);
407
+ const text = searchableText(JSON.parse(row.body));
408
+ if (text) {
409
+ this.#q("INSERT INTO message_search (text, session_id, message_id) VALUES (?, ?, ?)").run(text, toId, entryId);
410
+ }
411
+ }
412
+ const calls = this.#q("SELECT * FROM tool_calls WHERE session_id = ? ORDER BY id").all(fromId);
413
+ for (const call of calls) {
414
+ const messageId = ids.get(call.message_id);
415
+ if (!messageId)
416
+ continue;
417
+ this.#q(`INSERT INTO tool_calls (id, session_id, message_id, call_id, tool, args, status, detail,
418
+ result_message_id, started_at, finished_at, created_at)
419
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(newId(), toId, messageId, call.call_id, call.tool, call.args,
420
+ // A call that never ran is pending in the copy, one cut off while running needs review:
421
+ // the copy's next message closes both, as it would in the original.
422
+ call.status === "waiting"
423
+ ? "pending"
424
+ : call.status === "running"
425
+ ? "needs_review"
426
+ : call.status, call.detail, call.result_message_id ? (ids.get(call.result_message_id) ?? null) : null, call.started_at, call.finished_at, call.created_at);
427
+ }
428
+ this.#q("UPDATE sessions SET message_seq = ? WHERE id = ?").run(last, toId);
429
+ return last;
430
+ }
431
+ /**
432
+ * A copy of a session to take another way from here: the same settings, team, workspace, task list
433
+ * and conversation (with its tool calls), under a new name. Usage starts at zero; letters, approvals
434
+ * and the main-conversation role stay with the original. Not while the original is working, since its
435
+ * last calls would have no results.
436
+ */
437
+ /**
438
+ * A new session that goes on from one point of another (blueprint 6.11, item 39): the same
439
+ * settings, and the conversation up to that point: through a finished reply, or up to just before
440
+ * a message from the person. The original goes on as it is, working or not. The new one starts with
441
+ * a fresh view of its folder and instruction files.
442
+ */
443
+ forkSession(id, entryId, name) {
444
+ return this.tx(() => {
445
+ const source = this.getSession(id);
446
+ const through = this.turnPoint(id, entryId);
447
+ const copy = this.createSession({
448
+ name,
449
+ kind: source.kind,
450
+ groupId: source.groupId,
451
+ responsibility: source.responsibility,
452
+ cwd: source.cwd,
453
+ provider: source.provider,
454
+ model: source.model,
455
+ thinking: source.thinking,
456
+ rules: inheritableRules(source.rules),
457
+ options: source.options,
458
+ });
459
+ this.#copyHistory(id, copy.id, through);
460
+ return this.#emitSession(copy.id);
461
+ });
462
+ }
463
+ /**
464
+ * The last entry a fork or a rewind keeps for a point the person picked: a finished reply itself
465
+ * (text, no tool calls), or everything before a message from the person. Nothing else is a point
466
+ * where the conversation can stop.
467
+ */
468
+ turnPoint(sessionId, entryId) {
469
+ const entry = this.getEntry(entryId);
470
+ const row = this.#q("SELECT rewound FROM messages WHERE id = ?").get(entryId);
471
+ if (entry.sessionId === sessionId && row.rewound === 0) {
472
+ if (entry.role === "user")
473
+ return entry.seq - 1;
474
+ const finished = entry.role === "assistant" &&
475
+ entry.message.content.some((block) => block.type === "text" && block.text.trim()) &&
476
+ !entry.message.content.some((block) => block.type === "toolCall");
477
+ if (finished)
478
+ return entry.seq;
479
+ }
480
+ throw invalid("Pick one of the session's replies or one of your messages in it.", "entryId");
481
+ }
482
+ /**
483
+ * Takes the conversation back to just after `throughSeq` (blueprint 6.11, item 42). What came after
484
+ * is deleted, since a rewind is often for a key or something private pasted by mistake (security
485
+ * review, 2026-11-18): each entry keeps a row without content, so numbering and references stay
486
+ * whole, and its tool calls' arguments and results, the approvals asked for them, its search entries
487
+ * and the session's event history go. Files changed, commands run and letters sent meanwhile stay as
488
+ * they are. It cannot go back past the latest summary of earlier history. Returns how many entries
489
+ * were taken back.
490
+ */
491
+ rewindSession(id, throughSeq) {
492
+ const count = this.tx(() => {
493
+ this.getSession(id);
494
+ const summary = this.#q("SELECT seq FROM messages WHERE session_id = ? AND role = 'compaction' AND rewound = 0 ORDER BY seq DESC LIMIT 1").get(id);
495
+ if (summary && throughSeq < summary.seq) {
496
+ throw conflict("The conversation cannot go back past the point where its earlier history was summarized.", undefined, "before-summary");
497
+ }
498
+ const gone = this.#q("SELECT id FROM messages WHERE session_id = ? AND seq > ? AND rewound = 0").all(id, throughSeq);
499
+ if (gone.length === 0)
500
+ return 0;
501
+ this.#q("UPDATE messages SET rewound = 1 WHERE session_id = ? AND seq > ? AND rewound = 0").run(id, throughSeq);
502
+ for (const row of gone) {
503
+ this.#q("DELETE FROM message_search WHERE message_id = ?").run(row.id);
504
+ }
505
+ // Calls taken back before they finished are closed, so nothing picks them up later.
506
+ this.#q(`UPDATE tool_calls SET status = 'error', finished_at = ?
507
+ WHERE session_id = ? AND status IN ('pending', 'waiting', 'running', 'needs_review')
508
+ AND message_id IN (SELECT id FROM messages WHERE session_id = ? AND rewound = 1)`).run(Date.now(), id, id);
509
+ this.#q(`DELETE FROM approvals WHERE tool_call_id IN (SELECT id FROM tool_calls
510
+ WHERE message_id IN (SELECT id FROM messages WHERE session_id = ? AND rewound = 1))`).run(id);
511
+ this.#q(`UPDATE tool_calls SET args = '{}', detail = NULL
512
+ WHERE message_id IN (SELECT id FROM messages WHERE session_id = ? AND rewound = 1)`).run(id);
513
+ this.#q(`UPDATE messages SET body = ${TAKEN_BACK} WHERE session_id = ? AND rewound = 1`).run(id);
514
+ // Earlier events can carry what was taken back. A client that missed some loads the
515
+ // conversation again, as it does after a rewind anyway.
516
+ this.#q("DELETE FROM session_events WHERE session_id = ?").run(id);
517
+ // A fresh look at the folder and instruction files next turn; the context is measured again.
518
+ this.#q("UPDATE sessions SET context = NULL, context_tokens = 0 WHERE id = ?").run(id);
519
+ this.appendEvent(id, { type: "rewound", throughSeq });
520
+ this.#emitSession(id);
521
+ return gone.length;
522
+ });
523
+ // Old copies of the pages leave the write-ahead log too, where it is not in use.
524
+ try {
525
+ this.db.exec("PRAGMA wal_checkpoint(TRUNCATE)");
526
+ }
527
+ catch {
528
+ // Another connection is reading; the log is overwritten later.
529
+ }
530
+ return count;
531
+ }
532
+ duplicateSession(id, name) {
533
+ return this.tx(() => {
534
+ const source = this.getSession(id);
535
+ if (source.status === "working" || source.status === "waiting") {
536
+ throw conflict("Wait until the session stops working, then make the copy.", undefined, "session-busy");
537
+ }
538
+ const copy = this.createSession({
539
+ name,
540
+ kind: source.kind,
541
+ groupId: source.groupId,
542
+ responsibility: source.responsibility,
543
+ cwd: source.cwd,
544
+ provider: source.provider,
545
+ model: source.model,
546
+ thinking: source.thinking,
547
+ rules: inheritableRules(source.rules),
548
+ options: source.options,
549
+ });
550
+ this.copyHistory(id, copy.id, null);
551
+ const context = this.#q("SELECT context, message_seq FROM sessions WHERE id = ?").get(id);
552
+ this.#q(`UPDATE sessions SET todos = ?, context = ?, message_seq = ?, context_tokens = ?,
553
+ last_activity_at = ? WHERE id = ?`).run(JSON.stringify(source.todos), context.context, context.message_seq, source.contextTokens, Date.now(), copy.id);
554
+ return this.#emitSession(copy.id);
555
+ });
556
+ }
557
+ updateSession(id, patch) {
558
+ return this.tx(() => {
559
+ const current = this.getSession(id);
560
+ const sets = [];
561
+ const values = [];
562
+ const set = (column, value) => {
563
+ sets.push(`${column} = ?`);
564
+ values.push(value);
565
+ };
566
+ if (patch.name !== undefined) {
567
+ const name = validateSessionName(patch.name);
568
+ const other = this.findSessionByName(name);
569
+ if (other && other.id !== id) {
570
+ throw conflict(`A session named "${name}" already exists.`, { field: "name" });
571
+ }
572
+ set("name", name);
573
+ }
574
+ if (patch.groupId !== undefined) {
575
+ if (patch.groupId !== null)
576
+ this.getGroup(patch.groupId);
577
+ set("group_id", patch.groupId);
578
+ }
579
+ if (patch.cwd !== undefined)
580
+ set("cwd", patch.cwd);
581
+ if (patch.responsibility !== undefined)
582
+ set("responsibility", patch.responsibility);
583
+ if (patch.provider !== undefined)
584
+ set("provider", patch.provider);
585
+ if (patch.model !== undefined)
586
+ set("model", patch.model);
587
+ if (patch.thinking !== undefined)
588
+ set("thinking", patch.thinking);
589
+ if (patch.rules !== undefined)
590
+ set("rules", JSON.stringify(patch.rules));
591
+ if (patch.options !== undefined) {
592
+ set("options", JSON.stringify({ ...current.options, ...patch.options }));
593
+ }
594
+ if (patch.pinned !== undefined)
595
+ set("pinned", patch.pinned ? 1 : 0);
596
+ if (patch.archived !== undefined) {
597
+ set("archived_at", patch.archived ? (current.archivedAt ?? Date.now()) : null);
598
+ }
599
+ if (patch.read)
600
+ set("unread", 0);
601
+ if (sets.length === 0)
602
+ return current;
603
+ set("updated_at", Date.now());
604
+ this.#q(`UPDATE sessions SET ${sets.join(", ")} WHERE id = ?`).run(...values, id);
605
+ return this.#emitSession(id);
606
+ });
607
+ }
608
+ setStatus(id, status, detail = null) {
609
+ return this.tx(() => {
610
+ this.#q("UPDATE sessions SET status = ?, status_detail = ?, updated_at = ? WHERE id = ?").run(status, detail, Date.now(), id);
611
+ return this.#emitSession(id);
612
+ });
613
+ }
614
+ setTodos(id, todos) {
615
+ return this.tx(() => {
616
+ this.#q("UPDATE sessions SET todos = ?, updated_at = ? WHERE id = ?").run(JSON.stringify(todos), Date.now(), id);
617
+ return this.#emitSession(id);
618
+ });
619
+ }
620
+ /** Adds one model request's usage; `contextTokens` is what that request put in the context window. */
621
+ addUsage(id, usage, contextTokens, now = Date.now()) {
622
+ return this.tx(() => {
623
+ this.#q(`UPDATE sessions SET usage_input = usage_input + ?, usage_output = usage_output + ?,
624
+ usage_cache_read = usage_cache_read + ?, usage_cache_write = usage_cache_write + ?,
625
+ usage_cost = usage_cost + ?, context_tokens = ?, updated_at = ? WHERE id = ?`).run(usage.input, usage.output, usage.cacheRead, usage.cacheWrite, usage.cost, contextTokens, now, id);
626
+ this.#q(`INSERT INTO usage_daily (session_id, day, input, output, cache_read, cache_write, cost)
627
+ VALUES (?, ?, ?, ?, ?, ?, ?)
628
+ ON CONFLICT (session_id, day) DO UPDATE SET input = input + excluded.input,
629
+ output = output + excluded.output, cache_read = cache_read + excluded.cache_read,
630
+ cache_write = cache_write + excluded.cache_write, cost = cost + excluded.cost`).run(id, localDay(now), usage.input, usage.output, usage.cacheRead, usage.cacheWrite, usage.cost);
631
+ return this.#emitSession(id);
632
+ });
633
+ }
634
+ /** Dollars spent on a local calendar day, by one session or by all of them. */
635
+ spentOn(day, sessionId) {
636
+ const row = (sessionId
637
+ ? this.#q("SELECT COALESCE(SUM(cost), 0) AS cost FROM usage_daily WHERE day = ? AND session_id = ?").get(day, sessionId)
638
+ : this.#q("SELECT COALESCE(SUM(cost), 0) AS cost FROM usage_daily WHERE day = ?").get(day));
639
+ return row.cost;
640
+ }
641
+ /** What each session spent on a day, for the sessions that used a model then. */
642
+ spentBySession(day) {
643
+ const rows = this.#q("SELECT session_id, cost FROM usage_daily WHERE day = ?").all(day);
644
+ return Object.fromEntries(rows.map((row) => [row.session_id, row.cost]));
645
+ }
646
+ /** Cost and tokens of all sessions together on each day from `from` to `to`; days without use are left out. */
647
+ usageByDay(from, to) {
648
+ const rows = this.#q(`SELECT day, SUM(cost) AS cost, SUM(input) AS input, SUM(output) AS output,
649
+ SUM(cache_read) AS cache_read, SUM(cache_write) AS cache_write
650
+ FROM usage_daily WHERE day >= ? AND day <= ? GROUP BY day ORDER BY day`).all(from, to);
651
+ return rows.map((row) => ({ day: row.day, ...usageTotals(row) }));
652
+ }
653
+ /** What each session used on a day, the one that cost most first. */
654
+ usageBySession(day) {
655
+ const rows = this.#q(`SELECT u.session_id, s.name, s.archived_at, u.cost, u.input, u.output, u.cache_read, u.cache_write
656
+ FROM usage_daily u JOIN sessions s ON s.id = u.session_id
657
+ WHERE u.day = ? ORDER BY u.cost DESC, s.name`).all(day);
658
+ return rows.map((row) => ({
659
+ sessionId: row.session_id,
660
+ name: row.name,
661
+ archived: row.archived_at !== null,
662
+ ...usageTotals(row),
663
+ }));
664
+ }
665
+ setContextTokens(id, contextTokens) {
666
+ return this.tx(() => {
667
+ this.#q("UPDATE sessions SET context_tokens = ?, updated_at = ? WHERE id = ?").run(contextTokens, Date.now(), id);
668
+ return this.#emitSession(id);
669
+ });
670
+ }
671
+ /** Counts a letter against the session's quota. */
672
+ countLetterSent(id) {
673
+ return this.tx(() => {
674
+ this.#q("UPDATE sessions SET letters_sent = letters_sent + 1 WHERE id = ?").run(id);
675
+ return this.#emitSession(id);
676
+ });
677
+ }
678
+ /** The person wrote or decided: the session may send a full quota of letters again. */
679
+ resetLettersSent(id) {
680
+ this.tx(() => {
681
+ const result = this.#q("UPDATE sessions SET letters_sent = 0 WHERE id = ? AND letters_sent > 0").run(id);
682
+ if (result.changes > 0)
683
+ this.#emitSession(id);
684
+ });
685
+ }
686
+ /** The person stepped in: a message, an approval or an answer (blueprint 6.2, item 9). */
687
+ addIntervention(id) {
688
+ this.tx(() => {
689
+ this.#q("UPDATE sessions SET interventions = interventions + 1 WHERE id = ?").run(id);
690
+ this.#emitSession(id);
691
+ });
692
+ }
693
+ setOutcome(id, outcome) {
694
+ return this.tx(() => {
695
+ this.#q("UPDATE sessions SET outcome = ?, updated_at = ? WHERE id = ?").run(outcome, Date.now(), id);
696
+ return this.#emitSession(id);
697
+ });
698
+ }
699
+ /** Every session that is not archived, oldest first; the directory sessions address letters with. */
700
+ activeSessions() {
701
+ const rows = this.#q("SELECT * FROM sessions WHERE archived_at IS NULL ORDER BY created_at, id").all();
702
+ return rows.map(toSession);
703
+ }
704
+ bumpUnread(id) {
705
+ return this.tx(() => {
706
+ this.#q("UPDATE sessions SET unread = unread + 1 WHERE id = ?").run(id);
707
+ return this.#emitSession(id);
708
+ });
709
+ }
710
+ /** The saved system-prompt inputs (environment and instruction files) for this session. */
711
+ getContextSnapshot(id) {
712
+ const row = this.#q("SELECT context FROM sessions WHERE id = ?").get(id);
713
+ if (!row)
714
+ throw notFound("Session", id);
715
+ return json(row.context, null);
716
+ }
717
+ setContextSnapshot(id, snapshot) {
718
+ this.#q("UPDATE sessions SET context = ? WHERE id = ?").run(JSON.stringify(snapshot), id);
719
+ }
720
+ #emitSession(id) {
721
+ return this.tx(() => {
722
+ const current = this.getSession(id);
723
+ // The event carries the session as it is after the event, including its own sequence number.
724
+ const session = { ...current, eventSeq: current.eventSeq + 1 };
725
+ this.appendEvent(id, { type: "session", session });
726
+ this.#publish({ scope: "global", event: { type: "sessionSummary", session } });
727
+ return session;
728
+ });
729
+ }
730
+ // --- transcript entries ---
731
+ appendEntry(sessionId, body) {
732
+ return this.tx(() => {
733
+ const now = Date.now();
734
+ const active = body.role === "user" || body.role === "assistant";
735
+ const row = this.#q(`UPDATE sessions SET message_seq = message_seq + 1,
736
+ last_activity_at = CASE WHEN ? THEN ? ELSE last_activity_at END, updated_at = ?
737
+ WHERE id = ? RETURNING message_seq`).get(active ? 1 : 0, now, now, sessionId);
738
+ if (!row)
739
+ throw notFound("Session", sessionId);
740
+ const id = newId();
741
+ this.#q("INSERT INTO messages (id, session_id, seq, role, body, created_at) VALUES (?, ?, ?, ?, ?, ?)").run(id, sessionId, row.message_seq, body.role, JSON.stringify(body), now);
742
+ const text = searchableText(body);
743
+ if (text) {
744
+ this.#q("INSERT INTO message_search (text, session_id, message_id) VALUES (?, ?, ?)").run(text, sessionId, id);
745
+ }
746
+ const entry = { ...body, id, sessionId, seq: row.message_seq, createdAt: now };
747
+ this.appendEvent(sessionId, { type: "entry", entry });
748
+ if (active)
749
+ this.#emitSession(sessionId);
750
+ return entry;
751
+ });
752
+ }
753
+ getEntry(id) {
754
+ const row = this.#q("SELECT * FROM messages WHERE id = ?").get(id);
755
+ if (!row)
756
+ throw notFound("Message", id);
757
+ return toEntry(row);
758
+ }
759
+ /** A page of the transcript, newest last; `before` is a seq to page backwards from. */
760
+ listEntries(sessionId, options) {
761
+ const rows = this.#q("SELECT * FROM messages WHERE session_id = ? AND seq < ? AND rewound = 0 ORDER BY seq DESC LIMIT ?").all(sessionId, options.before ?? Number.MAX_SAFE_INTEGER, options.limit + 1);
762
+ const more = rows.length > options.limit;
763
+ const entries = rows.slice(0, options.limit).reverse().map(toEntry);
764
+ return { entries, olderCursor: more ? (entries[0]?.seq ?? null) : null };
765
+ }
766
+ /** Every entry, oldest first; the Markdown export needs the whole transcript, not one page. */
767
+ allEntries(sessionId) {
768
+ this.getSession(sessionId);
769
+ const rows = this.#q("SELECT * FROM messages WHERE session_id = ? AND rewound = 0 ORDER BY seq").all(sessionId);
770
+ return rows.map(toEntry);
771
+ }
772
+ /** Entries the model sees: everything since the latest compaction, plus that compaction's summary. */
773
+ contextEntries(sessionId) {
774
+ const latest = this.#q("SELECT * FROM messages WHERE session_id = ? AND role = 'compaction' AND rewound = 0 ORDER BY seq DESC LIMIT 1").get(sessionId);
775
+ if (!latest) {
776
+ const rows = this.#q(`SELECT * FROM messages WHERE session_id = ? AND role IN ${MODEL_ROLES} AND rewound = 0 ORDER BY seq`).all(sessionId);
777
+ return rows.map(toEntry);
778
+ }
779
+ const compaction = toEntry(latest);
780
+ const firstKept = compaction.role === "compaction" ? compaction.compaction.firstKeptSeq : 0;
781
+ const rows = this.#q(`SELECT * FROM messages WHERE session_id = ? AND role IN ${MODEL_ROLES} AND seq >= ? AND rewound = 0 ORDER BY seq`).all(sessionId, firstKept);
782
+ return [compaction, ...rows.map(toEntry)];
783
+ }
784
+ // --- tool calls ---
785
+ createToolCall(input) {
786
+ return this.tx(() => {
787
+ const id = newId();
788
+ this.#q(`INSERT INTO tool_calls (id, session_id, message_id, call_id, tool, args, status, created_at)
789
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(id, input.sessionId, input.messageId, input.callId, input.tool, JSON.stringify(input.args), input.status ?? "pending", Date.now());
790
+ return this.#emitToolCall(id);
791
+ });
792
+ }
793
+ getToolCall(id) {
794
+ const row = this.#q("SELECT * FROM tool_calls WHERE id = ?").get(id);
795
+ if (!row)
796
+ throw notFound("Tool call", id);
797
+ return toToolCall(row);
798
+ }
799
+ updateToolCall(id, patch) {
800
+ return this.tx(() => {
801
+ const current = this.getToolCall(id);
802
+ this.#q(`UPDATE tool_calls SET status = ?, detail = ?, result_message_id = ?, started_at = ?,
803
+ finished_at = ? WHERE id = ?`).run(patch.status ?? current.status, patch.detail === undefined
804
+ ? current.detail === null
805
+ ? null
806
+ : JSON.stringify(current.detail)
807
+ : patch.detail === null
808
+ ? null
809
+ : JSON.stringify(patch.detail), patch.resultMessageId ?? current.resultMessageId, patch.startedAt ?? current.startedAt, patch.finishedAt ?? current.finishedAt, id);
810
+ return this.#emitToolCall(id);
811
+ });
812
+ }
813
+ toolCallsForMessages(messageIds) {
814
+ if (messageIds.length === 0)
815
+ return [];
816
+ const placeholders = messageIds.map(() => "?").join(", ");
817
+ const rows = this.db
818
+ .prepare(`SELECT * FROM tool_calls WHERE message_id IN (${placeholders}) ORDER BY id`)
819
+ .all(...messageIds);
820
+ return rows.map(toToolCall);
821
+ }
822
+ /** Every call in the session, oldest first; used by the Markdown export. */
823
+ toolCallsForSession(sessionId) {
824
+ const rows = this.#q("SELECT * FROM tool_calls WHERE session_id = ? ORDER BY created_at, id").all(sessionId);
825
+ return rows.map(toToolCall);
826
+ }
827
+ toolCallsByStatus(sessionId, statuses) {
828
+ const placeholders = statuses.map(() => "?").join(", ");
829
+ const rows = this.db
830
+ .prepare(`SELECT * FROM tool_calls WHERE session_id = ? AND status IN (${placeholders}) ORDER BY id`)
831
+ .all(sessionId, ...statuses);
832
+ return rows.map(toToolCall);
833
+ }
834
+ #emitToolCall(id) {
835
+ const toolCall = this.getToolCall(id);
836
+ this.appendEvent(toolCall.sessionId, { type: "toolCall", toolCall });
837
+ return toolCall;
838
+ }
839
+ // --- approvals and questions ---
840
+ createApproval(input) {
841
+ return this.tx(() => {
842
+ const id = newId();
843
+ this.#q(`INSERT INTO approvals (id, session_id, tool_call_id, kind, request, created_at)
844
+ VALUES (?, ?, ?, ?, ?, ?)`).run(id, input.sessionId, input.toolCallId, input.kind, JSON.stringify(input.request), Date.now());
845
+ return this.#emitApproval(id);
846
+ });
847
+ }
848
+ getApproval(id) {
849
+ const row = this.#q("SELECT * FROM approvals WHERE id = ?").get(id);
850
+ if (!row)
851
+ throw notFound("Approval", id);
852
+ return toApproval(row);
853
+ }
854
+ /** Records the person's answer. Only a pending request can be answered, and only once. */
855
+ resolveApproval(id, response) {
856
+ return this.tx(() => {
857
+ const approval = this.getApproval(id);
858
+ if (approval.status !== "pending") {
859
+ throw conflict("This request has already been answered or withdrawn.", undefined, "already-answered");
860
+ }
861
+ this.#q("UPDATE approvals SET status = 'resolved', response = ?, resolved_at = ? WHERE id = ?").run(JSON.stringify(response), Date.now(), id);
862
+ return this.#emitApproval(id);
863
+ });
864
+ }
865
+ cancelApproval(id) {
866
+ return this.tx(() => {
867
+ this.#q("UPDATE approvals SET status = 'cancelled', resolved_at = ? WHERE id = ? AND status = 'pending'").run(Date.now(), id);
868
+ return this.#emitApproval(id);
869
+ });
870
+ }
871
+ pendingApprovals(sessionId) {
872
+ const rows = this.#q("SELECT * FROM approvals WHERE session_id = ? AND status = 'pending' ORDER BY id").all(sessionId);
873
+ return rows.map(toApproval);
874
+ }
875
+ approvalsForToolCalls(toolCallIds) {
876
+ if (toolCallIds.length === 0)
877
+ return [];
878
+ const placeholders = toolCallIds.map(() => "?").join(", ");
879
+ const rows = this.db
880
+ .prepare(`SELECT * FROM approvals WHERE tool_call_id IN (${placeholders}) ORDER BY id`)
881
+ .all(...toolCallIds);
882
+ return rows.map(toApproval);
883
+ }
884
+ /** Every pending approval and question, oldest first, for the approval center. */
885
+ allPendingApprovals() {
886
+ const rows = this.#q("SELECT * FROM approvals WHERE status = 'pending' ORDER BY created_at, id").all();
887
+ return rows.map(toApproval);
888
+ }
889
+ #emitApproval(id) {
890
+ const approval = this.getApproval(id);
891
+ this.appendEvent(approval.sessionId, { type: "approval", approval });
892
+ // The approval center lists every session's approvals, so it hears about each change too.
893
+ this.#publish({ scope: "global", event: { type: "approval", approval } });
894
+ return approval;
895
+ }
896
+ // --- messages queued while a session works ---
897
+ listQueue(sessionId) {
898
+ const rows = this.#q("SELECT * FROM queued_messages WHERE session_id = ? ORDER BY id").all(sessionId);
899
+ return rows.map(toQueued);
900
+ }
901
+ enqueue(sessionId, text) {
902
+ return this.tx(() => {
903
+ this.getSession(sessionId);
904
+ const now = Date.now();
905
+ const id = newId();
906
+ this.#q("INSERT INTO queued_messages (id, session_id, body, created_at, updated_at) VALUES (?, ?, ?, ?, ?)").run(id, sessionId, JSON.stringify({ text }), now, now);
907
+ this.#emitQueue(sessionId);
908
+ return this.#queued(id);
909
+ });
910
+ }
911
+ updateQueued(sessionId, id, text) {
912
+ return this.tx(() => {
913
+ const result = this.#q("UPDATE queued_messages SET body = ?, updated_at = ? WHERE id = ? AND session_id = ?").run(JSON.stringify({ text }), Date.now(), id, sessionId);
914
+ if (result.changes === 0) {
915
+ throw conflict("This message was already delivered or withdrawn.", undefined, "already-delivered");
916
+ }
917
+ this.#emitQueue(sessionId);
918
+ return this.#queued(id);
919
+ });
920
+ }
921
+ removeQueued(sessionId, id) {
922
+ this.tx(() => {
923
+ const result = this.#q("DELETE FROM queued_messages WHERE id = ? AND session_id = ?").run(id, sessionId);
924
+ if (result.changes === 0) {
925
+ throw conflict("This message was already delivered or withdrawn.", undefined, "already-delivered");
926
+ }
927
+ this.#emitQueue(sessionId);
928
+ });
929
+ }
930
+ /** Moves every queued message into the transcript in one transaction, so none is lost or doubled. */
931
+ deliverQueue(sessionId, toBody) {
932
+ return this.tx(() => {
933
+ const queued = this.listQueue(sessionId);
934
+ if (queued.length === 0)
935
+ return [];
936
+ this.#q("DELETE FROM queued_messages WHERE session_id = ?").run(sessionId);
937
+ const entries = queued.map((item) => this.appendEntry(sessionId, toBody(item.text)));
938
+ this.#emitQueue(sessionId);
939
+ return entries;
940
+ });
941
+ }
942
+ #queued(id) {
943
+ const row = this.#q("SELECT * FROM queued_messages WHERE id = ?").get(id);
944
+ if (!row)
945
+ throw notFound("Queued message", id);
946
+ return toQueued(row);
947
+ }
948
+ #emitQueue(sessionId) {
949
+ this.appendEvent(sessionId, { type: "queue", queue: this.listQueue(sessionId) });
950
+ }
951
+ // --- settings ---
952
+ getSetting(key, fallback) {
953
+ const row = this.#q("SELECT value FROM settings WHERE key = ?").get(key);
954
+ return row ? JSON.parse(row.value) : fallback;
955
+ }
956
+ setSetting(key, value) {
957
+ this.#q("INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value").run(key, JSON.stringify(value));
958
+ }
959
+ // --- custom model providers (their keys stay in the keychain) ---
960
+ listCustomProviders() {
961
+ const rows = this.#q("SELECT config FROM providers ORDER BY id").all();
962
+ return rows.map((row) => JSON.parse(row.config));
963
+ }
964
+ saveCustomProvider(config) {
965
+ const now = Date.now();
966
+ this.#q(`INSERT INTO providers (id, name, config, created_at, updated_at) VALUES (?, ?, ?, ?, ?)
967
+ ON CONFLICT (id) DO UPDATE SET name = excluded.name, config = excluded.config,
968
+ updated_at = excluded.updated_at`).run(config.id, config.name, JSON.stringify(config), now, now);
969
+ }
970
+ deleteCustomProvider(id) {
971
+ return this.#q("DELETE FROM providers WHERE id = ?").run(id).changes > 0;
972
+ }
973
+ // --- sign-in tokens (only hashes are stored) ---
974
+ saveAuthToken(hash, kind, expiresAt) {
975
+ this.#q("INSERT INTO auth_tokens (hash, kind, expires_at, created_at) VALUES (?, ?, ?, ?)").run(hash, kind, expiresAt, Date.now());
976
+ }
977
+ /** Removes a one-time login token and says whether it was valid; a token works only once. */
978
+ consumeLoginToken(hash) {
979
+ const row = this.#q("DELETE FROM auth_tokens WHERE hash = ? AND kind = 'login' AND expires_at > ? RETURNING hash").get(hash, Date.now());
980
+ return row !== undefined;
981
+ }
982
+ /** Checks a browser token and extends it; returns false when unknown or expired. */
983
+ touchBrowserToken(hash, extendTo) {
984
+ const now = Date.now();
985
+ const result = this.#q(`UPDATE auth_tokens SET last_used_at = ?, expires_at = MAX(expires_at, ?)
986
+ WHERE hash = ? AND kind = 'browser' AND expires_at > ?`).run(now, extendTo, hash, now);
987
+ return result.changes > 0;
988
+ }
989
+ deleteAuthToken(hash) {
990
+ this.#q("DELETE FROM auth_tokens WHERE hash = ?").run(hash);
991
+ }
992
+ pruneAuthTokens() {
993
+ this.#q("DELETE FROM auth_tokens WHERE expires_at <= ?").run(Date.now());
994
+ }
995
+ // --- search ---
996
+ search(query, limit = 20) {
997
+ const q = query.trim();
998
+ if (q.length === 0)
999
+ return { sessions: [], hits: [] };
1000
+ const like = `%${q.replace(/[\\%_]/g, (c) => `\\${c}`)}%`;
1001
+ const sessions = this.#q(`SELECT * FROM sessions WHERE name LIKE ? ESCAPE '\\' OR responsibility LIKE ? ESCAPE '\\'
1002
+ ORDER BY last_activity_at DESC LIMIT ?`).all(like, like, limit).map(toSession);
1003
+ // The trigram index needs at least three characters; shorter queries scan the index text.
1004
+ const select = `SELECT s.session_id AS sessionId, s.message_id AS entryId, m.seq AS seq,
1005
+ snippet(message_search, 0, '${MATCH_START}', '${MATCH_END}', '…', 16) AS snippet
1006
+ FROM message_search s JOIN messages m ON m.id = s.message_id`;
1007
+ const hits = [...q].length >= 3
1008
+ ? this.#q(`${select} WHERE message_search MATCH ? ORDER BY rank LIMIT ?`).all(`"${q.replace(/"/g, '""')}"`, limit)
1009
+ : this.#q(`SELECT s.session_id AS sessionId, s.message_id AS entryId, m.seq AS seq, s.text AS snippet
1010
+ FROM message_search s JOIN messages m ON m.id = s.message_id
1011
+ WHERE s.text LIKE ? ESCAPE '\\' ORDER BY m.created_at DESC LIMIT ?`).all(like, limit).map((hit) => ({ ...hit, snippet: highlight(hit.snippet, q) }));
1012
+ return { sessions, hits };
1013
+ }
1014
+ // --- deleting ---
1015
+ /**
1016
+ * Deletes archived sessions for good: their conversations, tool calls, approvals, queued messages,
1017
+ * events, search entries and the letters sent to them. Letters they sent and decisions they asked for
1018
+ * stay, without the link to them. Sessions `keep` names (still running) are left alone.
1019
+ */
1020
+ deleteArchivedSessions(keep = () => false) {
1021
+ return this.tx(() => {
1022
+ const rows = this.#q("SELECT id FROM sessions WHERE archived_at IS NOT NULL").all();
1023
+ const ids = rows.map((row) => row.id).filter((id) => !keep(id));
1024
+ for (const id of ids) {
1025
+ this.#q("DELETE FROM message_search WHERE session_id = ?").run(id);
1026
+ this.#q("DELETE FROM sessions WHERE id = ?").run(id);
1027
+ }
1028
+ if (ids.length > 0)
1029
+ this.publish({ type: "sessionsDeleted", ids });
1030
+ return ids;
1031
+ });
1032
+ }
1033
+ // --- restart recovery ---
1034
+ /**
1035
+ * After a restart nothing is running. Work that was in flight is marked "needs review" and is not
1036
+ * redone automatically (blueprint 7.3): a tool call that was running may or may not have finished;
1037
+ * a call that was only waiting for approval never ran and will be asked again.
1038
+ */
1039
+ recoverAfterRestart() {
1040
+ return this.tx(() => {
1041
+ // A question Yew took from a reply has no call behind it: it still waits for the person.
1042
+ const affected = this.#q(`SELECT id FROM sessions WHERE status = 'working' OR (status = 'waiting' AND id NOT IN
1043
+ (SELECT session_id FROM approvals WHERE status = 'pending' AND tool_call_id IS NULL))`).all();
1044
+ const now = Date.now();
1045
+ const running = this.#q("SELECT id FROM tool_calls WHERE status = 'running'").all();
1046
+ for (const call of running)
1047
+ this.updateToolCall(call.id, { status: "needs_review" });
1048
+ const waiting = this.#q("SELECT id FROM tool_calls WHERE status = 'waiting'").all();
1049
+ for (const call of waiting)
1050
+ this.updateToolCall(call.id, { status: "pending" });
1051
+ const pending = this.#q("SELECT id FROM approvals WHERE status = 'pending' AND tool_call_id IS NOT NULL").all();
1052
+ for (const approval of pending)
1053
+ this.cancelApproval(approval.id);
1054
+ for (const session of affected) {
1055
+ this.#q("UPDATE sessions SET status = 'needs_review', status_detail = ?, updated_at = ? WHERE id = ?").run("Yew restarted while this session was working.", now, session.id);
1056
+ this.appendEntry(session.id, {
1057
+ role: "notice",
1058
+ notice: {
1059
+ kind: "restarted",
1060
+ text: "Yew restarted while this session was working.",
1061
+ timestamp: now,
1062
+ },
1063
+ });
1064
+ this.#emitSession(session.id);
1065
+ }
1066
+ return affected.map((session) => session.id);
1067
+ });
1068
+ }
1069
+ }
1070
+ function highlight(text, query) {
1071
+ const index = text.toLowerCase().indexOf(query.toLowerCase());
1072
+ if (index < 0)
1073
+ return text.slice(0, 120);
1074
+ const start = Math.max(0, index - 40);
1075
+ const end = Math.min(text.length, index + query.length + 60);
1076
+ return `${start > 0 ? "…" : ""}${text.slice(start, index)}${MATCH_START}${text.slice(index, index + query.length)}${MATCH_END}${text.slice(index + query.length, end)}${end < text.length ? "…" : ""}`;
1077
+ }