@theoremjs/web 0.3.5-next.1012.g714018f → 0.3.5-next.1013.g9b838d0
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/README.md +27 -1
- package/client/chat.js +98 -2
- package/client/index.d.ts +1 -1
- package/client/transport.d.ts +13 -0
- package/client/transport.js +6 -0
- package/package.json +2 -2
- package/server/conversation-core.d.ts +13 -0
- package/server/conversation-core.js +122 -7
- package/server/create-conversation-core.d.ts +1 -1
- package/server/create-conversation-core.js +1 -0
- package/server/handler.d.ts +10 -1
- package/server/handler.js +22 -1
- package/server/mod.d.ts +2 -1
- package/server/mod.js +2 -1
- package/server/reply-feed.d.ts +41 -0
- package/server/reply-feed.js +48 -0
package/README.md
CHANGED
|
@@ -295,6 +295,7 @@ const transport = withPageToolDispatch(
|
|
|
295
295
|
| `onContinue` | Who runs the next reply when a reply ends with items that wait and may be told now. Return `'here'`, and the handler runs it in the same response. Return `'taken'`, and your app runs it with the conversation core's `followUp`. Unset, the handler lets the chat go, and the page wakes it. |
|
|
296
296
|
| `intake` | Your app's own save of each message the page sends, on `/turn` and `/steer`. Set it when a message must be in your database before any reply runs. Needs `inbox`. See [Save a page's message in your own write](#save-a-pages-message-in-your-own-write). |
|
|
297
297
|
| `notifier`, `notifyRetryMs` | Tell an open page that a background call ended, and how long the page waits to reopen a cut stream. Unset, the page reads the end on its next turn or reload. See [the background section](#share-session-authority). |
|
|
298
|
+
| `replyFeed` | Lets every page open on a conversation draw a running reply's lines live, whoever started it. Needs `notifier`. Unset, a page that did not start the reply reads it once it ends. See [Follow a running reply](#follow-a-running-reply). |
|
|
298
299
|
| `credentialStore` | Where tool credentials are kept, by session. Default: process memory. |
|
|
299
300
|
| `authorizationUrl` | Returns the sign-in URL for an OAuth gate. Without it, an OAuth gate has no URL. |
|
|
300
301
|
| `gateTtlMs` | How long a gate waits for an answer. A later answer fails with `session.gate_expired`, and the next message or the next wake cancels the call. Unset, a gate waits until it is answered. |
|
|
@@ -560,7 +561,7 @@ async function received(sessionId: string, text: string, ref: string | undefined
|
|
|
560
561
|
| `steer(at, { turnId, id, input })` | Puts `input` into a running turn. Returns `false` when the turn is not running. Throws what `message` throws for an `input` the profile does not take, such as text over `inputs.maxTextChars`. |
|
|
561
562
|
| `stop(at, { turnId } \| { conversation })` | Stops a running reply: the turn `turnId` names, or the reply that holds `conversation`. Returns `false` when it is not running. When your `inbox` has a `stop`, it stops the reply that holds the conversation, and reads neither. Without one, only `{ turnId }` reaches a turn, and `{ conversation }` throws `session.reply_unreachable`. |
|
|
562
563
|
|
|
563
|
-
The core takes these options from [Server options](#server-options), with the same meaning: `profile`, `onStage`, `sessionStore`, `conversationStore`, `credentialStore`, `gateTtlMs`, `operationRetentionMs`, `pageToolBroker`, `pageToolTimeoutMs`, `notifier`, `notifyRetryMs`, `lateResultsDecider`, `conversationLeaseMs`, `steerInbox`, and `clientEvents`. These options take the run context in place of the `Request`:
|
|
564
|
+
The core takes these options from [Server options](#server-options), with the same meaning: `profile`, `onStage`, `sessionStore`, `conversationStore`, `credentialStore`, `gateTtlMs`, `operationRetentionMs`, `pageToolBroker`, `pageToolTimeoutMs`, `notifier`, `notifyRetryMs`, `replyFeed`, `lateResultsDecider`, `conversationLeaseMs`, `steerInbox`, and `clientEvents`. These options take the run context in place of the `Request`:
|
|
564
565
|
|
|
565
566
|
| Option | Use |
|
|
566
567
|
| --- | --- |
|
|
@@ -692,6 +693,31 @@ The page reads again at `heldUntil` once for each `heldUntil`. When your server'
|
|
|
692
693
|
|
|
693
694
|
Call `notifier.publish` after each save that ends the reply. The page reads the conversation again. When `running` is gone, the queue sends its next message, unless the person stopped the reply.
|
|
694
695
|
|
|
696
|
+
### Follow a running reply
|
|
697
|
+
|
|
698
|
+
A page open on a conversation draws a reply that another page started, or that your app runs with no page request, as it happens: the steps, the pill and the words. Pass `replyFeed` with `notifier` to `createTheoremHandler` or `createTheoremConversationCore`. Without `notifier`, the setup fails with a `config` error.
|
|
699
|
+
|
|
700
|
+
```ts
|
|
701
|
+
import { createMemoryNotifier, createMemoryReplyFeed } from '@theoremjs/web/server';
|
|
702
|
+
|
|
703
|
+
createTheoremHandler({
|
|
704
|
+
// ...
|
|
705
|
+
notifier: createMemoryNotifier(),
|
|
706
|
+
replyFeed: createMemoryReplyFeed(),
|
|
707
|
+
});
|
|
708
|
+
```
|
|
709
|
+
|
|
710
|
+
Every reply that runs under a hold writes each of its lines to the feed, and calls `notifier.publish(sessionId)` when it starts and when it ends. This covers a message, an answer, a wake and a follow-up, from a page or from the core. The conversation read says `follow: true`, and a page that sees `running` and has no reply of its own posts `POST <base>/follow` with `{ conversation }`. The stream is the line stream of `/turn`, with the same `tools.showData` filter. It starts from the first line of the reply, so a page that joins late draws the whole reply, and ends with the reply. The page then reads the conversation as before. Stop and steer by conversation work as they do for any reply the page did not start. The chat draws the followed reply with the same `streaming` state as its own, so no host switch is added.
|
|
711
|
+
|
|
712
|
+
`TheoremReplyFeed` is yours to implement:
|
|
713
|
+
|
|
714
|
+
- `start(conversation, reply)` opens a reply. It replaces the earlier reply of that conversation, and ends that reply's followers.
|
|
715
|
+
- `append(conversation, reply, line)` adds a line.
|
|
716
|
+
- `end(conversation, reply)` closes it and ends its followers.
|
|
717
|
+
- `follow(conversation, listener)` calls `listener.line` with every line so far, then each new line, then `listener.end`. With no reply open, it calls `end` at once. It returns the function that stops the listening.
|
|
718
|
+
|
|
719
|
+
`conversation` is the conversation's id, which stays the same across writes, where the reference changes. Theorem sets no size, retention or timing. `createMemoryReplyFeed` keeps every line of the current reply of each conversation in the process, with no cap, and reaches only the pages of that process. On more than one instance, give a shared `TheoremReplyFeed`. A feed that throws never changes the reply: the error goes to `onError`. `running` is the store's, as in [the section on a running reply](#share-session-authority): the feed does not set it. Without `running`, the page does not follow.
|
|
720
|
+
|
|
695
721
|
### Shape the save that ends a reply
|
|
696
722
|
|
|
697
723
|
Use `beforeSave` when your app keeps each block as its own record, and must decide what a reply writes. The core calls it once for each save that ends a reply, before the store's `write`.
|
package/client/chat.js
CHANGED
|
@@ -7,7 +7,7 @@ import { clientFailure, turnFailure } from "./failure.js";
|
|
|
7
7
|
import { followGenerationDefaults } from "./generation-selection.js";
|
|
8
8
|
import { warnPageToolMismatch } from "./live/live-page-tool.js";
|
|
9
9
|
import { withPageToolDispatch } from "./page-dispatch.js";
|
|
10
|
-
import { sessionAfter, stampWorked, stoppedReply } from "./run-commit.js";
|
|
10
|
+
import { sessionAfter, stampWorked, stoppedReply, streamFoldedTurn } from "./run-commit.js";
|
|
11
11
|
import { extractInlineEncodedAttachments, keepsConversation, resumeInterfaceTool, streamInterfaceDraftTurn, streamInterfaceTurn, streamInterfaceWake, } from "./run-session.js";
|
|
12
12
|
import { isTurnEnded, isUnknownConversation, } from "./transport.js";
|
|
13
13
|
import { foldAssistantTurn, issuedOperationId } from "./turn-client.js";
|
|
@@ -133,6 +133,12 @@ class Chat {
|
|
|
133
133
|
/** What the last view said about the host's push; unset, nothing is listened for. */
|
|
134
134
|
#notify;
|
|
135
135
|
#listening = null;
|
|
136
|
+
/** The reply that runs elsewhere, as this page draws it from the host's lines. */
|
|
137
|
+
#following = null;
|
|
138
|
+
/** The `since` of the last reply whose lines this page began to read: one read of each reply. */
|
|
139
|
+
#followedSince = null;
|
|
140
|
+
/** The last view said the host streams the lines of a reply that runs elsewhere. */
|
|
141
|
+
#followOffered = false;
|
|
136
142
|
/** The last view said results wait that no reply has read: the chat wakes once it is idle. */
|
|
137
143
|
#wakeDue = false;
|
|
138
144
|
/** The ids a reply names the run's message by, once the host said it saved the message itself. */
|
|
@@ -183,10 +189,12 @@ class Chat {
|
|
|
183
189
|
}
|
|
184
190
|
this.#followPush();
|
|
185
191
|
this.#followHold();
|
|
192
|
+
this.#followReply();
|
|
186
193
|
return () => {
|
|
187
194
|
this.#listeners.delete(listener);
|
|
188
195
|
this.#followPush();
|
|
189
196
|
this.#followHold();
|
|
197
|
+
this.#followReply();
|
|
190
198
|
};
|
|
191
199
|
};
|
|
192
200
|
refresh = () => {
|
|
@@ -271,6 +279,86 @@ class Chat {
|
|
|
271
279
|
void this.refresh();
|
|
272
280
|
}, Math.max(0, running.heldUntil - Date.now()));
|
|
273
281
|
}
|
|
282
|
+
/**
|
|
283
|
+
* Draws the reply that runs elsewhere from the host's lines, while someone is here to see it:
|
|
284
|
+
* the same reducer the page that started it uses. It stays `runningElsewhere`, so stop and steer
|
|
285
|
+
* go by the conversation. The host ends the lines with the reply, and the page reads the saved
|
|
286
|
+
* conversation then.
|
|
287
|
+
*/
|
|
288
|
+
#followReply() {
|
|
289
|
+
const running = this.#state.runningElsewhere;
|
|
290
|
+
const { iface, transport } = this.#options;
|
|
291
|
+
const wanted = running !== null &&
|
|
292
|
+
this.#followOffered &&
|
|
293
|
+
this.#listeners.size > 0 &&
|
|
294
|
+
!this.#busy &&
|
|
295
|
+
iface !== undefined &&
|
|
296
|
+
transport.follow !== undefined;
|
|
297
|
+
const current = this.#following;
|
|
298
|
+
if (current && (!wanted || current.since !== running.since)) {
|
|
299
|
+
this.#following = null;
|
|
300
|
+
current.abort.abort();
|
|
301
|
+
this.#endFollow();
|
|
302
|
+
}
|
|
303
|
+
if (!wanted || this.#following || this.#followedSince === running.since)
|
|
304
|
+
return;
|
|
305
|
+
const ref = this.#conversation;
|
|
306
|
+
if (ref === undefined)
|
|
307
|
+
return;
|
|
308
|
+
const following = {
|
|
309
|
+
since: running.since,
|
|
310
|
+
abort: new AbortController(),
|
|
311
|
+
prompt: running.prompt,
|
|
312
|
+
partial: [],
|
|
313
|
+
};
|
|
314
|
+
this.#following = following;
|
|
315
|
+
void this.#streamFollowed(following, ref);
|
|
316
|
+
}
|
|
317
|
+
async #streamFollowed(following, ref) {
|
|
318
|
+
const { iface, transport } = this.#options;
|
|
319
|
+
if (!iface || !transport.follow)
|
|
320
|
+
return;
|
|
321
|
+
const follow = transport.follow.bind(transport);
|
|
322
|
+
let lines = 0;
|
|
323
|
+
try {
|
|
324
|
+
await streamFoldedTurn({
|
|
325
|
+
iface,
|
|
326
|
+
events: [],
|
|
327
|
+
view: {
|
|
328
|
+
blocks: (partial) => {
|
|
329
|
+
if (this.#following !== following)
|
|
330
|
+
return;
|
|
331
|
+
lines += 1;
|
|
332
|
+
this.#followedSince = following.since;
|
|
333
|
+
following.partial = partial;
|
|
334
|
+
if (!this.#state.streaming)
|
|
335
|
+
this.#set({ streaming: true });
|
|
336
|
+
this.#streamFrame([...following.prompt, ...partial]);
|
|
337
|
+
},
|
|
338
|
+
skipped: (error) => this.#set({ failure: clientFailure(error, iface.labels) }),
|
|
339
|
+
},
|
|
340
|
+
stream: (onLine) => follow({ conversation: ref }, onLine, following.abort.signal),
|
|
341
|
+
});
|
|
342
|
+
}
|
|
343
|
+
catch {
|
|
344
|
+
// why: A cut follow leaves the page as the last read drew it; the next read shows where the reply stands.
|
|
345
|
+
}
|
|
346
|
+
if (this.#following !== following)
|
|
347
|
+
return;
|
|
348
|
+
this.#following = null;
|
|
349
|
+
this.#endFollow();
|
|
350
|
+
// why: A host with no reply to follow yet (it began a moment later) says nothing has changed; its push says when.
|
|
351
|
+
if (lines > 0 && !following.abort.signal.aborted)
|
|
352
|
+
void this.refresh();
|
|
353
|
+
}
|
|
354
|
+
/** Nothing follows: the frame in flight is dropped or drawn, and the reply no longer shows as streaming. */
|
|
355
|
+
#endFollow() {
|
|
356
|
+
this.#frame?.();
|
|
357
|
+
this.#frame = null;
|
|
358
|
+
this.#frameBlocks = null;
|
|
359
|
+
if (this.#state.streaming)
|
|
360
|
+
this.#set({ streaming: false });
|
|
361
|
+
}
|
|
274
362
|
async #listen(listening) {
|
|
275
363
|
const { signal } = listening;
|
|
276
364
|
while (!signal.aborted) {
|
|
@@ -679,19 +767,27 @@ class Chat {
|
|
|
679
767
|
const after = view.paused?.blocks ?? view.running?.prompt ?? [];
|
|
680
768
|
const drawn = [...view.transcript, ...after].map((block) => block.id);
|
|
681
769
|
const ended = this.#state.runningElsewhere !== null && view.running === undefined;
|
|
770
|
+
if (this.#following && view.running?.since === this.#following.since) {
|
|
771
|
+
this.#following.prompt = view.running.prompt;
|
|
772
|
+
}
|
|
682
773
|
this.#set({
|
|
683
774
|
// why: A saved message the conversation now shows is no longer waiting.
|
|
684
775
|
pendingMessages: takeSavedComposerPending(this.#state.pendingMessages, drawn).remaining,
|
|
685
776
|
blocks,
|
|
686
|
-
|
|
777
|
+
// why: A reply this page follows draws from the host's lines, over the prompt as the read now shows it.
|
|
778
|
+
streamBlocks: this.#following && view.running?.since === this.#following.since
|
|
779
|
+
? [...view.running.prompt, ...this.#following.partial]
|
|
780
|
+
: keepIds(shown.slice(blocks.length), after),
|
|
687
781
|
// why: A reply at rest leaves the run's own events (tokens, an ask); a paused one, the host's.
|
|
688
782
|
session: this.#sessionAfter(session, view.paused?.events ?? events),
|
|
689
783
|
chatStarted: view.transcript.length > 0 || after.length > 0 || view.running !== undefined,
|
|
690
784
|
runningElsewhere: view.running ?? null,
|
|
691
785
|
});
|
|
692
786
|
this.#wakeDue = view.wake === true;
|
|
787
|
+
this.#followOffered = view.follow === true;
|
|
693
788
|
this.#setPush(view.notify);
|
|
694
789
|
this.#followHold();
|
|
790
|
+
this.#followReply();
|
|
695
791
|
// why: The reply that ran elsewhere ended as a reply here ends: the queue sends on, unless it was stopped.
|
|
696
792
|
if (ended && !this.#busy) {
|
|
697
793
|
this.#runEnded(!this.#stopped);
|
package/client/index.d.ts
CHANGED
|
@@ -33,5 +33,5 @@ export { hasLead, layoutResult, type ResultChart, type ResultFigure, type Result
|
|
|
33
33
|
export type { AnsweringGate, ToolDecisionAction, ToolGateResolution, } from './tool-resume.ts';
|
|
34
34
|
export { continueGatedToolInvocation, type PersonGateResolution } from './tool-resume.ts';
|
|
35
35
|
export { createTraceFeed, recordedFeed, type TraceFeed } from './trace-feed.ts';
|
|
36
|
-
export { CHAT_LINES, type ChatLine, type ChatLineSink, type ClientTurnEvent, type ConversationLine, type ConversationView, createHttpTransport, fetchConversation, fetchRewound, fetchStarted, type HostErrorBody, type HttpOptions, type HttpTransportOptions, hostError, isTheoremStreamError, type MalformedEvent, type NotifyLine, postJson, postNdjson, type RunningReply, readNdjsonStream, type StatedTurn, type TheoremConversationRequest, type TheoremInvokeRequest, type TheoremReplay, type TheoremRewindRequest, type TheoremRewound, type TheoremSavedMessage, type TheoremStartRequest, type TheoremSteerReply, type TheoremSteerRequest, type TheoremStopRequest, TheoremStreamError, type TheoremTransport, type TheoremTurnInput, type TheoremTurnRequest, type TheoremWakeRequest, type TurnEventSink, type UnsupportedEvent, type WireLines, } from './transport.ts';
|
|
36
|
+
export { CHAT_LINES, type ChatLine, type ChatLineSink, type ClientTurnEvent, type ConversationLine, type ConversationView, createHttpTransport, fetchConversation, fetchRewound, fetchStarted, type HostErrorBody, type HttpOptions, type HttpTransportOptions, hostError, isTheoremStreamError, type MalformedEvent, type NotifyLine, postJson, postNdjson, type RunningReply, readNdjsonStream, type StatedTurn, type TheoremConversationRequest, type TheoremFollowRequest, type TheoremInvokeRequest, type TheoremReplay, type TheoremRewindRequest, type TheoremRewound, type TheoremSavedMessage, type TheoremStartRequest, type TheoremSteerReply, type TheoremSteerRequest, type TheoremStopRequest, TheoremStreamError, type TheoremTransport, type TheoremTurnInput, type TheoremTurnRequest, type TheoremWakeRequest, type TurnEventSink, type UnsupportedEvent, type WireLines, } from './transport.ts';
|
|
37
37
|
export { buildInvokeRequest, buildTurnRequest, foldAssistantTurn, issuedOperationId, type RunScope, type WalkAway, } from './turn-client.ts';
|
package/client/transport.d.ts
CHANGED
|
@@ -219,6 +219,8 @@ export type ConversationView = {
|
|
|
219
219
|
notify?: {
|
|
220
220
|
retryMs?: number;
|
|
221
221
|
};
|
|
222
|
+
/** The host streams the lines of a reply that runs elsewhere (`transport.follow`). */
|
|
223
|
+
follow?: true;
|
|
222
224
|
/** Results wait that no reply has read: the page wakes the conversation (`transport.wake`). */
|
|
223
225
|
wake?: true;
|
|
224
226
|
};
|
|
@@ -228,6 +230,12 @@ export type TheoremConversationRequest = {
|
|
|
228
230
|
};
|
|
229
231
|
/** A `/conversation` body as `createTheoremHandler` reads it. */
|
|
230
232
|
export declare const theoremConversationRequestSchema: z.ZodType<TheoremConversationRequest>;
|
|
233
|
+
/** Follow the reply that runs on a conversation now: a `/follow` body. */
|
|
234
|
+
export type TheoremFollowRequest = {
|
|
235
|
+
conversation: string;
|
|
236
|
+
};
|
|
237
|
+
/** A `/follow` body as `createTheoremHandler` reads it. */
|
|
238
|
+
export declare const theoremFollowRequestSchema: z.ZodType<TheoremFollowRequest>;
|
|
231
239
|
/**
|
|
232
240
|
* Wake the conversation: the model takes up the results of its background calls that ended and it
|
|
233
241
|
* has not read, in a reply to no message. A `/wake` body. The host does nothing when no result
|
|
@@ -291,6 +299,11 @@ export interface TheoremTransport {
|
|
|
291
299
|
conversation(request: TheoremConversationRequest, signal?: AbortSignal): Promise<ConversationView>;
|
|
292
300
|
/** Calls `changed` for each line of the host's push, and settles when the push ends. */
|
|
293
301
|
notify?(changed: () => void, signal: AbortSignal): Promise<void>;
|
|
302
|
+
/**
|
|
303
|
+
* Streams the lines of the reply that runs on the conversation now, whoever started it, from its
|
|
304
|
+
* first line until it ends. No line at all when none runs.
|
|
305
|
+
*/
|
|
306
|
+
follow?(request: TheoremFollowRequest, onLine: ChatLineSink, signal?: AbortSignal): Promise<void>;
|
|
294
307
|
/** Streams the reply a wake runs; no line at all when the host had nothing to wake for. */
|
|
295
308
|
wake?(request: TheoremWakeRequest, onLine: ChatLineSink, signal?: AbortSignal): Promise<void>;
|
|
296
309
|
/** The conversation cut after a transcript block, under the ref the host issued for it. */
|
package/client/transport.js
CHANGED
|
@@ -137,6 +137,7 @@ const conversationView = z.object({
|
|
|
137
137
|
.optional(),
|
|
138
138
|
running: runningReply.optional(),
|
|
139
139
|
notify: z.object({ retryMs: z.number().optional() }).optional(),
|
|
140
|
+
follow: z.literal(true).optional(),
|
|
140
141
|
wake: z.literal(true).optional(),
|
|
141
142
|
});
|
|
142
143
|
true;
|
|
@@ -144,6 +145,10 @@ const theoremConversationRequest = z.object({ conversation: z.string().min(1) })
|
|
|
144
145
|
true;
|
|
145
146
|
/** A `/conversation` body as `createTheoremHandler` reads it. */
|
|
146
147
|
export const theoremConversationRequestSchema = theoremConversationRequest;
|
|
148
|
+
const theoremFollowRequest = z.object({ conversation: z.string().min(1) });
|
|
149
|
+
true;
|
|
150
|
+
/** A `/follow` body as `createTheoremHandler` reads it. */
|
|
151
|
+
export const theoremFollowRequestSchema = theoremFollowRequest;
|
|
147
152
|
const theoremWakeRequest = z.object({
|
|
148
153
|
conversation: z.string().min(1),
|
|
149
154
|
input: theoremTurnInput.pick({ options: true, context: true }).optional(),
|
|
@@ -398,6 +403,7 @@ export function createHttpTransport(options = {}) {
|
|
|
398
403
|
invoke: ({ replay: _replay, ...body }, onEvent, signal) => postNdjson(`${base}/invoke`, body, CHAT_LINES, onEvent, { ...options, signal }),
|
|
399
404
|
conversation: (body, signal) => fetchConversation(`${base}/conversation`, body, { ...options, signal }),
|
|
400
405
|
wake: (body, onLine, signal) => postNdjson(`${base}/wake`, body, CHAT_LINES, onLine, { ...options, signal }),
|
|
406
|
+
follow: (body, onLine, signal) => postNdjson(`${base}/follow`, body, CHAT_LINES, onLine, { ...options, signal }),
|
|
401
407
|
notify: (changed, signal) => postNdjson(`${base}/notify`, {}, NOTIFY_LINES, (line) => {
|
|
402
408
|
if (line.type === 'changed')
|
|
403
409
|
changed();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@theoremjs/web",
|
|
3
|
-
"version": "0.3.5-next.
|
|
3
|
+
"version": "0.3.5-next.1013.g9b838d0",
|
|
4
4
|
"description": "Theorem on the web platform, with no UI framework: Web-standard server handlers that serve a profile, and the browser client that talks to them.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -25,6 +25,6 @@
|
|
|
25
25
|
},
|
|
26
26
|
"peerDependencies": {
|
|
27
27
|
"zod": "^4.6.5",
|
|
28
|
-
"@theoremjs/agents": "^0.3.5-next.
|
|
28
|
+
"@theoremjs/agents": "^0.3.5-next.1013.g9b838d0"
|
|
29
29
|
}
|
|
30
30
|
}
|
|
@@ -12,6 +12,7 @@ import { type TranscriptBlock } from '@theoremjs/agents/interface';
|
|
|
12
12
|
import type { ConversationView, StatedTurn, TheoremInvokeRequest, TheoremRewound, TheoremSteerRequest, TheoremStopRequest, TheoremTurnInput } from '../client/transport.ts';
|
|
13
13
|
import { type ReplyLine, type ReplyToSave, type ShapedReply } from './conversation.ts';
|
|
14
14
|
import { type ReplyEnd, type TheoremConversationStore } from './conversation-store.ts';
|
|
15
|
+
import type { TheoremReplyFeed } from './reply-feed.ts';
|
|
15
16
|
import { type CallsContext, type CoreContext } from './session-calls.ts';
|
|
16
17
|
import { type SteerInbox } from './steer-inbox.ts';
|
|
17
18
|
import { type ReplyRefusal } from './turn-wiring.ts';
|
|
@@ -133,6 +134,8 @@ export type ReplyWiring<Item extends InboxItem = InboxItem> = SaveHooks<Item> &
|
|
|
133
134
|
export declare function oneInbox(options: {
|
|
134
135
|
inbox?: unknown;
|
|
135
136
|
lateResultsDecider?: unknown;
|
|
137
|
+
replyFeed?: unknown;
|
|
138
|
+
notifier?: unknown;
|
|
136
139
|
}): void;
|
|
137
140
|
/** Everything a conversation's runs read from whoever serves them. */
|
|
138
141
|
export type CoreState<Item extends InboxItem = InboxItem> = Omit<CallsContext, 'options'> & {
|
|
@@ -142,6 +145,8 @@ export type CoreState<Item extends InboxItem = InboxItem> = Omit<CallsContext, '
|
|
|
142
145
|
provider: (at: CoreContext, model?: string) => ProviderHostOptions | Promise<ProviderHostOptions>;
|
|
143
146
|
conversationLeaseMs?: number;
|
|
144
147
|
notifyRetryMs?: number;
|
|
148
|
+
/** Where a running reply's lines go for the pages that follow it. Needs `notifier`. */
|
|
149
|
+
replyFeed?: TheoremReplyFeed;
|
|
145
150
|
clientEvents?: ClientTurnOptions;
|
|
146
151
|
};
|
|
147
152
|
};
|
|
@@ -262,6 +267,14 @@ export type ConversationCore = {
|
|
|
262
267
|
ref: string;
|
|
263
268
|
at: number;
|
|
264
269
|
}): Promise<TheoremRewound>;
|
|
270
|
+
/**
|
|
271
|
+
* The lines of the reply that runs on the conversation now, whoever started it: from its first
|
|
272
|
+
* line, then each as it comes, until it ends or `at.signal` aborts. Ends at once when no reply
|
|
273
|
+
* runs. Throws `config` without `replyFeed`.
|
|
274
|
+
*/
|
|
275
|
+
follow(at: CoreContext, args: {
|
|
276
|
+
ref: string;
|
|
277
|
+
}): Promise<AsyncGenerator<ReplyLine>>;
|
|
265
278
|
/**
|
|
266
279
|
* Puts a steer into a running turn, as the one user message the model reads. Throws what
|
|
267
280
|
* `message` throws for an input the profile does not take, such as text over its limit, and
|
|
@@ -63,6 +63,10 @@ function chatInterface(chat) {
|
|
|
63
63
|
}
|
|
64
64
|
/** Refuses an app's inbox beside a decider for the session's: one inbox holds what a reply is told. */
|
|
65
65
|
export function oneInbox(options) {
|
|
66
|
+
if (options.replyFeed !== undefined && options.notifier === undefined) {
|
|
67
|
+
// labels-exempt: builder config error; the user reads error.config
|
|
68
|
+
throw new TheoremError('config', '`replyFeed` needs `notifier`: the notifier tells the pages that a reply starts and ends');
|
|
69
|
+
}
|
|
66
70
|
if (options.inbox === undefined || options.lateResultsDecider === undefined)
|
|
67
71
|
return;
|
|
68
72
|
// labels-exempt: builder config error; the user reads error.config
|
|
@@ -283,9 +287,10 @@ function holdingOf(ctx, at, host, opened) {
|
|
|
283
287
|
*/
|
|
284
288
|
function heldLines(ctx, at, host, opened, start, reply) {
|
|
285
289
|
const holding = holdingOf(ctx, at, host, opened);
|
|
290
|
+
const feed = (lines) => fed(ctx, at, opened.conversation.id, lines);
|
|
286
291
|
if (!holding)
|
|
287
|
-
return unheld(reply(undefined, () => opened.ref));
|
|
288
|
-
return sent(async (send) => {
|
|
292
|
+
return feed(unheld(reply(undefined, () => opened.ref)));
|
|
293
|
+
return feed(sent(async (send) => {
|
|
289
294
|
const run = await holding.run(start, (held) => reply(held, holding.ref), send);
|
|
290
295
|
if (run.outcome === 'held')
|
|
291
296
|
return { outcome: 'held', leasedUntil: run.leasedUntil };
|
|
@@ -304,7 +309,109 @@ function heldLines(ctx, at, host, opened, start, reply) {
|
|
|
304
309
|
if (run.failure !== undefined)
|
|
305
310
|
throw run.failure;
|
|
306
311
|
return { outcome: run.outcome === 'lost' ? 'lost' : 'released' };
|
|
312
|
+
}));
|
|
313
|
+
}
|
|
314
|
+
/**
|
|
315
|
+
* `lines`, each also sent to the reply feed under the conversation's id, and the pages told when
|
|
316
|
+
* the reply starts and ends. A reply that yields no line (nothing waited to tell, or the chat
|
|
317
|
+
* was held) starts nothing. The feed's failure goes to `onError`, never into the reply.
|
|
318
|
+
* invariant: The reply ends in the feed however `lines` ends: its end, a throw, or the caller
|
|
319
|
+
* stopping the read, so a follower is never left waiting for a reply that is over.
|
|
320
|
+
*/
|
|
321
|
+
async function* fed(ctx, at, conversation, lines) {
|
|
322
|
+
const { replyFeed: feed, notifier } = ctx.options;
|
|
323
|
+
if (!feed)
|
|
324
|
+
return yield* lines;
|
|
325
|
+
const reply = crypto.randomUUID();
|
|
326
|
+
const tell = async (step) => {
|
|
327
|
+
try {
|
|
328
|
+
await step();
|
|
329
|
+
}
|
|
330
|
+
catch (err) {
|
|
331
|
+
ctx.options.onError?.(err, at);
|
|
332
|
+
}
|
|
333
|
+
};
|
|
334
|
+
let begun = false;
|
|
335
|
+
let over = false;
|
|
336
|
+
try {
|
|
337
|
+
for (;;) {
|
|
338
|
+
const next = await lines.next();
|
|
339
|
+
if (next.done) {
|
|
340
|
+
over = true;
|
|
341
|
+
return next.value;
|
|
342
|
+
}
|
|
343
|
+
if (!begun) {
|
|
344
|
+
begun = true;
|
|
345
|
+
await tell(() => feed.start(conversation, reply));
|
|
346
|
+
await tell(() => notifier?.publish(at.sessionId));
|
|
347
|
+
}
|
|
348
|
+
await tell(() => feed.append(conversation, reply, next.value));
|
|
349
|
+
yield next.value;
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
finally {
|
|
353
|
+
if (!over)
|
|
354
|
+
await lines.return({ outcome: 'released' }).catch(() => undefined);
|
|
355
|
+
if (begun) {
|
|
356
|
+
await tell(() => feed.end(conversation, reply));
|
|
357
|
+
await tell(() => notifier?.publish(at.sessionId));
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
/**
|
|
362
|
+
* The lines of the reply that runs on the conversation under `args.ref`, from its first, then
|
|
363
|
+
* each as it comes, until it ends or `at.signal` aborts. Ends at once when no reply runs.
|
|
364
|
+
*/
|
|
365
|
+
async function follow(ctx, at, args) {
|
|
366
|
+
const feed = ctx.options.replyFeed;
|
|
367
|
+
if (!feed) {
|
|
368
|
+
// labels-exempt: builder config error; the user reads error.config
|
|
369
|
+
throw new TheoremError('config', 'following a reply needs `replyFeed`');
|
|
370
|
+
}
|
|
371
|
+
const host = conversationHost(ctx, at);
|
|
372
|
+
if (!host)
|
|
373
|
+
throw statelessRefusal('follow');
|
|
374
|
+
const opened = await openConversation(host, args.ref, { kind: 'read' });
|
|
375
|
+
const queue = [];
|
|
376
|
+
let over = false;
|
|
377
|
+
let wake = () => { };
|
|
378
|
+
const stop = await feed.follow(opened.conversation.id, {
|
|
379
|
+
line(line) {
|
|
380
|
+
queue.push(line);
|
|
381
|
+
wake();
|
|
382
|
+
},
|
|
383
|
+
end() {
|
|
384
|
+
over = true;
|
|
385
|
+
wake();
|
|
386
|
+
},
|
|
307
387
|
});
|
|
388
|
+
const leave = () => {
|
|
389
|
+
over = true;
|
|
390
|
+
wake();
|
|
391
|
+
};
|
|
392
|
+
if (at.signal.aborted)
|
|
393
|
+
leave();
|
|
394
|
+
else
|
|
395
|
+
at.signal.addEventListener('abort', leave, { once: true });
|
|
396
|
+
return (async function* () {
|
|
397
|
+
try {
|
|
398
|
+
for (;;) {
|
|
399
|
+
if (queue.length > 0) {
|
|
400
|
+
yield queue.splice(0, 1)[0];
|
|
401
|
+
continue;
|
|
402
|
+
}
|
|
403
|
+
if (over)
|
|
404
|
+
return;
|
|
405
|
+
await new Promise((resolve) => {
|
|
406
|
+
wake = resolve;
|
|
407
|
+
});
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
finally {
|
|
411
|
+
at.signal.removeEventListener('abort', leave);
|
|
412
|
+
stop();
|
|
413
|
+
}
|
|
414
|
+
})();
|
|
308
415
|
}
|
|
309
416
|
/**
|
|
310
417
|
* A run, then what `choose` says for each `continue` it and its follow-ups end with. It ends as
|
|
@@ -505,7 +612,7 @@ async function* waiting(waits) {
|
|
|
505
612
|
}
|
|
506
613
|
/**
|
|
507
614
|
* A reply to no message under `held`, on the chat as it stands now. The page that woke draws it;
|
|
508
|
-
* any other page open on the session reads it once it ends.
|
|
615
|
+
* with a `replyFeed`, any other page open on the session follows it, and without one reads it once it ends.
|
|
509
616
|
*/
|
|
510
617
|
async function* wakeReplyLines(ctx, at, host, ref, generation, held, input) {
|
|
511
618
|
if (ref === null)
|
|
@@ -534,18 +641,25 @@ async function* wakeReplyLines(ctx, at, host, ref, generation, held, input) {
|
|
|
534
641
|
async function currentView(ctx, at, host, ref, opened) {
|
|
535
642
|
const { conversation, running } = opened;
|
|
536
643
|
const view = { ...conversationView(host, conversation), ...(running ? { running } : {}) };
|
|
644
|
+
const { replyFeed, inbox } = ctx.options;
|
|
645
|
+
const following = replyFeed ? { follow: true } : {};
|
|
537
646
|
// why: a session's late results come from detached calls only, ended or not; an app's items come from anywhere
|
|
538
|
-
if (!view.transcript.some(wasDetached) && !
|
|
647
|
+
if (!view.transcript.some(wasDetached) && !inbox && !replyFeed)
|
|
539
648
|
return view;
|
|
540
649
|
const wake = (await wakeDue(ctx, at, host, ref, conversation)) ? { wake: true } : {};
|
|
541
650
|
if (!view.transcript.some(isDetachedBlock)) {
|
|
542
|
-
return {
|
|
651
|
+
return {
|
|
652
|
+
...view,
|
|
653
|
+
...(inbox || replyFeed ? notifyOffer(ctx) : {}),
|
|
654
|
+
...following,
|
|
655
|
+
...wake,
|
|
656
|
+
};
|
|
543
657
|
}
|
|
544
658
|
const { operations } = await ctx.sessions.read(at.sessionId);
|
|
545
659
|
const transcript = await Promise.all(view.transcript.map((block) => isDetachedBlock(block) ? lateBlock(ctx, at, block, operations, host) : block));
|
|
546
660
|
// why: an app's inbox saves replies the page did not ask for, so its page always listens
|
|
547
|
-
const listens =
|
|
548
|
-
return { ...view, transcript, ...(listens ? notifyOffer(ctx) : {}), ...wake };
|
|
661
|
+
const listens = inbox !== undefined || replyFeed !== undefined || transcript.some(isDetachedBlock);
|
|
662
|
+
return { ...view, transcript, ...(listens ? notifyOffer(ctx) : {}), ...following, ...wake };
|
|
549
663
|
}
|
|
550
664
|
/** The view's offer to listen on `/notify`: none without a notifier. */
|
|
551
665
|
function notifyOffer(ctx) {
|
|
@@ -789,6 +903,7 @@ export function createConversationCore(state) {
|
|
|
789
903
|
release: (at, args) => release(state, at, args),
|
|
790
904
|
read: (at, args) => read(state, at, args),
|
|
791
905
|
rewind: (at, args) => rewind(state, at, args),
|
|
906
|
+
follow: (at, args) => follow(state, at, args),
|
|
792
907
|
steer: async (at, { turnId, ...steer }) => {
|
|
793
908
|
postedMessage(chatInterface(state.chat), steer.input);
|
|
794
909
|
return await state.steer.enqueue(inboxKey(at.sessionId, turnId), steerUnitOf(steer));
|
|
@@ -15,7 +15,7 @@ import { type CallHooks, type CoreContext } from './session-calls.ts';
|
|
|
15
15
|
* `TheoremHandlerOptions` means what it means there. The others take the run's `CoreContext`
|
|
16
16
|
* where the handler's take the `Request`.
|
|
17
17
|
*/
|
|
18
|
-
export type TheoremConversationCoreOptions<Item extends InboxItem = InboxItem> = Pick<TheoremHandlerOptions, 'profile' | 'onStage' | 'sessionStore' | 'conversationStore' | 'credentialStore' | 'gateTtlMs' | 'operationRetentionMs' | 'pageToolBroker' | 'pageToolTimeoutMs' | 'notifier' | 'notifyRetryMs' | 'lateResultsDecider' | 'conversationLeaseMs' | 'steerInbox' | 'clientEvents'> & ReplyWiring<Item> & {
|
|
18
|
+
export type TheoremConversationCoreOptions<Item extends InboxItem = InboxItem> = Pick<TheoremHandlerOptions, 'profile' | 'onStage' | 'sessionStore' | 'conversationStore' | 'credentialStore' | 'gateTtlMs' | 'operationRetentionMs' | 'pageToolBroker' | 'pageToolTimeoutMs' | 'notifier' | 'replyFeed' | 'notifyRetryMs' | 'lateResultsDecider' | 'conversationLeaseMs' | 'steerInbox' | 'clientEvents'> & ReplyWiring<Item> & {
|
|
19
19
|
/** Host options for registered providers, or a factory for apps that pick keys per run. */
|
|
20
20
|
provider: ProviderHostOptions | ((at: CoreContext, model?: string) => ProviderHostOptions | Promise<ProviderHostOptions>);
|
|
21
21
|
/**
|
|
@@ -29,6 +29,7 @@ export function createTheoremConversationCore(options) {
|
|
|
29
29
|
pageToolTimeoutMs: options.pageToolTimeoutMs,
|
|
30
30
|
notifier: options.notifier,
|
|
31
31
|
notifyRetryMs: options.notifyRetryMs,
|
|
32
|
+
replyFeed: options.replyFeed,
|
|
32
33
|
lateResultsDecider: options.lateResultsDecider,
|
|
33
34
|
conversationLeaseMs: options.conversationLeaseMs,
|
|
34
35
|
clientEvents: options.clientEvents,
|
package/server/handler.d.ts
CHANGED
|
@@ -16,6 +16,8 @@ import { type PageToolBroker } from './page-dispatch.ts';
|
|
|
16
16
|
* - `POST <base>/notify` → NDJSON that stays open: one line now, and one for each `publish` under
|
|
17
17
|
* this session: a background call ended, or the app saved a reply.
|
|
18
18
|
* Set `notifier` to serve it
|
|
19
|
+
* - `POST <base>/follow` → NDJSON for the reply that runs on a conversation now, whoever started
|
|
20
|
+
* it: its lines from the first, until it ends. Set `replyFeed` to serve it
|
|
19
21
|
* - `POST <base>/rewind` → `{ conversation, view }` the conversation cut after one block, and its new ref
|
|
20
22
|
* - `POST <base>/wake` → NDJSON for a reply to no message: the model takes up the results of
|
|
21
23
|
* background calls that ended since it last ran. Empty when none waits
|
|
@@ -49,6 +51,7 @@ import { type ReplyWiring } from './conversation-core.ts';
|
|
|
49
51
|
import type { TheoremConversationStore } from './conversation-store.ts';
|
|
50
52
|
import type { TheoremCredentialStore } from './credential-store.ts';
|
|
51
53
|
import type { TheoremNotifier } from './notifier.ts';
|
|
54
|
+
import type { TheoremReplyFeed } from './reply-feed.ts';
|
|
52
55
|
import { type CoreContext } from './session-calls.ts';
|
|
53
56
|
export { theoremSession, theoremSessionId } from './session-identity.ts';
|
|
54
57
|
import type { SessionToolOperation, TheoremSessionStore } from './session-store.ts';
|
|
@@ -147,6 +150,12 @@ export type TheoremHandlerOptions<Item extends InboxItem = InboxItem> = ReplyWir
|
|
|
147
150
|
* reply it saves away from the page. `createMemoryNotifier` for one instance.
|
|
148
151
|
*/
|
|
149
152
|
notifier?: TheoremNotifier;
|
|
153
|
+
/**
|
|
154
|
+
* Where the lines of a running reply go, so every page open on the conversation draws the reply
|
|
155
|
+
* live, whoever started it. Needs `notifier`, which tells the pages when a reply starts and ends.
|
|
156
|
+
* `createMemoryReplyFeed` for one instance.
|
|
157
|
+
*/
|
|
158
|
+
replyFeed?: TheoremReplyFeed;
|
|
150
159
|
/**
|
|
151
160
|
* How long an open page waits to reopen `notifier`'s stream after it ends, in milliseconds.
|
|
152
161
|
* Hosting platforms cut long responses. Unset, the page does not reopen it.
|
|
@@ -249,7 +258,7 @@ export type MessageIntake = {
|
|
|
249
258
|
landsAs: readonly string[];
|
|
250
259
|
};
|
|
251
260
|
/** A host profile runs no model, and takes no turns to steer. */
|
|
252
|
-
export type TheoremHostHandlerOptions = Omit<TheoremHandlerOptions, 'profile' | 'provider' | 'steerInbox' | 'conversationStore' | 'prepare' | 'inbox' | 'beforeSave' | 'afterSave' | 'compact' | 'notifier' | 'notifyRetryMs' | 'conversationLeaseMs'> & {
|
|
261
|
+
export type TheoremHostHandlerOptions = Omit<TheoremHandlerOptions, 'profile' | 'provider' | 'steerInbox' | 'conversationStore' | 'prepare' | 'inbox' | 'beforeSave' | 'afterSave' | 'compact' | 'notifier' | 'replyFeed' | 'notifyRetryMs' | 'conversationLeaseMs'> & {
|
|
253
262
|
/** Host profile to serve. Registered with the kernel when the handler is created. */
|
|
254
263
|
profile: Extract<Profile, {
|
|
255
264
|
type: 'host';
|
package/server/handler.js
CHANGED
|
@@ -16,6 +16,8 @@ import { pageToolResultSchema, sessionPageDispatch } from "./page-dispatch.js";
|
|
|
16
16
|
* - `POST <base>/notify` → NDJSON that stays open: one line now, and one for each `publish` under
|
|
17
17
|
* this session: a background call ended, or the app saved a reply.
|
|
18
18
|
* Set `notifier` to serve it
|
|
19
|
+
* - `POST <base>/follow` → NDJSON for the reply that runs on a conversation now, whoever started
|
|
20
|
+
* it: its lines from the first, until it ends. Set `replyFeed` to serve it
|
|
19
21
|
* - `POST <base>/rewind` → `{ conversation, view }` the conversation cut after one block, and its new ref
|
|
20
22
|
* - `POST <base>/wake` → NDJSON for a reply to no message: the model takes up the results of
|
|
21
23
|
* background calls that ended since it last ran. Empty when none waits
|
|
@@ -43,7 +45,7 @@ import { defaultKernelScope, defineProfile, labelText, TheoremError, } from '@th
|
|
|
43
45
|
import { caughtStatus, clientError, forClient, HTTP_NOT_FOUND, } from '@theoremjs/agents/host';
|
|
44
46
|
import { blockWithoutToolData, clientProfileInterface, eventWithoutToolData, profileShowsToolData, } from '@theoremjs/agents/interface';
|
|
45
47
|
import { hostInterface, theoremHostCallRequestSchema } from "../client/host-transport.js";
|
|
46
|
-
import { theoremConversationRequestSchema, theoremInvokeRequestSchema, theoremNotifyRequestSchema, theoremRewindRequestSchema, theoremSteerRequestSchema, theoremStopRequestSchema, theoremTurnRequestSchema, theoremWakeRequestSchema, } from "../client/transport.js";
|
|
48
|
+
import { theoremConversationRequestSchema, theoremFollowRequestSchema, theoremInvokeRequestSchema, theoremNotifyRequestSchema, theoremRewindRequestSchema, theoremSteerRequestSchema, theoremStopRequestSchema, theoremTurnRequestSchema, theoremWakeRequestSchema, } from "../client/transport.js";
|
|
47
49
|
import { statelessRefusal } from "./conversation.js";
|
|
48
50
|
import { chatOf, createConversationCore, endingsOf, followedUp, oneInbox, replyUnreachable, unconversedAnswer, } from "./conversation-core.js";
|
|
49
51
|
import { callEvents, sessionParts } from "./session-calls.js";
|
|
@@ -95,6 +97,7 @@ function routeOf(request) {
|
|
|
95
97
|
last === 'stop' ||
|
|
96
98
|
last === 'conversation' ||
|
|
97
99
|
last === 'notify' ||
|
|
100
|
+
last === 'follow' ||
|
|
98
101
|
last === 'rewind' ||
|
|
99
102
|
last === 'wake' ||
|
|
100
103
|
last === 'call' ||
|
|
@@ -244,6 +247,7 @@ function coreOf(ctx, chat, request) {
|
|
|
244
247
|
provider: (_at, model) => providerFor(ctx, request, model),
|
|
245
248
|
conversationLeaseMs: ctx.options.conversationLeaseMs,
|
|
246
249
|
notifyRetryMs: ctx.options.notifyRetryMs,
|
|
250
|
+
replyFeed: ctx.options.replyFeed,
|
|
247
251
|
clientEvents: ctx.options.clientEvents,
|
|
248
252
|
},
|
|
249
253
|
});
|
|
@@ -372,6 +376,18 @@ async function wake(ctx, chat, request, session) {
|
|
|
372
376
|
const reply = await core.wake(at, { ref: body.conversation, generation: body, input });
|
|
373
377
|
return eventStream(ctx, request, () => pageRun(ctx, request, core, at, reply));
|
|
374
378
|
}
|
|
379
|
+
/**
|
|
380
|
+
* The lines of the reply that runs on the conversation now, whoever started it: the same lines,
|
|
381
|
+
* encoded the same way, as the reply's own stream. The stream ends with the reply, and the page
|
|
382
|
+
* reads the saved conversation.
|
|
383
|
+
*/
|
|
384
|
+
async function follow(ctx, chat, request, session) {
|
|
385
|
+
const body = await readBody(request, theoremFollowRequestSchema, ctx.options.maxRequestBytes);
|
|
386
|
+
const lines = await coreOf(ctx, chat, request).follow(contextOf(ctx, request, session.id), {
|
|
387
|
+
ref: body.conversation,
|
|
388
|
+
});
|
|
389
|
+
return eventStream(ctx, request, () => lines);
|
|
390
|
+
}
|
|
375
391
|
const CHANGED_LINE = new TextEncoder().encode('{"type":"changed"}\n');
|
|
376
392
|
/**
|
|
377
393
|
* One line now, then one for each background call that ends. The stream names no conversation,
|
|
@@ -535,6 +551,11 @@ async function route(ctx, request, session) {
|
|
|
535
551
|
return refused(ctx);
|
|
536
552
|
return notify(ctx, request, session, notifier);
|
|
537
553
|
}
|
|
554
|
+
if (target === 'follow') {
|
|
555
|
+
if (!ctx.options.replyFeed || !chat.conversations)
|
|
556
|
+
return refused(ctx);
|
|
557
|
+
return follow(ctx, chat, request, session);
|
|
558
|
+
}
|
|
538
559
|
if (target === 'rewind')
|
|
539
560
|
return rewind(ctx, chat, request, session);
|
|
540
561
|
if (target === 'wake')
|
package/server/mod.d.ts
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
export { theoremHostCallRequestSchema } from '../client/host-transport.ts';
|
|
9
9
|
export type { LiveClientMessage, LiveOpenMessage } from '../client/live-messages.ts';
|
|
10
10
|
export { transcriptBlockSchema } from '../client/transcript-schema.ts';
|
|
11
|
-
export { type StatedTurn, theoremConversationRequestSchema, theoremInvokeRequestSchema, theoremNotifyRequestSchema, theoremReplaySchema, theoremRewindRequestSchema, theoremStartRequestSchema, theoremSteerRequestSchema, theoremStopRequestSchema, theoremTurnRequestSchema, theoremWakeRequestSchema, } from '../client/transport.ts';
|
|
11
|
+
export { type StatedTurn, theoremConversationRequestSchema, theoremFollowRequestSchema, theoremInvokeRequestSchema, theoremNotifyRequestSchema, theoremReplaySchema, theoremRewindRequestSchema, theoremStartRequestSchema, theoremSteerRequestSchema, theoremStopRequestSchema, theoremTurnRequestSchema, theoremWakeRequestSchema, } from '../client/transport.ts';
|
|
12
12
|
export { answerReply, type ConversationHost, type ConversationUse, conversationView, type IssuedWalkAway, messageReply, type OpenedConversation, openConversation, type PostedMessage, postedMessage, type ReplyLine, type ReplyRunner, type ReplySaving, type ReplyToSave, type ReplyTurn, readerConversationHost, rewindConversation, type ShapedReply, startConversation, statelessRefusal, type WalkedAwayCall, waitingCalls, wakeReply, } from './conversation.ts';
|
|
13
13
|
export type { AppInbox, ContinueChoice, ConversationCore, FollowUpArgs, Generation, HoldStop, MessageArgs, Reply, ReplyPrepare, ReplyWiring, RunEnd, SaveHooks, WakeArgs, } from './conversation-core.ts';
|
|
14
14
|
export { followedUp } from './conversation-core.ts';
|
|
@@ -22,6 +22,7 @@ export { createTheoremHandler, createTheoremHostHandler, type MessageIntake, rea
|
|
|
22
22
|
export { createTheoremMcpHandler, type TheoremMcpHandlerOptions } from './mcp-handler.ts';
|
|
23
23
|
export { createMemoryNotifier, type TheoremNotifier } from './notifier.ts';
|
|
24
24
|
export { createMemoryPageToolBroker, type PageToolBroker, type PageToolResult, pageToolResultSchema, sessionPageDispatch, } from './page-dispatch.ts';
|
|
25
|
+
export { createMemoryReplyFeed, type ReplyFeedListener, type TheoremReplyFeed, } from './reply-feed.ts';
|
|
25
26
|
export { checkRequest, parseLiveClientMessage, parseLiveOpenMessage } from './request-check.ts';
|
|
26
27
|
export { sessionStateStore } from './session-authority.ts';
|
|
27
28
|
export { createTheoremSessionBoundary, type PreparedLiveOpen, type SessionBoundaryOptions, type TheoremSessionBoundary, } from './session-boundary.ts';
|
package/server/mod.js
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
*/
|
|
8
8
|
export { theoremHostCallRequestSchema } from "../client/host-transport.js";
|
|
9
9
|
export { transcriptBlockSchema } from "../client/transcript-schema.js";
|
|
10
|
-
export { theoremConversationRequestSchema, theoremInvokeRequestSchema, theoremNotifyRequestSchema, theoremReplaySchema, theoremRewindRequestSchema, theoremStartRequestSchema, theoremSteerRequestSchema, theoremStopRequestSchema, theoremTurnRequestSchema, theoremWakeRequestSchema, } from "../client/transport.js";
|
|
10
|
+
export { theoremConversationRequestSchema, theoremFollowRequestSchema, theoremInvokeRequestSchema, theoremNotifyRequestSchema, theoremReplaySchema, theoremRewindRequestSchema, theoremStartRequestSchema, theoremSteerRequestSchema, theoremStopRequestSchema, theoremTurnRequestSchema, theoremWakeRequestSchema, } from "../client/transport.js";
|
|
11
11
|
export { answerReply, conversationView, messageReply, openConversation, postedMessage, readerConversationHost, rewindConversation, startConversation, statelessRefusal, waitingCalls, wakeReply, } from "./conversation.js";
|
|
12
12
|
export { followedUp } from "./conversation-core.js";
|
|
13
13
|
export { detachedEnding } from "./conversation-inbox.js";
|
|
@@ -20,6 +20,7 @@ export { createTheoremHandler, createTheoremHostHandler, readBody, theoremSessio
|
|
|
20
20
|
export { createTheoremMcpHandler } from "./mcp-handler.js";
|
|
21
21
|
export { createMemoryNotifier } from "./notifier.js";
|
|
22
22
|
export { createMemoryPageToolBroker, pageToolResultSchema, sessionPageDispatch, } from "./page-dispatch.js";
|
|
23
|
+
export { createMemoryReplyFeed, } from "./reply-feed.js";
|
|
23
24
|
export { checkRequest, parseLiveClientMessage, parseLiveOpenMessage } from "./request-check.js";
|
|
24
25
|
export { sessionStateStore } from "./session-authority.js";
|
|
25
26
|
export { createTheoremSessionBoundary, } from "./session-boundary.js";
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where the lines of a running reply go, so every page open on the conversation can draw it live,
|
|
3
|
+
* whichever request, server or process runs the reply. A page that follows reads the same lines
|
|
4
|
+
* the page that started the reply reads.
|
|
5
|
+
*
|
|
6
|
+
* @module
|
|
7
|
+
*/
|
|
8
|
+
import type { ReplyLine } from './conversation.ts';
|
|
9
|
+
/** What a follower is told, in order. */
|
|
10
|
+
export type ReplyFeedListener = {
|
|
11
|
+
/** One line of the reply. */
|
|
12
|
+
line(line: ReplyLine): void;
|
|
13
|
+
/** The reply is over, or none runs: the follower reads the saved conversation. */
|
|
14
|
+
end(): void;
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* Keyed by the conversation's id, which stays the same across every write; a store's ref does not.
|
|
18
|
+
* `reply` names one reply on that conversation, so the end of an old reply never ends a new one.
|
|
19
|
+
* The default lives in process memory, which reaches only followers connected to the process that
|
|
20
|
+
* runs the reply. Bring a shared one (Redis streams, a Durable Object) for several instances.
|
|
21
|
+
*
|
|
22
|
+
* A reply's lines are plain JSON: the events `createTheoremHandler` streams, as they leave the
|
|
23
|
+
* kernel. Keep them as long as `reply` runs, and what your host decides beyond that (a cap, an
|
|
24
|
+
* expiry, a dead server's reply) is yours.
|
|
25
|
+
*/
|
|
26
|
+
export interface TheoremReplyFeed {
|
|
27
|
+
/** A reply began on `conversation`. Drop the lines of any earlier reply on it. */
|
|
28
|
+
start(conversation: string, reply: string): void | Promise<void>;
|
|
29
|
+
/** The next line of `reply`, in order. */
|
|
30
|
+
append(conversation: string, reply: string, line: ReplyLine): void | Promise<void>;
|
|
31
|
+
/** `reply` is over. Tell each follower `end`, and keep nothing of it. */
|
|
32
|
+
end(conversation: string, reply: string): void | Promise<void>;
|
|
33
|
+
/**
|
|
34
|
+
* Tells `listener` each line of the reply that runs on `conversation` now, from its first and in
|
|
35
|
+
* order, then each new line as it comes, then `end`. When no reply runs, tells `end` at once.
|
|
36
|
+
* Returns the function that stops the listening.
|
|
37
|
+
*/
|
|
38
|
+
follow(conversation: string, listener: ReplyFeedListener): (() => void) | Promise<() => void>;
|
|
39
|
+
}
|
|
40
|
+
/** A feed in process memory. It keeps every line of a running reply until it ends, and sets no limit. */
|
|
41
|
+
export declare function createMemoryReplyFeed(): TheoremReplyFeed;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where the lines of a running reply go, so every page open on the conversation can draw it live,
|
|
3
|
+
* whichever request, server or process runs the reply. A page that follows reads the same lines
|
|
4
|
+
* the page that started the reply reads.
|
|
5
|
+
*
|
|
6
|
+
* @module
|
|
7
|
+
*/
|
|
8
|
+
/** A feed in process memory. It keeps every line of a running reply until it ends, and sets no limit. */
|
|
9
|
+
export function createMemoryReplyFeed() {
|
|
10
|
+
const live = new Map();
|
|
11
|
+
return {
|
|
12
|
+
start(conversation, reply) {
|
|
13
|
+
const earlier = live.get(conversation);
|
|
14
|
+
live.set(conversation, { reply, lines: [], listeners: new Set() });
|
|
15
|
+
for (const listener of earlier?.listeners ?? [])
|
|
16
|
+
listener.end();
|
|
17
|
+
},
|
|
18
|
+
append(conversation, reply, line) {
|
|
19
|
+
const current = live.get(conversation);
|
|
20
|
+
if (current?.reply !== reply)
|
|
21
|
+
return;
|
|
22
|
+
current.lines.push(line);
|
|
23
|
+
for (const listener of [...current.listeners])
|
|
24
|
+
listener.line(line);
|
|
25
|
+
},
|
|
26
|
+
end(conversation, reply) {
|
|
27
|
+
const current = live.get(conversation);
|
|
28
|
+
if (current?.reply !== reply)
|
|
29
|
+
return;
|
|
30
|
+
live.delete(conversation);
|
|
31
|
+
for (const listener of [...current.listeners])
|
|
32
|
+
listener.end();
|
|
33
|
+
},
|
|
34
|
+
follow(conversation, listener) {
|
|
35
|
+
const current = live.get(conversation);
|
|
36
|
+
if (!current) {
|
|
37
|
+
listener.end();
|
|
38
|
+
return () => { };
|
|
39
|
+
}
|
|
40
|
+
for (const line of [...current.lines])
|
|
41
|
+
listener.line(line);
|
|
42
|
+
current.listeners.add(listener);
|
|
43
|
+
return () => {
|
|
44
|
+
current.listeners.delete(listener);
|
|
45
|
+
};
|
|
46
|
+
},
|
|
47
|
+
};
|
|
48
|
+
}
|