@pingagent/sdk 0.1.7 → 0.1.9

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.
@@ -0,0 +1,2433 @@
1
+ // src/client.ts
2
+ import { SCHEMA_TASK, SCHEMA_CONTACT_REQUEST, SCHEMA_RESULT, SCHEMA_TEXT } from "@pingagent/schemas";
3
+ import {
4
+ buildUnsignedEnvelope,
5
+ signEnvelope
6
+ } from "@pingagent/protocol";
7
+
8
+ // src/transport.ts
9
+ import { ErrorCode } from "@pingagent/schemas";
10
+ var HttpTransport = class {
11
+ serverUrl;
12
+ accessToken;
13
+ maxRetries;
14
+ onTokenRefreshed;
15
+ constructor(opts) {
16
+ this.serverUrl = opts.serverUrl.replace(/\/$/, "");
17
+ this.accessToken = opts.accessToken;
18
+ this.maxRetries = opts.maxRetries ?? 3;
19
+ this.onTokenRefreshed = opts.onTokenRefreshed;
20
+ }
21
+ setToken(token) {
22
+ this.accessToken = token;
23
+ }
24
+ /** Fetch a URL with Bearer auth (e.g. artifact upload/download). */
25
+ async fetchWithAuth(url, options = {}) {
26
+ const headers = { Authorization: `Bearer ${this.accessToken}` };
27
+ if (options.contentType) headers["Content-Type"] = options.contentType;
28
+ const res = await fetch(url, {
29
+ method: options.method ?? "GET",
30
+ headers,
31
+ body: options.body ?? void 0
32
+ });
33
+ if (!res.ok) {
34
+ const text = await res.text();
35
+ throw new Error(`Request failed (${res.status}): ${text.slice(0, 200)}`);
36
+ }
37
+ return res.arrayBuffer();
38
+ }
39
+ async request(method, path4, body, skipAuth = false) {
40
+ const url = `${this.serverUrl}${path4}`;
41
+ const headers = {
42
+ "Content-Type": "application/json"
43
+ };
44
+ if (!skipAuth) {
45
+ headers["Authorization"] = `Bearer ${this.accessToken}`;
46
+ }
47
+ let lastError = null;
48
+ const delays = [1e3, 2e3, 4e3];
49
+ for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
50
+ try {
51
+ const res = await fetch(url, {
52
+ method,
53
+ headers,
54
+ body: body ? JSON.stringify(body) : void 0
55
+ });
56
+ const text = await res.text();
57
+ let data;
58
+ try {
59
+ data = text ? JSON.parse(text) : {};
60
+ } catch {
61
+ throw new Error(`Server returned non-JSON (${res.status}): ${text.slice(0, 200)}`);
62
+ }
63
+ if (res.status === 401 && data.error?.code === ErrorCode.TOKEN_EXPIRED && attempt === 0) {
64
+ const refreshed = await this.refreshToken();
65
+ if (refreshed) {
66
+ headers["Authorization"] = `Bearer ${this.accessToken}`;
67
+ continue;
68
+ }
69
+ }
70
+ if (res.status === 429 && data.error?.retry_after_ms) {
71
+ await sleep(data.error.retry_after_ms);
72
+ continue;
73
+ }
74
+ if (res.status >= 500 && attempt < this.maxRetries) {
75
+ await sleep(delays[attempt] ?? 4e3);
76
+ continue;
77
+ }
78
+ return data;
79
+ } catch (e) {
80
+ lastError = e;
81
+ if (attempt < this.maxRetries) {
82
+ await sleep(delays[attempt] ?? 4e3);
83
+ }
84
+ }
85
+ }
86
+ throw lastError ?? new Error("Request failed after retries");
87
+ }
88
+ async refreshToken() {
89
+ try {
90
+ const res = await fetch(`${this.serverUrl}/v1/auth/refresh`, {
91
+ method: "POST",
92
+ headers: { "Content-Type": "application/json" },
93
+ body: JSON.stringify({ access_token: this.accessToken })
94
+ });
95
+ if (!res.ok) return false;
96
+ const text = await res.text();
97
+ let data;
98
+ try {
99
+ data = text ? JSON.parse(text) : {};
100
+ } catch {
101
+ return false;
102
+ }
103
+ if (!data.ok || !data.data) return false;
104
+ this.accessToken = data.data.access_token;
105
+ const expiresAt = Date.now() + data.data.expires_ms;
106
+ this.onTokenRefreshed?.(data.data.access_token, expiresAt);
107
+ return true;
108
+ } catch {
109
+ return false;
110
+ }
111
+ }
112
+ };
113
+ function sleep(ms) {
114
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
115
+ }
116
+
117
+ // src/contacts.ts
118
+ function rowToContact(row) {
119
+ return {
120
+ did: row.did,
121
+ alias: row.alias ?? void 0,
122
+ display_name: row.display_name ?? void 0,
123
+ notes: row.notes ?? void 0,
124
+ conversation_id: row.conversation_id ?? void 0,
125
+ trusted: row.trusted === 1,
126
+ added_at: row.added_at,
127
+ last_message_at: row.last_message_at ?? void 0,
128
+ tags: row.tags ? JSON.parse(row.tags) : void 0
129
+ };
130
+ }
131
+ var ContactManager = class {
132
+ store;
133
+ constructor(store) {
134
+ this.store = store;
135
+ }
136
+ add(contact) {
137
+ const db = this.store.getDb();
138
+ const now = contact.added_at ?? Date.now();
139
+ db.prepare(`
140
+ INSERT INTO contacts (did, alias, display_name, notes, conversation_id, trusted, added_at, last_message_at, tags)
141
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
142
+ ON CONFLICT(did) DO UPDATE SET
143
+ alias = COALESCE(excluded.alias, contacts.alias),
144
+ display_name = COALESCE(excluded.display_name, contacts.display_name),
145
+ notes = COALESCE(excluded.notes, contacts.notes),
146
+ conversation_id = COALESCE(excluded.conversation_id, contacts.conversation_id),
147
+ trusted = excluded.trusted,
148
+ last_message_at = COALESCE(excluded.last_message_at, contacts.last_message_at),
149
+ tags = COALESCE(excluded.tags, contacts.tags)
150
+ `).run(
151
+ contact.did,
152
+ contact.alias ?? null,
153
+ contact.display_name ?? null,
154
+ contact.notes ?? null,
155
+ contact.conversation_id ?? null,
156
+ contact.trusted ? 1 : 0,
157
+ now,
158
+ contact.last_message_at ?? null,
159
+ contact.tags ? JSON.stringify(contact.tags) : null
160
+ );
161
+ return { ...contact, added_at: now };
162
+ }
163
+ remove(did) {
164
+ const result = this.store.getDb().prepare("DELETE FROM contacts WHERE did = ?").run(did);
165
+ return result.changes > 0;
166
+ }
167
+ get(did) {
168
+ const row = this.store.getDb().prepare("SELECT * FROM contacts WHERE did = ?").get(did);
169
+ return row ? rowToContact(row) : null;
170
+ }
171
+ update(did, updates) {
172
+ const existing = this.get(did);
173
+ if (!existing) return null;
174
+ const fields = [];
175
+ const values = [];
176
+ if (updates.alias !== void 0) {
177
+ fields.push("alias = ?");
178
+ values.push(updates.alias);
179
+ }
180
+ if (updates.display_name !== void 0) {
181
+ fields.push("display_name = ?");
182
+ values.push(updates.display_name);
183
+ }
184
+ if (updates.notes !== void 0) {
185
+ fields.push("notes = ?");
186
+ values.push(updates.notes);
187
+ }
188
+ if (updates.conversation_id !== void 0) {
189
+ fields.push("conversation_id = ?");
190
+ values.push(updates.conversation_id);
191
+ }
192
+ if (updates.trusted !== void 0) {
193
+ fields.push("trusted = ?");
194
+ values.push(updates.trusted ? 1 : 0);
195
+ }
196
+ if (updates.last_message_at !== void 0) {
197
+ fields.push("last_message_at = ?");
198
+ values.push(updates.last_message_at);
199
+ }
200
+ if (updates.tags !== void 0) {
201
+ fields.push("tags = ?");
202
+ values.push(JSON.stringify(updates.tags));
203
+ }
204
+ if (fields.length === 0) return existing;
205
+ values.push(did);
206
+ this.store.getDb().prepare(`UPDATE contacts SET ${fields.join(", ")} WHERE did = ?`).run(...values);
207
+ return this.get(did);
208
+ }
209
+ list(opts) {
210
+ const conditions = [];
211
+ const params = [];
212
+ if (opts?.trusted !== void 0) {
213
+ conditions.push("trusted = ?");
214
+ params.push(opts.trusted ? 1 : 0);
215
+ }
216
+ if (opts?.tag) {
217
+ conditions.push("tags LIKE ?");
218
+ params.push(`%"${opts.tag}"%`);
219
+ }
220
+ const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
221
+ const limit = opts?.limit ? `LIMIT ${opts.limit}` : "";
222
+ const offset = opts?.offset ? `OFFSET ${opts.offset}` : "";
223
+ const rows = this.store.getDb().prepare(`SELECT * FROM contacts ${where} ORDER BY added_at DESC ${limit} ${offset}`).all(...params);
224
+ return rows.map(rowToContact);
225
+ }
226
+ search(query) {
227
+ const pattern = `%${query}%`;
228
+ const rows = this.store.getDb().prepare(`
229
+ SELECT * FROM contacts
230
+ WHERE did LIKE ? OR alias LIKE ? OR display_name LIKE ? OR notes LIKE ?
231
+ ORDER BY added_at DESC
232
+ `).all(pattern, pattern, pattern, pattern);
233
+ return rows.map(rowToContact);
234
+ }
235
+ export(format = "json") {
236
+ const contacts = this.list();
237
+ if (format === "csv") {
238
+ const header = "did,alias,display_name,notes,conversation_id,trusted,added_at,last_message_at,tags";
239
+ const rows = contacts.map(
240
+ (c) => [
241
+ c.did,
242
+ c.alias ?? "",
243
+ c.display_name ?? "",
244
+ c.notes ?? "",
245
+ c.conversation_id ?? "",
246
+ c.trusted,
247
+ c.added_at,
248
+ c.last_message_at ?? "",
249
+ c.tags ? JSON.stringify(c.tags) : ""
250
+ ].map((v) => `"${String(v).replace(/"/g, '""')}"`).join(",")
251
+ );
252
+ return [header, ...rows].join("\n");
253
+ }
254
+ return JSON.stringify(contacts, null, 2);
255
+ }
256
+ import(data, format = "json") {
257
+ let imported = 0;
258
+ let skipped = 0;
259
+ if (format === "json") {
260
+ const contacts = JSON.parse(data);
261
+ for (const c of contacts) {
262
+ try {
263
+ this.add(c);
264
+ imported++;
265
+ } catch {
266
+ skipped++;
267
+ }
268
+ }
269
+ } else {
270
+ const lines = data.split("\n").filter((l) => l.trim());
271
+ for (let i = 1; i < lines.length; i++) {
272
+ try {
273
+ const cols = parseCsvLine(lines[i]);
274
+ this.add({
275
+ did: cols[0],
276
+ alias: cols[1] || void 0,
277
+ display_name: cols[2] || void 0,
278
+ notes: cols[3] || void 0,
279
+ conversation_id: cols[4] || void 0,
280
+ trusted: cols[5] === "1" || cols[5] === "true",
281
+ added_at: parseInt(cols[6]) || Date.now(),
282
+ last_message_at: cols[7] ? parseInt(cols[7]) : void 0,
283
+ tags: cols[8] ? JSON.parse(cols[8]) : void 0
284
+ });
285
+ imported++;
286
+ } catch {
287
+ skipped++;
288
+ }
289
+ }
290
+ }
291
+ return { imported, skipped };
292
+ }
293
+ };
294
+ function parseCsvLine(line) {
295
+ const result = [];
296
+ let current = "";
297
+ let inQuotes = false;
298
+ for (let i = 0; i < line.length; i++) {
299
+ const ch = line[i];
300
+ if (inQuotes) {
301
+ if (ch === '"' && line[i + 1] === '"') {
302
+ current += '"';
303
+ i++;
304
+ } else if (ch === '"') {
305
+ inQuotes = false;
306
+ } else {
307
+ current += ch;
308
+ }
309
+ } else {
310
+ if (ch === '"') {
311
+ inQuotes = true;
312
+ } else if (ch === ",") {
313
+ result.push(current);
314
+ current = "";
315
+ } else {
316
+ current += ch;
317
+ }
318
+ }
319
+ }
320
+ result.push(current);
321
+ return result;
322
+ }
323
+
324
+ // src/history.ts
325
+ function rowToMessage(row) {
326
+ return {
327
+ conversation_id: row.conversation_id,
328
+ message_id: row.message_id,
329
+ seq: row.seq ?? void 0,
330
+ sender_did: row.sender_did,
331
+ schema: row.schema,
332
+ payload: JSON.parse(row.payload),
333
+ ts_ms: row.ts_ms,
334
+ direction: row.direction
335
+ };
336
+ }
337
+ var HistoryManager = class {
338
+ store;
339
+ constructor(store) {
340
+ this.store = store;
341
+ }
342
+ save(messages) {
343
+ const db = this.store.getDb();
344
+ const stmt = db.prepare(`
345
+ INSERT INTO messages (conversation_id, message_id, seq, sender_did, schema, payload, ts_ms, direction)
346
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
347
+ ON CONFLICT(message_id) DO UPDATE SET
348
+ seq = COALESCE(excluded.seq, messages.seq),
349
+ payload = excluded.payload,
350
+ ts_ms = excluded.ts_ms
351
+ `);
352
+ let count = 0;
353
+ const tx = db.transaction(() => {
354
+ for (const msg of messages) {
355
+ stmt.run(
356
+ msg.conversation_id,
357
+ msg.message_id,
358
+ msg.seq ?? null,
359
+ msg.sender_did,
360
+ msg.schema,
361
+ JSON.stringify(msg.payload),
362
+ msg.ts_ms,
363
+ msg.direction
364
+ );
365
+ count++;
366
+ }
367
+ });
368
+ tx();
369
+ return count;
370
+ }
371
+ list(conversationId, opts) {
372
+ const conditions = ["conversation_id = ?"];
373
+ const params = [conversationId];
374
+ if (opts?.beforeSeq !== void 0) {
375
+ conditions.push("seq < ?");
376
+ params.push(opts.beforeSeq);
377
+ }
378
+ if (opts?.afterSeq !== void 0) {
379
+ conditions.push("seq > ?");
380
+ params.push(opts.afterSeq);
381
+ }
382
+ if (opts?.beforeTsMs !== void 0) {
383
+ conditions.push("ts_ms < ?");
384
+ params.push(opts.beforeTsMs);
385
+ }
386
+ if (opts?.afterTsMs !== void 0) {
387
+ conditions.push("ts_ms > ?");
388
+ params.push(opts.afterTsMs);
389
+ }
390
+ const limit = opts?.limit ?? 100;
391
+ const rows = this.store.getDb().prepare(`SELECT * FROM messages WHERE ${conditions.join(" AND ")} ORDER BY COALESCE(seq, ts_ms) ASC LIMIT ?`).all(...params, limit);
392
+ return rows.map(rowToMessage);
393
+ }
394
+ /**
395
+ * List the most recent N messages *before* a seq (paging older history).
396
+ * Only compares rows where seq is not null.
397
+ */
398
+ listBeforeSeq(conversationId, beforeSeq, limit) {
399
+ const rows = this.store.getDb().prepare(
400
+ `SELECT * FROM messages
401
+ WHERE conversation_id = ? AND seq IS NOT NULL AND seq < ?
402
+ ORDER BY seq DESC
403
+ LIMIT ?`
404
+ ).all(conversationId, beforeSeq, limit);
405
+ return rows.map(rowToMessage).reverse();
406
+ }
407
+ /**
408
+ * List the most recent N messages *before* a timestamp (paging older history).
409
+ */
410
+ listBeforeTs(conversationId, beforeTsMs, limit) {
411
+ const rows = this.store.getDb().prepare(
412
+ `SELECT * FROM messages
413
+ WHERE conversation_id = ? AND ts_ms < ?
414
+ ORDER BY ts_ms DESC
415
+ LIMIT ?`
416
+ ).all(conversationId, beforeTsMs, limit);
417
+ return rows.map(rowToMessage).reverse();
418
+ }
419
+ /** Returns the N most recent messages (chronological order, oldest to newest of those N). */
420
+ listRecent(conversationId, limit) {
421
+ const rows = this.store.getDb().prepare(
422
+ `SELECT * FROM messages WHERE conversation_id = ? ORDER BY COALESCE(seq, ts_ms) DESC LIMIT ?`
423
+ ).all(conversationId, limit);
424
+ return rows.map(rowToMessage).reverse();
425
+ }
426
+ search(query, opts) {
427
+ const conditions = ["payload LIKE ?"];
428
+ const params = [`%${query}%`];
429
+ if (opts?.conversationId) {
430
+ conditions.push("conversation_id = ?");
431
+ params.push(opts.conversationId);
432
+ }
433
+ const limit = opts?.limit ?? 50;
434
+ const rows = this.store.getDb().prepare(`SELECT * FROM messages WHERE ${conditions.join(" AND ")} ORDER BY ts_ms DESC LIMIT ?`).all(...params, limit);
435
+ return rows.map(rowToMessage);
436
+ }
437
+ delete(conversationId) {
438
+ const result = this.store.getDb().prepare("DELETE FROM messages WHERE conversation_id = ?").run(conversationId);
439
+ this.store.getDb().prepare("DELETE FROM sync_state WHERE conversation_id = ?").run(conversationId);
440
+ return result.changes;
441
+ }
442
+ listConversations() {
443
+ const rows = this.store.getDb().prepare(`
444
+ SELECT conversation_id, COUNT(*) as message_count, MAX(ts_ms) as last_message_at
445
+ FROM messages
446
+ GROUP BY conversation_id
447
+ ORDER BY last_message_at DESC
448
+ `).all();
449
+ return rows;
450
+ }
451
+ getLastSyncedSeq(conversationId) {
452
+ const row = this.store.getDb().prepare("SELECT last_synced_seq FROM sync_state WHERE conversation_id = ?").get(conversationId);
453
+ return row?.last_synced_seq ?? 0;
454
+ }
455
+ setLastSyncedSeq(conversationId, seq) {
456
+ this.store.getDb().prepare(`
457
+ INSERT INTO sync_state (conversation_id, last_synced_seq, last_synced_at)
458
+ VALUES (?, ?, ?)
459
+ ON CONFLICT(conversation_id) DO UPDATE SET last_synced_seq = excluded.last_synced_seq, last_synced_at = excluded.last_synced_at
460
+ `).run(conversationId, seq, Date.now());
461
+ }
462
+ export(opts) {
463
+ const format = opts?.format ?? "json";
464
+ let messages;
465
+ if (opts?.conversationId) {
466
+ messages = this.list(opts.conversationId, { limit: 1e5 });
467
+ } else {
468
+ const rows = this.store.getDb().prepare("SELECT * FROM messages ORDER BY ts_ms ASC").all();
469
+ messages = rows.map(rowToMessage);
470
+ }
471
+ if (format === "csv") {
472
+ const header = "conversation_id,message_id,seq,sender_did,schema,payload,ts_ms,direction";
473
+ const lines = messages.map(
474
+ (m) => [
475
+ m.conversation_id,
476
+ m.message_id,
477
+ m.seq ?? "",
478
+ m.sender_did,
479
+ m.schema,
480
+ JSON.stringify(m.payload),
481
+ m.ts_ms,
482
+ m.direction
483
+ ].map((v) => `"${String(v).replace(/"/g, '""')}"`).join(",")
484
+ );
485
+ return [header, ...lines].join("\n");
486
+ }
487
+ return JSON.stringify(messages, null, 2);
488
+ }
489
+ async syncFromServer(client, conversationId, opts) {
490
+ const sinceSeq = opts?.full ? 0 : this.getLastSyncedSeq(conversationId);
491
+ let totalSynced = 0;
492
+ let currentSeq = sinceSeq;
493
+ while (true) {
494
+ const res = await client.fetchInbox(conversationId, {
495
+ sinceSeq: currentSeq,
496
+ limit: 50
497
+ });
498
+ if (!res.ok || !res.data || res.data.messages.length === 0) break;
499
+ const messages = res.data.messages.map((msg) => ({
500
+ conversation_id: conversationId,
501
+ message_id: msg.message_id,
502
+ seq: msg.seq,
503
+ sender_did: msg.sender_did,
504
+ schema: msg.schema,
505
+ payload: msg.payload,
506
+ ts_ms: msg.ts_ms,
507
+ direction: "received"
508
+ }));
509
+ this.save(messages);
510
+ totalSynced += messages.length;
511
+ currentSeq = res.data.next_since_seq;
512
+ this.setLastSyncedSeq(conversationId, currentSeq);
513
+ if (!res.data.has_more) break;
514
+ }
515
+ return { synced: totalSynced };
516
+ }
517
+ async listMergedRecent(client, conversationId, opts) {
518
+ const limit = opts?.limit ?? 50;
519
+ const box = opts?.box ?? "ready";
520
+ const local = this.listRecent(conversationId, limit * 2);
521
+ const remoteRes = await client.fetchInbox(conversationId, { sinceSeq: 0, limit, box: box === "all" ? "ready" : box });
522
+ const remote = remoteRes.ok && remoteRes.data ? remoteRes.data.messages.map((msg) => ({
523
+ conversation_id: conversationId,
524
+ message_id: msg.message_id,
525
+ seq: msg.seq,
526
+ sender_did: msg.sender_did,
527
+ schema: msg.schema,
528
+ payload: msg.payload,
529
+ ts_ms: msg.ts_ms,
530
+ direction: msg.sender_did === client.getDid() ? "sent" : "received"
531
+ })) : [];
532
+ const byId = /* @__PURE__ */ new Map();
533
+ for (const msg of [...local, ...remote]) byId.set(msg.message_id, msg);
534
+ return Array.from(byId.values()).sort((a, b) => (a.seq ?? a.ts_ms) - (b.seq ?? b.ts_ms)).slice(-limit);
535
+ }
536
+ };
537
+
538
+ // src/session.ts
539
+ function rowToSession(row) {
540
+ return {
541
+ session_key: row.session_key,
542
+ remote_did: row.remote_did ?? void 0,
543
+ conversation_id: row.conversation_id ?? void 0,
544
+ trust_state: row.trust_state || "stranger",
545
+ last_message_preview: row.last_message_preview ?? void 0,
546
+ last_remote_activity_at: row.last_remote_activity_at ?? void 0,
547
+ last_read_seq: row.last_read_seq ?? 0,
548
+ unread_count: row.unread_count ?? 0,
549
+ active: row.active === 1,
550
+ updated_at: row.updated_at ?? 0
551
+ };
552
+ }
553
+ function previewFromPayload(payload) {
554
+ if (payload == null) return "";
555
+ if (typeof payload === "string") return payload.slice(0, 280);
556
+ if (typeof payload !== "object") return String(payload).slice(0, 280);
557
+ const value = payload;
558
+ const preferred = value.text ?? value.title ?? value.summary ?? value.message ?? value.description ?? value.error_message;
559
+ if (typeof preferred === "string") return preferred.slice(0, 280);
560
+ return JSON.stringify(payload).slice(0, 280);
561
+ }
562
+ function buildSessionKey(opts) {
563
+ const type = opts.conversationType ?? "";
564
+ if (type === "channel" || type === "group" || opts.conversationId.startsWith("c_grp_")) {
565
+ return `hook:im:conv:${opts.conversationId}`;
566
+ }
567
+ const remote = (opts.remoteDid ?? "").trim();
568
+ if (!remote) {
569
+ return `hook:im:conv:${opts.conversationId}`;
570
+ }
571
+ const local = (opts.localDid ?? "").trim();
572
+ if (!local) {
573
+ return `hook:im:peer:${remote}:conv:${opts.conversationId}`;
574
+ }
575
+ return `hook:im:did:${local}:peer:${remote}`;
576
+ }
577
+ var SessionManager = class {
578
+ constructor(store) {
579
+ this.store = store;
580
+ }
581
+ upsert(state) {
582
+ const now = state.updated_at ?? Date.now();
583
+ const existing = this.get(state.session_key);
584
+ const next = {
585
+ session_key: state.session_key,
586
+ remote_did: state.remote_did ?? existing?.remote_did,
587
+ conversation_id: state.conversation_id ?? existing?.conversation_id,
588
+ trust_state: state.trust_state ?? existing?.trust_state ?? "stranger",
589
+ last_message_preview: state.last_message_preview ?? existing?.last_message_preview,
590
+ last_remote_activity_at: state.last_remote_activity_at ?? existing?.last_remote_activity_at,
591
+ last_read_seq: state.last_read_seq ?? existing?.last_read_seq ?? 0,
592
+ unread_count: state.unread_count ?? existing?.unread_count ?? 0,
593
+ active: state.active ?? existing?.active ?? false,
594
+ updated_at: now
595
+ };
596
+ if (next.active) {
597
+ this.store.getDb().prepare("UPDATE session_state SET active = 0 WHERE session_key != ?").run(next.session_key);
598
+ }
599
+ this.store.getDb().prepare(`
600
+ INSERT INTO session_state (
601
+ session_key, remote_did, conversation_id, trust_state, last_message_preview,
602
+ last_remote_activity_at, last_read_seq, unread_count, active, updated_at
603
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
604
+ ON CONFLICT(session_key) DO UPDATE SET
605
+ remote_did = COALESCE(excluded.remote_did, session_state.remote_did),
606
+ conversation_id = COALESCE(excluded.conversation_id, session_state.conversation_id),
607
+ trust_state = excluded.trust_state,
608
+ last_message_preview = COALESCE(excluded.last_message_preview, session_state.last_message_preview),
609
+ last_remote_activity_at = COALESCE(excluded.last_remote_activity_at, session_state.last_remote_activity_at),
610
+ last_read_seq = excluded.last_read_seq,
611
+ unread_count = excluded.unread_count,
612
+ active = excluded.active,
613
+ updated_at = excluded.updated_at
614
+ `).run(
615
+ next.session_key,
616
+ next.remote_did ?? null,
617
+ next.conversation_id ?? null,
618
+ next.trust_state,
619
+ next.last_message_preview ?? null,
620
+ next.last_remote_activity_at ?? null,
621
+ next.last_read_seq,
622
+ next.unread_count,
623
+ next.active ? 1 : 0,
624
+ next.updated_at
625
+ );
626
+ return next;
627
+ }
628
+ upsertFromMessage(input) {
629
+ const sessionKey = input.session_key ?? buildSessionKey({
630
+ localDid: "",
631
+ remoteDid: input.remote_did ?? input.sender_did ?? "",
632
+ conversationId: input.conversation_id
633
+ });
634
+ const existing = this.get(sessionKey);
635
+ const preview = previewFromPayload(input.payload);
636
+ const isRemote = input.sender_is_self !== true;
637
+ const seq = input.seq ?? 0;
638
+ const lastReadSeq = existing?.last_read_seq ?? 0;
639
+ const unreadCount = isRemote && seq > lastReadSeq ? Math.max(existing?.unread_count ?? 0, seq - lastReadSeq) : existing?.unread_count ?? 0;
640
+ const activity = isRemote ? input.ts_ms ?? Date.now() : existing?.last_remote_activity_at;
641
+ return this.upsert({
642
+ session_key: sessionKey,
643
+ remote_did: input.remote_did ?? existing?.remote_did ?? (isRemote ? input.sender_did : void 0),
644
+ conversation_id: input.conversation_id,
645
+ trust_state: input.trust_state ?? existing?.trust_state ?? "stranger",
646
+ last_message_preview: preview || existing?.last_message_preview,
647
+ last_remote_activity_at: activity,
648
+ last_read_seq: existing?.last_read_seq ?? 0,
649
+ unread_count: unreadCount,
650
+ active: existing?.active ?? false,
651
+ updated_at: input.ts_ms ?? Date.now()
652
+ });
653
+ }
654
+ get(sessionKey) {
655
+ const row = this.store.getDb().prepare("SELECT * FROM session_state WHERE session_key = ?").get(sessionKey);
656
+ return row ? rowToSession(row) : null;
657
+ }
658
+ getByConversationId(conversationId) {
659
+ const row = this.store.getDb().prepare("SELECT * FROM session_state WHERE conversation_id = ? ORDER BY updated_at DESC LIMIT 1").get(conversationId);
660
+ return row ? rowToSession(row) : null;
661
+ }
662
+ getActiveSession() {
663
+ const row = this.store.getDb().prepare("SELECT * FROM session_state WHERE active = 1 ORDER BY updated_at DESC LIMIT 1").get();
664
+ return row ? rowToSession(row) : null;
665
+ }
666
+ listRecentSessions(limit = 20) {
667
+ const rows = this.store.getDb().prepare("SELECT * FROM session_state ORDER BY COALESCE(last_remote_activity_at, updated_at) DESC, updated_at DESC LIMIT ?").all(limit);
668
+ return rows.map(rowToSession);
669
+ }
670
+ focusSession(sessionKey) {
671
+ const session = this.get(sessionKey);
672
+ if (!session) return null;
673
+ this.store.getDb().prepare("UPDATE session_state SET active = CASE WHEN session_key = ? THEN 1 ELSE 0 END").run(sessionKey);
674
+ return this.get(sessionKey);
675
+ }
676
+ markRead(sessionKey, seq) {
677
+ const session = this.get(sessionKey);
678
+ if (!session) return null;
679
+ const lastReadSeq = Math.max(session.last_read_seq, seq ?? session.last_read_seq);
680
+ return this.upsert({
681
+ session_key: sessionKey,
682
+ last_read_seq: lastReadSeq,
683
+ unread_count: 0,
684
+ active: session.active
685
+ });
686
+ }
687
+ nextUnread() {
688
+ const row = this.store.getDb().prepare("SELECT * FROM session_state WHERE unread_count > 0 ORDER BY last_remote_activity_at DESC, updated_at DESC LIMIT 1").get();
689
+ return row ? rowToSession(row) : null;
690
+ }
691
+ resolveReplyTarget(sessionKey) {
692
+ const session = sessionKey ? this.get(sessionKey) : this.getActiveSession();
693
+ if (!session) return null;
694
+ return {
695
+ session_key: session.session_key,
696
+ remote_did: session.remote_did,
697
+ conversation_id: session.conversation_id,
698
+ trust_state: session.trust_state
699
+ };
700
+ }
701
+ };
702
+
703
+ // src/task-threads.ts
704
+ function rowToThread(row) {
705
+ return {
706
+ task_id: row.task_id,
707
+ session_key: row.session_key,
708
+ conversation_id: row.conversation_id,
709
+ title: row.title ?? void 0,
710
+ status: row.status,
711
+ started_at: row.started_at ?? void 0,
712
+ updated_at: row.updated_at,
713
+ result_summary: row.result_summary ?? void 0,
714
+ error_code: row.error_code ?? void 0,
715
+ error_message: row.error_message ?? void 0
716
+ };
717
+ }
718
+ var TaskThreadManager = class {
719
+ constructor(store) {
720
+ this.store = store;
721
+ }
722
+ upsert(thread) {
723
+ const updatedAt = thread.updated_at ?? Date.now();
724
+ const existing = this.get(thread.task_id);
725
+ this.store.getDb().prepare(`
726
+ INSERT INTO task_threads (
727
+ task_id, session_key, conversation_id, title, status, started_at, updated_at, result_summary, error_code, error_message
728
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
729
+ ON CONFLICT(task_id) DO UPDATE SET
730
+ session_key = excluded.session_key,
731
+ conversation_id = excluded.conversation_id,
732
+ title = COALESCE(excluded.title, task_threads.title),
733
+ status = excluded.status,
734
+ started_at = COALESCE(excluded.started_at, task_threads.started_at),
735
+ updated_at = excluded.updated_at,
736
+ result_summary = COALESCE(excluded.result_summary, task_threads.result_summary),
737
+ error_code = COALESCE(excluded.error_code, task_threads.error_code),
738
+ error_message = COALESCE(excluded.error_message, task_threads.error_message)
739
+ `).run(
740
+ thread.task_id,
741
+ thread.session_key,
742
+ thread.conversation_id,
743
+ thread.title ?? null,
744
+ thread.status,
745
+ thread.started_at ?? existing?.started_at ?? updatedAt,
746
+ updatedAt,
747
+ thread.result_summary ?? null,
748
+ thread.error_code ?? null,
749
+ thread.error_message ?? null
750
+ );
751
+ return this.get(thread.task_id);
752
+ }
753
+ get(taskId) {
754
+ const row = this.store.getDb().prepare("SELECT * FROM task_threads WHERE task_id = ?").get(taskId);
755
+ return row ? rowToThread(row) : null;
756
+ }
757
+ listBySession(sessionKey, limit = 20) {
758
+ const rows = this.store.getDb().prepare("SELECT * FROM task_threads WHERE session_key = ? ORDER BY updated_at DESC LIMIT ?").all(sessionKey, limit);
759
+ return rows.map(rowToThread);
760
+ }
761
+ listByConversation(conversationId, limit = 20) {
762
+ const rows = this.store.getDb().prepare("SELECT * FROM task_threads WHERE conversation_id = ? ORDER BY updated_at DESC LIMIT ?").all(conversationId, limit);
763
+ return rows.map(rowToThread);
764
+ }
765
+ listRecent(limit = 20) {
766
+ const rows = this.store.getDb().prepare("SELECT * FROM task_threads ORDER BY updated_at DESC LIMIT ?").all(limit);
767
+ return rows.map(rowToThread);
768
+ }
769
+ };
770
+
771
+ // src/client.ts
772
+ var PingAgentClient = class {
773
+ constructor(opts) {
774
+ this.opts = opts;
775
+ this.identity = opts.identity;
776
+ this.transport = new HttpTransport({
777
+ serverUrl: opts.serverUrl,
778
+ accessToken: opts.accessToken,
779
+ onTokenRefreshed: opts.onTokenRefreshed
780
+ });
781
+ if (opts.store) {
782
+ this.contactManager = new ContactManager(opts.store);
783
+ this.historyManager = new HistoryManager(opts.store);
784
+ this.sessionManager = new SessionManager(opts.store);
785
+ this.taskThreadManager = new TaskThreadManager(opts.store);
786
+ }
787
+ }
788
+ transport;
789
+ identity;
790
+ contactManager;
791
+ historyManager;
792
+ sessionManager;
793
+ taskThreadManager;
794
+ getContactManager() {
795
+ return this.contactManager;
796
+ }
797
+ getHistoryManager() {
798
+ return this.historyManager;
799
+ }
800
+ getSessionManager() {
801
+ return this.sessionManager;
802
+ }
803
+ getTaskThreadManager() {
804
+ return this.taskThreadManager;
805
+ }
806
+ /** Update the in-memory access token (e.g. after proactive refresh from disk). */
807
+ setAccessToken(token) {
808
+ this.transport.setToken(token);
809
+ }
810
+ async register(developerToken) {
811
+ let binary = "";
812
+ for (const b of this.identity.publicKey) binary += String.fromCharCode(b);
813
+ const publicKeyBase64 = btoa(binary);
814
+ return this.transport.request("POST", "/v1/agent/register", {
815
+ device_id: this.identity.deviceId,
816
+ public_key: publicKeyBase64,
817
+ developer_token: developerToken
818
+ }, true);
819
+ }
820
+ async openConversation(targetDid) {
821
+ return this.transport.request("POST", "/v1/conversations/open", {
822
+ targets: [targetDid]
823
+ });
824
+ }
825
+ async sendMessage(conversationId, schema, payload) {
826
+ const ttlMs = schema === SCHEMA_TEXT ? 6048e5 : void 0;
827
+ const unsigned = buildUnsignedEnvelope({
828
+ type: "message",
829
+ conversationId,
830
+ senderDid: this.identity.did,
831
+ senderDeviceId: this.identity.deviceId,
832
+ schema,
833
+ payload,
834
+ ttlMs
835
+ });
836
+ const signed = signEnvelope(unsigned, this.identity.privateKey);
837
+ const res = await this.transport.request("POST", "/v1/messages/send", signed);
838
+ if (res.ok && this.historyManager) {
839
+ this.historyManager.save([{
840
+ conversation_id: conversationId,
841
+ message_id: signed.message_id,
842
+ seq: res.data?.seq,
843
+ sender_did: this.identity.did,
844
+ schema,
845
+ payload,
846
+ ts_ms: signed.ts_ms,
847
+ direction: "sent"
848
+ }]);
849
+ this.sessionManager?.upsertFromMessage({
850
+ session_key: this.sessionManager.getByConversationId(conversationId)?.session_key,
851
+ remote_did: this.sessionManager.getByConversationId(conversationId)?.remote_did,
852
+ conversation_id: conversationId,
853
+ trust_state: this.sessionManager.getByConversationId(conversationId)?.trust_state ?? "trusted",
854
+ sender_did: this.identity.did,
855
+ sender_is_self: true,
856
+ schema,
857
+ payload,
858
+ seq: res.data?.seq,
859
+ ts_ms: signed.ts_ms
860
+ });
861
+ }
862
+ return res;
863
+ }
864
+ async sendTask(conversationId, task) {
865
+ return this.sendMessage(conversationId, SCHEMA_TASK, {
866
+ ...task,
867
+ idempotency_key: task.task_id,
868
+ expected_output_schema: SCHEMA_RESULT
869
+ });
870
+ }
871
+ async sendContactRequest(conversationId, message) {
872
+ const { v7: uuidv7 } = await import("uuid");
873
+ return this.sendMessage(conversationId, SCHEMA_CONTACT_REQUEST, {
874
+ request_id: `r_${uuidv7()}`,
875
+ from_did: this.identity.did,
876
+ to_did: "",
877
+ capabilities: ["task", "result", "files"],
878
+ message,
879
+ expires_ms: 864e5
880
+ });
881
+ }
882
+ async fetchInbox(conversationId, opts) {
883
+ const params = new URLSearchParams({
884
+ conversation_id: conversationId,
885
+ since_seq: String(opts?.sinceSeq ?? 0),
886
+ limit: String(opts?.limit ?? 50),
887
+ box: opts?.box ?? "ready"
888
+ });
889
+ const res = await this.transport.request("GET", `/v1/inbox/fetch?${params}`);
890
+ if (res.ok && res.data && this.historyManager) {
891
+ const msgs = res.data.messages.map((msg) => ({
892
+ conversation_id: conversationId,
893
+ message_id: msg.message_id,
894
+ seq: msg.seq,
895
+ sender_did: msg.sender_did,
896
+ schema: msg.schema,
897
+ payload: msg.payload,
898
+ ts_ms: msg.ts_ms,
899
+ direction: msg.sender_did === this.identity.did ? "sent" : "received"
900
+ }));
901
+ if (msgs.length > 0) {
902
+ this.historyManager.save(msgs);
903
+ const maxSeq = Math.max(...msgs.map((m) => m.seq ?? 0));
904
+ if (maxSeq > 0) this.historyManager.setLastSyncedSeq(conversationId, maxSeq);
905
+ }
906
+ for (const msg of res.data.messages) {
907
+ const existingSession = this.sessionManager?.getByConversationId(conversationId);
908
+ this.sessionManager?.upsertFromMessage({
909
+ session_key: existingSession?.session_key,
910
+ remote_did: existingSession?.remote_did ?? (msg.sender_did !== this.identity.did ? msg.sender_did : void 0),
911
+ conversation_id: conversationId,
912
+ trust_state: existingSession?.trust_state ?? (opts?.box === "strangers" ? "pending" : "trusted"),
913
+ sender_did: msg.sender_did,
914
+ sender_is_self: msg.sender_did === this.identity.did,
915
+ schema: msg.schema,
916
+ payload: msg.payload,
917
+ seq: msg.seq,
918
+ ts_ms: msg.ts_ms
919
+ });
920
+ if (msg.schema === SCHEMA_RESULT && msg.payload?.task_id) {
921
+ const session = this.sessionManager?.getByConversationId(conversationId);
922
+ this.taskThreadManager?.upsert({
923
+ task_id: msg.payload.task_id,
924
+ session_key: session?.session_key ?? buildSessionKey({ localDid: this.identity.did, conversationId, remoteDid: session?.remote_did }),
925
+ conversation_id: conversationId,
926
+ status: msg.payload.status === "ok" ? "processed" : "failed",
927
+ updated_at: msg.ts_ms ?? Date.now(),
928
+ result_summary: msg.payload?.output?.summary,
929
+ error_code: msg.payload?.error?.code,
930
+ error_message: msg.payload?.error?.message
931
+ });
932
+ }
933
+ }
934
+ }
935
+ return res;
936
+ }
937
+ async ack(conversationId, forMessageId, status, opts) {
938
+ return this.transport.request("POST", "/v1/receipts/ack", {
939
+ conversation_id: conversationId,
940
+ for_message_id: forMessageId,
941
+ for_task_id: opts?.forTaskId,
942
+ status,
943
+ reason: opts?.reason,
944
+ detail: opts?.detail
945
+ });
946
+ }
947
+ async approveContact(conversationId) {
948
+ const res = await this.transport.request("POST", "/v1/control/approve_contact", {
949
+ conversation_id: conversationId
950
+ });
951
+ if (res.ok && this.contactManager) {
952
+ const pendingMessages = this.historyManager?.list(conversationId, { limit: 1 });
953
+ const senderDid = pendingMessages?.[0]?.sender_did;
954
+ if (senderDid && senderDid !== this.identity.did) {
955
+ this.contactManager.add({
956
+ did: senderDid,
957
+ conversation_id: res.data?.dm_conversation_id ?? conversationId,
958
+ trusted: true
959
+ });
960
+ }
961
+ }
962
+ if (res.ok) {
963
+ const existing = this.sessionManager?.getByConversationId(conversationId);
964
+ if (existing) {
965
+ this.sessionManager?.upsert({
966
+ session_key: existing.session_key,
967
+ conversation_id: res.data?.dm_conversation_id ?? conversationId,
968
+ trust_state: "trusted",
969
+ remote_did: existing.remote_did,
970
+ active: existing.active
971
+ });
972
+ }
973
+ }
974
+ return res;
975
+ }
976
+ async revokeConversation(conversationId) {
977
+ return this.transport.request("POST", "/v1/control/revoke_conversation", {
978
+ conversation_id: conversationId
979
+ });
980
+ }
981
+ async cancelTask(conversationId, taskId) {
982
+ const res = await this.transport.request("POST", "/v1/control/cancel_task", {
983
+ conversation_id: conversationId,
984
+ task_id: taskId
985
+ });
986
+ if (res.ok && res.data) {
987
+ const session = this.sessionManager?.getByConversationId(conversationId);
988
+ this.taskThreadManager?.upsert({
989
+ task_id: taskId,
990
+ session_key: session?.session_key ?? buildSessionKey({ localDid: this.identity.did, conversationId, remoteDid: session?.remote_did }),
991
+ conversation_id: conversationId,
992
+ status: normalizeTaskThreadStatus(res.data.task_state),
993
+ updated_at: Date.now()
994
+ });
995
+ }
996
+ return res;
997
+ }
998
+ async blockSender(conversationId, senderDid) {
999
+ return this.transport.request("POST", "/v1/control/block_sender", {
1000
+ conversation_id: conversationId,
1001
+ sender_did: senderDid
1002
+ });
1003
+ }
1004
+ async acquireLease(conversationId) {
1005
+ return this.transport.request("POST", "/v1/lease/acquire", {
1006
+ conversation_id: conversationId
1007
+ });
1008
+ }
1009
+ async renewLease(conversationId) {
1010
+ return this.transport.request("POST", "/v1/lease/renew", {
1011
+ conversation_id: conversationId
1012
+ });
1013
+ }
1014
+ async releaseLease(conversationId) {
1015
+ return this.transport.request("POST", "/v1/lease/release", {
1016
+ conversation_id: conversationId
1017
+ });
1018
+ }
1019
+ async uploadArtifact(content) {
1020
+ const presignRes = await this.transport.request("POST", "/v1/artifacts/presign_upload", {
1021
+ size: content.length,
1022
+ content_type: "application/octet-stream"
1023
+ });
1024
+ if (!presignRes.ok || !presignRes.data) throw new Error("Failed to presign upload");
1025
+ const { upload_url, artifact_ref } = presignRes.data;
1026
+ await this.transport.fetchWithAuth(upload_url, {
1027
+ method: "PUT",
1028
+ body: content,
1029
+ contentType: "application/octet-stream"
1030
+ });
1031
+ const { createHash } = await import("crypto");
1032
+ const hash = createHash("sha256").update(content).digest("hex");
1033
+ return { artifact_ref, sha256: hash, size: content.length };
1034
+ }
1035
+ async downloadArtifact(artifactRef, expectedSha256, expectedSize) {
1036
+ const presignRes = await this.transport.request("POST", "/v1/artifacts/presign_download", {
1037
+ artifact_ref: artifactRef
1038
+ });
1039
+ if (!presignRes.ok || !presignRes.data) throw new Error("Failed to presign download");
1040
+ const buffer = Buffer.from(await this.transport.fetchWithAuth(presignRes.data.download_url));
1041
+ if (buffer.length !== expectedSize) {
1042
+ throw new Error(`Size mismatch: expected ${expectedSize}, got ${buffer.length}`);
1043
+ }
1044
+ const { createHash } = await import("crypto");
1045
+ const hash = createHash("sha256").update(buffer).digest("hex");
1046
+ if (hash !== expectedSha256) {
1047
+ throw new Error(`SHA256 mismatch: expected ${expectedSha256}, got ${hash}`);
1048
+ }
1049
+ return buffer;
1050
+ }
1051
+ async getSubscription() {
1052
+ return this.transport.request("GET", "/v1/subscription");
1053
+ }
1054
+ async resolveAlias(alias) {
1055
+ return this.transport.request("GET", `/v1/directory/resolve?alias=${encodeURIComponent(alias)}`);
1056
+ }
1057
+ async registerAlias(alias) {
1058
+ return this.transport.request("POST", "/v1/directory/alias", { alias });
1059
+ }
1060
+ async listConversations(opts) {
1061
+ const params = new URLSearchParams();
1062
+ if (opts?.type) params.set("type", opts.type);
1063
+ const qs = params.toString();
1064
+ const res = await this.transport.request("GET", `/v1/conversations/list${qs ? "?" + qs : ""}`);
1065
+ if (res.ok && res.data && this.sessionManager) {
1066
+ for (const conv of res.data.conversations) {
1067
+ const trustState = conv.trusted ? "trusted" : conv.type === "pending_dm" ? "pending" : "stranger";
1068
+ this.sessionManager.upsert({
1069
+ session_key: buildSessionKey({
1070
+ localDid: this.identity.did,
1071
+ remoteDid: conv.target_did,
1072
+ conversationId: conv.conversation_id,
1073
+ conversationType: conv.type
1074
+ }),
1075
+ remote_did: conv.target_did,
1076
+ conversation_id: conv.conversation_id,
1077
+ trust_state: trustState,
1078
+ last_remote_activity_at: conv.last_activity_at ?? void 0,
1079
+ updated_at: conv.last_activity_at ?? conv.created_at
1080
+ });
1081
+ }
1082
+ }
1083
+ return res;
1084
+ }
1085
+ async getTaskStatus(conversationId, taskId) {
1086
+ const params = new URLSearchParams({ conversation_id: conversationId, task_id: taskId });
1087
+ const res = await this.transport.request("GET", `/v1/tasks/status?${params.toString()}`);
1088
+ if (res.ok && res.data) {
1089
+ const session = this.sessionManager?.getByConversationId(conversationId);
1090
+ this.taskThreadManager?.upsert({
1091
+ task_id: taskId,
1092
+ session_key: session?.session_key ?? buildSessionKey({ localDid: this.identity.did, conversationId, remoteDid: session?.remote_did }),
1093
+ conversation_id: conversationId,
1094
+ status: res.data.status,
1095
+ updated_at: res.data.last_update_ts_ms,
1096
+ result_summary: res.data.result_summary,
1097
+ error_code: res.data.error?.code,
1098
+ error_message: res.data.error?.message ?? res.data.reason
1099
+ });
1100
+ }
1101
+ return res;
1102
+ }
1103
+ async listTaskThreads(conversationId) {
1104
+ const params = new URLSearchParams({ conversation_id: conversationId });
1105
+ const res = await this.transport.request("GET", `/v1/tasks/list?${params.toString()}`);
1106
+ if (res.ok && res.data) {
1107
+ const session = this.sessionManager?.getByConversationId(conversationId);
1108
+ for (const task of res.data.tasks) {
1109
+ this.taskThreadManager?.upsert({
1110
+ task_id: task.task_id,
1111
+ session_key: session?.session_key ?? buildSessionKey({ localDid: this.identity.did, conversationId, remoteDid: session?.remote_did }),
1112
+ conversation_id: conversationId,
1113
+ title: task.title,
1114
+ status: task.status,
1115
+ updated_at: task.last_update_ts_ms,
1116
+ result_summary: task.result_summary,
1117
+ error_code: task.error?.code,
1118
+ error_message: task.error?.message ?? task.reason
1119
+ });
1120
+ }
1121
+ }
1122
+ return res;
1123
+ }
1124
+ async getProfile() {
1125
+ return this.transport.request("GET", "/v1/directory/profile");
1126
+ }
1127
+ async updateProfile(profile) {
1128
+ return this.transport.request("POST", "/v1/directory/profile", profile);
1129
+ }
1130
+ async enableDiscovery() {
1131
+ return this.transport.request("POST", "/v1/directory/enable_discovery");
1132
+ }
1133
+ async disableDiscovery() {
1134
+ return this.transport.request("POST", "/v1/directory/disable_discovery");
1135
+ }
1136
+ async browseDirectory(opts) {
1137
+ const params = new URLSearchParams();
1138
+ if (opts?.tag) params.set("tag", opts.tag);
1139
+ if (opts?.query) params.set("q", opts.query);
1140
+ if (opts?.limit != null) params.set("limit", String(opts.limit));
1141
+ if (opts?.offset != null) params.set("offset", String(opts.offset));
1142
+ if (opts?.sort) params.set("sort", opts.sort);
1143
+ const qs = params.toString();
1144
+ return this.transport.request("GET", `/v1/directory/browse${qs ? "?" + qs : ""}`);
1145
+ }
1146
+ async publishPost(opts) {
1147
+ return this.transport.request("POST", "/v1/feed/publish", { text: opts.text, artifact_ref: opts.artifact_ref });
1148
+ }
1149
+ async listFeedPublic(opts) {
1150
+ const params = new URLSearchParams();
1151
+ if (opts?.limit != null) params.set("limit", String(opts.limit));
1152
+ if (opts?.since != null) params.set("since", String(opts.since));
1153
+ const qs = params.toString();
1154
+ return this.transport.request("GET", `/v1/feed/public${qs ? "?" + qs : ""}`, void 0, true);
1155
+ }
1156
+ async listFeedByDid(did, opts) {
1157
+ const params = new URLSearchParams({ did });
1158
+ if (opts?.limit != null) params.set("limit", String(opts.limit));
1159
+ return this.transport.request("GET", `/v1/feed/by_did?${params.toString()}`, void 0, true);
1160
+ }
1161
+ async createChannel(opts) {
1162
+ return this.transport.request("POST", "/v1/channels/create", {
1163
+ name: opts.name,
1164
+ alias: opts.alias,
1165
+ description: opts.description,
1166
+ join_policy: "open",
1167
+ discoverable: opts.discoverable
1168
+ });
1169
+ }
1170
+ async updateChannel(opts) {
1171
+ const alias = opts.alias.replace(/^@ch\//, "");
1172
+ return this.transport.request("PATCH", "/v1/channels/update", {
1173
+ alias,
1174
+ name: opts.name,
1175
+ description: opts.description,
1176
+ discoverable: opts.discoverable
1177
+ });
1178
+ }
1179
+ async deleteChannel(alias) {
1180
+ const a = alias.replace(/^@ch\//, "");
1181
+ return this.transport.request("DELETE", "/v1/channels/delete", { alias: a });
1182
+ }
1183
+ async discoverChannels(opts) {
1184
+ const params = new URLSearchParams();
1185
+ if (opts?.limit != null) params.set("limit", String(opts.limit));
1186
+ if (opts?.query) params.set("q", opts.query);
1187
+ const qs = params.toString();
1188
+ return this.transport.request("GET", `/v1/channels/discover${qs ? "?" + qs : ""}`, void 0, true);
1189
+ }
1190
+ async joinChannel(alias) {
1191
+ return this.transport.request("POST", "/v1/channels/join", { alias });
1192
+ }
1193
+ getDid() {
1194
+ return this.identity.did;
1195
+ }
1196
+ // === Billing: device linking ===
1197
+ async createBillingLinkCode() {
1198
+ return this.transport.request("POST", "/v1/billing/link-code");
1199
+ }
1200
+ async redeemBillingLink(code) {
1201
+ return this.transport.request("POST", "/v1/billing/link", { code });
1202
+ }
1203
+ async unlinkBillingDevice(did) {
1204
+ return this.transport.request("POST", "/v1/billing/unlink", { did });
1205
+ }
1206
+ async getLinkedDevices() {
1207
+ return this.transport.request("GET", "/v1/billing/linked-devices");
1208
+ }
1209
+ // P0: High-level send-task-and-wait
1210
+ async sendTaskAndWait(targetDid, task, opts) {
1211
+ const { v7: uuidv7 } = await import("uuid");
1212
+ const timeout = opts?.timeoutMs ?? 12e4;
1213
+ const pollInterval = opts?.pollIntervalMs ?? 2e3;
1214
+ const taskId = `t_${uuidv7()}`;
1215
+ const startTime = Date.now();
1216
+ const openRes = await this.openConversation(targetDid);
1217
+ if (!openRes.ok || !openRes.data) {
1218
+ return { status: "error", task_id: taskId, error: { code: "E_OPEN_FAILED", message: "Failed to open conversation" }, elapsed_ms: Date.now() - startTime };
1219
+ }
1220
+ let conversationId = openRes.data.conversation_id;
1221
+ if (!openRes.data.trusted) {
1222
+ await this.sendContactRequest(conversationId, task.title);
1223
+ const approvalDeadline = startTime + timeout;
1224
+ while (Date.now() < approvalDeadline) {
1225
+ await sleep2(pollInterval);
1226
+ const reopen = await this.openConversation(targetDid);
1227
+ if (reopen.ok && reopen.data?.trusted) {
1228
+ conversationId = reopen.data.conversation_id;
1229
+ break;
1230
+ }
1231
+ }
1232
+ if (Date.now() >= approvalDeadline) {
1233
+ return { status: "error", task_id: taskId, error: { code: "E_NOT_APPROVED", message: "Contact request not approved within timeout" }, elapsed_ms: Date.now() - startTime };
1234
+ }
1235
+ }
1236
+ const sendRes = await this.sendTask(conversationId, { task_id: taskId, ...task });
1237
+ if (!sendRes.ok) {
1238
+ return { status: "error", task_id: taskId, error: { code: sendRes.error?.code ?? "E_SEND_FAILED", message: sendRes.error?.message ?? "Send failed" }, elapsed_ms: Date.now() - startTime };
1239
+ }
1240
+ const session = this.sessionManager?.getByConversationId(conversationId);
1241
+ this.taskThreadManager?.upsert({
1242
+ task_id: taskId,
1243
+ session_key: session?.session_key ?? buildSessionKey({ localDid: this.identity.did, conversationId, remoteDid: targetDid }),
1244
+ conversation_id: conversationId,
1245
+ title: task.title,
1246
+ status: "queued",
1247
+ started_at: Date.now(),
1248
+ updated_at: Date.now()
1249
+ });
1250
+ const sinceSeq = sendRes.data?.seq ?? 0;
1251
+ const deadline = startTime + timeout;
1252
+ while (Date.now() < deadline) {
1253
+ await sleep2(pollInterval);
1254
+ const statusRes = await this.getTaskStatus(conversationId, taskId);
1255
+ if (statusRes.ok && statusRes.data) {
1256
+ if (statusRes.data.status === "failed" || statusRes.data.status === "cancelled") {
1257
+ return {
1258
+ status: "error",
1259
+ task_id: taskId,
1260
+ error: {
1261
+ code: statusRes.data.error?.code ?? (statusRes.data.status === "cancelled" ? "E_CANCELLED" : "E_TASK_FAILED"),
1262
+ message: statusRes.data.error?.message ?? statusRes.data.reason ?? `Task ${statusRes.data.status}`
1263
+ },
1264
+ elapsed_ms: Date.now() - startTime
1265
+ };
1266
+ }
1267
+ }
1268
+ const fetchRes = await this.fetchInbox(conversationId, { sinceSeq });
1269
+ if (!fetchRes.ok || !fetchRes.data) continue;
1270
+ for (const msg of fetchRes.data.messages) {
1271
+ if (msg.schema === SCHEMA_RESULT && msg.payload?.task_id === taskId) {
1272
+ return {
1273
+ status: msg.payload.status === "ok" ? "ok" : "error",
1274
+ task_id: taskId,
1275
+ result: msg.payload.output,
1276
+ error: msg.payload.error,
1277
+ elapsed_ms: Date.now() - startTime
1278
+ };
1279
+ }
1280
+ }
1281
+ }
1282
+ return { status: "error", task_id: taskId, error: { code: "E_TIMEOUT", message: `No result within ${timeout}ms` }, elapsed_ms: timeout };
1283
+ }
1284
+ };
1285
+ function normalizeTaskThreadStatus(state) {
1286
+ if (state === "completed") return "processed";
1287
+ if (state === "cancel_requested") return "running";
1288
+ if (state === "cancelled") return "cancelled";
1289
+ if (state === "failed") return "failed";
1290
+ if (state === "running") return "running";
1291
+ return "queued";
1292
+ }
1293
+ function sleep2(ms) {
1294
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
1295
+ }
1296
+
1297
+ // src/identity.ts
1298
+ import * as fs from "fs";
1299
+ import * as path2 from "path";
1300
+ import { generateIdentity as genId } from "@pingagent/protocol";
1301
+
1302
+ // src/paths.ts
1303
+ import * as path from "path";
1304
+ import * as os from "os";
1305
+ var DEFAULT_ROOT_DIR = path.join(os.homedir(), ".pingagent");
1306
+ function getRootDir() {
1307
+ return process.env.PINGAGENT_ROOT_DIR || DEFAULT_ROOT_DIR;
1308
+ }
1309
+ function getProfile() {
1310
+ const p = process.env.PINGAGENT_PROFILE;
1311
+ if (!p) return void 0;
1312
+ return p.trim() || void 0;
1313
+ }
1314
+ function getIdentityPath(explicitPath) {
1315
+ const envPath = process.env.PINGAGENT_IDENTITY_PATH?.trim();
1316
+ if (explicitPath) return explicitPath;
1317
+ if (envPath) return path.resolve(envPath.replace(/^~(?=\/|$)/, os.homedir()));
1318
+ const root = getRootDir();
1319
+ const profile = getProfile();
1320
+ if (!profile) {
1321
+ return path.join(root, "identity.json");
1322
+ }
1323
+ return path.join(root, "profiles", profile, "identity.json");
1324
+ }
1325
+ function getStorePath(explicitPath) {
1326
+ const envPath = process.env.PINGAGENT_STORE_PATH?.trim();
1327
+ if (explicitPath) return explicitPath;
1328
+ if (envPath) return path.resolve(envPath.replace(/^~(?=\/|$)/, os.homedir()));
1329
+ const root = getRootDir();
1330
+ const profile = getProfile();
1331
+ if (!profile) {
1332
+ return path.join(root, "store.db");
1333
+ }
1334
+ return path.join(root, "profiles", profile, "store.db");
1335
+ }
1336
+
1337
+ // src/identity.ts
1338
+ function toBase64(bytes) {
1339
+ let binary = "";
1340
+ for (const b of bytes) binary += String.fromCharCode(b);
1341
+ return btoa(binary);
1342
+ }
1343
+ function fromBase64(b64) {
1344
+ const binary = atob(b64);
1345
+ const bytes = new Uint8Array(binary.length);
1346
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
1347
+ return bytes;
1348
+ }
1349
+ function generateIdentity() {
1350
+ return genId();
1351
+ }
1352
+ function identityExists(identityPath) {
1353
+ return fs.existsSync(getIdentityPath(identityPath));
1354
+ }
1355
+ function loadIdentity(identityPath) {
1356
+ const p = getIdentityPath(identityPath);
1357
+ const data = JSON.parse(fs.readFileSync(p, "utf-8"));
1358
+ return {
1359
+ publicKey: fromBase64(data.public_key),
1360
+ privateKey: fromBase64(data.private_key),
1361
+ did: data.did,
1362
+ deviceId: data.device_id,
1363
+ serverUrl: data.server_url,
1364
+ accessToken: data.access_token,
1365
+ tokenExpiresAt: data.token_expires_at,
1366
+ mode: data.mode
1367
+ };
1368
+ }
1369
+ function saveIdentity(identity, opts, identityPath) {
1370
+ const p = getIdentityPath(identityPath);
1371
+ const dir = path2.dirname(p);
1372
+ if (!fs.existsSync(dir)) {
1373
+ fs.mkdirSync(dir, { recursive: true, mode: 448 });
1374
+ }
1375
+ const stored = {
1376
+ public_key: toBase64(identity.publicKey),
1377
+ private_key: toBase64(identity.privateKey),
1378
+ did: identity.did,
1379
+ device_id: identity.deviceId,
1380
+ server_url: opts?.serverUrl,
1381
+ access_token: opts?.accessToken,
1382
+ token_expires_at: opts?.tokenExpiresAt,
1383
+ mode: opts?.mode,
1384
+ alias: opts?.alias
1385
+ };
1386
+ fs.writeFileSync(p, JSON.stringify(stored, null, 2), { mode: 384 });
1387
+ }
1388
+ function updateStoredToken(accessToken, expiresAt, identityPath) {
1389
+ const p = getIdentityPath(identityPath);
1390
+ const data = JSON.parse(fs.readFileSync(p, "utf-8"));
1391
+ data.access_token = accessToken;
1392
+ data.token_expires_at = expiresAt;
1393
+ fs.writeFileSync(p, JSON.stringify(data, null, 2), { mode: 384 });
1394
+ }
1395
+
1396
+ // src/auth.ts
1397
+ var REFRESH_GRACE_MS = 5 * 60 * 1e3;
1398
+ async function ensureTokenValid(identityPath, serverUrl) {
1399
+ if (!identityExists(identityPath)) return false;
1400
+ const id = loadIdentity(identityPath);
1401
+ const token = id.accessToken;
1402
+ const expiresAt = id.tokenExpiresAt;
1403
+ if (!token || expiresAt == null) return false;
1404
+ const now = Date.now();
1405
+ if (expiresAt > now + REFRESH_GRACE_MS) return false;
1406
+ const baseUrl = (serverUrl ?? id.serverUrl ?? "https://pingagent.chat").replace(/\/$/, "");
1407
+ try {
1408
+ const res = await fetch(`${baseUrl}/v1/auth/refresh`, {
1409
+ method: "POST",
1410
+ headers: { "Content-Type": "application/json" },
1411
+ body: JSON.stringify({ access_token: token })
1412
+ });
1413
+ const text = await res.text();
1414
+ let data;
1415
+ try {
1416
+ data = text ? JSON.parse(text) : {};
1417
+ } catch {
1418
+ return false;
1419
+ }
1420
+ if (!res.ok || !data.ok || !data.data?.access_token || data.data.expires_ms == null) return false;
1421
+ const newExpiresAt = now + data.data.expires_ms;
1422
+ updateStoredToken(data.data.access_token, newExpiresAt, identityPath);
1423
+ return true;
1424
+ } catch {
1425
+ return false;
1426
+ }
1427
+ }
1428
+
1429
+ // src/store.ts
1430
+ import Database from "better-sqlite3";
1431
+ import * as fs2 from "fs";
1432
+ import * as path3 from "path";
1433
+ var SCHEMA_SQL = `
1434
+ CREATE TABLE IF NOT EXISTS contacts (
1435
+ did TEXT PRIMARY KEY,
1436
+ alias TEXT,
1437
+ display_name TEXT,
1438
+ notes TEXT,
1439
+ conversation_id TEXT,
1440
+ trusted INTEGER NOT NULL DEFAULT 0,
1441
+ added_at INTEGER NOT NULL,
1442
+ last_message_at INTEGER,
1443
+ tags TEXT
1444
+ );
1445
+ CREATE INDEX IF NOT EXISTS idx_contacts_alias ON contacts(alias);
1446
+
1447
+ CREATE TABLE IF NOT EXISTS messages (
1448
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
1449
+ conversation_id TEXT NOT NULL,
1450
+ message_id TEXT NOT NULL UNIQUE,
1451
+ seq INTEGER,
1452
+ sender_did TEXT NOT NULL,
1453
+ schema TEXT NOT NULL,
1454
+ payload TEXT NOT NULL,
1455
+ ts_ms INTEGER NOT NULL,
1456
+ direction TEXT NOT NULL CHECK(direction IN ('sent', 'received'))
1457
+ );
1458
+ CREATE INDEX IF NOT EXISTS idx_messages_conv_seq ON messages(conversation_id, seq);
1459
+ CREATE INDEX IF NOT EXISTS idx_messages_ts ON messages(ts_ms);
1460
+
1461
+ CREATE TABLE IF NOT EXISTS sync_state (
1462
+ conversation_id TEXT PRIMARY KEY,
1463
+ last_synced_seq INTEGER NOT NULL DEFAULT 0,
1464
+ last_synced_at INTEGER
1465
+ );
1466
+
1467
+ CREATE TABLE IF NOT EXISTS session_state (
1468
+ session_key TEXT PRIMARY KEY,
1469
+ remote_did TEXT,
1470
+ conversation_id TEXT,
1471
+ trust_state TEXT NOT NULL DEFAULT 'stranger',
1472
+ last_message_preview TEXT,
1473
+ last_remote_activity_at INTEGER,
1474
+ last_read_seq INTEGER NOT NULL DEFAULT 0,
1475
+ unread_count INTEGER NOT NULL DEFAULT 0,
1476
+ active INTEGER NOT NULL DEFAULT 0,
1477
+ updated_at INTEGER NOT NULL
1478
+ );
1479
+ CREATE INDEX IF NOT EXISTS idx_session_state_updated ON session_state(updated_at DESC);
1480
+ CREATE INDEX IF NOT EXISTS idx_session_state_conversation ON session_state(conversation_id);
1481
+ CREATE INDEX IF NOT EXISTS idx_session_state_remote_did ON session_state(remote_did);
1482
+
1483
+ CREATE TABLE IF NOT EXISTS task_threads (
1484
+ task_id TEXT PRIMARY KEY,
1485
+ session_key TEXT NOT NULL,
1486
+ conversation_id TEXT NOT NULL,
1487
+ title TEXT,
1488
+ status TEXT NOT NULL,
1489
+ started_at INTEGER,
1490
+ updated_at INTEGER NOT NULL,
1491
+ result_summary TEXT,
1492
+ error_code TEXT,
1493
+ error_message TEXT
1494
+ );
1495
+ CREATE INDEX IF NOT EXISTS idx_task_threads_session ON task_threads(session_key, updated_at DESC);
1496
+ CREATE INDEX IF NOT EXISTS idx_task_threads_conversation ON task_threads(conversation_id, updated_at DESC);
1497
+
1498
+ CREATE TABLE IF NOT EXISTS trust_policy_audit (
1499
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
1500
+ ts_ms INTEGER NOT NULL,
1501
+ event_type TEXT NOT NULL,
1502
+ policy_scope TEXT,
1503
+ remote_did TEXT,
1504
+ sender_alias TEXT,
1505
+ sender_verification_status TEXT,
1506
+ session_key TEXT,
1507
+ conversation_id TEXT,
1508
+ action TEXT,
1509
+ outcome TEXT,
1510
+ explanation TEXT,
1511
+ matched_rule TEXT,
1512
+ detail_json TEXT
1513
+ );
1514
+ CREATE INDEX IF NOT EXISTS idx_trust_policy_audit_ts ON trust_policy_audit(ts_ms DESC, id DESC);
1515
+ CREATE INDEX IF NOT EXISTS idx_trust_policy_audit_session ON trust_policy_audit(session_key, ts_ms DESC);
1516
+ CREATE INDEX IF NOT EXISTS idx_trust_policy_audit_remote ON trust_policy_audit(remote_did, ts_ms DESC);
1517
+ `;
1518
+ var LocalStore = class {
1519
+ db;
1520
+ constructor(dbPath) {
1521
+ const p = getStorePath(dbPath);
1522
+ const dir = path3.dirname(p);
1523
+ if (!fs2.existsSync(dir)) {
1524
+ fs2.mkdirSync(dir, { recursive: true, mode: 448 });
1525
+ }
1526
+ this.db = new Database(p);
1527
+ this.db.pragma("journal_mode = WAL");
1528
+ this.db.exec(SCHEMA_SQL);
1529
+ this.applyMigrations();
1530
+ }
1531
+ getDb() {
1532
+ return this.db;
1533
+ }
1534
+ close() {
1535
+ this.db.close();
1536
+ }
1537
+ applyMigrations() {
1538
+ const alterStatements = [
1539
+ `ALTER TABLE session_state ADD COLUMN remote_did TEXT`,
1540
+ `ALTER TABLE session_state ADD COLUMN conversation_id TEXT`,
1541
+ `ALTER TABLE session_state ADD COLUMN trust_state TEXT NOT NULL DEFAULT 'stranger'`,
1542
+ `ALTER TABLE session_state ADD COLUMN last_message_preview TEXT`,
1543
+ `ALTER TABLE session_state ADD COLUMN last_remote_activity_at INTEGER`,
1544
+ `ALTER TABLE session_state ADD COLUMN last_read_seq INTEGER NOT NULL DEFAULT 0`,
1545
+ `ALTER TABLE session_state ADD COLUMN unread_count INTEGER NOT NULL DEFAULT 0`,
1546
+ `ALTER TABLE session_state ADD COLUMN active INTEGER NOT NULL DEFAULT 0`,
1547
+ `ALTER TABLE session_state ADD COLUMN updated_at INTEGER NOT NULL DEFAULT 0`,
1548
+ `ALTER TABLE task_threads ADD COLUMN title TEXT`,
1549
+ `ALTER TABLE task_threads ADD COLUMN result_summary TEXT`,
1550
+ `ALTER TABLE task_threads ADD COLUMN error_code TEXT`,
1551
+ `ALTER TABLE task_threads ADD COLUMN error_message TEXT`
1552
+ ];
1553
+ for (const sql of alterStatements) {
1554
+ try {
1555
+ this.db.exec(sql);
1556
+ } catch {
1557
+ }
1558
+ }
1559
+ }
1560
+ };
1561
+
1562
+ // src/trust-policy.ts
1563
+ var CONTACT_ACTIONS = /* @__PURE__ */ new Set(["approve", "manual", "reject"]);
1564
+ var TASK_ACTIONS = /* @__PURE__ */ new Set(["bridge", "execute", "deny"]);
1565
+ function defaultTrustPolicyDoc() {
1566
+ return {
1567
+ version: 1,
1568
+ contact_policy: {
1569
+ enabled: true,
1570
+ default_action: "manual",
1571
+ rules: []
1572
+ },
1573
+ task_policy: {
1574
+ enabled: true,
1575
+ default_action: "bridge",
1576
+ rules: []
1577
+ }
1578
+ };
1579
+ }
1580
+ function normalizeTrustPolicyDoc(raw) {
1581
+ const base = defaultTrustPolicyDoc();
1582
+ const contactRules = Array.isArray(raw?.contact_policy?.rules) ? raw.contact_policy.rules.filter((rule) => typeof rule?.match === "string" && CONTACT_ACTIONS.has(rule?.action)) : [];
1583
+ const taskRules = Array.isArray(raw?.task_policy?.rules) ? raw.task_policy.rules.filter((rule) => typeof rule?.match === "string" && TASK_ACTIONS.has(rule?.action)) : [];
1584
+ return {
1585
+ version: 1,
1586
+ contact_policy: {
1587
+ enabled: raw?.contact_policy?.enabled !== false,
1588
+ default_action: CONTACT_ACTIONS.has(raw?.contact_policy?.default_action) ? raw.contact_policy.default_action : base.contact_policy.default_action,
1589
+ rules: contactRules
1590
+ },
1591
+ task_policy: {
1592
+ enabled: raw?.task_policy?.enabled !== false,
1593
+ default_action: TASK_ACTIONS.has(raw?.task_policy?.default_action) ? raw.task_policy.default_action : base.task_policy.default_action,
1594
+ rules: taskRules
1595
+ }
1596
+ };
1597
+ }
1598
+ function matchesTrustPolicyRule(match, context) {
1599
+ if (match === "*") return true;
1600
+ if (match.startsWith("did:agent:")) {
1601
+ return context.sender_did === match;
1602
+ }
1603
+ if (match.startsWith("verification_status:")) {
1604
+ return context.sender_verification_status === match.split(":")[1];
1605
+ }
1606
+ if (match.startsWith("alias:")) {
1607
+ const pattern = match.slice(6);
1608
+ const senderAlias = context.sender_alias ?? "";
1609
+ if (pattern.endsWith("*")) return senderAlias.startsWith(pattern.slice(0, -1));
1610
+ return senderAlias === pattern;
1611
+ }
1612
+ return false;
1613
+ }
1614
+ function decideContactPolicy(policyDoc, context, opts) {
1615
+ if (policyDoc.contact_policy.enabled) {
1616
+ for (const rule of policyDoc.contact_policy.rules) {
1617
+ if (matchesTrustPolicyRule(rule.match, context)) {
1618
+ return {
1619
+ action: rule.action,
1620
+ source: "rule",
1621
+ matched_rule: rule,
1622
+ explanation: `Matched contact_policy rule ${rule.match} -> ${rule.action}`
1623
+ };
1624
+ }
1625
+ }
1626
+ return {
1627
+ action: policyDoc.contact_policy.default_action,
1628
+ source: "default",
1629
+ explanation: `No contact_policy rule matched; using default_action=${policyDoc.contact_policy.default_action}`
1630
+ };
1631
+ }
1632
+ if (opts?.legacyAutoApproveEnabled) {
1633
+ for (const rule of opts.legacyAutoApproveRules ?? []) {
1634
+ if (rule.action === "approve" && matchesTrustPolicyRule(rule.match, context)) {
1635
+ return {
1636
+ action: "approve",
1637
+ source: "legacy_auto_approve",
1638
+ matched_rule: { match: rule.match, action: "approve" },
1639
+ explanation: `Matched legacy auto_approve rule ${rule.match} -> approve`
1640
+ };
1641
+ }
1642
+ }
1643
+ }
1644
+ return {
1645
+ action: "manual",
1646
+ source: "runtime_default",
1647
+ explanation: "contact_policy disabled and no legacy auto_approve match; defaulting to manual"
1648
+ };
1649
+ }
1650
+ function decideTaskPolicy(policyDoc, context, opts) {
1651
+ if (policyDoc.task_policy.enabled) {
1652
+ for (const rule of policyDoc.task_policy.rules) {
1653
+ if (matchesTrustPolicyRule(rule.match, context)) {
1654
+ return {
1655
+ action: rule.action,
1656
+ source: "rule",
1657
+ matched_rule: rule,
1658
+ explanation: `Matched task_policy rule ${rule.match} -> ${rule.action}`
1659
+ };
1660
+ }
1661
+ }
1662
+ return {
1663
+ action: policyDoc.task_policy.default_action,
1664
+ source: "default",
1665
+ explanation: `No task_policy rule matched; using default_action=${policyDoc.task_policy.default_action}`
1666
+ };
1667
+ }
1668
+ const runtimeDefault = opts?.runtimeMode === "executor" ? "execute" : "bridge";
1669
+ return {
1670
+ action: runtimeDefault,
1671
+ source: "runtime_default",
1672
+ explanation: `task_policy disabled; defaulting to runtime_mode=${opts?.runtimeMode ?? "bridge"} -> ${runtimeDefault}`
1673
+ };
1674
+ }
1675
+
1676
+ // src/trust-policy-audit.ts
1677
+ function rowToEvent(row) {
1678
+ return {
1679
+ id: row.id,
1680
+ ts_ms: row.ts_ms,
1681
+ event_type: row.event_type,
1682
+ policy_scope: row.policy_scope ?? void 0,
1683
+ remote_did: row.remote_did ?? void 0,
1684
+ sender_alias: row.sender_alias ?? void 0,
1685
+ sender_verification_status: row.sender_verification_status ?? void 0,
1686
+ session_key: row.session_key ?? void 0,
1687
+ conversation_id: row.conversation_id ?? void 0,
1688
+ action: row.action ?? void 0,
1689
+ outcome: row.outcome ?? void 0,
1690
+ explanation: row.explanation ?? void 0,
1691
+ matched_rule: row.matched_rule ?? void 0,
1692
+ detail: row.detail_json ? JSON.parse(row.detail_json) : void 0
1693
+ };
1694
+ }
1695
+ function buildSummaryFromEvents(events) {
1696
+ const byType = {};
1697
+ const byPolicyScope = {};
1698
+ let latestTsMs = 0;
1699
+ for (const event of events) {
1700
+ byType[event.event_type] = (byType[event.event_type] ?? 0) + 1;
1701
+ if (event.policy_scope) byPolicyScope[event.policy_scope] = (byPolicyScope[event.policy_scope] ?? 0) + 1;
1702
+ latestTsMs = Math.max(latestTsMs, event.ts_ms);
1703
+ }
1704
+ return {
1705
+ total_events: events.length,
1706
+ latest_ts_ms: latestTsMs || void 0,
1707
+ by_type: byType,
1708
+ by_policy_scope: byPolicyScope
1709
+ };
1710
+ }
1711
+ var TrustPolicyAuditManager = class {
1712
+ constructor(store) {
1713
+ this.store = store;
1714
+ }
1715
+ record(event) {
1716
+ const tsMs = event.ts_ms ?? Date.now();
1717
+ const result = this.store.getDb().prepare(`
1718
+ INSERT INTO trust_policy_audit (
1719
+ ts_ms, event_type, policy_scope, remote_did, sender_alias, sender_verification_status,
1720
+ session_key, conversation_id, action, outcome, explanation, matched_rule, detail_json
1721
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1722
+ `).run(
1723
+ tsMs,
1724
+ event.event_type,
1725
+ event.policy_scope ?? null,
1726
+ event.remote_did ?? null,
1727
+ event.sender_alias ?? null,
1728
+ event.sender_verification_status ?? null,
1729
+ event.session_key ?? null,
1730
+ event.conversation_id ?? null,
1731
+ event.action ?? null,
1732
+ event.outcome ?? null,
1733
+ event.explanation ?? null,
1734
+ event.matched_rule ?? null,
1735
+ event.detail ? JSON.stringify(event.detail) : null
1736
+ );
1737
+ return {
1738
+ id: Number(result.lastInsertRowid),
1739
+ ts_ms: tsMs,
1740
+ event_type: event.event_type,
1741
+ policy_scope: event.policy_scope,
1742
+ remote_did: event.remote_did,
1743
+ sender_alias: event.sender_alias,
1744
+ sender_verification_status: event.sender_verification_status,
1745
+ session_key: event.session_key,
1746
+ conversation_id: event.conversation_id,
1747
+ action: event.action,
1748
+ outcome: event.outcome,
1749
+ explanation: event.explanation,
1750
+ matched_rule: event.matched_rule,
1751
+ detail: event.detail
1752
+ };
1753
+ }
1754
+ listRecent(limit = 50) {
1755
+ const rows = this.store.getDb().prepare("SELECT * FROM trust_policy_audit ORDER BY ts_ms DESC, id DESC LIMIT ?").all(limit);
1756
+ return rows.map(rowToEvent);
1757
+ }
1758
+ listBySession(sessionKey, limit = 50) {
1759
+ const rows = this.store.getDb().prepare("SELECT * FROM trust_policy_audit WHERE session_key = ? ORDER BY ts_ms DESC, id DESC LIMIT ?").all(sessionKey, limit);
1760
+ return rows.map(rowToEvent);
1761
+ }
1762
+ listByRemoteDid(remoteDid, limit = 50) {
1763
+ const rows = this.store.getDb().prepare("SELECT * FROM trust_policy_audit WHERE remote_did = ? ORDER BY ts_ms DESC, id DESC LIMIT ?").all(remoteDid, limit);
1764
+ return rows.map(rowToEvent);
1765
+ }
1766
+ summarize(limit = 200) {
1767
+ return buildSummaryFromEvents(this.listRecent(limit));
1768
+ }
1769
+ };
1770
+ function aggregateLearning(sessions, tasks, events) {
1771
+ const summaries = /* @__PURE__ */ new Map();
1772
+ function ensure(remoteDid) {
1773
+ if (!remoteDid) return null;
1774
+ const existing = summaries.get(remoteDid);
1775
+ if (existing) return existing;
1776
+ const created = {
1777
+ remote_did: remoteDid,
1778
+ trusted_sessions: 0,
1779
+ pending_sessions: 0,
1780
+ blocked_sessions: 0,
1781
+ revoked_sessions: 0,
1782
+ processed_tasks: 0,
1783
+ failed_tasks: 0,
1784
+ cancelled_tasks: 0,
1785
+ contact_approvals: 0,
1786
+ contact_manual_reviews: 0,
1787
+ contact_rejections: 0,
1788
+ task_bridged: 0,
1789
+ task_executed: 0,
1790
+ task_denied: 0
1791
+ };
1792
+ summaries.set(remoteDid, created);
1793
+ return created;
1794
+ }
1795
+ const remoteBySession = /* @__PURE__ */ new Map();
1796
+ for (const session of sessions) {
1797
+ const summary = ensure(session.remote_did);
1798
+ if (!summary) continue;
1799
+ remoteBySession.set(session.session_key, session.remote_did);
1800
+ summary.last_seen_at = Math.max(summary.last_seen_at ?? 0, session.last_remote_activity_at ?? 0, session.updated_at ?? 0) || summary.last_seen_at;
1801
+ if (session.trust_state === "trusted") summary.trusted_sessions += 1;
1802
+ if (session.trust_state === "pending") summary.pending_sessions += 1;
1803
+ if (session.trust_state === "blocked") summary.blocked_sessions += 1;
1804
+ if (session.trust_state === "revoked") summary.revoked_sessions += 1;
1805
+ }
1806
+ for (const task of tasks) {
1807
+ const remoteDid = remoteBySession.get(task.session_key);
1808
+ const summary = ensure(remoteDid);
1809
+ if (!summary) continue;
1810
+ summary.last_seen_at = Math.max(summary.last_seen_at ?? 0, task.updated_at ?? 0) || summary.last_seen_at;
1811
+ if (task.status === "processed") summary.processed_tasks += 1;
1812
+ if (task.status === "failed") summary.failed_tasks += 1;
1813
+ if (task.status === "cancelled") summary.cancelled_tasks += 1;
1814
+ }
1815
+ for (const event of events) {
1816
+ const summary = ensure(event.remote_did ?? remoteBySession.get(event.session_key ?? ""));
1817
+ if (!summary) continue;
1818
+ summary.last_seen_at = Math.max(summary.last_seen_at ?? 0, event.ts_ms ?? 0) || summary.last_seen_at;
1819
+ if (event.event_type === "contact_auto_approved") summary.contact_approvals += 1;
1820
+ if (event.event_type === "contact_manual_review") summary.contact_manual_reviews += 1;
1821
+ if (event.event_type === "contact_rejected" || event.event_type === "session_blocked") summary.contact_rejections += 1;
1822
+ if (event.event_type === "session_revoked") summary.revoked_sessions += 1;
1823
+ if (event.event_type === "task_bridged") summary.task_bridged += 1;
1824
+ if (event.event_type === "task_executed") summary.task_executed += 1;
1825
+ if (event.event_type === "task_denied") summary.task_denied += 1;
1826
+ if (event.event_type === "task_processed") summary.processed_tasks += 1;
1827
+ if (event.event_type === "task_failed") summary.failed_tasks += 1;
1828
+ if (event.event_type === "task_cancelled") summary.cancelled_tasks += 1;
1829
+ }
1830
+ return [...summaries.values()].sort((a, b) => (b.last_seen_at ?? 0) - (a.last_seen_at ?? 0));
1831
+ }
1832
+ function recommendationId(policy, remoteDid, action) {
1833
+ return `${policy}:${remoteDid}:${action}`;
1834
+ }
1835
+ function describePositiveSignals(summary) {
1836
+ const parts = [];
1837
+ if (summary.trusted_sessions > 0) parts.push(`trusted_sessions=${summary.trusted_sessions}`);
1838
+ if (summary.contact_approvals > 0) parts.push(`contact_approvals=${summary.contact_approvals}`);
1839
+ if (summary.processed_tasks > 0) parts.push(`processed_tasks=${summary.processed_tasks}`);
1840
+ return parts.join(", ");
1841
+ }
1842
+ function describeRiskSignals(summary) {
1843
+ const parts = [];
1844
+ if (summary.blocked_sessions > 0) parts.push(`blocked_sessions=${summary.blocked_sessions}`);
1845
+ if (summary.revoked_sessions > 0) parts.push(`revoked_sessions=${summary.revoked_sessions}`);
1846
+ if (summary.contact_rejections > 0) parts.push(`contact_rejections=${summary.contact_rejections}`);
1847
+ if (summary.task_denied > 0) parts.push(`task_denied=${summary.task_denied}`);
1848
+ if (summary.failed_tasks > 0) parts.push(`failed_tasks=${summary.failed_tasks}`);
1849
+ return parts.join(", ");
1850
+ }
1851
+ function buildTrustPolicyRecommendations(opts) {
1852
+ const policyDoc = normalizeTrustPolicyDoc(opts.policyDoc);
1853
+ const summaries = aggregateLearning(opts.sessions, opts.tasks, opts.auditEvents);
1854
+ const recommendations = [];
1855
+ for (const summary of summaries) {
1856
+ const contactDecision = decideContactPolicy(policyDoc, { sender_did: summary.remote_did });
1857
+ const taskDecision = decideTaskPolicy(policyDoc, { sender_did: summary.remote_did }, { runtimeMode: opts.runtimeMode });
1858
+ const riskSignals = summary.blocked_sessions + summary.revoked_sessions + summary.contact_rejections + summary.task_denied;
1859
+ const positiveSignals = summary.trusted_sessions + summary.contact_approvals + summary.processed_tasks;
1860
+ if (riskSignals > 0) {
1861
+ if (contactDecision.action !== "reject") {
1862
+ recommendations.push({
1863
+ id: recommendationId("contact", summary.remote_did, "reject"),
1864
+ policy: "contact",
1865
+ remote_did: summary.remote_did,
1866
+ match: summary.remote_did,
1867
+ action: "reject",
1868
+ current_action: contactDecision.action,
1869
+ confidence: riskSignals >= 2 ? "high" : "medium",
1870
+ reason: `Observed repeated negative signals: ${describeRiskSignals(summary)}`,
1871
+ signals: {
1872
+ trusted_sessions: summary.trusted_sessions,
1873
+ blocked_sessions: summary.blocked_sessions,
1874
+ revoked_sessions: summary.revoked_sessions,
1875
+ processed_tasks: summary.processed_tasks,
1876
+ failed_tasks: summary.failed_tasks,
1877
+ cancelled_tasks: summary.cancelled_tasks,
1878
+ contact_approvals: summary.contact_approvals,
1879
+ contact_rejections: summary.contact_rejections,
1880
+ task_denied: summary.task_denied,
1881
+ last_seen_at: summary.last_seen_at
1882
+ }
1883
+ });
1884
+ }
1885
+ if (taskDecision.action !== "deny") {
1886
+ recommendations.push({
1887
+ id: recommendationId("task", summary.remote_did, "deny"),
1888
+ policy: "task",
1889
+ remote_did: summary.remote_did,
1890
+ match: summary.remote_did,
1891
+ action: "deny",
1892
+ current_action: taskDecision.action,
1893
+ confidence: summary.task_denied > 0 || summary.blocked_sessions > 0 || summary.contact_rejections > 0 ? "high" : "medium",
1894
+ reason: `Observed repeated negative task/session signals: ${describeRiskSignals(summary)}`,
1895
+ signals: {
1896
+ trusted_sessions: summary.trusted_sessions,
1897
+ blocked_sessions: summary.blocked_sessions,
1898
+ revoked_sessions: summary.revoked_sessions,
1899
+ processed_tasks: summary.processed_tasks,
1900
+ failed_tasks: summary.failed_tasks,
1901
+ cancelled_tasks: summary.cancelled_tasks,
1902
+ contact_approvals: summary.contact_approvals,
1903
+ contact_rejections: summary.contact_rejections,
1904
+ task_denied: summary.task_denied,
1905
+ last_seen_at: summary.last_seen_at
1906
+ }
1907
+ });
1908
+ }
1909
+ continue;
1910
+ }
1911
+ if (positiveSignals > 0 && contactDecision.action !== "approve" && (summary.trusted_sessions > 0 || summary.contact_approvals > 0 || summary.processed_tasks >= 2)) {
1912
+ recommendations.push({
1913
+ id: recommendationId("contact", summary.remote_did, "approve"),
1914
+ policy: "contact",
1915
+ remote_did: summary.remote_did,
1916
+ match: summary.remote_did,
1917
+ action: "approve",
1918
+ current_action: contactDecision.action,
1919
+ confidence: summary.processed_tasks >= 2 || summary.contact_approvals > 0 ? "high" : "medium",
1920
+ reason: `Observed stable positive collaboration: ${describePositiveSignals(summary)}`,
1921
+ signals: {
1922
+ trusted_sessions: summary.trusted_sessions,
1923
+ blocked_sessions: summary.blocked_sessions,
1924
+ revoked_sessions: summary.revoked_sessions,
1925
+ processed_tasks: summary.processed_tasks,
1926
+ failed_tasks: summary.failed_tasks,
1927
+ cancelled_tasks: summary.cancelled_tasks,
1928
+ contact_approvals: summary.contact_approvals,
1929
+ contact_rejections: summary.contact_rejections,
1930
+ task_denied: summary.task_denied,
1931
+ last_seen_at: summary.last_seen_at
1932
+ }
1933
+ });
1934
+ }
1935
+ const desiredTaskAction = opts.runtimeMode === "executor" ? "execute" : "bridge";
1936
+ if (summary.processed_tasks >= 2 && summary.failed_tasks === 0 && summary.cancelled_tasks === 0 && summary.task_denied === 0 && taskDecision.action !== desiredTaskAction) {
1937
+ recommendations.push({
1938
+ id: recommendationId("task", summary.remote_did, desiredTaskAction),
1939
+ policy: "task",
1940
+ remote_did: summary.remote_did,
1941
+ match: summary.remote_did,
1942
+ action: desiredTaskAction,
1943
+ current_action: taskDecision.action,
1944
+ confidence: "high",
1945
+ reason: `Observed successful task flow without negative outcomes: processed_tasks=${summary.processed_tasks}`,
1946
+ signals: {
1947
+ trusted_sessions: summary.trusted_sessions,
1948
+ blocked_sessions: summary.blocked_sessions,
1949
+ revoked_sessions: summary.revoked_sessions,
1950
+ processed_tasks: summary.processed_tasks,
1951
+ failed_tasks: summary.failed_tasks,
1952
+ cancelled_tasks: summary.cancelled_tasks,
1953
+ contact_approvals: summary.contact_approvals,
1954
+ contact_rejections: summary.contact_rejections,
1955
+ task_denied: summary.task_denied,
1956
+ last_seen_at: summary.last_seen_at
1957
+ }
1958
+ });
1959
+ }
1960
+ }
1961
+ recommendations.sort((a, b) => {
1962
+ const confidenceScore = (value) => value === "high" ? 2 : 1;
1963
+ const delta = confidenceScore(b.confidence) - confidenceScore(a.confidence);
1964
+ if (delta !== 0) return delta;
1965
+ return (b.signals.last_seen_at ?? 0) - (a.signals.last_seen_at ?? 0);
1966
+ });
1967
+ return recommendations.slice(0, opts.limit ?? 20);
1968
+ }
1969
+ function upsertTrustPolicyRecommendation(policyDoc, recommendation) {
1970
+ const doc = normalizeTrustPolicyDoc(policyDoc);
1971
+ if (recommendation.policy === "contact") {
1972
+ return normalizeTrustPolicyDoc({
1973
+ ...doc,
1974
+ contact_policy: {
1975
+ ...doc.contact_policy,
1976
+ enabled: true,
1977
+ rules: [
1978
+ { match: recommendation.match, action: recommendation.action },
1979
+ ...doc.contact_policy.rules.filter((rule) => rule.match !== recommendation.match)
1980
+ ]
1981
+ }
1982
+ });
1983
+ }
1984
+ return normalizeTrustPolicyDoc({
1985
+ ...doc,
1986
+ task_policy: {
1987
+ ...doc.task_policy,
1988
+ enabled: true,
1989
+ rules: [
1990
+ { match: recommendation.match, action: recommendation.action },
1991
+ ...doc.task_policy.rules.filter((rule) => rule.match !== recommendation.match)
1992
+ ]
1993
+ }
1994
+ });
1995
+ }
1996
+ function summarizeTrustPolicyAudit(events) {
1997
+ return buildSummaryFromEvents(events);
1998
+ }
1999
+
2000
+ // src/a2a-adapter.ts
2001
+ import {
2002
+ A2AClient
2003
+ } from "@pingagent/a2a";
2004
+ var A2AAdapter = class {
2005
+ client;
2006
+ cachedCard = null;
2007
+ constructor(opts) {
2008
+ this.client = new A2AClient({
2009
+ agentUrl: opts.agentUrl,
2010
+ authToken: opts.authToken ? `Bearer ${opts.authToken}` : void 0,
2011
+ timeoutMs: opts.timeoutMs
2012
+ });
2013
+ }
2014
+ async getAgentCard() {
2015
+ if (!this.cachedCard) {
2016
+ this.cachedCard = await this.client.fetchAgentCard();
2017
+ }
2018
+ return this.cachedCard;
2019
+ }
2020
+ /**
2021
+ * Send a task to the external A2A agent and optionally wait for completion.
2022
+ */
2023
+ async sendTask(opts) {
2024
+ const parts = [];
2025
+ parts.push({ kind: "text", text: opts.title });
2026
+ if (opts.description) {
2027
+ parts.push({ kind: "text", text: opts.description });
2028
+ }
2029
+ if (opts.input) {
2030
+ parts.push({
2031
+ kind: "data",
2032
+ data: typeof opts.input === "object" ? opts.input : { value: opts.input }
2033
+ });
2034
+ }
2035
+ const messageId = `msg_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
2036
+ const message = {
2037
+ kind: "message",
2038
+ messageId,
2039
+ role: "user",
2040
+ parts
2041
+ };
2042
+ if (opts.wait) {
2043
+ const task = await this.client.sendAndWait(
2044
+ { message, configuration: { blocking: true } },
2045
+ { maxPollMs: opts.timeoutMs ?? 12e4 }
2046
+ );
2047
+ return this.convertTask(task);
2048
+ }
2049
+ const result = await this.client.sendMessage({ message });
2050
+ if (result.kind === "task") {
2051
+ return this.convertTask(result);
2052
+ }
2053
+ return {
2054
+ taskId: result.messageId,
2055
+ state: "completed",
2056
+ summary: this.extractText(result.parts)
2057
+ };
2058
+ }
2059
+ async getTaskStatus(taskId) {
2060
+ const task = await this.client.getTask(taskId);
2061
+ return this.convertTask(task);
2062
+ }
2063
+ async cancelTask(taskId) {
2064
+ const task = await this.client.cancelTask(taskId);
2065
+ return this.convertTask(task);
2066
+ }
2067
+ async sendText(text, opts) {
2068
+ const result = await this.client.sendText(text, { blocking: opts?.blocking });
2069
+ if (result.kind === "task") {
2070
+ return this.convertTask(result);
2071
+ }
2072
+ return {
2073
+ taskId: result.messageId,
2074
+ state: "completed",
2075
+ summary: this.extractText(result.parts)
2076
+ };
2077
+ }
2078
+ convertTask(task) {
2079
+ const summary = task.artifacts?.flatMap((a) => a.parts).filter((p) => p.kind === "text").map((p) => p.text).join("\n");
2080
+ const output = task.artifacts?.flatMap((a) => a.parts).filter((p) => p.kind === "data").map((p) => p.data);
2081
+ return {
2082
+ taskId: task.id,
2083
+ contextId: task.contextId,
2084
+ state: task.status.state,
2085
+ summary: summary || void 0,
2086
+ output: output && output.length > 0 ? output.length === 1 ? output[0] : output : void 0,
2087
+ timestamp: task.status.timestamp
2088
+ };
2089
+ }
2090
+ extractText(parts) {
2091
+ return parts.filter((p) => p.kind === "text").map((p) => p.text).join("\n") || void 0;
2092
+ }
2093
+ };
2094
+
2095
+ // src/ws-subscription.ts
2096
+ import WebSocket from "ws";
2097
+ var RECONNECT_BASE_MS = 1e3;
2098
+ var RECONNECT_MAX_MS = 3e4;
2099
+ var RECONNECT_JITTER = 0.2;
2100
+ var LIST_CONVERSATIONS_INTERVAL_MS = 6e4;
2101
+ var DEFAULT_HEARTBEAT = {
2102
+ enable: true,
2103
+ idleThresholdMs: 1e4,
2104
+ pingIntervalMs: 15e3,
2105
+ pongTimeoutMs: 1e4,
2106
+ maxMissedPongs: 2,
2107
+ tickMs: 5e3,
2108
+ jitter: 0.2
2109
+ };
2110
+ var WsSubscription = class {
2111
+ opts;
2112
+ connections = /* @__PURE__ */ new Map();
2113
+ reconnectTimers = /* @__PURE__ */ new Map();
2114
+ reconnectAttempts = /* @__PURE__ */ new Map();
2115
+ listInterval = null;
2116
+ stopped = false;
2117
+ /** Conversation IDs that were explicitly stopped (e.g. revoke); do not reconnect. */
2118
+ stoppedConversations = /* @__PURE__ */ new Set();
2119
+ lastParseErrorAtByConv = /* @__PURE__ */ new Map();
2120
+ lastFrameAtByConv = /* @__PURE__ */ new Map();
2121
+ heartbeatTimer = null;
2122
+ heartbeatStates = /* @__PURE__ */ new Map();
2123
+ constructor(opts) {
2124
+ this.opts = opts;
2125
+ }
2126
+ start() {
2127
+ this.stopped = false;
2128
+ this.connectAll();
2129
+ this.listInterval = setInterval(() => this.syncConnections(), LIST_CONVERSATIONS_INTERVAL_MS);
2130
+ const hb = this.opts.heartbeat ?? {};
2131
+ if (hb.enable ?? DEFAULT_HEARTBEAT.enable) {
2132
+ this.heartbeatTimer = setInterval(() => this.heartbeatTick(), hb.tickMs ?? DEFAULT_HEARTBEAT.tickMs);
2133
+ }
2134
+ }
2135
+ stop() {
2136
+ this.stopped = true;
2137
+ if (this.listInterval) {
2138
+ clearInterval(this.listInterval);
2139
+ this.listInterval = null;
2140
+ }
2141
+ if (this.heartbeatTimer) {
2142
+ clearInterval(this.heartbeatTimer);
2143
+ this.heartbeatTimer = null;
2144
+ }
2145
+ for (const timer of this.reconnectTimers.values()) {
2146
+ clearTimeout(timer);
2147
+ }
2148
+ this.reconnectTimers.clear();
2149
+ for (const [convId, ws] of this.connections) {
2150
+ ws.removeAllListeners();
2151
+ if (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING) {
2152
+ ws.close();
2153
+ }
2154
+ this.connections.delete(convId);
2155
+ }
2156
+ this.reconnectAttempts.clear();
2157
+ this.stoppedConversations.clear();
2158
+ this.lastParseErrorAtByConv.clear();
2159
+ this.lastFrameAtByConv.clear();
2160
+ for (const state of this.heartbeatStates.values()) {
2161
+ if (state.pongTimeout) clearTimeout(state.pongTimeout);
2162
+ }
2163
+ this.heartbeatStates.clear();
2164
+ }
2165
+ /**
2166
+ * Stop a single conversation's WebSocket and do not reconnect.
2167
+ * Used when the conversation is revoked or the client no longer wants to subscribe.
2168
+ */
2169
+ stopConversation(conversationId) {
2170
+ this.stoppedConversations.add(conversationId);
2171
+ const timer = this.reconnectTimers.get(conversationId);
2172
+ if (timer) {
2173
+ clearTimeout(timer);
2174
+ this.reconnectTimers.delete(conversationId);
2175
+ }
2176
+ const hbState = this.heartbeatStates.get(conversationId);
2177
+ if (hbState?.pongTimeout) clearTimeout(hbState.pongTimeout);
2178
+ this.heartbeatStates.delete(conversationId);
2179
+ const ws = this.connections.get(conversationId);
2180
+ if (ws) {
2181
+ ws.removeAllListeners();
2182
+ if (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING) {
2183
+ ws.close();
2184
+ }
2185
+ this.connections.delete(conversationId);
2186
+ }
2187
+ this.lastParseErrorAtByConv.delete(conversationId);
2188
+ this.lastFrameAtByConv.delete(conversationId);
2189
+ }
2190
+ wsUrl(conversationId) {
2191
+ const base = this.opts.serverUrl.replace(/^http/, "ws").replace(/\/$/, "");
2192
+ return `${base}/v1/ws?conversation_id=${encodeURIComponent(conversationId)}`;
2193
+ }
2194
+ async connectAsync(conversationId) {
2195
+ if (this.stopped || this.stoppedConversations.has(conversationId) || this.connections.has(conversationId)) return;
2196
+ const token = await Promise.resolve(this.opts.getAccessToken());
2197
+ const url = this.wsUrl(conversationId);
2198
+ const ws = new WebSocket(url, {
2199
+ headers: { Authorization: `Bearer ${token}` }
2200
+ });
2201
+ this.connections.set(conversationId, ws);
2202
+ const hb = this.opts.heartbeat ?? {};
2203
+ const hbEnabled = hb.enable ?? DEFAULT_HEARTBEAT.enable;
2204
+ if (hbEnabled) {
2205
+ const now = Date.now();
2206
+ this.heartbeatStates.set(conversationId, {
2207
+ lastRxAt: now,
2208
+ lastPingAt: 0,
2209
+ nextPingAt: now + (hb.idleThresholdMs ?? DEFAULT_HEARTBEAT.idleThresholdMs),
2210
+ missedPongs: 0,
2211
+ pongTimeout: null
2212
+ });
2213
+ }
2214
+ ws.on("open", () => {
2215
+ this.reconnectAttempts.set(conversationId, 0);
2216
+ this.opts.onOpen?.(conversationId);
2217
+ });
2218
+ ws.on("message", (data) => {
2219
+ try {
2220
+ const state = this.heartbeatStates.get(conversationId);
2221
+ if (state) {
2222
+ state.lastRxAt = Date.now();
2223
+ state.missedPongs = 0;
2224
+ if (state.pongTimeout) {
2225
+ clearTimeout(state.pongTimeout);
2226
+ state.pongTimeout = null;
2227
+ }
2228
+ }
2229
+ const rawText = typeof data === "string" ? data : Buffer.isBuffer(data) ? data.toString() : Array.isArray(data) ? Buffer.concat(data).toString() : data instanceof ArrayBuffer ? Buffer.from(new Uint8Array(data)).toString() : (
2230
+ // Fallback: try best-effort stringification
2231
+ String(data)
2232
+ );
2233
+ this.lastFrameAtByConv.set(conversationId, Date.now());
2234
+ const msg = JSON.parse(rawText);
2235
+ if (msg.type === "ws_connected") {
2236
+ this.opts.onDebug?.({
2237
+ event: "ws_connected",
2238
+ conversationId,
2239
+ detail: {
2240
+ your_did: msg.your_did,
2241
+ server_ts_ms: msg.server_ts_ms,
2242
+ conversation_id: msg.conversation_id
2243
+ }
2244
+ });
2245
+ } else if (msg.type === "ws_message" && msg.envelope) {
2246
+ const env = msg.envelope;
2247
+ const ignoreSelf = this.opts.ignoreSelfMessages ?? true;
2248
+ if (!ignoreSelf || env.sender_did !== this.opts.myDid) {
2249
+ this.opts.onMessage(env, conversationId);
2250
+ } else {
2251
+ this.opts.onDebug?.({
2252
+ event: "ws_message_ignored_self",
2253
+ conversationId,
2254
+ detail: { sender_did: env.sender_did, message_id: env.message_id, seq: env.seq }
2255
+ });
2256
+ }
2257
+ } else if (msg.type === "ws_control" && msg.control) {
2258
+ this.opts.onControl?.(msg.control, conversationId);
2259
+ this.opts.onDebug?.({ event: "ws_control", conversationId, detail: msg.control });
2260
+ } else if (msg.type === "ws_receipt" && msg.receipt) {
2261
+ this.opts.onDebug?.({ event: "ws_receipt", conversationId, detail: msg.receipt });
2262
+ } else if (msg?.type) {
2263
+ this.opts.onDebug?.({ event: "ws_unknown_type", conversationId, detail: { type: msg.type } });
2264
+ }
2265
+ } catch (e) {
2266
+ const now = Date.now();
2267
+ const last = this.lastParseErrorAtByConv.get(conversationId) ?? 0;
2268
+ if (now - last > 3e4) {
2269
+ this.lastParseErrorAtByConv.set(conversationId, now);
2270
+ this.opts.onDebug?.({
2271
+ event: "ws_parse_error",
2272
+ conversationId,
2273
+ detail: {
2274
+ message: e?.message ?? String(e),
2275
+ last_frame_at_ms: this.lastFrameAtByConv.get(conversationId) ?? null
2276
+ }
2277
+ });
2278
+ }
2279
+ }
2280
+ });
2281
+ ws.on("pong", () => {
2282
+ const state = this.heartbeatStates.get(conversationId);
2283
+ if (!state) return;
2284
+ state.lastRxAt = Date.now();
2285
+ state.missedPongs = 0;
2286
+ if (state.pongTimeout) {
2287
+ clearTimeout(state.pongTimeout);
2288
+ state.pongTimeout = null;
2289
+ }
2290
+ });
2291
+ ws.on("close", () => {
2292
+ this.connections.delete(conversationId);
2293
+ const state = this.heartbeatStates.get(conversationId);
2294
+ if (state?.pongTimeout) clearTimeout(state.pongTimeout);
2295
+ this.heartbeatStates.delete(conversationId);
2296
+ if (!this.stopped && !this.stoppedConversations.has(conversationId)) {
2297
+ this.scheduleReconnect(conversationId);
2298
+ }
2299
+ });
2300
+ ws.on("error", (err) => {
2301
+ this.opts.onError?.(err);
2302
+ });
2303
+ }
2304
+ heartbeatTick() {
2305
+ const hb = this.opts.heartbeat ?? {};
2306
+ const hbEnabled = hb.enable ?? DEFAULT_HEARTBEAT.enable;
2307
+ if (!hbEnabled) return;
2308
+ const idleThresholdMs = hb.idleThresholdMs ?? DEFAULT_HEARTBEAT.idleThresholdMs;
2309
+ const pingIntervalMs = hb.pingIntervalMs ?? DEFAULT_HEARTBEAT.pingIntervalMs;
2310
+ const pongTimeoutMs = hb.pongTimeoutMs ?? DEFAULT_HEARTBEAT.pongTimeoutMs;
2311
+ const maxMissedPongs = hb.maxMissedPongs ?? DEFAULT_HEARTBEAT.maxMissedPongs;
2312
+ const jitter = hb.jitter ?? DEFAULT_HEARTBEAT.jitter;
2313
+ const now = Date.now();
2314
+ for (const [conversationId, ws] of this.connections) {
2315
+ if (ws.readyState !== WebSocket.OPEN) continue;
2316
+ const state = this.heartbeatStates.get(conversationId);
2317
+ if (!state) continue;
2318
+ if (state.pongTimeout) continue;
2319
+ const idleFor = now - state.lastRxAt;
2320
+ if (idleFor < idleThresholdMs) continue;
2321
+ if (now < state.nextPingAt) continue;
2322
+ if (state.lastPingAt !== 0 && now - state.lastPingAt < pingIntervalMs * 0.5) {
2323
+ continue;
2324
+ }
2325
+ try {
2326
+ ws.send(JSON.stringify({ type: "hb" }));
2327
+ } catch {
2328
+ }
2329
+ ws.ping();
2330
+ state.lastPingAt = now;
2331
+ const jitterFactor = 1 + (Math.random() - 0.5) * 2 * jitter;
2332
+ state.nextPingAt = now + Math.max(1e3, pingIntervalMs * jitterFactor);
2333
+ state.pongTimeout = setTimeout(() => {
2334
+ state.missedPongs += 1;
2335
+ state.pongTimeout = null;
2336
+ if (state.missedPongs >= maxMissedPongs) {
2337
+ try {
2338
+ ws.close(1001, "pong timeout");
2339
+ } catch {
2340
+ }
2341
+ }
2342
+ }, pongTimeoutMs);
2343
+ }
2344
+ }
2345
+ scheduleReconnect(conversationId) {
2346
+ if (this.reconnectTimers.has(conversationId)) return;
2347
+ const attempt = this.reconnectAttempts.get(conversationId) ?? 0;
2348
+ this.reconnectAttempts.set(conversationId, attempt + 1);
2349
+ const tryConnect = () => {
2350
+ this.reconnectTimers.delete(conversationId);
2351
+ if (this.stopped) return;
2352
+ void this.connectAsync(conversationId);
2353
+ };
2354
+ const delay = Math.min(
2355
+ RECONNECT_BASE_MS * Math.pow(2, attempt) + (Math.random() - 0.5) * RECONNECT_JITTER * RECONNECT_BASE_MS,
2356
+ RECONNECT_MAX_MS
2357
+ );
2358
+ const timer = setTimeout(tryConnect, delay);
2359
+ this.reconnectTimers.set(conversationId, timer);
2360
+ }
2361
+ isSubscribableConversationType(type) {
2362
+ return type === "dm" || type === "pending_dm" || type === "channel" || type === "group";
2363
+ }
2364
+ async connectAll() {
2365
+ try {
2366
+ const convos = await this.opts.listConversations();
2367
+ const subscribable = convos.filter((c) => this.isSubscribableConversationType(c.type));
2368
+ for (const c of subscribable) {
2369
+ void this.connectAsync(c.conversation_id);
2370
+ }
2371
+ } catch (err) {
2372
+ this.opts.onError?.(err instanceof Error ? err : new Error(String(err)));
2373
+ }
2374
+ }
2375
+ async syncConnections() {
2376
+ if (this.stopped) return;
2377
+ try {
2378
+ const convos = await this.opts.listConversations();
2379
+ const subscribableIds = new Set(
2380
+ convos.filter((c) => this.isSubscribableConversationType(c.type)).map((c) => c.conversation_id)
2381
+ );
2382
+ for (const convId of subscribableIds) {
2383
+ if (!this.stoppedConversations.has(convId) && !this.connections.has(convId)) {
2384
+ void this.connectAsync(convId);
2385
+ }
2386
+ }
2387
+ for (const convId of this.connections.keys()) {
2388
+ if (!subscribableIds.has(convId) || this.stoppedConversations.has(convId)) {
2389
+ const ws = this.connections.get(convId);
2390
+ if (ws) {
2391
+ ws.removeAllListeners();
2392
+ ws.close();
2393
+ this.connections.delete(convId);
2394
+ }
2395
+ }
2396
+ }
2397
+ } catch {
2398
+ }
2399
+ }
2400
+ };
2401
+
2402
+ export {
2403
+ HttpTransport,
2404
+ ContactManager,
2405
+ HistoryManager,
2406
+ previewFromPayload,
2407
+ buildSessionKey,
2408
+ SessionManager,
2409
+ TaskThreadManager,
2410
+ PingAgentClient,
2411
+ getRootDir,
2412
+ getProfile,
2413
+ getIdentityPath,
2414
+ getStorePath,
2415
+ generateIdentity,
2416
+ identityExists,
2417
+ loadIdentity,
2418
+ saveIdentity,
2419
+ updateStoredToken,
2420
+ ensureTokenValid,
2421
+ LocalStore,
2422
+ defaultTrustPolicyDoc,
2423
+ normalizeTrustPolicyDoc,
2424
+ matchesTrustPolicyRule,
2425
+ decideContactPolicy,
2426
+ decideTaskPolicy,
2427
+ TrustPolicyAuditManager,
2428
+ buildTrustPolicyRecommendations,
2429
+ upsertTrustPolicyRecommendation,
2430
+ summarizeTrustPolicyAudit,
2431
+ A2AAdapter,
2432
+ WsSubscription
2433
+ };