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