@aliou/pi-durable-channels 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,863 @@
1
+ import { AgentDoc, GenerationTask, LiveDoc, configure, defineDoc, defineEntry, defineExtension, defineTask, defineTool, hook, runEndTask, section } from "@earendil-works/pi-durable";
2
+ import { copyJson } from "@earendil-works/chord";
3
+ import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
4
+ import { createHash } from "node:crypto";
5
+ import { DEFAULT_IMAGE_LIMITS } from "@earendil-works/pi-durable/tools";
6
+ import { obj, str } from "@earendil-works/pi-schema";
7
+ // src/doc.ts
8
+ const ChannelsDoc = defineDoc({
9
+ kind: "channels.bindings",
10
+ version: 1,
11
+ scope: "session",
12
+ initial: () => ({ bindings: {} }),
13
+ checkpointWhen: (_value, _ops, info) => info.deltasSinceBase >= 50
14
+ });
15
+ const ChannelMessage = defineEntry("channel.message");
16
+ const ChannelNote = defineEntry("channel.note");
17
+ function own(record, key) {
18
+ if (record === void 0 || !Object.hasOwn(record, key)) return void 0;
19
+ return record[key];
20
+ }
21
+ function findBinding(state, key) {
22
+ return own(own(state?.bindings, key.channel), key.address);
23
+ }
24
+ function entriesOf(state) {
25
+ return Object.entries(state?.bindings ?? {}).flatMap(([channel, addresses]) => Object.entries(addresses).map(([address, binding]) => ({
26
+ channel,
27
+ address,
28
+ binding
29
+ })));
30
+ }
31
+ function conversationAddresses(state, conversationId) {
32
+ return entriesOf(state).filter(({ binding }) => binding.conversationId === conversationId).map(({ channel, address }) => ({
33
+ channel,
34
+ address
35
+ }));
36
+ }
37
+ function setBinding(state, key, binding) {
38
+ if (!Object.hasOwn(state.bindings, key.channel)) state.bindings[key.channel] = {};
39
+ state.bindings[key.channel][key.address] = binding;
40
+ }
41
+ function deleteConversation(state, conversationId) {
42
+ for (const { channel, address } of conversationAddresses(state, conversationId)) delete state.bindings[channel][address];
43
+ }
44
+ // src/bind.ts
45
+ const EXTENSION = "channels";
46
+ async function selectChannels(tx, id) {
47
+ const state = await tx.doc(AgentDoc, id);
48
+ const selected = state.extensions;
49
+ if (!Array.isArray(selected) || selected.includes("channels")) return;
50
+ state.extensions = [...selected, EXTENSION];
51
+ }
52
+ async function bindAddress(tx, target, conversationId) {
53
+ const state = await tx.doc(ChannelsDoc);
54
+ const existing = findBinding(state, target);
55
+ if (existing !== void 0 && existing.conversationId !== conversationId) throw new Error(`Address ${target.address} on channel ${target.channel} belongs to another conversation`);
56
+ const addressData = target.addressData ?? existing?.addressData;
57
+ setBinding(state, target, {
58
+ conversationId,
59
+ ...addressData === void 0 ? {} : { addressData: copyJson(addressData) }
60
+ });
61
+ await selectChannels(tx, conversationId);
62
+ }
63
+ // src/hook.ts
64
+ function replyKey(entryId) {
65
+ return `reply:${entryId}`;
66
+ }
67
+ async function runEntries(source, range, context) {
68
+ const entries = [];
69
+ let cursor;
70
+ do {
71
+ const query = {
72
+ minEntryId: range.first,
73
+ ...range.last === void 0 ? {} : { maxEntryId: range.last },
74
+ order: "ascending"
75
+ };
76
+ const page = await source.entries(query, 100, cursor, context);
77
+ entries.push(...page.items);
78
+ cursor = page.next;
79
+ } while (cursor !== void 0);
80
+ return entries;
81
+ }
82
+ function answerParts(entry) {
83
+ const text = (entry?.model ?? []).flatMap((message) => message.role === "assistant" ? message.content : []).flatMap((part) => part.type === "text" ? [part.text] : []).join("");
84
+ return text === "" ? [] : [{
85
+ type: "text",
86
+ text
87
+ }];
88
+ }
89
+ function replyHook(Send) {
90
+ return async (run, api, context) => {
91
+ const messages = (await runEntries(api, run, context)).filter(ChannelMessage.is);
92
+ if (messages.length === 0) return void 0;
93
+ const answer = await api.entry(run.answer, context);
94
+ const parts = run.reason === "terminate" ? [] : answerParts(answer);
95
+ return { tasks: messages.map(({ id, data: { author: _author, ...target } }) => runEndTask(Send, {
96
+ ...target,
97
+ parts,
98
+ idempotencyKey: replyKey(id)
99
+ })) };
100
+ };
101
+ }
102
+ // src/attachments.ts
103
+ const INLINE_IMAGE_TYPES = /* @__PURE__ */ new Set([
104
+ "image/png",
105
+ "image/jpeg",
106
+ "image/gif",
107
+ "image/webp"
108
+ ]);
109
+ function safeName(name) {
110
+ const cleaned = (name.split(/[\\/]/).at(-1) ?? "").replace(/[^\w.-]+/g, "_").replace(/^\.+/, "");
111
+ return cleaned === "" ? "file" : cleaned;
112
+ }
113
+ function messageOf(error) {
114
+ return error instanceof Error ? error.message : String(error);
115
+ }
116
+ async function save(env, folder, file, bytes, context) {
117
+ const dir = await env.joinPath([env.cwd, folder], context);
118
+ if (!dir.ok) throw dir.error;
119
+ const created = await env.createDir(dir.value, { recursive: true }, context);
120
+ if (!created.ok) throw created.error;
121
+ const path = await env.joinPath([dir.value, safeName(file.name)], context);
122
+ if (!path.ok) throw path.error;
123
+ const written = await env.writeFile(path.value, bytes, context);
124
+ if (!written.ok) throw written.error;
125
+ return path.value;
126
+ }
127
+ function imagesOf(file, bytes) {
128
+ if (!INLINE_IMAGE_TYPES.has(file.mimeType)) return [];
129
+ const data = Buffer.from(bytes).toString("base64");
130
+ if (data.length > DEFAULT_IMAGE_LIMITS.maxBytes) return [];
131
+ return [{
132
+ type: "image",
133
+ data,
134
+ mimeType: file.mimeType
135
+ }];
136
+ }
137
+ async function placed(file, bytes, source, context) {
138
+ const label = `${file.name} (${file.mimeType})`;
139
+ if (source.env === void 0) return `Attached file ${label}, not saved: no environment`;
140
+ const folder = `.channels/attachments/${attachmentKey(source.requestId, file.url)}`;
141
+ const path = await save(source.env, folder, file, bytes, context).catch((error) => error);
142
+ if (typeof path !== "string") return `Attached file ${label}, not saved: ${messageOf(path)}`;
143
+ return `Attached file ${path} (${file.mimeType})`;
144
+ }
145
+ async function attach(file, source, context) {
146
+ const label = `${file.name} (${file.mimeType})`;
147
+ if (source.adapter.fetchFile === void 0) return {
148
+ line: `Attached file ${label}, not downloaded`,
149
+ images: []
150
+ };
151
+ const bytes = await source.adapter.fetchFile(file.url).catch((error) => error);
152
+ if (!(bytes instanceof Uint8Array)) return {
153
+ line: `Attached file ${label}, not downloaded: ${messageOf(bytes)}`,
154
+ images: []
155
+ };
156
+ return {
157
+ line: await placed(file, bytes, source, context),
158
+ images: imagesOf(file, bytes)
159
+ };
160
+ }
161
+ function attachmentKey(requestId, url) {
162
+ return createHash("sha256").update(JSON.stringify([requestId, url])).digest("hex").slice(0, 16);
163
+ }
164
+ async function conversationEnv(source, context) {
165
+ if (source.env === void 0) return void 0;
166
+ const { conversationId, read } = source;
167
+ const cwd = (await read.snapshot(AgentDoc, conversationId, context))?.cwd;
168
+ const target = {
169
+ conversationId,
170
+ read,
171
+ ...cwd === void 0 ? {} : { cwd }
172
+ };
173
+ return source.env(target, context);
174
+ }
175
+ async function messageContent(message, source, context) {
176
+ const files = message.files ?? [];
177
+ if (files.length === 0) return message.text;
178
+ const env = await conversationEnv(source, context);
179
+ const fileSource = {
180
+ adapter: source.adapter,
181
+ env,
182
+ requestId: message.requestId
183
+ };
184
+ const lines = [message.text];
185
+ const images = [];
186
+ for (const file of files) {
187
+ const attached = await attach(file, fileSource, context);
188
+ lines.push(attached.line);
189
+ images.push(...attached.images);
190
+ }
191
+ return [{
192
+ type: "text",
193
+ text: lines.join("\n")
194
+ }, ...images];
195
+ }
196
+ // src/tools.ts
197
+ const TOOLS_EXTENSION = "channels-tools";
198
+ const NO_REPLY = "no_reply";
199
+ function text(value, isError = false) {
200
+ return {
201
+ output: [{
202
+ type: "text",
203
+ text: value
204
+ }],
205
+ isError
206
+ };
207
+ }
208
+ function defineChannelTools(Send) {
209
+ const sendMessage = defineTool({
210
+ name: "send_message",
211
+ description: "Send a text message to one of your channel addresses, delivered in the background and retried on failure. Your final answer is already sent to the address of the message you are answering, so never use this to send that answer; use it to reach your other addresses, or to post an update before you finish.",
212
+ parameters: obj({
213
+ channel: str(),
214
+ address: str(),
215
+ text: str()
216
+ }),
217
+ execute: async ({ channel, address, text: body }, api, context) => {
218
+ const binding = findBinding(await api.snapshot(ChannelsDoc, context), {
219
+ channel,
220
+ address
221
+ });
222
+ if (binding?.conversationId !== api.conversationId) return text(`Unknown address ${address} on channel ${channel}.`, true);
223
+ const input = {
224
+ channel,
225
+ address,
226
+ parts: [{
227
+ type: "text",
228
+ text: body
229
+ }],
230
+ idempotencyKey: `notify:${api.taskId}`,
231
+ ...binding.addressData === void 0 ? {} : { addressData: binding.addressData }
232
+ };
233
+ await api.createTask(Send, input, {
234
+ ownership: { kind: "conversation" },
235
+ background: true
236
+ }, context);
237
+ return text(`Message queued for ${address} on ${channel}.`);
238
+ }
239
+ });
240
+ const listAddresses = defineTool({
241
+ name: "list_addresses",
242
+ description: "List the channel addresses you can send messages to.",
243
+ parameters: obj({}),
244
+ replay: "safe",
245
+ execute: async (_args, api, context) => {
246
+ const addresses = conversationAddresses(await api.snapshot(ChannelsDoc, context), api.conversationId);
247
+ return text(JSON.stringify(addresses));
248
+ }
249
+ });
250
+ const noReply = defineTool({
251
+ name: NO_REPLY,
252
+ description: "End this run without answering. Use it when the latest message needs no answer from you, such as a thread message meant for someone else. Call it alone, without writing text.",
253
+ parameters: obj({}),
254
+ replay: "safe",
255
+ execute: async () => ({
256
+ ...text("No reply sent."),
257
+ control: { terminate: true }
258
+ })
259
+ });
260
+ const channelsSection = section("channels", async ({ read, conversationId }, context) => {
261
+ const lines = conversationAddresses(await read.snapshot(ChannelsDoc, context), conversationId).map(({ channel, address }) => `- ${channel}: ${address}`);
262
+ return ["Your final answer goes to the address of the message you are answering. Use send_message only for your other addresses, or for an update before you finish. Your addresses:", ...lines.length === 0 ? ["(none yet)"] : lines].join("\n");
263
+ });
264
+ return defineExtension({
265
+ name: TOOLS_EXTENSION,
266
+ tools: [
267
+ sendMessage,
268
+ listAddresses,
269
+ noReply
270
+ ],
271
+ sections: [channelsSection]
272
+ });
273
+ }
274
+ // src/run-events.ts
275
+ function startedEvents(entry, message) {
276
+ if (message.role !== "assistant") return [];
277
+ const calls = message.content.flatMap((part) => part.type === "toolCall" && part.name !== "no_reply" ? [part] : []);
278
+ if (calls.length === 0) return [];
279
+ const text = message.content.flatMap((part) => part.type === "text" ? [part.text] : []).join("").trim();
280
+ return [...text === "" ? [] : [{
281
+ type: "text",
282
+ id: String(entry.id),
283
+ text
284
+ }], ...calls.map((call) => ({
285
+ type: "tool_started",
286
+ id: call.id,
287
+ name: call.name,
288
+ args: call.arguments
289
+ }))];
290
+ }
291
+ function finishedEvents(message) {
292
+ if (message.role !== "toolResult" || message.toolName === "no_reply") return [];
293
+ return [{
294
+ type: "tool_finished",
295
+ id: message.toolCallId,
296
+ name: message.toolName,
297
+ isError: message.isError,
298
+ output: message.content.flatMap((part) => part.type === "text" ? [part.text] : []).join("")
299
+ }];
300
+ }
301
+ function eventsOf(entries) {
302
+ return entries.flatMap((entry) => (entry.model ?? []).flatMap((message) => [...startedEvents(entry, message), ...finishedEvents(message)]));
303
+ }
304
+ // src/run-tracker.ts
305
+ const context$3 = BACKGROUND_CONTEXT;
306
+ async function notify(recipients, event, report) {
307
+ for (const { channel, adapter, target } of recipients) await Promise.resolve().then(() => adapter.events?.(target, event)).catch((error) => report({
308
+ kind: "adapter_error",
309
+ channel,
310
+ address: target.address,
311
+ error
312
+ }));
313
+ }
314
+ function outcomeOf(live, run) {
315
+ const failure = live.runFailure;
316
+ if (failure?.first !== run.first) return {
317
+ type: "run_ended",
318
+ outcome: "completed"
319
+ };
320
+ return {
321
+ type: "run_ended",
322
+ outcome: failure.reason === "aborted" || failure.reason === "reset" ? "aborted" : "failed"
323
+ };
324
+ }
325
+ async function recipientsOf(conversation, first, adapterFor) {
326
+ return (await runEntries(conversation, { first }, context$3)).filter(ChannelMessage.is).flatMap(({ id, data }) => {
327
+ const adapter = adapterFor(data.channel);
328
+ if (adapter?.events === void 0) return [];
329
+ const { channel, author: _author, ...target } = data;
330
+ const idempotencyKey = replyKey(id);
331
+ return [{
332
+ channel,
333
+ adapter,
334
+ target: {
335
+ ...target,
336
+ idempotencyKey
337
+ }
338
+ }];
339
+ });
340
+ }
341
+ function runTracker(conversation, adapterFor, report) {
342
+ let run;
343
+ async function admit(current, live) {
344
+ const inputs = live.inputs.join(",");
345
+ if (inputs === "" || inputs === current.inputs) return;
346
+ current.inputs = inputs;
347
+ const known = new Set(current.recipients.map(({ target }) => target.idempotencyKey));
348
+ current.recipients = await recipientsOf(conversation, current.first, adapterFor);
349
+ await notify(current.recipients.filter(({ target }) => !known.has(target.idempotencyKey)), { type: "run_started" }, report);
350
+ }
351
+ async function freshEntries(current) {
352
+ const previous = current.cursor;
353
+ const entries = await runEntries(conversation, { first: previous ?? current.first }, context$3);
354
+ current.cursor = entries.at(-1)?.id ?? previous;
355
+ if (previous === void 0) return entries;
356
+ return entries.filter(({ id }) => id > previous);
357
+ }
358
+ async function activity(current) {
359
+ const entries = await freshEntries(current);
360
+ for (const event of eventsOf(entries)) await notify(current.recipients, event, report);
361
+ }
362
+ async function end(live) {
363
+ if (run === void 0) return;
364
+ const ended = run;
365
+ run = void 0;
366
+ await activity(ended);
367
+ await notify(ended.recipients, outcomeOf(live, ended), report);
368
+ }
369
+ return async (live) => {
370
+ const first = live.run?.first;
371
+ if (run !== void 0 && run.first !== first) await end(live);
372
+ if (live.run === void 0 || first === void 0) return;
373
+ run ??= {
374
+ first,
375
+ inputs: "",
376
+ recipients: []
377
+ };
378
+ await admit(run, live.run);
379
+ await activity(run);
380
+ };
381
+ }
382
+ // src/events.ts
383
+ const context$2 = BACKGROUND_CONTEXT;
384
+ async function follow(harness, id, adapterFor, report) {
385
+ const conversation = await harness.conversation(id, context$2);
386
+ const watch = await harness.watchDoc(LiveDoc, id, context$2);
387
+ if (conversation === void 0 || watch === void 0) return void 0;
388
+ const track = runTracker(conversation, adapterFor, report);
389
+ let closing = false;
390
+ let idle = false;
391
+ let busy = Promise.resolve();
392
+ const stopWhenIdle = () => closing && idle && void watch.stop();
393
+ async function observe(live) {
394
+ await track(live);
395
+ idle = live.run === void 0;
396
+ stopWhenIdle();
397
+ }
398
+ watch.start(async (call) => {
399
+ if (call.kind !== "value") return;
400
+ busy = observe(call.value);
401
+ await busy;
402
+ });
403
+ return {
404
+ closed: watch.closed.then(() => busy),
405
+ stop: () => void watch.stop(),
406
+ close: () => {
407
+ closing = true;
408
+ stopWhenIdle();
409
+ },
410
+ keep: () => {
411
+ closing = false;
412
+ }
413
+ };
414
+ }
415
+ function generating(graph) {
416
+ return new Set(Object.values(graph.tasks).filter((node) => node.kind === GenerationTask.definition.name).map((node) => node.conversationId));
417
+ }
418
+ async function watchEvents(harness, adapterFor, report) {
419
+ let stopped = false;
420
+ const followers = /* @__PURE__ */ new Map();
421
+ const graph = await harness.watchTaskGraph(context$2);
422
+ function start(id) {
423
+ const follower = follow(harness, id, adapterFor, report);
424
+ followers.set(id, follower);
425
+ follower.then(async (found) => {
426
+ if (found === void 0) return followers.delete(id);
427
+ await found.closed;
428
+ followers.delete(id);
429
+ if (!stopped && generating(graph.value).has(id)) start(id);
430
+ });
431
+ }
432
+ function update(active) {
433
+ for (const id of active) {
434
+ const existing = followers.get(id);
435
+ if (existing === void 0) start(id);
436
+ else existing.then((follower) => follower?.keep());
437
+ }
438
+ for (const [id, follower] of followers) if (!active.has(id)) follower.then((found) => found?.close());
439
+ }
440
+ graph.start(async (call) => {
441
+ if (call.kind === "value" && !stopped) update(generating(call.value));
442
+ });
443
+ async function stopFollower(follower) {
444
+ const found = await follower;
445
+ found?.stop();
446
+ await found?.closed;
447
+ }
448
+ return { stop: async () => {
449
+ stopped = true;
450
+ await graph.stop();
451
+ await Promise.all([...followers.values()].map(stopFollower));
452
+ } };
453
+ }
454
+ // src/send.ts
455
+ const SEND_TASK = "channels.send";
456
+ async function attemptSend(adapterFor, input, addressData, signal) {
457
+ try {
458
+ const adapter = adapterFor(input.channel);
459
+ if (adapter === void 0) throw new Error(`No channel ${input.channel}`);
460
+ const { address, parts, replyContext, idempotencyKey } = input;
461
+ return { result: await adapter.send({
462
+ address,
463
+ parts
464
+ }, {
465
+ addressData,
466
+ replyContext,
467
+ idempotencyKey,
468
+ signal
469
+ }) || void 0 };
470
+ } catch (error) {
471
+ return { error: error instanceof Error ? error : new Error(String(error)) };
472
+ }
473
+ }
474
+ async function recordResult(tx, conversationId, input, result) {
475
+ if (result === void 0) return;
476
+ const state = await tx.doc(ChannelsDoc);
477
+ const current = findBinding(state, input);
478
+ if (current?.conversationId !== conversationId) return;
479
+ const addressData = result.addressData ?? current.addressData;
480
+ const binding = () => ({
481
+ conversationId,
482
+ ...addressData === void 0 ? {} : { addressData: copyJson(addressData) }
483
+ });
484
+ setBinding(state, input, binding());
485
+ if (result.alias === void 0) return;
486
+ const alias = {
487
+ channel: input.channel,
488
+ address: result.alias
489
+ };
490
+ if (findBinding(state, alias) === void 0) setBinding(state, alias, binding());
491
+ }
492
+ function defineSendTask(adapterFor, retry, report) {
493
+ return defineTask({
494
+ name: SEND_TASK,
495
+ version: 1,
496
+ initial: () => ({
497
+ phase: "send",
498
+ attempt: 1
499
+ }),
500
+ phases: { send: async (task, runtime, context) => {
501
+ const { attempt } = task.state.checkpoint;
502
+ const binding = findBinding(await runtime.snapshot(ChannelsDoc, context), task.input);
503
+ const addressData = binding?.conversationId === runtime.conversationId ? binding.addressData : task.input.addressData;
504
+ const outcome = await attemptSend(adapterFor, task.input, addressData, runtime.signal);
505
+ if ("result" in outcome) {
506
+ await runtime.commit(async (tx) => {
507
+ await recordResult(tx, runtime.conversationId, task.input, outcome.result);
508
+ return {
509
+ status: "terminal",
510
+ outcome: {
511
+ status: "completed",
512
+ result: null
513
+ }
514
+ };
515
+ }, context);
516
+ return;
517
+ }
518
+ const { channel, address } = task.input;
519
+ const { error } = outcome;
520
+ if (attempt < retry.attempts) {
521
+ report({
522
+ kind: "send_retry",
523
+ channel,
524
+ address,
525
+ attempt,
526
+ error
527
+ });
528
+ const until = runtime.now() + retry.baseDelayMs * 2 ** (attempt - 1);
529
+ await runtime.sleepUntil(until, {
530
+ phase: "send",
531
+ attempt: attempt + 1
532
+ }, context);
533
+ return;
534
+ }
535
+ report({
536
+ kind: "send_failed",
537
+ channel,
538
+ address,
539
+ error
540
+ });
541
+ const failure = { message: error.message };
542
+ await runtime.commit(() => ({
543
+ status: "terminal",
544
+ outcome: {
545
+ status: "failed",
546
+ error: failure
547
+ }
548
+ }), context);
549
+ } },
550
+ abort: (_task, runtime, context) => runtime.commit(() => ({
551
+ status: "terminal",
552
+ outcome: { status: "aborted" }
553
+ }), context)
554
+ });
555
+ }
556
+ // src/status.ts
557
+ const context$1 = BACKGROUND_CONTEXT;
558
+ function sendOutcome(task) {
559
+ if (task.state.status !== "terminal") return { state: "sending" };
560
+ const outcome = task.state.outcome;
561
+ switch (outcome.status) {
562
+ case "completed": return { state: "done" };
563
+ case "failed":
564
+ case "faulted": return {
565
+ state: "failed",
566
+ error: outcome.error.message
567
+ };
568
+ default: return { state: "aborted" };
569
+ }
570
+ }
571
+ async function findSend(harness, conversationId, key) {
572
+ return harness.commit(async (tx) => {
573
+ let cursor;
574
+ do {
575
+ const query = {
576
+ conversationId,
577
+ kind: SEND_TASK,
578
+ order: "descending"
579
+ };
580
+ const page = await tx.scanTasks(query, 100, cursor);
581
+ const found = page.items.find((task) => task.input.idempotencyKey === key);
582
+ if (found !== void 0) return found;
583
+ cursor = page.next;
584
+ } while (cursor !== void 0);
585
+ }, context$1);
586
+ }
587
+ async function replyStatus(harness, conversationId, entry) {
588
+ const task = await findSend(harness, conversationId, replyKey(entry));
589
+ if (task === void 0) return { state: "sending" };
590
+ const live = (await harness.inspect(context$1)).tasks.find((item) => item.record.id === task.id);
591
+ if (live?.state.kind === "blocked") return {
592
+ state: "blocked",
593
+ reason: live.state.reason
594
+ };
595
+ return sendOutcome(task);
596
+ }
597
+ async function deliveryStatus(harness, deliveryId) {
598
+ const found = await harness.submission(deliveryId, context$1);
599
+ if (found === void 0) return void 0;
600
+ const record = await found.status(context$1);
601
+ if (record.status === "queued") return { state: "queued" };
602
+ if (record.status === "placed") return { state: "running" };
603
+ if (record.status === "unanswered") return record.reason === "aborted" ? { state: "aborted" } : {
604
+ state: "failed",
605
+ error: record.reason
606
+ };
607
+ if (record.type === "write" || record.entry === void 0) return { state: "done" };
608
+ return replyStatus(harness, record.conversationId, record.entry);
609
+ }
610
+ // src/submission.ts
611
+ const WHEN_BUSY = {
612
+ queue: "followUp",
613
+ steer: "steer"
614
+ };
615
+ function messageData(key, message, addressData) {
616
+ return {
617
+ author: message.author,
618
+ ...key,
619
+ ...addressData === void 0 ? {} : { addressData },
620
+ ...message.replyContext === void 0 ? {} : { replyContext: message.replyContext }
621
+ };
622
+ }
623
+ function submission(requestId, content, data, options) {
624
+ if (options.run) return {
625
+ type: "input",
626
+ content,
627
+ requestId,
628
+ whenBusy: WHEN_BUSY[options.whenBusy],
629
+ entry: {
630
+ kind: ChannelMessage.kind,
631
+ data
632
+ }
633
+ };
634
+ const model = [{
635
+ role: "user",
636
+ content,
637
+ timestamp: Date.now()
638
+ }];
639
+ return {
640
+ type: "write",
641
+ requestId,
642
+ entry: {
643
+ kind: ChannelNote.kind,
644
+ data,
645
+ model
646
+ }
647
+ };
648
+ }
649
+ // src/hub.ts
650
+ const context = BACKGROUND_CONTEXT;
651
+ const cancel = (conversation) => conversation.abort(context, { background: true });
652
+ function createHub(harness, setup) {
653
+ const tails = /* @__PURE__ */ new Map();
654
+ const controller = new AbortController();
655
+ const adapters = Object.values(setup.options.channels).map(({ adapter }) => adapter);
656
+ let starting;
657
+ let watcher;
658
+ let stopping;
659
+ function serial(key, run) {
660
+ if (stopping !== void 0) return Promise.reject(/* @__PURE__ */ new Error("Channels hub is stopped"));
661
+ const id = JSON.stringify([key.channel, key.address]);
662
+ const result = (tails.get(id) ?? Promise.resolve()).then(run);
663
+ const tail = result.catch(() => void 0);
664
+ tails.set(id, tail);
665
+ tail.then(() => tails.get(id) === tail && tails.delete(id));
666
+ return result;
667
+ }
668
+ async function conversationFor(key, message, create) {
669
+ const factory = create ? setup.registration(key.channel).conversation : void 0;
670
+ return harness.commit(async (tx) => {
671
+ const existing = findBinding(await tx.doc(ChannelsDoc), key);
672
+ if (existing !== void 0) return existing.conversationId;
673
+ const created = factory?.(message, { channel: key.channel });
674
+ if (created === void 0) return void 0;
675
+ const record = await tx.createConversation({ ownership: { kind: "ownerless" } });
676
+ await configure(tx, record.id, created.agent ?? {});
677
+ await bindAddress(tx, key, record.id);
678
+ return record.id;
679
+ }, context);
680
+ }
681
+ async function admit(key, message, options) {
682
+ const conversationId = await conversationFor(key, message, options.run && options.create);
683
+ if (conversationId === void 0) {
684
+ setup.report({
685
+ kind: "ignored",
686
+ ...key
687
+ });
688
+ return;
689
+ }
690
+ const conversation = await harness.conversation(conversationId, context);
691
+ if (conversation === void 0) throw new Error(`Conversation ${conversationId} not found`);
692
+ const content = await messageContent(message, {
693
+ adapter: setup.registration(key.channel).adapter,
694
+ env: setup.env,
695
+ read: harness,
696
+ conversationId
697
+ }, context);
698
+ const admitted = await harness.commit(async (tx) => {
699
+ const known = await tx.submissionByRequest(conversationId, message.requestId);
700
+ if (known !== void 0) return {
701
+ submissionId: known.id,
702
+ duplicate: true
703
+ };
704
+ const state = await tx.doc(ChannelsDoc);
705
+ const stored = findBinding(state, key)?.addressData;
706
+ if (message.addressData !== void 0) setBinding(state, key, {
707
+ conversationId,
708
+ addressData: message.addressData
709
+ });
710
+ const data = messageData(key, message, message.addressData ?? (stored === void 0 ? void 0 : copyJson(stored)));
711
+ const draft = submission(message.requestId, content, data, options);
712
+ return {
713
+ submissionId: await conversation.submit(tx, draft),
714
+ duplicate: false
715
+ };
716
+ }, context);
717
+ setup.report({
718
+ kind: "admitted",
719
+ ...key,
720
+ conversationId,
721
+ ...admitted
722
+ });
723
+ return {
724
+ submissionId: admitted.submissionId,
725
+ conversationId
726
+ };
727
+ }
728
+ const deliver = async (channel, message, options) => {
729
+ setup.registration(channel);
730
+ const key = {
731
+ channel,
732
+ address: message.address
733
+ };
734
+ const resolved = {
735
+ whenBusy: options?.whenBusy ?? setup.options.whenBusy ?? "queue",
736
+ run: options?.run ?? true,
737
+ create: options?.create ?? true
738
+ };
739
+ return serial(key, () => admit(key, message, resolved));
740
+ };
741
+ function start() {
742
+ if (starting !== void 0 || stopping !== void 0) return Promise.reject(/* @__PURE__ */ new Error("Channels hub can only start once"));
743
+ starting = startAll();
744
+ return starting;
745
+ }
746
+ async function startAll() {
747
+ const channels = Object.entries(setup.options.channels);
748
+ if (adapters.some((adapter) => adapter.events !== void 0)) watcher = await watchEvents(harness, setup.adapterFor, setup.report);
749
+ const { signal } = controller;
750
+ await Promise.all(channels.map(([channel, { adapter }]) => adapter.start?.({
751
+ deliver: (message, options) => deliver(channel, message, options),
752
+ cancel: (address) => cancelAt({
753
+ channel,
754
+ address
755
+ }),
756
+ report: (report) => setup.report({
757
+ ...report,
758
+ channel
759
+ }),
760
+ signal
761
+ })));
762
+ }
763
+ async function drain() {
764
+ await starting?.catch(() => void 0);
765
+ await Promise.all(tails.values());
766
+ await watcher?.stop();
767
+ controller.abort();
768
+ if (starting === void 0) return;
769
+ await Promise.all(adapters.map((adapter) => adapter.stop?.()));
770
+ }
771
+ function stop() {
772
+ stopping ??= drain();
773
+ return stopping;
774
+ }
775
+ async function bind(target, conversationId) {
776
+ setup.registration(target.channel);
777
+ return serial(target, () => harness.commit((tx) => bindAddress(tx, target, conversationId), context));
778
+ }
779
+ function atAddress(key, run) {
780
+ return serial(key, async () => {
781
+ const binding = findBinding(await harness.snapshot(ChannelsDoc, context), key);
782
+ if (binding === void 0) return;
783
+ const conversation = await harness.conversation(binding.conversationId, context);
784
+ if (conversation !== void 0) await run(conversation);
785
+ });
786
+ }
787
+ const cancelAt = (key) => atAddress(key, cancel);
788
+ async function addresses(conversationId) {
789
+ return conversationAddresses(await harness.snapshot(ChannelsDoc, context), conversationId);
790
+ }
791
+ async function conversationOf(key) {
792
+ return findBinding(await harness.snapshot(ChannelsDoc, context), key)?.conversationId;
793
+ }
794
+ return {
795
+ start,
796
+ stop,
797
+ deliver,
798
+ bind,
799
+ addresses,
800
+ conversationOf,
801
+ status: (deliveryId) => deliveryStatus(harness, deliveryId),
802
+ cancel: cancelAt,
803
+ clear: (key) => atAddress(key, async (conversation) => {
804
+ await cancel(conversation);
805
+ await conversation.reset(void 0, context);
806
+ }),
807
+ compact: (key) => atAddress(key, async (conversation) => {
808
+ await conversation.compact(void 0, context);
809
+ }),
810
+ end: (key) => atAddress(key, async (conversation) => {
811
+ await cancel(conversation);
812
+ await harness.commit(async (tx) => {
813
+ deleteConversation(await tx.doc(ChannelsDoc), conversation.id);
814
+ }, context);
815
+ })
816
+ };
817
+ }
818
+ // src/report.ts
819
+ function reporter(onReport) {
820
+ return (report) => {
821
+ try {
822
+ onReport?.(report);
823
+ } catch {
824
+ return;
825
+ }
826
+ };
827
+ }
828
+ // src/core.ts
829
+ const DEFAULT_RETRY = {
830
+ attempts: 5,
831
+ baseDelayMs: 1e3
832
+ };
833
+ function createChannels(options) {
834
+ const registration = (channel) => {
835
+ if (!Object.hasOwn(options.channels, channel)) throw new Error(`No channel ${channel}`);
836
+ return options.channels[channel];
837
+ };
838
+ const adapterFor = (channel) => Object.hasOwn(options.channels, channel) ? options.channels[channel].adapter : void 0;
839
+ const report = reporter(options.onReport);
840
+ const Send = defineSendTask(adapterFor, options.retry ?? DEFAULT_RETRY, report);
841
+ return {
842
+ extension: defineExtension({
843
+ name: EXTENSION,
844
+ tasks: [Send],
845
+ hooks: [hook(GenerationTask, { afterRun: replyHook(Send) })]
846
+ }),
847
+ tools: defineChannelTools(Send),
848
+ bind: async (tx, target, conversationId) => {
849
+ registration(target.channel);
850
+ await bindAddress(tx, target, conversationId);
851
+ },
852
+ hub: (harness, hubOptions) => createHub(harness, {
853
+ options,
854
+ registration,
855
+ adapterFor,
856
+ report,
857
+ env: hubOptions?.env
858
+ })
859
+ };
860
+ }
861
+ export { createChannels };
862
+
863
+ //# sourceMappingURL=index.mjs.map