@pingagent/sdk 0.1.2 → 0.1.4

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,1350 @@
1
+ // src/client.ts
2
+ import { SCHEMA_TASK, SCHEMA_CONTACT_REQUEST, SCHEMA_RESULT, SCHEMA_RECEIPT, SCHEMA_TEXT } from "@pingagent/schemas";
3
+ import {
4
+ buildUnsignedEnvelope,
5
+ signEnvelope
6
+ } from "@pingagent/protocol";
7
+
8
+ // src/transport.ts
9
+ import { ErrorCode } from "@pingagent/schemas";
10
+ var HttpTransport = class {
11
+ serverUrl;
12
+ accessToken;
13
+ maxRetries;
14
+ onTokenRefreshed;
15
+ constructor(opts) {
16
+ this.serverUrl = opts.serverUrl.replace(/\/$/, "");
17
+ this.accessToken = opts.accessToken;
18
+ this.maxRetries = opts.maxRetries ?? 3;
19
+ this.onTokenRefreshed = opts.onTokenRefreshed;
20
+ }
21
+ setToken(token) {
22
+ this.accessToken = token;
23
+ }
24
+ /** Fetch a URL with Bearer auth (e.g. artifact upload/download). */
25
+ async fetchWithAuth(url, options = {}) {
26
+ const headers = { Authorization: `Bearer ${this.accessToken}` };
27
+ if (options.contentType) headers["Content-Type"] = options.contentType;
28
+ const res = await fetch(url, {
29
+ method: options.method ?? "GET",
30
+ headers,
31
+ body: options.body ?? void 0
32
+ });
33
+ if (!res.ok) {
34
+ const text = await res.text();
35
+ throw new Error(`Request failed (${res.status}): ${text.slice(0, 200)}`);
36
+ }
37
+ return res.arrayBuffer();
38
+ }
39
+ async request(method, path4, body, skipAuth = false) {
40
+ const url = `${this.serverUrl}${path4}`;
41
+ const headers = {
42
+ "Content-Type": "application/json"
43
+ };
44
+ if (!skipAuth) {
45
+ headers["Authorization"] = `Bearer ${this.accessToken}`;
46
+ }
47
+ let lastError = null;
48
+ const delays = [1e3, 2e3, 4e3];
49
+ for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
50
+ try {
51
+ const res = await fetch(url, {
52
+ method,
53
+ headers,
54
+ body: body ? JSON.stringify(body) : void 0
55
+ });
56
+ const text = await res.text();
57
+ let data;
58
+ try {
59
+ data = text ? JSON.parse(text) : {};
60
+ } catch {
61
+ throw new Error(`Server returned non-JSON (${res.status}): ${text.slice(0, 200)}`);
62
+ }
63
+ if (res.status === 401 && data.error?.code === ErrorCode.TOKEN_EXPIRED && attempt === 0) {
64
+ const refreshed = await this.refreshToken();
65
+ if (refreshed) {
66
+ headers["Authorization"] = `Bearer ${this.accessToken}`;
67
+ continue;
68
+ }
69
+ }
70
+ if (res.status === 429 && data.error?.retry_after_ms) {
71
+ await sleep(data.error.retry_after_ms);
72
+ continue;
73
+ }
74
+ if (res.status >= 500 && attempt < this.maxRetries) {
75
+ await sleep(delays[attempt] ?? 4e3);
76
+ continue;
77
+ }
78
+ return data;
79
+ } catch (e) {
80
+ lastError = e;
81
+ if (attempt < this.maxRetries) {
82
+ await sleep(delays[attempt] ?? 4e3);
83
+ }
84
+ }
85
+ }
86
+ throw lastError ?? new Error("Request failed after retries");
87
+ }
88
+ async refreshToken() {
89
+ try {
90
+ const res = await fetch(`${this.serverUrl}/v1/auth/refresh`, {
91
+ method: "POST",
92
+ headers: { "Content-Type": "application/json" },
93
+ body: JSON.stringify({ access_token: this.accessToken })
94
+ });
95
+ if (!res.ok) return false;
96
+ const text = await res.text();
97
+ let data;
98
+ try {
99
+ data = text ? JSON.parse(text) : {};
100
+ } catch {
101
+ return false;
102
+ }
103
+ if (!data.ok || !data.data) return false;
104
+ this.accessToken = data.data.access_token;
105
+ const expiresAt = Date.now() + data.data.expires_ms;
106
+ this.onTokenRefreshed?.(data.data.access_token, expiresAt);
107
+ return true;
108
+ } catch {
109
+ return false;
110
+ }
111
+ }
112
+ };
113
+ function sleep(ms) {
114
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
115
+ }
116
+
117
+ // src/contacts.ts
118
+ function rowToContact(row) {
119
+ return {
120
+ did: row.did,
121
+ alias: row.alias ?? void 0,
122
+ display_name: row.display_name ?? void 0,
123
+ notes: row.notes ?? void 0,
124
+ conversation_id: row.conversation_id ?? void 0,
125
+ trusted: row.trusted === 1,
126
+ added_at: row.added_at,
127
+ last_message_at: row.last_message_at ?? void 0,
128
+ tags: row.tags ? JSON.parse(row.tags) : void 0
129
+ };
130
+ }
131
+ var ContactManager = class {
132
+ store;
133
+ constructor(store) {
134
+ this.store = store;
135
+ }
136
+ add(contact) {
137
+ const db = this.store.getDb();
138
+ const now = contact.added_at ?? Date.now();
139
+ db.prepare(`
140
+ INSERT INTO contacts (did, alias, display_name, notes, conversation_id, trusted, added_at, last_message_at, tags)
141
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
142
+ ON CONFLICT(did) DO UPDATE SET
143
+ alias = COALESCE(excluded.alias, contacts.alias),
144
+ display_name = COALESCE(excluded.display_name, contacts.display_name),
145
+ notes = COALESCE(excluded.notes, contacts.notes),
146
+ conversation_id = COALESCE(excluded.conversation_id, contacts.conversation_id),
147
+ trusted = excluded.trusted,
148
+ last_message_at = COALESCE(excluded.last_message_at, contacts.last_message_at),
149
+ tags = COALESCE(excluded.tags, contacts.tags)
150
+ `).run(
151
+ contact.did,
152
+ contact.alias ?? null,
153
+ contact.display_name ?? null,
154
+ contact.notes ?? null,
155
+ contact.conversation_id ?? null,
156
+ contact.trusted ? 1 : 0,
157
+ now,
158
+ contact.last_message_at ?? null,
159
+ contact.tags ? JSON.stringify(contact.tags) : null
160
+ );
161
+ return { ...contact, added_at: now };
162
+ }
163
+ remove(did) {
164
+ const result = this.store.getDb().prepare("DELETE FROM contacts WHERE did = ?").run(did);
165
+ return result.changes > 0;
166
+ }
167
+ get(did) {
168
+ const row = this.store.getDb().prepare("SELECT * FROM contacts WHERE did = ?").get(did);
169
+ return row ? rowToContact(row) : null;
170
+ }
171
+ update(did, updates) {
172
+ const existing = this.get(did);
173
+ if (!existing) return null;
174
+ const fields = [];
175
+ const values = [];
176
+ if (updates.alias !== void 0) {
177
+ fields.push("alias = ?");
178
+ values.push(updates.alias);
179
+ }
180
+ if (updates.display_name !== void 0) {
181
+ fields.push("display_name = ?");
182
+ values.push(updates.display_name);
183
+ }
184
+ if (updates.notes !== void 0) {
185
+ fields.push("notes = ?");
186
+ values.push(updates.notes);
187
+ }
188
+ if (updates.conversation_id !== void 0) {
189
+ fields.push("conversation_id = ?");
190
+ values.push(updates.conversation_id);
191
+ }
192
+ if (updates.trusted !== void 0) {
193
+ fields.push("trusted = ?");
194
+ values.push(updates.trusted ? 1 : 0);
195
+ }
196
+ if (updates.last_message_at !== void 0) {
197
+ fields.push("last_message_at = ?");
198
+ values.push(updates.last_message_at);
199
+ }
200
+ if (updates.tags !== void 0) {
201
+ fields.push("tags = ?");
202
+ values.push(JSON.stringify(updates.tags));
203
+ }
204
+ if (fields.length === 0) return existing;
205
+ values.push(did);
206
+ this.store.getDb().prepare(`UPDATE contacts SET ${fields.join(", ")} WHERE did = ?`).run(...values);
207
+ return this.get(did);
208
+ }
209
+ list(opts) {
210
+ const conditions = [];
211
+ const params = [];
212
+ if (opts?.trusted !== void 0) {
213
+ conditions.push("trusted = ?");
214
+ params.push(opts.trusted ? 1 : 0);
215
+ }
216
+ if (opts?.tag) {
217
+ conditions.push("tags LIKE ?");
218
+ params.push(`%"${opts.tag}"%`);
219
+ }
220
+ const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
221
+ const limit = opts?.limit ? `LIMIT ${opts.limit}` : "";
222
+ const offset = opts?.offset ? `OFFSET ${opts.offset}` : "";
223
+ const rows = this.store.getDb().prepare(`SELECT * FROM contacts ${where} ORDER BY added_at DESC ${limit} ${offset}`).all(...params);
224
+ return rows.map(rowToContact);
225
+ }
226
+ search(query) {
227
+ const pattern = `%${query}%`;
228
+ const rows = this.store.getDb().prepare(`
229
+ SELECT * FROM contacts
230
+ WHERE did LIKE ? OR alias LIKE ? OR display_name LIKE ? OR notes LIKE ?
231
+ ORDER BY added_at DESC
232
+ `).all(pattern, pattern, pattern, pattern);
233
+ return rows.map(rowToContact);
234
+ }
235
+ export(format = "json") {
236
+ const contacts = this.list();
237
+ if (format === "csv") {
238
+ const header = "did,alias,display_name,notes,conversation_id,trusted,added_at,last_message_at,tags";
239
+ const rows = contacts.map(
240
+ (c) => [
241
+ c.did,
242
+ c.alias ?? "",
243
+ c.display_name ?? "",
244
+ c.notes ?? "",
245
+ c.conversation_id ?? "",
246
+ c.trusted,
247
+ c.added_at,
248
+ c.last_message_at ?? "",
249
+ c.tags ? JSON.stringify(c.tags) : ""
250
+ ].map((v) => `"${String(v).replace(/"/g, '""')}"`).join(",")
251
+ );
252
+ return [header, ...rows].join("\n");
253
+ }
254
+ return JSON.stringify(contacts, null, 2);
255
+ }
256
+ import(data, format = "json") {
257
+ let imported = 0;
258
+ let skipped = 0;
259
+ if (format === "json") {
260
+ const contacts = JSON.parse(data);
261
+ for (const c of contacts) {
262
+ try {
263
+ this.add(c);
264
+ imported++;
265
+ } catch {
266
+ skipped++;
267
+ }
268
+ }
269
+ } else {
270
+ const lines = data.split("\n").filter((l) => l.trim());
271
+ for (let i = 1; i < lines.length; i++) {
272
+ try {
273
+ const cols = parseCsvLine(lines[i]);
274
+ this.add({
275
+ did: cols[0],
276
+ alias: cols[1] || void 0,
277
+ display_name: cols[2] || void 0,
278
+ notes: cols[3] || void 0,
279
+ conversation_id: cols[4] || void 0,
280
+ trusted: cols[5] === "1" || cols[5] === "true",
281
+ added_at: parseInt(cols[6]) || Date.now(),
282
+ last_message_at: cols[7] ? parseInt(cols[7]) : void 0,
283
+ tags: cols[8] ? JSON.parse(cols[8]) : void 0
284
+ });
285
+ imported++;
286
+ } catch {
287
+ skipped++;
288
+ }
289
+ }
290
+ }
291
+ return { imported, skipped };
292
+ }
293
+ };
294
+ function parseCsvLine(line) {
295
+ const result = [];
296
+ let current = "";
297
+ let inQuotes = false;
298
+ for (let i = 0; i < line.length; i++) {
299
+ const ch = line[i];
300
+ if (inQuotes) {
301
+ if (ch === '"' && line[i + 1] === '"') {
302
+ current += '"';
303
+ i++;
304
+ } else if (ch === '"') {
305
+ inQuotes = false;
306
+ } else {
307
+ current += ch;
308
+ }
309
+ } else {
310
+ if (ch === '"') {
311
+ inQuotes = true;
312
+ } else if (ch === ",") {
313
+ result.push(current);
314
+ current = "";
315
+ } else {
316
+ current += ch;
317
+ }
318
+ }
319
+ }
320
+ result.push(current);
321
+ return result;
322
+ }
323
+
324
+ // src/history.ts
325
+ function rowToMessage(row) {
326
+ return {
327
+ conversation_id: row.conversation_id,
328
+ message_id: row.message_id,
329
+ seq: row.seq ?? void 0,
330
+ sender_did: row.sender_did,
331
+ schema: row.schema,
332
+ payload: JSON.parse(row.payload),
333
+ ts_ms: row.ts_ms,
334
+ direction: row.direction
335
+ };
336
+ }
337
+ var HistoryManager = class {
338
+ store;
339
+ constructor(store) {
340
+ this.store = store;
341
+ }
342
+ save(messages) {
343
+ const db = this.store.getDb();
344
+ const stmt = db.prepare(`
345
+ INSERT INTO messages (conversation_id, message_id, seq, sender_did, schema, payload, ts_ms, direction)
346
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
347
+ ON CONFLICT(message_id) DO UPDATE SET
348
+ seq = COALESCE(excluded.seq, messages.seq),
349
+ payload = excluded.payload,
350
+ ts_ms = excluded.ts_ms
351
+ `);
352
+ let count = 0;
353
+ const tx = db.transaction(() => {
354
+ for (const msg of messages) {
355
+ stmt.run(
356
+ msg.conversation_id,
357
+ msg.message_id,
358
+ msg.seq ?? null,
359
+ msg.sender_did,
360
+ msg.schema,
361
+ JSON.stringify(msg.payload),
362
+ msg.ts_ms,
363
+ msg.direction
364
+ );
365
+ count++;
366
+ }
367
+ });
368
+ tx();
369
+ return count;
370
+ }
371
+ list(conversationId, opts) {
372
+ const conditions = ["conversation_id = ?"];
373
+ const params = [conversationId];
374
+ if (opts?.beforeSeq !== void 0) {
375
+ conditions.push("seq < ?");
376
+ params.push(opts.beforeSeq);
377
+ }
378
+ if (opts?.afterSeq !== void 0) {
379
+ conditions.push("seq > ?");
380
+ params.push(opts.afterSeq);
381
+ }
382
+ if (opts?.beforeTsMs !== void 0) {
383
+ conditions.push("ts_ms < ?");
384
+ params.push(opts.beforeTsMs);
385
+ }
386
+ if (opts?.afterTsMs !== void 0) {
387
+ conditions.push("ts_ms > ?");
388
+ params.push(opts.afterTsMs);
389
+ }
390
+ const limit = opts?.limit ?? 100;
391
+ const rows = this.store.getDb().prepare(`SELECT * FROM messages WHERE ${conditions.join(" AND ")} ORDER BY COALESCE(seq, ts_ms) ASC LIMIT ?`).all(...params, limit);
392
+ return rows.map(rowToMessage);
393
+ }
394
+ /**
395
+ * List the most recent N messages *before* a seq (paging older history).
396
+ * Only compares rows where seq is not null.
397
+ */
398
+ listBeforeSeq(conversationId, beforeSeq, limit) {
399
+ const rows = this.store.getDb().prepare(
400
+ `SELECT * FROM messages
401
+ WHERE conversation_id = ? AND seq IS NOT NULL AND seq < ?
402
+ ORDER BY seq DESC
403
+ LIMIT ?`
404
+ ).all(conversationId, beforeSeq, limit);
405
+ return rows.map(rowToMessage).reverse();
406
+ }
407
+ /**
408
+ * List the most recent N messages *before* a timestamp (paging older history).
409
+ */
410
+ listBeforeTs(conversationId, beforeTsMs, limit) {
411
+ const rows = this.store.getDb().prepare(
412
+ `SELECT * FROM messages
413
+ WHERE conversation_id = ? AND ts_ms < ?
414
+ ORDER BY ts_ms DESC
415
+ LIMIT ?`
416
+ ).all(conversationId, beforeTsMs, limit);
417
+ return rows.map(rowToMessage).reverse();
418
+ }
419
+ /** Returns the N most recent messages (chronological order, oldest to newest of those N). */
420
+ listRecent(conversationId, limit) {
421
+ const rows = this.store.getDb().prepare(
422
+ `SELECT * FROM messages WHERE conversation_id = ? ORDER BY COALESCE(seq, ts_ms) DESC LIMIT ?`
423
+ ).all(conversationId, limit);
424
+ return rows.map(rowToMessage).reverse();
425
+ }
426
+ search(query, opts) {
427
+ const conditions = ["payload LIKE ?"];
428
+ const params = [`%${query}%`];
429
+ if (opts?.conversationId) {
430
+ conditions.push("conversation_id = ?");
431
+ params.push(opts.conversationId);
432
+ }
433
+ const limit = opts?.limit ?? 50;
434
+ const rows = this.store.getDb().prepare(`SELECT * FROM messages WHERE ${conditions.join(" AND ")} ORDER BY ts_ms DESC LIMIT ?`).all(...params, limit);
435
+ return rows.map(rowToMessage);
436
+ }
437
+ delete(conversationId) {
438
+ const result = this.store.getDb().prepare("DELETE FROM messages WHERE conversation_id = ?").run(conversationId);
439
+ this.store.getDb().prepare("DELETE FROM sync_state WHERE conversation_id = ?").run(conversationId);
440
+ return result.changes;
441
+ }
442
+ listConversations() {
443
+ const rows = this.store.getDb().prepare(`
444
+ SELECT conversation_id, COUNT(*) as message_count, MAX(ts_ms) as last_message_at
445
+ FROM messages
446
+ GROUP BY conversation_id
447
+ ORDER BY last_message_at DESC
448
+ `).all();
449
+ return rows;
450
+ }
451
+ getLastSyncedSeq(conversationId) {
452
+ const row = this.store.getDb().prepare("SELECT last_synced_seq FROM sync_state WHERE conversation_id = ?").get(conversationId);
453
+ return row?.last_synced_seq ?? 0;
454
+ }
455
+ setLastSyncedSeq(conversationId, seq) {
456
+ this.store.getDb().prepare(`
457
+ INSERT INTO sync_state (conversation_id, last_synced_seq, last_synced_at)
458
+ VALUES (?, ?, ?)
459
+ ON CONFLICT(conversation_id) DO UPDATE SET last_synced_seq = excluded.last_synced_seq, last_synced_at = excluded.last_synced_at
460
+ `).run(conversationId, seq, Date.now());
461
+ }
462
+ export(opts) {
463
+ const format = opts?.format ?? "json";
464
+ let messages;
465
+ if (opts?.conversationId) {
466
+ messages = this.list(opts.conversationId, { limit: 1e5 });
467
+ } else {
468
+ const rows = this.store.getDb().prepare("SELECT * FROM messages ORDER BY ts_ms ASC").all();
469
+ messages = rows.map(rowToMessage);
470
+ }
471
+ if (format === "csv") {
472
+ const header = "conversation_id,message_id,seq,sender_did,schema,payload,ts_ms,direction";
473
+ const lines = messages.map(
474
+ (m) => [
475
+ m.conversation_id,
476
+ m.message_id,
477
+ m.seq ?? "",
478
+ m.sender_did,
479
+ m.schema,
480
+ JSON.stringify(m.payload),
481
+ m.ts_ms,
482
+ m.direction
483
+ ].map((v) => `"${String(v).replace(/"/g, '""')}"`).join(",")
484
+ );
485
+ return [header, ...lines].join("\n");
486
+ }
487
+ return JSON.stringify(messages, null, 2);
488
+ }
489
+ async syncFromServer(client, conversationId, opts) {
490
+ const sinceSeq = opts?.full ? 0 : this.getLastSyncedSeq(conversationId);
491
+ let totalSynced = 0;
492
+ let currentSeq = sinceSeq;
493
+ while (true) {
494
+ const res = await client.fetchInbox(conversationId, {
495
+ sinceSeq: currentSeq,
496
+ limit: 50
497
+ });
498
+ if (!res.ok || !res.data || res.data.messages.length === 0) break;
499
+ const messages = res.data.messages.map((msg) => ({
500
+ conversation_id: conversationId,
501
+ message_id: msg.message_id,
502
+ seq: msg.seq,
503
+ sender_did: msg.sender_did,
504
+ schema: msg.schema,
505
+ payload: msg.payload,
506
+ ts_ms: msg.ts_ms,
507
+ direction: "received"
508
+ }));
509
+ this.save(messages);
510
+ totalSynced += messages.length;
511
+ currentSeq = res.data.next_since_seq;
512
+ this.setLastSyncedSeq(conversationId, currentSeq);
513
+ if (!res.data.has_more) break;
514
+ }
515
+ return { synced: totalSynced };
516
+ }
517
+ };
518
+
519
+ // src/client.ts
520
+ var PingAgentClient = class {
521
+ constructor(opts) {
522
+ this.opts = opts;
523
+ this.identity = opts.identity;
524
+ this.transport = new HttpTransport({
525
+ serverUrl: opts.serverUrl,
526
+ accessToken: opts.accessToken,
527
+ onTokenRefreshed: opts.onTokenRefreshed
528
+ });
529
+ if (opts.store) {
530
+ this.contactManager = new ContactManager(opts.store);
531
+ this.historyManager = new HistoryManager(opts.store);
532
+ }
533
+ }
534
+ transport;
535
+ identity;
536
+ contactManager;
537
+ historyManager;
538
+ getContactManager() {
539
+ return this.contactManager;
540
+ }
541
+ getHistoryManager() {
542
+ return this.historyManager;
543
+ }
544
+ /** Update the in-memory access token (e.g. after proactive refresh from disk). */
545
+ setAccessToken(token) {
546
+ this.transport.setToken(token);
547
+ }
548
+ async register(developerToken) {
549
+ let binary = "";
550
+ for (const b of this.identity.publicKey) binary += String.fromCharCode(b);
551
+ const publicKeyBase64 = btoa(binary);
552
+ return this.transport.request("POST", "/v1/agent/register", {
553
+ device_id: this.identity.deviceId,
554
+ public_key: publicKeyBase64,
555
+ developer_token: developerToken
556
+ }, true);
557
+ }
558
+ async openConversation(targetDid) {
559
+ return this.transport.request("POST", "/v1/conversations/open", {
560
+ targets: [targetDid]
561
+ });
562
+ }
563
+ async sendMessage(conversationId, schema, payload) {
564
+ const ttlMs = schema === SCHEMA_TEXT ? 6048e5 : void 0;
565
+ const unsigned = buildUnsignedEnvelope({
566
+ type: "message",
567
+ conversationId,
568
+ senderDid: this.identity.did,
569
+ senderDeviceId: this.identity.deviceId,
570
+ schema,
571
+ payload,
572
+ ttlMs
573
+ });
574
+ const signed = signEnvelope(unsigned, this.identity.privateKey);
575
+ const res = await this.transport.request("POST", "/v1/messages/send", signed);
576
+ if (res.ok && this.historyManager) {
577
+ this.historyManager.save([{
578
+ conversation_id: conversationId,
579
+ message_id: signed.message_id,
580
+ seq: res.data?.seq,
581
+ sender_did: this.identity.did,
582
+ schema,
583
+ payload,
584
+ ts_ms: signed.ts_ms,
585
+ direction: "sent"
586
+ }]);
587
+ }
588
+ return res;
589
+ }
590
+ async sendTask(conversationId, task) {
591
+ return this.sendMessage(conversationId, SCHEMA_TASK, {
592
+ ...task,
593
+ idempotency_key: task.task_id,
594
+ expected_output_schema: SCHEMA_RESULT
595
+ });
596
+ }
597
+ async sendContactRequest(conversationId, message) {
598
+ const { v7: uuidv7 } = await import("uuid");
599
+ return this.sendMessage(conversationId, SCHEMA_CONTACT_REQUEST, {
600
+ request_id: `r_${uuidv7()}`,
601
+ from_did: this.identity.did,
602
+ to_did: "",
603
+ capabilities: ["task", "result", "files"],
604
+ message,
605
+ expires_ms: 864e5
606
+ });
607
+ }
608
+ async fetchInbox(conversationId, opts) {
609
+ const params = new URLSearchParams({
610
+ conversation_id: conversationId,
611
+ since_seq: String(opts?.sinceSeq ?? 0),
612
+ limit: String(opts?.limit ?? 50),
613
+ box: opts?.box ?? "ready"
614
+ });
615
+ const res = await this.transport.request("GET", `/v1/inbox/fetch?${params}`);
616
+ if (res.ok && res.data && this.historyManager) {
617
+ const msgs = res.data.messages.map((msg) => ({
618
+ conversation_id: conversationId,
619
+ message_id: msg.message_id,
620
+ seq: msg.seq,
621
+ sender_did: msg.sender_did,
622
+ schema: msg.schema,
623
+ payload: msg.payload,
624
+ ts_ms: msg.ts_ms,
625
+ direction: msg.sender_did === this.identity.did ? "sent" : "received"
626
+ }));
627
+ if (msgs.length > 0) {
628
+ this.historyManager.save(msgs);
629
+ const maxSeq = Math.max(...msgs.map((m) => m.seq ?? 0));
630
+ if (maxSeq > 0) this.historyManager.setLastSyncedSeq(conversationId, maxSeq);
631
+ }
632
+ }
633
+ return res;
634
+ }
635
+ async ack(conversationId, forMessageId, status, opts) {
636
+ return this.transport.request("POST", "/v1/receipts/ack", {
637
+ conversation_id: conversationId,
638
+ for_message_id: forMessageId,
639
+ for_task_id: opts?.forTaskId,
640
+ status,
641
+ reason: opts?.reason,
642
+ detail: opts?.detail
643
+ });
644
+ }
645
+ async approveContact(conversationId) {
646
+ const res = await this.transport.request("POST", "/v1/control/approve_contact", {
647
+ conversation_id: conversationId
648
+ });
649
+ if (res.ok && this.contactManager) {
650
+ const pendingMessages = this.historyManager?.list(conversationId, { limit: 1 });
651
+ const senderDid = pendingMessages?.[0]?.sender_did;
652
+ if (senderDid && senderDid !== this.identity.did) {
653
+ this.contactManager.add({
654
+ did: senderDid,
655
+ conversation_id: res.data?.dm_conversation_id ?? conversationId,
656
+ trusted: true
657
+ });
658
+ }
659
+ }
660
+ return res;
661
+ }
662
+ async revokeConversation(conversationId) {
663
+ return this.transport.request("POST", "/v1/control/revoke_conversation", {
664
+ conversation_id: conversationId
665
+ });
666
+ }
667
+ async cancelTask(conversationId, taskId) {
668
+ return this.transport.request("POST", "/v1/control/cancel_task", {
669
+ conversation_id: conversationId,
670
+ task_id: taskId
671
+ });
672
+ }
673
+ async blockSender(conversationId, senderDid) {
674
+ return this.transport.request("POST", "/v1/control/block_sender", {
675
+ conversation_id: conversationId,
676
+ sender_did: senderDid
677
+ });
678
+ }
679
+ async acquireLease(conversationId) {
680
+ return this.transport.request("POST", "/v1/lease/acquire", {
681
+ conversation_id: conversationId
682
+ });
683
+ }
684
+ async renewLease(conversationId) {
685
+ return this.transport.request("POST", "/v1/lease/renew", {
686
+ conversation_id: conversationId
687
+ });
688
+ }
689
+ async releaseLease(conversationId) {
690
+ return this.transport.request("POST", "/v1/lease/release", {
691
+ conversation_id: conversationId
692
+ });
693
+ }
694
+ async uploadArtifact(content) {
695
+ const presignRes = await this.transport.request("POST", "/v1/artifacts/presign_upload", {
696
+ size: content.length,
697
+ content_type: "application/octet-stream"
698
+ });
699
+ if (!presignRes.ok || !presignRes.data) throw new Error("Failed to presign upload");
700
+ const { upload_url, artifact_ref } = presignRes.data;
701
+ await this.transport.fetchWithAuth(upload_url, {
702
+ method: "PUT",
703
+ body: content,
704
+ contentType: "application/octet-stream"
705
+ });
706
+ const { createHash } = await import("crypto");
707
+ const hash = createHash("sha256").update(content).digest("hex");
708
+ return { artifact_ref, sha256: hash, size: content.length };
709
+ }
710
+ async downloadArtifact(artifactRef, expectedSha256, expectedSize) {
711
+ const presignRes = await this.transport.request("POST", "/v1/artifacts/presign_download", {
712
+ artifact_ref: artifactRef
713
+ });
714
+ if (!presignRes.ok || !presignRes.data) throw new Error("Failed to presign download");
715
+ const buffer = Buffer.from(await this.transport.fetchWithAuth(presignRes.data.download_url));
716
+ if (buffer.length !== expectedSize) {
717
+ throw new Error(`Size mismatch: expected ${expectedSize}, got ${buffer.length}`);
718
+ }
719
+ const { createHash } = await import("crypto");
720
+ const hash = createHash("sha256").update(buffer).digest("hex");
721
+ if (hash !== expectedSha256) {
722
+ throw new Error(`SHA256 mismatch: expected ${expectedSha256}, got ${hash}`);
723
+ }
724
+ return buffer;
725
+ }
726
+ async getSubscription() {
727
+ return this.transport.request("GET", "/v1/subscription");
728
+ }
729
+ async resolveAlias(alias) {
730
+ return this.transport.request("GET", `/v1/directory/resolve?alias=${encodeURIComponent(alias)}`);
731
+ }
732
+ async registerAlias(alias) {
733
+ return this.transport.request("POST", "/v1/directory/alias", { alias });
734
+ }
735
+ async listConversations(opts) {
736
+ const params = new URLSearchParams();
737
+ if (opts?.type) params.set("type", opts.type);
738
+ const qs = params.toString();
739
+ return this.transport.request("GET", `/v1/conversations/list${qs ? "?" + qs : ""}`);
740
+ }
741
+ async getProfile() {
742
+ return this.transport.request("GET", "/v1/directory/profile");
743
+ }
744
+ async updateProfile(profile) {
745
+ return this.transport.request("POST", "/v1/directory/profile", profile);
746
+ }
747
+ async enableDiscovery() {
748
+ return this.transport.request("POST", "/v1/directory/enable_discovery");
749
+ }
750
+ async disableDiscovery() {
751
+ return this.transport.request("POST", "/v1/directory/disable_discovery");
752
+ }
753
+ async browseDirectory(opts) {
754
+ const params = new URLSearchParams();
755
+ if (opts?.tag) params.set("tag", opts.tag);
756
+ if (opts?.query) params.set("q", opts.query);
757
+ if (opts?.limit != null) params.set("limit", String(opts.limit));
758
+ if (opts?.offset != null) params.set("offset", String(opts.offset));
759
+ if (opts?.sort) params.set("sort", opts.sort);
760
+ const qs = params.toString();
761
+ return this.transport.request("GET", `/v1/directory/browse${qs ? "?" + qs : ""}`);
762
+ }
763
+ async publishPost(opts) {
764
+ return this.transport.request("POST", "/v1/feed/publish", { text: opts.text, artifact_ref: opts.artifact_ref });
765
+ }
766
+ async listFeedPublic(opts) {
767
+ const params = new URLSearchParams();
768
+ if (opts?.limit != null) params.set("limit", String(opts.limit));
769
+ if (opts?.since != null) params.set("since", String(opts.since));
770
+ const qs = params.toString();
771
+ return this.transport.request("GET", `/v1/feed/public${qs ? "?" + qs : ""}`, void 0, true);
772
+ }
773
+ async listFeedByDid(did, opts) {
774
+ const params = new URLSearchParams({ did });
775
+ if (opts?.limit != null) params.set("limit", String(opts.limit));
776
+ return this.transport.request("GET", `/v1/feed/by_did?${params.toString()}`, void 0, true);
777
+ }
778
+ async createChannel(opts) {
779
+ return this.transport.request("POST", "/v1/channels/create", {
780
+ name: opts.name,
781
+ alias: opts.alias,
782
+ description: opts.description,
783
+ join_policy: "open",
784
+ discoverable: opts.discoverable
785
+ });
786
+ }
787
+ async updateChannel(opts) {
788
+ const alias = opts.alias.replace(/^@ch\//, "");
789
+ return this.transport.request("PATCH", "/v1/channels/update", {
790
+ alias,
791
+ name: opts.name,
792
+ description: opts.description,
793
+ discoverable: opts.discoverable
794
+ });
795
+ }
796
+ async deleteChannel(alias) {
797
+ const a = alias.replace(/^@ch\//, "");
798
+ return this.transport.request("DELETE", "/v1/channels/delete", { alias: a });
799
+ }
800
+ async discoverChannels(opts) {
801
+ const params = new URLSearchParams();
802
+ if (opts?.limit != null) params.set("limit", String(opts.limit));
803
+ if (opts?.query) params.set("q", opts.query);
804
+ const qs = params.toString();
805
+ return this.transport.request("GET", `/v1/channels/discover${qs ? "?" + qs : ""}`, void 0, true);
806
+ }
807
+ async joinChannel(alias) {
808
+ return this.transport.request("POST", "/v1/channels/join", { alias });
809
+ }
810
+ getDid() {
811
+ return this.identity.did;
812
+ }
813
+ // === Billing: device linking ===
814
+ async createBillingLinkCode() {
815
+ return this.transport.request("POST", "/v1/billing/link-code");
816
+ }
817
+ async redeemBillingLink(code) {
818
+ return this.transport.request("POST", "/v1/billing/link", { code });
819
+ }
820
+ async unlinkBillingDevice(did) {
821
+ return this.transport.request("POST", "/v1/billing/unlink", { did });
822
+ }
823
+ async getLinkedDevices() {
824
+ return this.transport.request("GET", "/v1/billing/linked-devices");
825
+ }
826
+ // P0: High-level send-task-and-wait
827
+ async sendTaskAndWait(targetDid, task, opts) {
828
+ const { v7: uuidv7 } = await import("uuid");
829
+ const timeout = opts?.timeoutMs ?? 12e4;
830
+ const pollInterval = opts?.pollIntervalMs ?? 2e3;
831
+ const taskId = `t_${uuidv7()}`;
832
+ const startTime = Date.now();
833
+ const openRes = await this.openConversation(targetDid);
834
+ if (!openRes.ok || !openRes.data) {
835
+ return { status: "error", task_id: taskId, error: { code: "E_OPEN_FAILED", message: "Failed to open conversation" }, elapsed_ms: Date.now() - startTime };
836
+ }
837
+ let conversationId = openRes.data.conversation_id;
838
+ if (!openRes.data.trusted) {
839
+ await this.sendContactRequest(conversationId, task.title);
840
+ const approvalDeadline = startTime + timeout;
841
+ while (Date.now() < approvalDeadline) {
842
+ await sleep2(pollInterval);
843
+ const reopen = await this.openConversation(targetDid);
844
+ if (reopen.ok && reopen.data?.trusted) {
845
+ conversationId = reopen.data.conversation_id;
846
+ break;
847
+ }
848
+ }
849
+ if (Date.now() >= approvalDeadline) {
850
+ return { status: "error", task_id: taskId, error: { code: "E_NOT_APPROVED", message: "Contact request not approved within timeout" }, elapsed_ms: Date.now() - startTime };
851
+ }
852
+ }
853
+ const sendRes = await this.sendTask(conversationId, { task_id: taskId, ...task });
854
+ if (!sendRes.ok) {
855
+ 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 };
856
+ }
857
+ const sinceSeq = sendRes.data?.seq ?? 0;
858
+ const deadline = startTime + timeout;
859
+ while (Date.now() < deadline) {
860
+ await sleep2(pollInterval);
861
+ const fetchRes = await this.fetchInbox(conversationId, { sinceSeq });
862
+ if (!fetchRes.ok || !fetchRes.data) continue;
863
+ for (const msg of fetchRes.data.messages) {
864
+ if (msg.schema === SCHEMA_RESULT && msg.payload?.task_id === taskId) {
865
+ return {
866
+ status: msg.payload.status === "ok" ? "ok" : "error",
867
+ task_id: taskId,
868
+ result: msg.payload.output,
869
+ error: msg.payload.error,
870
+ elapsed_ms: Date.now() - startTime
871
+ };
872
+ }
873
+ if (msg.schema === SCHEMA_RECEIPT && msg.payload?.for_task_id === taskId && msg.payload?.status === "failed") {
874
+ return {
875
+ status: "error",
876
+ task_id: taskId,
877
+ error: { code: msg.payload.reason ?? "E_TASK_FAILED", message: msg.payload.reason ?? "Task failed" },
878
+ elapsed_ms: Date.now() - startTime
879
+ };
880
+ }
881
+ }
882
+ }
883
+ return { status: "error", task_id: taskId, error: { code: "E_TIMEOUT", message: `No result within ${timeout}ms` }, elapsed_ms: timeout };
884
+ }
885
+ };
886
+ function sleep2(ms) {
887
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
888
+ }
889
+
890
+ // src/identity.ts
891
+ import * as fs from "fs";
892
+ import * as path2 from "path";
893
+ import { generateIdentity as genId } from "@pingagent/protocol";
894
+
895
+ // src/paths.ts
896
+ import * as path from "path";
897
+ import * as os from "os";
898
+ var DEFAULT_ROOT_DIR = path.join(os.homedir(), ".pingagent");
899
+ function getRootDir() {
900
+ return process.env.PINGAGENT_ROOT_DIR || DEFAULT_ROOT_DIR;
901
+ }
902
+ function getProfile() {
903
+ const p = process.env.PINGAGENT_PROFILE;
904
+ if (!p) return void 0;
905
+ return p.trim() || void 0;
906
+ }
907
+ function getIdentityPath(explicitPath) {
908
+ const envPath = process.env.PINGAGENT_IDENTITY_PATH?.trim();
909
+ if (explicitPath) return explicitPath;
910
+ if (envPath) return path.resolve(envPath.replace(/^~(?=\/|$)/, os.homedir()));
911
+ const root = getRootDir();
912
+ const profile = getProfile();
913
+ if (!profile) {
914
+ return path.join(root, "identity.json");
915
+ }
916
+ return path.join(root, "profiles", profile, "identity.json");
917
+ }
918
+ function getStorePath(explicitPath) {
919
+ const envPath = process.env.PINGAGENT_STORE_PATH?.trim();
920
+ if (explicitPath) return explicitPath;
921
+ if (envPath) return path.resolve(envPath.replace(/^~(?=\/|$)/, os.homedir()));
922
+ const root = getRootDir();
923
+ const profile = getProfile();
924
+ if (!profile) {
925
+ return path.join(root, "store.db");
926
+ }
927
+ return path.join(root, "profiles", profile, "store.db");
928
+ }
929
+
930
+ // src/identity.ts
931
+ function toBase64(bytes) {
932
+ let binary = "";
933
+ for (const b of bytes) binary += String.fromCharCode(b);
934
+ return btoa(binary);
935
+ }
936
+ function fromBase64(b64) {
937
+ const binary = atob(b64);
938
+ const bytes = new Uint8Array(binary.length);
939
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
940
+ return bytes;
941
+ }
942
+ function generateIdentity() {
943
+ return genId();
944
+ }
945
+ function identityExists(identityPath) {
946
+ return fs.existsSync(getIdentityPath(identityPath));
947
+ }
948
+ function loadIdentity(identityPath) {
949
+ const p = getIdentityPath(identityPath);
950
+ const data = JSON.parse(fs.readFileSync(p, "utf-8"));
951
+ return {
952
+ publicKey: fromBase64(data.public_key),
953
+ privateKey: fromBase64(data.private_key),
954
+ did: data.did,
955
+ deviceId: data.device_id,
956
+ serverUrl: data.server_url,
957
+ accessToken: data.access_token,
958
+ tokenExpiresAt: data.token_expires_at,
959
+ mode: data.mode
960
+ };
961
+ }
962
+ function saveIdentity(identity, opts, identityPath) {
963
+ const p = getIdentityPath(identityPath);
964
+ const dir = path2.dirname(p);
965
+ if (!fs.existsSync(dir)) {
966
+ fs.mkdirSync(dir, { recursive: true, mode: 448 });
967
+ }
968
+ const stored = {
969
+ public_key: toBase64(identity.publicKey),
970
+ private_key: toBase64(identity.privateKey),
971
+ did: identity.did,
972
+ device_id: identity.deviceId,
973
+ server_url: opts?.serverUrl,
974
+ access_token: opts?.accessToken,
975
+ token_expires_at: opts?.tokenExpiresAt,
976
+ mode: opts?.mode,
977
+ alias: opts?.alias
978
+ };
979
+ fs.writeFileSync(p, JSON.stringify(stored, null, 2), { mode: 384 });
980
+ }
981
+ function updateStoredToken(accessToken, expiresAt, identityPath) {
982
+ const p = getIdentityPath(identityPath);
983
+ const data = JSON.parse(fs.readFileSync(p, "utf-8"));
984
+ data.access_token = accessToken;
985
+ data.token_expires_at = expiresAt;
986
+ fs.writeFileSync(p, JSON.stringify(data, null, 2), { mode: 384 });
987
+ }
988
+
989
+ // src/auth.ts
990
+ var REFRESH_GRACE_MS = 5 * 60 * 1e3;
991
+ async function ensureTokenValid(identityPath, serverUrl) {
992
+ if (!identityExists(identityPath)) return false;
993
+ const id = loadIdentity(identityPath);
994
+ const token = id.accessToken;
995
+ const expiresAt = id.tokenExpiresAt;
996
+ if (!token || expiresAt == null) return false;
997
+ const now = Date.now();
998
+ if (expiresAt > now + REFRESH_GRACE_MS) return false;
999
+ const baseUrl = (serverUrl ?? id.serverUrl ?? "https://pingagent.chat").replace(/\/$/, "");
1000
+ try {
1001
+ const res = await fetch(`${baseUrl}/v1/auth/refresh`, {
1002
+ method: "POST",
1003
+ headers: { "Content-Type": "application/json" },
1004
+ body: JSON.stringify({ access_token: token })
1005
+ });
1006
+ const text = await res.text();
1007
+ let data;
1008
+ try {
1009
+ data = text ? JSON.parse(text) : {};
1010
+ } catch {
1011
+ return false;
1012
+ }
1013
+ if (!res.ok || !data.ok || !data.data?.access_token || data.data.expires_ms == null) return false;
1014
+ const newExpiresAt = now + data.data.expires_ms;
1015
+ updateStoredToken(data.data.access_token, newExpiresAt, identityPath);
1016
+ return true;
1017
+ } catch {
1018
+ return false;
1019
+ }
1020
+ }
1021
+
1022
+ // src/store.ts
1023
+ import Database from "better-sqlite3";
1024
+ import * as fs2 from "fs";
1025
+ import * as path3 from "path";
1026
+ var SCHEMA_SQL = `
1027
+ CREATE TABLE IF NOT EXISTS contacts (
1028
+ did TEXT PRIMARY KEY,
1029
+ alias TEXT,
1030
+ display_name TEXT,
1031
+ notes TEXT,
1032
+ conversation_id TEXT,
1033
+ trusted INTEGER NOT NULL DEFAULT 0,
1034
+ added_at INTEGER NOT NULL,
1035
+ last_message_at INTEGER,
1036
+ tags TEXT
1037
+ );
1038
+ CREATE INDEX IF NOT EXISTS idx_contacts_alias ON contacts(alias);
1039
+
1040
+ CREATE TABLE IF NOT EXISTS messages (
1041
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
1042
+ conversation_id TEXT NOT NULL,
1043
+ message_id TEXT NOT NULL UNIQUE,
1044
+ seq INTEGER,
1045
+ sender_did TEXT NOT NULL,
1046
+ schema TEXT NOT NULL,
1047
+ payload TEXT NOT NULL,
1048
+ ts_ms INTEGER NOT NULL,
1049
+ direction TEXT NOT NULL CHECK(direction IN ('sent', 'received'))
1050
+ );
1051
+ CREATE INDEX IF NOT EXISTS idx_messages_conv_seq ON messages(conversation_id, seq);
1052
+ CREATE INDEX IF NOT EXISTS idx_messages_ts ON messages(ts_ms);
1053
+
1054
+ CREATE TABLE IF NOT EXISTS sync_state (
1055
+ conversation_id TEXT PRIMARY KEY,
1056
+ last_synced_seq INTEGER NOT NULL DEFAULT 0,
1057
+ last_synced_at INTEGER
1058
+ );
1059
+ `;
1060
+ var LocalStore = class {
1061
+ db;
1062
+ constructor(dbPath) {
1063
+ const p = getStorePath(dbPath);
1064
+ const dir = path3.dirname(p);
1065
+ if (!fs2.existsSync(dir)) {
1066
+ fs2.mkdirSync(dir, { recursive: true, mode: 448 });
1067
+ }
1068
+ this.db = new Database(p);
1069
+ this.db.pragma("journal_mode = WAL");
1070
+ this.db.exec(SCHEMA_SQL);
1071
+ }
1072
+ getDb() {
1073
+ return this.db;
1074
+ }
1075
+ close() {
1076
+ this.db.close();
1077
+ }
1078
+ };
1079
+
1080
+ // src/a2a-adapter.ts
1081
+ import {
1082
+ A2AClient
1083
+ } from "@pingagent/a2a";
1084
+ var A2AAdapter = class {
1085
+ client;
1086
+ cachedCard = null;
1087
+ constructor(opts) {
1088
+ this.client = new A2AClient({
1089
+ agentUrl: opts.agentUrl,
1090
+ authToken: opts.authToken ? `Bearer ${opts.authToken}` : void 0,
1091
+ timeoutMs: opts.timeoutMs
1092
+ });
1093
+ }
1094
+ async getAgentCard() {
1095
+ if (!this.cachedCard) {
1096
+ this.cachedCard = await this.client.fetchAgentCard();
1097
+ }
1098
+ return this.cachedCard;
1099
+ }
1100
+ /**
1101
+ * Send a task to the external A2A agent and optionally wait for completion.
1102
+ */
1103
+ async sendTask(opts) {
1104
+ const parts = [];
1105
+ parts.push({ kind: "text", text: opts.title });
1106
+ if (opts.description) {
1107
+ parts.push({ kind: "text", text: opts.description });
1108
+ }
1109
+ if (opts.input) {
1110
+ parts.push({
1111
+ kind: "data",
1112
+ data: typeof opts.input === "object" ? opts.input : { value: opts.input }
1113
+ });
1114
+ }
1115
+ const messageId = `msg_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
1116
+ const message = {
1117
+ kind: "message",
1118
+ messageId,
1119
+ role: "user",
1120
+ parts
1121
+ };
1122
+ if (opts.wait) {
1123
+ const task = await this.client.sendAndWait(
1124
+ { message, configuration: { blocking: true } },
1125
+ { maxPollMs: opts.timeoutMs ?? 12e4 }
1126
+ );
1127
+ return this.convertTask(task);
1128
+ }
1129
+ const result = await this.client.sendMessage({ message });
1130
+ if (result.kind === "task") {
1131
+ return this.convertTask(result);
1132
+ }
1133
+ return {
1134
+ taskId: result.messageId,
1135
+ state: "completed",
1136
+ summary: this.extractText(result.parts)
1137
+ };
1138
+ }
1139
+ async getTaskStatus(taskId) {
1140
+ const task = await this.client.getTask(taskId);
1141
+ return this.convertTask(task);
1142
+ }
1143
+ async cancelTask(taskId) {
1144
+ const task = await this.client.cancelTask(taskId);
1145
+ return this.convertTask(task);
1146
+ }
1147
+ async sendText(text, opts) {
1148
+ const result = await this.client.sendText(text, { blocking: opts?.blocking });
1149
+ if (result.kind === "task") {
1150
+ return this.convertTask(result);
1151
+ }
1152
+ return {
1153
+ taskId: result.messageId,
1154
+ state: "completed",
1155
+ summary: this.extractText(result.parts)
1156
+ };
1157
+ }
1158
+ convertTask(task) {
1159
+ const summary = task.artifacts?.flatMap((a) => a.parts).filter((p) => p.kind === "text").map((p) => p.text).join("\n");
1160
+ const output = task.artifacts?.flatMap((a) => a.parts).filter((p) => p.kind === "data").map((p) => p.data);
1161
+ return {
1162
+ taskId: task.id,
1163
+ contextId: task.contextId,
1164
+ state: task.status.state,
1165
+ summary: summary || void 0,
1166
+ output: output && output.length > 0 ? output.length === 1 ? output[0] : output : void 0,
1167
+ timestamp: task.status.timestamp
1168
+ };
1169
+ }
1170
+ extractText(parts) {
1171
+ return parts.filter((p) => p.kind === "text").map((p) => p.text).join("\n") || void 0;
1172
+ }
1173
+ };
1174
+
1175
+ // src/ws-subscription.ts
1176
+ import WebSocket from "ws";
1177
+ var RECONNECT_BASE_MS = 1e3;
1178
+ var RECONNECT_MAX_MS = 3e4;
1179
+ var RECONNECT_JITTER = 0.2;
1180
+ var LIST_CONVERSATIONS_INTERVAL_MS = 6e4;
1181
+ var WsSubscription = class {
1182
+ opts;
1183
+ connections = /* @__PURE__ */ new Map();
1184
+ reconnectTimers = /* @__PURE__ */ new Map();
1185
+ reconnectAttempts = /* @__PURE__ */ new Map();
1186
+ listInterval = null;
1187
+ stopped = false;
1188
+ /** Conversation IDs that were explicitly stopped (e.g. revoke); do not reconnect. */
1189
+ stoppedConversations = /* @__PURE__ */ new Set();
1190
+ constructor(opts) {
1191
+ this.opts = opts;
1192
+ }
1193
+ start() {
1194
+ this.stopped = false;
1195
+ this.connectAll();
1196
+ this.listInterval = setInterval(() => this.syncConnections(), LIST_CONVERSATIONS_INTERVAL_MS);
1197
+ }
1198
+ stop() {
1199
+ this.stopped = true;
1200
+ if (this.listInterval) {
1201
+ clearInterval(this.listInterval);
1202
+ this.listInterval = null;
1203
+ }
1204
+ for (const timer of this.reconnectTimers.values()) {
1205
+ clearTimeout(timer);
1206
+ }
1207
+ this.reconnectTimers.clear();
1208
+ for (const [convId, ws] of this.connections) {
1209
+ ws.removeAllListeners();
1210
+ if (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING) {
1211
+ ws.close();
1212
+ }
1213
+ this.connections.delete(convId);
1214
+ }
1215
+ this.reconnectAttempts.clear();
1216
+ this.stoppedConversations.clear();
1217
+ }
1218
+ /**
1219
+ * Stop a single conversation's WebSocket and do not reconnect.
1220
+ * Used when the conversation is revoked or the client no longer wants to subscribe.
1221
+ */
1222
+ stopConversation(conversationId) {
1223
+ this.stoppedConversations.add(conversationId);
1224
+ const timer = this.reconnectTimers.get(conversationId);
1225
+ if (timer) {
1226
+ clearTimeout(timer);
1227
+ this.reconnectTimers.delete(conversationId);
1228
+ }
1229
+ const ws = this.connections.get(conversationId);
1230
+ if (ws) {
1231
+ ws.removeAllListeners();
1232
+ if (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING) {
1233
+ ws.close();
1234
+ }
1235
+ this.connections.delete(conversationId);
1236
+ }
1237
+ }
1238
+ wsUrl(conversationId) {
1239
+ const base = this.opts.serverUrl.replace(/^http/, "ws").replace(/\/$/, "");
1240
+ return `${base}/v1/ws?conversation_id=${encodeURIComponent(conversationId)}`;
1241
+ }
1242
+ async connectAsync(conversationId) {
1243
+ if (this.stopped || this.stoppedConversations.has(conversationId) || this.connections.has(conversationId)) return;
1244
+ const token = await Promise.resolve(this.opts.getAccessToken());
1245
+ const url = this.wsUrl(conversationId);
1246
+ const ws = new WebSocket(url, {
1247
+ headers: { Authorization: `Bearer ${token}` }
1248
+ });
1249
+ this.connections.set(conversationId, ws);
1250
+ ws.on("open", () => {
1251
+ this.reconnectAttempts.set(conversationId, 0);
1252
+ this.opts.onOpen?.(conversationId);
1253
+ });
1254
+ ws.on("message", (data) => {
1255
+ try {
1256
+ const msg = JSON.parse(data.toString());
1257
+ if (msg.type === "ws_message" && msg.envelope) {
1258
+ const env = msg.envelope;
1259
+ if (env.sender_did !== this.opts.myDid) {
1260
+ this.opts.onMessage(env, conversationId);
1261
+ }
1262
+ } else if (msg.type === "ws_control" && msg.control) {
1263
+ this.opts.onControl?.(msg.control, conversationId);
1264
+ }
1265
+ } catch {
1266
+ }
1267
+ });
1268
+ ws.on("close", () => {
1269
+ this.connections.delete(conversationId);
1270
+ if (!this.stopped && !this.stoppedConversations.has(conversationId)) {
1271
+ this.scheduleReconnect(conversationId);
1272
+ }
1273
+ });
1274
+ ws.on("error", (err) => {
1275
+ this.opts.onError?.(err);
1276
+ });
1277
+ }
1278
+ scheduleReconnect(conversationId) {
1279
+ if (this.reconnectTimers.has(conversationId)) return;
1280
+ const attempt = this.reconnectAttempts.get(conversationId) ?? 0;
1281
+ this.reconnectAttempts.set(conversationId, attempt + 1);
1282
+ const tryConnect = () => {
1283
+ this.reconnectTimers.delete(conversationId);
1284
+ if (this.stopped) return;
1285
+ void this.connectAsync(conversationId);
1286
+ };
1287
+ const delay = Math.min(
1288
+ RECONNECT_BASE_MS * Math.pow(2, attempt) + (Math.random() - 0.5) * RECONNECT_JITTER * RECONNECT_BASE_MS,
1289
+ RECONNECT_MAX_MS
1290
+ );
1291
+ const timer = setTimeout(tryConnect, delay);
1292
+ this.reconnectTimers.set(conversationId, timer);
1293
+ }
1294
+ async connectAll() {
1295
+ try {
1296
+ const convos = await this.opts.listConversations();
1297
+ const subscribable = convos.filter((c) => c.type === "dm" || c.type === "channel");
1298
+ for (const c of subscribable) {
1299
+ void this.connectAsync(c.conversation_id);
1300
+ }
1301
+ } catch (err) {
1302
+ this.opts.onError?.(err instanceof Error ? err : new Error(String(err)));
1303
+ }
1304
+ }
1305
+ async syncConnections() {
1306
+ if (this.stopped) return;
1307
+ try {
1308
+ const convos = await this.opts.listConversations();
1309
+ const subscribableIds = new Set(
1310
+ convos.filter((c) => c.type === "dm" || c.type === "channel").map((c) => c.conversation_id)
1311
+ );
1312
+ for (const convId of subscribableIds) {
1313
+ if (!this.stoppedConversations.has(convId) && !this.connections.has(convId)) {
1314
+ void this.connectAsync(convId);
1315
+ }
1316
+ }
1317
+ for (const convId of this.connections.keys()) {
1318
+ if (!subscribableIds.has(convId) || this.stoppedConversations.has(convId)) {
1319
+ const ws = this.connections.get(convId);
1320
+ if (ws) {
1321
+ ws.removeAllListeners();
1322
+ ws.close();
1323
+ this.connections.delete(convId);
1324
+ }
1325
+ }
1326
+ }
1327
+ } catch {
1328
+ }
1329
+ }
1330
+ };
1331
+
1332
+ export {
1333
+ HttpTransport,
1334
+ ContactManager,
1335
+ HistoryManager,
1336
+ PingAgentClient,
1337
+ getRootDir,
1338
+ getProfile,
1339
+ getIdentityPath,
1340
+ getStorePath,
1341
+ generateIdentity,
1342
+ identityExists,
1343
+ loadIdentity,
1344
+ saveIdentity,
1345
+ updateStoredToken,
1346
+ ensureTokenValid,
1347
+ LocalStore,
1348
+ A2AAdapter,
1349
+ WsSubscription
1350
+ };