@loomwork/conversation 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +8 -0
  3. package/README.md +117 -2
  4. package/dist/access.d.ts +59 -0
  5. package/dist/access.d.ts.map +1 -0
  6. package/dist/access.js +178 -0
  7. package/dist/access.js.map +1 -0
  8. package/dist/bargeIn.d.ts +62 -0
  9. package/dist/bargeIn.d.ts.map +1 -0
  10. package/dist/bargeIn.js +110 -0
  11. package/dist/bargeIn.js.map +1 -0
  12. package/dist/budget.d.ts +82 -0
  13. package/dist/budget.d.ts.map +1 -0
  14. package/dist/budget.js +134 -0
  15. package/dist/budget.js.map +1 -0
  16. package/dist/conversation.d.ts +59 -0
  17. package/dist/conversation.d.ts.map +1 -0
  18. package/dist/conversation.js +786 -0
  19. package/dist/conversation.js.map +1 -0
  20. package/dist/conversations.d.ts +149 -0
  21. package/dist/conversations.d.ts.map +1 -0
  22. package/dist/conversations.js +498 -0
  23. package/dist/conversations.js.map +1 -0
  24. package/dist/feed.d.ts +32 -0
  25. package/dist/feed.d.ts.map +1 -0
  26. package/dist/feed.js +83 -0
  27. package/dist/feed.js.map +1 -0
  28. package/dist/hub.d.ts +119 -0
  29. package/dist/hub.d.ts.map +1 -0
  30. package/dist/hub.js +257 -0
  31. package/dist/hub.js.map +1 -0
  32. package/dist/ids.d.ts +9 -0
  33. package/dist/ids.d.ts.map +1 -0
  34. package/dist/ids.js +29 -0
  35. package/dist/ids.js.map +1 -0
  36. package/dist/index.d.ts +27 -0
  37. package/dist/index.d.ts.map +1 -0
  38. package/dist/index.js +65 -0
  39. package/dist/index.js.map +1 -0
  40. package/dist/providerError.d.ts +10 -0
  41. package/dist/providerError.d.ts.map +1 -0
  42. package/dist/providerError.js +16 -0
  43. package/dist/providerError.js.map +1 -0
  44. package/dist/reader.d.ts +53 -0
  45. package/dist/reader.d.ts.map +1 -0
  46. package/dist/reader.js +217 -0
  47. package/dist/reader.js.map +1 -0
  48. package/dist/settled.d.ts +49 -0
  49. package/dist/settled.d.ts.map +1 -0
  50. package/dist/settled.js +51 -0
  51. package/dist/settled.js.map +1 -0
  52. package/dist/signEnvelope.d.ts +51 -0
  53. package/dist/signEnvelope.d.ts.map +1 -0
  54. package/dist/signEnvelope.js +55 -0
  55. package/dist/signEnvelope.js.map +1 -0
  56. package/dist/summarizerText.d.ts +2 -0
  57. package/dist/summarizerText.d.ts.map +1 -0
  58. package/dist/summarizerText.js +9 -0
  59. package/dist/summarizerText.js.map +1 -0
  60. package/dist/turn.d.ts +67 -0
  61. package/dist/turn.d.ts.map +1 -0
  62. package/dist/turn.js +213 -0
  63. package/dist/turn.js.map +1 -0
  64. package/dist/types.d.ts +267 -0
  65. package/dist/types.d.ts.map +1 -0
  66. package/dist/types.js +18 -0
  67. package/dist/types.js.map +1 -0
  68. package/package.json +61 -3
  69. package/src/access.ts +221 -0
  70. package/src/bargeIn.ts +172 -0
  71. package/src/budget.ts +170 -0
  72. package/src/conversation.ts +961 -0
  73. package/src/conversations.ts +690 -0
  74. package/src/feed.ts +112 -0
  75. package/src/hub.ts +336 -0
  76. package/src/ids.ts +25 -0
  77. package/src/index.ts +75 -0
  78. package/src/reader.ts +274 -0
  79. package/src/settled.ts +80 -0
  80. package/src/signEnvelope.ts +76 -0
  81. package/src/summarizerText.ts +3 -0
  82. package/src/turn.ts +344 -0
  83. package/src/types.ts +271 -0
package/src/reader.ts ADDED
@@ -0,0 +1,274 @@
1
+ import type { EventEnvelope } from "@loomwork/core";
2
+ import { type EventStore, headOf, readRangeOf } from "@loomwork/event-runtime";
3
+ import { type Identity, parseIdentity } from "./access";
4
+ import { generationId } from "./ids";
5
+ import { type HistoryEntry, type MessageRecord, RECORD_SOURCE } from "./types";
6
+
7
+ // ── Reading a conversation back out of the log (ADR 0122 D4) ──────────────────────────────────────
8
+ //
9
+ // A conversation's transcript is the `conversation.message` events its flow emitted, spread over the
10
+ // generations of one chain (`<id>`, `<id>~1`, ...). The reader walks them with BOUNDED range reads: a
11
+ // call scans at most `maxScan` events and returns a cursor even when the page is not full, so one
12
+ // request costs O(maxScan) however long the conversation or however much model/tool traffic sits
13
+ // between two messages. It never folds state and never reads a whole log.
14
+ //
15
+ // THE READER DOES NOT AUTHORIZE. Whoever calls it has already decided the caller may read this
16
+ // conversation (`createConversations` does, against the runtime's execution authorizer).
17
+
18
+ /** `<generation>.<sequence>`: a position in the chain's log. */
19
+ export interface Position {
20
+ g: number;
21
+ seq: number;
22
+ }
23
+
24
+ const CURSOR = /^(\d{1,9})\.(\d{1,15})$/;
25
+
26
+ export function formatCursor(p: Position): string {
27
+ return `${p.g}.${p.seq}`;
28
+ }
29
+
30
+ export function parseCursor(cursor: string | undefined): Position | undefined {
31
+ if (cursor === undefined) return undefined;
32
+ const m = CURSOR.exec(cursor);
33
+ if (m === null) return undefined;
34
+ return { g: Number(m[1]), seq: Number(m[2]) };
35
+ }
36
+
37
+ /** A malformed cursor is a caller error, not "start over". */
38
+ export class InvalidCursorError extends Error {
39
+ readonly code = "INVALID_CURSOR";
40
+ constructor() {
41
+ super("invalid cursor");
42
+ this.name = "InvalidCursorError";
43
+ }
44
+ }
45
+
46
+ export interface ReadOptions {
47
+ /** Messages to return at most. Default 50, capped at 500. */
48
+ limit?: number;
49
+ /**
50
+ * Events to SCAN at most (the cost bound). Default 2 000. A page may return fewer than `limit`
51
+ * messages with `done: false`: call again with `nextCursor`.
52
+ */
53
+ maxScan?: number;
54
+ /** Where to continue: forward = after this position, backward = before it. */
55
+ cursor?: string;
56
+ /** `"forward"` (oldest first, default) or `"backward"` (newest first). */
57
+ direction?: "forward" | "backward";
58
+ /** Stop reading (the caller went away): the call returns what it has with `done: false`. */
59
+ signal?: AbortSignal;
60
+ }
61
+
62
+ export interface ReadResult {
63
+ entries: HistoryEntry[];
64
+ /** Pass back as `cursor` to continue in the same direction. Absent when nothing was scanned. */
65
+ nextCursor?: string;
66
+ /** True when the scan reached the end of the log in its direction (forward: the live tip; backward: the start). */
67
+ done: boolean;
68
+ /** True when the conversation has a `conversation.closed` event (forward scans only). */
69
+ closed?: boolean;
70
+ }
71
+
72
+ const DEFAULT_LIMIT = 50;
73
+ const MAX_LIMIT = 500;
74
+ const DEFAULT_MAX_SCAN = 2000;
75
+ const BLOCK = 256;
76
+
77
+ /** The conversation fact a `DECISION_RECORDED` carries, if it is one of ours. */
78
+ function factOf(ev: EventEnvelope): unknown {
79
+ if (ev.eventType !== "DECISION_RECORDED") return undefined;
80
+ const d = ev.payload as { source?: unknown; choice?: unknown } | null;
81
+ return d !== null && typeof d === "object" && d.source === RECORD_SOURCE ? d.choice : undefined;
82
+ }
83
+
84
+ const isOrd = (v: unknown): v is number =>
85
+ typeof v === "number" && Number.isSafeInteger(v) && v >= 1;
86
+
87
+ /** The message record a `conversation.message` decision event carries, or `undefined` if it is not one. */
88
+ export function recordOf(ev: EventEnvelope): MessageRecord | undefined {
89
+ const p = factOf(ev) as Partial<MessageRecord> | null | undefined;
90
+ if (p === undefined) return undefined;
91
+ if (
92
+ typeof p !== "object" ||
93
+ p === null ||
94
+ typeof p.turn !== "number" ||
95
+ (p.role !== "user" && p.role !== "assistant") ||
96
+ typeof p.text !== "string" ||
97
+ typeof p.status !== "string"
98
+ ) {
99
+ return undefined;
100
+ }
101
+ return {
102
+ turn: p.turn,
103
+ ...(isOrd(p.ord) && { ord: p.ord }),
104
+ ...(isOrd(p.editOf) && { editOf: p.editOf }),
105
+ ...(isOrd(p.editOfTurn) && { editOfTurn: p.editOfTurn }),
106
+ role: p.role,
107
+ text: p.text,
108
+ status: p.status,
109
+ ...(typeof p.reason === "string" && { reason: p.reason }),
110
+ ...(typeof p.errorId === "string" && { errorId: p.errorId }),
111
+ ...(parseIdentity(p.asker) !== undefined && { asker: parseIdentity(p.asker) as Identity }),
112
+ ...(Array.isArray(p.classes) &&
113
+ p.classes.length > 0 && {
114
+ classes: p.classes.filter((x): x is string => typeof x === "string"),
115
+ }),
116
+ ...(typeof p.turnExecutionId === "string" && { turnExecutionId: p.turnExecutionId }),
117
+ };
118
+ }
119
+
120
+ function entryOf(g: number, ev: EventEnvelope, rec: MessageRecord): HistoryEntry {
121
+ return {
122
+ ...rec,
123
+ cursor: formatCursor({ g, seq: ev.sequence }),
124
+ executionId: ev.executionId,
125
+ at: ev.timestamp,
126
+ };
127
+ }
128
+
129
+ /** Whether an execution (generation) has any events. One indexed point read. */
130
+ async function exists(store: EventStore, id: string): Promise<boolean> {
131
+ return (await headOf(store, id)) !== null;
132
+ }
133
+
134
+ /**
135
+ * The newest generation of a chain, by galloping then bisecting over `exists` (generations are
136
+ * consecutive from 0): O(log G) point reads, not a walk. `hint` is a generation known to exist.
137
+ */
138
+ export async function findHeadGeneration(
139
+ store: EventStore,
140
+ conversationId: string,
141
+ hint = 0
142
+ ): Promise<number | undefined> {
143
+ if (!(await exists(store, generationId(conversationId, hint)))) {
144
+ if (hint === 0) return undefined;
145
+ return findHeadGeneration(store, conversationId, 0);
146
+ }
147
+ let lo = hint; // exists
148
+ let step = 1;
149
+ let hi = lo + step; // find a missing one
150
+ while (await exists(store, generationId(conversationId, hi))) {
151
+ lo = hi;
152
+ step *= 2;
153
+ hi = lo + step;
154
+ }
155
+ while (hi - lo > 1) {
156
+ const mid = lo + Math.floor((hi - lo) / 2);
157
+ if (await exists(store, generationId(conversationId, mid))) lo = mid;
158
+ else hi = mid;
159
+ }
160
+ return lo;
161
+ }
162
+
163
+ export interface ConversationReader {
164
+ read(conversationId: string, options?: ReadOptions): Promise<ReadResult>;
165
+ /** The newest generation that has events, or `undefined` when the conversation has none. */
166
+ headGeneration(conversationId: string, hint?: number): Promise<number | undefined>;
167
+ }
168
+
169
+ export function createConversationReader(store: EventStore): ConversationReader {
170
+ async function forward(conversationId: string, opts: ReadOptions): Promise<ReadResult> {
171
+ const limit = Math.min(Math.max(1, opts.limit ?? DEFAULT_LIMIT), MAX_LIMIT);
172
+ const maxScan = Math.max(1, opts.maxScan ?? DEFAULT_MAX_SCAN);
173
+ const after = parseCursor(opts.cursor);
174
+ if (opts.cursor !== undefined && after === undefined) throw new InvalidCursorError();
175
+ let g = after?.g ?? 0;
176
+ let next = after !== undefined ? after.seq + 1 : 0;
177
+ let last: Position | undefined = after;
178
+ let scanned = 0;
179
+ let closed = false;
180
+ const entries: HistoryEntry[] = [];
181
+ for (;;) {
182
+ if (entries.length >= limit || scanned >= maxScan || opts.signal?.aborted === true) {
183
+ return { entries, ...(last && { nextCursor: formatCursor(last) }), done: false, closed };
184
+ }
185
+ const evs = await readRangeOf(
186
+ store,
187
+ generationId(conversationId, g),
188
+ next,
189
+ next + Math.min(BLOCK, maxScan - scanned) - 1
190
+ );
191
+ if (evs.length === 0) {
192
+ // This generation has nothing more: a successor means keep going, none means we are at the tip.
193
+ if (await exists(store, generationId(conversationId, g + 1))) {
194
+ g++;
195
+ next = 0;
196
+ scanned++; // a generation hop is work: it counts against the scan budget
197
+ continue;
198
+ }
199
+ return { entries, ...(last && { nextCursor: formatCursor(last) }), done: true, closed };
200
+ }
201
+ for (const ev of evs) {
202
+ scanned++;
203
+ last = { g, seq: ev.sequence };
204
+ if ((factOf(ev) as { kind?: unknown } | undefined)?.kind === "closed") closed = true;
205
+ const rec = recordOf(ev);
206
+ if (rec !== undefined) entries.push(entryOf(g, ev, rec));
207
+ if (entries.length >= limit) break;
208
+ }
209
+ next = (last as Position).seq + 1;
210
+ }
211
+ }
212
+
213
+ async function backward(conversationId: string, opts: ReadOptions): Promise<ReadResult> {
214
+ const limit = Math.min(Math.max(1, opts.limit ?? DEFAULT_LIMIT), MAX_LIMIT);
215
+ const maxScan = Math.max(1, opts.maxScan ?? DEFAULT_MAX_SCAN);
216
+ const before = parseCursor(opts.cursor);
217
+ if (opts.cursor !== undefined && before === undefined) throw new InvalidCursorError();
218
+ // The cursor is UNTRUSTED input: it is clamped to what exists. A generation past the head, or a
219
+ // sequence past a generation's tip, means "from the end", never a walk through nothing.
220
+ const head = await findHeadGeneration(store, conversationId);
221
+ if (head === undefined) return { entries: [], done: true };
222
+ const tipOf = async (gen: number): Promise<number> =>
223
+ ((await headOf(store, generationId(conversationId, gen))) ?? -1) + 1;
224
+ let g = before === undefined ? head : Math.min(before.g, head);
225
+ let upper = await tipOf(g); // exclusive upper bound within generation g
226
+ if (before !== undefined && before.g <= head) upper = Math.min(before.seq, upper);
227
+ let last: Position | undefined = before;
228
+ let scanned = 0;
229
+ const entries: HistoryEntry[] = [];
230
+ for (;;) {
231
+ if (entries.length >= limit || scanned >= maxScan || opts.signal?.aborted === true) {
232
+ return { entries, ...(last && { nextCursor: formatCursor(last) }), done: false };
233
+ }
234
+ if (upper <= 0) {
235
+ if (g === 0)
236
+ return { entries, ...(last && { nextCursor: formatCursor(last) }), done: true };
237
+ g--;
238
+ upper = await tipOf(g);
239
+ scanned++; // a generation hop is work: it counts against the scan budget
240
+ last = { g, seq: upper };
241
+ continue;
242
+ }
243
+ const take = Math.min(BLOCK, maxScan - scanned, upper);
244
+ const evs = await readRangeOf(
245
+ store,
246
+ generationId(conversationId, g),
247
+ upper - take,
248
+ upper - 1
249
+ );
250
+ if (evs.length === 0) {
251
+ // The range is gone (retention): treat the rest of this generation as exhausted.
252
+ upper = 0;
253
+ continue;
254
+ }
255
+ for (let i = evs.length - 1; i >= 0; i--) {
256
+ const ev = evs[i] as EventEnvelope;
257
+ scanned++;
258
+ last = { g, seq: ev.sequence };
259
+ const rec = recordOf(ev);
260
+ if (rec !== undefined) entries.push(entryOf(g, ev, rec));
261
+ if (entries.length >= limit) break;
262
+ }
263
+ upper = (last as Position).seq;
264
+ }
265
+ }
266
+
267
+ return {
268
+ read: (conversationId, options = {}) =>
269
+ (options.direction ?? "forward") === "backward"
270
+ ? backward(conversationId, options)
271
+ : forward(conversationId, options),
272
+ headGeneration: (conversationId, hint) => findHeadGeneration(store, conversationId, hint),
273
+ };
274
+ }
package/src/settled.ts ADDED
@@ -0,0 +1,80 @@
1
+ import type { EventEnvelope } from "@loomwork/core";
2
+ import type { Identity } from "./access";
3
+ import { conversationIdOf } from "./ids";
4
+ import { recordOf } from "./reader";
5
+
6
+ // ── Turn settled: start work once a reply is in the log ───────────────────────────────────────
7
+ //
8
+ // A host often has work to do after a turn: a title, an index entry, a notification, something
9
+ // composed from the finished answer. The hub cannot say "a turn of SOME conversation settled"
10
+ // (it is per conversation, and lossy), and the flow body cannot say "and it is durable" (a record
11
+ // is folded before its write lands). The runtime's `onDurableEvent` (ADR 0147) can: it fires once a
12
+ // write has resolved, never for an event replay or recovery serves from the log. This turns that
13
+ // stream into one callback per settled turn.
14
+
15
+ /** A turn of a conversation whose closing record is in the log. Ids and status only, never text. */
16
+ export interface TurnSettledEvent {
17
+ conversationId: string;
18
+ /** The generation that wrote the record (`<conversationId>` or `<conversationId>~<n>`). */
19
+ executionId: string;
20
+ /** The turn number. A rejected message belongs to no turn and carries `0`. */
21
+ turn: number;
22
+ /** The closing record's `ord`: unique within the conversation, so a good idempotency key. */
23
+ ord: number;
24
+ /**
25
+ * `complete`, `interrupted` (a barge-in) or `failed` close an answered turn (the assistant record);
26
+ * `rejected` is a user message refused before any model call (the user record).
27
+ */
28
+ status: "complete" | "interrupted" | "failed" | "rejected";
29
+ /** Shared mode only: who asked. */
30
+ asker?: Identity;
31
+ }
32
+
33
+ export type TurnSettledListener = (event: TurnSettledEvent) => void | Promise<void>;
34
+
35
+ const SETTLED = new Set<string>(["complete", "interrupted", "failed"]);
36
+
37
+ /**
38
+ * An `onDurableEvent` observer that calls `listener` once for each turn of `flow` whose closing
39
+ * record has been written: the assistant reply (`complete` / `interrupted` / `failed`), or a user
40
+ * message recorded as `rejected`. A read made from the listener sees the record.
41
+ *
42
+ * ```ts
43
+ * new WorkflowRuntime({ ..., onDurableEvent: turnSettledObserver(flow, (e) => queue.push(e)) });
44
+ * // or: defineConfig({ observability: { onDurableEvent: turnSettledObserver(flow, listener) } })
45
+ * ```
46
+ *
47
+ * The guarantees are `onDurableEvent`'s:
48
+ * - **After the write, at most once.** Replay and recovery serve the record from the log and append
49
+ * nothing, so they do not call it again. A process that dies after the write but before the call
50
+ * never makes it: if the work must happen, keep a recovery path (read `history` from your last
51
+ * handled `ord`). A fork of a conversation execution copies its prefix through the runtime, and those
52
+ * copies can be reported again under the fork's id: key idempotent work by `conversationId` + `ord`.
53
+ * - **Isolated.** A throw or a rejected promise is reported through the runtime's `onWarn` and never
54
+ * reaches the turn. An async listener is not awaited. Its SYNCHRONOUS part runs on the write chain,
55
+ * though, and delays the next write: start the work and return, do not do it inline.
56
+ * - **Only this runtime's writes.** A turn answered by another process is reported there.
57
+ *
58
+ * One runtime has one `onDurableEvent`: to observe several things, call each observer from one function.
59
+ */
60
+ export function turnSettledObserver(
61
+ flow: { readonly definition: { readonly id: string } },
62
+ listener: TurnSettledListener
63
+ ): (event: EventEnvelope) => void | Promise<void> {
64
+ const flowId = flow.definition.id;
65
+ return (event) => {
66
+ if (event.workflowId !== flowId) return;
67
+ const rec = recordOf(event);
68
+ if (rec === undefined || rec.ord === undefined) return;
69
+ const settled = rec.role === "assistant" ? SETTLED.has(rec.status) : rec.status === "rejected";
70
+ if (!settled) return;
71
+ return listener({
72
+ conversationId: conversationIdOf(event.executionId),
73
+ executionId: event.executionId,
74
+ turn: rec.turn,
75
+ ord: rec.ord,
76
+ status: rec.status as TurnSettledEvent["status"],
77
+ ...(rec.asker !== undefined && { asker: rec.asker }),
78
+ });
79
+ };
80
+ }
@@ -0,0 +1,76 @@
1
+ import type { Identity } from "./access";
2
+ import { parseSignedEnvelope, signedEnvelope } from "./conversation";
3
+
4
+ /** What a host-signed inbox envelope says (the signature is added by {@link signInboxEnvelope}). */
5
+ export interface InboxEnvelopeBody {
6
+ /** The conversation this message is for. A signature for one conversation is refused by any other. */
7
+ conversationId: string;
8
+ /** `"user"` is a turn (needs `text`); `"close"` closes the conversation. */
9
+ kind: "user" | "close";
10
+ /** The replay-set key: unique per message. Re-using an id is refused as `replayed`. */
11
+ id: string;
12
+ /** Issue time, ms since epoch. An envelope at or before the conversation's staleness floor is refused as `stale`. */
13
+ iat: number;
14
+ /** The user text (kind `"user"`). */
15
+ text?: string;
16
+ /** Whose voice this is. Owner mode accepts only the owner's; shared mode needs a participant. */
17
+ asker?: Identity;
18
+ /** Shared mode: the `ord` of the asker's earlier user turn this one replaces. */
19
+ editOf?: number;
20
+ }
21
+
22
+ /** Thrown by {@link signInboxEnvelope} when the body is not an envelope the conversation would accept the SHAPE of. */
23
+ export class InvalidEnvelopeError extends Error {
24
+ constructor(message: string) {
25
+ super(message);
26
+ this.name = "InvalidEnvelopeError";
27
+ }
28
+ }
29
+
30
+ /**
31
+ * Sign an inbox envelope the way a host's own client does, so a test, a script or a TRUSTED bridge can write
32
+ * to a conversation's inbox directly (`runtime.send(id, { topic: CONVERSATION_TOPIC, payload })`).
33
+ *
34
+ * - It needs the conversation's envelope key (`ConversationFlowOptions.key`). The key is the authority of a
35
+ * TRUSTED bridge: keep it server-side, never ship it to a browser, and rotate it via `previousKeys`.
36
+ * - The body is checked up front with the same shape rules the conversation applies (a non-empty `id` of
37
+ * at most 256 chars, a finite `iat`, a valid `asker`, non-blank `text` for `"user"`, a positive integer
38
+ * `editOf`); a body that would be refused as malformed throws {@link InvalidEnvelopeError} instead of
39
+ * being signed. `maxTurnChars` is NOT checked here (the signer does not know the flow's limit): the
40
+ * conversation enforces it on the body.
41
+ * - A signature is NOT "nothing". A holder of the key can: (1) in SHARED mode, speak as ANY participant (the
42
+ * body checks only that the named `asker` is a participant); (2) edit that asker's earlier turns (`editOf`
43
+ * is checked against the signed `asker`, so it is only as strong as (1)); (3) bypass the client-only
44
+ * checks: the per-asker queue cap (`maxQueuedPerAsker`), and the "delegated sender needs `principalFor`"
45
+ * rule; (4) in OWNER mode the `asker` = owner comparison is a consistency check, not authentication: the
46
+ * runtime's access policy on `send` decides who may write at all; (5) write to EVERY conversation the
47
+ * runtime's `send` policy admits, because the key is per flow, not per tenant; (6) skew the staleness
48
+ * floor: an `iat` up to 60 s in the future is accepted, and once that id is evicted from the replay set
49
+ * the floor moves forward, making legitimate envelopes issued in the following ~60 s `stale`.
50
+ * - What still holds against a key holder: the conversation binding, replayed ids, the staleness floor and
51
+ * age window, the owner-mode voice, the shared-mode participant check for user turns, a shared-mode
52
+ * close needing the owner, the service principal or a `manageParticipants` manager, `maxTurnChars`, and
53
+ * the shape checks above.
54
+ * - Intended users: tests and trusted server-side bridges. An application normally calls
55
+ * `conversations.sendTurn`, which builds and signs the envelope itself.
56
+ */
57
+ export function signInboxEnvelope(key: string, body: InboxEnvelopeBody): Record<string, unknown> {
58
+ if (typeof key !== "string" || key.length === 0) {
59
+ throw new TypeError(
60
+ "signInboxEnvelope: `key` must be the conversation's non-empty envelope key"
61
+ );
62
+ }
63
+ if (body.kind === "user" && typeof body.text === "string" && body.text.trim() === "") {
64
+ throw new InvalidEnvelopeError(
65
+ "signInboxEnvelope: a `user` envelope needs non-blank `text` (the conversation refuses it as malformed)"
66
+ );
67
+ }
68
+ const signed = signedEnvelope(key, { ...body });
69
+ const { reason } = parseSignedEnvelope(signed, key, body.conversationId);
70
+ if (reason !== undefined) {
71
+ throw new InvalidEnvelopeError(
72
+ `signInboxEnvelope: the body would be refused as ${reason} (check conversationId, kind, id, iat, text, asker, editOf)`
73
+ );
74
+ }
75
+ return signed;
76
+ }
@@ -0,0 +1,3 @@
1
+ // The walker moved down to @loomwork/agent so the built-in compaction summarizer can use it
2
+ // (ADR 0137); this re-export keeps `@loomwork/conversation`'s public surface and imports unchanged.
3
+ export { SUMMARIZER_TEXT_TRUNCATED, summarizerText } from "@loomwork/agent";