@aliou/pi-durable-channels 0.3.0 → 0.4.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 +10 -0
- package/README.md +16 -5
- package/dist/index.d.mts +31 -12
- package/dist/index.mjs +144 -28
- package/dist/index.mjs.map +1 -1
- package/package.json +5 -5
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
# @aliou/pi-durable-channels
|
|
2
2
|
|
|
3
|
+
## 0.4.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 05b4e8f: Route aliases into shared conversations, persist admission cursors, coalesce replies and run events per address, and add authorized bounded source-history reads.
|
|
8
|
+
|
|
9
|
+
### Patch Changes
|
|
10
|
+
|
|
11
|
+
- bb20f1b: Update Earendil Pi libraries to 1.7.0 and migrate transactional admission to `conversation.admit`.
|
|
12
|
+
|
|
3
13
|
## 0.3.0
|
|
4
14
|
|
|
5
15
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -82,11 +82,15 @@ Start the hub after opening the Harness. On shutdown, stop the hub before closin
|
|
|
82
82
|
|
|
83
83
|
- `whenBusy: "queue"` is the default: a message gets its own run after the current one. `"steer"` joins the current run. Set a default on `createChannels` or override per delivery.
|
|
84
84
|
- `run: false` stores a message as context without starting a run or creating a conversation.
|
|
85
|
-
- `create: false` permits a run only for an already-bound address.
|
|
85
|
+
- `create: false` permits a run only for an already-bound address or an alias whose `conversationAddress` is bound.
|
|
86
|
+
- `conversationAddress` provides a same-channel fallback route when `address` is unbound. The exact binding always wins. An alias records its conversation address in `via` but keeps its own address data and reply destination. Creating through an alias binds both addresses; it never copies alias data or cursors to the canonical address.
|
|
87
|
+
- `cursor` stores an opaque per-address admission cursor. Successful, non-duplicate admission commits it with the submission. A duplicate, failed admission, or delivery without a cursor leaves the stored value unchanged. The core does not interpret cursors.
|
|
86
88
|
- A repeated `requestId` within the same conversation returns the original receipt without starting another run. IDs must distinguish messages from all addresses sharing that conversation.
|
|
87
89
|
- `deliver` resolves after admission, not after the reply. Attachments are fetched before admission and can delay acknowledgement.
|
|
88
90
|
|
|
89
|
-
An address identifies a destination within a channel, such as a Slack thread. Several addresses can bind to the same conversation, but an address belongs to only one conversation at a time. Bind from host code with `hub.bind(target, conversationId)`, or from a tool's commit with `channels.bind(tx, target, api.conversationId)`. Binding an address owned by another conversation throws.
|
|
91
|
+
An address identifies a destination within a channel, such as a Slack thread. Several addresses can bind to the same conversation, but an address belongs to only one conversation at a time. Bind from host code with `hub.bind(target, conversationId)`, or from a tool's commit with `channels.bind(tx, target, api.conversationId)`. Binding an address owned by another conversation throws. Explicit binds and send-result updates preserve alias metadata and admission cursors.
|
|
92
|
+
|
|
93
|
+
A run coalesces final replies by channel and address: only the newest input at each address carries the final answer. Earlier inputs complete with empty sends and retain their own `reply:<entry>` idempotency keys. Distinct addresses sharing a conversation each receive one answer.
|
|
90
94
|
|
|
91
95
|
## Adapter contract
|
|
92
96
|
|
|
@@ -101,12 +105,15 @@ Implement the exported `ChannelAdapter` type:
|
|
|
101
105
|
| `send(message, ctx)` | Required. Post the outbound parts; throwing retries the send |
|
|
102
106
|
| `events(target, event)` | Optional best-effort run presentation |
|
|
103
107
|
| `fetchFile(url)` | Optional authenticated attachment download |
|
|
108
|
+
| `history(request, ctx)` | Optional bounded, formatted source-history read around opaque cursors |
|
|
104
109
|
|
|
105
|
-
The start context's `signal` aborts during hub shutdown. The send context has its own task signal; wire it into outbound I/O. `cancel(address)` stops the run, sends, and notifications for the bound conversation.
|
|
110
|
+
The start context's `binding(address)` reads the calling channel's binding, including `via` and `cursor`. Its `signal` aborts during hub shutdown. The send context has its own task signal; wire it into outbound I/O. `cancel(address)` stops the run, sends, and notifications for the bound conversation.
|
|
106
111
|
|
|
107
112
|
`send` receives `addressData`, `replyContext`, and a stable `idempotencyKey`. It can return `{ addressData?, alias? }`: the data updates the binding, and an unbound alias is attached to the same conversation. Use this when an initial platform post creates the actual thread.
|
|
108
113
|
|
|
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
|
|
114
|
+
Address data persists until replaced. Reply context belongs to one message, and is also passed to its run events. Adapters can use it to select a per-message reply thread when several source addresses share a conversation. A reply with no parts means `no_reply` or an earlier input coalesced into a newer answer at the same address; post nothing and clear the adapter's presentation state.
|
|
115
|
+
|
|
116
|
+
Implement `history` when the source supports authorized reads around opaque `after` or `before` cursors and the model may need records omitted from admitted input. The request includes the target address and a 32 KiB `maxBytes` bound. Return formatted `content`, an optional continuation `cursor`, and whether the source truncated the result. Use the provided signal for cancellation, enforce target-level authorization and network origin and timeout rules, and keep output bounded. History reads are read-only: never admit messages or advance the binding's admission cursor.
|
|
110
117
|
|
|
111
118
|
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
119
|
|
|
@@ -147,6 +154,8 @@ The default retry policy is five attempts with a one-second initial delay and ex
|
|
|
147
154
|
|
|
148
155
|
Adapters receive `run_started`, narration `text`, `tool_started`, `tool_finished`, and `run_ended` with `completed`, `failed`, or `aborted`. Events follow committed state; the final answer arrives through `send`, not a run event. A lone `no_reply` call and its accompanying text produce no activity events.
|
|
149
156
|
|
|
157
|
+
Run events use the same newest-input-per-address selection as final replies. When steering adds a newer input, later events go only to that recipient.
|
|
158
|
+
|
|
150
159
|
Events can be lost while the host is down and can repeat after restart. Activity events have an `id`; use it for deduplication. `run_started` and `run_ended` have no event ID: use the event type and `target.idempotencyKey`. That target key matches the corresponding reply's send key. Anything requiring durable delivery belongs in `send`.
|
|
151
160
|
|
|
152
161
|
## Attachments
|
|
@@ -175,7 +184,9 @@ After `end`, another message creates a conversation only if the channel's factor
|
|
|
175
184
|
|
|
176
185
|
## Model tools
|
|
177
186
|
|
|
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.
|
|
187
|
+
`channels.tools` adds `send_message({ channel, address, text })`, `list_addresses()`, `no_reply()`, and an address prompt section. When at least one adapter supports history, it also adds `read_history({ channel, address, after?, before? })`. Sending and listing are restricted to addresses bound to the calling conversation, including aliases. The prompt lists only canonical addresses, without `via` metadata. `send_message` queues a background notification; the final answer already goes to the inbound address.
|
|
188
|
+
|
|
189
|
+
`read_history` returns formatted content, an optional continuation cursor, and a truncation flag. It rejects unsupported channels and addresses outside the calling conversation, enforces the 32 KiB output bound without splitting UTF-8 text, and performs no durable writes or admission-cursor changes. Adapters control source-specific authorization and formatting; adapter failures return tool errors.
|
|
179
190
|
|
|
180
191
|
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
192
|
|
package/dist/index.d.mts
CHANGED
|
@@ -3,6 +3,19 @@ import { JsonValue } from "@earendil-works/chord/json";
|
|
|
3
3
|
import "@earendil-works/chord/context";
|
|
4
4
|
import { JsonObject } from "@earendil-works/pi-ai";
|
|
5
5
|
import "@earendil-works/chord/delta";
|
|
6
|
+
type Binding = {
|
|
7
|
+
conversationId: ConversationId;
|
|
8
|
+
addressData?: JsonValue;
|
|
9
|
+
via?: string;
|
|
10
|
+
cursor?: string;
|
|
11
|
+
};
|
|
12
|
+
type Bindings = Record<string, Record<string, Binding>>;
|
|
13
|
+
type ChannelsState = {
|
|
14
|
+
bindings: Bindings;
|
|
15
|
+
};
|
|
16
|
+
export declare const ChannelsDoc: import("@earendil-works/pi-durable").SessionDocToken<ChannelsState>;
|
|
17
|
+
export declare function findBinding(state: Readonly<ChannelsState> | undefined, key: AddressKey): Binding | undefined;
|
|
18
|
+
export declare function conversationAddresses(state: Readonly<ChannelsState> | undefined, conversationId: ConversationId): AddressKey[];
|
|
6
19
|
type BusyPolicy = "queue" | "steer";
|
|
7
20
|
type InboundFile = {
|
|
8
21
|
name: string;
|
|
@@ -11,6 +24,8 @@ type InboundFile = {
|
|
|
11
24
|
};
|
|
12
25
|
type InboundMessage = {
|
|
13
26
|
address: string;
|
|
27
|
+
conversationAddress?: string;
|
|
28
|
+
cursor?: string;
|
|
14
29
|
text: string;
|
|
15
30
|
requestId: string;
|
|
16
31
|
author: string;
|
|
@@ -111,9 +126,21 @@ type ChannelReport = {
|
|
|
111
126
|
type AdapterStart = {
|
|
112
127
|
deliver: Deliver;
|
|
113
128
|
cancel(address: string): Promise<void>;
|
|
129
|
+
binding(address: string): Promise<Binding | undefined>;
|
|
114
130
|
report(report: AdapterReport): void;
|
|
115
131
|
signal: AbortSignal;
|
|
116
132
|
};
|
|
133
|
+
type ChannelHistoryRequest = {
|
|
134
|
+
address: string;
|
|
135
|
+
after?: string;
|
|
136
|
+
before?: string;
|
|
137
|
+
maxBytes: number;
|
|
138
|
+
};
|
|
139
|
+
type ChannelHistoryResult = {
|
|
140
|
+
content: string;
|
|
141
|
+
cursor?: string;
|
|
142
|
+
truncated: boolean;
|
|
143
|
+
};
|
|
117
144
|
type ChannelAdapter = {
|
|
118
145
|
start?(ctx: AdapterStart): void | Promise<void>;
|
|
119
146
|
stop?(): Promise<void>;
|
|
@@ -121,6 +148,9 @@ type ChannelAdapter = {
|
|
|
121
148
|
formats?: readonly string[];
|
|
122
149
|
send(message: OutboundMessage, ctx: SendContext): Promise<SendResult | undefined | void>;
|
|
123
150
|
events?(target: ReplyTarget, event: ChannelEvent): void | Promise<void>;
|
|
151
|
+
history?(request: ChannelHistoryRequest, ctx: {
|
|
152
|
+
signal: AbortSignal;
|
|
153
|
+
}): Promise<ChannelHistoryResult>;
|
|
124
154
|
fetchFile?(url: string): Promise<Uint8Array>;
|
|
125
155
|
};
|
|
126
156
|
type AddressKey = {
|
|
@@ -192,16 +222,5 @@ type Channels = {
|
|
|
192
222
|
hub(harness: Harness, options?: HubOptions): ChannelsHub;
|
|
193
223
|
};
|
|
194
224
|
export declare function createChannels(options: ChannelsOptions): Channels;
|
|
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 };
|
|
225
|
+
export type { AdapterReport, AdapterStart, AddressKey, BindTarget, Binding, BusyPolicy, ChannelAdapter, ChannelEvent, ChannelHistoryRequest, ChannelHistoryResult, ChannelRegistration, ChannelReport, ChannelSend, Channels, ChannelsHub, ChannelsOptions, ChannelsState, ConversationSetup, Deliver, DeliverOptions, DeliveryReceipt, DeliveryStatus, HubOptions, InboundFile, InboundMessage, OutboundMessage, OutboundPart, ReplyTarget, Send, SendContext, SendResult, SendRetry };
|
|
207
226
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.mjs
CHANGED
|
@@ -3,7 +3,7 @@ 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";
|
|
6
|
-
import { obj, str } from "@earendil-works/pi-schema";
|
|
6
|
+
import { obj, opt, str } from "@earendil-works/pi-schema";
|
|
7
7
|
// src/doc.ts
|
|
8
8
|
const ChannelsDoc = defineDoc({
|
|
9
9
|
kind: "channels.bindings",
|
|
@@ -34,6 +34,12 @@ function conversationAddresses(state, conversationId) {
|
|
|
34
34
|
address
|
|
35
35
|
}));
|
|
36
36
|
}
|
|
37
|
+
function canonicalConversationAddresses(state, conversationId) {
|
|
38
|
+
return entriesOf(state).filter(({ binding }) => binding.conversationId === conversationId && binding.via === void 0).map(({ channel, address }) => ({
|
|
39
|
+
channel,
|
|
40
|
+
address
|
|
41
|
+
}));
|
|
42
|
+
}
|
|
37
43
|
function setBinding(state, key, binding) {
|
|
38
44
|
if (!Object.hasOwn(state.bindings, key.channel)) state.bindings[key.channel] = {};
|
|
39
45
|
state.bindings[key.channel][key.address] = binding;
|
|
@@ -56,7 +62,9 @@ async function bindAddress(tx, target, conversationId) {
|
|
|
56
62
|
const addressData = target.addressData ?? existing?.addressData;
|
|
57
63
|
setBinding(state, target, {
|
|
58
64
|
conversationId,
|
|
59
|
-
...addressData === void 0 ? {} : { addressData: copyJson(addressData) }
|
|
65
|
+
...addressData === void 0 ? {} : { addressData: copyJson(addressData) },
|
|
66
|
+
...existing?.via === void 0 ? {} : { via: existing.via },
|
|
67
|
+
...existing?.cursor === void 0 ? {} : { cursor: existing.cursor }
|
|
60
68
|
});
|
|
61
69
|
await selectChannels(tx, conversationId);
|
|
62
70
|
}
|
|
@@ -79,6 +87,15 @@ async function runEntries(source, range, context) {
|
|
|
79
87
|
} while (cursor !== void 0);
|
|
80
88
|
return entries;
|
|
81
89
|
}
|
|
90
|
+
function latestMessageIds(entries) {
|
|
91
|
+
const latest = /* @__PURE__ */ new Map();
|
|
92
|
+
for (const entry of entries) {
|
|
93
|
+
if (!ChannelMessage.is(entry)) continue;
|
|
94
|
+
const key = JSON.stringify([entry.data.channel, entry.data.address]);
|
|
95
|
+
latest.set(key, entry.id);
|
|
96
|
+
}
|
|
97
|
+
return new Set(latest.values());
|
|
98
|
+
}
|
|
82
99
|
function answerParts(entry) {
|
|
83
100
|
const text = (entry?.model ?? []).flatMap((message) => message.role === "assistant" ? message.content : []).flatMap((part) => part.type === "text" ? [part.text] : []).join("");
|
|
84
101
|
return text === "" ? [] : [{
|
|
@@ -92,9 +109,10 @@ function replyHook(Send) {
|
|
|
92
109
|
if (messages.length === 0) return void 0;
|
|
93
110
|
const answer = await api.entry(run.answer, context);
|
|
94
111
|
const parts = run.reason === "terminate" ? [] : answerParts(answer);
|
|
112
|
+
const latest = latestMessageIds(messages);
|
|
95
113
|
return { tasks: messages.map(({ id, data: { author: _author, ...target } }) => hookTask(Send, {
|
|
96
114
|
...target,
|
|
97
|
-
parts,
|
|
115
|
+
parts: latest.has(id) ? parts : [],
|
|
98
116
|
idempotencyKey: replyKey(id)
|
|
99
117
|
})) };
|
|
100
118
|
};
|
|
@@ -196,6 +214,7 @@ async function messageContent(message, source, context) {
|
|
|
196
214
|
// src/tools.ts
|
|
197
215
|
const TOOLS_EXTENSION = "channels-tools";
|
|
198
216
|
const NO_REPLY = "no_reply";
|
|
217
|
+
const HISTORY_BYTES = 32768;
|
|
199
218
|
function text(value, isError = false) {
|
|
200
219
|
return {
|
|
201
220
|
output: [{
|
|
@@ -205,7 +224,26 @@ function text(value, isError = false) {
|
|
|
205
224
|
isError
|
|
206
225
|
};
|
|
207
226
|
}
|
|
208
|
-
function
|
|
227
|
+
function boundedContent(content) {
|
|
228
|
+
const encoder = new TextEncoder();
|
|
229
|
+
let end = 0;
|
|
230
|
+
let size = 0;
|
|
231
|
+
let truncated = false;
|
|
232
|
+
for (const character of content) {
|
|
233
|
+
const length = encoder.encode(character).length;
|
|
234
|
+
if (size + length > HISTORY_BYTES) {
|
|
235
|
+
truncated = true;
|
|
236
|
+
break;
|
|
237
|
+
}
|
|
238
|
+
size += length;
|
|
239
|
+
end += character.length;
|
|
240
|
+
}
|
|
241
|
+
return {
|
|
242
|
+
content: truncated ? content.slice(0, end) : content,
|
|
243
|
+
truncated
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
function defineChannelTools(send, adapterFor, historyAvailable) {
|
|
209
247
|
const sendMessage = defineTool({
|
|
210
248
|
name: "send_message",
|
|
211
249
|
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.",
|
|
@@ -240,6 +278,41 @@ function defineChannelTools(send) {
|
|
|
240
278
|
return text(JSON.stringify(addresses));
|
|
241
279
|
}
|
|
242
280
|
});
|
|
281
|
+
const readHistory = defineTool({
|
|
282
|
+
name: "read_history",
|
|
283
|
+
description: "Read bounded source history for one of your channel addresses. Use after or before to continue from an opaque cursor returned by the channel.",
|
|
284
|
+
parameters: obj({
|
|
285
|
+
channel: str(),
|
|
286
|
+
address: str(),
|
|
287
|
+
after: opt(str()),
|
|
288
|
+
before: opt(str())
|
|
289
|
+
}),
|
|
290
|
+
replay: "safe",
|
|
291
|
+
execute: async ({ channel, address, after, before }, api, context) => {
|
|
292
|
+
if (findBinding(await api.snapshot(ChannelsDoc, context), {
|
|
293
|
+
channel,
|
|
294
|
+
address
|
|
295
|
+
})?.conversationId !== api.conversationId) return text(`Unknown address ${address} on channel ${channel}.`, true);
|
|
296
|
+
const adapter = adapterFor(channel);
|
|
297
|
+
if (adapter?.history === void 0) return text(`History is unavailable on channel ${channel}.`, true);
|
|
298
|
+
try {
|
|
299
|
+
const result = await adapter.history({
|
|
300
|
+
address,
|
|
301
|
+
...after === void 0 ? {} : { after },
|
|
302
|
+
...before === void 0 ? {} : { before },
|
|
303
|
+
maxBytes: HISTORY_BYTES
|
|
304
|
+
}, { signal: context.abortSignal ?? new AbortController().signal });
|
|
305
|
+
const bounded = boundedContent(result.content);
|
|
306
|
+
return text(JSON.stringify({
|
|
307
|
+
content: bounded.content,
|
|
308
|
+
...result.cursor === void 0 ? {} : { cursor: result.cursor },
|
|
309
|
+
truncated: result.truncated || bounded.truncated
|
|
310
|
+
}));
|
|
311
|
+
} catch (error) {
|
|
312
|
+
return text(`History read failed: ${error instanceof Error ? error.message : String(error)}`, true);
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
});
|
|
243
316
|
const noReply = defineTool({
|
|
244
317
|
name: NO_REPLY,
|
|
245
318
|
description: "End this run without answering. Use it when the latest message needs no answer from you, such as a thread message meant for someone else. Call it alone, without writing text.",
|
|
@@ -251,7 +324,7 @@ function defineChannelTools(send) {
|
|
|
251
324
|
})
|
|
252
325
|
});
|
|
253
326
|
const channelsSection = section("channels", async ({ read, conversationId }, context) => {
|
|
254
|
-
const lines =
|
|
327
|
+
const lines = canonicalConversationAddresses(await read.snapshot(ChannelsDoc, context), conversationId).map(({ channel, address }) => `- ${channel}: ${address}`);
|
|
255
328
|
return ["Your final answer goes to the address of the message you are answering. Use send_message only for your other addresses, or for an update before you finish. Your addresses:", ...lines.length === 0 ? ["(none yet)"] : lines].join("\n");
|
|
256
329
|
});
|
|
257
330
|
return defineExtension({
|
|
@@ -259,6 +332,7 @@ function defineChannelTools(send) {
|
|
|
259
332
|
tools: [
|
|
260
333
|
sendMessage,
|
|
261
334
|
listAddresses,
|
|
335
|
+
...historyAvailable ? [readHistory] : [],
|
|
262
336
|
noReply
|
|
263
337
|
],
|
|
264
338
|
sections: [channelsSection]
|
|
@@ -316,7 +390,10 @@ function outcomeOf(live, run) {
|
|
|
316
390
|
};
|
|
317
391
|
}
|
|
318
392
|
async function recipientsOf(conversation, first, adapterFor) {
|
|
319
|
-
|
|
393
|
+
const messages = (await runEntries(conversation, { first }, context$3)).filter(ChannelMessage.is);
|
|
394
|
+
const latest = latestMessageIds(messages);
|
|
395
|
+
return messages.flatMap(({ id, data }) => {
|
|
396
|
+
if (!latest.has(id)) return [];
|
|
320
397
|
const adapter = adapterFor(data.channel);
|
|
321
398
|
if (adapter?.events === void 0) return [];
|
|
322
399
|
const { channel, author: _author, ...target } = data;
|
|
@@ -472,7 +549,9 @@ async function recordResult(tx, conversationId, input, result) {
|
|
|
472
549
|
const addressData = result.addressData ?? current.addressData;
|
|
473
550
|
const binding = () => ({
|
|
474
551
|
conversationId,
|
|
475
|
-
...addressData === void 0 ? {} : { addressData: copyJson(addressData) }
|
|
552
|
+
...addressData === void 0 ? {} : { addressData: copyJson(addressData) },
|
|
553
|
+
...current.via === void 0 ? {} : { via: current.via },
|
|
554
|
+
...current.cursor === void 0 ? {} : { cursor: current.cursor }
|
|
476
555
|
});
|
|
477
556
|
setBinding(state, input, binding());
|
|
478
557
|
if (result.alias === void 0) return;
|
|
@@ -480,7 +559,10 @@ async function recordResult(tx, conversationId, input, result) {
|
|
|
480
559
|
channel: input.channel,
|
|
481
560
|
address: result.alias
|
|
482
561
|
};
|
|
483
|
-
if (findBinding(state, alias) === void 0) setBinding(state, alias,
|
|
562
|
+
if (findBinding(state, alias) === void 0) setBinding(state, alias, {
|
|
563
|
+
conversationId,
|
|
564
|
+
...addressData === void 0 ? {} : { addressData: copyJson(addressData) }
|
|
565
|
+
});
|
|
484
566
|
}
|
|
485
567
|
function defineSendTask(adapterFor, retry, report) {
|
|
486
568
|
return defineTask({
|
|
@@ -659,28 +741,37 @@ function createHub(harness, setup) {
|
|
|
659
741
|
return result;
|
|
660
742
|
}
|
|
661
743
|
async function conversationFor(key, message, create) {
|
|
744
|
+
const canonical = {
|
|
745
|
+
channel: key.channel,
|
|
746
|
+
address: message.conversationAddress ?? key.address
|
|
747
|
+
};
|
|
662
748
|
const factory = create ? setup.registration(key.channel).conversation : void 0;
|
|
663
749
|
return harness.commit(async (tx) => {
|
|
664
|
-
const
|
|
750
|
+
const state = await tx.doc(ChannelsDoc);
|
|
751
|
+
const existing = findBinding(state, key);
|
|
665
752
|
if (existing !== void 0) return existing.conversationId;
|
|
753
|
+
const bound = findBinding(state, canonical);
|
|
754
|
+
if (bound !== void 0) {
|
|
755
|
+
setBinding(state, key, {
|
|
756
|
+
conversationId: bound.conversationId,
|
|
757
|
+
via: canonical.address
|
|
758
|
+
});
|
|
759
|
+
return bound.conversationId;
|
|
760
|
+
}
|
|
666
761
|
const created = factory?.(message, { channel: key.channel });
|
|
667
762
|
if (created === void 0) return void 0;
|
|
668
763
|
const record = await tx.createConversation({ ownership: { kind: "ownerless" } });
|
|
669
764
|
await configure(tx, record.id, created.agent ?? {});
|
|
670
765
|
await created.init?.(tx, record.id);
|
|
671
|
-
await bindAddress(tx,
|
|
766
|
+
await bindAddress(tx, canonical, record.id);
|
|
767
|
+
if (key.address !== canonical.address) setBinding(state, key, {
|
|
768
|
+
conversationId: record.id,
|
|
769
|
+
via: canonical.address
|
|
770
|
+
});
|
|
672
771
|
return record.id;
|
|
673
772
|
}, context);
|
|
674
773
|
}
|
|
675
|
-
async function admit(key, message, options) {
|
|
676
|
-
const conversationId = await conversationFor(key, message, options.run && options.create);
|
|
677
|
-
if (conversationId === void 0) {
|
|
678
|
-
setup.report({
|
|
679
|
-
kind: "ignored",
|
|
680
|
-
...key
|
|
681
|
-
});
|
|
682
|
-
return;
|
|
683
|
-
}
|
|
774
|
+
async function admit(key, message, options, conversationId) {
|
|
684
775
|
const conversation = await harness.conversation(conversationId, context);
|
|
685
776
|
if (conversation === void 0) throw new Error(`Conversation ${conversationId} not found`);
|
|
686
777
|
const content = await messageContent(message, {
|
|
@@ -696,15 +787,22 @@ function createHub(harness, setup) {
|
|
|
696
787
|
duplicate: true
|
|
697
788
|
};
|
|
698
789
|
const state = await tx.doc(ChannelsDoc);
|
|
699
|
-
const stored = findBinding(state, key)
|
|
700
|
-
if (message.addressData !== void 0
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
790
|
+
const stored = findBinding(state, key);
|
|
791
|
+
if (message.addressData !== void 0 || message.cursor !== void 0) {
|
|
792
|
+
const addressData = message.addressData ?? stored?.addressData;
|
|
793
|
+
const cursor = message.cursor ?? stored?.cursor;
|
|
794
|
+
setBinding(state, key, {
|
|
795
|
+
conversationId,
|
|
796
|
+
...addressData === void 0 ? {} : { addressData },
|
|
797
|
+
...stored?.via === void 0 ? {} : { via: stored.via },
|
|
798
|
+
...cursor === void 0 ? {} : { cursor }
|
|
799
|
+
});
|
|
800
|
+
}
|
|
801
|
+
const storedData = stored?.addressData;
|
|
802
|
+
const data = messageData(key, message, message.addressData ?? (storedData === void 0 ? void 0 : copyJson(storedData)));
|
|
705
803
|
const draft = submission(message.requestId, content, data, options);
|
|
706
804
|
return {
|
|
707
|
-
submissionId: await conversation.
|
|
805
|
+
submissionId: await conversation.admit(tx, draft),
|
|
708
806
|
duplicate: false
|
|
709
807
|
};
|
|
710
808
|
}, context);
|
|
@@ -725,12 +823,24 @@ function createHub(harness, setup) {
|
|
|
725
823
|
channel,
|
|
726
824
|
address: message.address
|
|
727
825
|
};
|
|
826
|
+
const canonical = {
|
|
827
|
+
channel,
|
|
828
|
+
address: message.conversationAddress ?? message.address
|
|
829
|
+
};
|
|
728
830
|
const resolved = {
|
|
729
831
|
whenBusy: options?.whenBusy ?? setup.options.whenBusy ?? "queue",
|
|
730
832
|
run: options?.run ?? true,
|
|
731
833
|
create: options?.create ?? true
|
|
732
834
|
};
|
|
733
|
-
|
|
835
|
+
const conversationId = await serial(canonical, () => conversationFor(key, message, resolved.run && resolved.create));
|
|
836
|
+
if (conversationId === void 0) {
|
|
837
|
+
setup.report({
|
|
838
|
+
kind: "ignored",
|
|
839
|
+
...key
|
|
840
|
+
});
|
|
841
|
+
return;
|
|
842
|
+
}
|
|
843
|
+
return serial(key, () => admit(key, message, resolved, conversationId));
|
|
734
844
|
};
|
|
735
845
|
function start() {
|
|
736
846
|
if (starting !== void 0 || stopping !== void 0) return Promise.reject(/* @__PURE__ */ new Error("Channels hub can only start once"));
|
|
@@ -747,6 +857,12 @@ function createHub(harness, setup) {
|
|
|
747
857
|
channel,
|
|
748
858
|
address
|
|
749
859
|
}),
|
|
860
|
+
binding: async (address) => {
|
|
861
|
+
return findBinding(await harness.snapshot(ChannelsDoc, context), {
|
|
862
|
+
channel,
|
|
863
|
+
address
|
|
864
|
+
});
|
|
865
|
+
},
|
|
750
866
|
report: (report) => setup.report({
|
|
751
867
|
...report,
|
|
752
868
|
channel
|
|
@@ -855,7 +971,7 @@ function createChannels(options) {
|
|
|
855
971
|
tasks: [Send],
|
|
856
972
|
hooks: [hook(GenerationTask, { afterRun: replyHook(Send) })]
|
|
857
973
|
}),
|
|
858
|
-
tools: defineChannelTools(send),
|
|
974
|
+
tools: defineChannelTools(send, adapterFor, Object.values(options.channels).some(({ adapter }) => adapter.history !== void 0)),
|
|
859
975
|
bind: async (tx, target, conversationId) => {
|
|
860
976
|
registration(target.channel);
|
|
861
977
|
await bindAddress(tx, target, conversationId);
|
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 { 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,IAAI,OAAO,GAAG,IAAI,OAAO;AAC3D;AAEA,SAAS,UACP,OACuC;CACvC,OAAO,OAAO,QAAQ,OAAO,YAAY,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,SAAS,eAC9D,OAAO,QAAQ,SAAS,CAAC,CAAC,KAAK,CAAC,SAAS,cAAc;EACrD;EACA;EACA;CACF,EAAE,CACJ;AACF;AAEA,SAAgB,sBACd,OACA,gBACc;CACd,OAAO,UAAU,KAAK,CAAC,CACpB,QAAQ,EAAE,cAAc,QAAQ,mBAAmB,cAAc,CAAC,C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AM,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;CACA,MAAM,OAAa,OAAO,IAAI,gBAAgB,UAAU;EACtD,aAAa,MAAM,OAAO;EAC1B,MAAM,GAAG,WACP,MACA;GACE,SAAS,MAAM;GACf,SAAS,MAAM;GACf,OAAO,CAAC;IAAE,MAAM;IAAQ,MAAM,MAAM;GAAK,CAAC;GAC1C,gBAAgB,MAAM;GACtB,GAAI,MAAM,gBAAgB,KAAA,IACtB,CAAC,IACD,EAAE,aAAa,MAAM,YAAY;EACvC,GACA;GACE,WAAW,EAAE,MAAM,eAAe;GAClC;GACA,YAAY;EACd,CACF;CACF;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;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 via?: string;\n cursor?: string;\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 canonicalConversationAddresses(\n state: Readonly<ChannelsState> | undefined,\n conversationId: ConversationId,\n): AddressKey[] {\n return entriesOf(state)\n .filter(\n ({ binding }) =>\n binding.conversationId === conversationId && binding.via === undefined,\n )\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 ...(existing?.via === undefined ? {} : { via: existing.via }),\n ...(existing?.cursor === undefined ? {} : { cursor: existing.cursor }),\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\nexport function latestMessageIds(\n entries: readonly EntryRecord[],\n): Set<EntryId> {\n const latest = new Map<string, EntryId>();\n for (const entry of entries) {\n if (!ChannelMessage.is(entry)) continue;\n const key = JSON.stringify([entry.data.channel, entry.data.address]);\n latest.set(key, entry.id);\n }\n return new Set(latest.values());\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 latest = latestMessageIds(messages);\n const tasks = messages.map(({ id, data: { author: _author, ...target } }) =>\n hookTask(Send, {\n ...target,\n parts: latest.has(id) ? parts : [],\n idempotencyKey: replyKey(id),\n }),\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, opt, str } from \"@earendil-works/pi-schema\";\nimport type { Send } from \"./core\";\nimport {\n ChannelsDoc,\n canonicalConversationAddresses,\n conversationAddresses,\n findBinding,\n} from \"./doc\";\nimport type { AdapterLookup } from \"./send\";\n\nexport const TOOLS_EXTENSION = \"channels-tools\";\n\nexport const NO_REPLY = \"no_reply\";\n\nconst HISTORY_BYTES = 32 * 1024;\n\nfunction text(value: string, isError = false) {\n return { output: [{ type: \"text\" as const, text: value }], isError };\n}\n\nfunction boundedContent(content: string): {\n content: string;\n truncated: boolean;\n} {\n const encoder = new TextEncoder();\n let end = 0;\n let size = 0;\n let truncated = false;\n for (const character of content) {\n const length = encoder.encode(character).length;\n if (size + length > HISTORY_BYTES) {\n truncated = true;\n break;\n }\n size += length;\n end += character.length;\n }\n return { content: truncated ? content.slice(0, end) : content, truncated };\n}\n\nexport function defineChannelTools(\n send: Send,\n adapterFor: AdapterLookup,\n historyAvailable: boolean,\n): 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 readHistory = defineTool({\n name: \"read_history\",\n description:\n \"Read bounded source history for one of your channel addresses. Use after or before to continue from an opaque cursor returned by the channel.\",\n parameters: obj({\n channel: str(),\n address: str(),\n after: opt(str()),\n before: opt(str()),\n }),\n replay: \"safe\",\n execute: async ({ channel, address, after, before }, 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 adapter = adapterFor(channel);\n if (adapter?.history === undefined)\n return text(`History is unavailable on channel ${channel}.`, true);\n try {\n const result = await adapter.history(\n {\n address,\n ...(after === undefined ? {} : { after }),\n ...(before === undefined ? {} : { before }),\n maxBytes: HISTORY_BYTES,\n },\n { signal: context.abortSignal ?? new AbortController().signal },\n );\n const bounded = boundedContent(result.content);\n return text(\n JSON.stringify({\n content: bounded.content,\n ...(result.cursor === undefined ? {} : { cursor: result.cursor }),\n truncated: result.truncated || bounded.truncated,\n }),\n );\n } catch (error) {\n return text(\n `History read failed: ${error instanceof Error ? error.message : String(error)}`,\n true,\n );\n }\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 = canonicalConversationAddresses(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: [\n sendMessage,\n listAddresses,\n ...(historyAvailable ? [readHistory] : []),\n noReply,\n ],\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 { latestMessageIds, 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 const messages = entries.filter(ChannelMessage.is);\n const latest = latestMessageIds(messages);\n return messages.flatMap(({ id, data }) => {\n if (!latest.has(id)) return [];\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 ...(current.via === undefined ? {} : { via: current.via }),\n ...(current.cursor === undefined ? {} : { cursor: current.cursor }),\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, {\n conversationId,\n ...(addressData === undefined\n ? {}\n : { addressData: copyJson(addressData) }),\n });\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 canonical = {\n channel: key.channel,\n address: message.conversationAddress ?? key.address,\n };\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 bound = findBinding(state, canonical);\n if (bound !== undefined) {\n setBinding(state, key, {\n conversationId: bound.conversationId,\n via: canonical.address,\n });\n return bound.conversationId;\n }\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, canonical, record.id);\n if (key.address !== canonical.address)\n setBinding(state, key, {\n conversationId: record.id,\n via: canonical.address,\n });\n return record.id;\n }, context);\n }\n\n async function admit(\n key: AddressKey,\n message: InboundMessage,\n options: Required<DeliverOptions>,\n conversationId: ConversationId,\n ): Promise<DeliveryReceipt | undefined> {\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);\n if (message.addressData !== undefined || message.cursor !== undefined) {\n const addressData = message.addressData ?? stored?.addressData;\n const cursor = message.cursor ?? stored?.cursor;\n setBinding(state, key, {\n conversationId,\n ...(addressData === undefined ? {} : { addressData }),\n ...(stored?.via === undefined ? {} : { via: stored.via }),\n ...(cursor === undefined ? {} : { cursor }),\n });\n }\n const storedData = stored?.addressData;\n const addressData =\n message.addressData ??\n (storedData === undefined ? undefined : copyJson(storedData));\n const data = messageData(key, message, addressData);\n const draft = submission(message.requestId, content, data, options);\n const submissionId = await conversation.admit(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 canonical = {\n channel,\n address: message.conversationAddress ?? message.address,\n };\n const resolved = {\n whenBusy: options?.whenBusy ?? setup.options.whenBusy ?? \"queue\",\n run: options?.run ?? true,\n create: options?.create ?? true,\n };\n const conversationId = await serial(canonical, () =>\n conversationFor(key, message, resolved.run && resolved.create),\n );\n if (conversationId === undefined) {\n setup.report({ kind: \"ignored\", ...key });\n return undefined;\n }\n return serial(key, () => admit(key, message, resolved, conversationId));\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 binding: async (address) => {\n const state = await harness.snapshot(ChannelsDoc, context);\n return findBinding(state, { channel, address });\n },\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(\n send,\n adapterFor,\n Object.values(options.channels).some(\n ({ adapter }) => adapter.history !== undefined,\n ),\n ),\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":";;;;;;;AAoBA,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,SAAS,UACP,OACuC;CACvC,OAAO,OAAO,QAAQ,OAAO,YAAY,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,SAAS,eAC9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O,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;CACA,MAAM,OAAa,OAAO,IAAI,gBAAgB,UAAU;EACtD,aAAa,MAAM,OAAO;EAC1B,MAAM,GAAG,WACP,MACA;GACE,SAAS,MAAM;GACf,SAAS,MAAM;GACf,OAAO,CAAC;IAAE,MAAM;IAAQ,MAAM,MAAM;GAAK,CAAC;GAC1C,gBAAgB,MAAM;GACtB,GAAI,MAAM,gBAAgB,KAAA,IACtB,CAAC,IACD,EAAE,aAAa,MAAM,YAAY;EACvC,GACA;GACE,WAAW,EAAE,MAAM,eAAe;GAClC;GACA,YAAY;EACd,CACF;CACF;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,mBACL,MACA,YACA,OAAO,OAAO,QAAQ,QAAQ,CAAC,CAAC,MAC7B,EAAE,cAAc,QAAQ,YAAY,KAAA,CACvC,CACF;EACA,MAAM,OAAO,IAAI,QAAQ,mBAAmB;GAC1C,aAAa,OAAO,OAAO;GAC3B,MAAM,YAAY,IAAI,QAAQ,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.4.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.7.0",
|
|
32
|
+
"@earendil-works/pi-ai": "1.7.0",
|
|
33
|
+
"@earendil-works/pi-durable": "1.7.0",
|
|
34
|
+
"@earendil-works/pi-schema": "1.7.0"
|
|
35
35
|
},
|
|
36
36
|
"devDependencies": {
|
|
37
37
|
"vitest": "^5.1.0"
|