@aliou/pi-durable-channels 0.2.0 → 0.3.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/CHANGELOG.md +12 -0
- package/README.md +33 -3
- package/dist/index.d.mts +25 -2
- package/dist/index.mjs +27 -16
- package/dist/index.mjs.map +1 -1
- package/package.json +5 -5
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
# @aliou/pi-durable-channels
|
|
2
2
|
|
|
3
|
+
## 0.3.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 0d37f0e: Export the binding-read helpers channel packages need to build conversation-scoped tools: `ChannelsDoc`, `ChannelsState`, `Binding`, `findBinding`, and `conversationAddresses`.
|
|
8
|
+
- c3b4299: Add transactional host sends for durable channel notifications.
|
|
9
|
+
- 94aede0: Allow outbound text parts to carry JSON representations keyed by format, and let channel adapters declare the formats they can render.
|
|
10
|
+
|
|
11
|
+
### Patch Changes
|
|
12
|
+
|
|
13
|
+
- 03f2542: Update Earendil dependencies to 1.6.0.
|
|
14
|
+
|
|
3
15
|
## 0.2.0
|
|
4
16
|
|
|
5
17
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -66,7 +66,9 @@ It prints `Hello from pi-durable.`. For crash recovery, use a persistent pi-dura
|
|
|
66
66
|
|
|
67
67
|
## Host registration
|
|
68
68
|
|
|
69
|
-
`createChannels(options)` returns `extension`, `tools`, transactional `bind`, and a `hub` factory. Install `channels.extension` in the Harness registry for durable sends and reply hooks. Install `channels.tools` when the agent needs messaging tools and the address prompt section.
|
|
69
|
+
`createChannels(options)` returns `extension`, `tools`, transactional `bind` and `send`, and a `hub` factory. Install `channels.extension` in the Harness registry for durable sends and reply hooks. Install `channels.tools` when the agent needs messaging tools and the address prompt section.
|
|
70
|
+
|
|
71
|
+
`channels.send(tx, conversationId, { channel, address, text, idempotencyKey })` enqueues a background durable send in the caller's transaction. Use it for host-originated notifications, including conversation initialization. The task retains the idempotency key across retries and recovery. Bind the address in the same transaction when the conversation should later accept replies from it.
|
|
70
72
|
|
|
71
73
|
A channel is a host-assigned name, not an agent persona. Its optional `conversation(message, { channel })` factory creates a conversation for an unknown address. Returning `undefined` ignores the message. Without a factory, only bound addresses accept messages. `message.event` can select an agent, but is not stored in the channel entry.
|
|
72
74
|
|
|
@@ -90,11 +92,12 @@ An address identifies a destination within a channel, such as a Slack thread. Se
|
|
|
90
92
|
|
|
91
93
|
Implement the exported `ChannelAdapter` type:
|
|
92
94
|
|
|
93
|
-
|
|
|
95
|
+
| Member | Contract |
|
|
94
96
|
| --- | --- |
|
|
95
97
|
| `start(ctx)` | Optional. Keep `deliver`, `cancel`, and `report`; resolve once the transport is ready. A rejection fails `hub.start()` |
|
|
96
98
|
| `stop()` | Optional. Resolve once the transport is closed |
|
|
97
99
|
| `fetch(request)` | Optional HTTP entry point, mounted by the host. Socket and polling adapters omit it |
|
|
100
|
+
| `formats` | Optional list of outbound representation keys the adapter can consume |
|
|
98
101
|
| `send(message, ctx)` | Required. Post the outbound parts; throwing retries the send |
|
|
99
102
|
| `events(target, event)` | Optional best-effort run presentation |
|
|
100
103
|
| `fetchFile(url)` | Optional authenticated attachment download |
|
|
@@ -105,7 +108,32 @@ The start context's `signal` aborts during hub shutdown. The send context has it
|
|
|
105
108
|
|
|
106
109
|
Address data persists until replaced. Reply context belongs to one message, and is also passed to its run events. A reply with no parts means `no_reply`; post nothing and clear the adapter's presentation state.
|
|
107
110
|
|
|
108
|
-
[Slack
|
|
111
|
+
Use the published [Slack adapter](https://github.com/aliou/pi-durable-channels/tree/main/packages/slack) for Slack. [GitHub and webhook adapters](https://github.com/aliou/pi-durable-channels/tree/main/examples/channels) are copyable examples, not published adapter packages. The [examples guide](https://github.com/aliou/pi-durable-channels/tree/main/examples) covers complete platform integrations.
|
|
112
|
+
|
|
113
|
+
## Outbound parts
|
|
114
|
+
|
|
115
|
+
Every outbound part contains readable fallback text and can carry platform-specific JSON representations:
|
|
116
|
+
|
|
117
|
+
```ts
|
|
118
|
+
{
|
|
119
|
+
type: "text",
|
|
120
|
+
text: "Deployment completed for api.",
|
|
121
|
+
representations: {
|
|
122
|
+
"slack.block-kit": {
|
|
123
|
+
blocks: [
|
|
124
|
+
{
|
|
125
|
+
type: "section",
|
|
126
|
+
text: { type: "mrkdwn", text: "*Deployment completed* for api." },
|
|
127
|
+
},
|
|
128
|
+
],
|
|
129
|
+
},
|
|
130
|
+
},
|
|
131
|
+
}
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
Representation keys identify formats, not host-assigned channel names. An adapter's `formats` property lists the keys it can consume. The adapter selects, validates, and renders those representations; the core contains no native format schemas or rendering rules. An adapter without a suitable representation delivers the part's required `text`.
|
|
135
|
+
|
|
136
|
+
Durable sends persist the source parts. Retries and recovery pass the same representations and idempotency key to the configured adapter. Final replies and `send_message` create text-only parts; channel-specific producer tools can supply representations without changing the core delivery contract.
|
|
109
137
|
|
|
110
138
|
## Delivery and retries
|
|
111
139
|
|
|
@@ -149,6 +177,8 @@ After `end`, another message creates a conversation only if the channel's factor
|
|
|
149
177
|
|
|
150
178
|
`channels.tools` adds `send_message({ channel, address, text })`, `list_addresses()`, `no_reply()`, and an address prompt section. Sending and listing are restricted to addresses bound to the calling conversation. `send_message` queues a background notification; the final answer already goes to the inbound address.
|
|
151
179
|
|
|
180
|
+
Channel packages that add their own tools reuse the same restriction: the package exports `ChannelsDoc`, `findBinding(state, { channel, address })`, and `conversationAddresses(state, conversationId)`, the helpers `channels.tools` itself uses. A tool reads the doc with `api.snapshot(ChannelsDoc, context)` and rejects addresses whose binding names another conversation.
|
|
181
|
+
|
|
152
182
|
## Reports
|
|
153
183
|
|
|
154
184
|
`onReport` receives `admitted` with a duplicate flag, `ignored`, `send_retry`, `send_failed`, and adapter-supplied `skipped` or `adapter_error`, each with its channel. Send reports may repeat after restart; use them for logs, not accounting. A throwing report callback is ignored. The core writes nothing to the console.
|
package/dist/index.d.mts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { AgentChange, ConversationId, ConversationInit, Extension, Harness, HarnessOptions, SubmissionId, Tx } from "@earendil-works/pi-durable";
|
|
2
|
-
import { JsonValue } from "@earendil-works/chord";
|
|
2
|
+
import { JsonValue } from "@earendil-works/chord/json";
|
|
3
3
|
import "@earendil-works/chord/context";
|
|
4
4
|
import { JsonObject } from "@earendil-works/pi-ai";
|
|
5
|
+
import "@earendil-works/chord/delta";
|
|
5
6
|
type BusyPolicy = "queue" | "steer";
|
|
6
7
|
type InboundFile = {
|
|
7
8
|
name: string;
|
|
@@ -26,6 +27,7 @@ type DeliverOptions = {
|
|
|
26
27
|
type OutboundPart = {
|
|
27
28
|
type: "text";
|
|
28
29
|
text: string;
|
|
30
|
+
representations?: Readonly<Record<string, JsonValue>>;
|
|
29
31
|
};
|
|
30
32
|
type OutboundMessage = {
|
|
31
33
|
address: string;
|
|
@@ -116,6 +118,7 @@ type ChannelAdapter = {
|
|
|
116
118
|
start?(ctx: AdapterStart): void | Promise<void>;
|
|
117
119
|
stop?(): Promise<void>;
|
|
118
120
|
fetch?(request: Request): Promise<Response>;
|
|
121
|
+
formats?: readonly string[];
|
|
119
122
|
send(message: OutboundMessage, ctx: SendContext): Promise<SendResult | undefined | void>;
|
|
120
123
|
events?(target: ReplyTarget, event: ChannelEvent): void | Promise<void>;
|
|
121
124
|
fetchFile?(url: string): Promise<Uint8Array>;
|
|
@@ -173,12 +176,32 @@ type ChannelsHub = {
|
|
|
173
176
|
type HubOptions = {
|
|
174
177
|
env?: EnvBuilder;
|
|
175
178
|
};
|
|
179
|
+
type ChannelSend = {
|
|
180
|
+
channel: string;
|
|
181
|
+
address: string;
|
|
182
|
+
text: string;
|
|
183
|
+
idempotencyKey: string;
|
|
184
|
+
addressData?: JsonValue;
|
|
185
|
+
};
|
|
186
|
+
type Send = (tx: Tx, conversationId: ConversationId, input: ChannelSend) => Promise<void>;
|
|
176
187
|
type Channels = {
|
|
177
188
|
extension: Extension;
|
|
178
189
|
tools: Extension;
|
|
179
190
|
bind(tx: Tx, target: BindTarget, conversationId: ConversationId): Promise<void>;
|
|
191
|
+
send: Send;
|
|
180
192
|
hub(harness: Harness, options?: HubOptions): ChannelsHub;
|
|
181
193
|
};
|
|
182
194
|
export declare function createChannels(options: ChannelsOptions): Channels;
|
|
183
|
-
|
|
195
|
+
type Binding = {
|
|
196
|
+
conversationId: ConversationId;
|
|
197
|
+
addressData?: JsonValue;
|
|
198
|
+
};
|
|
199
|
+
type Bindings = Record<string, Record<string, Binding>>;
|
|
200
|
+
type ChannelsState = {
|
|
201
|
+
bindings: Bindings;
|
|
202
|
+
};
|
|
203
|
+
export declare const ChannelsDoc: import("@earendil-works/pi-durable").SessionDocToken<ChannelsState>;
|
|
204
|
+
export declare function findBinding(state: Readonly<ChannelsState> | undefined, key: AddressKey): Binding | undefined;
|
|
205
|
+
export declare function conversationAddresses(state: Readonly<ChannelsState> | undefined, conversationId: ConversationId): AddressKey[];
|
|
206
|
+
export type { AdapterReport, AdapterStart, AddressKey, BindTarget, Binding, BusyPolicy, ChannelAdapter, ChannelEvent, ChannelRegistration, ChannelReport, ChannelSend, Channels, ChannelsHub, ChannelsOptions, ChannelsState, ConversationSetup, Deliver, DeliverOptions, DeliveryReceipt, DeliveryStatus, HubOptions, InboundFile, InboundMessage, OutboundMessage, OutboundPart, ReplyTarget, Send, SendContext, SendResult, SendRetry };
|
|
184
207
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { AgentDoc, GenerationTask, LiveDoc, configure, defineDoc, defineEntry, defineExtension, defineTask, defineTool, hook,
|
|
2
|
-
import { copyJson } from "@earendil-works/chord";
|
|
1
|
+
import { AgentDoc, GenerationTask, LiveDoc, configure, defineDoc, defineEntry, defineExtension, defineTask, defineTool, hook, hookTask, section } from "@earendil-works/pi-durable";
|
|
2
|
+
import { copyJson } from "@earendil-works/chord/json";
|
|
3
3
|
import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
|
|
4
4
|
import { createHash } from "node:crypto";
|
|
5
5
|
import { DEFAULT_IMAGE_LIMITS } from "@earendil-works/pi-durable/tools";
|
|
@@ -92,7 +92,7 @@ function replyHook(Send) {
|
|
|
92
92
|
if (messages.length === 0) return void 0;
|
|
93
93
|
const answer = await api.entry(run.answer, context);
|
|
94
94
|
const parts = run.reason === "terminate" ? [] : answerParts(answer);
|
|
95
|
-
return { tasks: messages.map(({ id, data: { author: _author, ...target } }) =>
|
|
95
|
+
return { tasks: messages.map(({ id, data: { author: _author, ...target } }) => hookTask(Send, {
|
|
96
96
|
...target,
|
|
97
97
|
parts,
|
|
98
98
|
idempotencyKey: replyKey(id)
|
|
@@ -205,7 +205,7 @@ function text(value, isError = false) {
|
|
|
205
205
|
isError
|
|
206
206
|
};
|
|
207
207
|
}
|
|
208
|
-
function defineChannelTools(
|
|
208
|
+
function defineChannelTools(send) {
|
|
209
209
|
const sendMessage = defineTool({
|
|
210
210
|
name: "send_message",
|
|
211
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.",
|
|
@@ -220,20 +220,13 @@ function defineChannelTools(Send) {
|
|
|
220
220
|
address
|
|
221
221
|
});
|
|
222
222
|
if (binding?.conversationId !== api.conversationId) return text(`Unknown address ${address} on channel ${channel}.`, true);
|
|
223
|
-
|
|
223
|
+
await api.commit((tx) => send(tx, api.conversationId, {
|
|
224
224
|
channel,
|
|
225
225
|
address,
|
|
226
|
-
|
|
227
|
-
type: "text",
|
|
228
|
-
text: body
|
|
229
|
-
}],
|
|
226
|
+
text: body,
|
|
230
227
|
idempotencyKey: `notify:${api.taskId}`,
|
|
231
228
|
...binding.addressData === void 0 ? {} : { addressData: binding.addressData }
|
|
232
|
-
};
|
|
233
|
-
await api.createTask(Send, input, {
|
|
234
|
-
ownership: { kind: "conversation" },
|
|
235
|
-
background: true
|
|
236
|
-
}, context);
|
|
229
|
+
}), context);
|
|
237
230
|
return text(`Message queued for ${address} on ${channel}.`);
|
|
238
231
|
}
|
|
239
232
|
});
|
|
@@ -839,17 +832,35 @@ function createChannels(options) {
|
|
|
839
832
|
const adapterFor = (channel) => Object.hasOwn(options.channels, channel) ? options.channels[channel].adapter : void 0;
|
|
840
833
|
const report = reporter(options.onReport);
|
|
841
834
|
const Send = defineSendTask(adapterFor, options.retry ?? DEFAULT_RETRY, report);
|
|
835
|
+
const send = async (tx, conversationId, input) => {
|
|
836
|
+
registration(input.channel);
|
|
837
|
+
await tx.createTask(Send, {
|
|
838
|
+
channel: input.channel,
|
|
839
|
+
address: input.address,
|
|
840
|
+
parts: [{
|
|
841
|
+
type: "text",
|
|
842
|
+
text: input.text
|
|
843
|
+
}],
|
|
844
|
+
idempotencyKey: input.idempotencyKey,
|
|
845
|
+
...input.addressData === void 0 ? {} : { addressData: input.addressData }
|
|
846
|
+
}, {
|
|
847
|
+
ownership: { kind: "conversation" },
|
|
848
|
+
conversationId,
|
|
849
|
+
background: true
|
|
850
|
+
});
|
|
851
|
+
};
|
|
842
852
|
return {
|
|
843
853
|
extension: defineExtension({
|
|
844
854
|
name: EXTENSION,
|
|
845
855
|
tasks: [Send],
|
|
846
856
|
hooks: [hook(GenerationTask, { afterRun: replyHook(Send) })]
|
|
847
857
|
}),
|
|
848
|
-
tools: defineChannelTools(
|
|
858
|
+
tools: defineChannelTools(send),
|
|
849
859
|
bind: async (tx, target, conversationId) => {
|
|
850
860
|
registration(target.channel);
|
|
851
861
|
await bindAddress(tx, target, conversationId);
|
|
852
862
|
},
|
|
863
|
+
send,
|
|
853
864
|
hub: (harness, hubOptions) => createHub(harness, {
|
|
854
865
|
options,
|
|
855
866
|
registration,
|
|
@@ -859,6 +870,6 @@ function createChannels(options) {
|
|
|
859
870
|
})
|
|
860
871
|
};
|
|
861
872
|
}
|
|
862
|
-
export { createChannels };
|
|
873
|
+
export { ChannelsDoc, conversationAddresses, createChannels, findBinding };
|
|
863
874
|
|
|
864
875
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["context","context","context"],"sources":["../src/doc.ts","../src/bind.ts","../src/hook.ts","../src/attachments.ts","../src/tools.ts","../src/run-events.ts","../src/run-tracker.ts","../src/events.ts","../src/send.ts","../src/status.ts","../src/submission.ts","../src/hub.ts","../src/report.ts","../src/core.ts"],"sourcesContent":["import type { JsonValue } from \"@earendil-works/chord\";\nimport type { Draft } from \"@earendil-works/chord/delta\";\nimport {\n type ConversationId,\n defineDoc,\n defineEntry,\n} from \"@earendil-works/pi-durable\";\nimport type { AddressKey } from \"./types\";\n\nexport type Binding = {\n conversationId: ConversationId;\n addressData?: JsonValue;\n};\n\ntype Bindings = Record<string, Record<string, Binding>>;\n\nexport type ChannelsState = { bindings: Bindings };\n\nexport const ChannelsDoc = defineDoc<ChannelsState>({\n kind: \"channels.bindings\",\n version: 1,\n scope: \"session\",\n initial: () => ({ bindings: {} }),\n checkpointWhen: (_value, _ops, info) => info.deltasSinceBase >= 50,\n});\n\nexport type ChannelMessageData = AddressKey & {\n author: string;\n addressData?: JsonValue;\n replyContext?: JsonValue;\n};\n\nexport const ChannelMessage =\n defineEntry<ChannelMessageData>(\"channel.message\");\n\nexport const ChannelNote = defineEntry<ChannelMessageData>(\"channel.note\");\n\nfunction own<T>(\n record: Readonly<Record<string, T>> | undefined,\n key: string,\n): T | undefined {\n if (record === undefined || !Object.hasOwn(record, key)) return undefined;\n return record[key];\n}\n\nexport function findBinding(\n state: Readonly<ChannelsState> | undefined,\n key: AddressKey,\n): Binding | undefined {\n return own(own(state?.bindings, key.channel), key.address);\n}\n\nfunction entriesOf(\n state: Readonly<ChannelsState> | undefined,\n): (AddressKey & { binding: Binding })[] {\n return Object.entries(state?.bindings ?? {}).flatMap(([channel, addresses]) =>\n Object.entries(addresses).map(([address, binding]) => ({\n channel,\n address,\n binding,\n })),\n );\n}\n\nexport function conversationAddresses(\n state: Readonly<ChannelsState> | undefined,\n conversationId: ConversationId,\n): AddressKey[] {\n return entriesOf(state)\n .filter(({ binding }) => binding.conversationId === conversationId)\n .map(({ channel, address }) => ({ channel, address }));\n}\n\nexport function setBinding(\n state: Draft<ChannelsState>,\n key: AddressKey,\n binding: Binding,\n): void {\n if (!Object.hasOwn(state.bindings, key.channel))\n state.bindings[key.channel] = {};\n state.bindings[key.channel][key.address] = binding;\n}\n\nexport function deleteConversation(\n state: Draft<ChannelsState>,\n conversationId: ConversationId,\n): void {\n for (const { channel, address } of conversationAddresses(\n state,\n conversationId,\n ))\n delete state.bindings[channel][address];\n}\n","import { copyJson, type JsonValue } from \"@earendil-works/chord\";\nimport {\n AgentDoc,\n type ConversationId,\n type Tx,\n} from \"@earendil-works/pi-durable\";\nimport { ChannelsDoc, findBinding, setBinding } from \"./doc\";\nimport type { AddressKey } from \"./types\";\n\nexport const EXTENSION = \"channels\";\n\nexport type BindTarget = AddressKey & { addressData?: JsonValue };\n\nasync function selectChannels(tx: Tx, id: ConversationId): Promise<void> {\n const state = await tx.doc(AgentDoc, id);\n const selected = state.extensions;\n if (!Array.isArray(selected) || selected.includes(EXTENSION)) return;\n state.extensions = [...selected, EXTENSION];\n}\n\nexport async function bindAddress(\n tx: Tx,\n target: BindTarget,\n conversationId: ConversationId,\n): Promise<void> {\n const state = await tx.doc(ChannelsDoc);\n const existing = findBinding(state, target);\n if (existing !== undefined && existing.conversationId !== conversationId) {\n throw new Error(\n `Address ${target.address} on channel ${target.channel} belongs to another conversation`,\n );\n }\n const addressData = target.addressData ?? existing?.addressData;\n setBinding(state, target, {\n conversationId,\n ...(addressData === undefined\n ? {}\n : { addressData: copyJson(addressData) }),\n });\n await selectChannels(tx, conversationId);\n}\n","import type { Context } from \"@earendil-works/chord/context\";\nimport {\n type EntryId,\n type EntryRecord,\n type GenerationHooks,\n type HookApi,\n runEndTask,\n} from \"@earendil-works/pi-durable\";\nimport { ChannelMessage } from \"./doc\";\nimport type { SendTask } from \"./send\";\nimport type { OutboundPart } from \"./types\";\n\nexport function replyKey(entryId: EntryId): string {\n return `reply:${entryId}`;\n}\n\nexport type EntrySource = Pick<HookApi, \"entries\">;\n\nexport async function runEntries(\n source: EntrySource,\n range: { first: EntryId; last?: EntryId },\n context: Context,\n): Promise<EntryRecord[]> {\n const entries: EntryRecord[] = [];\n let cursor: Parameters<HookApi[\"entries\"]>[2];\n do {\n const query = {\n minEntryId: range.first,\n ...(range.last === undefined ? {} : { maxEntryId: range.last }),\n order: \"ascending\",\n } as const;\n const page = await source.entries(query, 100, cursor, context);\n entries.push(...page.items);\n cursor = page.next;\n } while (cursor !== undefined);\n return entries;\n}\n\nfunction answerParts(entry: EntryRecord | undefined): OutboundPart[] {\n const messages = entry?.model ?? [];\n const text = messages\n .flatMap((message) => (message.role === \"assistant\" ? message.content : []))\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\");\n return text === \"\" ? [] : [{ type: \"text\", text }];\n}\n\nexport function replyHook(Send: SendTask): GenerationHooks[\"afterRun\"] {\n return async (run, api, context) => {\n const entries = await runEntries(api, run, context);\n const messages = entries.filter(ChannelMessage.is);\n if (messages.length === 0) return undefined;\n const answer = await api.entry(run.answer, context);\n const parts = run.reason === \"terminate\" ? [] : answerParts(answer);\n const tasks = messages.map(({ id, data: { author: _author, ...target } }) =>\n runEndTask(Send, { ...target, parts, idempotencyKey: replyKey(id) }),\n );\n return { tasks };\n };\n}\n","import { createHash } from \"node:crypto\";\nimport type { Context } from \"@earendil-works/chord/context\";\nimport type { ImageContent, TextContent } from \"@earendil-works/pi-ai\";\nimport {\n AgentDoc,\n type ConversationId,\n type DocumentReader,\n type HarnessOptions,\n type UserInput,\n} from \"@earendil-works/pi-durable\";\nimport type { ExecutionEnv } from \"@earendil-works/pi-durable/env\";\nimport { DEFAULT_IMAGE_LIMITS } from \"@earendil-works/pi-durable/tools\";\nimport type { ChannelAdapter, InboundFile, InboundMessage } from \"./types\";\n\nconst INLINE_IMAGE_TYPES: ReadonlySet<string> = new Set([\n \"image/png\",\n \"image/jpeg\",\n \"image/gif\",\n \"image/webp\",\n]);\n\nexport type EnvBuilder = NonNullable<HarnessOptions[\"env\"]>;\n\ntype FileSource = {\n adapter: ChannelAdapter;\n env: ExecutionEnv | undefined;\n requestId: string;\n};\n\nexport type ContentSource = {\n adapter: ChannelAdapter;\n env: EnvBuilder | undefined;\n read: DocumentReader;\n conversationId: ConversationId;\n};\n\nfunction safeName(name: string): string {\n const last = name.split(/[\\\\/]/).at(-1) ?? \"\";\n const cleaned = last.replace(/[^\\w.-]+/g, \"_\").replace(/^\\.+/, \"\");\n return cleaned === \"\" ? \"file\" : cleaned;\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nasync function save(\n env: ExecutionEnv,\n folder: string,\n file: InboundFile,\n bytes: Uint8Array,\n context: Context,\n): Promise<string> {\n const dir = await env.joinPath([env.cwd, folder], context);\n if (!dir.ok) throw dir.error;\n const created = await env.createDir(dir.value, { recursive: true }, context);\n if (!created.ok) throw created.error;\n const path = await env.joinPath([dir.value, safeName(file.name)], context);\n if (!path.ok) throw path.error;\n const written = await env.writeFile(path.value, bytes, context);\n if (!written.ok) throw written.error;\n return path.value;\n}\n\nfunction imagesOf(file: InboundFile, bytes: Uint8Array): ImageContent[] {\n if (!INLINE_IMAGE_TYPES.has(file.mimeType)) return [];\n const data = Buffer.from(bytes).toString(\"base64\");\n if (data.length > DEFAULT_IMAGE_LIMITS.maxBytes) return [];\n return [{ type: \"image\", data, mimeType: file.mimeType }];\n}\n\nasync function placed(\n file: InboundFile,\n bytes: Uint8Array,\n source: FileSource,\n context: Context,\n): Promise<string> {\n const label = `${file.name} (${file.mimeType})`;\n if (source.env === undefined)\n return `Attached file ${label}, not saved: no environment`;\n const folder = `.channels/attachments/${attachmentKey(source.requestId, file.url)}`;\n const path = await save(source.env, folder, file, bytes, context).catch(\n (error: unknown) => error,\n );\n if (typeof path !== \"string\")\n return `Attached file ${label}, not saved: ${messageOf(path)}`;\n return `Attached file ${path} (${file.mimeType})`;\n}\n\ntype Attached = { line: string; images: ImageContent[] };\n\nasync function attach(\n file: InboundFile,\n source: FileSource,\n context: Context,\n): Promise<Attached> {\n const label = `${file.name} (${file.mimeType})`;\n if (source.adapter.fetchFile === undefined)\n return { line: `Attached file ${label}, not downloaded`, images: [] };\n const bytes = await source.adapter\n .fetchFile(file.url)\n .catch((error: unknown) => error);\n if (!(bytes instanceof Uint8Array)) {\n const line = `Attached file ${label}, not downloaded: ${messageOf(bytes)}`;\n return { line, images: [] };\n }\n const line = await placed(file, bytes, source, context);\n return { line, images: imagesOf(file, bytes) };\n}\n\nfunction attachmentKey(requestId: string, url: string): string {\n const hash = createHash(\"sha256\").update(JSON.stringify([requestId, url]));\n return hash.digest(\"hex\").slice(0, 16);\n}\n\nasync function conversationEnv(\n source: ContentSource,\n context: Context,\n): Promise<ExecutionEnv | undefined> {\n if (source.env === undefined) return undefined;\n const { conversationId, read } = source;\n const agent = await read.snapshot(AgentDoc, conversationId, context);\n const cwd = agent?.cwd;\n const target = {\n conversationId,\n read,\n ...(cwd === undefined ? {} : { cwd }),\n };\n return source.env(target, context);\n}\n\nexport async function messageContent(\n message: InboundMessage,\n source: ContentSource,\n context: Context,\n): Promise<UserInput> {\n const files = message.files ?? [];\n if (files.length === 0) return message.text;\n const env = await conversationEnv(source, context);\n const fileSource = {\n adapter: source.adapter,\n env,\n requestId: message.requestId,\n };\n const lines = [message.text];\n const images: ImageContent[] = [];\n for (const file of files) {\n const attached = await attach(file, fileSource, context);\n lines.push(attached.line);\n images.push(...attached.images);\n }\n const text: TextContent = { type: \"text\", text: lines.join(\"\\n\") };\n return [text, ...images];\n}\n","import {\n defineExtension,\n defineTool,\n type Extension,\n section,\n} from \"@earendil-works/pi-durable\";\nimport { obj, str } from \"@earendil-works/pi-schema\";\nimport { ChannelsDoc, conversationAddresses, findBinding } from \"./doc\";\nimport type { SendTask } from \"./send\";\n\nexport const TOOLS_EXTENSION = \"channels-tools\";\n\nexport const NO_REPLY = \"no_reply\";\n\nfunction text(value: string, isError = false) {\n return { output: [{ type: \"text\" as const, text: value }], isError };\n}\n\nexport function defineChannelTools(Send: SendTask): Extension {\n const sendMessage = defineTool({\n name: \"send_message\",\n description:\n \"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.\",\n parameters: obj({ channel: str(), address: str(), text: str() }),\n execute: async ({ channel, address, text: body }, api, context) => {\n const state = await api.snapshot(ChannelsDoc, context);\n const binding = findBinding(state, { channel, address });\n if (binding?.conversationId !== api.conversationId)\n return text(`Unknown address ${address} on channel ${channel}.`, true);\n const input = {\n channel,\n address,\n parts: [{ type: \"text\" as const, text: body }],\n idempotencyKey: `notify:${api.taskId}`,\n ...(binding.addressData === undefined\n ? {}\n : { addressData: binding.addressData }),\n };\n await api.createTask(\n Send,\n input,\n { ownership: { kind: \"conversation\" }, background: true },\n context,\n );\n return text(`Message queued for ${address} on ${channel}.`);\n },\n });\n\n const listAddresses = defineTool({\n name: \"list_addresses\",\n description: \"List the channel addresses you can send messages to.\",\n parameters: obj({}),\n replay: \"safe\",\n execute: async (_args, api, context) => {\n const state = await api.snapshot(ChannelsDoc, context);\n const addresses = conversationAddresses(state, api.conversationId);\n return text(JSON.stringify(addresses));\n },\n });\n\n const noReply = defineTool({\n name: NO_REPLY,\n description:\n \"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.\",\n parameters: obj({}),\n replay: \"safe\",\n execute: async () => ({\n ...text(\"No reply sent.\"),\n control: { terminate: true },\n }),\n });\n\n const channelsSection = section(\n \"channels\",\n async ({ read, conversationId }, context) => {\n const state = await read.snapshot(ChannelsDoc, context);\n const addresses = conversationAddresses(state, conversationId);\n const lines = addresses.map(\n ({ channel, address }) => `- ${channel}: ${address}`,\n );\n return [\n \"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:\",\n ...(lines.length === 0 ? [\"(none yet)\"] : lines),\n ].join(\"\\n\");\n },\n );\n\n return defineExtension({\n name: TOOLS_EXTENSION,\n tools: [sendMessage, listAddresses, noReply],\n sections: [channelsSection],\n });\n}\n","import type { EntryRecord } from \"@earendil-works/pi-durable\";\nimport { NO_REPLY } from \"./tools\";\nimport type { ChannelEvent } from \"./types\";\n\ntype Message = NonNullable<EntryRecord[\"model\"]>[number];\n\nfunction startedEvents(entry: EntryRecord, message: Message): ChannelEvent[] {\n if (message.role !== \"assistant\") return [];\n const calls = message.content.flatMap((part) =>\n part.type === \"toolCall\" && part.name !== NO_REPLY ? [part] : [],\n );\n if (calls.length === 0) return [];\n const text = message.content\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\")\n .trim();\n const narration: ChannelEvent[] =\n text === \"\" ? [] : [{ type: \"text\", id: String(entry.id), text }];\n return [\n ...narration,\n ...calls.map(\n (call): ChannelEvent => ({\n type: \"tool_started\",\n id: call.id,\n name: call.name,\n args: call.arguments,\n }),\n ),\n ];\n}\n\nfunction finishedEvents(message: Message): ChannelEvent[] {\n if (message.role !== \"toolResult\" || message.toolName === NO_REPLY) return [];\n return [\n {\n type: \"tool_finished\",\n id: message.toolCallId,\n name: message.toolName,\n isError: message.isError,\n output: message.content\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\"),\n },\n ];\n}\n\nexport function eventsOf(entries: readonly EntryRecord[]): ChannelEvent[] {\n return entries.flatMap((entry) =>\n (entry.model ?? []).flatMap((message) => [\n ...startedEvents(entry, message),\n ...finishedEvents(message),\n ]),\n );\n}\n","import { BACKGROUND_CONTEXT } from \"@earendil-works/chord/context\";\nimport type {\n Conversation,\n EntryId,\n LiveRun,\n LiveState,\n} from \"@earendil-works/pi-durable\";\nimport { ChannelMessage } from \"./doc\";\nimport { replyKey, runEntries } from \"./hook\";\nimport type { Reporter } from \"./report\";\nimport { eventsOf } from \"./run-events\";\nimport type { AdapterLookup } from \"./send\";\nimport type { ChannelAdapter, ChannelEvent, ReplyTarget } from \"./types\";\n\nconst context = BACKGROUND_CONTEXT;\n\ntype Recipient = {\n channel: string;\n adapter: ChannelAdapter;\n target: ReplyTarget;\n};\n\ntype Run = {\n first: EntryId;\n inputs: string;\n recipients: Recipient[];\n cursor?: EntryId;\n};\n\nasync function notify(\n recipients: readonly Recipient[],\n event: ChannelEvent,\n report: Reporter,\n): Promise<void> {\n for (const { channel, adapter, target } of recipients) {\n await Promise.resolve()\n .then(() => adapter.events?.(target, event))\n .catch((error: unknown) =>\n report({\n kind: \"adapter_error\",\n channel,\n address: target.address,\n error,\n }),\n );\n }\n}\n\nfunction outcomeOf(live: LiveState, run: Run): ChannelEvent {\n const failure = live.runFailure;\n if (failure?.first !== run.first)\n return { type: \"run_ended\", outcome: \"completed\" };\n const aborted = failure.reason === \"aborted\" || failure.reason === \"reset\";\n return { type: \"run_ended\", outcome: aborted ? \"aborted\" : \"failed\" };\n}\n\nasync function recipientsOf(\n conversation: Conversation,\n first: EntryId,\n adapterFor: AdapterLookup,\n): Promise<Recipient[]> {\n const entries = await runEntries(conversation, { first }, context);\n return entries.filter(ChannelMessage.is).flatMap(({ id, data }) => {\n const adapter = adapterFor(data.channel);\n if (adapter?.events === undefined) return [];\n const { channel, author: _author, ...target } = data;\n const idempotencyKey = replyKey(id);\n return [{ channel, adapter, target: { ...target, idempotencyKey } }];\n });\n}\n\nexport function runTracker(\n conversation: Conversation,\n adapterFor: AdapterLookup,\n report: Reporter,\n) {\n let run: Run | undefined;\n\n async function admit(current: Run, live: LiveRun): Promise<void> {\n const inputs = live.inputs.join(\",\");\n if (inputs === \"\" || inputs === current.inputs) return;\n current.inputs = inputs;\n const known = new Set(\n current.recipients.map(({ target }) => target.idempotencyKey),\n );\n current.recipients = await recipientsOf(\n conversation,\n current.first,\n adapterFor,\n );\n const added = current.recipients.filter(\n ({ target }) => !known.has(target.idempotencyKey),\n );\n await notify(added, { type: \"run_started\" }, report);\n }\n\n async function freshEntries(current: Run) {\n const previous = current.cursor;\n const first = previous ?? current.first;\n const entries = await runEntries(conversation, { first }, context);\n current.cursor = entries.at(-1)?.id ?? previous;\n if (previous === undefined) return entries;\n return entries.filter(({ id }) => id > previous);\n }\n\n async function activity(current: Run): Promise<void> {\n const entries = await freshEntries(current);\n for (const event of eventsOf(entries))\n await notify(current.recipients, event, report);\n }\n\n async function end(live: LiveState): Promise<void> {\n if (run === undefined) return;\n const ended = run;\n run = undefined;\n await activity(ended);\n await notify(ended.recipients, outcomeOf(live, ended), report);\n }\n\n return async (live: LiveState): Promise<void> => {\n const first = live.run?.first;\n if (run !== undefined && run.first !== first) await end(live);\n if (live.run === undefined || first === undefined) return;\n run ??= { first, inputs: \"\", recipients: [] };\n await admit(run, live.run);\n await activity(run);\n };\n}\n","import { BACKGROUND_CONTEXT } from \"@earendil-works/chord/context\";\nimport {\n type ConversationId,\n GenerationTask,\n type Harness,\n LiveDoc,\n type LiveState,\n type TaskGraph,\n} from \"@earendil-works/pi-durable\";\nimport type { Reporter } from \"./report\";\nimport { runTracker } from \"./run-tracker\";\nimport type { AdapterLookup } from \"./send\";\n\nconst context = BACKGROUND_CONTEXT;\n\ntype Follower = {\n closed: Promise<void>;\n stop(): void;\n close(): void;\n keep(): void;\n};\n\nasync function follow(\n harness: Harness,\n id: ConversationId,\n adapterFor: AdapterLookup,\n report: Reporter,\n): Promise<Follower | undefined> {\n const conversation = await harness.conversation(id, context);\n const watch = await harness.watchDoc(LiveDoc, id, context);\n if (conversation === undefined || watch === undefined) return undefined;\n const track = runTracker(conversation, adapterFor, report);\n let closing = false;\n let idle = false;\n let busy = Promise.resolve();\n const stopWhenIdle = () => closing && idle && void watch.stop();\n async function observe(live: LiveState): Promise<void> {\n await track(live);\n idle = live.run === undefined;\n stopWhenIdle();\n }\n watch.start(async (call) => {\n if (call.kind !== \"value\") return;\n busy = observe(call.value);\n await busy;\n });\n return {\n closed: watch.closed.then(() => busy),\n stop: () => void watch.stop(),\n close: () => {\n closing = true;\n stopWhenIdle();\n },\n keep: () => {\n closing = false;\n },\n };\n}\n\nfunction generating(graph: TaskGraph): Set<ConversationId> {\n return new Set(\n Object.values(graph.tasks)\n .filter((node) => node.kind === GenerationTask.definition.name)\n .map((node) => node.conversationId),\n );\n}\n\nexport type EventsWatch = { stop(): Promise<void> };\n\nexport async function watchEvents(\n harness: Harness,\n adapterFor: AdapterLookup,\n report: Reporter,\n): Promise<EventsWatch> {\n let stopped = false;\n const followers = new Map<ConversationId, Promise<Follower | undefined>>();\n const graph = await harness.watchTaskGraph(context);\n\n function start(id: ConversationId): void {\n const follower = follow(harness, id, adapterFor, report);\n followers.set(id, follower);\n void follower.then(async (found) => {\n if (found === undefined) return followers.delete(id);\n await found.closed;\n followers.delete(id);\n if (!stopped && generating(graph.value).has(id)) start(id);\n });\n }\n\n function update(active: Set<ConversationId>): void {\n for (const id of active) {\n const existing = followers.get(id);\n if (existing === undefined) start(id);\n else void existing.then((follower) => follower?.keep());\n }\n for (const [id, follower] of followers)\n if (!active.has(id)) void follower.then((found) => found?.close());\n }\n\n graph.start(async (call) => {\n if (call.kind === \"value\" && !stopped) update(generating(call.value));\n });\n\n async function stopFollower(follower: Promise<Follower | undefined>) {\n const found = await follower;\n found?.stop();\n await found?.closed;\n }\n\n return {\n stop: async () => {\n stopped = true;\n await graph.stop();\n await Promise.all([...followers.values()].map(stopFollower));\n },\n };\n}\n","import { copyJson, type JsonValue } from \"@earendil-works/chord\";\nimport type { ConversationId, Tx } from \"@earendil-works/pi-durable\";\nimport { defineTask } from \"@earendil-works/pi-durable\";\nimport { ChannelsDoc, findBinding, setBinding } from \"./doc\";\nimport type { Reporter } from \"./report\";\nimport type {\n ChannelAdapter,\n OutboundPart,\n SendResult,\n SendRetry,\n} from \"./types\";\n\nexport type SendInput = {\n channel: string;\n address: string;\n parts: OutboundPart[];\n idempotencyKey: string;\n addressData?: JsonValue;\n replyContext?: JsonValue;\n};\n\ntype SendState = { phase: \"send\"; attempt: number };\n\ntype Attempt = { result: SendResult | undefined } | { error: Error };\n\nexport type AdapterLookup = (channel: string) => ChannelAdapter | undefined;\n\nexport const SEND_TASK = \"channels.send\";\n\nasync function attemptSend(\n adapterFor: AdapterLookup,\n input: SendInput,\n addressData: JsonValue | undefined,\n signal: AbortSignal,\n): Promise<Attempt> {\n try {\n const adapter = adapterFor(input.channel);\n if (adapter === undefined) throw new Error(`No channel ${input.channel}`);\n const { address, parts, replyContext, idempotencyKey } = input;\n const result = await adapter.send(\n { address, parts },\n { addressData, replyContext, idempotencyKey, signal },\n );\n return { result: result || undefined };\n } catch (error) {\n return {\n error: error instanceof Error ? error : new Error(String(error)),\n };\n }\n}\n\nasync function recordResult(\n tx: Tx,\n conversationId: ConversationId,\n input: SendInput,\n result: SendResult | undefined,\n): Promise<void> {\n if (result === undefined) return;\n const state = await tx.doc(ChannelsDoc);\n const current = findBinding(state, input);\n if (current?.conversationId !== conversationId) return;\n const addressData = result.addressData ?? current.addressData;\n const binding = () => ({\n conversationId,\n ...(addressData === undefined\n ? {}\n : { addressData: copyJson(addressData) }),\n });\n setBinding(state, input, binding());\n if (result.alias === undefined) return;\n const alias = { channel: input.channel, address: result.alias };\n if (findBinding(state, alias) === undefined)\n setBinding(state, alias, binding());\n}\n\nexport function defineSendTask(\n adapterFor: AdapterLookup,\n retry: SendRetry,\n report: Reporter,\n) {\n return defineTask<SendInput, SendState, null>({\n name: SEND_TASK,\n version: 1,\n initial: () => ({ phase: \"send\", attempt: 1 }),\n phases: {\n send: async (task, runtime, context) => {\n const { attempt } = task.state.checkpoint;\n const state = await runtime.snapshot(ChannelsDoc, context);\n const binding = findBinding(state, task.input);\n const addressData =\n binding?.conversationId === runtime.conversationId\n ? binding.addressData\n : task.input.addressData;\n const outcome = await attemptSend(\n adapterFor,\n task.input,\n addressData,\n runtime.signal,\n );\n if (\"result\" in outcome) {\n await runtime.commit(async (tx) => {\n await recordResult(\n tx,\n runtime.conversationId,\n task.input,\n outcome.result,\n );\n return {\n status: \"terminal\",\n outcome: { status: \"completed\", result: null },\n };\n }, context);\n return;\n }\n const { channel, address } = task.input;\n const { error } = outcome;\n if (attempt < retry.attempts) {\n report({ kind: \"send_retry\", channel, address, attempt, error });\n const until = runtime.now() + retry.baseDelayMs * 2 ** (attempt - 1);\n await runtime.sleepUntil(\n until,\n { phase: \"send\", attempt: attempt + 1 },\n context,\n );\n return;\n }\n report({ kind: \"send_failed\", channel, address, error });\n const failure = { message: error.message };\n await runtime.commit(\n () => ({\n status: \"terminal\",\n outcome: { status: \"failed\", error: failure },\n }),\n context,\n );\n },\n },\n abort: (_task, runtime, context) =>\n runtime.commit(\n () => ({ status: \"terminal\", outcome: { status: \"aborted\" } }),\n context,\n ),\n });\n}\n\nexport type SendTask = ReturnType<typeof defineSendTask>;\n","import { BACKGROUND_CONTEXT } from \"@earendil-works/chord/context\";\nimport type {\n ConversationId,\n EntryId,\n Harness,\n SubmissionId,\n TaskRecord,\n} from \"@earendil-works/pi-durable\";\nimport { replyKey } from \"./hook\";\nimport { SEND_TASK } from \"./send\";\nimport type { DeliveryStatus } from \"./types\";\n\nconst context = BACKGROUND_CONTEXT;\n\ntype SendRecord = TaskRecord<{ idempotencyKey: string }, unknown, unknown>;\n\nfunction sendOutcome(task: SendRecord): DeliveryStatus {\n if (task.state.status !== \"terminal\") return { state: \"sending\" };\n const outcome = task.state.outcome;\n switch (outcome.status) {\n case \"completed\":\n return { state: \"done\" };\n case \"failed\":\n case \"faulted\":\n return { state: \"failed\", error: outcome.error.message };\n default:\n return { state: \"aborted\" };\n }\n}\n\nasync function findSend(\n harness: Harness,\n conversationId: ConversationId,\n key: string,\n): Promise<SendRecord | undefined> {\n return harness.commit(async (tx) => {\n let cursor: Parameters<typeof tx.scanTasks>[2];\n do {\n const query = {\n conversationId,\n kind: SEND_TASK,\n order: \"descending\",\n } as const;\n const page = await tx.scanTasks(query, 100, cursor);\n const found = (page.items as SendRecord[]).find(\n (task) => task.input.idempotencyKey === key,\n );\n if (found !== undefined) return found;\n cursor = page.next;\n } while (cursor !== undefined);\n return undefined;\n }, context);\n}\n\nasync function replyStatus(\n harness: Harness,\n conversationId: ConversationId,\n entry: EntryId,\n): Promise<DeliveryStatus> {\n const task = await findSend(harness, conversationId, replyKey(entry));\n if (task === undefined) return { state: \"sending\" };\n const inspection = await harness.inspect(context);\n const live = inspection.tasks.find((item) => item.record.id === task.id);\n if (live?.state.kind === \"blocked\")\n return { state: \"blocked\", reason: live.state.reason };\n return sendOutcome(task);\n}\n\nexport async function deliveryStatus(\n harness: Harness,\n deliveryId: SubmissionId,\n): Promise<DeliveryStatus | undefined> {\n const found = await harness.submission(deliveryId, context);\n if (found === undefined) return undefined;\n const record = await found.status(context);\n if (record.status === \"queued\") return { state: \"queued\" };\n if (record.status === \"placed\") return { state: \"running\" };\n if (record.status === \"unanswered\") {\n return record.reason === \"aborted\"\n ? { state: \"aborted\" }\n : { state: \"failed\", error: record.reason };\n }\n if (record.type === \"write\" || record.entry === undefined)\n return { state: \"done\" };\n return replyStatus(harness, record.conversationId, record.entry);\n}\n","import type { JsonValue } from \"@earendil-works/chord\";\nimport type { SubmissionDraft, UserInput } from \"@earendil-works/pi-durable\";\nimport { ChannelMessage, type ChannelMessageData, ChannelNote } from \"./doc\";\nimport type { AddressKey, DeliverOptions, InboundMessage } from \"./types\";\n\nconst WHEN_BUSY = { queue: \"followUp\", steer: \"steer\" } as const;\n\nexport function messageData(\n key: AddressKey,\n message: InboundMessage,\n addressData: JsonValue | undefined,\n): ChannelMessageData {\n return {\n author: message.author,\n ...key,\n ...(addressData === undefined ? {} : { addressData }),\n ...(message.replyContext === undefined\n ? {}\n : { replyContext: message.replyContext }),\n };\n}\n\nexport function submission(\n requestId: string,\n content: UserInput,\n data: ChannelMessageData,\n options: Required<DeliverOptions>,\n): SubmissionDraft {\n if (options.run) {\n return {\n type: \"input\",\n content,\n requestId,\n whenBusy: WHEN_BUSY[options.whenBusy],\n entry: { kind: ChannelMessage.kind, data },\n };\n }\n const model = [{ role: \"user\" as const, content, timestamp: Date.now() }];\n return {\n type: \"write\",\n requestId,\n entry: { kind: ChannelNote.kind, data, model },\n };\n}\n","import { copyJson } from \"@earendil-works/chord\";\nimport { BACKGROUND_CONTEXT } from \"@earendil-works/chord/context\";\nimport {\n type Conversation,\n type ConversationId,\n configure,\n type Harness,\n type SubmissionId,\n} from \"@earendil-works/pi-durable\";\nimport { type EnvBuilder, messageContent } from \"./attachments\";\nimport { type BindTarget, bindAddress } from \"./bind\";\nimport {\n ChannelsDoc,\n conversationAddresses,\n deleteConversation,\n findBinding,\n setBinding,\n} from \"./doc\";\nimport { type EventsWatch, watchEvents } from \"./events\";\nimport type { Reporter } from \"./report\";\nimport type { AdapterLookup } from \"./send\";\nimport { deliveryStatus } from \"./status\";\nimport { messageData, submission } from \"./submission\";\nimport type {\n AddressKey,\n ChannelRegistration,\n ChannelsOptions,\n DeliverOptions,\n DeliveryReceipt,\n DeliveryStatus,\n InboundMessage,\n} from \"./types\";\n\nconst context = BACKGROUND_CONTEXT;\n\nexport type ChannelsHub = {\n start(): Promise<void>;\n stop(): Promise<void>;\n deliver(\n channel: string,\n message: InboundMessage,\n options?: DeliverOptions,\n ): Promise<DeliveryReceipt | undefined>;\n bind(target: BindTarget, conversationId: ConversationId): Promise<void>;\n addresses(conversationId: ConversationId): Promise<AddressKey[]>;\n conversationOf(key: AddressKey): Promise<ConversationId | undefined>;\n status(deliveryId: SubmissionId): Promise<DeliveryStatus | undefined>;\n cancel(key: AddressKey): Promise<void>;\n clear(key: AddressKey): Promise<void>;\n compact(key: AddressKey): Promise<void>;\n end(key: AddressKey): Promise<void>;\n};\n\nexport type HubSetup = {\n options: ChannelsOptions;\n registration(channel: string): ChannelRegistration;\n adapterFor: AdapterLookup;\n report: Reporter;\n env: EnvBuilder | undefined;\n};\n\nexport type HubOptions = { env?: EnvBuilder };\n\nconst cancel = (conversation: Conversation) =>\n conversation.abort(context, { background: true });\n\nexport function createHub(harness: Harness, setup: HubSetup): ChannelsHub {\n const tails = new Map<string, Promise<unknown>>();\n const controller = new AbortController();\n const adapters = Object.values(setup.options.channels).map(\n ({ adapter }) => adapter,\n );\n let starting: Promise<void> | undefined;\n let watcher: EventsWatch | undefined;\n let stopping: Promise<void> | undefined;\n\n function serial<T>(key: AddressKey, run: () => Promise<T>): Promise<T> {\n if (stopping !== undefined)\n return Promise.reject(new Error(\"Channels hub is stopped\"));\n const id = JSON.stringify([key.channel, key.address]);\n const result = (tails.get(id) ?? Promise.resolve()).then(run);\n const tail = result.catch(() => undefined);\n tails.set(id, tail);\n void tail.then(() => tails.get(id) === tail && tails.delete(id));\n return result;\n }\n\n async function conversationFor(\n key: AddressKey,\n message: InboundMessage,\n create: boolean,\n ): Promise<ConversationId | undefined> {\n const factory = create\n ? setup.registration(key.channel).conversation\n : undefined;\n return harness.commit(async (tx) => {\n const state = await tx.doc(ChannelsDoc);\n const existing = findBinding(state, key);\n if (existing !== undefined) return existing.conversationId;\n const created = factory?.(message, { channel: key.channel });\n if (created === undefined) return undefined;\n const record = await tx.createConversation({\n ownership: { kind: \"ownerless\" },\n });\n await configure(tx, record.id, created.agent ?? {});\n await created.init?.(tx, record.id);\n await bindAddress(tx, key, record.id);\n return record.id;\n }, context);\n }\n\n async function admit(\n key: AddressKey,\n message: InboundMessage,\n options: Required<DeliverOptions>,\n ): Promise<DeliveryReceipt | undefined> {\n const create = options.run && options.create;\n const conversationId = await conversationFor(key, message, create);\n if (conversationId === undefined) {\n setup.report({ kind: \"ignored\", ...key });\n return undefined;\n }\n const conversation = await harness.conversation(conversationId, context);\n if (conversation === undefined)\n throw new Error(`Conversation ${conversationId} not found`);\n const content = await messageContent(\n message,\n {\n adapter: setup.registration(key.channel).adapter,\n env: setup.env,\n read: harness,\n conversationId,\n },\n context,\n );\n const admitted = await harness.commit(async (tx) => {\n const known = await tx.submissionByRequest(\n conversationId,\n message.requestId,\n );\n if (known !== undefined)\n return { submissionId: known.id, duplicate: true };\n const state = await tx.doc(ChannelsDoc);\n const stored = findBinding(state, key)?.addressData;\n if (message.addressData !== undefined) {\n setBinding(state, key, {\n conversationId,\n addressData: message.addressData,\n });\n }\n const addressData =\n message.addressData ??\n (stored === undefined ? undefined : copyJson(stored));\n const data = messageData(key, message, addressData);\n const draft = submission(message.requestId, content, data, options);\n const submissionId = await conversation.submit(tx, draft);\n return { submissionId, duplicate: false };\n }, context);\n setup.report({ kind: \"admitted\", ...key, conversationId, ...admitted });\n return { submissionId: admitted.submissionId, conversationId };\n }\n\n const deliver: ChannelsHub[\"deliver\"] = async (channel, message, options) => {\n setup.registration(channel);\n const key = { channel, address: message.address };\n const resolved = {\n whenBusy: options?.whenBusy ?? setup.options.whenBusy ?? \"queue\",\n run: options?.run ?? true,\n create: options?.create ?? true,\n };\n return serial(key, () => admit(key, message, resolved));\n };\n\n function start(): Promise<void> {\n if (starting !== undefined || stopping !== undefined)\n return Promise.reject(new Error(\"Channels hub can only start once\"));\n starting = startAll();\n return starting;\n }\n\n async function startAll(): Promise<void> {\n const channels = Object.entries(setup.options.channels);\n if (adapters.some((adapter) => adapter.events !== undefined))\n watcher = await watchEvents(harness, setup.adapterFor, setup.report);\n const { signal } = controller;\n await Promise.all(\n channels.map(([channel, { adapter }]) =>\n adapter.start?.({\n deliver: (message, options) => deliver(channel, message, options),\n cancel: (address) => cancelAt({ channel, address }),\n report: (report) => setup.report({ ...report, channel }),\n signal,\n }),\n ),\n );\n }\n\n async function drain(): Promise<void> {\n await starting?.catch(() => undefined);\n await Promise.all(tails.values());\n await watcher?.stop();\n controller.abort();\n if (starting === undefined) return;\n await Promise.all(adapters.map((adapter) => adapter.stop?.()));\n }\n\n function stop(): Promise<void> {\n stopping ??= drain();\n return stopping;\n }\n\n async function bind(target: BindTarget, conversationId: ConversationId) {\n setup.registration(target.channel);\n return serial(target, () =>\n harness.commit((tx) => bindAddress(tx, target, conversationId), context),\n );\n }\n\n function atAddress(\n key: AddressKey,\n run: (conversation: Conversation) => Promise<void>,\n ): Promise<void> {\n return serial(key, async () => {\n const state = await harness.snapshot(ChannelsDoc, context);\n const binding = findBinding(state, key);\n if (binding === undefined) return;\n const conversation = await harness.conversation(\n binding.conversationId,\n context,\n );\n if (conversation !== undefined) await run(conversation);\n });\n }\n\n const cancelAt = (key: AddressKey) => atAddress(key, cancel);\n\n async function addresses(conversationId: ConversationId) {\n const state = await harness.snapshot(ChannelsDoc, context);\n return conversationAddresses(state, conversationId);\n }\n\n async function conversationOf(key: AddressKey) {\n const state = await harness.snapshot(ChannelsDoc, context);\n return findBinding(state, key)?.conversationId;\n }\n\n return {\n start,\n stop,\n deliver,\n bind,\n addresses,\n conversationOf,\n status: (deliveryId) => deliveryStatus(harness, deliveryId),\n cancel: cancelAt,\n clear: (key) =>\n atAddress(key, async (conversation) => {\n await cancel(conversation);\n await conversation.reset(undefined, context);\n }),\n compact: (key) =>\n atAddress(key, async (conversation) => {\n await conversation.compact(undefined, context);\n }),\n end: (key) =>\n atAddress(key, async (conversation) => {\n await cancel(conversation);\n await harness.commit(async (tx) => {\n const state = await tx.doc(ChannelsDoc);\n deleteConversation(state, conversation.id);\n }, context);\n }),\n };\n}\n","import type { ChannelReport, ChannelsOptions } from \"./types\";\n\nexport type Reporter = (report: ChannelReport) => void;\n\nexport function reporter(onReport: ChannelsOptions[\"onReport\"]): Reporter {\n return (report) => {\n try {\n onReport?.(report);\n } catch {\n return;\n }\n };\n}\n","import type { Tx } from \"@earendil-works/pi-durable\";\nimport {\n type ConversationId,\n defineExtension,\n type Extension,\n GenerationTask,\n type Harness,\n hook,\n} from \"@earendil-works/pi-durable\";\nimport { type BindTarget, bindAddress, EXTENSION } from \"./bind\";\nimport { replyHook } from \"./hook\";\nimport { type ChannelsHub, createHub, type HubOptions } from \"./hub\";\nimport { reporter } from \"./report\";\nimport { defineSendTask } from \"./send\";\nimport { defineChannelTools } from \"./tools\";\nimport type { ChannelRegistration, ChannelsOptions } from \"./types\";\n\nconst DEFAULT_RETRY = { attempts: 5, baseDelayMs: 1000 };\n\nexport type Channels = {\n extension: Extension;\n tools: Extension;\n bind(\n tx: Tx,\n target: BindTarget,\n conversationId: ConversationId,\n ): Promise<void>;\n hub(harness: Harness, options?: HubOptions): ChannelsHub;\n};\n\nexport function createChannels(options: ChannelsOptions): Channels {\n const registration = (channel: string): ChannelRegistration => {\n if (!Object.hasOwn(options.channels, channel))\n throw new Error(`No channel ${channel}`);\n return options.channels[channel];\n };\n const adapterFor = (channel: string) =>\n Object.hasOwn(options.channels, channel)\n ? options.channels[channel].adapter\n : undefined;\n const report = reporter(options.onReport);\n const Send = defineSendTask(\n adapterFor,\n options.retry ?? DEFAULT_RETRY,\n report,\n );\n\n return {\n extension: defineExtension({\n name: EXTENSION,\n tasks: [Send],\n hooks: [hook(GenerationTask, { afterRun: replyHook(Send) })],\n }),\n tools: defineChannelTools(Send),\n bind: async (tx, target, conversationId) => {\n registration(target.channel);\n await bindAddress(tx, target, conversationId);\n },\n hub: (harness, hubOptions) =>\n createHub(harness, {\n options,\n registration,\n adapterFor,\n report,\n env: hubOptions?.env,\n }),\n };\n}\n"],"mappings":";;;;;;;AAkBA,MAAa,cAAc,UAAyB;CAClD,MAAM;CACN,SAAS;CACT,OAAO;CACP,gBAAgB,EAAE,UAAU,CAAC,EAAE;CAC/B,iBAAiB,QAAQ,MAAM,SAAS,KAAK,mBAAmB;AAClE,CAAC;AAQD,MAAa,iBACX,YAAgC,iBAAiB;AAEnD,MAAa,cAAc,YAAgC,cAAc;AAEzE,SAAS,IACP,QACA,KACe;CACf,IAAI,WAAW,KAAA,KAAa,CAAC,OAAO,OAAO,QAAQ,GAAG,GAAG,OAAO,KAAA;CAChE,OAAO,OAAO;AAChB;AAEA,SAAgB,YACd,OACA,KACqB;CACrB,OAAO,IAAI,IAAI,OAAO,UAAU,IAAI,OAAO,GAAG,IAAI,OAAO;AAC3D;AAEA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,OAAO,OAAO,OAAO;IAEjC,mBAAmB,MADC,GAAG,IAAI,WAAW,GACZ,aAAa,EAAE;GAC3C,GAAG,OAAO;EACZ,CAAC;CACL;AACF;;AC7QA,SAAgB,SAAS,UAAiD;CACxE,QAAQ,WAAW;EACjB,IAAI;GACF,WAAW,MAAM;EACnB,QAAQ;GACN;EACF;CACF;AACF;;ACKA,MAAM,gBAAgB;CAAE,UAAU;CAAG,aAAa;AAAK;AAavD,SAAgB,eAAe,SAAoC;CACjE,MAAM,gBAAgB,YAAyC;EAC7D,IAAI,CAAC,OAAO,OAAO,QAAQ,UAAU,OAAO,GAC1C,MAAM,IAAI,MAAM,cAAc,SAAS;EACzC,OAAO,QAAQ,SAAS;CAC1B;CACA,MAAM,cAAc,YAClB,OAAO,OAAO,QAAQ,UAAU,OAAO,IACnC,QAAQ,SAAS,QAAQ,CAAC,UAC1B,KAAA;CACN,MAAM,SAAS,SAAS,QAAQ,QAAQ;CACxC,MAAM,OAAO,eACX,YACA,QAAQ,SAAS,eACjB,MACF;CAEA,OAAO;EACL,WAAW,gBAAgB;GACzB,MAAM;GACN,OAAO,CAAC,IAAI;GACZ,OAAO,CAAC,KAAK,gBAAgB,EAAE,UAAU,UAAU,IAAI,EAAE,CAAC,CAAC;EAC7D,CAAC;EACD,OAAO,mBAAmB,IAAI;EAC9B,MAAM,OAAO,IAAI,QAAQ,mBAAmB;GAC1C,aAAa,OAAO,OAAO;GAC3B,MAAM,YAAY,IAAI,QAAQ,cAAc;EAC9C;EACA,MAAM,SAAS,eACb,UAAU,SAAS;GACjB;GACA;GACA;GACA;GACA,KAAK,YAAY;EACnB,CAAC;CACL;AACF"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["context","context","context"],"sources":["../src/doc.ts","../src/bind.ts","../src/hook.ts","../src/attachments.ts","../src/tools.ts","../src/run-events.ts","../src/run-tracker.ts","../src/events.ts","../src/send.ts","../src/status.ts","../src/submission.ts","../src/hub.ts","../src/report.ts","../src/core.ts"],"sourcesContent":["import type { Draft } from \"@earendil-works/chord/delta\";\nimport type { JsonValue } from \"@earendil-works/chord/json\";\nimport {\n type ConversationId,\n defineDoc,\n defineEntry,\n} from \"@earendil-works/pi-durable\";\nimport type { AddressKey } from \"./types\";\n\nexport type Binding = {\n conversationId: ConversationId;\n addressData?: JsonValue;\n};\n\ntype Bindings = Record<string, Record<string, Binding>>;\n\nexport type ChannelsState = { bindings: Bindings };\n\nexport const ChannelsDoc = defineDoc<ChannelsState>({\n kind: \"channels.bindings\",\n version: 1,\n scope: \"session\",\n initial: () => ({ bindings: {} }),\n checkpointWhen: (_value, _ops, info) => info.deltasSinceBase >= 50,\n});\n\nexport type ChannelMessageData = AddressKey & {\n author: string;\n addressData?: JsonValue;\n replyContext?: JsonValue;\n};\n\nexport const ChannelMessage =\n defineEntry<ChannelMessageData>(\"channel.message\");\n\nexport const ChannelNote = defineEntry<ChannelMessageData>(\"channel.note\");\n\nfunction own<T>(\n record: Readonly<Record<string, T>> | undefined,\n key: string,\n): T | undefined {\n if (record === undefined || !Object.hasOwn(record, key)) return undefined;\n return record[key];\n}\n\nexport function findBinding(\n state: Readonly<ChannelsState> | undefined,\n key: AddressKey,\n): Binding | undefined {\n return own(own(state?.bindings, key.channel), key.address);\n}\n\nfunction entriesOf(\n state: Readonly<ChannelsState> | undefined,\n): (AddressKey & { binding: Binding })[] {\n return Object.entries(state?.bindings ?? {}).flatMap(([channel, addresses]) =>\n Object.entries(addresses).map(([address, binding]) => ({\n channel,\n address,\n binding,\n })),\n );\n}\n\nexport function conversationAddresses(\n state: Readonly<ChannelsState> | undefined,\n conversationId: ConversationId,\n): AddressKey[] {\n return entriesOf(state)\n .filter(({ binding }) => binding.conversationId === conversationId)\n .map(({ channel, address }) => ({ channel, address }));\n}\n\nexport function setBinding(\n state: Draft<ChannelsState>,\n key: AddressKey,\n binding: Binding,\n): void {\n if (!Object.hasOwn(state.bindings, key.channel))\n state.bindings[key.channel] = {};\n state.bindings[key.channel][key.address] = binding;\n}\n\nexport function deleteConversation(\n state: Draft<ChannelsState>,\n conversationId: ConversationId,\n): void {\n for (const { channel, address } of conversationAddresses(\n state,\n conversationId,\n ))\n delete state.bindings[channel][address];\n}\n","import { copyJson, type JsonValue } from \"@earendil-works/chord/json\";\nimport {\n AgentDoc,\n type ConversationId,\n type Tx,\n} from \"@earendil-works/pi-durable\";\nimport { ChannelsDoc, findBinding, setBinding } from \"./doc\";\nimport type { AddressKey } from \"./types\";\n\nexport const EXTENSION = \"channels\";\n\nexport type BindTarget = AddressKey & { addressData?: JsonValue };\n\nasync function selectChannels(tx: Tx, id: ConversationId): Promise<void> {\n const state = await tx.doc(AgentDoc, id);\n const selected = state.extensions;\n if (!Array.isArray(selected) || selected.includes(EXTENSION)) return;\n state.extensions = [...selected, EXTENSION];\n}\n\nexport async function bindAddress(\n tx: Tx,\n target: BindTarget,\n conversationId: ConversationId,\n): Promise<void> {\n const state = await tx.doc(ChannelsDoc);\n const existing = findBinding(state, target);\n if (existing !== undefined && existing.conversationId !== conversationId) {\n throw new Error(\n `Address ${target.address} on channel ${target.channel} belongs to another conversation`,\n );\n }\n const addressData = target.addressData ?? existing?.addressData;\n setBinding(state, target, {\n conversationId,\n ...(addressData === undefined\n ? {}\n : { addressData: copyJson(addressData) }),\n });\n await selectChannels(tx, conversationId);\n}\n","import type { Context } from \"@earendil-works/chord/context\";\nimport {\n type EntryId,\n type EntryRecord,\n type GenerationHooks,\n type HookApi,\n hookTask,\n} from \"@earendil-works/pi-durable\";\nimport { ChannelMessage } from \"./doc\";\nimport type { SendTask } from \"./send\";\nimport type { OutboundPart } from \"./types\";\n\nexport function replyKey(entryId: EntryId): string {\n return `reply:${entryId}`;\n}\n\nexport type EntrySource = Pick<HookApi, \"entries\">;\n\nexport async function runEntries(\n source: EntrySource,\n range: { first: EntryId; last?: EntryId },\n context: Context,\n): Promise<EntryRecord[]> {\n const entries: EntryRecord[] = [];\n let cursor: Parameters<HookApi[\"entries\"]>[2];\n do {\n const query = {\n minEntryId: range.first,\n ...(range.last === undefined ? {} : { maxEntryId: range.last }),\n order: \"ascending\",\n } as const;\n const page = await source.entries(query, 100, cursor, context);\n entries.push(...page.items);\n cursor = page.next;\n } while (cursor !== undefined);\n return entries;\n}\n\nfunction answerParts(entry: EntryRecord | undefined): OutboundPart[] {\n const messages = entry?.model ?? [];\n const text = messages\n .flatMap((message) => (message.role === \"assistant\" ? message.content : []))\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\");\n return text === \"\" ? [] : [{ type: \"text\", text }];\n}\n\nexport function replyHook(Send: SendTask): GenerationHooks[\"afterRun\"] {\n return async (run, api, context) => {\n const entries = await runEntries(api, run, context);\n const messages = entries.filter(ChannelMessage.is);\n if (messages.length === 0) return undefined;\n const answer = await api.entry(run.answer, context);\n const parts = run.reason === \"terminate\" ? [] : answerParts(answer);\n const tasks = messages.map(({ id, data: { author: _author, ...target } }) =>\n hookTask(Send, { ...target, parts, idempotencyKey: replyKey(id) }),\n );\n return { tasks };\n };\n}\n","import { createHash } from \"node:crypto\";\nimport type { Context } from \"@earendil-works/chord/context\";\nimport type { ImageContent, TextContent } from \"@earendil-works/pi-ai\";\nimport {\n AgentDoc,\n type ConversationId,\n type DocumentReader,\n type HarnessOptions,\n type UserInput,\n} from \"@earendil-works/pi-durable\";\nimport type { ExecutionEnv } from \"@earendil-works/pi-durable/env\";\nimport { DEFAULT_IMAGE_LIMITS } from \"@earendil-works/pi-durable/tools\";\nimport type { ChannelAdapter, InboundFile, InboundMessage } from \"./types\";\n\nconst INLINE_IMAGE_TYPES: ReadonlySet<string> = new Set([\n \"image/png\",\n \"image/jpeg\",\n \"image/gif\",\n \"image/webp\",\n]);\n\nexport type EnvBuilder = NonNullable<HarnessOptions[\"env\"]>;\n\ntype FileSource = {\n adapter: ChannelAdapter;\n env: ExecutionEnv | undefined;\n requestId: string;\n};\n\nexport type ContentSource = {\n adapter: ChannelAdapter;\n env: EnvBuilder | undefined;\n read: DocumentReader;\n conversationId: ConversationId;\n};\n\nfunction safeName(name: string): string {\n const last = name.split(/[\\\\/]/).at(-1) ?? \"\";\n const cleaned = last.replace(/[^\\w.-]+/g, \"_\").replace(/^\\.+/, \"\");\n return cleaned === \"\" ? \"file\" : cleaned;\n}\n\nfunction messageOf(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nasync function save(\n env: ExecutionEnv,\n folder: string,\n file: InboundFile,\n bytes: Uint8Array,\n context: Context,\n): Promise<string> {\n const dir = await env.joinPath([env.cwd, folder], context);\n if (!dir.ok) throw dir.error;\n const created = await env.createDir(dir.value, { recursive: true }, context);\n if (!created.ok) throw created.error;\n const path = await env.joinPath([dir.value, safeName(file.name)], context);\n if (!path.ok) throw path.error;\n const written = await env.writeFile(path.value, bytes, context);\n if (!written.ok) throw written.error;\n return path.value;\n}\n\nfunction imagesOf(file: InboundFile, bytes: Uint8Array): ImageContent[] {\n if (!INLINE_IMAGE_TYPES.has(file.mimeType)) return [];\n const data = Buffer.from(bytes).toString(\"base64\");\n if (data.length > DEFAULT_IMAGE_LIMITS.maxBytes) return [];\n return [{ type: \"image\", data, mimeType: file.mimeType }];\n}\n\nasync function placed(\n file: InboundFile,\n bytes: Uint8Array,\n source: FileSource,\n context: Context,\n): Promise<string> {\n const label = `${file.name} (${file.mimeType})`;\n if (source.env === undefined)\n return `Attached file ${label}, not saved: no environment`;\n const folder = `.channels/attachments/${attachmentKey(source.requestId, file.url)}`;\n const path = await save(source.env, folder, file, bytes, context).catch(\n (error: unknown) => error,\n );\n if (typeof path !== \"string\")\n return `Attached file ${label}, not saved: ${messageOf(path)}`;\n return `Attached file ${path} (${file.mimeType})`;\n}\n\ntype Attached = { line: string; images: ImageContent[] };\n\nasync function attach(\n file: InboundFile,\n source: FileSource,\n context: Context,\n): Promise<Attached> {\n const label = `${file.name} (${file.mimeType})`;\n if (source.adapter.fetchFile === undefined)\n return { line: `Attached file ${label}, not downloaded`, images: [] };\n const bytes = await source.adapter\n .fetchFile(file.url)\n .catch((error: unknown) => error);\n if (!(bytes instanceof Uint8Array)) {\n const line = `Attached file ${label}, not downloaded: ${messageOf(bytes)}`;\n return { line, images: [] };\n }\n const line = await placed(file, bytes, source, context);\n return { line, images: imagesOf(file, bytes) };\n}\n\nfunction attachmentKey(requestId: string, url: string): string {\n const hash = createHash(\"sha256\").update(JSON.stringify([requestId, url]));\n return hash.digest(\"hex\").slice(0, 16);\n}\n\nasync function conversationEnv(\n source: ContentSource,\n context: Context,\n): Promise<ExecutionEnv | undefined> {\n if (source.env === undefined) return undefined;\n const { conversationId, read } = source;\n const agent = await read.snapshot(AgentDoc, conversationId, context);\n const cwd = agent?.cwd;\n const target = {\n conversationId,\n read,\n ...(cwd === undefined ? {} : { cwd }),\n };\n return source.env(target, context);\n}\n\nexport async function messageContent(\n message: InboundMessage,\n source: ContentSource,\n context: Context,\n): Promise<UserInput> {\n const files = message.files ?? [];\n if (files.length === 0) return message.text;\n const env = await conversationEnv(source, context);\n const fileSource = {\n adapter: source.adapter,\n env,\n requestId: message.requestId,\n };\n const lines = [message.text];\n const images: ImageContent[] = [];\n for (const file of files) {\n const attached = await attach(file, fileSource, context);\n lines.push(attached.line);\n images.push(...attached.images);\n }\n const text: TextContent = { type: \"text\", text: lines.join(\"\\n\") };\n return [text, ...images];\n}\n","import {\n defineExtension,\n defineTool,\n type Extension,\n section,\n} from \"@earendil-works/pi-durable\";\nimport { obj, str } from \"@earendil-works/pi-schema\";\nimport type { Send } from \"./core\";\nimport { ChannelsDoc, conversationAddresses, findBinding } from \"./doc\";\n\nexport const TOOLS_EXTENSION = \"channels-tools\";\n\nexport const NO_REPLY = \"no_reply\";\n\nfunction text(value: string, isError = false) {\n return { output: [{ type: \"text\" as const, text: value }], isError };\n}\n\nexport function defineChannelTools(send: Send): Extension {\n const sendMessage = defineTool({\n name: \"send_message\",\n description:\n \"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.\",\n parameters: obj({ channel: str(), address: str(), text: str() }),\n execute: async ({ channel, address, text: body }, api, context) => {\n const state = await api.snapshot(ChannelsDoc, context);\n const binding = findBinding(state, { channel, address });\n if (binding?.conversationId !== api.conversationId)\n return text(`Unknown address ${address} on channel ${channel}.`, true);\n await api.commit(\n (tx) =>\n send(tx, api.conversationId, {\n channel,\n address,\n text: body,\n idempotencyKey: `notify:${api.taskId}`,\n ...(binding.addressData === undefined\n ? {}\n : { addressData: binding.addressData }),\n }),\n context,\n );\n return text(`Message queued for ${address} on ${channel}.`);\n },\n });\n\n const listAddresses = defineTool({\n name: \"list_addresses\",\n description: \"List the channel addresses you can send messages to.\",\n parameters: obj({}),\n replay: \"safe\",\n execute: async (_args, api, context) => {\n const state = await api.snapshot(ChannelsDoc, context);\n const addresses = conversationAddresses(state, api.conversationId);\n return text(JSON.stringify(addresses));\n },\n });\n\n const noReply = defineTool({\n name: NO_REPLY,\n description:\n \"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.\",\n parameters: obj({}),\n replay: \"safe\",\n execute: async () => ({\n ...text(\"No reply sent.\"),\n control: { terminate: true },\n }),\n });\n\n const channelsSection = section(\n \"channels\",\n async ({ read, conversationId }, context) => {\n const state = await read.snapshot(ChannelsDoc, context);\n const addresses = conversationAddresses(state, conversationId);\n const lines = addresses.map(\n ({ channel, address }) => `- ${channel}: ${address}`,\n );\n return [\n \"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:\",\n ...(lines.length === 0 ? [\"(none yet)\"] : lines),\n ].join(\"\\n\");\n },\n );\n\n return defineExtension({\n name: TOOLS_EXTENSION,\n tools: [sendMessage, listAddresses, noReply],\n sections: [channelsSection],\n });\n}\n","import type { EntryRecord } from \"@earendil-works/pi-durable\";\nimport { NO_REPLY } from \"./tools\";\nimport type { ChannelEvent } from \"./types\";\n\ntype Message = NonNullable<EntryRecord[\"model\"]>[number];\n\nfunction startedEvents(entry: EntryRecord, message: Message): ChannelEvent[] {\n if (message.role !== \"assistant\") return [];\n const calls = message.content.flatMap((part) =>\n part.type === \"toolCall\" && part.name !== NO_REPLY ? [part] : [],\n );\n if (calls.length === 0) return [];\n const text = message.content\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\")\n .trim();\n const narration: ChannelEvent[] =\n text === \"\" ? [] : [{ type: \"text\", id: String(entry.id), text }];\n return [\n ...narration,\n ...calls.map(\n (call): ChannelEvent => ({\n type: \"tool_started\",\n id: call.id,\n name: call.name,\n args: call.arguments,\n }),\n ),\n ];\n}\n\nfunction finishedEvents(message: Message): ChannelEvent[] {\n if (message.role !== \"toolResult\" || message.toolName === NO_REPLY) return [];\n return [\n {\n type: \"tool_finished\",\n id: message.toolCallId,\n name: message.toolName,\n isError: message.isError,\n output: message.content\n .flatMap((part) => (part.type === \"text\" ? [part.text] : []))\n .join(\"\"),\n },\n ];\n}\n\nexport function eventsOf(entries: readonly EntryRecord[]): ChannelEvent[] {\n return entries.flatMap((entry) =>\n (entry.model ?? []).flatMap((message) => [\n ...startedEvents(entry, message),\n ...finishedEvents(message),\n ]),\n );\n}\n","import { BACKGROUND_CONTEXT } from \"@earendil-works/chord/context\";\nimport type {\n Conversation,\n EntryId,\n LiveRun,\n LiveState,\n} from \"@earendil-works/pi-durable\";\nimport { ChannelMessage } from \"./doc\";\nimport { replyKey, runEntries } from \"./hook\";\nimport type { Reporter } from \"./report\";\nimport { eventsOf } from \"./run-events\";\nimport type { AdapterLookup } from \"./send\";\nimport type { ChannelAdapter, ChannelEvent, ReplyTarget } from \"./types\";\n\nconst context = BACKGROUND_CONTEXT;\n\ntype Recipient = {\n channel: string;\n adapter: ChannelAdapter;\n target: ReplyTarget;\n};\n\ntype Run = {\n first: EntryId;\n inputs: string;\n recipients: Recipient[];\n cursor?: EntryId;\n};\n\nasync function notify(\n recipients: readonly Recipient[],\n event: ChannelEvent,\n report: Reporter,\n): Promise<void> {\n for (const { channel, adapter, target } of recipients) {\n await Promise.resolve()\n .then(() => adapter.events?.(target, event))\n .catch((error: unknown) =>\n report({\n kind: \"adapter_error\",\n channel,\n address: target.address,\n error,\n }),\n );\n }\n}\n\nfunction outcomeOf(live: LiveState, run: Run): ChannelEvent {\n const failure = live.runFailure;\n if (failure?.first !== run.first)\n return { type: \"run_ended\", outcome: \"completed\" };\n const aborted = failure.reason === \"aborted\" || failure.reason === \"reset\";\n return { type: \"run_ended\", outcome: aborted ? \"aborted\" : \"failed\" };\n}\n\nasync function recipientsOf(\n conversation: Conversation,\n first: EntryId,\n adapterFor: AdapterLookup,\n): Promise<Recipient[]> {\n const entries = await runEntries(conversation, { first }, context);\n return entries.filter(ChannelMessage.is).flatMap(({ id, data }) => {\n const adapter = adapterFor(data.channel);\n if (adapter?.events === undefined) return [];\n const { channel, author: _author, ...target } = data;\n const idempotencyKey = replyKey(id);\n return [{ channel, adapter, target: { ...target, idempotencyKey } }];\n });\n}\n\nexport function runTracker(\n conversation: Conversation,\n adapterFor: AdapterLookup,\n report: Reporter,\n) {\n let run: Run | undefined;\n\n async function admit(current: Run, live: LiveRun): Promise<void> {\n const inputs = live.inputs.join(\",\");\n if (inputs === \"\" || inputs === current.inputs) return;\n current.inputs = inputs;\n const known = new Set(\n current.recipients.map(({ target }) => target.idempotencyKey),\n );\n current.recipients = await recipientsOf(\n conversation,\n current.first,\n adapterFor,\n );\n const added = current.recipients.filter(\n ({ target }) => !known.has(target.idempotencyKey),\n );\n await notify(added, { type: \"run_started\" }, report);\n }\n\n async function freshEntries(current: Run) {\n const previous = current.cursor;\n const first = previous ?? current.first;\n const entries = await runEntries(conversation, { first }, context);\n current.cursor = entries.at(-1)?.id ?? previous;\n if (previous === undefined) return entries;\n return entries.filter(({ id }) => id > previous);\n }\n\n async function activity(current: Run): Promise<void> {\n const entries = await freshEntries(current);\n for (const event of eventsOf(entries))\n await notify(current.recipients, event, report);\n }\n\n async function end(live: LiveState): Promise<void> {\n if (run === undefined) return;\n const ended = run;\n run = undefined;\n await activity(ended);\n await notify(ended.recipients, outcomeOf(live, ended), report);\n }\n\n return async (live: LiveState): Promise<void> => {\n const first = live.run?.first;\n if (run !== undefined && run.first !== first) await end(live);\n if (live.run === undefined || first === undefined) return;\n run ??= { first, inputs: \"\", recipients: [] };\n await admit(run, live.run);\n await activity(run);\n };\n}\n","import { BACKGROUND_CONTEXT } from \"@earendil-works/chord/context\";\nimport {\n type ConversationId,\n GenerationTask,\n type Harness,\n LiveDoc,\n type LiveState,\n type TaskGraph,\n} from \"@earendil-works/pi-durable\";\nimport type { Reporter } from \"./report\";\nimport { runTracker } from \"./run-tracker\";\nimport type { AdapterLookup } from \"./send\";\n\nconst context = BACKGROUND_CONTEXT;\n\ntype Follower = {\n closed: Promise<void>;\n stop(): void;\n close(): void;\n keep(): void;\n};\n\nasync function follow(\n harness: Harness,\n id: ConversationId,\n adapterFor: AdapterLookup,\n report: Reporter,\n): Promise<Follower | undefined> {\n const conversation = await harness.conversation(id, context);\n const watch = await harness.watchDoc(LiveDoc, id, context);\n if (conversation === undefined || watch === undefined) return undefined;\n const track = runTracker(conversation, adapterFor, report);\n let closing = false;\n let idle = false;\n let busy = Promise.resolve();\n const stopWhenIdle = () => closing && idle && void watch.stop();\n async function observe(live: LiveState): Promise<void> {\n await track(live);\n idle = live.run === undefined;\n stopWhenIdle();\n }\n watch.start(async (call) => {\n if (call.kind !== \"value\") return;\n busy = observe(call.value);\n await busy;\n });\n return {\n closed: watch.closed.then(() => busy),\n stop: () => void watch.stop(),\n close: () => {\n closing = true;\n stopWhenIdle();\n },\n keep: () => {\n closing = false;\n },\n };\n}\n\nfunction generating(graph: TaskGraph): Set<ConversationId> {\n return new Set(\n Object.values(graph.tasks)\n .filter((node) => node.kind === GenerationTask.definition.name)\n .map((node) => node.conversationId),\n );\n}\n\nexport type EventsWatch = { stop(): Promise<void> };\n\nexport async function watchEvents(\n harness: Harness,\n adapterFor: AdapterLookup,\n report: Reporter,\n): Promise<EventsWatch> {\n let stopped = false;\n const followers = new Map<ConversationId, Promise<Follower | undefined>>();\n const graph = await harness.watchTaskGraph(context);\n\n function start(id: ConversationId): void {\n const follower = follow(harness, id, adapterFor, report);\n followers.set(id, follower);\n void follower.then(async (found) => {\n if (found === undefined) return followers.delete(id);\n await found.closed;\n followers.delete(id);\n if (!stopped && generating(graph.value).has(id)) start(id);\n });\n }\n\n function update(active: Set<ConversationId>): void {\n for (const id of active) {\n const existing = followers.get(id);\n if (existing === undefined) start(id);\n else void existing.then((follower) => follower?.keep());\n }\n for (const [id, follower] of followers)\n if (!active.has(id)) void follower.then((found) => found?.close());\n }\n\n graph.start(async (call) => {\n if (call.kind === \"value\" && !stopped) update(generating(call.value));\n });\n\n async function stopFollower(follower: Promise<Follower | undefined>) {\n const found = await follower;\n found?.stop();\n await found?.closed;\n }\n\n return {\n stop: async () => {\n stopped = true;\n await graph.stop();\n await Promise.all([...followers.values()].map(stopFollower));\n },\n };\n}\n","import { copyJson, type JsonValue } from \"@earendil-works/chord/json\";\nimport type { ConversationId, Tx } from \"@earendil-works/pi-durable\";\nimport { defineTask } from \"@earendil-works/pi-durable\";\nimport { ChannelsDoc, findBinding, setBinding } from \"./doc\";\nimport type { Reporter } from \"./report\";\nimport type {\n ChannelAdapter,\n OutboundPart,\n SendResult,\n SendRetry,\n} from \"./types\";\n\nexport type SendInput = {\n channel: string;\n address: string;\n parts: OutboundPart[];\n idempotencyKey: string;\n addressData?: JsonValue;\n replyContext?: JsonValue;\n};\n\ntype SendState = { phase: \"send\"; attempt: number };\n\ntype Attempt = { result: SendResult | undefined } | { error: Error };\n\nexport type AdapterLookup = (channel: string) => ChannelAdapter | undefined;\n\nexport const SEND_TASK = \"channels.send\";\n\nasync function attemptSend(\n adapterFor: AdapterLookup,\n input: SendInput,\n addressData: JsonValue | undefined,\n signal: AbortSignal,\n): Promise<Attempt> {\n try {\n const adapter = adapterFor(input.channel);\n if (adapter === undefined) throw new Error(`No channel ${input.channel}`);\n const { address, parts, replyContext, idempotencyKey } = input;\n const result = await adapter.send(\n { address, parts },\n { addressData, replyContext, idempotencyKey, signal },\n );\n return { result: result || undefined };\n } catch (error) {\n return {\n error: error instanceof Error ? error : new Error(String(error)),\n };\n }\n}\n\nasync function recordResult(\n tx: Tx,\n conversationId: ConversationId,\n input: SendInput,\n result: SendResult | undefined,\n): Promise<void> {\n if (result === undefined) return;\n const state = await tx.doc(ChannelsDoc);\n const current = findBinding(state, input);\n if (current?.conversationId !== conversationId) return;\n const addressData = result.addressData ?? current.addressData;\n const binding = () => ({\n conversationId,\n ...(addressData === undefined\n ? {}\n : { addressData: copyJson(addressData) }),\n });\n setBinding(state, input, binding());\n if (result.alias === undefined) return;\n const alias = { channel: input.channel, address: result.alias };\n if (findBinding(state, alias) === undefined)\n setBinding(state, alias, binding());\n}\n\nexport function defineSendTask(\n adapterFor: AdapterLookup,\n retry: SendRetry,\n report: Reporter,\n) {\n return defineTask<SendInput, SendState, null>({\n name: SEND_TASK,\n version: 1,\n initial: () => ({ phase: \"send\", attempt: 1 }),\n phases: {\n send: async (task, runtime, context) => {\n const { attempt } = task.state.checkpoint;\n const state = await runtime.snapshot(ChannelsDoc, context);\n const binding = findBinding(state, task.input);\n const addressData =\n binding?.conversationId === runtime.conversationId\n ? binding.addressData\n : task.input.addressData;\n const outcome = await attemptSend(\n adapterFor,\n task.input,\n addressData,\n runtime.signal,\n );\n if (\"result\" in outcome) {\n await runtime.commit(async (tx) => {\n await recordResult(\n tx,\n runtime.conversationId,\n task.input,\n outcome.result,\n );\n return {\n status: \"terminal\",\n outcome: { status: \"completed\", result: null },\n };\n }, context);\n return;\n }\n const { channel, address } = task.input;\n const { error } = outcome;\n if (attempt < retry.attempts) {\n report({ kind: \"send_retry\", channel, address, attempt, error });\n const until = runtime.now() + retry.baseDelayMs * 2 ** (attempt - 1);\n await runtime.sleepUntil(\n until,\n { phase: \"send\", attempt: attempt + 1 },\n context,\n );\n return;\n }\n report({ kind: \"send_failed\", channel, address, error });\n const failure = { message: error.message };\n await runtime.commit(\n () => ({\n status: \"terminal\",\n outcome: { status: \"failed\", error: failure },\n }),\n context,\n );\n },\n },\n abort: (_task, runtime, context) =>\n runtime.commit(\n () => ({ status: \"terminal\", outcome: { status: \"aborted\" } }),\n context,\n ),\n });\n}\n\nexport type SendTask = ReturnType<typeof defineSendTask>;\n","import { BACKGROUND_CONTEXT } from \"@earendil-works/chord/context\";\nimport type {\n ConversationId,\n EntryId,\n Harness,\n SubmissionId,\n TaskRecord,\n} from \"@earendil-works/pi-durable\";\nimport { replyKey } from \"./hook\";\nimport { SEND_TASK } from \"./send\";\nimport type { DeliveryStatus } from \"./types\";\n\nconst context = BACKGROUND_CONTEXT;\n\ntype SendRecord = TaskRecord<{ idempotencyKey: string }, unknown, unknown>;\n\nfunction sendOutcome(task: SendRecord): DeliveryStatus {\n if (task.state.status !== \"terminal\") return { state: \"sending\" };\n const outcome = task.state.outcome;\n switch (outcome.status) {\n case \"completed\":\n return { state: \"done\" };\n case \"failed\":\n case \"faulted\":\n return { state: \"failed\", error: outcome.error.message };\n default:\n return { state: \"aborted\" };\n }\n}\n\nasync function findSend(\n harness: Harness,\n conversationId: ConversationId,\n key: string,\n): Promise<SendRecord | undefined> {\n return harness.commit(async (tx) => {\n let cursor: Parameters<typeof tx.scanTasks>[2];\n do {\n const query = {\n conversationId,\n kind: SEND_TASK,\n order: \"descending\",\n } as const;\n const page = await tx.scanTasks(query, 100, cursor);\n const found = (page.items as SendRecord[]).find(\n (task) => task.input.idempotencyKey === key,\n );\n if (found !== undefined) return found;\n cursor = page.next;\n } while (cursor !== undefined);\n return undefined;\n }, context);\n}\n\nasync function replyStatus(\n harness: Harness,\n conversationId: ConversationId,\n entry: EntryId,\n): Promise<DeliveryStatus> {\n const task = await findSend(harness, conversationId, replyKey(entry));\n if (task === undefined) return { state: \"sending\" };\n const inspection = await harness.inspect(context);\n const live = inspection.tasks.find((item) => item.record.id === task.id);\n if (live?.state.kind === \"blocked\")\n return { state: \"blocked\", reason: live.state.reason };\n return sendOutcome(task);\n}\n\nexport async function deliveryStatus(\n harness: Harness,\n deliveryId: SubmissionId,\n): Promise<DeliveryStatus | undefined> {\n const found = await harness.submission(deliveryId, context);\n if (found === undefined) return undefined;\n const record = await found.status(context);\n if (record.status === \"queued\") return { state: \"queued\" };\n if (record.status === \"placed\") return { state: \"running\" };\n if (record.status === \"unanswered\") {\n return record.reason === \"aborted\"\n ? { state: \"aborted\" }\n : { state: \"failed\", error: record.reason };\n }\n if (record.type === \"write\" || record.entry === undefined)\n return { state: \"done\" };\n return replyStatus(harness, record.conversationId, record.entry);\n}\n","import type { JsonValue } from \"@earendil-works/chord/json\";\nimport type { SubmissionDraft, UserInput } from \"@earendil-works/pi-durable\";\nimport { ChannelMessage, type ChannelMessageData, ChannelNote } from \"./doc\";\nimport type { AddressKey, DeliverOptions, InboundMessage } from \"./types\";\n\nconst WHEN_BUSY = { queue: \"followUp\", steer: \"steer\" } as const;\n\nexport function messageData(\n key: AddressKey,\n message: InboundMessage,\n addressData: JsonValue | undefined,\n): ChannelMessageData {\n return {\n author: message.author,\n ...key,\n ...(addressData === undefined ? {} : { addressData }),\n ...(message.replyContext === undefined\n ? {}\n : { replyContext: message.replyContext }),\n };\n}\n\nexport function submission(\n requestId: string,\n content: UserInput,\n data: ChannelMessageData,\n options: Required<DeliverOptions>,\n): SubmissionDraft {\n if (options.run) {\n return {\n type: \"input\",\n content,\n requestId,\n whenBusy: WHEN_BUSY[options.whenBusy],\n entry: { kind: ChannelMessage.kind, data },\n };\n }\n const model = [{ role: \"user\" as const, content, timestamp: Date.now() }];\n return {\n type: \"write\",\n requestId,\n entry: { kind: ChannelNote.kind, data, model },\n };\n}\n","import { BACKGROUND_CONTEXT } from \"@earendil-works/chord/context\";\nimport { copyJson } from \"@earendil-works/chord/json\";\nimport {\n type Conversation,\n type ConversationId,\n configure,\n type Harness,\n type SubmissionId,\n} from \"@earendil-works/pi-durable\";\nimport { type EnvBuilder, messageContent } from \"./attachments\";\nimport { type BindTarget, bindAddress } from \"./bind\";\nimport {\n ChannelsDoc,\n conversationAddresses,\n deleteConversation,\n findBinding,\n setBinding,\n} from \"./doc\";\nimport { type EventsWatch, watchEvents } from \"./events\";\nimport type { Reporter } from \"./report\";\nimport type { AdapterLookup } from \"./send\";\nimport { deliveryStatus } from \"./status\";\nimport { messageData, submission } from \"./submission\";\nimport type {\n AddressKey,\n ChannelRegistration,\n ChannelsOptions,\n DeliverOptions,\n DeliveryReceipt,\n DeliveryStatus,\n InboundMessage,\n} from \"./types\";\n\nconst context = BACKGROUND_CONTEXT;\n\nexport type ChannelsHub = {\n start(): Promise<void>;\n stop(): Promise<void>;\n deliver(\n channel: string,\n message: InboundMessage,\n options?: DeliverOptions,\n ): Promise<DeliveryReceipt | undefined>;\n bind(target: BindTarget, conversationId: ConversationId): Promise<void>;\n addresses(conversationId: ConversationId): Promise<AddressKey[]>;\n conversationOf(key: AddressKey): Promise<ConversationId | undefined>;\n status(deliveryId: SubmissionId): Promise<DeliveryStatus | undefined>;\n cancel(key: AddressKey): Promise<void>;\n clear(key: AddressKey): Promise<void>;\n compact(key: AddressKey): Promise<void>;\n end(key: AddressKey): Promise<void>;\n};\n\nexport type HubSetup = {\n options: ChannelsOptions;\n registration(channel: string): ChannelRegistration;\n adapterFor: AdapterLookup;\n report: Reporter;\n env: EnvBuilder | undefined;\n};\n\nexport type HubOptions = { env?: EnvBuilder };\n\nconst cancel = (conversation: Conversation) =>\n conversation.abort(context, { background: true });\n\nexport function createHub(harness: Harness, setup: HubSetup): ChannelsHub {\n const tails = new Map<string, Promise<unknown>>();\n const controller = new AbortController();\n const adapters = Object.values(setup.options.channels).map(\n ({ adapter }) => adapter,\n );\n let starting: Promise<void> | undefined;\n let watcher: EventsWatch | undefined;\n let stopping: Promise<void> | undefined;\n\n function serial<T>(key: AddressKey, run: () => Promise<T>): Promise<T> {\n if (stopping !== undefined)\n return Promise.reject(new Error(\"Channels hub is stopped\"));\n const id = JSON.stringify([key.channel, key.address]);\n const result = (tails.get(id) ?? Promise.resolve()).then(run);\n const tail = result.catch(() => undefined);\n tails.set(id, tail);\n void tail.then(() => tails.get(id) === tail && tails.delete(id));\n return result;\n }\n\n async function conversationFor(\n key: AddressKey,\n message: InboundMessage,\n create: boolean,\n ): Promise<ConversationId | undefined> {\n const factory = create\n ? setup.registration(key.channel).conversation\n : undefined;\n return harness.commit(async (tx) => {\n const state = await tx.doc(ChannelsDoc);\n const existing = findBinding(state, key);\n if (existing !== undefined) return existing.conversationId;\n const created = factory?.(message, { channel: key.channel });\n if (created === undefined) return undefined;\n const record = await tx.createConversation({\n ownership: { kind: \"ownerless\" },\n });\n await configure(tx, record.id, created.agent ?? {});\n await created.init?.(tx, record.id);\n await bindAddress(tx, key, record.id);\n return record.id;\n }, context);\n }\n\n async function admit(\n key: AddressKey,\n message: InboundMessage,\n options: Required<DeliverOptions>,\n ): Promise<DeliveryReceipt | undefined> {\n const create = options.run && options.create;\n const conversationId = await conversationFor(key, message, create);\n if (conversationId === undefined) {\n setup.report({ kind: \"ignored\", ...key });\n return undefined;\n }\n const conversation = await harness.conversation(conversationId, context);\n if (conversation === undefined)\n throw new Error(`Conversation ${conversationId} not found`);\n const content = await messageContent(\n message,\n {\n adapter: setup.registration(key.channel).adapter,\n env: setup.env,\n read: harness,\n conversationId,\n },\n context,\n );\n const admitted = await harness.commit(async (tx) => {\n const known = await tx.submissionByRequest(\n conversationId,\n message.requestId,\n );\n if (known !== undefined)\n return { submissionId: known.id, duplicate: true };\n const state = await tx.doc(ChannelsDoc);\n const stored = findBinding(state, key)?.addressData;\n if (message.addressData !== undefined) {\n setBinding(state, key, {\n conversationId,\n addressData: message.addressData,\n });\n }\n const addressData =\n message.addressData ??\n (stored === undefined ? undefined : copyJson(stored));\n const data = messageData(key, message, addressData);\n const draft = submission(message.requestId, content, data, options);\n const submissionId = await conversation.submit(tx, draft);\n return { submissionId, duplicate: false };\n }, context);\n setup.report({ kind: \"admitted\", ...key, conversationId, ...admitted });\n return { submissionId: admitted.submissionId, conversationId };\n }\n\n const deliver: ChannelsHub[\"deliver\"] = async (channel, message, options) => {\n setup.registration(channel);\n const key = { channel, address: message.address };\n const resolved = {\n whenBusy: options?.whenBusy ?? setup.options.whenBusy ?? \"queue\",\n run: options?.run ?? true,\n create: options?.create ?? true,\n };\n return serial(key, () => admit(key, message, resolved));\n };\n\n function start(): Promise<void> {\n if (starting !== undefined || stopping !== undefined)\n return Promise.reject(new Error(\"Channels hub can only start once\"));\n starting = startAll();\n return starting;\n }\n\n async function startAll(): Promise<void> {\n const channels = Object.entries(setup.options.channels);\n if (adapters.some((adapter) => adapter.events !== undefined))\n watcher = await watchEvents(harness, setup.adapterFor, setup.report);\n const { signal } = controller;\n await Promise.all(\n channels.map(([channel, { adapter }]) =>\n adapter.start?.({\n deliver: (message, options) => deliver(channel, message, options),\n cancel: (address) => cancelAt({ channel, address }),\n report: (report) => setup.report({ ...report, channel }),\n signal,\n }),\n ),\n );\n }\n\n async function drain(): Promise<void> {\n await starting?.catch(() => undefined);\n await Promise.all(tails.values());\n await watcher?.stop();\n controller.abort();\n if (starting === undefined) return;\n await Promise.all(adapters.map((adapter) => adapter.stop?.()));\n }\n\n function stop(): Promise<void> {\n stopping ??= drain();\n return stopping;\n }\n\n async function bind(target: BindTarget, conversationId: ConversationId) {\n setup.registration(target.channel);\n return serial(target, () =>\n harness.commit((tx) => bindAddress(tx, target, conversationId), context),\n );\n }\n\n function atAddress(\n key: AddressKey,\n run: (conversation: Conversation) => Promise<void>,\n ): Promise<void> {\n return serial(key, async () => {\n const state = await harness.snapshot(ChannelsDoc, context);\n const binding = findBinding(state, key);\n if (binding === undefined) return;\n const conversation = await harness.conversation(\n binding.conversationId,\n context,\n );\n if (conversation !== undefined) await run(conversation);\n });\n }\n\n const cancelAt = (key: AddressKey) => atAddress(key, cancel);\n\n async function addresses(conversationId: ConversationId) {\n const state = await harness.snapshot(ChannelsDoc, context);\n return conversationAddresses(state, conversationId);\n }\n\n async function conversationOf(key: AddressKey) {\n const state = await harness.snapshot(ChannelsDoc, context);\n return findBinding(state, key)?.conversationId;\n }\n\n return {\n start,\n stop,\n deliver,\n bind,\n addresses,\n conversationOf,\n status: (deliveryId) => deliveryStatus(harness, deliveryId),\n cancel: cancelAt,\n clear: (key) =>\n atAddress(key, async (conversation) => {\n await cancel(conversation);\n await conversation.reset(undefined, context);\n }),\n compact: (key) =>\n atAddress(key, async (conversation) => {\n await conversation.compact(undefined, context);\n }),\n end: (key) =>\n atAddress(key, async (conversation) => {\n await cancel(conversation);\n await harness.commit(async (tx) => {\n const state = await tx.doc(ChannelsDoc);\n deleteConversation(state, conversation.id);\n }, context);\n }),\n };\n}\n","import type { ChannelReport, ChannelsOptions } from \"./types\";\n\nexport type Reporter = (report: ChannelReport) => void;\n\nexport function reporter(onReport: ChannelsOptions[\"onReport\"]): Reporter {\n return (report) => {\n try {\n onReport?.(report);\n } catch {\n return;\n }\n };\n}\n","import type { JsonValue } from \"@earendil-works/chord/json\";\nimport type { Tx } from \"@earendil-works/pi-durable\";\nimport {\n type ConversationId,\n defineExtension,\n type Extension,\n GenerationTask,\n type Harness,\n hook,\n} from \"@earendil-works/pi-durable\";\nimport { type BindTarget, bindAddress, EXTENSION } from \"./bind\";\nimport { replyHook } from \"./hook\";\nimport { type ChannelsHub, createHub, type HubOptions } from \"./hub\";\nimport { reporter } from \"./report\";\nimport { defineSendTask } from \"./send\";\nimport { defineChannelTools } from \"./tools\";\nimport type { ChannelRegistration, ChannelsOptions } from \"./types\";\n\nconst DEFAULT_RETRY = { attempts: 5, baseDelayMs: 1000 };\n\nexport type ChannelSend = {\n channel: string;\n address: string;\n text: string;\n idempotencyKey: string;\n addressData?: JsonValue;\n};\n\nexport type Send = (\n tx: Tx,\n conversationId: ConversationId,\n input: ChannelSend,\n) => Promise<void>;\n\nexport type Channels = {\n extension: Extension;\n tools: Extension;\n bind(\n tx: Tx,\n target: BindTarget,\n conversationId: ConversationId,\n ): Promise<void>;\n send: Send;\n hub(harness: Harness, options?: HubOptions): ChannelsHub;\n};\n\nexport function createChannels(options: ChannelsOptions): Channels {\n const registration = (channel: string): ChannelRegistration => {\n if (!Object.hasOwn(options.channels, channel))\n throw new Error(`No channel ${channel}`);\n return options.channels[channel];\n };\n const adapterFor = (channel: string) =>\n Object.hasOwn(options.channels, channel)\n ? options.channels[channel].adapter\n : undefined;\n const report = reporter(options.onReport);\n const Send = defineSendTask(\n adapterFor,\n options.retry ?? DEFAULT_RETRY,\n report,\n );\n const send: Send = async (tx, conversationId, input) => {\n registration(input.channel);\n await tx.createTask(\n Send,\n {\n channel: input.channel,\n address: input.address,\n parts: [{ type: \"text\", text: input.text }],\n idempotencyKey: input.idempotencyKey,\n ...(input.addressData === undefined\n ? {}\n : { addressData: input.addressData }),\n },\n {\n ownership: { kind: \"conversation\" },\n conversationId,\n background: true,\n },\n );\n };\n\n return {\n extension: defineExtension({\n name: EXTENSION,\n tasks: [Send],\n hooks: [hook(GenerationTask, { afterRun: replyHook(Send) })],\n }),\n tools: defineChannelTools(send),\n bind: async (tx, target, conversationId) => {\n registration(target.channel);\n await bindAddress(tx, target, conversationId);\n },\n send,\n hub: (harness, hubOptions) =>\n createHub(harness, {\n options,\n registration,\n adapterFor,\n report,\n env: hubOptions?.env,\n }),\n };\n}\n"],"mappings":";;;;;;;AAkBA,MAAa,cAAc,UAAyB;CAClD,MAAM;CACN,SAAS;CACT,OAAO;CACP,gBAAgB,EAAE,UAAU,CAAC,EAAE;CAC/B,iBAAiB,QAAQ,MAAM,SAAS,KAAK,mBAAmB;AAClE,CAAC;AAQD,MAAa,iBACX,YAAgC,iBAAiB;AAEnD,MAAa,cAAc,YAAgC,cAAc;AAEzE,SAAS,IACP,QACA,KACe;CACf,IAAI,WAAW,KAAA,KAAa,CAAC,OAAO,OAAO,QAAQ,GAAG,GAAG,OAAO,KAAA;CAChE,OAAO,OAAO;AAChB;AAEA,SAAgB,YACd,OACA,KACqB;CACrB,OAAO,IAAI,IAAI,OAAO,UAAU,IAA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cAAc;EAC9C;EACA;EACA,MAAM,SAAS,eACb,UAAU,SAAS;GACjB;GACA;GACA;GACA;GACA,KAAK,YAAY;EACnB,CAAC;CACL;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aliou/pi-durable-channels",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Durable inbound and outbound messaging channels for pi-durable hosts",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -28,10 +28,10 @@
|
|
|
28
28
|
"node": ">=24.0.0"
|
|
29
29
|
},
|
|
30
30
|
"dependencies": {
|
|
31
|
-
"@earendil-works/chord": "1.
|
|
32
|
-
"@earendil-works/pi-ai": "1.
|
|
33
|
-
"@earendil-works/pi-durable": "1.
|
|
34
|
-
"@earendil-works/pi-schema": "1.
|
|
31
|
+
"@earendil-works/chord": "1.6.0",
|
|
32
|
+
"@earendil-works/pi-ai": "1.6.0",
|
|
33
|
+
"@earendil-works/pi-durable": "1.6.0",
|
|
34
|
+
"@earendil-works/pi-schema": "1.6.0"
|
|
35
35
|
},
|
|
36
36
|
"devDependencies": {
|
|
37
37
|
"vitest": "^5.1.0"
|