@pingagent/sdk 0.1.6 → 0.1.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-4W44SPLT.js +1459 -0
- package/dist/chunk-GBG3JF75.js +1454 -0
- package/dist/chunk-OVLKR4JF.js +1500 -0
- package/dist/chunk-SHTDIRC6.js +1455 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.js +1 -1
- package/dist/web-server.js +1 -1
- package/package.json +3 -3
- package/src/ws-subscription.ts +76 -9
|
@@ -0,0 +1,1459 @@
|
|
|
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 DEFAULT_HEARTBEAT = {
|
|
1182
|
+
enable: true,
|
|
1183
|
+
idleThresholdMs: 1e4,
|
|
1184
|
+
pingIntervalMs: 15e3,
|
|
1185
|
+
pongTimeoutMs: 1e4,
|
|
1186
|
+
maxMissedPongs: 2,
|
|
1187
|
+
tickMs: 5e3,
|
|
1188
|
+
jitter: 0.2
|
|
1189
|
+
};
|
|
1190
|
+
var WsSubscription = class {
|
|
1191
|
+
opts;
|
|
1192
|
+
connections = /* @__PURE__ */ new Map();
|
|
1193
|
+
reconnectTimers = /* @__PURE__ */ new Map();
|
|
1194
|
+
reconnectAttempts = /* @__PURE__ */ new Map();
|
|
1195
|
+
listInterval = null;
|
|
1196
|
+
stopped = false;
|
|
1197
|
+
/** Conversation IDs that were explicitly stopped (e.g. revoke); do not reconnect. */
|
|
1198
|
+
stoppedConversations = /* @__PURE__ */ new Set();
|
|
1199
|
+
heartbeatTimer = null;
|
|
1200
|
+
heartbeatStates = /* @__PURE__ */ new Map();
|
|
1201
|
+
constructor(opts) {
|
|
1202
|
+
this.opts = opts;
|
|
1203
|
+
}
|
|
1204
|
+
start() {
|
|
1205
|
+
this.stopped = false;
|
|
1206
|
+
this.connectAll();
|
|
1207
|
+
this.listInterval = setInterval(() => this.syncConnections(), LIST_CONVERSATIONS_INTERVAL_MS);
|
|
1208
|
+
const hb = this.opts.heartbeat ?? {};
|
|
1209
|
+
if (hb.enable ?? DEFAULT_HEARTBEAT.enable) {
|
|
1210
|
+
this.heartbeatTimer = setInterval(() => this.heartbeatTick(), hb.tickMs ?? DEFAULT_HEARTBEAT.tickMs);
|
|
1211
|
+
}
|
|
1212
|
+
}
|
|
1213
|
+
stop() {
|
|
1214
|
+
this.stopped = true;
|
|
1215
|
+
if (this.listInterval) {
|
|
1216
|
+
clearInterval(this.listInterval);
|
|
1217
|
+
this.listInterval = null;
|
|
1218
|
+
}
|
|
1219
|
+
if (this.heartbeatTimer) {
|
|
1220
|
+
clearInterval(this.heartbeatTimer);
|
|
1221
|
+
this.heartbeatTimer = null;
|
|
1222
|
+
}
|
|
1223
|
+
for (const timer of this.reconnectTimers.values()) {
|
|
1224
|
+
clearTimeout(timer);
|
|
1225
|
+
}
|
|
1226
|
+
this.reconnectTimers.clear();
|
|
1227
|
+
for (const [convId, ws] of this.connections) {
|
|
1228
|
+
ws.removeAllListeners();
|
|
1229
|
+
if (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING) {
|
|
1230
|
+
ws.close();
|
|
1231
|
+
}
|
|
1232
|
+
this.connections.delete(convId);
|
|
1233
|
+
}
|
|
1234
|
+
this.reconnectAttempts.clear();
|
|
1235
|
+
this.stoppedConversations.clear();
|
|
1236
|
+
for (const state of this.heartbeatStates.values()) {
|
|
1237
|
+
if (state.pongTimeout) clearTimeout(state.pongTimeout);
|
|
1238
|
+
}
|
|
1239
|
+
this.heartbeatStates.clear();
|
|
1240
|
+
}
|
|
1241
|
+
/**
|
|
1242
|
+
* Stop a single conversation's WebSocket and do not reconnect.
|
|
1243
|
+
* Used when the conversation is revoked or the client no longer wants to subscribe.
|
|
1244
|
+
*/
|
|
1245
|
+
stopConversation(conversationId) {
|
|
1246
|
+
this.stoppedConversations.add(conversationId);
|
|
1247
|
+
const timer = this.reconnectTimers.get(conversationId);
|
|
1248
|
+
if (timer) {
|
|
1249
|
+
clearTimeout(timer);
|
|
1250
|
+
this.reconnectTimers.delete(conversationId);
|
|
1251
|
+
}
|
|
1252
|
+
const hbState = this.heartbeatStates.get(conversationId);
|
|
1253
|
+
if (hbState?.pongTimeout) clearTimeout(hbState.pongTimeout);
|
|
1254
|
+
this.heartbeatStates.delete(conversationId);
|
|
1255
|
+
const ws = this.connections.get(conversationId);
|
|
1256
|
+
if (ws) {
|
|
1257
|
+
ws.removeAllListeners();
|
|
1258
|
+
if (ws.readyState === WebSocket.OPEN || ws.readyState === WebSocket.CONNECTING) {
|
|
1259
|
+
ws.close();
|
|
1260
|
+
}
|
|
1261
|
+
this.connections.delete(conversationId);
|
|
1262
|
+
}
|
|
1263
|
+
}
|
|
1264
|
+
wsUrl(conversationId) {
|
|
1265
|
+
const base = this.opts.serverUrl.replace(/^http/, "ws").replace(/\/$/, "");
|
|
1266
|
+
return `${base}/v1/ws?conversation_id=${encodeURIComponent(conversationId)}`;
|
|
1267
|
+
}
|
|
1268
|
+
async connectAsync(conversationId) {
|
|
1269
|
+
if (this.stopped || this.stoppedConversations.has(conversationId) || this.connections.has(conversationId)) return;
|
|
1270
|
+
const token = await Promise.resolve(this.opts.getAccessToken());
|
|
1271
|
+
const url = this.wsUrl(conversationId);
|
|
1272
|
+
const ws = new WebSocket(url, {
|
|
1273
|
+
headers: { Authorization: `Bearer ${token}` }
|
|
1274
|
+
});
|
|
1275
|
+
this.connections.set(conversationId, ws);
|
|
1276
|
+
const hb = this.opts.heartbeat ?? {};
|
|
1277
|
+
const hbEnabled = hb.enable ?? DEFAULT_HEARTBEAT.enable;
|
|
1278
|
+
if (hbEnabled) {
|
|
1279
|
+
const now = Date.now();
|
|
1280
|
+
this.heartbeatStates.set(conversationId, {
|
|
1281
|
+
lastRxAt: now,
|
|
1282
|
+
lastPingAt: 0,
|
|
1283
|
+
nextPingAt: now + (hb.idleThresholdMs ?? DEFAULT_HEARTBEAT.idleThresholdMs),
|
|
1284
|
+
missedPongs: 0,
|
|
1285
|
+
pongTimeout: null
|
|
1286
|
+
});
|
|
1287
|
+
}
|
|
1288
|
+
ws.on("open", () => {
|
|
1289
|
+
this.reconnectAttempts.set(conversationId, 0);
|
|
1290
|
+
this.opts.onOpen?.(conversationId);
|
|
1291
|
+
});
|
|
1292
|
+
ws.on("message", (data) => {
|
|
1293
|
+
try {
|
|
1294
|
+
const state = this.heartbeatStates.get(conversationId);
|
|
1295
|
+
if (state) {
|
|
1296
|
+
state.lastRxAt = Date.now();
|
|
1297
|
+
state.missedPongs = 0;
|
|
1298
|
+
if (state.pongTimeout) {
|
|
1299
|
+
clearTimeout(state.pongTimeout);
|
|
1300
|
+
state.pongTimeout = null;
|
|
1301
|
+
}
|
|
1302
|
+
}
|
|
1303
|
+
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() : (
|
|
1304
|
+
// Fallback: try best-effort stringification
|
|
1305
|
+
String(data)
|
|
1306
|
+
);
|
|
1307
|
+
const msg = JSON.parse(rawText);
|
|
1308
|
+
if (msg.type === "ws_message" && msg.envelope) {
|
|
1309
|
+
const env = msg.envelope;
|
|
1310
|
+
const ignoreSelf = this.opts.ignoreSelfMessages ?? true;
|
|
1311
|
+
if (!ignoreSelf || env.sender_did !== this.opts.myDid) {
|
|
1312
|
+
this.opts.onMessage(env, conversationId);
|
|
1313
|
+
}
|
|
1314
|
+
} else if (msg.type === "ws_control" && msg.control) {
|
|
1315
|
+
this.opts.onControl?.(msg.control, conversationId);
|
|
1316
|
+
}
|
|
1317
|
+
} catch {
|
|
1318
|
+
}
|
|
1319
|
+
});
|
|
1320
|
+
ws.on("pong", () => {
|
|
1321
|
+
const state = this.heartbeatStates.get(conversationId);
|
|
1322
|
+
if (!state) return;
|
|
1323
|
+
state.lastRxAt = Date.now();
|
|
1324
|
+
state.missedPongs = 0;
|
|
1325
|
+
if (state.pongTimeout) {
|
|
1326
|
+
clearTimeout(state.pongTimeout);
|
|
1327
|
+
state.pongTimeout = null;
|
|
1328
|
+
}
|
|
1329
|
+
});
|
|
1330
|
+
ws.on("close", () => {
|
|
1331
|
+
this.connections.delete(conversationId);
|
|
1332
|
+
const state = this.heartbeatStates.get(conversationId);
|
|
1333
|
+
if (state?.pongTimeout) clearTimeout(state.pongTimeout);
|
|
1334
|
+
this.heartbeatStates.delete(conversationId);
|
|
1335
|
+
if (!this.stopped && !this.stoppedConversations.has(conversationId)) {
|
|
1336
|
+
this.scheduleReconnect(conversationId);
|
|
1337
|
+
}
|
|
1338
|
+
});
|
|
1339
|
+
ws.on("error", (err) => {
|
|
1340
|
+
this.opts.onError?.(err);
|
|
1341
|
+
});
|
|
1342
|
+
}
|
|
1343
|
+
heartbeatTick() {
|
|
1344
|
+
const hb = this.opts.heartbeat ?? {};
|
|
1345
|
+
const hbEnabled = hb.enable ?? DEFAULT_HEARTBEAT.enable;
|
|
1346
|
+
if (!hbEnabled) return;
|
|
1347
|
+
const idleThresholdMs = hb.idleThresholdMs ?? DEFAULT_HEARTBEAT.idleThresholdMs;
|
|
1348
|
+
const pingIntervalMs = hb.pingIntervalMs ?? DEFAULT_HEARTBEAT.pingIntervalMs;
|
|
1349
|
+
const pongTimeoutMs = hb.pongTimeoutMs ?? DEFAULT_HEARTBEAT.pongTimeoutMs;
|
|
1350
|
+
const maxMissedPongs = hb.maxMissedPongs ?? DEFAULT_HEARTBEAT.maxMissedPongs;
|
|
1351
|
+
const jitter = hb.jitter ?? DEFAULT_HEARTBEAT.jitter;
|
|
1352
|
+
const now = Date.now();
|
|
1353
|
+
for (const [conversationId, ws] of this.connections) {
|
|
1354
|
+
if (ws.readyState !== WebSocket.OPEN) continue;
|
|
1355
|
+
const state = this.heartbeatStates.get(conversationId);
|
|
1356
|
+
if (!state) continue;
|
|
1357
|
+
if (state.pongTimeout) continue;
|
|
1358
|
+
const idleFor = now - state.lastRxAt;
|
|
1359
|
+
if (idleFor < idleThresholdMs) continue;
|
|
1360
|
+
if (now < state.nextPingAt) continue;
|
|
1361
|
+
if (state.lastPingAt !== 0 && now - state.lastPingAt < pingIntervalMs * 0.5) {
|
|
1362
|
+
continue;
|
|
1363
|
+
}
|
|
1364
|
+
try {
|
|
1365
|
+
ws.send(JSON.stringify({ type: "hb" }));
|
|
1366
|
+
} catch {
|
|
1367
|
+
}
|
|
1368
|
+
ws.ping();
|
|
1369
|
+
state.lastPingAt = now;
|
|
1370
|
+
const jitterFactor = 1 + (Math.random() - 0.5) * 2 * jitter;
|
|
1371
|
+
state.nextPingAt = now + Math.max(1e3, pingIntervalMs * jitterFactor);
|
|
1372
|
+
state.pongTimeout = setTimeout(() => {
|
|
1373
|
+
state.missedPongs += 1;
|
|
1374
|
+
state.pongTimeout = null;
|
|
1375
|
+
if (state.missedPongs >= maxMissedPongs) {
|
|
1376
|
+
try {
|
|
1377
|
+
ws.close(1001, "pong timeout");
|
|
1378
|
+
} catch {
|
|
1379
|
+
}
|
|
1380
|
+
}
|
|
1381
|
+
}, pongTimeoutMs);
|
|
1382
|
+
}
|
|
1383
|
+
}
|
|
1384
|
+
scheduleReconnect(conversationId) {
|
|
1385
|
+
if (this.reconnectTimers.has(conversationId)) return;
|
|
1386
|
+
const attempt = this.reconnectAttempts.get(conversationId) ?? 0;
|
|
1387
|
+
this.reconnectAttempts.set(conversationId, attempt + 1);
|
|
1388
|
+
const tryConnect = () => {
|
|
1389
|
+
this.reconnectTimers.delete(conversationId);
|
|
1390
|
+
if (this.stopped) return;
|
|
1391
|
+
void this.connectAsync(conversationId);
|
|
1392
|
+
};
|
|
1393
|
+
const delay = Math.min(
|
|
1394
|
+
RECONNECT_BASE_MS * Math.pow(2, attempt) + (Math.random() - 0.5) * RECONNECT_JITTER * RECONNECT_BASE_MS,
|
|
1395
|
+
RECONNECT_MAX_MS
|
|
1396
|
+
);
|
|
1397
|
+
const timer = setTimeout(tryConnect, delay);
|
|
1398
|
+
this.reconnectTimers.set(conversationId, timer);
|
|
1399
|
+
}
|
|
1400
|
+
isSubscribableConversationType(type) {
|
|
1401
|
+
return type === "dm" || type === "pending_dm" || type === "channel" || type === "group";
|
|
1402
|
+
}
|
|
1403
|
+
async connectAll() {
|
|
1404
|
+
try {
|
|
1405
|
+
const convos = await this.opts.listConversations();
|
|
1406
|
+
const subscribable = convos.filter((c) => this.isSubscribableConversationType(c.type));
|
|
1407
|
+
for (const c of subscribable) {
|
|
1408
|
+
void this.connectAsync(c.conversation_id);
|
|
1409
|
+
}
|
|
1410
|
+
} catch (err) {
|
|
1411
|
+
this.opts.onError?.(err instanceof Error ? err : new Error(String(err)));
|
|
1412
|
+
}
|
|
1413
|
+
}
|
|
1414
|
+
async syncConnections() {
|
|
1415
|
+
if (this.stopped) return;
|
|
1416
|
+
try {
|
|
1417
|
+
const convos = await this.opts.listConversations();
|
|
1418
|
+
const subscribableIds = new Set(
|
|
1419
|
+
convos.filter((c) => this.isSubscribableConversationType(c.type)).map((c) => c.conversation_id)
|
|
1420
|
+
);
|
|
1421
|
+
for (const convId of subscribableIds) {
|
|
1422
|
+
if (!this.stoppedConversations.has(convId) && !this.connections.has(convId)) {
|
|
1423
|
+
void this.connectAsync(convId);
|
|
1424
|
+
}
|
|
1425
|
+
}
|
|
1426
|
+
for (const convId of this.connections.keys()) {
|
|
1427
|
+
if (!subscribableIds.has(convId) || this.stoppedConversations.has(convId)) {
|
|
1428
|
+
const ws = this.connections.get(convId);
|
|
1429
|
+
if (ws) {
|
|
1430
|
+
ws.removeAllListeners();
|
|
1431
|
+
ws.close();
|
|
1432
|
+
this.connections.delete(convId);
|
|
1433
|
+
}
|
|
1434
|
+
}
|
|
1435
|
+
}
|
|
1436
|
+
} catch {
|
|
1437
|
+
}
|
|
1438
|
+
}
|
|
1439
|
+
};
|
|
1440
|
+
|
|
1441
|
+
export {
|
|
1442
|
+
HttpTransport,
|
|
1443
|
+
ContactManager,
|
|
1444
|
+
HistoryManager,
|
|
1445
|
+
PingAgentClient,
|
|
1446
|
+
getRootDir,
|
|
1447
|
+
getProfile,
|
|
1448
|
+
getIdentityPath,
|
|
1449
|
+
getStorePath,
|
|
1450
|
+
generateIdentity,
|
|
1451
|
+
identityExists,
|
|
1452
|
+
loadIdentity,
|
|
1453
|
+
saveIdentity,
|
|
1454
|
+
updateStoredToken,
|
|
1455
|
+
ensureTokenValid,
|
|
1456
|
+
LocalStore,
|
|
1457
|
+
A2AAdapter,
|
|
1458
|
+
WsSubscription
|
|
1459
|
+
};
|