@pingagent/sdk 0.1.10 → 0.1.11

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,3553 @@
1
+ // src/client.ts
2
+ import { ERROR_HINTS, ErrorCode as ErrorCode2, SCHEMA_TASK as SCHEMA_TASK2, SCHEMA_CONTACT_REQUEST as SCHEMA_CONTACT_REQUEST2, SCHEMA_RESULT as SCHEMA_RESULT2, SCHEMA_TEXT as SCHEMA_TEXT2 } 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, path6, body, skipAuth = false) {
40
+ const url = `${this.serverUrl}${path6}`;
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((resolve4) => setTimeout(resolve4, ms));
115
+ }
116
+
117
+ // src/identity.ts
118
+ import * as fs from "fs";
119
+ import * as path2 from "path";
120
+ import { generateKeyPairSync } from "crypto";
121
+ import { generateIdentity as genId } from "@pingagent/protocol";
122
+
123
+ // src/paths.ts
124
+ import * as path from "path";
125
+ import * as os from "os";
126
+ var DEFAULT_ROOT_DIR = path.join(os.homedir(), ".pingagent");
127
+ function getRootDir() {
128
+ return process.env.PINGAGENT_ROOT_DIR || DEFAULT_ROOT_DIR;
129
+ }
130
+ function getProfile() {
131
+ const p = process.env.PINGAGENT_PROFILE;
132
+ if (!p) return void 0;
133
+ return p.trim() || void 0;
134
+ }
135
+ function getIdentityPath(explicitPath) {
136
+ const envPath = process.env.PINGAGENT_IDENTITY_PATH?.trim();
137
+ if (explicitPath) return explicitPath;
138
+ if (envPath) return path.resolve(envPath.replace(/^~(?=\/|$)/, os.homedir()));
139
+ const root = getRootDir();
140
+ const profile = getProfile();
141
+ if (!profile) {
142
+ return path.join(root, "identity.json");
143
+ }
144
+ return path.join(root, "profiles", profile, "identity.json");
145
+ }
146
+ function getStorePath(explicitPath) {
147
+ const envPath = process.env.PINGAGENT_STORE_PATH?.trim();
148
+ if (explicitPath) return explicitPath;
149
+ if (envPath) return path.resolve(envPath.replace(/^~(?=\/|$)/, os.homedir()));
150
+ const root = getRootDir();
151
+ const profile = getProfile();
152
+ if (!profile) {
153
+ return path.join(root, "store.db");
154
+ }
155
+ return path.join(root, "profiles", profile, "store.db");
156
+ }
157
+
158
+ // src/identity.ts
159
+ function toBase64(bytes) {
160
+ let binary = "";
161
+ for (const b of bytes) binary += String.fromCharCode(b);
162
+ return btoa(binary);
163
+ }
164
+ function fromBase64(b64) {
165
+ const binary = atob(b64);
166
+ const bytes = new Uint8Array(binary.length);
167
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
168
+ return bytes;
169
+ }
170
+ function generateEncryptionKeyPair() {
171
+ const { privateKey, publicKey } = generateKeyPairSync("ec", { namedCurve: "prime256v1" });
172
+ const privateJwk = privateKey.export({ format: "jwk" });
173
+ const publicJwk = publicKey.export({ format: "jwk" });
174
+ return {
175
+ encryptionPublicKeyJwk: {
176
+ kty: "EC",
177
+ crv: "P-256",
178
+ x: publicJwk.x,
179
+ y: publicJwk.y
180
+ },
181
+ encryptionPrivateKeyJwk: {
182
+ kty: "EC",
183
+ crv: "P-256",
184
+ x: privateJwk.x,
185
+ y: privateJwk.y,
186
+ d: privateJwk.d
187
+ }
188
+ };
189
+ }
190
+ function ensureIdentityEncryptionKeys(identity) {
191
+ if (identity.encryptionPublicKeyJwk && identity.encryptionPrivateKeyJwk) {
192
+ return {
193
+ encryptionPublicKeyJwk: identity.encryptionPublicKeyJwk,
194
+ encryptionPrivateKeyJwk: identity.encryptionPrivateKeyJwk
195
+ };
196
+ }
197
+ return generateEncryptionKeyPair();
198
+ }
199
+ function generateIdentity() {
200
+ const signingIdentity = genId();
201
+ return {
202
+ ...signingIdentity,
203
+ ...ensureIdentityEncryptionKeys({})
204
+ };
205
+ }
206
+ function identityExists(identityPath) {
207
+ return fs.existsSync(getIdentityPath(identityPath));
208
+ }
209
+ function loadIdentity(identityPath) {
210
+ const p = getIdentityPath(identityPath);
211
+ const data = JSON.parse(fs.readFileSync(p, "utf-8"));
212
+ const encryption = ensureIdentityEncryptionKeys({
213
+ encryptionPublicKeyJwk: data.encryption_public_key,
214
+ encryptionPrivateKeyJwk: data.encryption_private_key
215
+ });
216
+ if (!data.encryption_public_key || !data.encryption_private_key) {
217
+ data.encryption_public_key = encryption.encryptionPublicKeyJwk;
218
+ data.encryption_private_key = encryption.encryptionPrivateKeyJwk;
219
+ fs.writeFileSync(p, JSON.stringify(data, null, 2), { mode: 384 });
220
+ }
221
+ return {
222
+ publicKey: fromBase64(data.public_key),
223
+ privateKey: fromBase64(data.private_key),
224
+ ...encryption,
225
+ did: data.did,
226
+ deviceId: data.device_id,
227
+ serverUrl: data.server_url,
228
+ accessToken: data.access_token,
229
+ tokenExpiresAt: data.token_expires_at,
230
+ mode: data.mode
231
+ };
232
+ }
233
+ function saveIdentity(identity, opts, identityPath) {
234
+ const p = getIdentityPath(identityPath);
235
+ const dir = path2.dirname(p);
236
+ if (!fs.existsSync(dir)) {
237
+ fs.mkdirSync(dir, { recursive: true, mode: 448 });
238
+ }
239
+ const encryption = ensureIdentityEncryptionKeys(identity);
240
+ const stored = {
241
+ public_key: toBase64(identity.publicKey),
242
+ private_key: toBase64(identity.privateKey),
243
+ encryption_public_key: encryption.encryptionPublicKeyJwk,
244
+ encryption_private_key: encryption.encryptionPrivateKeyJwk,
245
+ did: identity.did,
246
+ device_id: identity.deviceId,
247
+ server_url: opts?.serverUrl,
248
+ access_token: opts?.accessToken,
249
+ token_expires_at: opts?.tokenExpiresAt,
250
+ mode: opts?.mode,
251
+ alias: opts?.alias
252
+ };
253
+ fs.writeFileSync(p, JSON.stringify(stored, null, 2), { mode: 384 });
254
+ }
255
+ function updateStoredToken(accessToken, expiresAt, identityPath) {
256
+ const p = getIdentityPath(identityPath);
257
+ const data = JSON.parse(fs.readFileSync(p, "utf-8"));
258
+ data.access_token = accessToken;
259
+ data.token_expires_at = expiresAt;
260
+ fs.writeFileSync(p, JSON.stringify(data, null, 2), { mode: 384 });
261
+ }
262
+
263
+ // src/contacts.ts
264
+ function rowToContact(row) {
265
+ return {
266
+ did: row.did,
267
+ alias: row.alias ?? void 0,
268
+ display_name: row.display_name ?? void 0,
269
+ notes: row.notes ?? void 0,
270
+ conversation_id: row.conversation_id ?? void 0,
271
+ trusted: row.trusted === 1,
272
+ added_at: row.added_at,
273
+ last_message_at: row.last_message_at ?? void 0,
274
+ tags: row.tags ? JSON.parse(row.tags) : void 0
275
+ };
276
+ }
277
+ var ContactManager = class {
278
+ store;
279
+ constructor(store) {
280
+ this.store = store;
281
+ }
282
+ add(contact) {
283
+ const db = this.store.getDb();
284
+ const now = contact.added_at ?? Date.now();
285
+ db.prepare(`
286
+ INSERT INTO contacts (did, alias, display_name, notes, conversation_id, trusted, added_at, last_message_at, tags)
287
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
288
+ ON CONFLICT(did) DO UPDATE SET
289
+ alias = COALESCE(excluded.alias, contacts.alias),
290
+ display_name = COALESCE(excluded.display_name, contacts.display_name),
291
+ notes = COALESCE(excluded.notes, contacts.notes),
292
+ conversation_id = COALESCE(excluded.conversation_id, contacts.conversation_id),
293
+ trusted = excluded.trusted,
294
+ last_message_at = COALESCE(excluded.last_message_at, contacts.last_message_at),
295
+ tags = COALESCE(excluded.tags, contacts.tags)
296
+ `).run(
297
+ contact.did,
298
+ contact.alias ?? null,
299
+ contact.display_name ?? null,
300
+ contact.notes ?? null,
301
+ contact.conversation_id ?? null,
302
+ contact.trusted ? 1 : 0,
303
+ now,
304
+ contact.last_message_at ?? null,
305
+ contact.tags ? JSON.stringify(contact.tags) : null
306
+ );
307
+ return { ...contact, added_at: now };
308
+ }
309
+ remove(did) {
310
+ const result = this.store.getDb().prepare("DELETE FROM contacts WHERE did = ?").run(did);
311
+ return result.changes > 0;
312
+ }
313
+ get(did) {
314
+ const row = this.store.getDb().prepare("SELECT * FROM contacts WHERE did = ?").get(did);
315
+ return row ? rowToContact(row) : null;
316
+ }
317
+ update(did, updates) {
318
+ const existing = this.get(did);
319
+ if (!existing) return null;
320
+ const fields = [];
321
+ const values = [];
322
+ if (updates.alias !== void 0) {
323
+ fields.push("alias = ?");
324
+ values.push(updates.alias);
325
+ }
326
+ if (updates.display_name !== void 0) {
327
+ fields.push("display_name = ?");
328
+ values.push(updates.display_name);
329
+ }
330
+ if (updates.notes !== void 0) {
331
+ fields.push("notes = ?");
332
+ values.push(updates.notes);
333
+ }
334
+ if (updates.conversation_id !== void 0) {
335
+ fields.push("conversation_id = ?");
336
+ values.push(updates.conversation_id);
337
+ }
338
+ if (updates.trusted !== void 0) {
339
+ fields.push("trusted = ?");
340
+ values.push(updates.trusted ? 1 : 0);
341
+ }
342
+ if (updates.last_message_at !== void 0) {
343
+ fields.push("last_message_at = ?");
344
+ values.push(updates.last_message_at);
345
+ }
346
+ if (updates.tags !== void 0) {
347
+ fields.push("tags = ?");
348
+ values.push(JSON.stringify(updates.tags));
349
+ }
350
+ if (fields.length === 0) return existing;
351
+ values.push(did);
352
+ this.store.getDb().prepare(`UPDATE contacts SET ${fields.join(", ")} WHERE did = ?`).run(...values);
353
+ return this.get(did);
354
+ }
355
+ list(opts) {
356
+ const conditions = [];
357
+ const params = [];
358
+ if (opts?.trusted !== void 0) {
359
+ conditions.push("trusted = ?");
360
+ params.push(opts.trusted ? 1 : 0);
361
+ }
362
+ if (opts?.tag) {
363
+ conditions.push("tags LIKE ?");
364
+ params.push(`%"${opts.tag}"%`);
365
+ }
366
+ const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
367
+ const limit = opts?.limit ? `LIMIT ${opts.limit}` : "";
368
+ const offset = opts?.offset ? `OFFSET ${opts.offset}` : "";
369
+ const rows = this.store.getDb().prepare(`SELECT * FROM contacts ${where} ORDER BY added_at DESC ${limit} ${offset}`).all(...params);
370
+ return rows.map(rowToContact);
371
+ }
372
+ search(query) {
373
+ const pattern = `%${query}%`;
374
+ const rows = this.store.getDb().prepare(`
375
+ SELECT * FROM contacts
376
+ WHERE did LIKE ? OR alias LIKE ? OR display_name LIKE ? OR notes LIKE ?
377
+ ORDER BY added_at DESC
378
+ `).all(pattern, pattern, pattern, pattern);
379
+ return rows.map(rowToContact);
380
+ }
381
+ export(format = "json") {
382
+ const contacts = this.list();
383
+ if (format === "csv") {
384
+ const header = "did,alias,display_name,notes,conversation_id,trusted,added_at,last_message_at,tags";
385
+ const rows = contacts.map(
386
+ (c) => [
387
+ c.did,
388
+ c.alias ?? "",
389
+ c.display_name ?? "",
390
+ c.notes ?? "",
391
+ c.conversation_id ?? "",
392
+ c.trusted,
393
+ c.added_at,
394
+ c.last_message_at ?? "",
395
+ c.tags ? JSON.stringify(c.tags) : ""
396
+ ].map((v) => `"${String(v).replace(/"/g, '""')}"`).join(",")
397
+ );
398
+ return [header, ...rows].join("\n");
399
+ }
400
+ return JSON.stringify(contacts, null, 2);
401
+ }
402
+ import(data, format = "json") {
403
+ let imported = 0;
404
+ let skipped = 0;
405
+ if (format === "json") {
406
+ const contacts = JSON.parse(data);
407
+ for (const c of contacts) {
408
+ try {
409
+ this.add(c);
410
+ imported++;
411
+ } catch {
412
+ skipped++;
413
+ }
414
+ }
415
+ } else {
416
+ const lines = data.split("\n").filter((l) => l.trim());
417
+ for (let i = 1; i < lines.length; i++) {
418
+ try {
419
+ const cols = parseCsvLine(lines[i]);
420
+ this.add({
421
+ did: cols[0],
422
+ alias: cols[1] || void 0,
423
+ display_name: cols[2] || void 0,
424
+ notes: cols[3] || void 0,
425
+ conversation_id: cols[4] || void 0,
426
+ trusted: cols[5] === "1" || cols[5] === "true",
427
+ added_at: parseInt(cols[6]) || Date.now(),
428
+ last_message_at: cols[7] ? parseInt(cols[7]) : void 0,
429
+ tags: cols[8] ? JSON.parse(cols[8]) : void 0
430
+ });
431
+ imported++;
432
+ } catch {
433
+ skipped++;
434
+ }
435
+ }
436
+ }
437
+ return { imported, skipped };
438
+ }
439
+ };
440
+ function parseCsvLine(line) {
441
+ const result = [];
442
+ let current = "";
443
+ let inQuotes = false;
444
+ for (let i = 0; i < line.length; i++) {
445
+ const ch = line[i];
446
+ if (inQuotes) {
447
+ if (ch === '"' && line[i + 1] === '"') {
448
+ current += '"';
449
+ i++;
450
+ } else if (ch === '"') {
451
+ inQuotes = false;
452
+ } else {
453
+ current += ch;
454
+ }
455
+ } else {
456
+ if (ch === '"') {
457
+ inQuotes = true;
458
+ } else if (ch === ",") {
459
+ result.push(current);
460
+ current = "";
461
+ } else {
462
+ current += ch;
463
+ }
464
+ }
465
+ }
466
+ result.push(current);
467
+ return result;
468
+ }
469
+
470
+ // src/history.ts
471
+ function rowToMessage(row) {
472
+ return {
473
+ conversation_id: row.conversation_id,
474
+ message_id: row.message_id,
475
+ seq: row.seq ?? void 0,
476
+ sender_did: row.sender_did,
477
+ schema: row.schema,
478
+ payload: JSON.parse(row.payload),
479
+ ts_ms: row.ts_ms,
480
+ direction: row.direction
481
+ };
482
+ }
483
+ var HistoryManager = class {
484
+ store;
485
+ constructor(store) {
486
+ this.store = store;
487
+ }
488
+ save(messages) {
489
+ const db = this.store.getDb();
490
+ const stmt = db.prepare(`
491
+ INSERT INTO messages (conversation_id, message_id, seq, sender_did, schema, payload, ts_ms, direction)
492
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
493
+ ON CONFLICT(message_id) DO UPDATE SET
494
+ seq = COALESCE(excluded.seq, messages.seq),
495
+ payload = excluded.payload,
496
+ ts_ms = excluded.ts_ms
497
+ `);
498
+ let count = 0;
499
+ const tx = db.transaction(() => {
500
+ for (const msg of messages) {
501
+ stmt.run(
502
+ msg.conversation_id,
503
+ msg.message_id,
504
+ msg.seq ?? null,
505
+ msg.sender_did,
506
+ msg.schema,
507
+ JSON.stringify(msg.payload),
508
+ msg.ts_ms,
509
+ msg.direction
510
+ );
511
+ count++;
512
+ }
513
+ });
514
+ tx();
515
+ return count;
516
+ }
517
+ list(conversationId, opts) {
518
+ const conditions = ["conversation_id = ?"];
519
+ const params = [conversationId];
520
+ if (opts?.beforeSeq !== void 0) {
521
+ conditions.push("seq < ?");
522
+ params.push(opts.beforeSeq);
523
+ }
524
+ if (opts?.afterSeq !== void 0) {
525
+ conditions.push("seq > ?");
526
+ params.push(opts.afterSeq);
527
+ }
528
+ if (opts?.beforeTsMs !== void 0) {
529
+ conditions.push("ts_ms < ?");
530
+ params.push(opts.beforeTsMs);
531
+ }
532
+ if (opts?.afterTsMs !== void 0) {
533
+ conditions.push("ts_ms > ?");
534
+ params.push(opts.afterTsMs);
535
+ }
536
+ const limit = opts?.limit ?? 100;
537
+ const rows = this.store.getDb().prepare(`SELECT * FROM messages WHERE ${conditions.join(" AND ")} ORDER BY COALESCE(seq, ts_ms) ASC LIMIT ?`).all(...params, limit);
538
+ return rows.map(rowToMessage);
539
+ }
540
+ /**
541
+ * List the most recent N messages *before* a seq (paging older history).
542
+ * Only compares rows where seq is not null.
543
+ */
544
+ listBeforeSeq(conversationId, beforeSeq, limit) {
545
+ const rows = this.store.getDb().prepare(
546
+ `SELECT * FROM messages
547
+ WHERE conversation_id = ? AND seq IS NOT NULL AND seq < ?
548
+ ORDER BY seq DESC
549
+ LIMIT ?`
550
+ ).all(conversationId, beforeSeq, limit);
551
+ return rows.map(rowToMessage).reverse();
552
+ }
553
+ /**
554
+ * List the most recent N messages *before* a timestamp (paging older history).
555
+ */
556
+ listBeforeTs(conversationId, beforeTsMs, limit) {
557
+ const rows = this.store.getDb().prepare(
558
+ `SELECT * FROM messages
559
+ WHERE conversation_id = ? AND ts_ms < ?
560
+ ORDER BY ts_ms DESC
561
+ LIMIT ?`
562
+ ).all(conversationId, beforeTsMs, limit);
563
+ return rows.map(rowToMessage).reverse();
564
+ }
565
+ /** Returns the N most recent messages (chronological order, oldest to newest of those N). */
566
+ listRecent(conversationId, limit) {
567
+ const rows = this.store.getDb().prepare(
568
+ `SELECT * FROM messages WHERE conversation_id = ? ORDER BY COALESCE(seq, ts_ms) DESC LIMIT ?`
569
+ ).all(conversationId, limit);
570
+ return rows.map(rowToMessage).reverse();
571
+ }
572
+ search(query, opts) {
573
+ const conditions = ["payload LIKE ?"];
574
+ const params = [`%${query}%`];
575
+ if (opts?.conversationId) {
576
+ conditions.push("conversation_id = ?");
577
+ params.push(opts.conversationId);
578
+ }
579
+ const limit = opts?.limit ?? 50;
580
+ const rows = this.store.getDb().prepare(`SELECT * FROM messages WHERE ${conditions.join(" AND ")} ORDER BY ts_ms DESC LIMIT ?`).all(...params, limit);
581
+ return rows.map(rowToMessage);
582
+ }
583
+ delete(conversationId) {
584
+ const result = this.store.getDb().prepare("DELETE FROM messages WHERE conversation_id = ?").run(conversationId);
585
+ this.store.getDb().prepare("DELETE FROM sync_state WHERE conversation_id = ?").run(conversationId);
586
+ return result.changes;
587
+ }
588
+ listConversations() {
589
+ const rows = this.store.getDb().prepare(`
590
+ SELECT conversation_id, COUNT(*) as message_count, MAX(ts_ms) as last_message_at
591
+ FROM messages
592
+ GROUP BY conversation_id
593
+ ORDER BY last_message_at DESC
594
+ `).all();
595
+ return rows;
596
+ }
597
+ getLastSyncedSeq(conversationId) {
598
+ const row = this.store.getDb().prepare("SELECT last_synced_seq FROM sync_state WHERE conversation_id = ?").get(conversationId);
599
+ return row?.last_synced_seq ?? 0;
600
+ }
601
+ setLastSyncedSeq(conversationId, seq) {
602
+ this.store.getDb().prepare(`
603
+ INSERT INTO sync_state (conversation_id, last_synced_seq, last_synced_at)
604
+ VALUES (?, ?, ?)
605
+ ON CONFLICT(conversation_id) DO UPDATE SET last_synced_seq = excluded.last_synced_seq, last_synced_at = excluded.last_synced_at
606
+ `).run(conversationId, seq, Date.now());
607
+ }
608
+ export(opts) {
609
+ const format = opts?.format ?? "json";
610
+ let messages;
611
+ if (opts?.conversationId) {
612
+ messages = this.list(opts.conversationId, { limit: 1e5 });
613
+ } else {
614
+ const rows = this.store.getDb().prepare("SELECT * FROM messages ORDER BY ts_ms ASC").all();
615
+ messages = rows.map(rowToMessage);
616
+ }
617
+ if (format === "csv") {
618
+ const header = "conversation_id,message_id,seq,sender_did,schema,payload,ts_ms,direction";
619
+ const lines = messages.map(
620
+ (m) => [
621
+ m.conversation_id,
622
+ m.message_id,
623
+ m.seq ?? "",
624
+ m.sender_did,
625
+ m.schema,
626
+ JSON.stringify(m.payload),
627
+ m.ts_ms,
628
+ m.direction
629
+ ].map((v) => `"${String(v).replace(/"/g, '""')}"`).join(",")
630
+ );
631
+ return [header, ...lines].join("\n");
632
+ }
633
+ return JSON.stringify(messages, null, 2);
634
+ }
635
+ async syncFromServer(client, conversationId, opts) {
636
+ const sinceSeq = opts?.full ? 0 : this.getLastSyncedSeq(conversationId);
637
+ let totalSynced = 0;
638
+ let currentSeq = sinceSeq;
639
+ while (true) {
640
+ const res = await client.fetchInbox(conversationId, {
641
+ sinceSeq: currentSeq,
642
+ limit: 50
643
+ });
644
+ if (!res.ok || !res.data || res.data.messages.length === 0) break;
645
+ const messages = res.data.messages.map((msg) => ({
646
+ conversation_id: conversationId,
647
+ message_id: msg.message_id,
648
+ seq: msg.seq,
649
+ sender_did: msg.sender_did,
650
+ schema: msg.schema,
651
+ payload: msg.payload,
652
+ ts_ms: msg.ts_ms,
653
+ direction: "received"
654
+ }));
655
+ this.save(messages);
656
+ totalSynced += messages.length;
657
+ currentSeq = res.data.next_since_seq;
658
+ this.setLastSyncedSeq(conversationId, currentSeq);
659
+ if (!res.data.has_more) break;
660
+ }
661
+ return { synced: totalSynced };
662
+ }
663
+ async listMergedRecent(client, conversationId, opts) {
664
+ const limit = opts?.limit ?? 50;
665
+ const box = opts?.box ?? "ready";
666
+ const local = this.listRecent(conversationId, limit * 2);
667
+ const remoteRes = await client.fetchInbox(conversationId, { sinceSeq: 0, limit, box: box === "all" ? "ready" : box });
668
+ const remote = remoteRes.ok && remoteRes.data ? remoteRes.data.messages.map((msg) => ({
669
+ conversation_id: conversationId,
670
+ message_id: msg.message_id,
671
+ seq: msg.seq,
672
+ sender_did: msg.sender_did,
673
+ schema: msg.schema,
674
+ payload: msg.payload,
675
+ ts_ms: msg.ts_ms,
676
+ direction: msg.sender_did === client.getDid() ? "sent" : "received"
677
+ })) : [];
678
+ const byId = /* @__PURE__ */ new Map();
679
+ for (const msg of [...local, ...remote]) byId.set(msg.message_id, msg);
680
+ return Array.from(byId.values()).sort((a, b) => (a.seq ?? a.ts_ms) - (b.seq ?? b.ts_ms)).slice(-limit);
681
+ }
682
+ };
683
+
684
+ // src/session.ts
685
+ function rowToSession(row) {
686
+ return {
687
+ session_key: row.session_key,
688
+ remote_did: row.remote_did ?? void 0,
689
+ conversation_id: row.conversation_id ?? void 0,
690
+ trust_state: row.trust_state || "stranger",
691
+ last_message_preview: row.last_message_preview ?? void 0,
692
+ last_remote_activity_at: row.last_remote_activity_at ?? void 0,
693
+ last_read_seq: row.last_read_seq ?? 0,
694
+ unread_count: row.unread_count ?? 0,
695
+ active: row.active === 1,
696
+ updated_at: row.updated_at ?? 0
697
+ };
698
+ }
699
+ function previewFromPayload(payload) {
700
+ if (payload == null) return "";
701
+ if (typeof payload === "string") return payload.slice(0, 280);
702
+ if (typeof payload !== "object") return String(payload).slice(0, 280);
703
+ const value = payload;
704
+ const preferred = value.text ?? value.title ?? value.summary ?? value.message ?? value.description ?? value.error_message;
705
+ if (typeof preferred === "string") return preferred.slice(0, 280);
706
+ return JSON.stringify(payload).slice(0, 280);
707
+ }
708
+ function buildSessionKey(opts) {
709
+ const type = opts.conversationType ?? "";
710
+ if (type === "channel" || type === "group" || opts.conversationId.startsWith("c_grp_")) {
711
+ return `hook:im:conv:${opts.conversationId}`;
712
+ }
713
+ const remote = (opts.remoteDid ?? "").trim();
714
+ if (!remote) {
715
+ return `hook:im:conv:${opts.conversationId}`;
716
+ }
717
+ const local = (opts.localDid ?? "").trim();
718
+ if (!local) {
719
+ return `hook:im:peer:${remote}:conv:${opts.conversationId}`;
720
+ }
721
+ return `hook:im:did:${local}:peer:${remote}`;
722
+ }
723
+ var SessionManager = class {
724
+ constructor(store) {
725
+ this.store = store;
726
+ }
727
+ upsert(state) {
728
+ const now = state.updated_at ?? Date.now();
729
+ const existing = this.get(state.session_key);
730
+ const next = {
731
+ session_key: state.session_key,
732
+ remote_did: state.remote_did ?? existing?.remote_did,
733
+ conversation_id: state.conversation_id ?? existing?.conversation_id,
734
+ trust_state: state.trust_state ?? existing?.trust_state ?? "stranger",
735
+ last_message_preview: state.last_message_preview ?? existing?.last_message_preview,
736
+ last_remote_activity_at: state.last_remote_activity_at ?? existing?.last_remote_activity_at,
737
+ last_read_seq: state.last_read_seq ?? existing?.last_read_seq ?? 0,
738
+ unread_count: state.unread_count ?? existing?.unread_count ?? 0,
739
+ active: state.active ?? existing?.active ?? false,
740
+ updated_at: now
741
+ };
742
+ if (next.active) {
743
+ this.store.getDb().prepare("UPDATE session_state SET active = 0 WHERE session_key != ?").run(next.session_key);
744
+ }
745
+ this.store.getDb().prepare(`
746
+ INSERT INTO session_state (
747
+ session_key, remote_did, conversation_id, trust_state, last_message_preview,
748
+ last_remote_activity_at, last_read_seq, unread_count, active, updated_at
749
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
750
+ ON CONFLICT(session_key) DO UPDATE SET
751
+ remote_did = COALESCE(excluded.remote_did, session_state.remote_did),
752
+ conversation_id = COALESCE(excluded.conversation_id, session_state.conversation_id),
753
+ trust_state = excluded.trust_state,
754
+ last_message_preview = COALESCE(excluded.last_message_preview, session_state.last_message_preview),
755
+ last_remote_activity_at = COALESCE(excluded.last_remote_activity_at, session_state.last_remote_activity_at),
756
+ last_read_seq = excluded.last_read_seq,
757
+ unread_count = excluded.unread_count,
758
+ active = excluded.active,
759
+ updated_at = excluded.updated_at
760
+ `).run(
761
+ next.session_key,
762
+ next.remote_did ?? null,
763
+ next.conversation_id ?? null,
764
+ next.trust_state,
765
+ next.last_message_preview ?? null,
766
+ next.last_remote_activity_at ?? null,
767
+ next.last_read_seq,
768
+ next.unread_count,
769
+ next.active ? 1 : 0,
770
+ next.updated_at
771
+ );
772
+ return next;
773
+ }
774
+ upsertFromMessage(input) {
775
+ const sessionKey = input.session_key ?? buildSessionKey({
776
+ localDid: "",
777
+ remoteDid: input.remote_did ?? input.sender_did ?? "",
778
+ conversationId: input.conversation_id
779
+ });
780
+ const existing = this.get(sessionKey);
781
+ const preview = previewFromPayload(input.payload);
782
+ const isRemote = input.sender_is_self !== true;
783
+ const seq = input.seq ?? 0;
784
+ const lastReadSeq = existing?.last_read_seq ?? 0;
785
+ const unreadCount = isRemote && seq > lastReadSeq ? Math.max(existing?.unread_count ?? 0, seq - lastReadSeq) : existing?.unread_count ?? 0;
786
+ const activity = isRemote ? input.ts_ms ?? Date.now() : existing?.last_remote_activity_at;
787
+ return this.upsert({
788
+ session_key: sessionKey,
789
+ remote_did: input.remote_did ?? existing?.remote_did ?? (isRemote ? input.sender_did : void 0),
790
+ conversation_id: input.conversation_id,
791
+ trust_state: input.trust_state ?? existing?.trust_state ?? "stranger",
792
+ last_message_preview: preview || existing?.last_message_preview,
793
+ last_remote_activity_at: activity,
794
+ last_read_seq: existing?.last_read_seq ?? 0,
795
+ unread_count: unreadCount,
796
+ active: existing?.active ?? false,
797
+ updated_at: input.ts_ms ?? Date.now()
798
+ });
799
+ }
800
+ get(sessionKey) {
801
+ const row = this.store.getDb().prepare("SELECT * FROM session_state WHERE session_key = ?").get(sessionKey);
802
+ return row ? rowToSession(row) : null;
803
+ }
804
+ getByConversationId(conversationId) {
805
+ const row = this.store.getDb().prepare("SELECT * FROM session_state WHERE conversation_id = ? ORDER BY updated_at DESC LIMIT 1").get(conversationId);
806
+ return row ? rowToSession(row) : null;
807
+ }
808
+ getActiveSession() {
809
+ const row = this.store.getDb().prepare("SELECT * FROM session_state WHERE active = 1 ORDER BY updated_at DESC LIMIT 1").get();
810
+ return row ? rowToSession(row) : null;
811
+ }
812
+ listRecentSessions(limit = 20) {
813
+ 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);
814
+ return rows.map(rowToSession);
815
+ }
816
+ focusSession(sessionKey) {
817
+ const session = this.get(sessionKey);
818
+ if (!session) return null;
819
+ this.store.getDb().prepare("UPDATE session_state SET active = CASE WHEN session_key = ? THEN 1 ELSE 0 END").run(sessionKey);
820
+ return this.get(sessionKey);
821
+ }
822
+ markRead(sessionKey, seq) {
823
+ const session = this.get(sessionKey);
824
+ if (!session) return null;
825
+ const lastReadSeq = Math.max(session.last_read_seq, seq ?? session.last_read_seq);
826
+ return this.upsert({
827
+ session_key: sessionKey,
828
+ last_read_seq: lastReadSeq,
829
+ unread_count: 0,
830
+ active: session.active
831
+ });
832
+ }
833
+ nextUnread() {
834
+ 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();
835
+ return row ? rowToSession(row) : null;
836
+ }
837
+ resolveReplyTarget(sessionKey) {
838
+ const session = sessionKey ? this.get(sessionKey) : this.getActiveSession();
839
+ if (!session) return null;
840
+ return {
841
+ session_key: session.session_key,
842
+ remote_did: session.remote_did,
843
+ conversation_id: session.conversation_id,
844
+ trust_state: session.trust_state
845
+ };
846
+ }
847
+ };
848
+
849
+ // src/session-summaries.ts
850
+ function rowToSummary(row) {
851
+ return {
852
+ session_key: row.session_key,
853
+ objective: row.objective ?? void 0,
854
+ context: row.context ?? void 0,
855
+ constraints: row.constraints ?? void 0,
856
+ decisions: row.decisions ?? void 0,
857
+ open_questions: row.open_questions ?? void 0,
858
+ next_action: row.next_action ?? void 0,
859
+ handoff_ready_text: row.handoff_ready_text ?? void 0,
860
+ updated_at: row.updated_at
861
+ };
862
+ }
863
+ function cleanText(value) {
864
+ const text = String(value ?? "").trim();
865
+ return text ? text.slice(0, 8e3) : void 0;
866
+ }
867
+ function buildSessionSummaryHandoffText(summary) {
868
+ if (!summary) return "";
869
+ if (summary.handoff_ready_text) return summary.handoff_ready_text;
870
+ const parts = [
871
+ summary.objective ? `Objective: ${summary.objective}` : null,
872
+ summary.context ? `Context: ${summary.context}` : null,
873
+ summary.constraints ? `Constraints: ${summary.constraints}` : null,
874
+ summary.decisions ? `Decisions: ${summary.decisions}` : null,
875
+ summary.open_questions ? `Open questions: ${summary.open_questions}` : null,
876
+ summary.next_action ? `Next action: ${summary.next_action}` : null
877
+ ].filter(Boolean);
878
+ return parts.join("\n");
879
+ }
880
+ var SessionSummaryManager = class {
881
+ constructor(store) {
882
+ this.store = store;
883
+ }
884
+ upsert(input) {
885
+ const now = input.updated_at ?? Date.now();
886
+ const existing = this.get(input.session_key);
887
+ const next = {
888
+ session_key: input.session_key,
889
+ objective: cleanText(input.objective) ?? existing?.objective,
890
+ context: cleanText(input.context) ?? existing?.context,
891
+ constraints: cleanText(input.constraints) ?? existing?.constraints,
892
+ decisions: cleanText(input.decisions) ?? existing?.decisions,
893
+ open_questions: cleanText(input.open_questions) ?? existing?.open_questions,
894
+ next_action: cleanText(input.next_action) ?? existing?.next_action,
895
+ handoff_ready_text: cleanText(input.handoff_ready_text) ?? existing?.handoff_ready_text,
896
+ updated_at: now
897
+ };
898
+ this.store.getDb().prepare(`
899
+ INSERT INTO session_summaries (
900
+ session_key, objective, context, constraints, decisions, open_questions, next_action, handoff_ready_text, updated_at
901
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
902
+ ON CONFLICT(session_key) DO UPDATE SET
903
+ objective = excluded.objective,
904
+ context = excluded.context,
905
+ constraints = excluded.constraints,
906
+ decisions = excluded.decisions,
907
+ open_questions = excluded.open_questions,
908
+ next_action = excluded.next_action,
909
+ handoff_ready_text = excluded.handoff_ready_text,
910
+ updated_at = excluded.updated_at
911
+ `).run(
912
+ next.session_key,
913
+ next.objective ?? null,
914
+ next.context ?? null,
915
+ next.constraints ?? null,
916
+ next.decisions ?? null,
917
+ next.open_questions ?? null,
918
+ next.next_action ?? null,
919
+ next.handoff_ready_text ?? null,
920
+ next.updated_at
921
+ );
922
+ return next;
923
+ }
924
+ get(sessionKey) {
925
+ const row = this.store.getDb().prepare("SELECT * FROM session_summaries WHERE session_key = ?").get(sessionKey);
926
+ return row ? rowToSummary(row) : null;
927
+ }
928
+ listRecent(limit = 20) {
929
+ const rows = this.store.getDb().prepare("SELECT * FROM session_summaries ORDER BY updated_at DESC LIMIT ?").all(limit);
930
+ return rows.map(rowToSummary);
931
+ }
932
+ };
933
+
934
+ // src/task-threads.ts
935
+ function rowToThread(row) {
936
+ return {
937
+ task_id: row.task_id,
938
+ session_key: row.session_key,
939
+ conversation_id: row.conversation_id,
940
+ title: row.title ?? void 0,
941
+ status: row.status,
942
+ started_at: row.started_at ?? void 0,
943
+ updated_at: row.updated_at,
944
+ result_summary: row.result_summary ?? void 0,
945
+ error_code: row.error_code ?? void 0,
946
+ error_message: row.error_message ?? void 0
947
+ };
948
+ }
949
+ var TaskThreadManager = class {
950
+ constructor(store) {
951
+ this.store = store;
952
+ }
953
+ upsert(thread) {
954
+ const updatedAt = thread.updated_at ?? Date.now();
955
+ const existing = this.get(thread.task_id);
956
+ this.store.getDb().prepare(`
957
+ INSERT INTO task_threads (
958
+ task_id, session_key, conversation_id, title, status, started_at, updated_at, result_summary, error_code, error_message
959
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
960
+ ON CONFLICT(task_id) DO UPDATE SET
961
+ session_key = excluded.session_key,
962
+ conversation_id = excluded.conversation_id,
963
+ title = COALESCE(excluded.title, task_threads.title),
964
+ status = excluded.status,
965
+ started_at = COALESCE(excluded.started_at, task_threads.started_at),
966
+ updated_at = excluded.updated_at,
967
+ result_summary = COALESCE(excluded.result_summary, task_threads.result_summary),
968
+ error_code = COALESCE(excluded.error_code, task_threads.error_code),
969
+ error_message = COALESCE(excluded.error_message, task_threads.error_message)
970
+ `).run(
971
+ thread.task_id,
972
+ thread.session_key,
973
+ thread.conversation_id,
974
+ thread.title ?? null,
975
+ thread.status,
976
+ thread.started_at ?? existing?.started_at ?? updatedAt,
977
+ updatedAt,
978
+ thread.result_summary ?? null,
979
+ thread.error_code ?? null,
980
+ thread.error_message ?? null
981
+ );
982
+ return this.get(thread.task_id);
983
+ }
984
+ get(taskId) {
985
+ const row = this.store.getDb().prepare("SELECT * FROM task_threads WHERE task_id = ?").get(taskId);
986
+ return row ? rowToThread(row) : null;
987
+ }
988
+ listBySession(sessionKey, limit = 20) {
989
+ const rows = this.store.getDb().prepare("SELECT * FROM task_threads WHERE session_key = ? ORDER BY updated_at DESC LIMIT ?").all(sessionKey, limit);
990
+ return rows.map(rowToThread);
991
+ }
992
+ listByConversation(conversationId, limit = 20) {
993
+ const rows = this.store.getDb().prepare("SELECT * FROM task_threads WHERE conversation_id = ? ORDER BY updated_at DESC LIMIT ?").all(conversationId, limit);
994
+ return rows.map(rowToThread);
995
+ }
996
+ listRecent(limit = 20) {
997
+ const rows = this.store.getDb().prepare("SELECT * FROM task_threads ORDER BY updated_at DESC LIMIT ?").all(limit);
998
+ return rows.map(rowToThread);
999
+ }
1000
+ };
1001
+
1002
+ // src/task-handoffs.ts
1003
+ function cleanText2(value) {
1004
+ const text = String(value ?? "").trim();
1005
+ return text ? text.slice(0, 8e3) : void 0;
1006
+ }
1007
+ function rowToHandoff(row) {
1008
+ return {
1009
+ task_id: row.task_id,
1010
+ session_key: row.session_key,
1011
+ conversation_id: row.conversation_id,
1012
+ objective: row.objective ?? void 0,
1013
+ carry_forward_summary: row.carry_forward_summary ?? void 0,
1014
+ success_criteria: row.success_criteria ?? void 0,
1015
+ callback_session_key: row.callback_session_key ?? void 0,
1016
+ priority: row.priority ?? void 0,
1017
+ delegated_by: row.delegated_by ?? void 0,
1018
+ delegated_to: row.delegated_to ?? void 0,
1019
+ updated_at: row.updated_at
1020
+ };
1021
+ }
1022
+ var TaskHandoffManager = class {
1023
+ constructor(store) {
1024
+ this.store = store;
1025
+ }
1026
+ upsert(input) {
1027
+ const now = input.updated_at ?? Date.now();
1028
+ const existing = this.get(input.task_id);
1029
+ const next = {
1030
+ task_id: input.task_id,
1031
+ session_key: input.session_key,
1032
+ conversation_id: input.conversation_id,
1033
+ objective: cleanText2(input.objective) ?? existing?.objective,
1034
+ carry_forward_summary: cleanText2(input.carry_forward_summary) ?? existing?.carry_forward_summary,
1035
+ success_criteria: cleanText2(input.success_criteria) ?? existing?.success_criteria,
1036
+ callback_session_key: cleanText2(input.callback_session_key) ?? existing?.callback_session_key,
1037
+ priority: cleanText2(input.priority) ?? existing?.priority,
1038
+ delegated_by: cleanText2(input.delegated_by) ?? existing?.delegated_by,
1039
+ delegated_to: cleanText2(input.delegated_to) ?? existing?.delegated_to,
1040
+ updated_at: now
1041
+ };
1042
+ this.store.getDb().prepare(`
1043
+ INSERT INTO task_handoffs (
1044
+ task_id, session_key, conversation_id, objective, carry_forward_summary, success_criteria,
1045
+ callback_session_key, priority, delegated_by, delegated_to, updated_at
1046
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1047
+ ON CONFLICT(task_id) DO UPDATE SET
1048
+ session_key = excluded.session_key,
1049
+ conversation_id = excluded.conversation_id,
1050
+ objective = excluded.objective,
1051
+ carry_forward_summary = excluded.carry_forward_summary,
1052
+ success_criteria = excluded.success_criteria,
1053
+ callback_session_key = excluded.callback_session_key,
1054
+ priority = excluded.priority,
1055
+ delegated_by = excluded.delegated_by,
1056
+ delegated_to = excluded.delegated_to,
1057
+ updated_at = excluded.updated_at
1058
+ `).run(
1059
+ next.task_id,
1060
+ next.session_key,
1061
+ next.conversation_id,
1062
+ next.objective ?? null,
1063
+ next.carry_forward_summary ?? null,
1064
+ next.success_criteria ?? null,
1065
+ next.callback_session_key ?? null,
1066
+ next.priority ?? null,
1067
+ next.delegated_by ?? null,
1068
+ next.delegated_to ?? null,
1069
+ next.updated_at
1070
+ );
1071
+ return next;
1072
+ }
1073
+ get(taskId) {
1074
+ const row = this.store.getDb().prepare("SELECT * FROM task_handoffs WHERE task_id = ?").get(taskId);
1075
+ return row ? rowToHandoff(row) : null;
1076
+ }
1077
+ listBySession(sessionKey, limit = 20) {
1078
+ const rows = this.store.getDb().prepare("SELECT * FROM task_handoffs WHERE session_key = ? ORDER BY updated_at DESC LIMIT ?").all(sessionKey, limit);
1079
+ return rows.map(rowToHandoff);
1080
+ }
1081
+ };
1082
+
1083
+ // src/capability-card.ts
1084
+ function normalizeStringList(value) {
1085
+ if (!Array.isArray(value)) return void 0;
1086
+ const list = value.map((item) => String(item ?? "").trim()).filter(Boolean).slice(0, 32);
1087
+ return list.length ? list : void 0;
1088
+ }
1089
+ function normalizeCapabilityCardItem(value) {
1090
+ if (!value || typeof value !== "object") return null;
1091
+ const source = value;
1092
+ const id = String(source.id ?? "").trim();
1093
+ if (!id) return null;
1094
+ const label = String(source.label ?? "").trim() || void 0;
1095
+ const description = String(source.description ?? "").trim() || void 0;
1096
+ const acceptsTasks = typeof source.accepts_tasks === "boolean" ? source.accepts_tasks : void 0;
1097
+ const acceptsMessages = typeof source.accepts_messages === "boolean" ? source.accepts_messages : void 0;
1098
+ return {
1099
+ id,
1100
+ label,
1101
+ description,
1102
+ accepts_tasks: acceptsTasks,
1103
+ accepts_messages: acceptsMessages,
1104
+ input_modes: normalizeStringList(source.input_modes),
1105
+ output_modes: normalizeStringList(source.output_modes),
1106
+ examples: normalizeStringList(source.examples)
1107
+ };
1108
+ }
1109
+ function normalizeCapabilityCard(value) {
1110
+ if (!value || typeof value !== "object") return void 0;
1111
+ const source = value;
1112
+ const preferred = String(source.preferred_contact_mode ?? "").trim();
1113
+ const capabilities = Array.isArray(source.capabilities) ? source.capabilities.map(normalizeCapabilityCardItem).filter(Boolean) : [];
1114
+ return {
1115
+ version: String(source.version ?? "1").trim() || "1",
1116
+ summary: String(source.summary ?? "").trim() || void 0,
1117
+ accepts_new_work: typeof source.accepts_new_work === "boolean" ? source.accepts_new_work : void 0,
1118
+ preferred_contact_mode: preferred === "dm" || preferred === "task" || preferred === "either" ? preferred : void 0,
1119
+ capabilities
1120
+ };
1121
+ }
1122
+ function capabilityCardToLegacyCapabilities(card) {
1123
+ if (!card?.capabilities?.length) return [];
1124
+ return card.capabilities.map((item) => item.label || item.id).map((item) => String(item ?? "").trim()).filter(Boolean).slice(0, 24);
1125
+ }
1126
+ function formatCapabilityCardSummary(card) {
1127
+ if (!card) return "(none)";
1128
+ const parts = [];
1129
+ if (card.summary) parts.push(card.summary);
1130
+ if (card.preferred_contact_mode) parts.push(`preferred_contact_mode=${card.preferred_contact_mode}`);
1131
+ if (typeof card.accepts_new_work === "boolean") parts.push(`accepts_new_work=${card.accepts_new_work}`);
1132
+ if (card.capabilities?.length) {
1133
+ parts.push(`capabilities=${card.capabilities.map((item) => item.label || item.id).join(", ")}`);
1134
+ }
1135
+ return parts.join(" | ") || "(none)";
1136
+ }
1137
+
1138
+ // src/e2ee.ts
1139
+ import { webcrypto } from "crypto";
1140
+ import { SCHEMA_CONTACT_REQUEST, SCHEMA_RESULT, SCHEMA_TASK, SCHEMA_TEXT } from "@pingagent/schemas";
1141
+ var subtle = webcrypto.subtle;
1142
+ var encoder = new TextEncoder();
1143
+ var decoder = new TextDecoder();
1144
+ function bytesToBase64Url(bytes) {
1145
+ return Buffer.from(bytes).toString("base64url");
1146
+ }
1147
+ function base64UrlToBytes(value) {
1148
+ return new Uint8Array(Buffer.from(value, "base64url"));
1149
+ }
1150
+ function isObject(value) {
1151
+ return value != null && typeof value === "object" && !Array.isArray(value);
1152
+ }
1153
+ async function importEncryptionPublicKey(jwk) {
1154
+ return subtle.importKey(
1155
+ "jwk",
1156
+ { ...jwk, ext: true },
1157
+ { name: "ECDH", namedCurve: "P-256" },
1158
+ false,
1159
+ []
1160
+ );
1161
+ }
1162
+ async function importEncryptionPrivateKey(jwk) {
1163
+ return subtle.importKey(
1164
+ "jwk",
1165
+ { ...jwk, ext: true, key_ops: ["deriveKey"] },
1166
+ { name: "ECDH", namedCurve: "P-256" },
1167
+ false,
1168
+ ["deriveKey"]
1169
+ );
1170
+ }
1171
+ function splitPayloadForEncryption(schema, payload) {
1172
+ if (schema === SCHEMA_TASK) {
1173
+ const {
1174
+ task_id,
1175
+ idempotency_key,
1176
+ expected_output_schema,
1177
+ timeout_ms,
1178
+ ...protectedPayload
1179
+ } = payload;
1180
+ return {
1181
+ cleartext: {
1182
+ ...task_id ? { task_id } : {},
1183
+ ...idempotency_key ? { idempotency_key } : {},
1184
+ ...expected_output_schema ? { expected_output_schema } : {},
1185
+ ...timeout_ms ? { timeout_ms } : {}
1186
+ },
1187
+ protectedPayload
1188
+ };
1189
+ }
1190
+ if (schema === SCHEMA_RESULT) {
1191
+ const { task_id, status, elapsed_ms, ...protectedPayload } = payload;
1192
+ return {
1193
+ cleartext: {
1194
+ ...task_id ? { task_id } : {},
1195
+ ...status ? { status } : {},
1196
+ ...elapsed_ms != null ? { elapsed_ms } : {}
1197
+ },
1198
+ protectedPayload
1199
+ };
1200
+ }
1201
+ if (schema === SCHEMA_TEXT || schema === SCHEMA_CONTACT_REQUEST) {
1202
+ return { cleartext: {}, protectedPayload: payload };
1203
+ }
1204
+ return { cleartext: payload, protectedPayload: {} };
1205
+ }
1206
+ function mergePayloadFromWrapper(wrapper, decryptedProtectedPayload) {
1207
+ return {
1208
+ ...wrapper.__e2ee.cleartext,
1209
+ ...decryptedProtectedPayload
1210
+ };
1211
+ }
1212
+ function isEncryptedPayload(payload) {
1213
+ return isObject(payload) && isObject(payload.__e2ee) && Array.isArray(payload.__e2ee.recipients) && isObject(payload.__e2ee.cleartext);
1214
+ }
1215
+ function shouldEncryptConversationPayload(conversationId, schema) {
1216
+ if (!(conversationId.startsWith("c_dm_") || conversationId.startsWith("c_pdm_"))) return false;
1217
+ return schema === SCHEMA_TEXT || schema === SCHEMA_CONTACT_REQUEST || schema === SCHEMA_TASK || schema === SCHEMA_RESULT;
1218
+ }
1219
+ async function encryptPayloadForRecipients(opts) {
1220
+ const { cleartext, protectedPayload } = splitPayloadForEncryption(opts.schema, opts.payload);
1221
+ const recipientBlobs = [];
1222
+ const plaintextBytes = encoder.encode(JSON.stringify(protectedPayload));
1223
+ const uniqueRecipients = /* @__PURE__ */ new Map();
1224
+ for (const recipient of opts.recipients) {
1225
+ uniqueRecipients.set(recipient.did, recipient);
1226
+ }
1227
+ for (const recipient of uniqueRecipients.values()) {
1228
+ if (!recipient.encryption_public_key) {
1229
+ throw new Error(`Recipient ${recipient.did} has no registered encryption public key`);
1230
+ }
1231
+ const ephemeral = await subtle.generateKey(
1232
+ { name: "ECDH", namedCurve: "P-256" },
1233
+ true,
1234
+ ["deriveKey"]
1235
+ );
1236
+ const recipientPublicKey = await importEncryptionPublicKey(recipient.encryption_public_key);
1237
+ const contentKey = await subtle.deriveKey(
1238
+ { name: "ECDH", public: recipientPublicKey },
1239
+ ephemeral.privateKey,
1240
+ { name: "AES-GCM", length: 256 },
1241
+ false,
1242
+ ["encrypt"]
1243
+ );
1244
+ const iv = webcrypto.getRandomValues(new Uint8Array(12));
1245
+ const ciphertext = await subtle.encrypt(
1246
+ { name: "AES-GCM", iv },
1247
+ contentKey,
1248
+ plaintextBytes
1249
+ );
1250
+ const ephemeralPublicKey = await subtle.exportKey("jwk", ephemeral.publicKey);
1251
+ recipientBlobs.push({
1252
+ did: recipient.did,
1253
+ alg: "ECDH-P256+A256GCM",
1254
+ ephemeral_public_key: {
1255
+ kty: "EC",
1256
+ crv: "P-256",
1257
+ x: ephemeralPublicKey.x,
1258
+ y: ephemeralPublicKey.y
1259
+ },
1260
+ iv: bytesToBase64Url(iv),
1261
+ ciphertext: bytesToBase64Url(new Uint8Array(ciphertext))
1262
+ });
1263
+ }
1264
+ return {
1265
+ __e2ee: {
1266
+ v: 1,
1267
+ alg: "ECDH-P256+A256GCM",
1268
+ recipients: recipientBlobs,
1269
+ cleartext
1270
+ }
1271
+ };
1272
+ }
1273
+ async function decryptPayloadForIdentity(schema, payload, identity) {
1274
+ if (!isEncryptedPayload(payload)) return payload;
1275
+ if (!identity.encryptionPrivateKeyJwk) return payload;
1276
+ const recipientBlob = payload.__e2ee.recipients.find((recipient) => recipient.did === identity.did);
1277
+ if (!recipientBlob) return payload;
1278
+ const privateKey = await importEncryptionPrivateKey(identity.encryptionPrivateKeyJwk);
1279
+ const ephemeralPublicKey = await importEncryptionPublicKey(recipientBlob.ephemeral_public_key);
1280
+ const contentKey = await subtle.deriveKey(
1281
+ { name: "ECDH", public: ephemeralPublicKey },
1282
+ privateKey,
1283
+ { name: "AES-GCM", length: 256 },
1284
+ false,
1285
+ ["decrypt"]
1286
+ );
1287
+ const plaintext = await subtle.decrypt(
1288
+ { name: "AES-GCM", iv: base64UrlToBytes(recipientBlob.iv) },
1289
+ contentKey,
1290
+ base64UrlToBytes(recipientBlob.ciphertext)
1291
+ );
1292
+ const decryptedProtectedPayload = JSON.parse(decoder.decode(plaintext));
1293
+ return mergePayloadFromWrapper(payload, decryptedProtectedPayload);
1294
+ }
1295
+
1296
+ // src/client.ts
1297
+ var PingAgentClient = class {
1298
+ constructor(opts) {
1299
+ this.opts = opts;
1300
+ this.identity = Object.assign(opts.identity, ensureIdentityEncryptionKeys(opts.identity));
1301
+ this.transport = new HttpTransport({
1302
+ serverUrl: opts.serverUrl,
1303
+ accessToken: opts.accessToken,
1304
+ onTokenRefreshed: opts.onTokenRefreshed
1305
+ });
1306
+ if (opts.store) {
1307
+ this.contactManager = new ContactManager(opts.store);
1308
+ this.historyManager = new HistoryManager(opts.store);
1309
+ this.sessionManager = new SessionManager(opts.store);
1310
+ this.sessionSummaryManager = new SessionSummaryManager(opts.store);
1311
+ this.taskThreadManager = new TaskThreadManager(opts.store);
1312
+ this.taskHandoffManager = new TaskHandoffManager(opts.store);
1313
+ }
1314
+ }
1315
+ transport;
1316
+ identity;
1317
+ contactManager;
1318
+ historyManager;
1319
+ sessionManager;
1320
+ sessionSummaryManager;
1321
+ taskThreadManager;
1322
+ taskHandoffManager;
1323
+ agentCardCache = /* @__PURE__ */ new Map();
1324
+ getContactManager() {
1325
+ return this.contactManager;
1326
+ }
1327
+ getHistoryManager() {
1328
+ return this.historyManager;
1329
+ }
1330
+ getSessionManager() {
1331
+ return this.sessionManager;
1332
+ }
1333
+ getSessionSummaryManager() {
1334
+ return this.sessionSummaryManager;
1335
+ }
1336
+ getTaskThreadManager() {
1337
+ return this.taskThreadManager;
1338
+ }
1339
+ getTaskHandoffManager() {
1340
+ return this.taskHandoffManager;
1341
+ }
1342
+ /** Update the in-memory access token (e.g. after proactive refresh from disk). */
1343
+ setAccessToken(token) {
1344
+ this.transport.setToken(token);
1345
+ }
1346
+ async register(developerToken) {
1347
+ let binary = "";
1348
+ for (const b of this.identity.publicKey) binary += String.fromCharCode(b);
1349
+ const publicKeyBase64 = btoa(binary);
1350
+ return this.transport.request("POST", "/v1/agent/register", {
1351
+ device_id: this.identity.deviceId,
1352
+ public_key: publicKeyBase64,
1353
+ encryption_public_key: this.identity.encryptionPublicKeyJwk,
1354
+ developer_token: developerToken
1355
+ }, true);
1356
+ }
1357
+ async openConversation(targetDid) {
1358
+ const res = await this.transport.request("POST", "/v1/conversations/open", {
1359
+ targets: [targetDid]
1360
+ });
1361
+ if (res.ok && res.data?.recipient_encryption_public_key) {
1362
+ this.agentCardCache.set(targetDid, {
1363
+ did: targetDid,
1364
+ encryption_public_key: res.data.recipient_encryption_public_key
1365
+ });
1366
+ }
1367
+ return res;
1368
+ }
1369
+ async resolveConversationPeer(conversationId) {
1370
+ const fromSession = this.sessionManager?.getByConversationId(conversationId)?.remote_did;
1371
+ if (fromSession) return fromSession;
1372
+ const convList = await this.listConversations({ type: "dm" });
1373
+ if (!convList.ok || !convList.data) return null;
1374
+ return convList.data.conversations.find((conv) => conv.conversation_id === conversationId)?.target_did ?? null;
1375
+ }
1376
+ async getRecipientEncryptionCard(did) {
1377
+ if (did === this.identity.did) {
1378
+ return {
1379
+ did,
1380
+ encryption_public_key: this.identity.encryptionPublicKeyJwk
1381
+ };
1382
+ }
1383
+ const cached = this.agentCardCache.get(did);
1384
+ if (cached?.encryption_public_key) return cached;
1385
+ const cardRes = await this.getAgentCard(did);
1386
+ if (!cardRes.ok || !cardRes.data?.encryption_public_key) {
1387
+ throw new Error(`Recipient ${did} has no registered encryption key`);
1388
+ }
1389
+ const card = {
1390
+ did,
1391
+ encryption_public_key: cardRes.data.encryption_public_key
1392
+ };
1393
+ this.agentCardCache.set(did, card);
1394
+ return card;
1395
+ }
1396
+ sameEncryptionPublicKey(left, right) {
1397
+ if (!left || !right) return false;
1398
+ return left.kty === right.kty && left.crv === right.crv && left.x === right.x && left.y === right.y;
1399
+ }
1400
+ async sendMessage(conversationId, schema, payload) {
1401
+ const ttlMs = schema === SCHEMA_TEXT2 ? 6048e5 : void 0;
1402
+ let payloadForTransport = payload;
1403
+ if (shouldEncryptConversationPayload(conversationId, schema)) {
1404
+ try {
1405
+ const remoteDid = await this.resolveConversationPeer(conversationId);
1406
+ if (!remoteDid) {
1407
+ return {
1408
+ ok: false,
1409
+ error: { code: ErrorCode2.INTERNAL, message: `Cannot determine peer DID for encrypted conversation ${conversationId}`, hint: "List conversations again or reopen the conversation before sending." }
1410
+ };
1411
+ }
1412
+ const recipient = await this.getRecipientEncryptionCard(remoteDid);
1413
+ payloadForTransport = await encryptPayloadForRecipients({
1414
+ schema,
1415
+ payload,
1416
+ recipients: [
1417
+ recipient,
1418
+ {
1419
+ did: this.identity.did,
1420
+ encryption_public_key: this.identity.encryptionPublicKeyJwk
1421
+ }
1422
+ ]
1423
+ });
1424
+ } catch (error) {
1425
+ return {
1426
+ ok: false,
1427
+ error: {
1428
+ code: ErrorCode2.INTERNAL,
1429
+ message: error?.message ?? "Failed to encrypt message payload",
1430
+ hint: "Both sides must register encryption keys before direct messages can be sent end-to-end encrypted."
1431
+ }
1432
+ };
1433
+ }
1434
+ }
1435
+ const unsigned = buildUnsignedEnvelope({
1436
+ type: "message",
1437
+ conversationId,
1438
+ senderDid: this.identity.did,
1439
+ senderDeviceId: this.identity.deviceId,
1440
+ schema,
1441
+ payload: payloadForTransport,
1442
+ ttlMs
1443
+ });
1444
+ const signed = signEnvelope(unsigned, this.identity.privateKey);
1445
+ const res = await this.transport.request("POST", "/v1/messages/send", signed);
1446
+ if (res.ok && this.historyManager) {
1447
+ this.historyManager.save([{
1448
+ conversation_id: conversationId,
1449
+ message_id: signed.message_id,
1450
+ seq: res.data?.seq,
1451
+ sender_did: this.identity.did,
1452
+ schema,
1453
+ payload,
1454
+ ts_ms: signed.ts_ms,
1455
+ direction: "sent"
1456
+ }]);
1457
+ this.sessionManager?.upsertFromMessage({
1458
+ session_key: this.sessionManager.getByConversationId(conversationId)?.session_key,
1459
+ remote_did: this.sessionManager.getByConversationId(conversationId)?.remote_did,
1460
+ conversation_id: conversationId,
1461
+ trust_state: this.sessionManager.getByConversationId(conversationId)?.trust_state ?? "trusted",
1462
+ sender_did: this.identity.did,
1463
+ sender_is_self: true,
1464
+ schema,
1465
+ payload,
1466
+ seq: res.data?.seq,
1467
+ ts_ms: signed.ts_ms
1468
+ });
1469
+ }
1470
+ return res;
1471
+ }
1472
+ async sendTask(conversationId, task) {
1473
+ return this.sendMessage(conversationId, SCHEMA_TASK2, {
1474
+ ...task,
1475
+ idempotency_key: task.task_id,
1476
+ expected_output_schema: SCHEMA_RESULT2
1477
+ });
1478
+ }
1479
+ async sendContactRequest(conversationId, message) {
1480
+ const { v7: uuidv7 } = await import("uuid");
1481
+ return this.sendMessage(conversationId, SCHEMA_CONTACT_REQUEST2, {
1482
+ request_id: `r_${uuidv7()}`,
1483
+ from_did: this.identity.did,
1484
+ to_did: "",
1485
+ capabilities: ["task", "result", "files"],
1486
+ message,
1487
+ expires_ms: 864e5
1488
+ });
1489
+ }
1490
+ async fetchInbox(conversationId, opts) {
1491
+ const params = new URLSearchParams({
1492
+ conversation_id: conversationId,
1493
+ since_seq: String(opts?.sinceSeq ?? 0),
1494
+ limit: String(opts?.limit ?? 50),
1495
+ box: opts?.box ?? "ready"
1496
+ });
1497
+ const res = await this.transport.request("GET", `/v1/inbox/fetch?${params}`);
1498
+ if (res.ok && res.data && this.historyManager) {
1499
+ const decryptedMessages = await Promise.all(res.data.messages.map(async (msg) => ({
1500
+ ...msg,
1501
+ payload: await decryptPayloadForIdentity(msg.schema, msg.payload ?? {}, this.identity).catch(() => msg.payload ?? {})
1502
+ })));
1503
+ res.data.messages = decryptedMessages;
1504
+ const msgs = decryptedMessages.map((msg) => ({
1505
+ conversation_id: conversationId,
1506
+ message_id: msg.message_id,
1507
+ seq: msg.seq,
1508
+ sender_did: msg.sender_did,
1509
+ schema: msg.schema,
1510
+ payload: msg.payload,
1511
+ ts_ms: msg.ts_ms,
1512
+ direction: msg.sender_did === this.identity.did ? "sent" : "received"
1513
+ }));
1514
+ if (msgs.length > 0) {
1515
+ this.historyManager.save(msgs);
1516
+ const maxSeq = Math.max(...msgs.map((m) => m.seq ?? 0));
1517
+ if (maxSeq > 0) this.historyManager.setLastSyncedSeq(conversationId, maxSeq);
1518
+ }
1519
+ for (const msg of decryptedMessages) {
1520
+ const existingSession = this.sessionManager?.getByConversationId(conversationId);
1521
+ this.sessionManager?.upsertFromMessage({
1522
+ session_key: existingSession?.session_key,
1523
+ remote_did: existingSession?.remote_did ?? (msg.sender_did !== this.identity.did ? msg.sender_did : void 0),
1524
+ conversation_id: conversationId,
1525
+ trust_state: existingSession?.trust_state ?? (opts?.box === "strangers" ? "pending" : "trusted"),
1526
+ sender_did: msg.sender_did,
1527
+ sender_is_self: msg.sender_did === this.identity.did,
1528
+ schema: msg.schema,
1529
+ payload: msg.payload,
1530
+ seq: msg.seq,
1531
+ ts_ms: msg.ts_ms
1532
+ });
1533
+ if (msg.schema === SCHEMA_RESULT2 && msg.payload?.task_id) {
1534
+ const session = this.sessionManager?.getByConversationId(conversationId);
1535
+ this.taskThreadManager?.upsert({
1536
+ task_id: msg.payload.task_id,
1537
+ session_key: session?.session_key ?? buildSessionKey({ localDid: this.identity.did, conversationId, remoteDid: session?.remote_did }),
1538
+ conversation_id: conversationId,
1539
+ status: msg.payload.status === "ok" ? "processed" : "failed",
1540
+ updated_at: msg.ts_ms ?? Date.now(),
1541
+ result_summary: msg.payload?.output?.summary,
1542
+ error_code: msg.payload?.error?.code,
1543
+ error_message: msg.payload?.error?.message
1544
+ });
1545
+ }
1546
+ }
1547
+ }
1548
+ return res;
1549
+ }
1550
+ async ack(conversationId, forMessageId, status, opts) {
1551
+ return this.transport.request("POST", "/v1/receipts/ack", {
1552
+ conversation_id: conversationId,
1553
+ for_message_id: forMessageId,
1554
+ for_task_id: opts?.forTaskId,
1555
+ status,
1556
+ reason: opts?.reason,
1557
+ detail: opts?.detail
1558
+ });
1559
+ }
1560
+ async approveContact(conversationId) {
1561
+ const res = await this.transport.request("POST", "/v1/control/approve_contact", {
1562
+ conversation_id: conversationId
1563
+ });
1564
+ if (res.ok && this.contactManager) {
1565
+ const pendingMessages = this.historyManager?.list(conversationId, { limit: 1 });
1566
+ const senderDid = pendingMessages?.[0]?.sender_did;
1567
+ if (senderDid && senderDid !== this.identity.did) {
1568
+ this.contactManager.add({
1569
+ did: senderDid,
1570
+ conversation_id: res.data?.dm_conversation_id ?? conversationId,
1571
+ trusted: true
1572
+ });
1573
+ }
1574
+ }
1575
+ if (res.ok) {
1576
+ const existing = this.sessionManager?.getByConversationId(conversationId);
1577
+ if (existing) {
1578
+ this.sessionManager?.upsert({
1579
+ session_key: existing.session_key,
1580
+ conversation_id: res.data?.dm_conversation_id ?? conversationId,
1581
+ trust_state: "trusted",
1582
+ remote_did: existing.remote_did,
1583
+ active: existing.active
1584
+ });
1585
+ }
1586
+ }
1587
+ return res;
1588
+ }
1589
+ async revokeConversation(conversationId) {
1590
+ return this.transport.request("POST", "/v1/control/revoke_conversation", {
1591
+ conversation_id: conversationId
1592
+ });
1593
+ }
1594
+ async cancelTask(conversationId, taskId) {
1595
+ const res = await this.transport.request("POST", "/v1/control/cancel_task", {
1596
+ conversation_id: conversationId,
1597
+ task_id: taskId
1598
+ });
1599
+ if (res.ok && res.data) {
1600
+ const session = this.sessionManager?.getByConversationId(conversationId);
1601
+ this.taskThreadManager?.upsert({
1602
+ task_id: taskId,
1603
+ session_key: session?.session_key ?? buildSessionKey({ localDid: this.identity.did, conversationId, remoteDid: session?.remote_did }),
1604
+ conversation_id: conversationId,
1605
+ status: normalizeTaskThreadStatus(res.data.task_state),
1606
+ updated_at: Date.now()
1607
+ });
1608
+ }
1609
+ return res;
1610
+ }
1611
+ async blockSender(conversationId, senderDid) {
1612
+ return this.transport.request("POST", "/v1/control/block_sender", {
1613
+ conversation_id: conversationId,
1614
+ sender_did: senderDid
1615
+ });
1616
+ }
1617
+ async acquireLease(conversationId) {
1618
+ return this.transport.request("POST", "/v1/lease/acquire", {
1619
+ conversation_id: conversationId
1620
+ });
1621
+ }
1622
+ async renewLease(conversationId) {
1623
+ return this.transport.request("POST", "/v1/lease/renew", {
1624
+ conversation_id: conversationId
1625
+ });
1626
+ }
1627
+ async releaseLease(conversationId) {
1628
+ return this.transport.request("POST", "/v1/lease/release", {
1629
+ conversation_id: conversationId
1630
+ });
1631
+ }
1632
+ async uploadArtifact(content) {
1633
+ const presignRes = await this.transport.request("POST", "/v1/artifacts/presign_upload", {
1634
+ size: content.length,
1635
+ content_type: "application/octet-stream"
1636
+ });
1637
+ if (!presignRes.ok || !presignRes.data) throw new Error("Failed to presign upload");
1638
+ const { upload_url, artifact_ref } = presignRes.data;
1639
+ await this.transport.fetchWithAuth(upload_url, {
1640
+ method: "PUT",
1641
+ body: content,
1642
+ contentType: "application/octet-stream"
1643
+ });
1644
+ const { createHash } = await import("crypto");
1645
+ const hash = createHash("sha256").update(content).digest("hex");
1646
+ return { artifact_ref, sha256: hash, size: content.length };
1647
+ }
1648
+ async downloadArtifact(artifactRef, expectedSha256, expectedSize) {
1649
+ const presignRes = await this.transport.request("POST", "/v1/artifacts/presign_download", {
1650
+ artifact_ref: artifactRef
1651
+ });
1652
+ if (!presignRes.ok || !presignRes.data) throw new Error("Failed to presign download");
1653
+ const buffer = Buffer.from(await this.transport.fetchWithAuth(presignRes.data.download_url));
1654
+ if (buffer.length !== expectedSize) {
1655
+ throw new Error(`Size mismatch: expected ${expectedSize}, got ${buffer.length}`);
1656
+ }
1657
+ const { createHash } = await import("crypto");
1658
+ const hash = createHash("sha256").update(buffer).digest("hex");
1659
+ if (hash !== expectedSha256) {
1660
+ throw new Error(`SHA256 mismatch: expected ${expectedSha256}, got ${hash}`);
1661
+ }
1662
+ return buffer;
1663
+ }
1664
+ async getSubscription() {
1665
+ return this.transport.request("GET", "/v1/subscription");
1666
+ }
1667
+ async resolveAlias(alias) {
1668
+ const res = await this.transport.request("GET", `/v1/directory/resolve?alias=${encodeURIComponent(alias)}`);
1669
+ if (res.ok && res.data?.did && res.data.encryption_public_key) {
1670
+ this.agentCardCache.set(res.data.did, {
1671
+ did: res.data.did,
1672
+ encryption_public_key: res.data.encryption_public_key
1673
+ });
1674
+ }
1675
+ return res;
1676
+ }
1677
+ async getAgentCard(did) {
1678
+ const res = await this.transport.request("GET", `/v1/directory/card?did=${encodeURIComponent(did)}`, void 0, true);
1679
+ if (res.ok && res.data?.encryption_public_key) {
1680
+ this.agentCardCache.set(did, {
1681
+ did,
1682
+ encryption_public_key: res.data.encryption_public_key
1683
+ });
1684
+ }
1685
+ return res;
1686
+ }
1687
+ async registerAlias(alias) {
1688
+ return this.transport.request("POST", "/v1/directory/alias", { alias });
1689
+ }
1690
+ async listConversations(opts) {
1691
+ const params = new URLSearchParams();
1692
+ if (opts?.type) params.set("type", opts.type);
1693
+ const qs = params.toString();
1694
+ const res = await this.transport.request("GET", `/v1/conversations/list${qs ? "?" + qs : ""}`);
1695
+ if (res.ok && res.data && this.sessionManager) {
1696
+ for (const conv of res.data.conversations) {
1697
+ if (conv.recipient_encryption_public_key && conv.target_did) {
1698
+ this.agentCardCache.set(conv.target_did, {
1699
+ did: conv.target_did,
1700
+ encryption_public_key: conv.recipient_encryption_public_key
1701
+ });
1702
+ }
1703
+ const trustState = conv.trusted ? "trusted" : conv.type === "pending_dm" ? "pending" : "stranger";
1704
+ this.sessionManager.upsert({
1705
+ session_key: buildSessionKey({
1706
+ localDid: this.identity.did,
1707
+ remoteDid: conv.target_did,
1708
+ conversationId: conv.conversation_id,
1709
+ conversationType: conv.type
1710
+ }),
1711
+ remote_did: conv.target_did,
1712
+ conversation_id: conv.conversation_id,
1713
+ trust_state: trustState,
1714
+ last_remote_activity_at: conv.last_activity_at ?? void 0,
1715
+ updated_at: conv.last_activity_at ?? conv.created_at
1716
+ });
1717
+ }
1718
+ }
1719
+ return res;
1720
+ }
1721
+ async getTaskStatus(conversationId, taskId) {
1722
+ const params = new URLSearchParams({ conversation_id: conversationId, task_id: taskId });
1723
+ const res = await this.transport.request("GET", `/v1/tasks/status?${params.toString()}`);
1724
+ if (res.ok && res.data) {
1725
+ const session = this.sessionManager?.getByConversationId(conversationId);
1726
+ this.taskThreadManager?.upsert({
1727
+ task_id: taskId,
1728
+ session_key: session?.session_key ?? buildSessionKey({ localDid: this.identity.did, conversationId, remoteDid: session?.remote_did }),
1729
+ conversation_id: conversationId,
1730
+ status: res.data.status,
1731
+ updated_at: res.data.last_update_ts_ms,
1732
+ result_summary: res.data.result_summary,
1733
+ error_code: res.data.error?.code,
1734
+ error_message: res.data.error?.message ?? res.data.reason
1735
+ });
1736
+ }
1737
+ return res;
1738
+ }
1739
+ async listTaskThreads(conversationId) {
1740
+ const params = new URLSearchParams({ conversation_id: conversationId });
1741
+ const res = await this.transport.request("GET", `/v1/tasks/list?${params.toString()}`);
1742
+ if (res.ok && res.data) {
1743
+ const session = this.sessionManager?.getByConversationId(conversationId);
1744
+ for (const task of res.data.tasks) {
1745
+ this.taskThreadManager?.upsert({
1746
+ task_id: task.task_id,
1747
+ session_key: session?.session_key ?? buildSessionKey({ localDid: this.identity.did, conversationId, remoteDid: session?.remote_did }),
1748
+ conversation_id: conversationId,
1749
+ title: task.title,
1750
+ status: task.status,
1751
+ updated_at: task.last_update_ts_ms,
1752
+ result_summary: task.result_summary,
1753
+ error_code: task.error?.code,
1754
+ error_message: task.error?.message ?? task.reason
1755
+ });
1756
+ }
1757
+ }
1758
+ return res;
1759
+ }
1760
+ async getProfile() {
1761
+ return this.transport.request("GET", "/v1/directory/profile");
1762
+ }
1763
+ async getDirectorySelf() {
1764
+ return this.transport.request("GET", "/v1/directory/self");
1765
+ }
1766
+ async updateProfile(profile) {
1767
+ const normalizedCard = profile.capability_card ? normalizeCapabilityCard(profile.capability_card) : void 0;
1768
+ const nextCapabilities = profile.capabilities !== void 0 ? profile.capabilities : normalizedCard ? capabilityCardToLegacyCapabilities(normalizedCard) : void 0;
1769
+ return this.transport.request("POST", "/v1/directory/profile", {
1770
+ ...profile,
1771
+ capability_card: normalizedCard,
1772
+ capabilities: nextCapabilities,
1773
+ encryption_public_key: this.identity.encryptionPublicKeyJwk
1774
+ });
1775
+ }
1776
+ async createPublicLink(opts) {
1777
+ return this.transport.request("POST", "/v1/public/link", {
1778
+ slug: opts?.slug,
1779
+ enabled: opts?.enabled
1780
+ });
1781
+ }
1782
+ async getPublicSelf() {
1783
+ return this.transport.request("GET", "/v1/public/self");
1784
+ }
1785
+ async getPublicAgent(slug) {
1786
+ return this.transport.request("GET", `/v1/public/agent/${encodeURIComponent(slug)}`, void 0, true);
1787
+ }
1788
+ async createContactCard(opts) {
1789
+ return this.transport.request("POST", "/v1/public/contact-card", {
1790
+ target_did: opts?.target_did,
1791
+ referrer_did: opts?.referrer_did,
1792
+ intro_note: opts?.intro_note,
1793
+ message_template: opts?.message_template
1794
+ });
1795
+ }
1796
+ async getContactCard(id) {
1797
+ return this.transport.request("GET", `/v1/public/contact-card/${encodeURIComponent(id)}`, void 0, true);
1798
+ }
1799
+ async createTaskShare(opts) {
1800
+ return this.transport.request("POST", "/v1/public/task-share", opts);
1801
+ }
1802
+ async getTaskShare(id) {
1803
+ return this.transport.request("GET", `/v1/public/task-share/${encodeURIComponent(id)}`, void 0, true);
1804
+ }
1805
+ async revokeTaskShare(id) {
1806
+ return this.transport.request("POST", `/v1/public/task-share/${encodeURIComponent(id)}/revoke`);
1807
+ }
1808
+ async ensureEncryptionKeyPublished() {
1809
+ const selfRes = await this.getDirectorySelf();
1810
+ if (!selfRes.ok || !selfRes.data) {
1811
+ return {
1812
+ ok: false,
1813
+ error: selfRes.error ?? {
1814
+ code: ErrorCode2.INTERNAL,
1815
+ message: "Failed to inspect directory card for encryption key publication",
1816
+ hint: ERROR_HINTS[ErrorCode2.INTERNAL]
1817
+ }
1818
+ };
1819
+ }
1820
+ if (this.sameEncryptionPublicKey(selfRes.data.encryption_public_key, this.identity.encryptionPublicKeyJwk)) {
1821
+ this.agentCardCache.set(this.identity.did, {
1822
+ did: this.identity.did,
1823
+ encryption_public_key: this.identity.encryptionPublicKeyJwk
1824
+ });
1825
+ return { ok: true, data: { published: true, status: "already_registered" } };
1826
+ }
1827
+ const updateRes = await this.updateProfile({});
1828
+ if (!updateRes.ok) {
1829
+ return {
1830
+ ok: false,
1831
+ error: updateRes.error ?? {
1832
+ code: ErrorCode2.INTERNAL,
1833
+ message: "Failed to publish encryption public key to directory profile",
1834
+ hint: ERROR_HINTS[ErrorCode2.INTERNAL]
1835
+ }
1836
+ };
1837
+ }
1838
+ this.agentCardCache.set(this.identity.did, {
1839
+ did: this.identity.did,
1840
+ encryption_public_key: this.identity.encryptionPublicKeyJwk
1841
+ });
1842
+ return { ok: true, data: { published: true, status: "updated" } };
1843
+ }
1844
+ async enableDiscovery() {
1845
+ return this.transport.request("POST", "/v1/directory/enable_discovery");
1846
+ }
1847
+ async disableDiscovery() {
1848
+ return this.transport.request("POST", "/v1/directory/disable_discovery");
1849
+ }
1850
+ async browseDirectory(opts) {
1851
+ const params = new URLSearchParams();
1852
+ if (opts?.tag) params.set("tag", opts.tag);
1853
+ if (opts?.query) params.set("q", opts.query);
1854
+ if (opts?.limit != null) params.set("limit", String(opts.limit));
1855
+ if (opts?.offset != null) params.set("offset", String(opts.offset));
1856
+ if (opts?.sort) params.set("sort", opts.sort);
1857
+ const qs = params.toString();
1858
+ return this.transport.request("GET", `/v1/directory/browse${qs ? "?" + qs : ""}`);
1859
+ }
1860
+ async publishPost(opts) {
1861
+ return this.transport.request("POST", "/v1/feed/publish", { text: opts.text, artifact_ref: opts.artifact_ref });
1862
+ }
1863
+ async listFeedPublic(opts) {
1864
+ const params = new URLSearchParams();
1865
+ if (opts?.limit != null) params.set("limit", String(opts.limit));
1866
+ if (opts?.since != null) params.set("since", String(opts.since));
1867
+ const qs = params.toString();
1868
+ return this.transport.request("GET", `/v1/feed/public${qs ? "?" + qs : ""}`, void 0, true);
1869
+ }
1870
+ async listFeedByDid(did, opts) {
1871
+ const params = new URLSearchParams({ did });
1872
+ if (opts?.limit != null) params.set("limit", String(opts.limit));
1873
+ return this.transport.request("GET", `/v1/feed/by_did?${params.toString()}`, void 0, true);
1874
+ }
1875
+ async createChannel(opts) {
1876
+ return this.transport.request("POST", "/v1/channels/create", {
1877
+ name: opts.name,
1878
+ alias: opts.alias,
1879
+ description: opts.description,
1880
+ join_policy: "open",
1881
+ discoverable: opts.discoverable
1882
+ });
1883
+ }
1884
+ async updateChannel(opts) {
1885
+ const alias = opts.alias.replace(/^@ch\//, "");
1886
+ return this.transport.request("PATCH", "/v1/channels/update", {
1887
+ alias,
1888
+ name: opts.name,
1889
+ description: opts.description,
1890
+ discoverable: opts.discoverable
1891
+ });
1892
+ }
1893
+ async deleteChannel(alias) {
1894
+ const a = alias.replace(/^@ch\//, "");
1895
+ return this.transport.request("DELETE", "/v1/channels/delete", { alias: a });
1896
+ }
1897
+ async discoverChannels(opts) {
1898
+ const params = new URLSearchParams();
1899
+ if (opts?.limit != null) params.set("limit", String(opts.limit));
1900
+ if (opts?.query) params.set("q", opts.query);
1901
+ const qs = params.toString();
1902
+ return this.transport.request("GET", `/v1/channels/discover${qs ? "?" + qs : ""}`, void 0, true);
1903
+ }
1904
+ async joinChannel(alias) {
1905
+ return this.transport.request("POST", "/v1/channels/join", { alias });
1906
+ }
1907
+ getDid() {
1908
+ return this.identity.did;
1909
+ }
1910
+ async decryptEnvelopePayload(envelope) {
1911
+ return decryptPayloadForIdentity(envelope.schema, envelope.payload ?? {}, this.identity);
1912
+ }
1913
+ // === Billing: device linking ===
1914
+ async createBillingLinkCode() {
1915
+ return this.transport.request("POST", "/v1/billing/link-code");
1916
+ }
1917
+ async redeemBillingLink(code) {
1918
+ return this.transport.request("POST", "/v1/billing/link", { code });
1919
+ }
1920
+ async unlinkBillingDevice(did) {
1921
+ return this.transport.request("POST", "/v1/billing/unlink", { did });
1922
+ }
1923
+ async getLinkedDevices() {
1924
+ return this.transport.request("GET", "/v1/billing/linked-devices");
1925
+ }
1926
+ // P0: High-level send-task-and-wait
1927
+ async sendTaskAndWait(targetDid, task, opts) {
1928
+ const { v7: uuidv7 } = await import("uuid");
1929
+ const timeout = opts?.timeoutMs ?? 12e4;
1930
+ const pollInterval = opts?.pollIntervalMs ?? 2e3;
1931
+ const taskId = `t_${uuidv7()}`;
1932
+ const startTime = Date.now();
1933
+ const openRes = await this.openConversation(targetDid);
1934
+ if (!openRes.ok || !openRes.data) {
1935
+ return { status: "error", task_id: taskId, error: { code: "E_OPEN_FAILED", message: "Failed to open conversation" }, elapsed_ms: Date.now() - startTime };
1936
+ }
1937
+ let conversationId = openRes.data.conversation_id;
1938
+ if (!openRes.data.trusted) {
1939
+ await this.sendContactRequest(conversationId, task.title);
1940
+ const approvalDeadline = startTime + timeout;
1941
+ while (Date.now() < approvalDeadline) {
1942
+ await sleep2(pollInterval);
1943
+ const reopen = await this.openConversation(targetDid);
1944
+ if (reopen.ok && reopen.data?.trusted) {
1945
+ conversationId = reopen.data.conversation_id;
1946
+ break;
1947
+ }
1948
+ }
1949
+ if (Date.now() >= approvalDeadline) {
1950
+ return { status: "error", task_id: taskId, error: { code: "E_NOT_APPROVED", message: "Contact request not approved within timeout" }, elapsed_ms: Date.now() - startTime };
1951
+ }
1952
+ }
1953
+ const sendRes = await this.sendTask(conversationId, { task_id: taskId, ...task });
1954
+ if (!sendRes.ok) {
1955
+ 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 };
1956
+ }
1957
+ const session = this.sessionManager?.getByConversationId(conversationId);
1958
+ this.taskThreadManager?.upsert({
1959
+ task_id: taskId,
1960
+ session_key: session?.session_key ?? buildSessionKey({ localDid: this.identity.did, conversationId, remoteDid: targetDid }),
1961
+ conversation_id: conversationId,
1962
+ title: task.title,
1963
+ status: "queued",
1964
+ started_at: Date.now(),
1965
+ updated_at: Date.now()
1966
+ });
1967
+ const sinceSeq = sendRes.data?.seq ?? 0;
1968
+ const deadline = startTime + timeout;
1969
+ while (Date.now() < deadline) {
1970
+ await sleep2(pollInterval);
1971
+ const statusRes = await this.getTaskStatus(conversationId, taskId);
1972
+ if (statusRes.ok && statusRes.data) {
1973
+ if (statusRes.data.status === "failed" || statusRes.data.status === "cancelled") {
1974
+ return {
1975
+ status: "error",
1976
+ task_id: taskId,
1977
+ error: {
1978
+ code: statusRes.data.error?.code ?? (statusRes.data.status === "cancelled" ? "E_CANCELLED" : "E_TASK_FAILED"),
1979
+ message: statusRes.data.error?.message ?? statusRes.data.reason ?? `Task ${statusRes.data.status}`
1980
+ },
1981
+ elapsed_ms: Date.now() - startTime
1982
+ };
1983
+ }
1984
+ }
1985
+ const fetchRes = await this.fetchInbox(conversationId, { sinceSeq });
1986
+ if (!fetchRes.ok || !fetchRes.data) continue;
1987
+ for (const msg of fetchRes.data.messages) {
1988
+ if (msg.schema === SCHEMA_RESULT2 && msg.payload?.task_id === taskId) {
1989
+ return {
1990
+ status: msg.payload.status === "ok" ? "ok" : "error",
1991
+ task_id: taskId,
1992
+ result: msg.payload.output,
1993
+ error: msg.payload.error,
1994
+ elapsed_ms: Date.now() - startTime
1995
+ };
1996
+ }
1997
+ }
1998
+ }
1999
+ return { status: "error", task_id: taskId, error: { code: "E_TIMEOUT", message: `No result within ${timeout}ms` }, elapsed_ms: timeout };
2000
+ }
2001
+ async sendHandoff(targetDid, handoff, opts) {
2002
+ const { v7: uuidv7 } = await import("uuid");
2003
+ const timeout = opts?.timeoutMs ?? 12e4;
2004
+ const pollInterval = opts?.pollIntervalMs ?? 2e3;
2005
+ const taskId = `t_${uuidv7()}`;
2006
+ const openRes = await this.openConversation(targetDid);
2007
+ if (!openRes.ok || !openRes.data) {
2008
+ return {
2009
+ ok: false,
2010
+ error: {
2011
+ code: "E_OPEN_FAILED",
2012
+ message: openRes.error?.message ?? "Failed to open conversation"
2013
+ }
2014
+ };
2015
+ }
2016
+ let conversationId = openRes.data.conversation_id;
2017
+ if (!openRes.data.trusted) {
2018
+ await this.sendContactRequest(conversationId, handoff.title);
2019
+ const approvalDeadline = Date.now() + timeout;
2020
+ while (Date.now() < approvalDeadline) {
2021
+ await sleep2(pollInterval);
2022
+ const reopen = await this.openConversation(targetDid);
2023
+ if (reopen.ok && reopen.data?.trusted) {
2024
+ conversationId = reopen.data.conversation_id;
2025
+ break;
2026
+ }
2027
+ }
2028
+ if (Date.now() >= approvalDeadline) {
2029
+ return {
2030
+ ok: false,
2031
+ error: {
2032
+ code: "E_NOT_APPROVED",
2033
+ message: "Contact request not approved within timeout"
2034
+ }
2035
+ };
2036
+ }
2037
+ }
2038
+ const summary = opts?.sessionKey ? this.sessionSummaryManager?.get(opts.sessionKey) : opts?.conversationId ? this.sessionSummaryManager?.get(this.sessionManager?.getByConversationId(opts.conversationId)?.session_key || "") : void 0;
2039
+ const handoffPayload = {
2040
+ objective: handoff.objective,
2041
+ carry_forward_summary: (handoff.carry_forward_summary ?? buildSessionSummaryHandoffText(summary)) || void 0,
2042
+ success_criteria: handoff.success_criteria,
2043
+ callback_session_key: handoff.callback_session_key ?? opts?.sessionKey,
2044
+ priority: handoff.priority,
2045
+ delegated_by: this.identity.did,
2046
+ delegated_to: targetDid
2047
+ };
2048
+ const sendRes = await this.sendTask(conversationId, {
2049
+ task_id: taskId,
2050
+ title: handoff.title,
2051
+ description: handoff.description,
2052
+ input: handoff.input,
2053
+ handoff: handoffPayload
2054
+ });
2055
+ if (!sendRes.ok) {
2056
+ return {
2057
+ ok: false,
2058
+ error: {
2059
+ code: sendRes.error?.code ?? "E_SEND_FAILED",
2060
+ message: sendRes.error?.message ?? "Send failed"
2061
+ }
2062
+ };
2063
+ }
2064
+ const session = this.sessionManager?.getByConversationId(conversationId);
2065
+ const sessionKey = session?.session_key ?? buildSessionKey({ localDid: this.identity.did, conversationId, remoteDid: targetDid });
2066
+ this.taskThreadManager?.upsert({
2067
+ task_id: taskId,
2068
+ session_key: sessionKey,
2069
+ conversation_id: conversationId,
2070
+ title: handoff.title,
2071
+ status: "queued",
2072
+ started_at: Date.now(),
2073
+ updated_at: Date.now()
2074
+ });
2075
+ this.taskHandoffManager?.upsert({
2076
+ task_id: taskId,
2077
+ session_key: sessionKey,
2078
+ conversation_id: conversationId,
2079
+ ...handoffPayload,
2080
+ updated_at: Date.now()
2081
+ });
2082
+ return {
2083
+ ok: true,
2084
+ data: {
2085
+ task_id: taskId,
2086
+ conversation_id: conversationId,
2087
+ handoff: handoffPayload
2088
+ }
2089
+ };
2090
+ }
2091
+ };
2092
+ function normalizeTaskThreadStatus(state) {
2093
+ if (state === "completed") return "processed";
2094
+ if (state === "cancel_requested") return "running";
2095
+ if (state === "cancelled") return "cancelled";
2096
+ if (state === "failed") return "failed";
2097
+ if (state === "running") return "running";
2098
+ return "queued";
2099
+ }
2100
+ function sleep2(ms) {
2101
+ return new Promise((resolve4) => setTimeout(resolve4, ms));
2102
+ }
2103
+
2104
+ // src/auth.ts
2105
+ var REFRESH_GRACE_MS = 5 * 60 * 1e3;
2106
+ async function ensureTokenValid(identityPath, serverUrl) {
2107
+ if (!identityExists(identityPath)) return false;
2108
+ const id = loadIdentity(identityPath);
2109
+ const token = id.accessToken;
2110
+ const expiresAt = id.tokenExpiresAt;
2111
+ if (!token || expiresAt == null) return false;
2112
+ const now = Date.now();
2113
+ if (expiresAt > now + REFRESH_GRACE_MS) return false;
2114
+ const baseUrl = (serverUrl ?? id.serverUrl ?? "https://pingagent.chat").replace(/\/$/, "");
2115
+ try {
2116
+ const res = await fetch(`${baseUrl}/v1/auth/refresh`, {
2117
+ method: "POST",
2118
+ headers: { "Content-Type": "application/json" },
2119
+ body: JSON.stringify({ access_token: token })
2120
+ });
2121
+ const text = await res.text();
2122
+ let data;
2123
+ try {
2124
+ data = text ? JSON.parse(text) : {};
2125
+ } catch {
2126
+ return false;
2127
+ }
2128
+ if (!res.ok || !data.ok || !data.data?.access_token || data.data.expires_ms == null) return false;
2129
+ const newExpiresAt = now + data.data.expires_ms;
2130
+ updateStoredToken(data.data.access_token, newExpiresAt, identityPath);
2131
+ return true;
2132
+ } catch {
2133
+ return false;
2134
+ }
2135
+ }
2136
+
2137
+ // src/store.ts
2138
+ import Database from "better-sqlite3";
2139
+ import * as fs2 from "fs";
2140
+ import * as path3 from "path";
2141
+ var SCHEMA_SQL = `
2142
+ CREATE TABLE IF NOT EXISTS contacts (
2143
+ did TEXT PRIMARY KEY,
2144
+ alias TEXT,
2145
+ display_name TEXT,
2146
+ notes TEXT,
2147
+ conversation_id TEXT,
2148
+ trusted INTEGER NOT NULL DEFAULT 0,
2149
+ added_at INTEGER NOT NULL,
2150
+ last_message_at INTEGER,
2151
+ tags TEXT
2152
+ );
2153
+ CREATE INDEX IF NOT EXISTS idx_contacts_alias ON contacts(alias);
2154
+
2155
+ CREATE TABLE IF NOT EXISTS messages (
2156
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
2157
+ conversation_id TEXT NOT NULL,
2158
+ message_id TEXT NOT NULL UNIQUE,
2159
+ seq INTEGER,
2160
+ sender_did TEXT NOT NULL,
2161
+ schema TEXT NOT NULL,
2162
+ payload TEXT NOT NULL,
2163
+ ts_ms INTEGER NOT NULL,
2164
+ direction TEXT NOT NULL CHECK(direction IN ('sent', 'received'))
2165
+ );
2166
+ CREATE INDEX IF NOT EXISTS idx_messages_conv_seq ON messages(conversation_id, seq);
2167
+ CREATE INDEX IF NOT EXISTS idx_messages_ts ON messages(ts_ms);
2168
+
2169
+ CREATE TABLE IF NOT EXISTS sync_state (
2170
+ conversation_id TEXT PRIMARY KEY,
2171
+ last_synced_seq INTEGER NOT NULL DEFAULT 0,
2172
+ last_synced_at INTEGER
2173
+ );
2174
+
2175
+ CREATE TABLE IF NOT EXISTS session_state (
2176
+ session_key TEXT PRIMARY KEY,
2177
+ remote_did TEXT,
2178
+ conversation_id TEXT,
2179
+ trust_state TEXT NOT NULL DEFAULT 'stranger',
2180
+ last_message_preview TEXT,
2181
+ last_remote_activity_at INTEGER,
2182
+ last_read_seq INTEGER NOT NULL DEFAULT 0,
2183
+ unread_count INTEGER NOT NULL DEFAULT 0,
2184
+ active INTEGER NOT NULL DEFAULT 0,
2185
+ updated_at INTEGER NOT NULL
2186
+ );
2187
+ CREATE INDEX IF NOT EXISTS idx_session_state_updated ON session_state(updated_at DESC);
2188
+ CREATE INDEX IF NOT EXISTS idx_session_state_conversation ON session_state(conversation_id);
2189
+ CREATE INDEX IF NOT EXISTS idx_session_state_remote_did ON session_state(remote_did);
2190
+
2191
+ CREATE TABLE IF NOT EXISTS task_threads (
2192
+ task_id TEXT PRIMARY KEY,
2193
+ session_key TEXT NOT NULL,
2194
+ conversation_id TEXT NOT NULL,
2195
+ title TEXT,
2196
+ status TEXT NOT NULL,
2197
+ started_at INTEGER,
2198
+ updated_at INTEGER NOT NULL,
2199
+ result_summary TEXT,
2200
+ error_code TEXT,
2201
+ error_message TEXT
2202
+ );
2203
+ CREATE INDEX IF NOT EXISTS idx_task_threads_session ON task_threads(session_key, updated_at DESC);
2204
+ CREATE INDEX IF NOT EXISTS idx_task_threads_conversation ON task_threads(conversation_id, updated_at DESC);
2205
+
2206
+ CREATE TABLE IF NOT EXISTS session_summaries (
2207
+ session_key TEXT PRIMARY KEY,
2208
+ objective TEXT,
2209
+ context TEXT,
2210
+ constraints TEXT,
2211
+ decisions TEXT,
2212
+ open_questions TEXT,
2213
+ next_action TEXT,
2214
+ handoff_ready_text TEXT,
2215
+ updated_at INTEGER NOT NULL
2216
+ );
2217
+ CREATE INDEX IF NOT EXISTS idx_session_summaries_updated ON session_summaries(updated_at DESC);
2218
+
2219
+ CREATE TABLE IF NOT EXISTS task_handoffs (
2220
+ task_id TEXT PRIMARY KEY,
2221
+ session_key TEXT NOT NULL,
2222
+ conversation_id TEXT NOT NULL,
2223
+ objective TEXT,
2224
+ carry_forward_summary TEXT,
2225
+ success_criteria TEXT,
2226
+ callback_session_key TEXT,
2227
+ priority TEXT,
2228
+ delegated_by TEXT,
2229
+ delegated_to TEXT,
2230
+ updated_at INTEGER NOT NULL
2231
+ );
2232
+ CREATE INDEX IF NOT EXISTS idx_task_handoffs_session ON task_handoffs(session_key, updated_at DESC);
2233
+ CREATE INDEX IF NOT EXISTS idx_task_handoffs_conversation ON task_handoffs(conversation_id, updated_at DESC);
2234
+
2235
+ CREATE TABLE IF NOT EXISTS trust_policy_audit (
2236
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
2237
+ ts_ms INTEGER NOT NULL,
2238
+ event_type TEXT NOT NULL,
2239
+ policy_scope TEXT,
2240
+ remote_did TEXT,
2241
+ sender_alias TEXT,
2242
+ sender_verification_status TEXT,
2243
+ session_key TEXT,
2244
+ conversation_id TEXT,
2245
+ action TEXT,
2246
+ outcome TEXT,
2247
+ explanation TEXT,
2248
+ matched_rule TEXT,
2249
+ detail_json TEXT
2250
+ );
2251
+ CREATE INDEX IF NOT EXISTS idx_trust_policy_audit_ts ON trust_policy_audit(ts_ms DESC, id DESC);
2252
+ CREATE INDEX IF NOT EXISTS idx_trust_policy_audit_session ON trust_policy_audit(session_key, ts_ms DESC);
2253
+ CREATE INDEX IF NOT EXISTS idx_trust_policy_audit_remote ON trust_policy_audit(remote_did, ts_ms DESC);
2254
+
2255
+ CREATE TABLE IF NOT EXISTS trust_policy_recommendations (
2256
+ id TEXT PRIMARY KEY,
2257
+ policy TEXT NOT NULL,
2258
+ remote_did TEXT NOT NULL,
2259
+ match TEXT NOT NULL,
2260
+ action TEXT NOT NULL,
2261
+ current_action TEXT NOT NULL,
2262
+ confidence TEXT NOT NULL,
2263
+ reason TEXT NOT NULL,
2264
+ signals_json TEXT NOT NULL,
2265
+ status TEXT NOT NULL DEFAULT 'open',
2266
+ first_seen_at INTEGER NOT NULL,
2267
+ last_seen_at INTEGER NOT NULL,
2268
+ updated_at INTEGER NOT NULL,
2269
+ last_state_change_at INTEGER,
2270
+ applied_at INTEGER,
2271
+ dismissed_at INTEGER
2272
+ );
2273
+ CREATE INDEX IF NOT EXISTS idx_trust_policy_recommendations_status ON trust_policy_recommendations(status, updated_at DESC);
2274
+ CREATE INDEX IF NOT EXISTS idx_trust_policy_recommendations_remote ON trust_policy_recommendations(remote_did, updated_at DESC);
2275
+ `;
2276
+ var LocalStore = class {
2277
+ db;
2278
+ constructor(dbPath) {
2279
+ const p = getStorePath(dbPath);
2280
+ const dir = path3.dirname(p);
2281
+ if (!fs2.existsSync(dir)) {
2282
+ fs2.mkdirSync(dir, { recursive: true, mode: 448 });
2283
+ }
2284
+ this.db = new Database(p);
2285
+ this.db.pragma("journal_mode = WAL");
2286
+ this.db.exec(SCHEMA_SQL);
2287
+ this.applyMigrations();
2288
+ }
2289
+ getDb() {
2290
+ return this.db;
2291
+ }
2292
+ close() {
2293
+ this.db.close();
2294
+ }
2295
+ applyMigrations() {
2296
+ const alterStatements = [
2297
+ `ALTER TABLE session_state ADD COLUMN remote_did TEXT`,
2298
+ `ALTER TABLE session_state ADD COLUMN conversation_id TEXT`,
2299
+ `ALTER TABLE session_state ADD COLUMN trust_state TEXT NOT NULL DEFAULT 'stranger'`,
2300
+ `ALTER TABLE session_state ADD COLUMN last_message_preview TEXT`,
2301
+ `ALTER TABLE session_state ADD COLUMN last_remote_activity_at INTEGER`,
2302
+ `ALTER TABLE session_state ADD COLUMN last_read_seq INTEGER NOT NULL DEFAULT 0`,
2303
+ `ALTER TABLE session_state ADD COLUMN unread_count INTEGER NOT NULL DEFAULT 0`,
2304
+ `ALTER TABLE session_state ADD COLUMN active INTEGER NOT NULL DEFAULT 0`,
2305
+ `ALTER TABLE session_state ADD COLUMN updated_at INTEGER NOT NULL DEFAULT 0`,
2306
+ `ALTER TABLE task_threads ADD COLUMN title TEXT`,
2307
+ `ALTER TABLE task_threads ADD COLUMN result_summary TEXT`,
2308
+ `ALTER TABLE task_threads ADD COLUMN error_code TEXT`,
2309
+ `ALTER TABLE task_threads ADD COLUMN error_message TEXT`
2310
+ ];
2311
+ for (const sql of alterStatements) {
2312
+ try {
2313
+ this.db.exec(sql);
2314
+ } catch {
2315
+ }
2316
+ }
2317
+ }
2318
+ };
2319
+
2320
+ // src/trust-policy.ts
2321
+ var CONTACT_ACTIONS = /* @__PURE__ */ new Set(["approve", "manual", "reject"]);
2322
+ var TASK_ACTIONS = /* @__PURE__ */ new Set(["bridge", "execute", "deny"]);
2323
+ function defaultTrustPolicyDoc() {
2324
+ return {
2325
+ version: 1,
2326
+ contact_policy: {
2327
+ enabled: true,
2328
+ default_action: "manual",
2329
+ rules: []
2330
+ },
2331
+ task_policy: {
2332
+ enabled: true,
2333
+ default_action: "bridge",
2334
+ rules: []
2335
+ }
2336
+ };
2337
+ }
2338
+ function normalizeTrustPolicyDoc(raw) {
2339
+ const base = defaultTrustPolicyDoc();
2340
+ const contactRules = Array.isArray(raw?.contact_policy?.rules) ? raw.contact_policy.rules.filter((rule) => typeof rule?.match === "string" && CONTACT_ACTIONS.has(rule?.action)) : [];
2341
+ const taskRules = Array.isArray(raw?.task_policy?.rules) ? raw.task_policy.rules.filter((rule) => typeof rule?.match === "string" && TASK_ACTIONS.has(rule?.action)) : [];
2342
+ return {
2343
+ version: 1,
2344
+ contact_policy: {
2345
+ enabled: raw?.contact_policy?.enabled !== false,
2346
+ default_action: CONTACT_ACTIONS.has(raw?.contact_policy?.default_action) ? raw.contact_policy.default_action : base.contact_policy.default_action,
2347
+ rules: contactRules
2348
+ },
2349
+ task_policy: {
2350
+ enabled: raw?.task_policy?.enabled !== false,
2351
+ default_action: TASK_ACTIONS.has(raw?.task_policy?.default_action) ? raw.task_policy.default_action : base.task_policy.default_action,
2352
+ rules: taskRules
2353
+ }
2354
+ };
2355
+ }
2356
+ function matchesTrustPolicyRule(match, context) {
2357
+ if (match === "*") return true;
2358
+ if (match.startsWith("did:agent:")) {
2359
+ return context.sender_did === match;
2360
+ }
2361
+ if (match.startsWith("verification_status:")) {
2362
+ return context.sender_verification_status === match.split(":")[1];
2363
+ }
2364
+ if (match.startsWith("alias:")) {
2365
+ const pattern = match.slice(6);
2366
+ const senderAlias = context.sender_alias ?? "";
2367
+ if (pattern.endsWith("*")) return senderAlias.startsWith(pattern.slice(0, -1));
2368
+ return senderAlias === pattern;
2369
+ }
2370
+ return false;
2371
+ }
2372
+ function decideContactPolicy(policyDoc, context, opts) {
2373
+ if (policyDoc.contact_policy.enabled) {
2374
+ for (const rule of policyDoc.contact_policy.rules) {
2375
+ if (matchesTrustPolicyRule(rule.match, context)) {
2376
+ return {
2377
+ action: rule.action,
2378
+ source: "rule",
2379
+ matched_rule: rule,
2380
+ explanation: `Matched contact_policy rule ${rule.match} -> ${rule.action}`
2381
+ };
2382
+ }
2383
+ }
2384
+ return {
2385
+ action: policyDoc.contact_policy.default_action,
2386
+ source: "default",
2387
+ explanation: `No contact_policy rule matched; using default_action=${policyDoc.contact_policy.default_action}`
2388
+ };
2389
+ }
2390
+ if (opts?.legacyAutoApproveEnabled) {
2391
+ for (const rule of opts.legacyAutoApproveRules ?? []) {
2392
+ if (rule.action === "approve" && matchesTrustPolicyRule(rule.match, context)) {
2393
+ return {
2394
+ action: "approve",
2395
+ source: "legacy_auto_approve",
2396
+ matched_rule: { match: rule.match, action: "approve" },
2397
+ explanation: `Matched legacy auto_approve rule ${rule.match} -> approve`
2398
+ };
2399
+ }
2400
+ }
2401
+ }
2402
+ return {
2403
+ action: "manual",
2404
+ source: "runtime_default",
2405
+ explanation: "contact_policy disabled and no legacy auto_approve match; defaulting to manual"
2406
+ };
2407
+ }
2408
+ function decideTaskPolicy(policyDoc, context, opts) {
2409
+ if (policyDoc.task_policy.enabled) {
2410
+ for (const rule of policyDoc.task_policy.rules) {
2411
+ if (matchesTrustPolicyRule(rule.match, context)) {
2412
+ return {
2413
+ action: rule.action,
2414
+ source: "rule",
2415
+ matched_rule: rule,
2416
+ explanation: `Matched task_policy rule ${rule.match} -> ${rule.action}`
2417
+ };
2418
+ }
2419
+ }
2420
+ return {
2421
+ action: policyDoc.task_policy.default_action,
2422
+ source: "default",
2423
+ explanation: `No task_policy rule matched; using default_action=${policyDoc.task_policy.default_action}`
2424
+ };
2425
+ }
2426
+ const runtimeDefault = opts?.runtimeMode === "executor" ? "execute" : "bridge";
2427
+ return {
2428
+ action: runtimeDefault,
2429
+ source: "runtime_default",
2430
+ explanation: `task_policy disabled; defaulting to runtime_mode=${opts?.runtimeMode ?? "bridge"} -> ${runtimeDefault}`
2431
+ };
2432
+ }
2433
+
2434
+ // src/trust-policy-audit.ts
2435
+ function rowToEvent(row) {
2436
+ return {
2437
+ id: row.id,
2438
+ ts_ms: row.ts_ms,
2439
+ event_type: row.event_type,
2440
+ policy_scope: row.policy_scope ?? void 0,
2441
+ remote_did: row.remote_did ?? void 0,
2442
+ sender_alias: row.sender_alias ?? void 0,
2443
+ sender_verification_status: row.sender_verification_status ?? void 0,
2444
+ session_key: row.session_key ?? void 0,
2445
+ conversation_id: row.conversation_id ?? void 0,
2446
+ action: row.action ?? void 0,
2447
+ outcome: row.outcome ?? void 0,
2448
+ explanation: row.explanation ?? void 0,
2449
+ matched_rule: row.matched_rule ?? void 0,
2450
+ detail: row.detail_json ? JSON.parse(row.detail_json) : void 0
2451
+ };
2452
+ }
2453
+ function buildSummaryFromEvents(events) {
2454
+ const byType = {};
2455
+ const byPolicyScope = {};
2456
+ let latestTsMs = 0;
2457
+ for (const event of events) {
2458
+ byType[event.event_type] = (byType[event.event_type] ?? 0) + 1;
2459
+ if (event.policy_scope) byPolicyScope[event.policy_scope] = (byPolicyScope[event.policy_scope] ?? 0) + 1;
2460
+ latestTsMs = Math.max(latestTsMs, event.ts_ms);
2461
+ }
2462
+ return {
2463
+ total_events: events.length,
2464
+ latest_ts_ms: latestTsMs || void 0,
2465
+ by_type: byType,
2466
+ by_policy_scope: byPolicyScope
2467
+ };
2468
+ }
2469
+ var TrustPolicyAuditManager = class {
2470
+ constructor(store) {
2471
+ this.store = store;
2472
+ }
2473
+ record(event) {
2474
+ const tsMs = event.ts_ms ?? Date.now();
2475
+ const result = this.store.getDb().prepare(`
2476
+ INSERT INTO trust_policy_audit (
2477
+ ts_ms, event_type, policy_scope, remote_did, sender_alias, sender_verification_status,
2478
+ session_key, conversation_id, action, outcome, explanation, matched_rule, detail_json
2479
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2480
+ `).run(
2481
+ tsMs,
2482
+ event.event_type,
2483
+ event.policy_scope ?? null,
2484
+ event.remote_did ?? null,
2485
+ event.sender_alias ?? null,
2486
+ event.sender_verification_status ?? null,
2487
+ event.session_key ?? null,
2488
+ event.conversation_id ?? null,
2489
+ event.action ?? null,
2490
+ event.outcome ?? null,
2491
+ event.explanation ?? null,
2492
+ event.matched_rule ?? null,
2493
+ event.detail ? JSON.stringify(event.detail) : null
2494
+ );
2495
+ return {
2496
+ id: Number(result.lastInsertRowid),
2497
+ ts_ms: tsMs,
2498
+ event_type: event.event_type,
2499
+ policy_scope: event.policy_scope,
2500
+ remote_did: event.remote_did,
2501
+ sender_alias: event.sender_alias,
2502
+ sender_verification_status: event.sender_verification_status,
2503
+ session_key: event.session_key,
2504
+ conversation_id: event.conversation_id,
2505
+ action: event.action,
2506
+ outcome: event.outcome,
2507
+ explanation: event.explanation,
2508
+ matched_rule: event.matched_rule,
2509
+ detail: event.detail
2510
+ };
2511
+ }
2512
+ listRecent(limit = 50) {
2513
+ const rows = this.store.getDb().prepare("SELECT * FROM trust_policy_audit ORDER BY ts_ms DESC, id DESC LIMIT ?").all(limit);
2514
+ return rows.map(rowToEvent);
2515
+ }
2516
+ listBySession(sessionKey, limit = 50) {
2517
+ 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);
2518
+ return rows.map(rowToEvent);
2519
+ }
2520
+ listByRemoteDid(remoteDid, limit = 50) {
2521
+ 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);
2522
+ return rows.map(rowToEvent);
2523
+ }
2524
+ summarize(limit = 200) {
2525
+ return buildSummaryFromEvents(this.listRecent(limit));
2526
+ }
2527
+ };
2528
+ function aggregateLearning(sessions, tasks, events) {
2529
+ const summaries = /* @__PURE__ */ new Map();
2530
+ function ensure(remoteDid) {
2531
+ if (!remoteDid) return null;
2532
+ const existing = summaries.get(remoteDid);
2533
+ if (existing) return existing;
2534
+ const created = {
2535
+ remote_did: remoteDid,
2536
+ trusted_sessions: 0,
2537
+ pending_sessions: 0,
2538
+ blocked_sessions: 0,
2539
+ revoked_sessions: 0,
2540
+ processed_tasks: 0,
2541
+ failed_tasks: 0,
2542
+ cancelled_tasks: 0,
2543
+ contact_approvals: 0,
2544
+ contact_manual_reviews: 0,
2545
+ contact_rejections: 0,
2546
+ task_bridged: 0,
2547
+ task_executed: 0,
2548
+ task_denied: 0
2549
+ };
2550
+ summaries.set(remoteDid, created);
2551
+ return created;
2552
+ }
2553
+ const remoteBySession = /* @__PURE__ */ new Map();
2554
+ for (const session of sessions) {
2555
+ const summary = ensure(session.remote_did);
2556
+ if (!summary) continue;
2557
+ remoteBySession.set(session.session_key, session.remote_did);
2558
+ 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;
2559
+ if (session.trust_state === "trusted") summary.trusted_sessions += 1;
2560
+ if (session.trust_state === "pending") summary.pending_sessions += 1;
2561
+ if (session.trust_state === "blocked") summary.blocked_sessions += 1;
2562
+ if (session.trust_state === "revoked") summary.revoked_sessions += 1;
2563
+ }
2564
+ for (const task of tasks) {
2565
+ const remoteDid = remoteBySession.get(task.session_key);
2566
+ const summary = ensure(remoteDid);
2567
+ if (!summary) continue;
2568
+ summary.last_seen_at = Math.max(summary.last_seen_at ?? 0, task.updated_at ?? 0) || summary.last_seen_at;
2569
+ if (task.status === "processed") summary.processed_tasks += 1;
2570
+ if (task.status === "failed") summary.failed_tasks += 1;
2571
+ if (task.status === "cancelled") summary.cancelled_tasks += 1;
2572
+ }
2573
+ for (const event of events) {
2574
+ const summary = ensure(event.remote_did ?? remoteBySession.get(event.session_key ?? ""));
2575
+ if (!summary) continue;
2576
+ summary.last_seen_at = Math.max(summary.last_seen_at ?? 0, event.ts_ms ?? 0) || summary.last_seen_at;
2577
+ if (event.event_type === "contact_auto_approved") summary.contact_approvals += 1;
2578
+ if (event.event_type === "contact_manual_review") summary.contact_manual_reviews += 1;
2579
+ if (event.event_type === "contact_rejected" || event.event_type === "session_blocked") summary.contact_rejections += 1;
2580
+ if (event.event_type === "session_revoked") summary.revoked_sessions += 1;
2581
+ if (event.event_type === "task_bridged") summary.task_bridged += 1;
2582
+ if (event.event_type === "task_executed") summary.task_executed += 1;
2583
+ if (event.event_type === "task_denied") summary.task_denied += 1;
2584
+ if (event.event_type === "task_processed") summary.processed_tasks += 1;
2585
+ if (event.event_type === "task_failed") summary.failed_tasks += 1;
2586
+ if (event.event_type === "task_cancelled") summary.cancelled_tasks += 1;
2587
+ }
2588
+ return [...summaries.values()].sort((a, b) => (b.last_seen_at ?? 0) - (a.last_seen_at ?? 0));
2589
+ }
2590
+ function recommendationId(policy, remoteDid, action) {
2591
+ return `${policy}:${remoteDid}:${action}`;
2592
+ }
2593
+ function describePositiveSignals(summary) {
2594
+ const parts = [];
2595
+ if (summary.trusted_sessions > 0) parts.push(`trusted_sessions=${summary.trusted_sessions}`);
2596
+ if (summary.contact_approvals > 0) parts.push(`contact_approvals=${summary.contact_approvals}`);
2597
+ if (summary.processed_tasks > 0) parts.push(`processed_tasks=${summary.processed_tasks}`);
2598
+ return parts.join(", ");
2599
+ }
2600
+ function describeRiskSignals(summary) {
2601
+ const parts = [];
2602
+ if (summary.blocked_sessions > 0) parts.push(`blocked_sessions=${summary.blocked_sessions}`);
2603
+ if (summary.revoked_sessions > 0) parts.push(`revoked_sessions=${summary.revoked_sessions}`);
2604
+ if (summary.contact_rejections > 0) parts.push(`contact_rejections=${summary.contact_rejections}`);
2605
+ if (summary.task_denied > 0) parts.push(`task_denied=${summary.task_denied}`);
2606
+ if (summary.failed_tasks > 0) parts.push(`failed_tasks=${summary.failed_tasks}`);
2607
+ return parts.join(", ");
2608
+ }
2609
+ function buildTrustPolicyRecommendations(opts) {
2610
+ const policyDoc = normalizeTrustPolicyDoc(opts.policyDoc);
2611
+ const summaries = aggregateLearning(opts.sessions, opts.tasks, opts.auditEvents);
2612
+ const recommendations = [];
2613
+ for (const summary of summaries) {
2614
+ const contactDecision = decideContactPolicy(policyDoc, { sender_did: summary.remote_did });
2615
+ const taskDecision = decideTaskPolicy(policyDoc, { sender_did: summary.remote_did }, { runtimeMode: opts.runtimeMode });
2616
+ const riskSignals = summary.blocked_sessions + summary.revoked_sessions + summary.contact_rejections + summary.task_denied;
2617
+ const positiveSignals = summary.trusted_sessions + summary.contact_approvals + summary.processed_tasks;
2618
+ if (riskSignals > 0) {
2619
+ if (contactDecision.action !== "reject") {
2620
+ recommendations.push({
2621
+ id: recommendationId("contact", summary.remote_did, "reject"),
2622
+ policy: "contact",
2623
+ remote_did: summary.remote_did,
2624
+ match: summary.remote_did,
2625
+ action: "reject",
2626
+ current_action: contactDecision.action,
2627
+ confidence: riskSignals >= 2 ? "high" : "medium",
2628
+ reason: `Observed repeated negative signals: ${describeRiskSignals(summary)}`,
2629
+ signals: {
2630
+ trusted_sessions: summary.trusted_sessions,
2631
+ blocked_sessions: summary.blocked_sessions,
2632
+ revoked_sessions: summary.revoked_sessions,
2633
+ processed_tasks: summary.processed_tasks,
2634
+ failed_tasks: summary.failed_tasks,
2635
+ cancelled_tasks: summary.cancelled_tasks,
2636
+ contact_approvals: summary.contact_approvals,
2637
+ contact_rejections: summary.contact_rejections,
2638
+ task_denied: summary.task_denied,
2639
+ last_seen_at: summary.last_seen_at
2640
+ }
2641
+ });
2642
+ }
2643
+ if (taskDecision.action !== "deny") {
2644
+ recommendations.push({
2645
+ id: recommendationId("task", summary.remote_did, "deny"),
2646
+ policy: "task",
2647
+ remote_did: summary.remote_did,
2648
+ match: summary.remote_did,
2649
+ action: "deny",
2650
+ current_action: taskDecision.action,
2651
+ confidence: summary.task_denied > 0 || summary.blocked_sessions > 0 || summary.contact_rejections > 0 ? "high" : "medium",
2652
+ reason: `Observed repeated negative task/session signals: ${describeRiskSignals(summary)}`,
2653
+ signals: {
2654
+ trusted_sessions: summary.trusted_sessions,
2655
+ blocked_sessions: summary.blocked_sessions,
2656
+ revoked_sessions: summary.revoked_sessions,
2657
+ processed_tasks: summary.processed_tasks,
2658
+ failed_tasks: summary.failed_tasks,
2659
+ cancelled_tasks: summary.cancelled_tasks,
2660
+ contact_approvals: summary.contact_approvals,
2661
+ contact_rejections: summary.contact_rejections,
2662
+ task_denied: summary.task_denied,
2663
+ last_seen_at: summary.last_seen_at
2664
+ }
2665
+ });
2666
+ }
2667
+ continue;
2668
+ }
2669
+ if (positiveSignals > 0 && contactDecision.action !== "approve" && (summary.trusted_sessions > 0 || summary.contact_approvals > 0 || summary.processed_tasks >= 2)) {
2670
+ recommendations.push({
2671
+ id: recommendationId("contact", summary.remote_did, "approve"),
2672
+ policy: "contact",
2673
+ remote_did: summary.remote_did,
2674
+ match: summary.remote_did,
2675
+ action: "approve",
2676
+ current_action: contactDecision.action,
2677
+ confidence: summary.processed_tasks >= 2 || summary.contact_approvals > 0 ? "high" : "medium",
2678
+ reason: `Observed stable positive collaboration: ${describePositiveSignals(summary)}`,
2679
+ signals: {
2680
+ trusted_sessions: summary.trusted_sessions,
2681
+ blocked_sessions: summary.blocked_sessions,
2682
+ revoked_sessions: summary.revoked_sessions,
2683
+ processed_tasks: summary.processed_tasks,
2684
+ failed_tasks: summary.failed_tasks,
2685
+ cancelled_tasks: summary.cancelled_tasks,
2686
+ contact_approvals: summary.contact_approvals,
2687
+ contact_rejections: summary.contact_rejections,
2688
+ task_denied: summary.task_denied,
2689
+ last_seen_at: summary.last_seen_at
2690
+ }
2691
+ });
2692
+ }
2693
+ const desiredTaskAction = opts.runtimeMode === "executor" ? "execute" : "bridge";
2694
+ if (summary.processed_tasks >= 2 && summary.failed_tasks === 0 && summary.cancelled_tasks === 0 && summary.task_denied === 0 && taskDecision.action !== desiredTaskAction) {
2695
+ recommendations.push({
2696
+ id: recommendationId("task", summary.remote_did, desiredTaskAction),
2697
+ policy: "task",
2698
+ remote_did: summary.remote_did,
2699
+ match: summary.remote_did,
2700
+ action: desiredTaskAction,
2701
+ current_action: taskDecision.action,
2702
+ confidence: "high",
2703
+ reason: `Observed successful task flow without negative outcomes: processed_tasks=${summary.processed_tasks}`,
2704
+ signals: {
2705
+ trusted_sessions: summary.trusted_sessions,
2706
+ blocked_sessions: summary.blocked_sessions,
2707
+ revoked_sessions: summary.revoked_sessions,
2708
+ processed_tasks: summary.processed_tasks,
2709
+ failed_tasks: summary.failed_tasks,
2710
+ cancelled_tasks: summary.cancelled_tasks,
2711
+ contact_approvals: summary.contact_approvals,
2712
+ contact_rejections: summary.contact_rejections,
2713
+ task_denied: summary.task_denied,
2714
+ last_seen_at: summary.last_seen_at
2715
+ }
2716
+ });
2717
+ }
2718
+ }
2719
+ recommendations.sort((a, b) => {
2720
+ const confidenceScore = (value) => value === "high" ? 2 : 1;
2721
+ const delta = confidenceScore(b.confidence) - confidenceScore(a.confidence);
2722
+ if (delta !== 0) return delta;
2723
+ return (b.signals.last_seen_at ?? 0) - (a.signals.last_seen_at ?? 0);
2724
+ });
2725
+ return recommendations.slice(0, opts.limit ?? 20);
2726
+ }
2727
+ function upsertTrustPolicyRecommendation(policyDoc, recommendation) {
2728
+ const doc = normalizeTrustPolicyDoc(policyDoc);
2729
+ if (recommendation.policy === "contact") {
2730
+ return normalizeTrustPolicyDoc({
2731
+ ...doc,
2732
+ contact_policy: {
2733
+ ...doc.contact_policy,
2734
+ enabled: true,
2735
+ rules: [
2736
+ { match: recommendation.match, action: recommendation.action },
2737
+ ...doc.contact_policy.rules.filter((rule) => rule.match !== recommendation.match)
2738
+ ]
2739
+ }
2740
+ });
2741
+ }
2742
+ return normalizeTrustPolicyDoc({
2743
+ ...doc,
2744
+ task_policy: {
2745
+ ...doc.task_policy,
2746
+ enabled: true,
2747
+ rules: [
2748
+ { match: recommendation.match, action: recommendation.action },
2749
+ ...doc.task_policy.rules.filter((rule) => rule.match !== recommendation.match)
2750
+ ]
2751
+ }
2752
+ });
2753
+ }
2754
+ function summarizeTrustPolicyAudit(events) {
2755
+ return buildSummaryFromEvents(events);
2756
+ }
2757
+
2758
+ // src/trust-policy-recommendations.ts
2759
+ function getTrustRecommendationActionLabel(recommendation) {
2760
+ if (recommendation.status === "dismissed" || recommendation.status === "superseded") {
2761
+ return "Reopen";
2762
+ }
2763
+ if (recommendation.status === "applied") {
2764
+ return "Applied";
2765
+ }
2766
+ if (recommendation.policy === "contact") {
2767
+ if (recommendation.action === "approve") return "Approve + remember sender";
2768
+ if (recommendation.action === "manual") return "Keep contact manual";
2769
+ if (recommendation.action === "reject") return "Block this sender";
2770
+ }
2771
+ if (recommendation.policy === "task") {
2772
+ if (recommendation.action === "bridge") return "Keep tasks manual";
2773
+ if (recommendation.action === "execute") return "Allow tasks from this sender";
2774
+ if (recommendation.action === "deny") return "Block tasks from this sender";
2775
+ }
2776
+ return `${recommendation.policy}:${recommendation.action}`;
2777
+ }
2778
+ function rowToRecommendation(row) {
2779
+ return {
2780
+ id: row.id,
2781
+ policy: row.policy,
2782
+ remote_did: row.remote_did,
2783
+ match: row.match,
2784
+ action: row.action,
2785
+ current_action: row.current_action,
2786
+ confidence: row.confidence,
2787
+ reason: row.reason,
2788
+ signals: JSON.parse(row.signals_json),
2789
+ status: row.status,
2790
+ first_seen_at: row.first_seen_at,
2791
+ last_seen_at: row.last_seen_at,
2792
+ updated_at: row.updated_at,
2793
+ last_state_change_at: row.last_state_change_at ?? void 0,
2794
+ applied_at: row.applied_at ?? void 0,
2795
+ dismissed_at: row.dismissed_at ?? void 0
2796
+ };
2797
+ }
2798
+ var TrustRecommendationManager = class {
2799
+ constructor(store) {
2800
+ this.store = store;
2801
+ }
2802
+ upsertRecommendation(recommendation, now, opts) {
2803
+ const existing = this.get(recommendation.id);
2804
+ const status = opts?.status ?? (opts?.preserveState !== false ? existing?.status : void 0) ?? (recommendation.current_action === recommendation.action ? "applied" : "open");
2805
+ const lastStateChangeAt = existing?.status !== status ? now : existing?.last_state_change_at ?? now;
2806
+ const appliedAt = status === "applied" ? existing?.applied_at ?? now : void 0;
2807
+ const dismissedAt = status === "dismissed" ? existing?.dismissed_at ?? now : void 0;
2808
+ this.store.getDb().prepare(`
2809
+ INSERT INTO trust_policy_recommendations (
2810
+ id, policy, remote_did, match, action, current_action, confidence, reason, signals_json,
2811
+ status, first_seen_at, last_seen_at, updated_at, last_state_change_at, applied_at, dismissed_at
2812
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2813
+ ON CONFLICT(id) DO UPDATE SET
2814
+ policy = excluded.policy,
2815
+ remote_did = excluded.remote_did,
2816
+ match = excluded.match,
2817
+ action = excluded.action,
2818
+ current_action = excluded.current_action,
2819
+ confidence = excluded.confidence,
2820
+ reason = excluded.reason,
2821
+ signals_json = excluded.signals_json,
2822
+ status = excluded.status,
2823
+ last_seen_at = excluded.last_seen_at,
2824
+ updated_at = excluded.updated_at,
2825
+ last_state_change_at = excluded.last_state_change_at,
2826
+ applied_at = COALESCE(excluded.applied_at, trust_policy_recommendations.applied_at),
2827
+ dismissed_at = COALESCE(excluded.dismissed_at, trust_policy_recommendations.dismissed_at)
2828
+ `).run(
2829
+ recommendation.id,
2830
+ recommendation.policy,
2831
+ recommendation.remote_did,
2832
+ recommendation.match,
2833
+ recommendation.action,
2834
+ recommendation.current_action,
2835
+ recommendation.confidence,
2836
+ recommendation.reason,
2837
+ JSON.stringify(recommendation.signals),
2838
+ status,
2839
+ existing?.first_seen_at ?? now,
2840
+ now,
2841
+ now,
2842
+ lastStateChangeAt,
2843
+ appliedAt ?? null,
2844
+ dismissedAt ?? null
2845
+ );
2846
+ return this.get(recommendation.id);
2847
+ }
2848
+ sync(input) {
2849
+ const now = Date.now();
2850
+ const computed = buildTrustPolicyRecommendations({
2851
+ policyDoc: input.policyDoc,
2852
+ sessions: input.sessions,
2853
+ tasks: input.tasks,
2854
+ auditEvents: input.auditEvents,
2855
+ runtimeMode: input.runtimeMode,
2856
+ limit: input.limit ?? 50
2857
+ });
2858
+ const activeIds = /* @__PURE__ */ new Set();
2859
+ const synced = [];
2860
+ for (const recommendation of computed) {
2861
+ activeIds.add(recommendation.id);
2862
+ synced.push(this.upsertRecommendation(recommendation, now));
2863
+ }
2864
+ const openRows = this.store.getDb().prepare("SELECT id FROM trust_policy_recommendations WHERE status = ?").all("open");
2865
+ for (const row of openRows) {
2866
+ if (!activeIds.has(row.id)) {
2867
+ this.store.getDb().prepare("UPDATE trust_policy_recommendations SET status = ?, updated_at = ?, last_state_change_at = ? WHERE id = ?").run("superseded", now, now, row.id);
2868
+ }
2869
+ }
2870
+ return this.list({ limit: input.limit ?? 50 });
2871
+ }
2872
+ get(id) {
2873
+ const row = this.store.getDb().prepare("SELECT * FROM trust_policy_recommendations WHERE id = ?").get(id);
2874
+ return row ? rowToRecommendation(row) : null;
2875
+ }
2876
+ list(opts) {
2877
+ const conditions = [];
2878
+ const params = [];
2879
+ if (opts?.status) {
2880
+ const statuses = Array.isArray(opts.status) ? opts.status : [opts.status];
2881
+ conditions.push(`status IN (${statuses.map(() => "?").join(",")})`);
2882
+ params.push(...statuses);
2883
+ }
2884
+ if (opts?.remoteDid) {
2885
+ conditions.push("remote_did = ?");
2886
+ params.push(opts.remoteDid);
2887
+ }
2888
+ const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
2889
+ const rows = this.store.getDb().prepare(`SELECT * FROM trust_policy_recommendations ${where} ORDER BY updated_at DESC, last_seen_at DESC LIMIT ?`).all(...params, opts?.limit ?? 50);
2890
+ return rows.map(rowToRecommendation);
2891
+ }
2892
+ apply(id) {
2893
+ const existing = this.get(id);
2894
+ if (!existing) return null;
2895
+ const now = Date.now();
2896
+ this.store.getDb().prepare("UPDATE trust_policy_recommendations SET status = ?, updated_at = ?, last_state_change_at = ?, applied_at = ? WHERE id = ?").run("applied", now, now, now, id);
2897
+ return this.get(id);
2898
+ }
2899
+ dismiss(id) {
2900
+ const existing = this.get(id);
2901
+ if (!existing) return null;
2902
+ const now = Date.now();
2903
+ this.store.getDb().prepare("UPDATE trust_policy_recommendations SET status = ?, updated_at = ?, last_state_change_at = ?, dismissed_at = ? WHERE id = ?").run("dismissed", now, now, now, id);
2904
+ return this.get(id);
2905
+ }
2906
+ reopen(id) {
2907
+ const existing = this.get(id);
2908
+ if (!existing) return null;
2909
+ const now = Date.now();
2910
+ this.store.getDb().prepare("UPDATE trust_policy_recommendations SET status = ?, updated_at = ?, last_state_change_at = ? WHERE id = ?").run("open", now, now, id);
2911
+ return this.get(id);
2912
+ }
2913
+ summarize() {
2914
+ const rows = this.store.getDb().prepare("SELECT status, COUNT(*) AS count FROM trust_policy_recommendations GROUP BY status").all();
2915
+ const byStatus = {};
2916
+ let total = 0;
2917
+ for (const row of rows) {
2918
+ byStatus[row.status] = row.count;
2919
+ total += row.count;
2920
+ }
2921
+ return { total, by_status: byStatus };
2922
+ }
2923
+ };
2924
+
2925
+ // src/a2a-adapter.ts
2926
+ import {
2927
+ A2AClient
2928
+ } from "@pingagent/a2a";
2929
+ var A2AAdapter = class {
2930
+ client;
2931
+ cachedCard = null;
2932
+ constructor(opts) {
2933
+ this.client = new A2AClient({
2934
+ agentUrl: opts.agentUrl,
2935
+ authToken: opts.authToken ? `Bearer ${opts.authToken}` : void 0,
2936
+ timeoutMs: opts.timeoutMs
2937
+ });
2938
+ }
2939
+ async getAgentCard() {
2940
+ if (!this.cachedCard) {
2941
+ this.cachedCard = await this.client.fetchAgentCard();
2942
+ }
2943
+ return this.cachedCard;
2944
+ }
2945
+ /**
2946
+ * Send a task to the external A2A agent and optionally wait for completion.
2947
+ */
2948
+ async sendTask(opts) {
2949
+ const parts = [];
2950
+ parts.push({ kind: "text", text: opts.title });
2951
+ if (opts.description) {
2952
+ parts.push({ kind: "text", text: opts.description });
2953
+ }
2954
+ if (opts.input) {
2955
+ parts.push({
2956
+ kind: "data",
2957
+ data: typeof opts.input === "object" ? opts.input : { value: opts.input }
2958
+ });
2959
+ }
2960
+ const messageId = `msg_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
2961
+ const message = {
2962
+ kind: "message",
2963
+ messageId,
2964
+ role: "user",
2965
+ parts
2966
+ };
2967
+ if (opts.wait) {
2968
+ const task = await this.client.sendAndWait(
2969
+ { message, configuration: { blocking: true } },
2970
+ { maxPollMs: opts.timeoutMs ?? 12e4 }
2971
+ );
2972
+ return this.convertTask(task);
2973
+ }
2974
+ const result = await this.client.sendMessage({ message });
2975
+ if (result.kind === "task") {
2976
+ return this.convertTask(result);
2977
+ }
2978
+ return {
2979
+ taskId: result.messageId,
2980
+ state: "completed",
2981
+ summary: this.extractText(result.parts)
2982
+ };
2983
+ }
2984
+ async getTaskStatus(taskId) {
2985
+ const task = await this.client.getTask(taskId);
2986
+ return this.convertTask(task);
2987
+ }
2988
+ async cancelTask(taskId) {
2989
+ const task = await this.client.cancelTask(taskId);
2990
+ return this.convertTask(task);
2991
+ }
2992
+ async sendText(text, opts) {
2993
+ const result = await this.client.sendText(text, { blocking: opts?.blocking });
2994
+ if (result.kind === "task") {
2995
+ return this.convertTask(result);
2996
+ }
2997
+ return {
2998
+ taskId: result.messageId,
2999
+ state: "completed",
3000
+ summary: this.extractText(result.parts)
3001
+ };
3002
+ }
3003
+ convertTask(task) {
3004
+ const summary = task.artifacts?.flatMap((a) => a.parts).filter((p) => p.kind === "text").map((p) => p.text).join("\n");
3005
+ const output = task.artifacts?.flatMap((a) => a.parts).filter((p) => p.kind === "data").map((p) => p.data);
3006
+ return {
3007
+ taskId: task.id,
3008
+ contextId: task.contextId,
3009
+ state: task.status.state,
3010
+ summary: summary || void 0,
3011
+ output: output && output.length > 0 ? output.length === 1 ? output[0] : output : void 0,
3012
+ timestamp: task.status.timestamp
3013
+ };
3014
+ }
3015
+ extractText(parts) {
3016
+ return parts.filter((p) => p.kind === "text").map((p) => p.text).join("\n") || void 0;
3017
+ }
3018
+ };
3019
+
3020
+ // src/ws-subscription.ts
3021
+ import WebSocket from "ws";
3022
+ var RECONNECT_BASE_MS = 1e3;
3023
+ var RECONNECT_MAX_MS = 3e4;
3024
+ var RECONNECT_JITTER = 0.2;
3025
+ var LIST_CONVERSATIONS_INTERVAL_MS = 6e4;
3026
+ var DEFAULT_HEARTBEAT = {
3027
+ enable: true,
3028
+ idleThresholdMs: 1e4,
3029
+ pingIntervalMs: 15e3,
3030
+ pongTimeoutMs: 1e4,
3031
+ maxMissedPongs: 2,
3032
+ tickMs: 5e3,
3033
+ jitter: 0.2
3034
+ };
3035
+ var WsSubscription = class {
3036
+ opts;
3037
+ connections = /* @__PURE__ */ new Map();
3038
+ reconnectTimers = /* @__PURE__ */ new Map();
3039
+ reconnectAttempts = /* @__PURE__ */ new Map();
3040
+ listInterval = null;
3041
+ stopped = false;
3042
+ /** Conversation IDs that were explicitly stopped (e.g. revoke); do not reconnect. */
3043
+ stoppedConversations = /* @__PURE__ */ new Set();
3044
+ lastParseErrorAtByConv = /* @__PURE__ */ new Map();
3045
+ lastFrameAtByConv = /* @__PURE__ */ new Map();
3046
+ heartbeatTimer = null;
3047
+ heartbeatStates = /* @__PURE__ */ new Map();
3048
+ constructor(opts) {
3049
+ this.opts = opts;
3050
+ }
3051
+ start() {
3052
+ this.stopped = false;
3053
+ this.connectAll();
3054
+ this.listInterval = setInterval(() => this.syncConnections(), LIST_CONVERSATIONS_INTERVAL_MS);
3055
+ const hb = this.opts.heartbeat ?? {};
3056
+ if (hb.enable ?? DEFAULT_HEARTBEAT.enable) {
3057
+ this.heartbeatTimer = setInterval(() => this.heartbeatTick(), hb.tickMs ?? DEFAULT_HEARTBEAT.tickMs);
3058
+ }
3059
+ }
3060
+ stop() {
3061
+ this.stopped = true;
3062
+ if (this.listInterval) {
3063
+ clearInterval(this.listInterval);
3064
+ this.listInterval = null;
3065
+ }
3066
+ if (this.heartbeatTimer) {
3067
+ clearInterval(this.heartbeatTimer);
3068
+ this.heartbeatTimer = null;
3069
+ }
3070
+ for (const timer of this.reconnectTimers.values()) {
3071
+ clearTimeout(timer);
3072
+ }
3073
+ this.reconnectTimers.clear();
3074
+ for (const [convId, ws] of this.connections) {
3075
+ ws.removeAllListeners();
3076
+ if (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING) {
3077
+ ws.close();
3078
+ }
3079
+ this.connections.delete(convId);
3080
+ }
3081
+ this.reconnectAttempts.clear();
3082
+ this.stoppedConversations.clear();
3083
+ this.lastParseErrorAtByConv.clear();
3084
+ this.lastFrameAtByConv.clear();
3085
+ for (const state of this.heartbeatStates.values()) {
3086
+ if (state.pongTimeout) clearTimeout(state.pongTimeout);
3087
+ }
3088
+ this.heartbeatStates.clear();
3089
+ }
3090
+ /**
3091
+ * Stop a single conversation's WebSocket and do not reconnect.
3092
+ * Used when the conversation is revoked or the client no longer wants to subscribe.
3093
+ */
3094
+ stopConversation(conversationId) {
3095
+ this.stoppedConversations.add(conversationId);
3096
+ const timer = this.reconnectTimers.get(conversationId);
3097
+ if (timer) {
3098
+ clearTimeout(timer);
3099
+ this.reconnectTimers.delete(conversationId);
3100
+ }
3101
+ const hbState = this.heartbeatStates.get(conversationId);
3102
+ if (hbState?.pongTimeout) clearTimeout(hbState.pongTimeout);
3103
+ this.heartbeatStates.delete(conversationId);
3104
+ const ws = this.connections.get(conversationId);
3105
+ if (ws) {
3106
+ ws.removeAllListeners();
3107
+ if (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING) {
3108
+ ws.close();
3109
+ }
3110
+ this.connections.delete(conversationId);
3111
+ }
3112
+ this.lastParseErrorAtByConv.delete(conversationId);
3113
+ this.lastFrameAtByConv.delete(conversationId);
3114
+ }
3115
+ wsUrl(conversationId) {
3116
+ const base = this.opts.serverUrl.replace(/^http/, "ws").replace(/\/$/, "");
3117
+ return `${base}/v1/ws?conversation_id=${encodeURIComponent(conversationId)}`;
3118
+ }
3119
+ async connectAsync(conversationId) {
3120
+ if (this.stopped || this.stoppedConversations.has(conversationId) || this.connections.has(conversationId)) return;
3121
+ const token = await Promise.resolve(this.opts.getAccessToken());
3122
+ const url = this.wsUrl(conversationId);
3123
+ const ws = new WebSocket(url, {
3124
+ headers: { Authorization: `Bearer ${token}` }
3125
+ });
3126
+ this.connections.set(conversationId, ws);
3127
+ const hb = this.opts.heartbeat ?? {};
3128
+ const hbEnabled = hb.enable ?? DEFAULT_HEARTBEAT.enable;
3129
+ if (hbEnabled) {
3130
+ const now = Date.now();
3131
+ this.heartbeatStates.set(conversationId, {
3132
+ lastRxAt: now,
3133
+ lastPingAt: 0,
3134
+ nextPingAt: now + (hb.idleThresholdMs ?? DEFAULT_HEARTBEAT.idleThresholdMs),
3135
+ missedPongs: 0,
3136
+ pongTimeout: null
3137
+ });
3138
+ }
3139
+ ws.on("open", () => {
3140
+ this.reconnectAttempts.set(conversationId, 0);
3141
+ this.opts.onOpen?.(conversationId);
3142
+ });
3143
+ ws.on("message", (data) => {
3144
+ try {
3145
+ const state = this.heartbeatStates.get(conversationId);
3146
+ if (state) {
3147
+ state.lastRxAt = Date.now();
3148
+ state.missedPongs = 0;
3149
+ if (state.pongTimeout) {
3150
+ clearTimeout(state.pongTimeout);
3151
+ state.pongTimeout = null;
3152
+ }
3153
+ }
3154
+ 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() : (
3155
+ // Fallback: try best-effort stringification
3156
+ String(data)
3157
+ );
3158
+ this.lastFrameAtByConv.set(conversationId, Date.now());
3159
+ const msg = JSON.parse(rawText);
3160
+ if (msg.type === "ws_connected") {
3161
+ this.opts.onDebug?.({
3162
+ event: "ws_connected",
3163
+ conversationId,
3164
+ detail: {
3165
+ your_did: msg.your_did,
3166
+ server_ts_ms: msg.server_ts_ms,
3167
+ conversation_id: msg.conversation_id
3168
+ }
3169
+ });
3170
+ } else if (msg.type === "ws_message" && msg.envelope) {
3171
+ const env = msg.envelope;
3172
+ const ignoreSelf = this.opts.ignoreSelfMessages ?? true;
3173
+ if (!ignoreSelf || env.sender_did !== this.opts.myDid) {
3174
+ Promise.resolve(this.opts.onMessage(env, conversationId)).catch((error) => {
3175
+ this.opts.onError?.(error instanceof Error ? error : new Error(String(error)));
3176
+ });
3177
+ } else {
3178
+ this.opts.onDebug?.({
3179
+ event: "ws_message_ignored_self",
3180
+ conversationId,
3181
+ detail: { sender_did: env.sender_did, message_id: env.message_id, seq: env.seq }
3182
+ });
3183
+ }
3184
+ } else if (msg.type === "ws_control" && msg.control) {
3185
+ this.opts.onControl?.(msg.control, conversationId);
3186
+ this.opts.onDebug?.({ event: "ws_control", conversationId, detail: msg.control });
3187
+ } else if (msg.type === "ws_receipt" && msg.receipt) {
3188
+ this.opts.onDebug?.({ event: "ws_receipt", conversationId, detail: msg.receipt });
3189
+ } else if (msg?.type) {
3190
+ this.opts.onDebug?.({ event: "ws_unknown_type", conversationId, detail: { type: msg.type } });
3191
+ }
3192
+ } catch (e) {
3193
+ const now = Date.now();
3194
+ const last = this.lastParseErrorAtByConv.get(conversationId) ?? 0;
3195
+ if (now - last > 3e4) {
3196
+ this.lastParseErrorAtByConv.set(conversationId, now);
3197
+ this.opts.onDebug?.({
3198
+ event: "ws_parse_error",
3199
+ conversationId,
3200
+ detail: {
3201
+ message: e?.message ?? String(e),
3202
+ last_frame_at_ms: this.lastFrameAtByConv.get(conversationId) ?? null
3203
+ }
3204
+ });
3205
+ }
3206
+ }
3207
+ });
3208
+ ws.on("pong", () => {
3209
+ const state = this.heartbeatStates.get(conversationId);
3210
+ if (!state) return;
3211
+ state.lastRxAt = Date.now();
3212
+ state.missedPongs = 0;
3213
+ if (state.pongTimeout) {
3214
+ clearTimeout(state.pongTimeout);
3215
+ state.pongTimeout = null;
3216
+ }
3217
+ });
3218
+ ws.on("close", () => {
3219
+ this.connections.delete(conversationId);
3220
+ const state = this.heartbeatStates.get(conversationId);
3221
+ if (state?.pongTimeout) clearTimeout(state.pongTimeout);
3222
+ this.heartbeatStates.delete(conversationId);
3223
+ if (!this.stopped && !this.stoppedConversations.has(conversationId)) {
3224
+ this.scheduleReconnect(conversationId);
3225
+ }
3226
+ });
3227
+ ws.on("error", (err) => {
3228
+ this.opts.onError?.(err);
3229
+ });
3230
+ }
3231
+ heartbeatTick() {
3232
+ const hb = this.opts.heartbeat ?? {};
3233
+ const hbEnabled = hb.enable ?? DEFAULT_HEARTBEAT.enable;
3234
+ if (!hbEnabled) return;
3235
+ const idleThresholdMs = hb.idleThresholdMs ?? DEFAULT_HEARTBEAT.idleThresholdMs;
3236
+ const pingIntervalMs = hb.pingIntervalMs ?? DEFAULT_HEARTBEAT.pingIntervalMs;
3237
+ const pongTimeoutMs = hb.pongTimeoutMs ?? DEFAULT_HEARTBEAT.pongTimeoutMs;
3238
+ const maxMissedPongs = hb.maxMissedPongs ?? DEFAULT_HEARTBEAT.maxMissedPongs;
3239
+ const jitter = hb.jitter ?? DEFAULT_HEARTBEAT.jitter;
3240
+ const now = Date.now();
3241
+ for (const [conversationId, ws] of this.connections) {
3242
+ if (ws.readyState !== WebSocket.OPEN) continue;
3243
+ const state = this.heartbeatStates.get(conversationId);
3244
+ if (!state) continue;
3245
+ if (state.pongTimeout) continue;
3246
+ const idleFor = now - state.lastRxAt;
3247
+ if (idleFor < idleThresholdMs) continue;
3248
+ if (now < state.nextPingAt) continue;
3249
+ if (state.lastPingAt !== 0 && now - state.lastPingAt < pingIntervalMs * 0.5) {
3250
+ continue;
3251
+ }
3252
+ try {
3253
+ ws.send(JSON.stringify({ type: "hb" }));
3254
+ } catch {
3255
+ }
3256
+ ws.ping();
3257
+ state.lastPingAt = now;
3258
+ const jitterFactor = 1 + (Math.random() - 0.5) * 2 * jitter;
3259
+ state.nextPingAt = now + Math.max(1e3, pingIntervalMs * jitterFactor);
3260
+ state.pongTimeout = setTimeout(() => {
3261
+ state.missedPongs += 1;
3262
+ state.pongTimeout = null;
3263
+ if (state.missedPongs >= maxMissedPongs) {
3264
+ try {
3265
+ ws.close(1001, "pong timeout");
3266
+ } catch {
3267
+ }
3268
+ }
3269
+ }, pongTimeoutMs);
3270
+ }
3271
+ }
3272
+ scheduleReconnect(conversationId) {
3273
+ if (this.reconnectTimers.has(conversationId)) return;
3274
+ const attempt = this.reconnectAttempts.get(conversationId) ?? 0;
3275
+ this.reconnectAttempts.set(conversationId, attempt + 1);
3276
+ const tryConnect = () => {
3277
+ this.reconnectTimers.delete(conversationId);
3278
+ if (this.stopped) return;
3279
+ void this.connectAsync(conversationId);
3280
+ };
3281
+ const delay = Math.min(
3282
+ RECONNECT_BASE_MS * Math.pow(2, attempt) + (Math.random() - 0.5) * RECONNECT_JITTER * RECONNECT_BASE_MS,
3283
+ RECONNECT_MAX_MS
3284
+ );
3285
+ const timer = setTimeout(tryConnect, delay);
3286
+ this.reconnectTimers.set(conversationId, timer);
3287
+ }
3288
+ isSubscribableConversationType(type) {
3289
+ return type === "dm" || type === "pending_dm" || type === "channel" || type === "group";
3290
+ }
3291
+ async connectAll() {
3292
+ try {
3293
+ const convos = await this.opts.listConversations();
3294
+ const subscribable = convos.filter((c) => this.isSubscribableConversationType(c.type));
3295
+ for (const c of subscribable) {
3296
+ void this.connectAsync(c.conversation_id);
3297
+ }
3298
+ } catch (err) {
3299
+ this.opts.onError?.(err instanceof Error ? err : new Error(String(err)));
3300
+ }
3301
+ }
3302
+ async syncConnections() {
3303
+ if (this.stopped) return;
3304
+ try {
3305
+ const convos = await this.opts.listConversations();
3306
+ const subscribableIds = new Set(
3307
+ convos.filter((c) => this.isSubscribableConversationType(c.type)).map((c) => c.conversation_id)
3308
+ );
3309
+ for (const convId of subscribableIds) {
3310
+ if (!this.stoppedConversations.has(convId) && !this.connections.has(convId)) {
3311
+ void this.connectAsync(convId);
3312
+ }
3313
+ }
3314
+ for (const convId of this.connections.keys()) {
3315
+ if (!subscribableIds.has(convId) || this.stoppedConversations.has(convId)) {
3316
+ const ws = this.connections.get(convId);
3317
+ if (ws) {
3318
+ ws.removeAllListeners();
3319
+ ws.close();
3320
+ this.connections.delete(convId);
3321
+ }
3322
+ }
3323
+ }
3324
+ } catch {
3325
+ }
3326
+ }
3327
+ };
3328
+
3329
+ // src/openclaw-session-bindings.ts
3330
+ import * as fs3 from "fs";
3331
+ import * as os2 from "os";
3332
+ import * as path4 from "path";
3333
+ function resolvePath(p) {
3334
+ if (!p) return null;
3335
+ if (p.startsWith("~")) return path4.join(os2.homedir(), p.slice(1));
3336
+ return path4.resolve(p);
3337
+ }
3338
+ function ensureDirForFile(filePath) {
3339
+ const dir = path4.dirname(filePath);
3340
+ if (!fs3.existsSync(dir)) fs3.mkdirSync(dir, { recursive: true });
3341
+ }
3342
+ function getDefaultActiveSessionFile() {
3343
+ return path4.join(os2.homedir(), ".openclaw", "workspace", "ACTIVE_GROUP.md");
3344
+ }
3345
+ function getDefaultIngressStorePath() {
3346
+ return path4.join(os2.homedir(), ".openclaw", "pingagent-im-ingress", "messages.jsonl");
3347
+ }
3348
+ function getDefaultSessionMapPath(storePath) {
3349
+ const base = resolvePath(storePath) || getDefaultIngressStorePath();
3350
+ return path4.join(path4.dirname(base), "session-map.json");
3351
+ }
3352
+ function getDefaultSessionBindingAlertsPath(storePath) {
3353
+ const base = resolvePath(storePath) || getDefaultIngressStorePath();
3354
+ return path4.join(path4.dirname(base), "session-map-alerts.json");
3355
+ }
3356
+ function getActiveSessionFilePath() {
3357
+ return resolvePath(process.env.IM_INGRESS_ACTIVE_GROUP_FILE?.trim()) || getDefaultActiveSessionFile();
3358
+ }
3359
+ function getSessionMapFilePath() {
3360
+ return resolvePath(process.env.IM_INGRESS_SESSION_MAP_FILE?.trim()) || getDefaultSessionMapPath(process.env.IM_INGRESS_STORE_PATH?.trim());
3361
+ }
3362
+ function getSessionBindingAlertsFilePath() {
3363
+ return resolvePath(process.env.IM_INGRESS_SESSION_BINDING_ALERTS_FILE?.trim()) || getDefaultSessionBindingAlertsPath(process.env.IM_INGRESS_STORE_PATH?.trim());
3364
+ }
3365
+ function readCurrentActiveSessionKey(filePath = getActiveSessionFilePath()) {
3366
+ try {
3367
+ if (!fs3.existsSync(filePath)) return null;
3368
+ const raw = fs3.readFileSync(filePath, "utf-8");
3369
+ const first = String(raw ?? "").split(/\r?\n/).map((s) => s.trim()).filter(Boolean)[0];
3370
+ return first || null;
3371
+ } catch {
3372
+ return null;
3373
+ }
3374
+ }
3375
+ function readSessionBindings(filePath = getSessionMapFilePath()) {
3376
+ try {
3377
+ if (!fs3.existsSync(filePath)) return [];
3378
+ const raw = JSON.parse(fs3.readFileSync(filePath, "utf-8"));
3379
+ return Object.entries(raw ?? {}).map(([conversation_id, session_key]) => ({
3380
+ conversation_id: String(conversation_id ?? "").trim(),
3381
+ session_key: String(session_key ?? "").trim()
3382
+ })).filter((row) => row.conversation_id && row.session_key).sort((a, b) => a.conversation_id.localeCompare(b.conversation_id));
3383
+ } catch {
3384
+ return [];
3385
+ }
3386
+ }
3387
+ function writeSessionBindings(entries, filePath = getSessionMapFilePath()) {
3388
+ ensureDirForFile(filePath);
3389
+ const obj = Object.fromEntries(
3390
+ entries.filter((row) => row.conversation_id && row.session_key).map((row) => [row.conversation_id, row.session_key])
3391
+ );
3392
+ fs3.writeFileSync(filePath, JSON.stringify(obj, null, 2), "utf-8");
3393
+ return filePath;
3394
+ }
3395
+ function setSessionBinding(conversationId, sessionKey, filePath = getSessionMapFilePath()) {
3396
+ const entries = readSessionBindings(filePath).filter((row) => row.conversation_id !== conversationId);
3397
+ const binding = { conversation_id: conversationId, session_key: sessionKey };
3398
+ entries.push(binding);
3399
+ writeSessionBindings(entries, filePath);
3400
+ clearSessionBindingAlert(conversationId);
3401
+ return { path: filePath, binding };
3402
+ }
3403
+ function removeSessionBinding(conversationId, filePath = getSessionMapFilePath()) {
3404
+ const entries = readSessionBindings(filePath);
3405
+ const next = entries.filter((row) => row.conversation_id !== conversationId);
3406
+ const removed = next.length !== entries.length;
3407
+ if (removed) writeSessionBindings(next, filePath);
3408
+ clearSessionBindingAlert(conversationId);
3409
+ return { path: filePath, removed };
3410
+ }
3411
+ function readSessionBindingAlerts(filePath = getSessionBindingAlertsFilePath()) {
3412
+ try {
3413
+ if (!fs3.existsSync(filePath)) return [];
3414
+ const raw = JSON.parse(fs3.readFileSync(filePath, "utf-8"));
3415
+ return Object.entries(raw ?? {}).map(([conversation_id, value]) => {
3416
+ const row = value;
3417
+ return {
3418
+ conversation_id: String(conversation_id ?? "").trim(),
3419
+ session_key: String(row?.session_key ?? "").trim(),
3420
+ status: "missing_session",
3421
+ message: String(row?.message ?? "").trim(),
3422
+ detected_at: String(row?.detected_at ?? "").trim()
3423
+ };
3424
+ }).filter((row) => row.conversation_id && row.session_key && row.message).sort((a, b) => a.conversation_id.localeCompare(b.conversation_id));
3425
+ } catch {
3426
+ return [];
3427
+ }
3428
+ }
3429
+ function writeSessionBindingAlerts(entries, filePath = getSessionBindingAlertsFilePath()) {
3430
+ ensureDirForFile(filePath);
3431
+ const obj = Object.fromEntries(
3432
+ entries.map((row) => [row.conversation_id, {
3433
+ session_key: row.session_key,
3434
+ status: row.status,
3435
+ message: row.message,
3436
+ detected_at: row.detected_at
3437
+ }])
3438
+ );
3439
+ fs3.writeFileSync(filePath, JSON.stringify(obj, null, 2), "utf-8");
3440
+ return filePath;
3441
+ }
3442
+ function upsertSessionBindingAlert(alert, filePath = getSessionBindingAlertsFilePath()) {
3443
+ const entries = readSessionBindingAlerts(filePath).filter((row) => row.conversation_id !== alert.conversation_id);
3444
+ entries.push(alert);
3445
+ writeSessionBindingAlerts(entries, filePath);
3446
+ return { path: filePath, alert };
3447
+ }
3448
+ function clearSessionBindingAlert(conversationId, filePath = getSessionBindingAlertsFilePath()) {
3449
+ const entries = readSessionBindingAlerts(filePath);
3450
+ const next = entries.filter((row) => row.conversation_id !== conversationId);
3451
+ const removed = next.length !== entries.length;
3452
+ if (removed) writeSessionBindingAlerts(next, filePath);
3453
+ return { path: filePath, removed };
3454
+ }
3455
+
3456
+ // src/openclaw-runtime.ts
3457
+ import * as fs4 from "fs";
3458
+ import * as os3 from "os";
3459
+ import * as path5 from "path";
3460
+ function resolvePath2(p) {
3461
+ if (!p) return null;
3462
+ if (p.startsWith("~")) return path5.join(os3.homedir(), p.slice(1));
3463
+ return path5.resolve(p);
3464
+ }
3465
+ function getDefaultIngressRuntimeStatusPath(storePath) {
3466
+ const base = resolvePath2(storePath) || path5.join(os3.homedir(), ".openclaw", "pingagent-im-ingress", "messages.jsonl");
3467
+ return path5.join(path5.dirname(base), "runtime-status.json");
3468
+ }
3469
+ function getIngressRuntimeStatusFilePath() {
3470
+ return resolvePath2(process.env.IM_INGRESS_RUNTIME_STATUS_FILE?.trim()) || getDefaultIngressRuntimeStatusPath(process.env.IM_INGRESS_STORE_PATH?.trim());
3471
+ }
3472
+ function readIngressRuntimeStatus(filePath = getIngressRuntimeStatusFilePath()) {
3473
+ try {
3474
+ if (!fs4.existsSync(filePath)) return null;
3475
+ const raw = JSON.parse(fs4.readFileSync(filePath, "utf-8"));
3476
+ return {
3477
+ receive_mode: raw?.receive_mode === "polling_degraded" ? "polling_degraded" : "webhook",
3478
+ reason: raw?.reason ? String(raw.reason) : null,
3479
+ hooks_url: raw?.hooks_url ? String(raw.hooks_url) : null,
3480
+ hooks_last_error: raw?.hooks_last_error ? String(raw.hooks_last_error) : null,
3481
+ hooks_last_error_at: raw?.hooks_last_error_at ? String(raw.hooks_last_error_at) : null,
3482
+ hooks_last_probe_ok_at: raw?.hooks_last_probe_ok_at ? String(raw.hooks_last_probe_ok_at) : null,
3483
+ fallback_last_injected_at: raw?.fallback_last_injected_at ? String(raw.fallback_last_injected_at) : null,
3484
+ fallback_last_injected_conversation_id: raw?.fallback_last_injected_conversation_id ? String(raw.fallback_last_injected_conversation_id) : null,
3485
+ active_work_session: raw?.active_work_session ? String(raw.active_work_session) : null,
3486
+ sessions_send_available: raw?.sessions_send_available === true,
3487
+ hooks_fix_hint: raw?.hooks_fix_hint ? String(raw.hooks_fix_hint) : null,
3488
+ status_updated_at: raw?.status_updated_at ? String(raw.status_updated_at) : null
3489
+ };
3490
+ } catch {
3491
+ return null;
3492
+ }
3493
+ }
3494
+
3495
+ export {
3496
+ HttpTransport,
3497
+ getRootDir,
3498
+ getProfile,
3499
+ getIdentityPath,
3500
+ getStorePath,
3501
+ ensureIdentityEncryptionKeys,
3502
+ generateIdentity,
3503
+ identityExists,
3504
+ loadIdentity,
3505
+ saveIdentity,
3506
+ updateStoredToken,
3507
+ ContactManager,
3508
+ HistoryManager,
3509
+ previewFromPayload,
3510
+ buildSessionKey,
3511
+ SessionManager,
3512
+ buildSessionSummaryHandoffText,
3513
+ SessionSummaryManager,
3514
+ TaskThreadManager,
3515
+ TaskHandoffManager,
3516
+ normalizeCapabilityCard,
3517
+ capabilityCardToLegacyCapabilities,
3518
+ formatCapabilityCardSummary,
3519
+ isEncryptedPayload,
3520
+ shouldEncryptConversationPayload,
3521
+ encryptPayloadForRecipients,
3522
+ decryptPayloadForIdentity,
3523
+ PingAgentClient,
3524
+ ensureTokenValid,
3525
+ LocalStore,
3526
+ defaultTrustPolicyDoc,
3527
+ normalizeTrustPolicyDoc,
3528
+ matchesTrustPolicyRule,
3529
+ decideContactPolicy,
3530
+ decideTaskPolicy,
3531
+ TrustPolicyAuditManager,
3532
+ buildTrustPolicyRecommendations,
3533
+ upsertTrustPolicyRecommendation,
3534
+ summarizeTrustPolicyAudit,
3535
+ getTrustRecommendationActionLabel,
3536
+ TrustRecommendationManager,
3537
+ A2AAdapter,
3538
+ WsSubscription,
3539
+ getActiveSessionFilePath,
3540
+ getSessionMapFilePath,
3541
+ getSessionBindingAlertsFilePath,
3542
+ readCurrentActiveSessionKey,
3543
+ readSessionBindings,
3544
+ writeSessionBindings,
3545
+ setSessionBinding,
3546
+ removeSessionBinding,
3547
+ readSessionBindingAlerts,
3548
+ writeSessionBindingAlerts,
3549
+ upsertSessionBindingAlert,
3550
+ clearSessionBindingAlert,
3551
+ getIngressRuntimeStatusFilePath,
3552
+ readIngressRuntimeStatus
3553
+ };