@murmurv2/cli 2.13.0 → 2.14.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.
- package/package.json +3 -3
- package/runtime/bin/murmur-svc.exe +0 -0
- package/runtime/npm-runtime-manifest.json +57 -37
- package/runtime/package.json +1 -1
- package/runtime/packages/setup/dist/src/autoreply.d.ts +23 -0
- package/runtime/packages/setup/dist/src/autoreply.js +71 -0
- package/runtime/packages/setup/dist/src/cli.js +47 -1
- package/runtime/packages/setup/dist/src/clients.d.ts +5 -5
- package/runtime/packages/setup/dist/src/commands.d.ts +1 -0
- package/runtime/packages/setup/dist/src/commands.js +17 -5
- package/runtime/packages/setup/dist/src/connect.d.ts +5 -5
- package/runtime/packages/setup/dist/src/connect.js +3 -1
- package/runtime/packages/setup/dist/src/conversations.d.ts +193 -0
- package/runtime/packages/setup/dist/src/conversations.js +674 -0
- package/runtime/packages/setup/dist/src/platform/darwin.js +12 -0
- package/runtime/packages/setup/dist/src/platform/linux.js +24 -10
- package/runtime/packages/setup/dist/src/platform/windows.js +26 -7
- package/runtime/packages/setup/dist/src/types.d.ts +1 -1
- package/runtime/packages/setup/package.json +1 -1
- package/runtime/scripts/codex-app-server-wake.mjs +23 -4
- package/runtime/scripts/murmur-daemon.mjs +5 -2
- package/runtime/scripts/murmur-shell-send.mjs +5 -1
- package/runtime/scripts/owner-review-store.mjs +54 -0
- package/runtime/scripts/wake-monitor.mjs +49 -10
|
@@ -0,0 +1,674 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
3
|
+
import { execFile } from 'node:child_process';
|
|
4
|
+
import { promisify } from 'node:util';
|
|
5
|
+
import { readFile, readdir, lstat, readlink, mkdir, rmdir } from 'node:fs/promises';
|
|
6
|
+
import { homedir } from 'node:os';
|
|
7
|
+
import { pathToFileURL } from 'node:url';
|
|
8
|
+
import { loadConfig, readJson, safeError } from './config.js';
|
|
9
|
+
import { writeState } from './state.js';
|
|
10
|
+
import { wakeColumns, personalInboxSql } from './message-status.js';
|
|
11
|
+
const run = promisify(execFile);
|
|
12
|
+
/** `dm:a:b` and `dm:b:a` are one conversation (same rule as wake-drain-claude.mjs canonicalConversationId). */
|
|
13
|
+
export function canonicalConversationId(id) {
|
|
14
|
+
const dm = /^dm:([^:]+):([^:]+)$/.exec(id);
|
|
15
|
+
return dm ? `dm:${[dm[1], dm[2]].sort().join(':')}` : id;
|
|
16
|
+
}
|
|
17
|
+
/** Canonical id of `conversation_id` in SQL, so grouping happens in SQLite. */
|
|
18
|
+
const canonicalSql = (column = 'conversation_id') => {
|
|
19
|
+
const rest = `substr(${column}, 4)`, cut = `instr(${rest}, ':')`;
|
|
20
|
+
const a = `substr(${column}, 4, ${cut} - 1)`, b = `substr(${column}, 4 + ${cut})`;
|
|
21
|
+
return `CASE WHEN ${column} GLOB 'dm:*:*' AND ${cut} > 1 AND instr(${b}, ':') = 0 AND length(${b}) > 0
|
|
22
|
+
THEN 'dm:' || min(${a}, ${b}) || ':' || max(${a}, ${b}) ELSE ${column} END`;
|
|
23
|
+
};
|
|
24
|
+
/** Doctor probes and setup reply tests are machine traffic, not conversations. */
|
|
25
|
+
const visibleSql = (column = 'conversation_id') => `${personalInboxSql.replaceAll('conversation_id', column)}
|
|
26
|
+
AND COALESCE(${column}, '') NOT LIKE 'murmur:setup:%'`;
|
|
27
|
+
const deliveryState = { pending: 'queued', sent: 'sent', failed: 'retrying', acked: 'acked', dlq: 'dead-letter' };
|
|
28
|
+
const sha = (value) => createHash('sha256').update(value).digest('hex');
|
|
29
|
+
const preview = (text) => String(text ?? '').replace(/\s+/g, ' ').trim().slice(0, 140);
|
|
30
|
+
/** A hand-off note is a local row the person wrote for one of their own sessions; it never reaches the peer. */
|
|
31
|
+
export const NOTE_TRANSPORT = 'desktop-note';
|
|
32
|
+
const origin = (direction, transport) => transport === NOTE_TRANSPORT ? 'note'
|
|
33
|
+
: direction === 'inbound' ? 'peer' : transport === 'desktop' ? 'desktop' : 'agent';
|
|
34
|
+
/** Sender-reported author of a row (unsigned hint): allowlisted, anything else is unknown (null). */
|
|
35
|
+
const authorOf = (raw) => {
|
|
36
|
+
if (typeof raw !== 'string' || raw.length > 256)
|
|
37
|
+
return null;
|
|
38
|
+
try {
|
|
39
|
+
const value = JSON.parse(raw);
|
|
40
|
+
if (!['person', 'assistant', 'auto'].includes(value?.kind))
|
|
41
|
+
return null;
|
|
42
|
+
return {
|
|
43
|
+
kind: value.kind,
|
|
44
|
+
app: ['claude', 'codex', 'gemini', 'cursor', 'murmur-app', 'autoreply', 'shell'].includes(value.app) ? value.app : null,
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
/** The auto-reply handler's marker: its exact first line, leading whitespace ignored. */
|
|
52
|
+
export const AUTO_MARKER = '[MURMUR-AUTO v1]';
|
|
53
|
+
const isAutoReply = (text) => text.trimStart().split('\n', 1)[0].trim() === AUTO_MARKER;
|
|
54
|
+
/** What a conversation waits for, from its newest visible row. */
|
|
55
|
+
const waitingOf = (kind, outboxStatus) => kind === 'note' ? 'session' : kind === 'in' ? 'you'
|
|
56
|
+
: outboxStatus === 'dlq' ? 'failed' : ['pending', 'sent', 'failed', 'acked'].includes(String(outboxStatus)) ? 'them' : null;
|
|
57
|
+
/** Stable machine prefix of an engine error even when safeError hides the detail (e.g. `policy-rejected`). */
|
|
58
|
+
const reasonCode = (raw) => { const head = String(raw ?? '').split(':')[0]; return /^[a-z][a-z0-9-]{0,40}$/.test(head) ? head : null; };
|
|
59
|
+
const TEXT_CAP = 1500;
|
|
60
|
+
const noOwner = { kind: 'none', sessionKey: null, pid: null, alive: null, listening: null, cwd: null, updatedAt: null, via: null };
|
|
61
|
+
/** Working directory of a live process; null when the platform or permissions do not tell. */
|
|
62
|
+
export async function processCwd(pid) {
|
|
63
|
+
try {
|
|
64
|
+
if (process.platform === 'linux')
|
|
65
|
+
return await readlink(`/proc/${pid}/cwd`);
|
|
66
|
+
if (process.platform === 'darwin') {
|
|
67
|
+
const { stdout } = await run('/usr/sbin/lsof', ['-a', '-p', String(pid), '-d', 'cwd', '-Fn'], { timeout: 2000, maxBuffer: 32768 });
|
|
68
|
+
const line = stdout.split('\n').find(l => l.startsWith('n'));
|
|
69
|
+
return line ? line.slice(1) : null;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
catch { /* Unknown stays unknown. */ }
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
function alive(pid) {
|
|
76
|
+
try {
|
|
77
|
+
process.kill(pid, 0);
|
|
78
|
+
return true;
|
|
79
|
+
}
|
|
80
|
+
catch (error) {
|
|
81
|
+
return error.code === 'EPERM';
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
const bindingsDir = (context) => path.resolve(process.env.MURMUR_WAKE_BINDINGS_DIR || path.join(path.dirname(context.storePath), '.claude-session-bindings'));
|
|
85
|
+
const bindingTtl = () => Number(process.env.MURMUR_WAKE_BIND_TTL_SECONDS) > 0 ? Number(process.env.MURMUR_WAKE_BIND_TTL_SECONDS) : 28800;
|
|
86
|
+
/** One Claude session binding written by the MCP server. A live MCP pid means the session holds the
|
|
87
|
+
* binding; whether its Stop-hook reader listens is `listening`, measured from reader locks. */
|
|
88
|
+
async function readBinding(file, key, expected, via, readers) {
|
|
89
|
+
try {
|
|
90
|
+
const info = await lstat(file);
|
|
91
|
+
if (!info.isFile() || info.size > 4096)
|
|
92
|
+
return null;
|
|
93
|
+
const record = JSON.parse(await readFile(file, 'utf8'));
|
|
94
|
+
if (record?.[key] !== expected || typeof record.sessionId !== 'string' || !record.sessionId)
|
|
95
|
+
return null;
|
|
96
|
+
const pid = Number.isSafeInteger(record.pid) && record.pid > 0 ? record.pid : null;
|
|
97
|
+
const updatedAt = typeof record.updatedAt === 'string' ? record.updatedAt : null;
|
|
98
|
+
const age = updatedAt ? Date.now() - Date.parse(updatedAt) : NaN;
|
|
99
|
+
const fresh = Number.isFinite(age) && age >= 0 && age < bindingTtl() * 1000;
|
|
100
|
+
const isAlive = pid !== null && fresh && alive(pid);
|
|
101
|
+
const sessionKey = record.sessionId.slice(0, 8);
|
|
102
|
+
const listening = isAlive ? readers.some(r => r.verified && r.lane === sessionKey) : false;
|
|
103
|
+
return { kind: 'claude', sessionKey, sessionId: record.sessionId, pid, alive: isAlive, listening,
|
|
104
|
+
cwd: isAlive && pid ? await processCwd(pid) : null, updatedAt, via };
|
|
105
|
+
}
|
|
106
|
+
catch {
|
|
107
|
+
return null;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
/** Who a reply in this conversation will wake, with the precedence of wake-drain-claude.mjs liveOwner:
|
|
111
|
+
* canonical conversation binding, legacy raw-id binding, then the peer's binding. */
|
|
112
|
+
export async function conversationOwner(context, replyId, peer, readers) {
|
|
113
|
+
const codex = /^codex:task:([0-9a-f-]{36})$/i.exec(replyId);
|
|
114
|
+
if (codex)
|
|
115
|
+
return { ...noOwner, kind: 'codex', sessionKey: codex[1], via: 'codex-task' };
|
|
116
|
+
const dir = bindingsDir(context);
|
|
117
|
+
const canonical = canonicalConversationId(replyId);
|
|
118
|
+
// wake-drain-claude.mjs liveOwner: the canonical file, then the id exactly as the letter carries it.
|
|
119
|
+
const candidates = canonical === replyId ? [canonical] : [canonical, replyId];
|
|
120
|
+
let found = null;
|
|
121
|
+
for (const id of candidates) {
|
|
122
|
+
const owner = await readBinding(path.join(dir, `${sha(id)}.json`), 'conversationId', id, 'conversation', readers);
|
|
123
|
+
if (owner?.alive)
|
|
124
|
+
return owner;
|
|
125
|
+
found ??= owner;
|
|
126
|
+
}
|
|
127
|
+
const byPeer = peer ? await readBinding(path.join(dir, `peer-${sha(peer)}.json`), 'peerId', peer, 'peer', readers) : null;
|
|
128
|
+
if (byPeer?.alive)
|
|
129
|
+
return byPeer;
|
|
130
|
+
return found ?? byPeer ?? noOwner;
|
|
131
|
+
}
|
|
132
|
+
async function openStore(context) {
|
|
133
|
+
const { DatabaseSync } = await import('node:sqlite');
|
|
134
|
+
let db;
|
|
135
|
+
try {
|
|
136
|
+
db = new DatabaseSync(context.storePath, { readOnly: true });
|
|
137
|
+
}
|
|
138
|
+
catch {
|
|
139
|
+
throw new Error('store.unavailable');
|
|
140
|
+
}
|
|
141
|
+
db.exec('PRAGMA busy_timeout=1000');
|
|
142
|
+
return db;
|
|
143
|
+
}
|
|
144
|
+
const limitOf = (value, max, code) => {
|
|
145
|
+
if (!Number.isSafeInteger(value) || value < 1 || value > max)
|
|
146
|
+
throw new Error(code);
|
|
147
|
+
return value;
|
|
148
|
+
};
|
|
149
|
+
const validId = (id) => !!id && id.length <= 256 && !/[\x00-\x1f\u007f]/.test(id);
|
|
150
|
+
/** Serializes a read-modify-write of profile state with every other setup writer (`.setup-write.lock`).
|
|
151
|
+
* Read marks are frequent, so a busy lock is retried briefly instead of failing at once. */
|
|
152
|
+
export async function withSetupLock(context, work, waitMs = 2000) {
|
|
153
|
+
const lock = path.join(context.dataDir, '.setup-write.lock');
|
|
154
|
+
for (let attempt = 0;; attempt++) {
|
|
155
|
+
try {
|
|
156
|
+
await mkdir(lock, { mode: 0o700 });
|
|
157
|
+
break;
|
|
158
|
+
}
|
|
159
|
+
catch (error) {
|
|
160
|
+
if (error.code !== 'EEXIST' || attempt >= waitMs / 50)
|
|
161
|
+
throw new Error('state.busy');
|
|
162
|
+
await new Promise(resolve => setTimeout(resolve, 50));
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
try {
|
|
166
|
+
return await work();
|
|
167
|
+
}
|
|
168
|
+
finally {
|
|
169
|
+
await rmdir(lock);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
/** The person's read marks: the profile-wide cursor of `inbox mark-read` and one mark per conversation. */
|
|
173
|
+
async function readMarks(context, agentId, tip = Number.MAX_SAFE_INTEGER) {
|
|
174
|
+
try {
|
|
175
|
+
const state = await readJson(path.join(context.dataDir, 'read-state.json'));
|
|
176
|
+
if (state?.schema !== 'murmur.read/1' || state.agentId !== agentId)
|
|
177
|
+
return { cursor: null, conversations: {} };
|
|
178
|
+
const conversations = {};
|
|
179
|
+
// A mark above the store's newest row was written for another store (reset, re-join): ignore it.
|
|
180
|
+
for (const [id, rowid] of Object.entries(state.conversations ?? {}))
|
|
181
|
+
if (Number.isSafeInteger(rowid) && rowid >= 0 && rowid <= tip)
|
|
182
|
+
conversations[id] = rowid;
|
|
183
|
+
return { cursor: Number.isSafeInteger(state.rowid) && state.rowid <= tip ? state.rowid : null, conversations };
|
|
184
|
+
}
|
|
185
|
+
catch {
|
|
186
|
+
return { cursor: null, conversations: {} };
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
const markOf = (marks, cid) => Math.max(marks.conversations[cid] ?? 0, marks.cursor ?? 0, 0);
|
|
190
|
+
/** Conversations with their newest message, attention counters, owner and newest inbound letter. Read-only. */
|
|
191
|
+
export async function listConversations(context, limit = 50, home = homedir()) {
|
|
192
|
+
limitOf(limit, 200, 'conversations.limit-invalid');
|
|
193
|
+
const config = await loadConfig(context);
|
|
194
|
+
const readers = await listReaders(context, home);
|
|
195
|
+
const db = await openStore(context);
|
|
196
|
+
let rows;
|
|
197
|
+
let marks;
|
|
198
|
+
try {
|
|
199
|
+
db.exec('BEGIN');
|
|
200
|
+
marks = await readMarks(context, config.agentId, Number(db.prepare('SELECT COALESCE(MAX(rowid), 0) AS m FROM local_messages').get().m));
|
|
201
|
+
rows = db.prepare(`WITH m AS (
|
|
202
|
+
SELECT l.rowid AS r, ${canonicalSql('l.conversation_id')} AS cid, l.conversation_id AS wid, l.msg_id, l.direction,
|
|
203
|
+
CASE WHEN COALESCE(l.transport, '') = '${NOTE_TRANSPORT}' THEN 'note' WHEN l.direction = 'inbound' THEN 'in' ELSE 'out' END AS kind,
|
|
204
|
+
l.sender, l.text, l.created_at, l.transport, o.status AS ostatus, json_extract(o.envelope_json, '$.recipients[0]') AS recipient
|
|
205
|
+
FROM local_messages l LEFT JOIN outbox o ON o.msg_id = l.msg_id AND l.direction = 'outbound'
|
|
206
|
+
WHERE ${visibleSql('l.conversation_id')}),
|
|
207
|
+
agg AS (SELECT cid, max(r) AS lastR, max(CASE WHEN kind = 'in' THEN r END) AS inR, count(*) AS n,
|
|
208
|
+
sum(ostatus = 'dlq') AS dlq, sum(ostatus IN ('pending','sent','failed')) AS pending,
|
|
209
|
+
max(CASE WHEN kind = 'in' THEN sender END) AS inboundPeer, max(recipient) AS outboundPeer
|
|
210
|
+
FROM m GROUP BY cid)
|
|
211
|
+
SELECT agg.*, last.direction, last.kind, last.ostatus AS lastStatus, last.sender, last.text, last.created_at AS createdAt, last.transport, last.wid AS lastWid,
|
|
212
|
+
inb.msg_id AS inMsgId, inb.text AS inText, inb.created_at AS inAt, inb.wid AS inWid,
|
|
213
|
+
(SELECT count(*) FROM m AS d WHERE d.cid = agg.cid AND ((d.direction = 'outbound' AND d.transport = 'desktop') OR d.kind = 'note') AND d.r > agg.inR) AS answered
|
|
214
|
+
FROM agg JOIN m AS last ON last.r = agg.lastR LEFT JOIN m AS inb ON inb.r = agg.inR
|
|
215
|
+
ORDER BY last.created_at DESC, last.r DESC LIMIT ?`).all(limit);
|
|
216
|
+
const unreadAbove = db.prepare(`SELECT count(*) AS n FROM local_messages WHERE ${canonicalSql()} = ? AND direction = 'inbound'
|
|
217
|
+
AND COALESCE(transport, '') <> '${NOTE_TRANSPORT}' AND rowid > ?`);
|
|
218
|
+
for (const row of rows)
|
|
219
|
+
row.unread = Number(unreadAbove.get(row.cid, markOf(marks, String(row.cid))).n);
|
|
220
|
+
db.exec('COMMIT');
|
|
221
|
+
}
|
|
222
|
+
finally {
|
|
223
|
+
db.close();
|
|
224
|
+
}
|
|
225
|
+
const conversations = [];
|
|
226
|
+
for (const row of rows) {
|
|
227
|
+
const replyId = String(row.inWid ?? row.lastWid ?? row.cid);
|
|
228
|
+
const peer = peerOf(String(row.cid), config.agentId, row.inboundPeer ?? row.outboundPeer);
|
|
229
|
+
conversations.push({
|
|
230
|
+
id: row.cid, replyConversationId: replyId, peer, lastAt: row.createdAt, count: Number(row.n),
|
|
231
|
+
lastMessage: { direction: row.direction, sender: row.sender, preview: preview(row.text),
|
|
232
|
+
createdAt: row.createdAt, origin: origin(row.direction, row.transport) },
|
|
233
|
+
// The newest letter from the peer, in full up to 1500 characters, so a client can read a question without
|
|
234
|
+
// opening the conversation; `answeredFromDesktop` tells whether the person already replied after it.
|
|
235
|
+
newestInbound: row.inMsgId ? { msgId: row.inMsgId, text: String(row.inText ?? '').slice(0, TEXT_CAP),
|
|
236
|
+
createdAt: row.inAt, answeredFromDesktop: Number(row.answered) > 0 } : null,
|
|
237
|
+
attention: { deadLetter: Number(row.dlq ?? 0), pendingDelivery: Number(row.pending ?? 0) },
|
|
238
|
+
waiting: waitingOf(String(row.kind), row.lastStatus), unread: Number(row.unread ?? 0),
|
|
239
|
+
owner: await conversationOwner(context, replyId, peer, readers),
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
return { schema: 'murmur.conversations/1', agentId: config.agentId, conversations };
|
|
243
|
+
}
|
|
244
|
+
/** The other party: from a `dm:` id, else the inbound sender or the outbound recipient seen in the conversation. */
|
|
245
|
+
function peerOf(id, self, seen) {
|
|
246
|
+
const dm = /^dm:([^:]+):([^:]+)$/.exec(id);
|
|
247
|
+
if (dm)
|
|
248
|
+
return dm[1] === self ? dm[2] : dm[1];
|
|
249
|
+
return typeof seen === 'string' && seen ? seen : null;
|
|
250
|
+
}
|
|
251
|
+
/** One conversation's history with delivery and wake state per message. Read-only and byte-bounded:
|
|
252
|
+
* texts above 1500 characters are cut (`truncated: true`), and older messages are dropped once the
|
|
253
|
+
* response would pass ~160 KB (`hasMore: true`), well under the app's 256 KiB read cap. */
|
|
254
|
+
export async function showConversation(context, id, limit = 60, home = homedir()) {
|
|
255
|
+
if (!validId(id))
|
|
256
|
+
throw new Error('conversations.id-invalid');
|
|
257
|
+
limitOf(limit, 200, 'conversations.limit-invalid');
|
|
258
|
+
const config = await loadConfig(context);
|
|
259
|
+
const canonical = canonicalConversationId(id);
|
|
260
|
+
const readers = await listReaders(context, home);
|
|
261
|
+
const db = await openStore(context);
|
|
262
|
+
let rows, meta;
|
|
263
|
+
try {
|
|
264
|
+
db.exec('BEGIN');
|
|
265
|
+
const where = `${canonicalSql('l.conversation_id')} = ? AND ${visibleSql('l.conversation_id')}`;
|
|
266
|
+
// Metadata comes from the whole conversation, independent of pagination.
|
|
267
|
+
meta = db.prepare(`SELECT group_concat(DISTINCT l.conversation_id) AS wids, count(*) AS n,
|
|
268
|
+
(SELECT l2.conversation_id FROM local_messages l2 WHERE ${canonicalSql('l2.conversation_id')} = ? AND l2.direction = 'inbound' AND COALESCE(l2.transport, '') <> '${NOTE_TRANSPORT}' ORDER BY l2.rowid DESC LIMIT 1) AS inWid,
|
|
269
|
+
(SELECT l3.sender FROM local_messages l3 WHERE ${canonicalSql('l3.conversation_id')} = ? AND l3.direction = 'inbound' AND COALESCE(l3.transport, '') <> '${NOTE_TRANSPORT}' ORDER BY l3.rowid DESC LIMIT 1) AS inSender,
|
|
270
|
+
(SELECT l4.conversation_id FROM local_messages l4 WHERE ${canonicalSql('l4.conversation_id')} = ? ORDER BY l4.rowid DESC LIMIT 1) AS lastWid
|
|
271
|
+
FROM local_messages l WHERE ${where}`).get(canonical, canonical, canonical, canonical);
|
|
272
|
+
const wake = wakeColumns(db).split(',').map(c => c.includes(' AS ') ? c : `l.${c}`).join(',');
|
|
273
|
+
const authorCol = (db.prepare("SELECT 1 FROM pragma_table_info('local_messages') WHERE name = 'author_json'").get()) != null
|
|
274
|
+
? 'l.author_json AS authorJson' : 'NULL AS authorJson';
|
|
275
|
+
rows = db.prepare(`SELECT l.rowid AS r, l.conversation_id AS wid, l.msg_id AS msgId, l.direction, l.sender, l.text,
|
|
276
|
+
l.created_at AS createdAt, l.transport, ${authorCol}, ${wake},
|
|
277
|
+
o.status AS outboxStatus, o.attempts, o.last_error AS lastError, o.updated_at AS outboxUpdatedAt,
|
|
278
|
+
json_extract(o.envelope_json, '$.recipients[0]') AS recipient
|
|
279
|
+
FROM local_messages l LEFT JOIN outbox o ON o.msg_id = l.msg_id AND l.direction = 'outbound'
|
|
280
|
+
WHERE ${where} ORDER BY l.created_at DESC, l.rowid DESC LIMIT ?`).all(canonical, limit);
|
|
281
|
+
db.exec('COMMIT');
|
|
282
|
+
}
|
|
283
|
+
finally {
|
|
284
|
+
db.close();
|
|
285
|
+
}
|
|
286
|
+
const peer = peerOf(canonical, config.agentId, meta.inSender ?? rows.find(r => r.recipient)?.recipient);
|
|
287
|
+
const replyId = String(meta.inWid ?? meta.lastWid ?? canonical);
|
|
288
|
+
let budget = 160_000, hasMore = Number(meta.n) > rows.length;
|
|
289
|
+
const newestFirst = [];
|
|
290
|
+
for (const row of rows) {
|
|
291
|
+
const text = String(row.text ?? '');
|
|
292
|
+
const message = {
|
|
293
|
+
msgId: row.msgId, direction: row.direction, sender: row.sender, origin: origin(row.direction, row.transport),
|
|
294
|
+
author: authorOf(row.authorJson), autoReply: isAutoReply(text),
|
|
295
|
+
text: text.slice(0, TEXT_CAP), truncated: text.length > TEXT_CAP, createdAt: row.createdAt,
|
|
296
|
+
delivery: row.direction === 'outbound' ? (row.outboxStatus == null
|
|
297
|
+
? { state: 'unknown', attempts: null, reason: null, reasonCode: null, updatedAt: null }
|
|
298
|
+
: { state: deliveryState[row.outboxStatus] ?? 'unknown', attempts: Number(row.attempts),
|
|
299
|
+
reason: row.lastError ? safeError(row.lastError) : null, reasonCode: reasonCode(row.lastError), updatedAt: row.outboxUpdatedAt }) : null,
|
|
300
|
+
wake: row.direction === 'inbound' ? { status: row.wake_status ?? null, updatedAt: row.wake_updated_at ?? null } : null,
|
|
301
|
+
};
|
|
302
|
+
budget -= Buffer.byteLength(JSON.stringify(message));
|
|
303
|
+
if (budget < 0 && newestFirst.length) {
|
|
304
|
+
hasMore = true;
|
|
305
|
+
break;
|
|
306
|
+
}
|
|
307
|
+
newestFirst.push(message);
|
|
308
|
+
}
|
|
309
|
+
return { schema: 'murmur.conversation/1', agentId: config.agentId, id: canonical,
|
|
310
|
+
wireIds: String(meta.wids ?? canonical).split(',').filter(Boolean), peer,
|
|
311
|
+
// Reply on the peer's own spelling: an active murmur_request on the other side matches it exactly.
|
|
312
|
+
replyConversationId: replyId, hasMore,
|
|
313
|
+
owner: await conversationOwner(context, replyId, peer, readers), messages: newestFirst.reverse() };
|
|
314
|
+
}
|
|
315
|
+
/** Where letters land right now: who a NEW conversation from each peer wakes, and which drains listen. Read-only. */
|
|
316
|
+
export async function showRouting(context, home = homedir()) {
|
|
317
|
+
const config = await loadConfig(context);
|
|
318
|
+
const readers = await listReaders(context, home);
|
|
319
|
+
const newFromPeer = [];
|
|
320
|
+
const seen = await lastSeen(context, Object.keys(config.peers ?? {}));
|
|
321
|
+
for (const peer of Object.keys(config.peers ?? {}).sort()) {
|
|
322
|
+
newFromPeer.push({ peer, lastSeenAt: seen[peer] ?? null,
|
|
323
|
+
owner: (await readBinding(path.join(bindingsDir(context), `peer-${sha(peer)}.json`), 'peerId', peer, 'peer', readers)) ?? noOwner });
|
|
324
|
+
}
|
|
325
|
+
return { schema: 'murmur.routing/1', agentId: config.agentId, newFromPeer, readers,
|
|
326
|
+
storage: { jetstream: config.jetstream?.enabled === true || process.env.MURMUR_JETSTREAM === '1' },
|
|
327
|
+
measuredAt: new Date().toISOString() };
|
|
328
|
+
}
|
|
329
|
+
/** When each peer's host last answered: its newest letter or the newest signed receipt for a letter to it.
|
|
330
|
+
* A fact from the past, never a presence claim. */
|
|
331
|
+
async function lastSeen(context, peers) {
|
|
332
|
+
const result = {};
|
|
333
|
+
if (!peers.length)
|
|
334
|
+
return result;
|
|
335
|
+
let db;
|
|
336
|
+
try {
|
|
337
|
+
db = await openStore(context);
|
|
338
|
+
}
|
|
339
|
+
catch {
|
|
340
|
+
return result;
|
|
341
|
+
}
|
|
342
|
+
try {
|
|
343
|
+
const inbound = db.prepare(`SELECT max(created_at) AS at FROM local_messages WHERE direction = 'inbound' AND sender = ?
|
|
344
|
+
AND COALESCE(transport, '') <> '${NOTE_TRANSPORT}' AND ${visibleSql()}`);
|
|
345
|
+
const acked = db.prepare(`SELECT max(updated_at) AS at FROM outbox WHERE status = 'acked' AND json_extract(envelope_json, '$.recipients[0]') = ?`);
|
|
346
|
+
for (const peer of peers) {
|
|
347
|
+
const times = [inbound.get(peer)?.at, (() => { try {
|
|
348
|
+
return acked.get(peer)?.at;
|
|
349
|
+
}
|
|
350
|
+
catch {
|
|
351
|
+
return null;
|
|
352
|
+
} })()]
|
|
353
|
+
.filter((t) => typeof t === 'string' && !Number.isNaN(Date.parse(t)));
|
|
354
|
+
if (times.length)
|
|
355
|
+
result[peer] = times.sort((a, b) => Date.parse(b) - Date.parse(a))[0];
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
finally {
|
|
359
|
+
db.close();
|
|
360
|
+
}
|
|
361
|
+
return result;
|
|
362
|
+
}
|
|
363
|
+
/** Live Claude drains for this store, verified like wake-readers.ts, with lane and working folder. */
|
|
364
|
+
export async function listReaders(context, home = homedir()) {
|
|
365
|
+
if (!['linux', 'darwin'].includes(process.platform))
|
|
366
|
+
return [];
|
|
367
|
+
const store = path.resolve(context.storePath);
|
|
368
|
+
const key = createHash('sha256').update(store).digest('hex').slice(0, 8);
|
|
369
|
+
let files = [];
|
|
370
|
+
try {
|
|
371
|
+
files = (await readdir(home)).filter(name => new RegExp(`^\\.murmur-wake-lock-${key}(?:-[A-Za-z0-9_-]{1,8})?$`).test(name));
|
|
372
|
+
}
|
|
373
|
+
catch {
|
|
374
|
+
return [];
|
|
375
|
+
}
|
|
376
|
+
const readers = [];
|
|
377
|
+
for (const name of files.sort()) {
|
|
378
|
+
const lane = name.slice(`.murmur-wake-lock-${key}`.length + 1) || null;
|
|
379
|
+
try {
|
|
380
|
+
const info = await lstat(path.join(home, name));
|
|
381
|
+
if (!info.isFile() || info.size > 64) {
|
|
382
|
+
readers.push({ pid: null, lane, cwd: null, verified: false });
|
|
383
|
+
continue;
|
|
384
|
+
}
|
|
385
|
+
const pid = Number((await readFile(path.join(home, name), 'utf8')).trim());
|
|
386
|
+
if (!Number.isSafeInteger(pid) || pid <= 0 || !alive(pid))
|
|
387
|
+
continue;
|
|
388
|
+
let verified = false;
|
|
389
|
+
try {
|
|
390
|
+
if (process.platform === 'linux') {
|
|
391
|
+
const args = (await readFile(`/proc/${pid}/cmdline`, 'utf8')).split('\0');
|
|
392
|
+
verified = args.some(a => a.endsWith('/wake-drain-claude.mjs')) && args[args.indexOf('--db') + 1] === store;
|
|
393
|
+
}
|
|
394
|
+
else {
|
|
395
|
+
const { stdout } = await run('/bin/ps', ['-p', String(pid), '-o', 'command='], { timeout: 2000, maxBuffer: 32768 });
|
|
396
|
+
verified = stdout.includes('/wake-drain-claude.mjs ') && stdout.includes(`--db ${store} `);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
catch {
|
|
400
|
+
verified = false;
|
|
401
|
+
}
|
|
402
|
+
readers.push({ pid, lane, cwd: verified ? await processCwd(pid) : null, verified });
|
|
403
|
+
}
|
|
404
|
+
catch {
|
|
405
|
+
readers.push({ pid: null, lane, cwd: null, verified: false });
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
return readers;
|
|
409
|
+
}
|
|
410
|
+
/** The person read a conversation through one of its letters: a per-conversation mark in read-state.json.
|
|
411
|
+
* The profile-wide cursor of `inbox mark-read` is kept as it is. */
|
|
412
|
+
export async function markConversationRead(context, id, throughMsgId, expectedAgent) {
|
|
413
|
+
if (!validId(id))
|
|
414
|
+
throw new Error('conversations.id-invalid');
|
|
415
|
+
const config = await loadConfig(context);
|
|
416
|
+
if (config.agentId !== expectedAgent)
|
|
417
|
+
throw new Error('read.identity-changed');
|
|
418
|
+
const canonical = canonicalConversationId(id);
|
|
419
|
+
const db = await openStore(context);
|
|
420
|
+
let rowid;
|
|
421
|
+
try {
|
|
422
|
+
const row = db.prepare(`SELECT rowid FROM local_messages WHERE msg_id = ? AND ${canonicalSql()} = ?`).get(throughMsgId, canonical);
|
|
423
|
+
if (!row)
|
|
424
|
+
throw new Error('read.message-missing');
|
|
425
|
+
rowid = Number(row.rowid);
|
|
426
|
+
}
|
|
427
|
+
finally {
|
|
428
|
+
db.close();
|
|
429
|
+
}
|
|
430
|
+
const file = path.join(context.dataDir, 'read-state.json');
|
|
431
|
+
await withSetupLock(context, async () => {
|
|
432
|
+
let state = null;
|
|
433
|
+
try {
|
|
434
|
+
state = await readJson(file);
|
|
435
|
+
}
|
|
436
|
+
catch { /* No state yet. */ }
|
|
437
|
+
const valid = state?.schema === 'murmur.read/1' && state.agentId === config.agentId;
|
|
438
|
+
const conversations = valid && state.conversations && typeof state.conversations === 'object' ? { ...state.conversations } : {};
|
|
439
|
+
conversations[canonical] = Math.max(Number.isSafeInteger(conversations[canonical]) ? conversations[canonical] : 0, rowid);
|
|
440
|
+
const next = { schema: 'murmur.read/1', agentId: config.agentId, conversations };
|
|
441
|
+
if (valid && Number.isSafeInteger(state.rowid))
|
|
442
|
+
next.rowid = state.rowid;
|
|
443
|
+
await writeState(context, file, next);
|
|
444
|
+
});
|
|
445
|
+
return { schema: 'murmur.read-conversation/1', agentId: config.agentId, id: canonical, rowid };
|
|
446
|
+
}
|
|
447
|
+
/** The newest letters from peers across all conversations, each with the conversation it landed in and who
|
|
448
|
+
* reads it there. Hand-off notes and machine traffic are left out. Read-only. */
|
|
449
|
+
export async function inboxFeed(context, limit = 30, home = homedir()) {
|
|
450
|
+
limitOf(limit, 100, 'inbox.limit-invalid');
|
|
451
|
+
const config = await loadConfig(context);
|
|
452
|
+
const readers = await listReaders(context, home);
|
|
453
|
+
const db = await openStore(context);
|
|
454
|
+
let rows;
|
|
455
|
+
let marks;
|
|
456
|
+
try {
|
|
457
|
+
marks = await readMarks(context, config.agentId, Number(db.prepare('SELECT COALESCE(MAX(rowid), 0) AS m FROM local_messages').get().m));
|
|
458
|
+
rows = db.prepare(`SELECT rowid AS r, msg_id AS msgId, ${canonicalSql()} AS cid, conversation_id AS wid, sender, text, created_at AS createdAt
|
|
459
|
+
FROM local_messages WHERE direction = 'inbound' AND COALESCE(transport, '') <> '${NOTE_TRANSPORT}' AND ${visibleSql()}
|
|
460
|
+
ORDER BY created_at DESC, rowid DESC LIMIT ?`).all(limit);
|
|
461
|
+
}
|
|
462
|
+
finally {
|
|
463
|
+
db.close();
|
|
464
|
+
}
|
|
465
|
+
const owners = new Map();
|
|
466
|
+
const letters = [];
|
|
467
|
+
for (const row of rows) {
|
|
468
|
+
const cid = String(row.cid);
|
|
469
|
+
if (!owners.has(cid))
|
|
470
|
+
owners.set(cid, await conversationOwner(context, String(row.wid), String(row.sender), readers));
|
|
471
|
+
letters.push({ msgId: row.msgId, conversationId: cid, replyConversationId: row.wid, peer: row.sender,
|
|
472
|
+
preview: preview(DECISION_STRIP(String(row.text ?? ''))), createdAt: row.createdAt,
|
|
473
|
+
unread: Number(row.r) > markOf(marks, cid), owner: owners.get(cid) });
|
|
474
|
+
}
|
|
475
|
+
return { schema: 'murmur.feed/1', agentId: config.agentId, letters };
|
|
476
|
+
}
|
|
477
|
+
/** The person's preview drops the machine decision block; the question stays readable in the app. */
|
|
478
|
+
const DECISION_STRIP = (text) => text.replace(/```murmur-decision[\s\S]*?```/g, '').trim() || text;
|
|
479
|
+
/** Parent of a process, and its executable name (macOS and Linux). */
|
|
480
|
+
async function parentOf(pid) {
|
|
481
|
+
try {
|
|
482
|
+
const { stdout } = await run('/bin/ps', ['-o', 'ppid=,comm=', '-p', String(pid)], { timeout: 2000 });
|
|
483
|
+
const match = /^\s*(\d+)\s+(.*)$/.exec(stdout.trim());
|
|
484
|
+
return match ? { ppid: Number(match[1]), command: match[2] } : null;
|
|
485
|
+
}
|
|
486
|
+
catch {
|
|
487
|
+
return null;
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
/** The Claude Code process a reader runs under: the reader restarts after every turn, the session lives on. */
|
|
491
|
+
async function claudeSessionPid(readerPid) {
|
|
492
|
+
let pid = readerPid;
|
|
493
|
+
for (let depth = 0; depth < 8 && pid > 1; depth++) {
|
|
494
|
+
const parent = await parentOf(pid);
|
|
495
|
+
if (!parent || parent.ppid <= 1)
|
|
496
|
+
return null;
|
|
497
|
+
pid = parent.ppid;
|
|
498
|
+
const up = await parentOf(pid);
|
|
499
|
+
if (up && /(^|\/)claude([^/]*)$/i.test(up.command))
|
|
500
|
+
return pid;
|
|
501
|
+
}
|
|
502
|
+
return null;
|
|
503
|
+
}
|
|
504
|
+
/** Claude Code project folders set up for THIS profile: their Stop hook drains this store (letters wake a session
|
|
505
|
+
* there) or their .mcp.json points Murmur at this profile. Folders with the wake hook come first. Candidates are
|
|
506
|
+
* the projects Claude Code itself knows (~/.claude.json), so nothing on disk is scanned. */
|
|
507
|
+
async function claudeFolders(context, home) {
|
|
508
|
+
let projects = [];
|
|
509
|
+
try {
|
|
510
|
+
projects = Object.keys(JSON.parse(await readFile(path.join(home, '.claude.json'), 'utf8'))?.projects ?? {});
|
|
511
|
+
}
|
|
512
|
+
catch {
|
|
513
|
+
return [];
|
|
514
|
+
}
|
|
515
|
+
const store = path.resolve(context.storePath), data = path.resolve(context.dataDir);
|
|
516
|
+
const found = [];
|
|
517
|
+
// Folders macOS guards with a privacy prompt (Downloads, Documents, Desktop, iCloud Drive, media, other
|
|
518
|
+
// volumes) are never read: a check like this must not make the app ask for access to them.
|
|
519
|
+
const guarded = ['Downloads', 'Documents', 'Desktop', 'Pictures', 'Movies', 'Music', path.join('Library', 'Mobile Documents')]
|
|
520
|
+
.map(name => path.join(home, name));
|
|
521
|
+
const hasPath = (raw, target) => raw.includes(target) || raw.includes(target.replaceAll('\\', '\\\\')) || raw.includes(target.replaceAll('\\', '/'));
|
|
522
|
+
for (const folder of projects.slice(0, 400)) {
|
|
523
|
+
if (!path.isAbsolute(folder) || folder.startsWith('/Volumes/'))
|
|
524
|
+
continue;
|
|
525
|
+
if (guarded.some(root => folder === root || folder.startsWith(root + path.sep)))
|
|
526
|
+
continue;
|
|
527
|
+
const read = async (file) => { try {
|
|
528
|
+
const info = await lstat(file);
|
|
529
|
+
return info.isFile() && info.size < 262144 ? await readFile(file, 'utf8') : '';
|
|
530
|
+
}
|
|
531
|
+
catch {
|
|
532
|
+
return '';
|
|
533
|
+
} };
|
|
534
|
+
const settings = await read(path.join(folder, '.claude', 'settings.json')) + await read(path.join(folder, '.claude', 'settings.local.json'));
|
|
535
|
+
const wake = settings.includes('wake-drain-claude') && hasPath(settings, store);
|
|
536
|
+
const mcp = hasPath(await read(path.join(folder, '.mcp.json')), data);
|
|
537
|
+
if (wake || mcp)
|
|
538
|
+
found.push({ path: folder, wake, mcp });
|
|
539
|
+
}
|
|
540
|
+
return found.sort((a, b) => Number(b.wake) - Number(a.wake));
|
|
541
|
+
}
|
|
542
|
+
/** Sessions that can take a conversation now: live, listening Claude Code sessions with their folder, and
|
|
543
|
+
* open Codex tasks that already took part in a Murmur conversation. Read-only. */
|
|
544
|
+
export async function listSessions(context, home = homedir()) {
|
|
545
|
+
const config = await loadConfig(context);
|
|
546
|
+
const claude = [];
|
|
547
|
+
for (const reader of await listReaders(context, home)) {
|
|
548
|
+
if (!reader.verified || !reader.pid || !reader.lane)
|
|
549
|
+
continue;
|
|
550
|
+
claude.push({ kind: 'claude', sessionKey: reader.lane, cwd: reader.cwd, sessionPid: await claudeSessionPid(reader.pid) });
|
|
551
|
+
}
|
|
552
|
+
const codex = [];
|
|
553
|
+
try {
|
|
554
|
+
const notify = await import(pathToFileURL(path.join(context.repoRoot, 'scripts', 'codex-desktop-notify.mjs')).href);
|
|
555
|
+
const statePath = notify.findCodexStateDb();
|
|
556
|
+
const db = await openStore(context);
|
|
557
|
+
let ids = [];
|
|
558
|
+
try {
|
|
559
|
+
ids = db.prepare(`SELECT DISTINCT substr(conversation_id, 12) AS id FROM local_messages WHERE conversation_id LIKE 'codex:task:%'`).all().map(r => String(r.id));
|
|
560
|
+
}
|
|
561
|
+
finally {
|
|
562
|
+
db.close();
|
|
563
|
+
}
|
|
564
|
+
for (const id of ids) {
|
|
565
|
+
const thread = statePath ? notify.selectAddressedUserThread({ dbPath: statePath, conversationId: `codex:task:${id}` }) : null;
|
|
566
|
+
if (thread)
|
|
567
|
+
codex.push({ kind: 'codex', threadId: thread.id, title: thread.title, openUrl: `codex://threads/${thread.id}` });
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
catch { /* No Codex on this host. */ }
|
|
571
|
+
return { schema: 'murmur.sessions/1', agentId: config.agentId, claude, codex, claudeFolders: await claudeFolders(context, home) };
|
|
572
|
+
}
|
|
573
|
+
/** The full text of an outbound letter in this conversation (any spelling of its id), for a resend. */
|
|
574
|
+
async function storedOutboundText(context, conversationId, msgId) {
|
|
575
|
+
const { DatabaseSync } = await import('node:sqlite');
|
|
576
|
+
const db = new DatabaseSync(context.storePath, { readOnly: true });
|
|
577
|
+
try {
|
|
578
|
+
const row = db.prepare(`SELECT text FROM local_messages WHERE msg_id = ? AND direction = 'outbound' AND ${canonicalSql()} = ?`)
|
|
579
|
+
.get(msgId, canonicalConversationId(conversationId));
|
|
580
|
+
if (!row)
|
|
581
|
+
throw new Error('send.resend-missing');
|
|
582
|
+
return String(row.text ?? '').trim();
|
|
583
|
+
}
|
|
584
|
+
finally {
|
|
585
|
+
db.close();
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
const DESKTOP_AUTHOR = { kind: 'person', app: 'murmur-app' };
|
|
589
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
590
|
+
/** Direct message from the person through the desktop app: the envelope, signing and outbox path of
|
|
591
|
+
* MCP murmur_send, DM only. It writes no Claude/Codex binding: the app is not a session, and replies
|
|
592
|
+
* must keep waking the session that owns the conversation.
|
|
593
|
+
*
|
|
594
|
+
* Every guard and both writes run in one `BEGIN IMMEDIATE` transaction, so two clients cannot both pass
|
|
595
|
+
* the already-answered or msg-id checks, and history and outbox commit together or not at all. */
|
|
596
|
+
export async function sendDirect(context, options) {
|
|
597
|
+
const { to, conversationId, msgId, expectedAgent, expectAfter, resendOf } = options;
|
|
598
|
+
if (!UUID.test(msgId))
|
|
599
|
+
throw new Error('send.msg-id-invalid');
|
|
600
|
+
if (!validId(conversationId))
|
|
601
|
+
throw new Error('send.conversation-invalid');
|
|
602
|
+
if (resendOf !== undefined && options.text !== undefined)
|
|
603
|
+
throw new Error('send.input-conflict');
|
|
604
|
+
const text = resendOf !== undefined ? await storedOutboundText(context, conversationId, resendOf) : (options.text ?? '').trim();
|
|
605
|
+
if (!text)
|
|
606
|
+
throw new Error('send.text-empty');
|
|
607
|
+
if (Buffer.byteLength(text, 'utf8') > 16384)
|
|
608
|
+
throw new Error('send.text-too-large');
|
|
609
|
+
const config = await loadConfig(context);
|
|
610
|
+
if (config.agentId !== expectedAgent)
|
|
611
|
+
throw new Error('send.identity-changed');
|
|
612
|
+
const peer = Object.hasOwn(config.peers ?? {}, to) ? config.peers[to] : undefined;
|
|
613
|
+
if (!peer)
|
|
614
|
+
throw new Error('send.unknown-peer');
|
|
615
|
+
const { DatabaseSync } = await import('node:sqlite');
|
|
616
|
+
const { SQLiteDedupeOutboxStore, SQLiteMessageStore, stableEnvelopePayload, resolveMessageSubject, deliveryIdFor } = await import('@murmurv2/core');
|
|
617
|
+
const { encryptPayload, signEnvelope } = await import('@murmurv2/security');
|
|
618
|
+
const result = (state) => ({ schema: 'murmur.send/1', agentId: config.agentId, msgId, to, conversationId, state });
|
|
619
|
+
// Constructing the stores applies their schema migrations; the writes below use one connection.
|
|
620
|
+
new SQLiteDedupeOutboxStore(context.storePath).close?.();
|
|
621
|
+
new SQLiteMessageStore(context.storePath).close?.();
|
|
622
|
+
const encrypted = await encryptPayload(text, peer.encryption.publicKey, config.keys.encryption.privateKey);
|
|
623
|
+
const envelope = { schemaVersion: '1.0', msgId, conversationId, senderAgentId: config.agentId, recipients: [to],
|
|
624
|
+
createdAt: new Date().toISOString(), payloadCiphertext: encrypted.ciphertext, payloadNonce: encrypted.nonce, signature: '' };
|
|
625
|
+
envelope.signature = await signEnvelope(stableEnvelopePayload(envelope), config.keys.signing.privateKey);
|
|
626
|
+
// Unsigned sender report (core normalizeAuthor): the person sent it from the desktop app.
|
|
627
|
+
envelope.author = DESKTOP_AUTHOR;
|
|
628
|
+
const db = new DatabaseSync(context.storePath);
|
|
629
|
+
try {
|
|
630
|
+
db.exec('PRAGMA busy_timeout=5000; BEGIN IMMEDIATE');
|
|
631
|
+
try {
|
|
632
|
+
const queued = db.prepare('SELECT envelope_json AS e FROM outbox WHERE msg_id = ?').get(msgId);
|
|
633
|
+
const local = db.prepare("SELECT text, conversation_id AS c FROM local_messages WHERE msg_id = ? AND direction = 'outbound'").get(msgId);
|
|
634
|
+
if (queued || local) {
|
|
635
|
+
const earlier = queued ? JSON.parse(String(queued.e ?? '{}')) : null;
|
|
636
|
+
const same = (!earlier || (earlier.conversationId === conversationId && earlier.recipients?.[0] === to))
|
|
637
|
+
&& (!local || (local.text === text && local.c === conversationId));
|
|
638
|
+
db.exec('ROLLBACK');
|
|
639
|
+
if (!same || !queued || !local)
|
|
640
|
+
throw new Error('send.msg-id-conflict');
|
|
641
|
+
return result('already-queued');
|
|
642
|
+
}
|
|
643
|
+
if (expectAfter !== undefined) {
|
|
644
|
+
const canonical = canonicalConversationId(conversationId);
|
|
645
|
+
const anchor = db.prepare(`SELECT rowid AS r FROM local_messages WHERE msg_id = ? AND direction = 'inbound' AND ${canonicalSql()} = ?`).get(expectAfter, canonical);
|
|
646
|
+
if (!anchor)
|
|
647
|
+
throw new Error('send.expected-message-missing');
|
|
648
|
+
const newer = db.prepare(`SELECT 1 FROM local_messages WHERE ${canonicalSql()} = ? AND direction = 'inbound' AND rowid > ? LIMIT 1`).get(canonical, anchor.r);
|
|
649
|
+
if (newer)
|
|
650
|
+
throw new Error('send.question-superseded');
|
|
651
|
+
const answered = db.prepare(`SELECT 1 FROM local_messages WHERE ${canonicalSql()} = ? AND direction = 'outbound'
|
|
652
|
+
AND transport = 'desktop' AND rowid > ? LIMIT 1`).get(canonical, anchor.r);
|
|
653
|
+
if (answered)
|
|
654
|
+
throw new Error('send.already-answered');
|
|
655
|
+
}
|
|
656
|
+
const now = new Date().toISOString();
|
|
657
|
+
const authorColumn = (db.prepare("SELECT 1 FROM pragma_table_info('local_messages') WHERE name = 'author_json'").get()) != null;
|
|
658
|
+
db.prepare(`INSERT INTO local_messages (id, conversation_id, msg_id, direction, sender, text, created_at, transport, delivery_id, wake_attempts${authorColumn ? ', author_json' : ''})
|
|
659
|
+
VALUES (?, ?, ?, 'outbound', ?, ?, ?, 'desktop', ?, 0${authorColumn ? ', ?' : ''})`).run(randomUUID(), conversationId, msgId, config.agentId, text, envelope.createdAt, deliveryIdFor('outbound', msgId), ...(authorColumn ? [JSON.stringify(DESKTOP_AUTHOR)] : []));
|
|
660
|
+
db.prepare(`INSERT INTO outbox (msg_id, subject, envelope_json, status, attempts, next_attempt_at, created_at, updated_at, version)
|
|
661
|
+
VALUES (?, ?, ?, 'pending', 0, ?, ?, ?, 1)`).run(msgId, resolveMessageSubject(peer), JSON.stringify(envelope), now, now, now);
|
|
662
|
+
db.exec('COMMIT');
|
|
663
|
+
return result('queued');
|
|
664
|
+
}
|
|
665
|
+
catch (error) {
|
|
666
|
+
if (db.isTransaction)
|
|
667
|
+
db.exec('ROLLBACK');
|
|
668
|
+
throw error;
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
finally {
|
|
672
|
+
db.close();
|
|
673
|
+
}
|
|
674
|
+
}
|