@joenandez/tldr 1.0.1 → 1.1.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 (31) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/bin/tldr-agent +3 -2
  4. package/install/tldr-agent-bootstrap.sh +7 -0
  5. package/package.json +7 -6
  6. package/release/activation-manifest.json +6 -6
  7. package/release/payloads/arm64/TldrAgentAegis.pkg +0 -0
  8. package/release/payloads/arm64/tldr-agent.tar.gz +0 -0
  9. package/release/starport-release.json +2 -2
  10. package/skills/tldr/SKILL.md +37 -36
  11. package/src/lib/aegis_native_distribution.mjs +1 -1
  12. package/src/lib/aegis_protocol.mjs +1 -1
  13. package/src/lib/starport_onboarding.mjs +303 -6
  14. package/src/lib/starport_orchestrator.mjs +21 -20
  15. package/src/lib/starport_runtime.mjs +28 -5
  16. package/src/lib/tightbeam_channel.mjs +63 -119
  17. package/src/lib/tightbeam_channel_runtime.mjs +76 -17
  18. package/src/lib/tightbeam_email_adapter.mjs +10 -0
  19. package/src/lib/tightbeam_email_delivery_channel.mjs +107 -133
  20. package/src/lib/tightbeam_email_provider_map.mjs +337 -0
  21. package/src/lib/tightbeam_inbound_publish.mjs +84 -0
  22. package/src/lib/tightbeam_welcome_dispatch.mjs +129 -33
  23. package/src/lib/tldr_agent_diagnostic_schema.mjs +1 -0
  24. package/src/lib/transports/email/render/email.mjs +66 -180
  25. package/src/lib/transports/email/render/html.mjs +37 -80
  26. package/src/lib/transports/email/render/text.mjs +2 -2
  27. package/src/lib/transports/email/render/tldr.mjs +10 -88
  28. package/src/lib/transports/email/render/tokens.mjs +56 -75
  29. package/src/lib/transports/email/templates.mjs +38 -27
  30. package/src/lib/transports/email.mjs +21 -1
  31. package/src/lib/transports/email/render/glyphs.mjs +0 -66
@@ -1,124 +1,15 @@
1
- import "./node_sqlite_warning.mjs";
2
- import { chmodSync, existsSync } from "node:fs";
3
- import { chmod, mkdir } from "node:fs/promises";
4
- import { join } from "node:path";
5
- import { DatabaseSync } from "node:sqlite";
1
+ import { expectedPreflightArgs } from "./tightbeam_channel_runtime.mjs";
2
+ import {
3
+ lookupProviderMap,
4
+ lookupProviderReplyBinding,
5
+ recordBoundProviderAcceptance,
6
+ recordInboundProviderAcceptance as persistInboundProviderAcceptance,
7
+ recordProviderMap,
8
+ recordProviderReplyBinding,
9
+ } from "./tightbeam_email_provider_map.mjs";
6
10
 
7
- function providerMapPath(home) {
8
- return join(home, "tightbeam-email-provider-map.sqlite");
9
- }
10
-
11
- function secureProviderMapFiles(path) {
12
- for (const candidate of [path, `${path}-wal`, `${path}-shm`]) {
13
- if (existsSync(candidate)) chmodSync(candidate, 0o600);
14
- }
15
- }
16
-
17
- function openProviderMap(home, { readOnly = false } = {}) {
18
- const path = providerMapPath(home);
19
- if (readOnly && !existsSync(path)) return null;
20
- const db = new DatabaseSync(path, readOnly ? { readOnly: true } : {});
21
- try {
22
- if (!readOnly) {
23
- secureProviderMapFiles(path);
24
- db.exec("PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 5000;");
25
- secureProviderMapFiles(path);
26
- db.exec(`CREATE TABLE IF NOT EXISTS provider_acceptance (
27
- delivery_id TEXT PRIMARY KEY,
28
- message_id TEXT NOT NULL,
29
- conversation_id TEXT NOT NULL,
30
- route_id TEXT NOT NULL,
31
- origin_endpoint_id TEXT,
32
- origin_session_id TEXT,
33
- external_id TEXT NOT NULL,
34
- external_thread_id TEXT NOT NULL
35
- );
36
- CREATE INDEX IF NOT EXISTS provider_acceptance_conversation
37
- ON provider_acceptance(conversation_id);
38
- CREATE INDEX IF NOT EXISTS provider_acceptance_thread
39
- ON provider_acceptance(external_thread_id);`);
40
- const columns = new Set(
41
- db
42
- .prepare("PRAGMA table_info(provider_acceptance)")
43
- .all()
44
- .map(({ name }) => name),
45
- );
46
- if (!columns.has("origin_endpoint_id")) {
47
- db.exec(
48
- "ALTER TABLE provider_acceptance ADD COLUMN origin_endpoint_id TEXT",
49
- );
50
- }
51
- if (!columns.has("origin_session_id")) {
52
- db.exec(
53
- "ALTER TABLE provider_acceptance ADD COLUMN origin_session_id TEXT",
54
- );
55
- }
56
- }
57
- return db;
58
- } catch (error) {
59
- db.close();
60
- throw error;
61
- }
62
- }
63
-
64
- async function recordProviderMap(home, record) {
65
- await mkdir(home, { recursive: true, mode: 0o700 });
66
- const db = openProviderMap(home);
67
- try {
68
- db.exec("BEGIN IMMEDIATE");
69
- db.prepare(
70
- `INSERT INTO provider_acceptance (
71
- delivery_id, message_id, conversation_id, route_id, external_id, external_thread_id
72
- , origin_endpoint_id, origin_session_id
73
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
74
- ON CONFLICT(delivery_id) DO UPDATE SET
75
- message_id = excluded.message_id,
76
- conversation_id = excluded.conversation_id,
77
- route_id = excluded.route_id,
78
- origin_endpoint_id = excluded.origin_endpoint_id,
79
- origin_session_id = excluded.origin_session_id,
80
- external_id = excluded.external_id,
81
- external_thread_id = excluded.external_thread_id`,
82
- ).run(
83
- record.delivery_id,
84
- record.message_id,
85
- record.conversation_id,
86
- record.route_id,
87
- record.external_id,
88
- record.external_thread_id,
89
- record.origin_endpoint_id,
90
- record.origin_session_id,
91
- );
92
- db.exec("COMMIT");
93
- } catch (error) {
94
- try {
95
- db.exec("ROLLBACK");
96
- } catch {}
97
- throw error;
98
- } finally {
99
- db.close();
100
- }
101
- await chmod(providerMapPath(home), 0o600);
102
- secureProviderMapFiles(providerMapPath(home));
103
- }
104
-
105
- function lookupProviderMap(home, column, value) {
106
- const db = openProviderMap(home, { readOnly: true });
107
- if (!db) return null;
108
- try {
109
- const latest =
110
- column === "delivery_id" ? "" : " ORDER BY rowid DESC LIMIT 1";
111
- return (
112
- db
113
- .prepare(
114
- `SELECT delivery_id, message_id, conversation_id, route_id, origin_endpoint_id, origin_session_id, external_id, external_thread_id FROM provider_acceptance WHERE ${column} = ?${latest}`,
115
- )
116
- .get(value) || null
117
- );
118
- } finally {
119
- db.close();
120
- }
121
- }
11
+ const REPLY_BINDING_CAPABILITY = "channels.reply-binding.v1";
12
+ const LISTENER_CAPABILITY = "listener.v1";
122
13
 
123
14
  export function createTightbeamEmailDeliveryChannel({
124
15
  execute,
@@ -129,6 +20,25 @@ export function createTightbeamEmailDeliveryChannel({
129
20
  principalRef,
130
21
  endpointSession,
131
22
  } = {}) {
23
+ let capabilities;
24
+
25
+ async function deliveryCapabilities() {
26
+ if (capabilities) return capabilities;
27
+ const supported = async (capability) => {
28
+ const result = await execute({
29
+ admin: true,
30
+ credentials: null,
31
+ args: [...expectedPreflightArgs(), "--require-capability", capability],
32
+ });
33
+ return result?.ok === true && result.result?.compatible === true;
34
+ };
35
+ capabilities = Object.freeze({
36
+ replyBinding: await supported(REPLY_BINDING_CAPABILITY),
37
+ listener: await supported(LISTENER_CAPABILITY),
38
+ });
39
+ return capabilities;
40
+ }
41
+
132
42
  async function registeredEmailIdentity() {
133
43
  const identity = await readIdentity();
134
44
  if (!identity) return null;
@@ -192,6 +102,7 @@ export function createTightbeamEmailDeliveryChannel({
192
102
  if (commandFailure(routes) || !route) {
193
103
  return Object.freeze({ ok: false, code: "route_unavailable" });
194
104
  }
105
+ const capability = await deliveryCapabilities();
195
106
  const claimed = await execute({
196
107
  admin: false,
197
108
  credentials: emailIdentity.identity,
@@ -202,6 +113,7 @@ export function createTightbeamEmailDeliveryChannel({
202
113
  emailIdentity.endpoint.endpoint_id,
203
114
  "--channel-route",
204
115
  route.route_id,
116
+ ...(capability.replyBinding ? ["--accept-reply-binding"] : []),
205
117
  ],
206
118
  });
207
119
  return commandFailure(claimed)
@@ -235,6 +147,10 @@ export function createTightbeamEmailDeliveryChannel({
235
147
  }
236
148
 
237
149
  async function recordProviderAcceptance({ delivery, provider }) {
150
+ if (typeof delivery?.reply_binding === "string") {
151
+ await recordBoundProviderAcceptance(home, delivery, provider);
152
+ return;
153
+ }
238
154
  const identity = await readIdentity();
239
155
  if (!identity) throw new Error("Tightbeam email identity is unavailable");
240
156
  const routes = await execute({
@@ -265,26 +181,67 @@ export function createTightbeamEmailDeliveryChannel({
265
181
  });
266
182
  }
267
183
 
184
+ async function recordReplyBinding({ delivery }) {
185
+ if (
186
+ typeof delivery?.delivery_id !== "string" ||
187
+ typeof delivery.reply_binding !== "string" ||
188
+ delivery.reply_binding.length === 0
189
+ ) {
190
+ throw new TypeError(
191
+ "Tightbeam claimed delivery has no opaque reply binding",
192
+ );
193
+ }
194
+ await recordProviderReplyBinding(home, delivery);
195
+ }
196
+
197
+ async function recordInboundProviderAcceptance({
198
+ binding,
199
+ provider_message_id: providerMessageId,
200
+ provider_thread_id: providerThreadId,
201
+ tightbeam_message_id: tightbeamMessageId,
202
+ tightbeam_conversation_id: tightbeamConversationId,
203
+ }) {
204
+ if (
205
+ typeof binding?.reply_binding !== "string" ||
206
+ binding.reply_binding.length === 0 ||
207
+ typeof providerMessageId !== "string" ||
208
+ providerMessageId.length === 0 ||
209
+ (providerThreadId !== undefined &&
210
+ (typeof providerThreadId !== "string" ||
211
+ providerThreadId.length === 0)) ||
212
+ typeof tightbeamMessageId !== "string" ||
213
+ tightbeamMessageId.length === 0
214
+ ) {
215
+ throw new TypeError("Accepted inbound provider identity is incomplete");
216
+ }
217
+ await persistInboundProviderAcceptance(home, {
218
+ reply_binding: binding.reply_binding,
219
+ provider_message_id: providerMessageId,
220
+ provider_thread_id: providerThreadId,
221
+ tightbeam_message_id: tightbeamMessageId,
222
+ tightbeam_conversation_id: tightbeamConversationId,
223
+ });
224
+ }
225
+
268
226
  async function findThreadBinding(externalThreadId) {
269
- const record = lookupProviderMap(
227
+ const bound = lookupProviderReplyBinding(
270
228
  home,
271
229
  "external_thread_id",
272
230
  externalThreadId,
273
231
  );
274
- return record
275
- ? {
276
- conversation_id: record.conversation_id,
277
- route_id: record.route_id,
278
- ...(typeof record.origin_endpoint_id === "string"
279
- ? { origin_endpoint_id: record.origin_endpoint_id }
280
- : {}),
281
- ...(typeof record.origin_session_id === "string"
282
- ? { origin_session_id: record.origin_session_id }
283
- : {}),
284
- }
285
- : null;
232
+ return bound ? { reply_binding: bound.reply_binding } : null;
286
233
  }
287
234
  async function findProviderAcceptanceByDelivery(deliveryId) {
235
+ const bound = lookupProviderReplyBinding(home, "delivery_id", deliveryId);
236
+ if (
237
+ typeof bound?.external_id === "string" &&
238
+ typeof bound.external_thread_id === "string"
239
+ ) {
240
+ return {
241
+ external_id: bound.external_id,
242
+ external_thread_id: bound.external_thread_id,
243
+ };
244
+ }
288
245
  const record = lookupProviderMap(home, "delivery_id", deliveryId);
289
246
  return record
290
247
  ? {
@@ -294,6 +251,21 @@ export function createTightbeamEmailDeliveryChannel({
294
251
  : null;
295
252
  }
296
253
  async function findProviderThreadByConversation(conversationId) {
254
+ const bound = lookupProviderReplyBinding(
255
+ home,
256
+ "conversation_id",
257
+ conversationId,
258
+ );
259
+ if (
260
+ typeof bound?.external_id === "string" &&
261
+ typeof bound.external_thread_id === "string"
262
+ ) {
263
+ return {
264
+ external_id:
265
+ bound.current_reply_parent_external_id || bound.external_id,
266
+ external_thread_id: bound.external_thread_id,
267
+ };
268
+ }
297
269
  const record = lookupProviderMap(home, "conversation_id", conversationId);
298
270
  return record
299
271
  ? {
@@ -305,7 +277,9 @@ export function createTightbeamEmailDeliveryChannel({
305
277
  return Object.freeze({
306
278
  claimEmailDelivery,
307
279
  completeEmailDelivery,
280
+ recordReplyBinding,
308
281
  recordProviderAcceptance,
282
+ recordInboundProviderAcceptance,
309
283
  findProviderAcceptanceByDelivery,
310
284
  findThreadBinding,
311
285
  findProviderThreadByConversation,
@@ -0,0 +1,337 @@
1
+ import "./node_sqlite_warning.mjs";
2
+ import { chmodSync, existsSync } from "node:fs";
3
+ import { chmod, mkdir } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ import { DatabaseSync } from "node:sqlite";
6
+
7
+ function providerMapPath(home) {
8
+ return join(home, "tightbeam-email-provider-map.sqlite");
9
+ }
10
+
11
+ function secureProviderMapFiles(path) {
12
+ for (const candidate of [path, `${path}-wal`, `${path}-shm`]) {
13
+ if (existsSync(candidate)) chmodSync(candidate, 0o600);
14
+ }
15
+ }
16
+
17
+ function openProviderMap(home, { readOnly = false } = {}) {
18
+ const path = providerMapPath(home);
19
+ if (readOnly && !existsSync(path)) return null;
20
+ const db = new DatabaseSync(path, readOnly ? { readOnly: true } : {});
21
+ try {
22
+ if (!readOnly) {
23
+ secureProviderMapFiles(path);
24
+ db.exec("PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 5000;");
25
+ secureProviderMapFiles(path);
26
+ db.exec(`CREATE TABLE IF NOT EXISTS provider_acceptance (
27
+ delivery_id TEXT PRIMARY KEY,
28
+ message_id TEXT NOT NULL,
29
+ conversation_id TEXT NOT NULL,
30
+ route_id TEXT NOT NULL,
31
+ origin_endpoint_id TEXT,
32
+ origin_session_id TEXT,
33
+ external_id TEXT NOT NULL,
34
+ external_thread_id TEXT NOT NULL
35
+ );
36
+ CREATE TABLE IF NOT EXISTS provider_reply_binding (
37
+ delivery_id TEXT PRIMARY KEY,
38
+ reply_binding TEXT NOT NULL,
39
+ conversation_id TEXT,
40
+ external_id TEXT,
41
+ external_thread_id TEXT,
42
+ current_reply_parent_external_id TEXT
43
+ );
44
+ CREATE TABLE IF NOT EXISTS provider_reply_parent_event (
45
+ provider_message_id TEXT PRIMARY KEY,
46
+ provider_thread_id TEXT NOT NULL,
47
+ delivery_id TEXT NOT NULL,
48
+ reply_binding TEXT NOT NULL,
49
+ tightbeam_message_id TEXT NOT NULL
50
+ );
51
+ CREATE INDEX IF NOT EXISTS provider_acceptance_conversation
52
+ ON provider_acceptance(conversation_id);
53
+ CREATE INDEX IF NOT EXISTS provider_acceptance_thread
54
+ ON provider_acceptance(external_thread_id);
55
+ CREATE INDEX IF NOT EXISTS provider_reply_binding_thread
56
+ ON provider_reply_binding(external_thread_id);
57
+ CREATE INDEX IF NOT EXISTS provider_reply_binding_conversation
58
+ ON provider_reply_binding(conversation_id);`);
59
+ const columns = new Set(
60
+ db
61
+ .prepare("PRAGMA table_info(provider_acceptance)")
62
+ .all()
63
+ .map(({ name }) => name),
64
+ );
65
+ if (!columns.has("origin_endpoint_id")) {
66
+ db.exec(
67
+ "ALTER TABLE provider_acceptance ADD COLUMN origin_endpoint_id TEXT",
68
+ );
69
+ }
70
+ if (!columns.has("origin_session_id")) {
71
+ db.exec(
72
+ "ALTER TABLE provider_acceptance ADD COLUMN origin_session_id TEXT",
73
+ );
74
+ }
75
+ const bindingColumns = new Set(
76
+ db
77
+ .prepare("PRAGMA table_info(provider_reply_binding)")
78
+ .all()
79
+ .map(({ name }) => name),
80
+ );
81
+ if (!bindingColumns.has("conversation_id")) {
82
+ db.exec(
83
+ "ALTER TABLE provider_reply_binding ADD COLUMN conversation_id TEXT",
84
+ );
85
+ }
86
+ if (!bindingColumns.has("current_reply_parent_external_id")) {
87
+ db.exec(
88
+ "ALTER TABLE provider_reply_binding ADD COLUMN current_reply_parent_external_id TEXT",
89
+ );
90
+ }
91
+ }
92
+ return db;
93
+ } catch (error) {
94
+ db.close();
95
+ throw error;
96
+ }
97
+ }
98
+
99
+ async function mutateProviderMap(home, mutate) {
100
+ await mkdir(home, { recursive: true, mode: 0o700 });
101
+ const db = openProviderMap(home);
102
+ try {
103
+ db.exec("BEGIN IMMEDIATE");
104
+ mutate(db);
105
+ db.exec("COMMIT");
106
+ } catch (error) {
107
+ try {
108
+ db.exec("ROLLBACK");
109
+ } catch {}
110
+ throw error;
111
+ } finally {
112
+ db.close();
113
+ }
114
+ await chmod(providerMapPath(home), 0o600);
115
+ secureProviderMapFiles(providerMapPath(home));
116
+ }
117
+
118
+ export async function recordProviderReplyBinding(home, delivery) {
119
+ await mutateProviderMap(home, (db) => {
120
+ db.prepare(
121
+ `INSERT INTO provider_reply_binding (delivery_id, reply_binding, conversation_id)
122
+ VALUES (?, ?, ?)
123
+ ON CONFLICT(delivery_id) DO UPDATE SET
124
+ reply_binding = excluded.reply_binding,
125
+ conversation_id = excluded.conversation_id`,
126
+ ).run(
127
+ delivery.delivery_id,
128
+ delivery.reply_binding,
129
+ delivery.message.conversation_id,
130
+ );
131
+ });
132
+ }
133
+
134
+ export async function recordBoundProviderAcceptance(home, delivery, provider) {
135
+ await mutateProviderMap(home, (db) => {
136
+ const binding = db
137
+ .prepare(
138
+ `SELECT conversation_id, current_reply_parent_external_id
139
+ FROM provider_reply_binding WHERE delivery_id = ?`,
140
+ )
141
+ .get(delivery.delivery_id);
142
+ if (!binding) {
143
+ throw new Error(
144
+ "Tightbeam reply binding is not durable before provider acceptance",
145
+ );
146
+ }
147
+ const previous = db
148
+ .prepare(
149
+ `SELECT current_reply_parent_external_id, external_id
150
+ FROM provider_reply_binding
151
+ WHERE conversation_id = ? AND delivery_id <> ?
152
+ AND external_id IS NOT NULL AND external_thread_id = ?
153
+ ORDER BY rowid DESC LIMIT 1`,
154
+ )
155
+ .get(
156
+ binding.conversation_id,
157
+ delivery.delivery_id,
158
+ provider.external_thread_id,
159
+ );
160
+ const replyParent =
161
+ binding.current_reply_parent_external_id ||
162
+ previous?.current_reply_parent_external_id ||
163
+ previous?.external_id ||
164
+ provider.external_id;
165
+ const updated = db
166
+ .prepare(
167
+ `UPDATE provider_reply_binding
168
+ SET external_id = ?, external_thread_id = ?,
169
+ current_reply_parent_external_id = ?
170
+ WHERE delivery_id = ?`,
171
+ )
172
+ .run(
173
+ provider.external_id,
174
+ provider.external_thread_id,
175
+ replyParent,
176
+ delivery.delivery_id,
177
+ );
178
+ if (updated.changes !== 1)
179
+ throw new Error("Tightbeam provider acceptance could not be recorded");
180
+ });
181
+ }
182
+
183
+ export async function recordInboundProviderAcceptance(home, record) {
184
+ await mutateProviderMap(home, (db) => {
185
+ const hasProviderThread = typeof record.provider_thread_id === "string";
186
+ const bindings = db
187
+ .prepare(
188
+ `SELECT delivery_id, conversation_id, external_id, external_thread_id
189
+ FROM provider_reply_binding
190
+ WHERE reply_binding = ?${hasProviderThread ? " AND external_thread_id = ?" : ""}`,
191
+ )
192
+ .all(
193
+ record.reply_binding,
194
+ ...(hasProviderThread ? [record.provider_thread_id] : []),
195
+ );
196
+ if (bindings.length !== 1 || typeof bindings[0].external_id !== "string") {
197
+ throw new Error("Tightbeam provider reply binding is not accepted");
198
+ }
199
+ const binding = bindings[0];
200
+ const providerThreadId = binding.external_thread_id;
201
+ if (
202
+ typeof record.tightbeam_conversation_id === "string" &&
203
+ record.tightbeam_conversation_id !== binding.conversation_id
204
+ ) {
205
+ throw new Error(
206
+ "Tightbeam inbound conversation does not match its provider binding",
207
+ );
208
+ }
209
+
210
+ const existing = db
211
+ .prepare(
212
+ `SELECT provider_thread_id, delivery_id, reply_binding, tightbeam_message_id
213
+ FROM provider_reply_parent_event
214
+ WHERE provider_message_id = ?`,
215
+ )
216
+ .get(record.provider_message_id);
217
+ if (existing) {
218
+ if (
219
+ existing.provider_thread_id !== providerThreadId ||
220
+ existing.delivery_id !== binding.delivery_id ||
221
+ existing.reply_binding !== record.reply_binding ||
222
+ existing.tightbeam_message_id !== record.tightbeam_message_id
223
+ ) {
224
+ throw new Error(
225
+ "Provider inbound event is bound to different reply authority",
226
+ );
227
+ }
228
+ return;
229
+ }
230
+
231
+ db.prepare(
232
+ `INSERT INTO provider_reply_parent_event
233
+ (provider_message_id, provider_thread_id, delivery_id, reply_binding, tightbeam_message_id)
234
+ VALUES (?, ?, ?, ?, ?)`,
235
+ ).run(
236
+ record.provider_message_id,
237
+ providerThreadId,
238
+ binding.delivery_id,
239
+ record.reply_binding,
240
+ record.tightbeam_message_id,
241
+ );
242
+ const updated = db
243
+ .prepare(
244
+ `UPDATE provider_reply_binding
245
+ SET current_reply_parent_external_id = ?
246
+ WHERE delivery_id = ? AND reply_binding = ? AND external_thread_id = ?`,
247
+ )
248
+ .run(
249
+ record.provider_message_id,
250
+ binding.delivery_id,
251
+ record.reply_binding,
252
+ providerThreadId,
253
+ );
254
+ if (updated.changes !== 1) {
255
+ throw new Error("Tightbeam provider reply parent could not be advanced");
256
+ }
257
+ });
258
+ }
259
+
260
+ export async function recordProviderMap(home, record) {
261
+ await mutateProviderMap(home, (db) => {
262
+ db.prepare(
263
+ `INSERT INTO provider_acceptance (
264
+ delivery_id, message_id, conversation_id, route_id, external_id, external_thread_id
265
+ , origin_endpoint_id, origin_session_id
266
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
267
+ ON CONFLICT(delivery_id) DO UPDATE SET
268
+ message_id = excluded.message_id,
269
+ conversation_id = excluded.conversation_id,
270
+ route_id = excluded.route_id,
271
+ origin_endpoint_id = excluded.origin_endpoint_id,
272
+ origin_session_id = excluded.origin_session_id,
273
+ external_id = excluded.external_id,
274
+ external_thread_id = excluded.external_thread_id`,
275
+ ).run(
276
+ record.delivery_id,
277
+ record.message_id,
278
+ record.conversation_id,
279
+ record.route_id,
280
+ record.external_id,
281
+ record.external_thread_id,
282
+ record.origin_endpoint_id,
283
+ record.origin_session_id,
284
+ );
285
+ });
286
+ }
287
+
288
+ export function lookupProviderMap(home, column, value) {
289
+ const db = openProviderMap(home, { readOnly: true });
290
+ if (!db) return null;
291
+ try {
292
+ const latest =
293
+ column === "delivery_id" ? "" : " ORDER BY rowid DESC LIMIT 1";
294
+ return (
295
+ db
296
+ .prepare(
297
+ `SELECT delivery_id, message_id, conversation_id, route_id, origin_endpoint_id, origin_session_id, external_id, external_thread_id FROM provider_acceptance WHERE ${column} = ?${latest}`,
298
+ )
299
+ .get(value) || null
300
+ );
301
+ } finally {
302
+ db.close();
303
+ }
304
+ }
305
+
306
+ export function lookupProviderReplyBinding(home, column, value) {
307
+ const db = openProviderMap(home, { readOnly: true });
308
+ if (!db) return null;
309
+ try {
310
+ const columns = new Set(
311
+ db
312
+ .prepare("PRAGMA table_info(provider_reply_binding)")
313
+ .all()
314
+ .map(({ name }) => name),
315
+ );
316
+ const currentReplyParent = columns.has("current_reply_parent_external_id")
317
+ ? "current_reply_parent_external_id"
318
+ : "external_id AS current_reply_parent_external_id";
319
+ const accepted =
320
+ column === "delivery_id"
321
+ ? ""
322
+ : " AND external_id IS NOT NULL AND external_thread_id IS NOT NULL";
323
+ const latest =
324
+ column === "delivery_id" ? "" : " ORDER BY rowid DESC LIMIT 1";
325
+ return (
326
+ db
327
+ .prepare(
328
+ `SELECT delivery_id, reply_binding, conversation_id, external_id, external_thread_id,
329
+ ${currentReplyParent}
330
+ FROM provider_reply_binding WHERE ${column} = ?${accepted}${latest}`,
331
+ )
332
+ .get(value) || null
333
+ );
334
+ } finally {
335
+ db.close();
336
+ }
337
+ }