@agimon-ai/po-session 0.0.0-alpha.21 → 0.0.0-alpha.211

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.
Files changed (38) hide show
  1. package/LICENSE +21 -149
  2. package/README.md +47 -1
  3. package/dist/apiContracts.cjs +34 -2
  4. package/dist/apiContracts.cjs.map +1 -1
  5. package/dist/apiContracts.d.mts +2 -2
  6. package/dist/apiContracts.d.mts.map +1 -1
  7. package/dist/apiContracts.mjs +35 -2
  8. package/dist/apiContracts.mjs.map +1 -1
  9. package/dist/extensions/native.mjs +410 -0
  10. package/dist/extensions/native.mjs.map +1 -0
  11. package/dist/extensions/server.cjs +1661 -113
  12. package/dist/extensions/server.cjs.map +1 -1
  13. package/dist/extensions/server.d.mts.map +1 -1
  14. package/dist/extensions/server.mjs +1657 -109
  15. package/dist/extensions/server.mjs.map +1 -1
  16. package/dist/extensions/web.mjs +361 -0
  17. package/dist/extensions/web.mjs.map +1 -0
  18. package/dist/index.cjs +410 -25
  19. package/dist/index.cjs.map +1 -0
  20. package/dist/index.d.mts +599 -82
  21. package/dist/index.d.mts.map +1 -1
  22. package/dist/index.mjs +358 -1
  23. package/dist/index.mjs.map +1 -0
  24. package/dist/po-runtime-identity.json +1 -0
  25. package/dist/type-BlbiS10p.mjs +2622 -0
  26. package/dist/type-BlbiS10p.mjs.map +1 -0
  27. package/dist/type-DZtqhE4a.cjs +3083 -0
  28. package/dist/type-DZtqhE4a.cjs.map +1 -0
  29. package/llms.txt +4 -1
  30. package/locales/vi.json +29 -0
  31. package/locales/zh-CN.json +29 -0
  32. package/package.json +96 -11
  33. package/src/prompts/codemode-how-to-network/SKILL.md +49 -0
  34. package/src/prompts/codemode-how-to-session/SKILL.md +25 -0
  35. package/dist/sessionDelivery-4svjzWUW.mjs +0 -1028
  36. package/dist/sessionDelivery-4svjzWUW.mjs.map +0 -1
  37. package/dist/sessionDelivery-CGWuQyLV.cjs +0 -1219
  38. package/dist/sessionDelivery-CGWuQyLV.cjs.map +0 -1
@@ -1,1219 +0,0 @@
1
- //#region \0rolldown/runtime.js
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __copyProps = (to, from, except, desc) => {
9
- if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
10
- key = keys[i];
11
- if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
12
- get: ((k) => from[k]).bind(null, key),
13
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
14
- });
15
- }
16
- return to;
17
- };
18
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
19
- value: mod,
20
- enumerable: true
21
- }) : target, mod));
22
- //#endregion
23
- let _agimon_ai_po_core_backgroundWork = require("@agimon-ai/po-core/backgroundWork");
24
- let typebox_value = require("typebox/value");
25
- let node_crypto = require("node:crypto");
26
- let node_path = require("node:path");
27
- node_path = __toESM(node_path, 1);
28
- let _agimon_ai_po_core_platform = require("@agimon-ai/po-core/platform");
29
- let _agimon_ai_po_core_piSettings = require("@agimon-ai/po-core/piSettings");
30
- let node_fs = require("node:fs");
31
- node_fs = __toESM(node_fs, 1);
32
- let node_sqlite = require("node:sqlite");
33
- let node_timers = require("node:timers");
34
- //#region src/services/backgroundWorkService/index.ts
35
- /** Creates the generation-bound, pull-based coordinator shared by session extensions. */
36
- function createBackgroundWorkService(ctx) {
37
- const registrations = /* @__PURE__ */ new Map();
38
- const generation = `po-background-work:${crypto.randomUUID()}`;
39
- const changed = (provider, providerGeneration, kind) => {
40
- ctx.emit(_agimon_ai_po_core_backgroundWork.PO_BACKGROUND_WORK_CHANGED_EVENT, {
41
- provider,
42
- generation: providerGeneration,
43
- kind
44
- });
45
- };
46
- return Object.freeze({
47
- generation,
48
- register(provider) {
49
- if (!provider || typeof provider !== "object" || typeof provider.listActiveWork !== "function") throw new TypeError("A background-work provider must expose listActiveWork().");
50
- const name = provider.provider.trim();
51
- if (!name || name !== provider.provider) throw new TypeError("A background-work provider requires a trimmed, non-empty name.");
52
- const token = Symbol(name);
53
- const providerGeneration = `${name}:${crypto.randomUUID()}`;
54
- registrations.set(name, {
55
- token,
56
- generation: providerGeneration,
57
- provider
58
- });
59
- changed(name, providerGeneration, "registered");
60
- let disposed = false;
61
- return Object.freeze({
62
- provider: name,
63
- generation: providerGeneration,
64
- update() {
65
- if (!disposed && registrations.get(name)?.token === token) changed(name, providerGeneration, "updated");
66
- },
67
- dispose() {
68
- if (disposed) return;
69
- disposed = true;
70
- if (registrations.get(name)?.token !== token) return;
71
- registrations.delete(name);
72
- changed(name, providerGeneration, "unregistered");
73
- }
74
- });
75
- },
76
- snapshot(sessionId) {
77
- const items = [];
78
- const errors = [];
79
- for (const [provider, registration] of registrations) try {
80
- const current = registration.provider.listActiveWork();
81
- if (!Array.isArray(current)) throw new TypeError("listActiveWork() must return an array.");
82
- for (const item of current) {
83
- if (!(0, typebox_value.Check)(_agimon_ai_po_core_backgroundWork.BackgroundProviderWorkItemSchema, item)) throw new TypeError("listActiveWork() returned an invalid item.");
84
- if (sessionId === void 0 || item.sessionId === sessionId) items.push({
85
- provider,
86
- ...item
87
- });
88
- }
89
- } catch (error) {
90
- errors.push({
91
- provider,
92
- message: error instanceof Error ? error.message : String(error)
93
- });
94
- }
95
- return Object.freeze({
96
- items: Object.freeze(items),
97
- errors: Object.freeze(errors)
98
- });
99
- }
100
- });
101
- }
102
- /** Installs one coordinator in the current session service context. */
103
- function provideBackgroundWorkService(context) {
104
- context.provide(_agimon_ai_po_core_backgroundWork.PO_BACKGROUND_WORK_SERVICE, createBackgroundWorkService(context));
105
- }
106
- const PEER_CONFIG_FILE = "peers.json";
107
- const PEER_ROUTE = "/api/plugins/session-peer/inbox";
108
- const PEER_HEADER = "x-po-session-peer";
109
- const TIMESTAMP_HEADER = "x-po-session-timestamp";
110
- const SIGNATURE_HEADER = "x-po-session-signature";
111
- const MAX_CLOCK_SKEW_MS = 3e5;
112
- const MAX_REPLAY_ENTRIES = 1e4;
113
- /** File the replay guard database lives in, beside the peer config. */
114
- const PEER_REPLAY_DATABASE_FILE = "peer-replay.sqlite";
115
- function validId(value) {
116
- return typeof value === "string" && /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u.test(value);
117
- }
118
- function peerOf(value) {
119
- if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
120
- const record = value;
121
- if (!validId(record.hostId) || typeof record.url !== "string" || typeof record.secret !== "string") return void 0;
122
- let url;
123
- try {
124
- url = new URL(record.url);
125
- } catch {
126
- return;
127
- }
128
- if (url.protocol !== "https:" || url.username !== "" || url.password !== "" || url.search !== "" || url.hash !== "") return void 0;
129
- const allowedSessionIds = Array.isArray(record.allowedSessionIds) && record.allowedSessionIds.every(validId) ? record.allowedSessionIds : void 0;
130
- const allowedVoiceSessionIds = Array.isArray(record.allowedVoiceSessionIds) && record.allowedVoiceSessionIds.every(validId) ? record.allowedVoiceSessionIds : [];
131
- if (allowedSessionIds === void 0 || record.secret.length < 32) return void 0;
132
- return {
133
- hostId: record.hostId,
134
- url: url.toString(),
135
- secret: record.secret,
136
- allowedSessionIds,
137
- allowedVoiceSessionIds
138
- };
139
- }
140
- function sessionPeerConfigPath(homeDirectory) {
141
- return node_path.default.join((0, _agimon_ai_po_core_piSettings.poHomeDirectory)(homeDirectory), "session", PEER_CONFIG_FILE);
142
- }
143
- /** Group or other permission bits on the peer config make it untrusted. */
144
- function peerConfigModeIsPrivate(mode) {
145
- return (mode & 63) === 0;
146
- }
147
- /** Validates peer config text. Invalid config fails closed. */
148
- function parseSessionPeerConfig(text) {
149
- let parsed;
150
- try {
151
- parsed = JSON.parse(text);
152
- } catch {
153
- return;
154
- }
155
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return void 0;
156
- const record = parsed;
157
- if (record.version !== 1 || !validId(record.hostId) || !Array.isArray(record.peers)) return void 0;
158
- const peers = record.peers.map(peerOf);
159
- if (peers.some((peer) => peer === void 0)) return void 0;
160
- const resolved = peers;
161
- if (new Set(resolved.map((peer) => peer.hostId)).size !== resolved.length || resolved.some((peer) => peer.hostId === record.hostId)) return void 0;
162
- return {
163
- version: 1,
164
- hostId: record.hostId,
165
- peers: resolved
166
- };
167
- }
168
- /** Replay guard SQL shared by the async guard and the Node-only sync shim. */
169
- const PEER_REPLAY_SQL = Object.freeze({
170
- schema: `
171
- CREATE TABLE IF NOT EXISTS peer_request_replays (
172
- signature TEXT PRIMARY KEY,
173
- expires_at INTEGER NOT NULL
174
- );
175
- `,
176
- removeExpired: "DELETE FROM peer_request_replays WHERE expires_at < ?",
177
- insert: "INSERT OR IGNORE INTO peer_request_replays (signature, expires_at) VALUES (?, ?)",
178
- insertReturning: "INSERT OR IGNORE INTO peer_request_replays (signature, expires_at) VALUES (?, ?) RETURNING signature",
179
- count: "SELECT COUNT(*) AS count FROM peer_request_replays",
180
- trim: `
181
- DELETE FROM peer_request_replays
182
- WHERE signature IN (
183
- SELECT signature FROM peer_request_replays ORDER BY expires_at ASC, signature ASC LIMIT ?
184
- )
185
- `
186
- });
187
- function peerRequestSignature(request) {
188
- return request.headers.get(SIGNATURE_HEADER);
189
- }
190
- function peerReplayExpiry(now) {
191
- return now + MAX_CLOCK_SKEW_MS;
192
- }
193
- function peerReplayOverflow(total) {
194
- return total > MAX_REPLAY_ENTRIES ? total - MAX_REPLAY_ENTRIES : 0;
195
- }
196
- //#endregion
197
- //#region src/services/peerTransport/sync.ts
198
- /**
199
- * Reads operator-provisioned peers. Invalid or unreadable config fails closed.
200
- *
201
- * @deprecated Node-only sync shim; use readSessionPeerConfigAsync. Removed in M2.
202
- */
203
- function readSessionPeerConfig(homeDirectory) {
204
- let text;
205
- try {
206
- const file = sessionPeerConfigPath(homeDirectory);
207
- if (!peerConfigModeIsPrivate(node_fs.default.statSync(file).mode)) return void 0;
208
- text = node_fs.default.readFileSync(file, "utf8");
209
- } catch {
210
- return;
211
- }
212
- return parseSessionPeerConfig(text);
213
- }
214
- /**
215
- * Persists accepted peer signatures so a valid request cannot be replayed within its clock-skew window.
216
- *
217
- * @deprecated Node-only sync shim; use createPeerReplayGuardAsync. Removed in M2.
218
- */
219
- function createPeerReplayGuard(homeDirectory) {
220
- const directory = node_path.default.dirname(sessionPeerConfigPath(homeDirectory));
221
- node_fs.default.mkdirSync(directory, {
222
- recursive: true,
223
- mode: 448
224
- });
225
- const database = new node_sqlite.DatabaseSync(node_path.default.join(directory, PEER_REPLAY_DATABASE_FILE));
226
- database.exec(`PRAGMA journal_mode = WAL;${PEER_REPLAY_SQL.schema}`);
227
- const removeExpired = database.prepare(PEER_REPLAY_SQL.removeExpired);
228
- const insert = database.prepare(PEER_REPLAY_SQL.insert);
229
- const count = database.prepare(PEER_REPLAY_SQL.count);
230
- const trim = database.prepare(PEER_REPLAY_SQL.trim);
231
- return {
232
- admit(request, now = Date.now()) {
233
- const supplied = peerRequestSignature(request);
234
- if (!supplied) return false;
235
- database.exec("BEGIN IMMEDIATE");
236
- try {
237
- removeExpired.run(now);
238
- const accepted = insert.run(supplied, peerReplayExpiry(now)).changes === 1;
239
- const overflow = peerReplayOverflow(Number(count.get().count));
240
- if (overflow > 0) trim.run(overflow);
241
- database.exec("COMMIT");
242
- return accepted;
243
- } catch (cause) {
244
- database.exec("ROLLBACK");
245
- throw cause;
246
- }
247
- },
248
- close: () => database.close()
249
- };
250
- }
251
- //#endregion
252
- //#region src/services/peerTransport/index.ts
253
- /** Reads operator-provisioned peers. Invalid or unreadable config fails closed. */
254
- async function readSessionPeerConfigAsync(fs, homeDirectory, context) {
255
- try {
256
- const file = sessionPeerConfigPath(homeDirectory);
257
- const mode = await _agimon_ai_po_core_platform.nodeHost.fileMode(file);
258
- if (mode !== void 0 && !peerConfigModeIsPrivate(mode)) return void 0;
259
- const text = await (0, _agimon_ai_po_core_platform.readTextIfExists)(fs, file, context);
260
- return text === void 0 ? void 0 : parseSessionPeerConfig(text);
261
- } catch {
262
- return;
263
- }
264
- }
265
- /**
266
- * Creates a directory tree, giving each directory it creates owner-only access, the way
267
- * `mkdirSync(directory, { recursive: true, mode: 0o700 })` does. Existing directories keep their mode.
268
- */
269
- async function ensurePrivateDirectory(fs, directory, context) {
270
- const missing = [];
271
- for (let current = node_path.default.resolve(directory); !(0, _agimon_ai_po_core_platform.getOrThrow)(await fs.exists(current, context));) {
272
- missing.unshift(current);
273
- const parent = node_path.default.dirname(current);
274
- if (parent === current) break;
275
- current = parent;
276
- }
277
- if (missing.length === 0) return;
278
- (0, _agimon_ai_po_core_platform.getOrThrow)(await fs.createDir(directory, { recursive: true }, context));
279
- for (const created of missing) await _agimon_ai_po_core_platform.nodeHost.setMode(created, 448);
280
- }
281
- /** `peer/<host-id>/<session-id>` is the only remote target spelling. */
282
- function parseRemoteSessionReference(value) {
283
- const match = /^peer\/([^/]+)\/([^/]+)$/u.exec(value);
284
- return match && validId(match[1]) && validId(match[2]) ? {
285
- hostId: match[1],
286
- sessionId: match[2]
287
- } : void 0;
288
- }
289
- function peerSessionReference(hostId, sessionId) {
290
- if (!validId(hostId) || !validId(sessionId)) throw new TypeError("Remote host and session identifiers must be safe opaque IDs.");
291
- return `peer/${hostId}/${sessionId}`;
292
- }
293
- function signature(secret, method, pathname, timestamp, body) {
294
- const digest = (0, node_crypto.createHash)("sha256").update(body).digest("base64url");
295
- return (0, node_crypto.createHmac)("sha256", secret).update(`${method}\n${pathname}\n${timestamp}\n${digest}`).digest("base64url");
296
- }
297
- function peerRequestHeaders(sourceHostId, peer, method, pathname, body, now = Date.now()) {
298
- if (!validId(sourceHostId)) throw new TypeError("Source host identity must be a safe opaque ID.");
299
- const timestamp = String(now);
300
- return new Headers({
301
- "content-type": "application/json",
302
- [PEER_HEADER]: sourceHostId,
303
- [TIMESTAMP_HEADER]: timestamp,
304
- [SIGNATURE_HEADER]: signature(peer.secret, method, pathname, timestamp, body)
305
- });
306
- }
307
- /**
308
- * Persists accepted peer signatures so a valid request cannot be replayed within its clock-skew window.
309
- * Takes over the database and closes it in `close()`.
310
- */
311
- async function createPeerReplayGuardAsync(database) {
312
- await database.exec(PEER_REPLAY_SQL.schema);
313
- return {
314
- async admit(request, now = Date.now()) {
315
- const supplied = peerRequestSignature(request);
316
- if (!supplied) return false;
317
- return database.transaction(async (transaction) => {
318
- await transaction.run(PEER_REPLAY_SQL.removeExpired, now);
319
- const accepted = await transaction.get(PEER_REPLAY_SQL.insertReturning, supplied, peerReplayExpiry(now)) !== void 0;
320
- const row = await transaction.get(PEER_REPLAY_SQL.count);
321
- const overflow = peerReplayOverflow(Number(row?.count ?? 0));
322
- if (overflow > 0) await transaction.run(PEER_REPLAY_SQL.trim, overflow);
323
- return accepted;
324
- });
325
- },
326
- close: () => database.close()
327
- };
328
- }
329
- function verifyPeerRequest(config, request, body, now = Date.now()) {
330
- const hostId = request.headers.get(PEER_HEADER);
331
- const timestamp = request.headers.get(TIMESTAMP_HEADER);
332
- const supplied = request.headers.get(SIGNATURE_HEADER);
333
- if (!hostId || !timestamp || !supplied || !/^\d{1,16}$/u.test(timestamp)) return void 0;
334
- const sentAt = Number(timestamp);
335
- if (!Number.isSafeInteger(sentAt) || Math.abs(now - sentAt) > 3e5) return void 0;
336
- const peer = config.peers.find((candidate) => candidate.hostId === hostId);
337
- if (!peer) return void 0;
338
- const expected = Buffer.from(signature(peer.secret, request.method, new URL(request.url).pathname, timestamp, body));
339
- const actual = Buffer.from(supplied);
340
- return actual.byteLength === expected.byteLength && (0, node_crypto.timingSafeEqual)(actual, expected) ? peer : void 0;
341
- }
342
- function envelopeOf$1(value) {
343
- if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
344
- const record = value;
345
- return validId(record.sourceSessionId) && validId(record.targetSessionId) && typeof record.type === "string" && record.type !== "" ? {
346
- sourceSessionId: record.sourceSessionId,
347
- targetSessionId: record.targetSessionId,
348
- type: record.type,
349
- payload: record.payload
350
- } : void 0;
351
- }
352
- function parseSessionPeerEnvelope(value) {
353
- return envelopeOf$1(value);
354
- }
355
- /** Adds asynchronous tunnel publication to a host-bound local communication endpoint. */
356
- function createPeerCommunication(options) {
357
- const config = options.config;
358
- const send = options.fetch ?? fetch;
359
- return {
360
- sessionId: options.local.sessionId,
361
- publish(target, type, payload) {
362
- const remote = parseRemoteSessionReference(target);
363
- if (!remote) return options.local.publish(target, type, payload);
364
- const peer = config?.peers.find((candidate) => candidate.hostId === remote.hostId);
365
- if (!config || !peer || !peer.allowedSessionIds.includes(remote.sessionId)) return false;
366
- const body = JSON.stringify({
367
- sourceSessionId: options.local.sessionId,
368
- targetSessionId: remote.sessionId,
369
- type,
370
- payload
371
- });
372
- const url = new URL(PEER_ROUTE, peer.url);
373
- send(url, {
374
- method: "POST",
375
- headers: peerRequestHeaders(config.hostId, peer, "POST", "/inbox", body),
376
- body
377
- }).catch(() => void 0);
378
- return true;
379
- },
380
- subscribe: (type, listener) => options.local.subscribe(type, listener),
381
- onPeerReady: (listener) => options.local.onPeerReady(listener),
382
- close: () => options.local.close()
383
- };
384
- }
385
- //#endregion
386
- //#region src/services/sessionDirectory/index.ts
387
- const UNKNOWN_FACTS = Object.freeze({
388
- reachability: "unknown",
389
- runtime: "unknown",
390
- activity: "unknown",
391
- voice: Object.freeze({
392
- eligible: "unknown",
393
- readiness: "unknown"
394
- })
395
- });
396
- function keyOf(observation) {
397
- return peerSessionReference(observation.hostId, observation.sessionId);
398
- }
399
- function publicEntry(observation, now, label, capabilities) {
400
- const freshUntil = observation.observedAt + observation.staleAfterMs;
401
- const fresh = now <= freshUntil;
402
- const facts = fresh ? observation : UNKNOWN_FACTS;
403
- return Object.freeze({
404
- reference: keyOf(observation),
405
- ...label === void 0 ? {} : { label },
406
- capabilities: Object.freeze([...capabilities]),
407
- hostIncarnation: observation.hostIncarnation,
408
- sessionIncarnation: observation.sessionIncarnation,
409
- sequence: observation.sequence,
410
- observedAt: observation.observedAt,
411
- freshUntil,
412
- fresh,
413
- reachability: facts.reachability,
414
- runtime: facts.runtime,
415
- activity: facts.activity,
416
- voice: Object.freeze({ ...facts.voice })
417
- });
418
- }
419
- /** In-memory authenticated presence cache. Restart deliberately forgets every observation. */
420
- function createSessionDirectory(options) {
421
- const now = options.now ?? Date.now;
422
- const observations = /* @__PURE__ */ new Map();
423
- const snapshotRequired = /* @__PURE__ */ new Set();
424
- const subscribers = /* @__PURE__ */ new Set();
425
- const discover = async (callerReference, allowedReferences) => {
426
- const result = [];
427
- for (const observation of Array.from(observations.values())) {
428
- const reference = keyOf(observation);
429
- if (allowedReferences && !allowedReferences.has(reference)) continue;
430
- const grant = await options.authorizeDiscovery(callerReference, observation);
431
- if (!grant) continue;
432
- result.push(publicEntry(observation, now(), grant.label ?? observation.label, grant.capabilities));
433
- }
434
- return result.sort((left, right) => left.reference.localeCompare(right.reference));
435
- };
436
- const push = (subscriber) => {
437
- subscriber.queue = subscriber.queue.then(async () => {
438
- if (!subscribers.has(subscriber)) return;
439
- const sessions = await discover(subscriber.callerReference);
440
- if (subscribers.has(subscriber)) subscriber.listener(sessions);
441
- }).catch(() => void 0);
442
- };
443
- const notify = () => {
444
- for (const subscriber of subscribers) push(subscriber);
445
- };
446
- return {
447
- observe(observation) {
448
- const key = keyOf(observation);
449
- const current = observations.get(key);
450
- if (snapshotRequired.has(observation.hostId)) return false;
451
- if (current?.hostIncarnation === observation.hostIncarnation) {
452
- if (current.sessionIncarnation === observation.sessionIncarnation && observation.sequence <= current.sequence) return false;
453
- if (observation.sequence !== current.sequence + 1) {
454
- snapshotRequired.add(observation.hostId);
455
- for (const [reference, candidate] of observations) if (candidate.hostId === observation.hostId) observations.set(reference, {
456
- ...candidate,
457
- ...UNKNOWN_FACTS,
458
- observedAt: now(),
459
- staleAfterMs: 0
460
- });
461
- notify();
462
- return false;
463
- }
464
- }
465
- observations.set(key, Object.freeze({
466
- ...observation,
467
- voice: Object.freeze({ ...observation.voice })
468
- }));
469
- notify();
470
- return true;
471
- },
472
- replaceHostSnapshot(hostId, hostIncarnation, replacements) {
473
- if (replacements.some((observation) => observation.hostId !== hostId || observation.hostIncarnation !== hostIncarnation)) throw new TypeError("A presence snapshot must contain only the declared host incarnation.");
474
- for (const [reference, observation] of observations) if (observation.hostId === hostId) observations.delete(reference);
475
- for (const observation of replacements) observations.set(keyOf(observation), Object.freeze({
476
- ...observation,
477
- voice: Object.freeze({ ...observation.voice })
478
- }));
479
- snapshotRequired.delete(hostId);
480
- notify();
481
- },
482
- hostDisconnected(hostId) {
483
- for (const [reference, observation] of observations) {
484
- if (observation.hostId !== hostId) continue;
485
- observations.set(reference, {
486
- ...observation,
487
- reachability: "unreachable"
488
- });
489
- }
490
- notify();
491
- },
492
- discover,
493
- async resolveDeliveryTarget(callerReference, reference) {
494
- const observation = observations.get(reference);
495
- return observation && await options.authorizeDiscovery(callerReference, observation) ? observation.deliveryTarget : void 0;
496
- },
497
- subscribe(callerReference, listener) {
498
- const subscriber = {
499
- callerReference,
500
- listener,
501
- queue: Promise.resolve()
502
- };
503
- subscribers.add(subscriber);
504
- push(subscriber);
505
- return () => subscribers.delete(subscriber);
506
- }
507
- };
508
- }
509
- //#endregion
510
- //#region src/services/sessionGroups/type.ts
511
- var SessionGroupRevisionError = class extends Error {
512
- constructor(groupId, expected, actual) {
513
- super(`Session group '${groupId}' revision conflict: expected ${expected}, current ${actual}.`);
514
- this.name = "SessionGroupRevisionError";
515
- }
516
- };
517
- //#endregion
518
- //#region src/services/sessionGroups/index.ts
519
- const ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u;
520
- const REFERENCE_PATTERN = /^peer\/[A-Za-z0-9][A-Za-z0-9._-]{0,127}\/[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/u;
521
- function validateGroupId(value) {
522
- if (!ID_PATTERN.test(value)) throw new TypeError("Session group IDs must be safe opaque IDs.");
523
- }
524
- function validateReference(value) {
525
- if (!REFERENCE_PATTERN.test(value)) throw new TypeError(`Session group member '${value}' is not a qualified reference.`);
526
- }
527
- const SCHEMA$1 = `
528
- CREATE TABLE IF NOT EXISTS session_groups (
529
- group_id TEXT PRIMARY KEY,
530
- owner_authority TEXT NOT NULL,
531
- revision INTEGER NOT NULL
532
- );
533
- CREATE TABLE IF NOT EXISTS session_group_members (
534
- group_id TEXT NOT NULL REFERENCES session_groups(group_id) ON DELETE CASCADE,
535
- member_reference TEXT NOT NULL,
536
- PRIMARY KEY (group_id, member_reference)
537
- );
538
- `;
539
- async function readGroup(database, groupId) {
540
- const row = await database.get("SELECT * FROM session_groups WHERE group_id = ?", groupId);
541
- if (!row) return void 0;
542
- const members = await database.all("SELECT member_reference FROM session_group_members WHERE group_id = ? ORDER BY member_reference", groupId);
543
- return Object.freeze({
544
- id: row.group_id,
545
- ownerAuthority: row.owner_authority,
546
- revision: Number(row.revision),
547
- members: Object.freeze(members.map((member) => member.member_reference))
548
- });
549
- }
550
- /** Opens a revisioned SQLite registry for communication-only group membership. */
551
- async function createSessionGroupStore(options) {
552
- const { database } = options;
553
- try {
554
- await database.exec("PRAGMA foreign_keys = ON");
555
- } catch {}
556
- await database.exec(SCHEMA$1);
557
- const enroll = async (transaction, groupId, members) => {
558
- for (const member of new Set(members)) {
559
- validateReference(member);
560
- if (options.validateEnrollment?.(groupId, member) === false) throw new Error(`Session group enrollment policy rejected '${member}'.`);
561
- await transaction.run("INSERT OR IGNORE INTO session_group_members (group_id, member_reference) VALUES (?, ?)", groupId, member);
562
- }
563
- };
564
- return {
565
- async create(groupId, ownerAuthority, members) {
566
- validateGroupId(groupId);
567
- if (!ownerAuthority.trim()) throw new TypeError("Session group owner authority is required.");
568
- return database.transaction(async (transaction) => {
569
- await transaction.run("INSERT INTO session_groups (group_id, owner_authority, revision) VALUES (?, ?, 1)", groupId, ownerAuthority);
570
- await enroll(transaction, groupId, members);
571
- return await readGroup(transaction, groupId);
572
- });
573
- },
574
- async mutate(mutation) {
575
- return database.transaction(async (transaction) => {
576
- const current = await readGroup(transaction, mutation.groupId);
577
- if (!current) throw new Error(`Session group '${mutation.groupId}' does not exist.`);
578
- if (mutation.authority !== current.ownerAuthority && options.authorizeManagement?.(mutation.authority, current) !== true) throw new Error(`Authority '${mutation.authority}' cannot manage Session group '${mutation.groupId}'.`);
579
- if (mutation.expectedRevision !== current.revision) throw new SessionGroupRevisionError(mutation.groupId, mutation.expectedRevision, current.revision);
580
- await enroll(transaction, mutation.groupId, mutation.add ?? []);
581
- for (const member of new Set(mutation.remove ?? [])) {
582
- validateReference(member);
583
- await transaction.run("DELETE FROM session_group_members WHERE group_id = ? AND member_reference = ?", mutation.groupId, member);
584
- }
585
- await transaction.run("UPDATE session_groups SET revision = revision + 1 WHERE group_id = ? AND revision = ?", mutation.groupId, current.revision);
586
- return await readGroup(transaction, mutation.groupId);
587
- });
588
- },
589
- get: (groupId) => readGroup(database, groupId),
590
- async groupsFor(memberReference) {
591
- validateReference(memberReference);
592
- const rows = await database.all(`SELECT g.group_id FROM session_groups g
593
- INNER JOIN session_group_members m ON m.group_id = g.group_id
594
- WHERE m.member_reference = ? ORDER BY g.group_id`, memberReference);
595
- const groups = [];
596
- for (const row of rows) {
597
- const group = await readGroup(database, row.group_id);
598
- if (group) groups.push(group);
599
- }
600
- return groups;
601
- },
602
- async canMessage(groupId, sourceReference, targetReference) {
603
- validateReference(sourceReference);
604
- validateReference(targetReference);
605
- const row = await database.get(`SELECT COUNT(*) AS count FROM session_group_members
606
- WHERE group_id = ? AND member_reference IN (?, ?)`, groupId, sourceReference, targetReference);
607
- return Number(row?.count ?? 0) === (sourceReference === targetReference ? 1 : 2);
608
- },
609
- close: () => database.close()
610
- };
611
- }
612
- //#endregion
613
- //#region src/services/sessionIntercom/type.ts
614
- const PO_SESSION_INTERCOM_SERVICE = "po/session-intercom";
615
- function readSessionIntercom(context) {
616
- return context.get(PO_SESSION_INTERCOM_SERVICE);
617
- }
618
- function requireSessionIntercom(context) {
619
- const service = readSessionIntercom(context);
620
- if (!service) throw new Error("Session intercom is unavailable. Activate Session with a configured persistent host identity.");
621
- return service;
622
- }
623
- //#endregion
624
- //#region src/services/sessionIntercom/index.ts
625
- const MESSAGE_KIND = "session-message";
626
- const REPORT_KIND = "session-report";
627
- async function metadataFor(options, request, reportStatus) {
628
- const group = await options.groups.get(request.groupId);
629
- if (!group || !await options.groups.canMessage(request.groupId, options.selfReference, request.targetReference)) throw new Error(`Session group '${request.groupId}' does not authorize this message.`);
630
- return {
631
- sourceReference: options.selfReference,
632
- targetReference: request.targetReference,
633
- groupId: request.groupId,
634
- groupRevision: String(group.revision),
635
- ...request.correlationId === void 0 ? {} : { correlationId: request.correlationId },
636
- ...reportStatus === void 0 ? {} : { reportStatus }
637
- };
638
- }
639
- /** The group IDs, among those given, whose current membership includes this session. */
640
- async function groupMembership(options, groupIds) {
641
- const memberOf = /* @__PURE__ */ new Set();
642
- for (const groupId of new Set(groupIds)) {
643
- if (groupId === void 0) continue;
644
- if ((await options.groups.get(groupId))?.members.includes(options.selfReference) === true) memberOf.add(groupId);
645
- }
646
- return memberOf;
647
- }
648
- /** Agent-facing intercom operations. A composition may acquire this service without gaining session controls. */
649
- function createSessionIntercom(options) {
650
- const deliver = async (request, kind, status) => {
651
- const recipientKey = await options.directory.resolveDeliveryTarget(options.selfReference, request.targetReference);
652
- if (!recipientKey) throw new Error(`Session '${request.targetReference}' is not discoverable.`);
653
- const metadata = await metadataFor(options, request, status);
654
- return options.delivery.deliver({
655
- ...request.deliveryId === void 0 ? {} : { deliveryId: request.deliveryId },
656
- recipientKey,
657
- kind,
658
- prompt: `[Session ${status === void 0 ? "message" : `report: ${status}`} from ${options.selfReference}] ${request.text}`,
659
- metadata
660
- });
661
- };
662
- return Object.freeze({
663
- async discover() {
664
- const members = new Set((await options.groups.groupsFor(options.selfReference)).flatMap((group) => group.members).filter((reference) => reference !== options.selfReference));
665
- return options.directory.discover(options.selfReference, members);
666
- },
667
- send: (request) => deliver(request, MESSAGE_KIND),
668
- report: (request) => deliver(request, REPORT_KIND, request.status),
669
- async messages() {
670
- const entries = (await options.delivery.inbox()).filter((entry) => entry.kind === MESSAGE_KIND || entry.kind === REPORT_KIND);
671
- const memberOf = await groupMembership(options, entries.map((entry) => entry.metadata.groupId));
672
- return entries.filter((entry) => {
673
- const groupId = entry.metadata.groupId;
674
- return groupId !== void 0 && memberOf.has(groupId);
675
- }).flatMap((entry) => {
676
- const sourceReference = entry.metadata.sourceReference;
677
- const targetReference = entry.metadata.targetReference;
678
- const groupId = entry.metadata.groupId;
679
- if (!sourceReference || !targetReference || !groupId) return [];
680
- const reportStatus = entry.metadata.reportStatus;
681
- return [{
682
- deliveryId: entry.deliveryId,
683
- sourceReference,
684
- targetReference,
685
- groupId,
686
- ...entry.metadata.correlationId === void 0 ? {} : { correlationId: entry.metadata.correlationId },
687
- text: entry.prompt,
688
- ...reportStatus === "done" || reportStatus === "blocked" || reportStatus === "failed" ? { reportStatus } : {},
689
- state: entry.state,
690
- consumed: entry.consumed
691
- }];
692
- });
693
- },
694
- async delivery(deliveryId) {
695
- const entry = await options.delivery.outbox(deliveryId);
696
- const groupId = entry?.metadata.groupId;
697
- return entry && groupId !== void 0 && (await groupMembership(options, [groupId])).has(groupId) ? entry : void 0;
698
- }
699
- });
700
- }
701
- /** Builds the dynamic delivery check used before every send, retry, and recipient acceptance. */
702
- function createSessionGroupDeliveryAuthorizer(options) {
703
- return async (peerKey, metadata) => {
704
- const sourceReference = metadata?.sourceReference;
705
- const targetReference = metadata?.targetReference;
706
- const groupId = metadata?.groupId;
707
- if (sourceReference && targetReference && groupId) {
708
- const peerReference = options.peerReference(peerKey);
709
- if (!peerReference) return false;
710
- return (sourceReference === options.selfReference && targetReference === peerReference || targetReference === options.selfReference && sourceReference === peerReference) && await options.groups.canMessage(groupId, sourceReference, targetReference);
711
- }
712
- return await options.fallback?.(peerKey, metadata) === true;
713
- };
714
- }
715
- //#endregion
716
- //#region src/services/sessionDelivery/type.ts
717
- const PO_SESSION_DELIVERY_SERVICE = "po/session-delivery";
718
- /** Reads the currently active provider each time, without retaining a stale binding. */
719
- function readPoSessionDelivery(context) {
720
- return context.get(PO_SESSION_DELIVERY_SERVICE);
721
- }
722
- //#endregion
723
- //#region src/services/sessionDelivery/index.ts
724
- const DELIVERY_EVENT = "po/session-delivery/envelope";
725
- const ACK_EVENT = "po/session-delivery/ack";
726
- const DEFAULT_DELIVERY = "prompt";
727
- const INBOX_STATES = /* @__PURE__ */ new Set([
728
- "accepted",
729
- "admitting",
730
- "admitted",
731
- "recovery_required"
732
- ]);
733
- function isRecord(value) {
734
- return typeof value === "object" && value !== null && !Array.isArray(value);
735
- }
736
- function isMode(value) {
737
- return value === "prompt" || value === "steer" || value === "followUp";
738
- }
739
- function metadataOf(value) {
740
- if (!isRecord(value)) return void 0;
741
- const metadata = {};
742
- for (const [key, item] of Object.entries(value)) {
743
- if (typeof item !== "string") return void 0;
744
- metadata[key] = item;
745
- }
746
- return metadata;
747
- }
748
- function envelopeOf(value) {
749
- if (!isRecord(value)) return void 0;
750
- const metadata = metadataOf(value.metadata);
751
- if (typeof value.deliveryId !== "string" || !value.deliveryId || typeof value.kind !== "string" || !value.kind || typeof value.prompt !== "string" || !isMode(value.delivery) || metadata === void 0) return;
752
- return {
753
- deliveryId: value.deliveryId,
754
- kind: value.kind,
755
- prompt: value.prompt,
756
- delivery: value.delivery,
757
- metadata
758
- };
759
- }
760
- function ackOf(value) {
761
- if (!isRecord(value)) return void 0;
762
- if (typeof value.deliveryId !== "string" || typeof value.state !== "string" || !INBOX_STATES.has(value.state)) return;
763
- return value;
764
- }
765
- function normalizedMetadata(metadata) {
766
- const normalized = {};
767
- for (const [key, value] of Object.entries(metadata ?? {})) if (value !== void 0) normalized[key] = value;
768
- return normalized;
769
- }
770
- function matchesMetadata(entry, query) {
771
- return Object.entries(query ?? {}).every(([key, value]) => value === void 0 || entry[key] === value);
772
- }
773
- function sameMetadata(left, right) {
774
- return matchesMetadata(left, right) && matchesMetadata(right, left);
775
- }
776
- const SCHEMA = `
777
- CREATE TABLE IF NOT EXISTS session_delivery_outbox (
778
- delivery_id TEXT PRIMARY KEY,
779
- recipient_key TEXT NOT NULL,
780
- kind TEXT NOT NULL,
781
- prompt TEXT NOT NULL,
782
- delivery_mode TEXT NOT NULL,
783
- metadata_json TEXT NOT NULL,
784
- state TEXT NOT NULL,
785
- recipient_state TEXT,
786
- created_at INTEGER NOT NULL,
787
- acknowledged_at INTEGER
788
- );
789
- CREATE TABLE IF NOT EXISTS session_delivery_inbox (
790
- delivery_id TEXT PRIMARY KEY,
791
- sender_key TEXT NOT NULL,
792
- recipient_key TEXT NOT NULL,
793
- kind TEXT NOT NULL,
794
- prompt TEXT NOT NULL,
795
- delivery_mode TEXT NOT NULL,
796
- metadata_json TEXT NOT NULL,
797
- state TEXT NOT NULL,
798
- created_at INTEGER NOT NULL,
799
- updated_at INTEGER NOT NULL,
800
- consumed_at INTEGER
801
- );
802
- `;
803
- const SET_INBOX_STATE = "UPDATE session_delivery_inbox SET state = ?, updated_at = ? WHERE delivery_id = ?";
804
- const UNSETTLED_OUTBOX = "(recipient_state IS NULL OR recipient_state NOT IN ('admitted', 'recovery_required'))";
805
- /** Opens and starts one durable delivery endpoint. */
806
- async function createSessionDeliveryService(options) {
807
- if (!options.recipientKey.trim() || options.recipientKey !== options.recipientKey.trim()) throw new TypeError("Session delivery requires a trimmed, non-empty recipient key.");
808
- const database = options.database;
809
- try {
810
- await database.exec(SCHEMA);
811
- await database.run("UPDATE session_delivery_inbox SET state = 'accepted', updated_at = ? WHERE state = 'admitting'", Date.now());
812
- } catch (error) {
813
- await database.close();
814
- throw error;
815
- }
816
- let closed = false;
817
- const scheduled = /* @__PURE__ */ new Set();
818
- let admissionQueue = Promise.resolve();
819
- const pending = /* @__PURE__ */ new Set();
820
- /** Tracks fire-and-forget work so close() can wait for it before the database closes. */
821
- const track = (work) => {
822
- const settled = work.catch(() => void 0);
823
- pending.add(settled);
824
- settled.finally(() => pending.delete(settled));
825
- };
826
- const authorized = async (peerKey, metadata) => await options.authorizePeer(peerKey, metadata) === true;
827
- const publishAck = (deliveryId, senderKey, state) => {
828
- options.communication.publish(senderKey, ACK_EVENT, {
829
- deliveryId,
830
- state
831
- });
832
- };
833
- const readInboxRow = (deliveryId) => database.get("SELECT * FROM session_delivery_inbox WHERE delivery_id = ?", deliveryId);
834
- const scheduleAdmission = (deliveryId) => {
835
- if (closed || scheduled.has(deliveryId)) return;
836
- scheduled.add(deliveryId);
837
- admissionQueue = admissionQueue.then(async () => {
838
- try {
839
- if (closed) return;
840
- const row = await database.get("UPDATE session_delivery_inbox SET state = 'admitting', updated_at = ? WHERE delivery_id = ? AND state = 'accepted' RETURNING *", Date.now(), deliveryId);
841
- if (!row) return;
842
- publishAck(deliveryId, row.sender_key, "admitting");
843
- try {
844
- await options.admitPrompt(row.prompt, row.delivery_mode, deliveryId);
845
- } catch {
846
- await database.run(SET_INBOX_STATE, "recovery_required", Date.now(), deliveryId);
847
- publishAck(deliveryId, row.sender_key, "recovery_required");
848
- return;
849
- }
850
- await database.run(SET_INBOX_STATE, "admitted", Date.now(), deliveryId);
851
- publishAck(deliveryId, row.sender_key, "admitted");
852
- } finally {
853
- scheduled.delete(deliveryId);
854
- }
855
- }).catch(async () => {
856
- scheduled.delete(deliveryId);
857
- try {
858
- const row = await readInboxRow(deliveryId);
859
- if (row?.state !== "admitting") return;
860
- await database.run(SET_INBOX_STATE, "recovery_required", Date.now(), deliveryId);
861
- try {
862
- publishAck(deliveryId, row.sender_key, "recovery_required");
863
- } catch {}
864
- } catch {}
865
- });
866
- };
867
- const receiveEnvelope = async (senderKey, value) => {
868
- if (closed) return void 0;
869
- const envelope = envelopeOf(value);
870
- if (!envelope || !await authorized(senderKey, envelope.metadata) || closed) return void 0;
871
- await database.run(`INSERT OR IGNORE INTO session_delivery_inbox
872
- (delivery_id, sender_key, recipient_key, kind, prompt, delivery_mode, metadata_json, state, created_at, updated_at)
873
- VALUES (?, ?, ?, ?, ?, ?, ?, 'accepted', ?, ?)`, envelope.deliveryId, senderKey, options.recipientKey, envelope.kind, envelope.prompt, envelope.delivery, JSON.stringify(envelope.metadata), Date.now(), Date.now());
874
- const current = await readInboxRow(envelope.deliveryId);
875
- if (!current) return void 0;
876
- if (!(current.sender_key === senderKey && current.recipient_key === options.recipientKey && current.kind === envelope.kind && current.prompt === envelope.prompt && current.delivery_mode === envelope.delivery && sameMetadata(JSON.parse(current.metadata_json), envelope.metadata))) return void 0;
877
- publishAck(envelope.deliveryId, current.sender_key, current.state);
878
- if (current.state === "accepted") scheduleAdmission(envelope.deliveryId);
879
- return current.state;
880
- };
881
- const receiveAck = async (recipientKey, value) => {
882
- const ack = ackOf(value);
883
- if (closed || !ack) return;
884
- await database.run(`UPDATE session_delivery_outbox
885
- SET state = 'acknowledged', recipient_state = ?, acknowledged_at = ?
886
- WHERE delivery_id = ? AND recipient_key = ?
887
- AND (recipient_state IS NULL
888
- OR (recipient_state = 'accepted' AND ? != 'accepted')
889
- OR (recipient_state = 'admitting' AND ? IN ('admitted', 'recovery_required')))`, ack.state, Date.now(), ack.deliveryId, recipientKey, ack.state, ack.state);
890
- };
891
- const publishOutbox = async (deliveryId) => {
892
- if (closed) return;
893
- const row = await database.get(`SELECT * FROM session_delivery_outbox WHERE delivery_id = ? AND ${UNSETTLED_OUTBOX}`, deliveryId);
894
- if (!row) return;
895
- const metadata = JSON.parse(row.metadata_json);
896
- if (!await authorized(row.recipient_key, metadata) || closed) return;
897
- options.communication.publish(row.recipient_key, DELIVERY_EVENT, {
898
- deliveryId: row.delivery_id,
899
- kind: row.kind,
900
- prompt: row.prompt,
901
- delivery: row.delivery_mode,
902
- metadata
903
- });
904
- };
905
- const publishQueued = async (recipientKey) => {
906
- if (closed) return;
907
- for (const row of await database.all(`SELECT delivery_id FROM session_delivery_outbox WHERE recipient_key = ? AND ${UNSETTLED_OUTBOX}`, recipientKey)) await publishOutbox(row.delivery_id);
908
- };
909
- let retryTimer;
910
- const startRetry = () => {
911
- if (closed || retryTimer) return;
912
- retryTimer = (0, node_timers.setInterval)(() => track(publishAllQueued()), 1e3);
913
- retryTimer.unref?.();
914
- };
915
- const stopRetry = () => {
916
- if (retryTimer) (0, node_timers.clearInterval)(retryTimer);
917
- retryTimer = void 0;
918
- };
919
- let retrying;
920
- const publishAllQueued = () => {
921
- retrying ??= (async () => {
922
- try {
923
- if (closed) return;
924
- const rows = await database.all(`SELECT delivery_id FROM session_delivery_outbox WHERE ${UNSETTLED_OUTBOX}`);
925
- if (rows.length === 0) stopRetry();
926
- else startRetry();
927
- for (const row of rows) await publishOutbox(row.delivery_id);
928
- } finally {
929
- retrying = void 0;
930
- }
931
- })();
932
- return retrying;
933
- };
934
- const releaseEnvelope = options.communication.subscribe(DELIVERY_EVENT, (senderKey, payload) => {
935
- track(receiveEnvelope(senderKey, payload));
936
- });
937
- const releaseAck = options.communication.subscribe(ACK_EVENT, (recipientKey, payload) => {
938
- track(receiveAck(recipientKey, payload));
939
- });
940
- const releaseReady = options.communication.onPeerReady((recipientKey) => {
941
- track(publishQueued(recipientKey));
942
- });
943
- for (const row of await database.all("SELECT delivery_id, sender_key FROM session_delivery_inbox WHERE state = 'recovery_required'")) publishAck(row.delivery_id, row.sender_key, "recovery_required");
944
- for (const row of await database.all("SELECT delivery_id FROM session_delivery_inbox WHERE state = 'accepted'")) scheduleAdmission(row.delivery_id);
945
- track(publishAllQueued());
946
- return Object.freeze({
947
- recipientKey: options.recipientKey,
948
- async deliver(request) {
949
- if (closed) throw new Error("Session delivery service is closed.");
950
- const deliveryId = request.deliveryId ?? crypto.randomUUID();
951
- const mode = request.delivery ?? DEFAULT_DELIVERY;
952
- if (!deliveryId.trim() || !request.recipientKey.trim() || !request.kind.trim() || !isMode(mode)) throw new TypeError("Delivery id, recipient key, kind, and mode must be valid.");
953
- if (!await authorized(request.recipientKey, request.metadata)) throw new Error(`Session '${request.recipientKey}' is not an authorized communication peer.`);
954
- if (closed) throw new Error("Session delivery service is closed.");
955
- const metadata = normalizedMetadata(request.metadata);
956
- await database.run(`INSERT OR IGNORE INTO session_delivery_outbox
957
- (delivery_id, recipient_key, kind, prompt, delivery_mode, metadata_json, state, created_at)
958
- VALUES (?, ?, ?, ?, ?, ?, 'queued', ?)`, deliveryId, request.recipientKey, request.kind, request.prompt, mode, JSON.stringify(metadata), Date.now());
959
- const current = await database.get("SELECT * FROM session_delivery_outbox WHERE delivery_id = ?", deliveryId);
960
- if (!current || current.recipient_key !== request.recipientKey || current.kind !== request.kind || current.prompt !== request.prompt || current.delivery_mode !== mode || !sameMetadata(JSON.parse(current.metadata_json), metadata)) throw new TypeError(`Delivery id '${deliveryId}' is already bound to another envelope.`);
961
- startRetry();
962
- await publishOutbox(deliveryId);
963
- return { deliveryId };
964
- },
965
- async waitForAdmission(deliveryId, timeoutMs = 5e3) {
966
- const deadline = Date.now() + Math.max(0, timeoutMs);
967
- let state;
968
- do {
969
- state = (await database.get("SELECT recipient_state FROM session_delivery_outbox WHERE delivery_id = ?", deliveryId))?.recipient_state ?? void 0;
970
- if (state === "admitted" || state === "recovery_required") return state;
971
- if (Date.now() >= deadline) return state;
972
- await new Promise((resolve) => (0, node_timers.setTimeout)(resolve, Math.min(10, deadline - Date.now())));
973
- } while (!closed);
974
- return state;
975
- },
976
- async receive(senderKey, kind, payload) {
977
- if (kind === DELIVERY_EVENT) return receiveEnvelope(senderKey, payload);
978
- if (kind === ACK_EVENT) {
979
- await receiveAck(senderKey, payload);
980
- return "accepted";
981
- }
982
- },
983
- async inbox(query = {}) {
984
- return (await database.all("SELECT * FROM session_delivery_inbox ORDER BY created_at, delivery_id")).map((row) => {
985
- const metadata = JSON.parse(row.metadata_json);
986
- return {
987
- deliveryId: row.delivery_id,
988
- senderKey: row.sender_key,
989
- recipientKey: row.recipient_key,
990
- kind: row.kind,
991
- prompt: row.prompt,
992
- delivery: row.delivery_mode,
993
- metadata,
994
- state: row.state,
995
- consumed: row.consumed_at !== null
996
- };
997
- }).filter((entry) => (query.kind === void 0 || entry.kind === query.kind) && (query.state === void 0 || entry.state === query.state) && (query.consumed === void 0 || entry.consumed === query.consumed) && matchesMetadata(entry.metadata, query.metadata));
998
- },
999
- async consume(deliveryId) {
1000
- return await database.get("UPDATE session_delivery_inbox SET consumed_at = ? WHERE delivery_id = ? AND state IN ('admitted', 'recovery_required') AND consumed_at IS NULL RETURNING delivery_id", Date.now(), deliveryId) !== void 0;
1001
- },
1002
- async outbox(deliveryId) {
1003
- const row = await database.get("SELECT delivery_id, recipient_key, kind, metadata_json, state, recipient_state FROM session_delivery_outbox WHERE delivery_id = ?", deliveryId);
1004
- if (!row) return void 0;
1005
- return {
1006
- deliveryId: row.delivery_id,
1007
- recipientKey: row.recipient_key,
1008
- kind: row.kind,
1009
- metadata: JSON.parse(row.metadata_json),
1010
- state: row.state,
1011
- ...row.recipient_state === null ? {} : { recipientState: row.recipient_state }
1012
- };
1013
- },
1014
- async close() {
1015
- if (closed) return;
1016
- closed = true;
1017
- stopRetry();
1018
- releaseEnvelope();
1019
- releaseAck();
1020
- releaseReady();
1021
- try {
1022
- await admissionQueue;
1023
- await Promise.all(pending);
1024
- } finally {
1025
- await database.close();
1026
- }
1027
- }
1028
- });
1029
- }
1030
- /**
1031
- * Installs a provider-owned endpoint in the current Cordis context.
1032
- *
1033
- * Returns the instance because a provider cannot read its own service back out:
1034
- * `ctx.get` is strict and hides an implementation while its providing fiber is
1035
- * LOADING, which is the whole of that fiber's own callback.
1036
- */
1037
- async function provideSessionDeliveryService(context, options) {
1038
- const service = await createSessionDeliveryService(options);
1039
- const unprovide = context.provide(PO_SESSION_DELIVERY_SERVICE, service);
1040
- context.effect(() => () => service.close(), "session delivery database");
1041
- return {
1042
- service,
1043
- close: async () => {
1044
- unprovide();
1045
- await service.close();
1046
- }
1047
- };
1048
- }
1049
- //#endregion
1050
- Object.defineProperty(exports, "PEER_REPLAY_DATABASE_FILE", {
1051
- enumerable: true,
1052
- get: function() {
1053
- return PEER_REPLAY_DATABASE_FILE;
1054
- }
1055
- });
1056
- Object.defineProperty(exports, "PO_SESSION_DELIVERY_SERVICE", {
1057
- enumerable: true,
1058
- get: function() {
1059
- return PO_SESSION_DELIVERY_SERVICE;
1060
- }
1061
- });
1062
- Object.defineProperty(exports, "PO_SESSION_INTERCOM_SERVICE", {
1063
- enumerable: true,
1064
- get: function() {
1065
- return PO_SESSION_INTERCOM_SERVICE;
1066
- }
1067
- });
1068
- Object.defineProperty(exports, "SessionGroupRevisionError", {
1069
- enumerable: true,
1070
- get: function() {
1071
- return SessionGroupRevisionError;
1072
- }
1073
- });
1074
- Object.defineProperty(exports, "__toESM", {
1075
- enumerable: true,
1076
- get: function() {
1077
- return __toESM;
1078
- }
1079
- });
1080
- Object.defineProperty(exports, "createBackgroundWorkService", {
1081
- enumerable: true,
1082
- get: function() {
1083
- return createBackgroundWorkService;
1084
- }
1085
- });
1086
- Object.defineProperty(exports, "createPeerCommunication", {
1087
- enumerable: true,
1088
- get: function() {
1089
- return createPeerCommunication;
1090
- }
1091
- });
1092
- Object.defineProperty(exports, "createPeerReplayGuard", {
1093
- enumerable: true,
1094
- get: function() {
1095
- return createPeerReplayGuard;
1096
- }
1097
- });
1098
- Object.defineProperty(exports, "createPeerReplayGuardAsync", {
1099
- enumerable: true,
1100
- get: function() {
1101
- return createPeerReplayGuardAsync;
1102
- }
1103
- });
1104
- Object.defineProperty(exports, "createSessionDeliveryService", {
1105
- enumerable: true,
1106
- get: function() {
1107
- return createSessionDeliveryService;
1108
- }
1109
- });
1110
- Object.defineProperty(exports, "createSessionDirectory", {
1111
- enumerable: true,
1112
- get: function() {
1113
- return createSessionDirectory;
1114
- }
1115
- });
1116
- Object.defineProperty(exports, "createSessionGroupDeliveryAuthorizer", {
1117
- enumerable: true,
1118
- get: function() {
1119
- return createSessionGroupDeliveryAuthorizer;
1120
- }
1121
- });
1122
- Object.defineProperty(exports, "createSessionGroupStore", {
1123
- enumerable: true,
1124
- get: function() {
1125
- return createSessionGroupStore;
1126
- }
1127
- });
1128
- Object.defineProperty(exports, "createSessionIntercom", {
1129
- enumerable: true,
1130
- get: function() {
1131
- return createSessionIntercom;
1132
- }
1133
- });
1134
- Object.defineProperty(exports, "ensurePrivateDirectory", {
1135
- enumerable: true,
1136
- get: function() {
1137
- return ensurePrivateDirectory;
1138
- }
1139
- });
1140
- Object.defineProperty(exports, "parseRemoteSessionReference", {
1141
- enumerable: true,
1142
- get: function() {
1143
- return parseRemoteSessionReference;
1144
- }
1145
- });
1146
- Object.defineProperty(exports, "parseSessionPeerEnvelope", {
1147
- enumerable: true,
1148
- get: function() {
1149
- return parseSessionPeerEnvelope;
1150
- }
1151
- });
1152
- Object.defineProperty(exports, "peerRequestHeaders", {
1153
- enumerable: true,
1154
- get: function() {
1155
- return peerRequestHeaders;
1156
- }
1157
- });
1158
- Object.defineProperty(exports, "peerSessionReference", {
1159
- enumerable: true,
1160
- get: function() {
1161
- return peerSessionReference;
1162
- }
1163
- });
1164
- Object.defineProperty(exports, "provideBackgroundWorkService", {
1165
- enumerable: true,
1166
- get: function() {
1167
- return provideBackgroundWorkService;
1168
- }
1169
- });
1170
- Object.defineProperty(exports, "provideSessionDeliveryService", {
1171
- enumerable: true,
1172
- get: function() {
1173
- return provideSessionDeliveryService;
1174
- }
1175
- });
1176
- Object.defineProperty(exports, "readPoSessionDelivery", {
1177
- enumerable: true,
1178
- get: function() {
1179
- return readPoSessionDelivery;
1180
- }
1181
- });
1182
- Object.defineProperty(exports, "readSessionIntercom", {
1183
- enumerable: true,
1184
- get: function() {
1185
- return readSessionIntercom;
1186
- }
1187
- });
1188
- Object.defineProperty(exports, "readSessionPeerConfig", {
1189
- enumerable: true,
1190
- get: function() {
1191
- return readSessionPeerConfig;
1192
- }
1193
- });
1194
- Object.defineProperty(exports, "readSessionPeerConfigAsync", {
1195
- enumerable: true,
1196
- get: function() {
1197
- return readSessionPeerConfigAsync;
1198
- }
1199
- });
1200
- Object.defineProperty(exports, "requireSessionIntercom", {
1201
- enumerable: true,
1202
- get: function() {
1203
- return requireSessionIntercom;
1204
- }
1205
- });
1206
- Object.defineProperty(exports, "sessionPeerConfigPath", {
1207
- enumerable: true,
1208
- get: function() {
1209
- return sessionPeerConfigPath;
1210
- }
1211
- });
1212
- Object.defineProperty(exports, "verifyPeerRequest", {
1213
- enumerable: true,
1214
- get: function() {
1215
- return verifyPeerRequest;
1216
- }
1217
- });
1218
-
1219
- //# sourceMappingURL=sessionDelivery-CGWuQyLV.cjs.map