@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.
- package/LICENSE +202 -0
- package/NOTICE +8 -0
- package/README.md +117 -2
- package/dist/access.d.ts +59 -0
- package/dist/access.d.ts.map +1 -0
- package/dist/access.js +178 -0
- package/dist/access.js.map +1 -0
- package/dist/bargeIn.d.ts +62 -0
- package/dist/bargeIn.d.ts.map +1 -0
- package/dist/bargeIn.js +110 -0
- package/dist/bargeIn.js.map +1 -0
- package/dist/budget.d.ts +82 -0
- package/dist/budget.d.ts.map +1 -0
- package/dist/budget.js +134 -0
- package/dist/budget.js.map +1 -0
- package/dist/conversation.d.ts +59 -0
- package/dist/conversation.d.ts.map +1 -0
- package/dist/conversation.js +786 -0
- package/dist/conversation.js.map +1 -0
- package/dist/conversations.d.ts +149 -0
- package/dist/conversations.d.ts.map +1 -0
- package/dist/conversations.js +498 -0
- package/dist/conversations.js.map +1 -0
- package/dist/feed.d.ts +32 -0
- package/dist/feed.d.ts.map +1 -0
- package/dist/feed.js +83 -0
- package/dist/feed.js.map +1 -0
- package/dist/hub.d.ts +119 -0
- package/dist/hub.d.ts.map +1 -0
- package/dist/hub.js +257 -0
- package/dist/hub.js.map +1 -0
- package/dist/ids.d.ts +9 -0
- package/dist/ids.d.ts.map +1 -0
- package/dist/ids.js +29 -0
- package/dist/ids.js.map +1 -0
- package/dist/index.d.ts +27 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +65 -0
- package/dist/index.js.map +1 -0
- package/dist/providerError.d.ts +10 -0
- package/dist/providerError.d.ts.map +1 -0
- package/dist/providerError.js +16 -0
- package/dist/providerError.js.map +1 -0
- package/dist/reader.d.ts +53 -0
- package/dist/reader.d.ts.map +1 -0
- package/dist/reader.js +217 -0
- package/dist/reader.js.map +1 -0
- package/dist/settled.d.ts +49 -0
- package/dist/settled.d.ts.map +1 -0
- package/dist/settled.js +51 -0
- package/dist/settled.js.map +1 -0
- package/dist/signEnvelope.d.ts +51 -0
- package/dist/signEnvelope.d.ts.map +1 -0
- package/dist/signEnvelope.js +55 -0
- package/dist/signEnvelope.js.map +1 -0
- package/dist/summarizerText.d.ts +2 -0
- package/dist/summarizerText.d.ts.map +1 -0
- package/dist/summarizerText.js +9 -0
- package/dist/summarizerText.js.map +1 -0
- package/dist/turn.d.ts +67 -0
- package/dist/turn.d.ts.map +1 -0
- package/dist/turn.js +213 -0
- package/dist/turn.js.map +1 -0
- package/dist/types.d.ts +267 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +18 -0
- package/dist/types.js.map +1 -0
- package/package.json +61 -3
- package/src/access.ts +221 -0
- package/src/bargeIn.ts +172 -0
- package/src/budget.ts +170 -0
- package/src/conversation.ts +961 -0
- package/src/conversations.ts +690 -0
- package/src/feed.ts +112 -0
- package/src/hub.ts +336 -0
- package/src/ids.ts +25 -0
- package/src/index.ts +75 -0
- package/src/reader.ts +274 -0
- package/src/settled.ts +80 -0
- package/src/signEnvelope.ts +76 -0
- package/src/summarizerText.ts +3 -0
- package/src/turn.ts +344 -0
- package/src/types.ts +271 -0
package/src/feed.ts
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import type { EventStore } from "@loomwork/event-runtime";
|
|
2
|
+
import { generationId } from "./ids";
|
|
3
|
+
import { type ConversationReader, parseCursor } from "./reader";
|
|
4
|
+
import type { HistoryEntry } from "./types";
|
|
5
|
+
|
|
6
|
+
// ── Following a conversation as it is written (ADR 0122 D6) ────────────────────────────────────────
|
|
7
|
+
//
|
|
8
|
+
// The durable half of a live view: every recorded message after a cursor, in order, then new ones as
|
|
9
|
+
// they are recorded, across rotations. DATA comes from bounded reads only. The store's subscription
|
|
10
|
+
// is used as a WAKE-UP (something was appended, go read), never as a source of events, so there is one
|
|
11
|
+
// ordering and one cursor, a missed notification costs latency (the poll interval) and never a
|
|
12
|
+
// message, and resuming from `Last-Event-ID` is the same code path as following.
|
|
13
|
+
|
|
14
|
+
export type FeedItem = { type: "message"; entry: HistoryEntry } | { type: "closed" };
|
|
15
|
+
|
|
16
|
+
export interface FollowOptions {
|
|
17
|
+
/** Continue after this cursor (a `HistoryEntry.cursor`, or a `nextCursor`). Absent: from the start. */
|
|
18
|
+
cursor?: string;
|
|
19
|
+
/** Stop following (the consumer went away). */
|
|
20
|
+
signal?: AbortSignal;
|
|
21
|
+
/** Safety-net poll when no notification arrives, ms. Default 2 000. */
|
|
22
|
+
pollMs?: number;
|
|
23
|
+
/** Messages per read. Default 100. */
|
|
24
|
+
pageLimit?: number;
|
|
25
|
+
/** Events one read may scan. Default 2 000. */
|
|
26
|
+
maxScan?: number;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface FollowDeps {
|
|
30
|
+
reader: ConversationReader;
|
|
31
|
+
eventStore: EventStore;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Yields each recorded message after `options.cursor`, then waits for more. Ends after yielding
|
|
36
|
+
* `closed` (the conversation was closed) or when `signal` aborts. Throws `InvalidCursorError` for a
|
|
37
|
+
* malformed cursor. AUTHORIZE BEFORE CALLING: this reads the log directly.
|
|
38
|
+
*/
|
|
39
|
+
export async function* followConversation(
|
|
40
|
+
deps: FollowDeps,
|
|
41
|
+
conversationId: string,
|
|
42
|
+
options: FollowOptions = {}
|
|
43
|
+
): AsyncGenerator<FeedItem> {
|
|
44
|
+
const { reader, eventStore } = deps;
|
|
45
|
+
const signal = options.signal;
|
|
46
|
+
const pollMs = options.pollMs ?? 2000;
|
|
47
|
+
let cursor = options.cursor;
|
|
48
|
+
parseCursor(cursor); // validated by the first read; a bad one throws there
|
|
49
|
+
|
|
50
|
+
// Wake-ups: subscribe to the generation we are reading and the next one (a rotation appends to a
|
|
51
|
+
// NEW execution), moving the pair forward as the cursor advances.
|
|
52
|
+
let wake: (() => void) | undefined;
|
|
53
|
+
let woken = false;
|
|
54
|
+
const poke = (): void => {
|
|
55
|
+
woken = true;
|
|
56
|
+
wake?.();
|
|
57
|
+
};
|
|
58
|
+
const subs = new Map<number, () => void>();
|
|
59
|
+
const watch = async (g: number): Promise<void> => {
|
|
60
|
+
for (const want of [g, g + 1]) {
|
|
61
|
+
if (subs.has(want)) continue;
|
|
62
|
+
subs.set(want, await eventStore.subscribe(generationId(conversationId, want), poke));
|
|
63
|
+
}
|
|
64
|
+
for (const [have, off] of subs) {
|
|
65
|
+
if (have < g) {
|
|
66
|
+
off();
|
|
67
|
+
subs.delete(have);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
};
|
|
71
|
+
const idle = (): Promise<void> =>
|
|
72
|
+
new Promise<void>((resolve) => {
|
|
73
|
+
if (woken || signal?.aborted === true) return resolve();
|
|
74
|
+
const timer = setTimeout(done, pollMs);
|
|
75
|
+
timer.unref?.();
|
|
76
|
+
function done(): void {
|
|
77
|
+
clearTimeout(timer);
|
|
78
|
+
wake = undefined;
|
|
79
|
+
signal?.removeEventListener("abort", done);
|
|
80
|
+
resolve();
|
|
81
|
+
}
|
|
82
|
+
wake = done;
|
|
83
|
+
signal?.addEventListener("abort", done, { once: true });
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
try {
|
|
87
|
+
await watch(parseCursor(cursor)?.g ?? 0);
|
|
88
|
+
while (signal?.aborted !== true) {
|
|
89
|
+
woken = false;
|
|
90
|
+
const page = await reader.read(conversationId, {
|
|
91
|
+
...(cursor !== undefined && { cursor }),
|
|
92
|
+
limit: options.pageLimit ?? 100,
|
|
93
|
+
...(options.maxScan !== undefined && { maxScan: options.maxScan }),
|
|
94
|
+
});
|
|
95
|
+
for (const entry of page.entries) {
|
|
96
|
+
yield { type: "message", entry };
|
|
97
|
+
}
|
|
98
|
+
if (page.nextCursor !== undefined) {
|
|
99
|
+
cursor = page.nextCursor;
|
|
100
|
+
await watch(parseCursor(cursor)?.g ?? 0);
|
|
101
|
+
}
|
|
102
|
+
if (page.closed === true) {
|
|
103
|
+
yield { type: "closed" };
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
if (!page.done) continue; // more is already waiting
|
|
107
|
+
await idle();
|
|
108
|
+
}
|
|
109
|
+
} finally {
|
|
110
|
+
for (const off of subs.values()) off();
|
|
111
|
+
}
|
|
112
|
+
}
|
package/src/hub.ts
ADDED
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
import { type TaintedValue, unwrapTainted } from "@loomwork/classify";
|
|
3
|
+
import { fail } from "@loomwork/core";
|
|
4
|
+
import { LLM_INTERRUPTED } from "@loomwork/llm";
|
|
5
|
+
import type { LlmProvider, LlmRequest, LlmStreamChunk } from "@loomwork/llm";
|
|
6
|
+
|
|
7
|
+
// ── The live (transient) channel of a conversation (ADR 0122 D5) ───────────────────────────────
|
|
8
|
+
//
|
|
9
|
+
// A turn's tokens are NOT durable (ADR 0119: a delta is never journaled and is not called on replay),
|
|
10
|
+
// so they cannot be read back from the log; they are pushed to whoever is attached RIGHT NOW. This
|
|
11
|
+
// hub is that fan-out, in process, bounded and lossy by design: a subscriber that attaches late, or
|
|
12
|
+
// is too slow, misses deltas and recovers from the DURABLE record (the turn's `conversation.message`
|
|
13
|
+
// event carries the whole reply). It never carries anything the log does not eventually hold.
|
|
14
|
+
|
|
15
|
+
/** A live event for a conversation. Deltas and resets only: everything durable comes from the log. */
|
|
16
|
+
export type LiveEvent =
|
|
17
|
+
| { type: "delta"; conversationId: string; turn: number; text: string; asker?: string }
|
|
18
|
+
/**
|
|
19
|
+
* ADR 0133 D6 - a readable reasoning increment of the turn's model call. A channel of its own, so no
|
|
20
|
+
* consumer of reply text sees it by accident; a transport serves it to the turn's ASKER and the conversation's OWNER only (`asker`
|
|
21
|
+
* is always set in shared mode) and only when the host opted in.
|
|
22
|
+
*/
|
|
23
|
+
| { type: "reasoning"; conversationId: string; turn: number; text: string; asker?: string }
|
|
24
|
+
/** The turn's stream restarted from zero (a crash-recovered re-run asked the model again): discard the partial. */
|
|
25
|
+
| { type: "reset"; conversationId: string; turn: number; asker?: string };
|
|
26
|
+
|
|
27
|
+
/** What the model effect's `onDelta` needs to know about the call it is serving. */
|
|
28
|
+
interface TurnScope {
|
|
29
|
+
conversationId: string;
|
|
30
|
+
turn: number;
|
|
31
|
+
/** Distinguishes one execution of the turn body from a re-run of it after a crash. */
|
|
32
|
+
run: number;
|
|
33
|
+
/** Fires when a newer user message barges in on this turn. */
|
|
34
|
+
signal: AbortSignal;
|
|
35
|
+
/** Called before a LIVE model request: starts whatever watches for a barge-in (a replayed turn never gets here). */
|
|
36
|
+
ensure?: () => Promise<unknown>;
|
|
37
|
+
/** Shared mode: the identity key of the asker. Live deltas are published for THIS viewer only. */
|
|
38
|
+
asker?: string;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const scope = new AsyncLocalStorage<TurnScope>();
|
|
42
|
+
let runCounter = 0;
|
|
43
|
+
|
|
44
|
+
/** Run `fn` as the body of `turn` of `conversationId`: model deltas produced inside it are attributed to it. */
|
|
45
|
+
export function withTurnScope<T>(
|
|
46
|
+
conversationId: string,
|
|
47
|
+
turn: number,
|
|
48
|
+
signal: AbortSignal,
|
|
49
|
+
fn: () => T,
|
|
50
|
+
ensure?: () => Promise<unknown>,
|
|
51
|
+
asker?: string
|
|
52
|
+
): T {
|
|
53
|
+
return scope.run(
|
|
54
|
+
{
|
|
55
|
+
conversationId,
|
|
56
|
+
turn,
|
|
57
|
+
run: ++runCounter,
|
|
58
|
+
signal,
|
|
59
|
+
...(ensure !== undefined && { ensure }),
|
|
60
|
+
...(asker !== undefined && { asker }),
|
|
61
|
+
},
|
|
62
|
+
fn
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** The request with the running turn's barge-in signal merged into its own, if there is a turn. */
|
|
67
|
+
function withTurnSignal(request: LlmRequest): LlmRequest {
|
|
68
|
+
const turn = scope.getStore()?.signal;
|
|
69
|
+
if (turn === undefined) return request;
|
|
70
|
+
return {
|
|
71
|
+
...request,
|
|
72
|
+
signal: request.signal === undefined ? turn : AbortSignal.any([request.signal, turn]),
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Maximum live subscribers per conversation. A further subscribe is refused (the caller answers 429). */
|
|
77
|
+
export const DEFAULT_MAX_SUBSCRIBERS = 64;
|
|
78
|
+
|
|
79
|
+
const MAX_TRACKED_TURNS = 1024;
|
|
80
|
+
|
|
81
|
+
export class SubscriberLimitError extends Error {
|
|
82
|
+
readonly code = "SUBSCRIBER_LIMIT";
|
|
83
|
+
constructor(conversationId: string, limit: number) {
|
|
84
|
+
super(`conversation "${conversationId}" already has ${limit} live subscribers`);
|
|
85
|
+
this.name = "SubscriberLimitError";
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export interface ConversationHubOptions {
|
|
90
|
+
/** Live subscribers allowed per conversation. Default {@link DEFAULT_MAX_SUBSCRIBERS}. */
|
|
91
|
+
maxSubscribersPerConversation?: number;
|
|
92
|
+
/**
|
|
93
|
+
* Characters of the in-progress reply kept per conversation so a subscriber that attaches (or
|
|
94
|
+
* reconnects) mid-stream can be caught up with {@link ConversationHub.partialOf}. 0 disables it.
|
|
95
|
+
* Default 65 536; beyond it the head of the partial is dropped (the catch-up is a convenience, the
|
|
96
|
+
* durable reply is the record).
|
|
97
|
+
*/
|
|
98
|
+
maxPartialChars?: number;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** The reasoning a conversation's model call has streamed so far (ADR 0133 D6). Same bound and lifetime as {@link PartialReply}. */
|
|
102
|
+
export interface PartialReasoning {
|
|
103
|
+
turn: number;
|
|
104
|
+
text: string;
|
|
105
|
+
/** Shared mode: whose turn it is. For that viewer alone, always. */
|
|
106
|
+
asker?: string;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** The reply a conversation is streaming right now. */
|
|
110
|
+
export interface PartialReply {
|
|
111
|
+
turn: number;
|
|
112
|
+
text: string;
|
|
113
|
+
/** Shared mode: whose turn it is. The partial is for that viewer alone until the turn is classified. */
|
|
114
|
+
asker?: string;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
interface Partial {
|
|
118
|
+
turn: number;
|
|
119
|
+
run: number;
|
|
120
|
+
text: string;
|
|
121
|
+
/** In-progress reasoning (ADR 0133 D6): superseded with the reply when the turn's durable message lands, cleared by a re-run. */
|
|
122
|
+
reasoning: string;
|
|
123
|
+
asker?: string;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export class ConversationHub {
|
|
127
|
+
private readonly subs = new Map<string, Set<(event: LiveEvent) => void>>();
|
|
128
|
+
/** The reply each conversation is streaming: also what tells a RE-RUN of a turn (a different run) from its continuation. Bounded to live turns. */
|
|
129
|
+
private readonly partials = new Map<string, Partial>();
|
|
130
|
+
private readonly max: number;
|
|
131
|
+
private readonly maxPartial: number;
|
|
132
|
+
|
|
133
|
+
constructor(options: ConversationHubOptions = {}) {
|
|
134
|
+
this.max = options.maxSubscribersPerConversation ?? DEFAULT_MAX_SUBSCRIBERS;
|
|
135
|
+
this.maxPartial = options.maxPartialChars ?? 65_536;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Attach a listener to ONE conversation. Events of other conversations are never delivered to it
|
|
140
|
+
* (the map is keyed by id; there is no wildcard). A throwing listener is isolated.
|
|
141
|
+
*/
|
|
142
|
+
subscribe(conversationId: string, listener: (event: LiveEvent) => void): () => void {
|
|
143
|
+
let set = this.subs.get(conversationId);
|
|
144
|
+
if (set === undefined) {
|
|
145
|
+
set = new Set();
|
|
146
|
+
this.subs.set(conversationId, set);
|
|
147
|
+
}
|
|
148
|
+
if (set.size >= this.max) throw new SubscriberLimitError(conversationId, this.max);
|
|
149
|
+
set.add(listener);
|
|
150
|
+
return () => {
|
|
151
|
+
const cur = this.subs.get(conversationId);
|
|
152
|
+
if (cur === undefined) return;
|
|
153
|
+
cur.delete(listener);
|
|
154
|
+
if (cur.size === 0) this.subs.delete(conversationId);
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
subscriberCount(conversationId: string): number {
|
|
159
|
+
return this.subs.get(conversationId)?.size ?? 0;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** What the conversation has streamed of the reply in progress, if one is. Read it right after {@link subscribe}. */
|
|
163
|
+
partialOf(conversationId: string): PartialReply | undefined {
|
|
164
|
+
const p = this.partials.get(conversationId);
|
|
165
|
+
return p === undefined || p.text === ""
|
|
166
|
+
? undefined
|
|
167
|
+
: { turn: p.turn, text: p.text, ...(p.asker !== undefined && { asker: p.asker }) };
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** What the turn's model call has streamed of its reasoning, if any. Read it right after {@link subscribe}. */
|
|
171
|
+
reasoningPartialOf(conversationId: string): PartialReasoning | undefined {
|
|
172
|
+
const p = this.partials.get(conversationId);
|
|
173
|
+
return p === undefined || p.reasoning === ""
|
|
174
|
+
? undefined
|
|
175
|
+
: { turn: p.turn, text: p.reasoning, ...(p.asker !== undefined && { asker: p.asker }) };
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
publish(conversationId: string, event: LiveEvent): void {
|
|
179
|
+
const set = this.subs.get(conversationId);
|
|
180
|
+
if (set === undefined) return;
|
|
181
|
+
for (const listener of [...set]) {
|
|
182
|
+
try {
|
|
183
|
+
listener(event);
|
|
184
|
+
} catch {
|
|
185
|
+
// a listener cannot hurt the turn
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** The turn's reply is durable: forget its stream bookkeeping. */
|
|
191
|
+
endTurn(conversationId: string, turn: number): void {
|
|
192
|
+
if (this.partials.get(conversationId)?.turn === turn) this.partials.delete(conversationId);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Wrap a provider so a barge-in CUTS the generation. The turn's abort signal (set by
|
|
197
|
+
* `conversation$` in the turn scope) is merged into every request's `signal`, so a streaming
|
|
198
|
+
* provider stops at the next chunk and its partial text is captured (`LLM_INTERRUPTED`); a
|
|
199
|
+
* request outside a turn scope is passed through untouched. Register the wrapped provider:
|
|
200
|
+
* `createAgentModelEffect(hub.wrapProvider(provider), { stream: true, onDelta: hub.deltaSink() })`.
|
|
201
|
+
* Without it a barge-in still lands, but only at the next checkpoint after the model call returns.
|
|
202
|
+
*/
|
|
203
|
+
wrapProvider(provider: LlmProvider): LlmProvider {
|
|
204
|
+
/** A barge-in landed on THIS request (as opposed to a caller's own abort or a transport failure). */
|
|
205
|
+
const bargedIn = (request: LlmRequest): boolean =>
|
|
206
|
+
scope.getStore()?.signal.aborted === true && request.signal?.aborted !== true;
|
|
207
|
+
const wrapped: LlmProvider = {
|
|
208
|
+
...(provider.capabilities !== undefined && { capabilities: provider.capabilities }),
|
|
209
|
+
complete: async (request) => {
|
|
210
|
+
try {
|
|
211
|
+
await scope.getStore()?.ensure?.();
|
|
212
|
+
return await provider.complete(withTurnSignal(request));
|
|
213
|
+
} catch (err) {
|
|
214
|
+
if (bargedIn(request)) fail(LLM_INTERRUPTED, { content: "" }, "generation interrupted");
|
|
215
|
+
throw err;
|
|
216
|
+
}
|
|
217
|
+
},
|
|
218
|
+
};
|
|
219
|
+
if (provider.stream !== undefined) {
|
|
220
|
+
const stream = provider.stream.bind(provider);
|
|
221
|
+
// The kernel's own capture of a partial (`collectStream`) watches the EFFECT's signal, which a
|
|
222
|
+
// barge-in does not touch; so the wrapper accumulates what it forwards and raises the typed
|
|
223
|
+
// interruption itself, whether the provider honoured the signal or kept on yielding.
|
|
224
|
+
wrapped.stream = async function* (request): AsyncGenerator<LlmStreamChunk> {
|
|
225
|
+
const turn = scope.getStore()?.signal;
|
|
226
|
+
let text = "";
|
|
227
|
+
try {
|
|
228
|
+
await scope.getStore()?.ensure?.();
|
|
229
|
+
for await (const chunk of stream(withTurnSignal(request))) {
|
|
230
|
+
if (turn?.aborted === true && request.signal?.aborted !== true) {
|
|
231
|
+
fail(LLM_INTERRUPTED, { content: text }, "generation interrupted");
|
|
232
|
+
}
|
|
233
|
+
text += chunk.delta;
|
|
234
|
+
yield chunk;
|
|
235
|
+
}
|
|
236
|
+
} catch (err) {
|
|
237
|
+
if (bargedIn(request)) fail(LLM_INTERRUPTED, { content: text }, "generation interrupted");
|
|
238
|
+
throw err;
|
|
239
|
+
}
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
return wrapped;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* The `onDelta` to register on the model effect:
|
|
247
|
+
* `createAgentModelEffect(provider, { stream: true, onDelta: hub.deltaSink() })`.
|
|
248
|
+
*
|
|
249
|
+
* It attributes each delta to the conversation turn whose body is running the call (an
|
|
250
|
+
* AsyncLocalStorage scope set by `conversation$`), so ONE shared effect serves every
|
|
251
|
+
* conversation without crossing their streams. A delta outside any turn scope (a call that did not
|
|
252
|
+
* come from a conversation, or an effect running in another process) has no conversation and is
|
|
253
|
+
* dropped, never broadcast. No subscriber means no work.
|
|
254
|
+
*/
|
|
255
|
+
deltaSink(): (delta: string) => void {
|
|
256
|
+
return (delta: string) => {
|
|
257
|
+
const s = scope.getStore();
|
|
258
|
+
if (s === undefined || delta === "") return;
|
|
259
|
+
const part = this.partialFor(s);
|
|
260
|
+
if (this.maxPartial > 0) {
|
|
261
|
+
const text = part.text + delta;
|
|
262
|
+
part.text =
|
|
263
|
+
text.length > this.maxPartial ? text.slice(text.length - this.maxPartial) : text;
|
|
264
|
+
}
|
|
265
|
+
this.publish(s.conversationId, {
|
|
266
|
+
type: "delta",
|
|
267
|
+
conversationId: s.conversationId,
|
|
268
|
+
turn: s.turn,
|
|
269
|
+
text: delta,
|
|
270
|
+
...(s.asker !== undefined && { asker: s.asker }),
|
|
271
|
+
});
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* ADR 0133 D6 - the live reasoning sink, for the model effect's reasoning option:
|
|
277
|
+
* `createAgentModelEffect(provider, { reasoning: { store, live: true, onDelta: hub.reasoningSink() } })`.
|
|
278
|
+
* Attributed to the turn exactly as {@link deltaSink} is, kept in a bounded in-progress buffer (the
|
|
279
|
+
* same cap as the reply, head dropped) and published as `reasoning` events. This is the transport
|
|
280
|
+
* edge: the increment arrives wrapped as untrusted content and is unwrapped HERE, into the buffer and
|
|
281
|
+
* the event, which a transport must serve to the turn's asker and the conversation's owner alone.
|
|
282
|
+
*/
|
|
283
|
+
reasoningSink(): (delta: TaintedValue<string>) => void {
|
|
284
|
+
return (wrapped: TaintedValue<string>) => {
|
|
285
|
+
const s = scope.getStore();
|
|
286
|
+
const delta = unwrapTainted(wrapped);
|
|
287
|
+
if (s === undefined || delta === "") return;
|
|
288
|
+
const part = this.partialFor(s);
|
|
289
|
+
if (this.maxPartial > 0) {
|
|
290
|
+
const text = part.reasoning + delta;
|
|
291
|
+
part.reasoning =
|
|
292
|
+
text.length > this.maxPartial ? text.slice(text.length - this.maxPartial) : text;
|
|
293
|
+
}
|
|
294
|
+
this.publish(s.conversationId, {
|
|
295
|
+
type: "reasoning",
|
|
296
|
+
conversationId: s.conversationId,
|
|
297
|
+
turn: s.turn,
|
|
298
|
+
text: delta,
|
|
299
|
+
...(s.asker !== undefined && { asker: s.asker }),
|
|
300
|
+
});
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* The in-progress entry of the running turn, created on its first delta. A different RUN of the same
|
|
306
|
+
* turn (a crash-recovered process asked the model again) supersedes it - text AND reasoning - with ONE
|
|
307
|
+
* `reset`, whichever channel notices first.
|
|
308
|
+
*/
|
|
309
|
+
private partialFor(s: TurnScope): Partial {
|
|
310
|
+
const cur = this.partials.get(s.conversationId);
|
|
311
|
+
if (cur !== undefined && cur.turn === s.turn && cur.run === s.run) return cur;
|
|
312
|
+
if (cur !== undefined && cur.turn === s.turn) {
|
|
313
|
+
// The same turn, a different run: a crash-recovered process asked the model again.
|
|
314
|
+
this.publish(s.conversationId, {
|
|
315
|
+
type: "reset",
|
|
316
|
+
conversationId: s.conversationId,
|
|
317
|
+
turn: s.turn,
|
|
318
|
+
...(s.asker !== undefined && { asker: s.asker }),
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
if (cur === undefined && this.partials.size >= MAX_TRACKED_TURNS) {
|
|
322
|
+
// Bounded: a turn that finished in another process never calls `endTurn` here.
|
|
323
|
+
const oldest = this.partials.keys().next().value;
|
|
324
|
+
if (oldest !== undefined) this.partials.delete(oldest);
|
|
325
|
+
}
|
|
326
|
+
const part: Partial = {
|
|
327
|
+
turn: s.turn,
|
|
328
|
+
run: s.run,
|
|
329
|
+
text: "",
|
|
330
|
+
reasoning: "",
|
|
331
|
+
...(s.asker !== undefined && { asker: s.asker }),
|
|
332
|
+
};
|
|
333
|
+
this.partials.set(s.conversationId, part);
|
|
334
|
+
return part;
|
|
335
|
+
}
|
|
336
|
+
}
|
package/src/ids.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/** The conversation id of an execution id: generations are `<chainId>~<n>` (ADR 0109 D2). */
|
|
2
|
+
export function conversationIdOf(executionId: string): string {
|
|
3
|
+
const i = executionId.indexOf("~");
|
|
4
|
+
return i < 0 ? executionId : executionId.slice(0, i);
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
/** The execution id of generation `g` of conversation `conversationId`. */
|
|
8
|
+
export function generationId(conversationId: string, g: number): string {
|
|
9
|
+
return g === 0 ? conversationId : `${conversationId}~${g}`;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** The generation number of an execution id of the chain (`0` for the first). */
|
|
13
|
+
export function generationOf(executionId: string): number {
|
|
14
|
+
const i = executionId.indexOf("~");
|
|
15
|
+
if (i < 0) return 0;
|
|
16
|
+
const n = Number(executionId.slice(i + 1));
|
|
17
|
+
return Number.isSafeInteger(n) && n >= 0 ? n : 0;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
|
|
21
|
+
|
|
22
|
+
/** A caller-chosen conversation id: no `~` (generation separator), no `::` (child separator), no reserved prefix. */
|
|
23
|
+
export function isValidConversationId(id: string): boolean {
|
|
24
|
+
return ID.test(id) && !id.startsWith("__loom_");
|
|
25
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
export { followConversation } from "./feed";
|
|
2
|
+
export type { FeedItem, FollowDeps, FollowOptions } from "./feed";
|
|
3
|
+
export { inboxBargeIn, pendingInbox } from "./bargeIn";
|
|
4
|
+
export type { BargeInHandlers, BargeInSource, StoredInboxMessage } from "./bargeIn";
|
|
5
|
+
export { InvalidEnvelopeError, signInboxEnvelope } from "./signEnvelope";
|
|
6
|
+
export type { InboxEnvelopeBody } from "./signEnvelope";
|
|
7
|
+
export { conversation$, conversationRunner } from "./conversation";
|
|
8
|
+
export type { ConversationFlow, ConversationFlowOptions } from "./conversation";
|
|
9
|
+
export {
|
|
10
|
+
MAX_PARTICIPANTS,
|
|
11
|
+
ParticipantLimitError,
|
|
12
|
+
identityKey,
|
|
13
|
+
identityOf,
|
|
14
|
+
logParticipants,
|
|
15
|
+
parseIdentity,
|
|
16
|
+
sameIdentity,
|
|
17
|
+
senderKey,
|
|
18
|
+
} from "./access";
|
|
19
|
+
export type { Identity, ParticipantChange, ParticipantDirectory } from "./access";
|
|
20
|
+
export { registerSharedTurnEffect, sharedTurnEffect, turnExecutionId } from "./turn";
|
|
21
|
+
export type { TurnInput, TurnResult } from "./turn";
|
|
22
|
+
export {
|
|
23
|
+
ConversationNotFoundError,
|
|
24
|
+
InvalidTurnError,
|
|
25
|
+
QueueFullError,
|
|
26
|
+
createConversations,
|
|
27
|
+
} from "./conversations";
|
|
28
|
+
export type {
|
|
29
|
+
CallOptions,
|
|
30
|
+
Conversations,
|
|
31
|
+
ConversationsDeps,
|
|
32
|
+
ConversationState,
|
|
33
|
+
ConversationStatus,
|
|
34
|
+
SendTurnOptions,
|
|
35
|
+
} from "./conversations";
|
|
36
|
+
export {
|
|
37
|
+
ContextBudgetError,
|
|
38
|
+
fitToWindow,
|
|
39
|
+
fitWithSummaryFallback,
|
|
40
|
+
heuristicTokenCounter,
|
|
41
|
+
truncateToTokens,
|
|
42
|
+
} from "./budget";
|
|
43
|
+
export type { BudgetRequest, BudgetTurn, BudgetVerdict, TokenCounter } from "./budget";
|
|
44
|
+
export {
|
|
45
|
+
ConversationHub,
|
|
46
|
+
DEFAULT_MAX_SUBSCRIBERS,
|
|
47
|
+
SubscriberLimitError,
|
|
48
|
+
withTurnScope,
|
|
49
|
+
} from "./hub";
|
|
50
|
+
export type { ConversationHubOptions, LiveEvent, PartialReasoning, PartialReply } from "./hub";
|
|
51
|
+
export {
|
|
52
|
+
InvalidCursorError,
|
|
53
|
+
createConversationReader,
|
|
54
|
+
findHeadGeneration,
|
|
55
|
+
formatCursor,
|
|
56
|
+
parseCursor,
|
|
57
|
+
} from "./reader";
|
|
58
|
+
export type { ConversationReader, Position, ReadOptions, ReadResult } from "./reader";
|
|
59
|
+
export { conversationIdOf, generationId, generationOf, isValidConversationId } from "./ids";
|
|
60
|
+
export { SUMMARIZER_TEXT_TRUNCATED, summarizerText } from "./summarizerText";
|
|
61
|
+
export { turnSettledObserver } from "./settled";
|
|
62
|
+
export type { TurnSettledEvent, TurnSettledListener } from "./settled";
|
|
63
|
+
export { CONVERSATION_TOPIC, RECORD_SOURCE, SUMMARY_ORIGIN, USER_ORIGIN } from "./types";
|
|
64
|
+
export type {
|
|
65
|
+
BudgetConfig,
|
|
66
|
+
CarriedTurn,
|
|
67
|
+
ConversationCarry,
|
|
68
|
+
ConversationConfig,
|
|
69
|
+
ConversationResult,
|
|
70
|
+
HistoryEntry,
|
|
71
|
+
MessageRecord,
|
|
72
|
+
MessageStatus,
|
|
73
|
+
SharedConfig,
|
|
74
|
+
TurnEnvelope,
|
|
75
|
+
} from "./types";
|