@theoremjs/web 0.3.5-next.919.gc55551d → 0.3.5-next.927.g1f89ea0
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 +7 -2
- package/client/chat.js +48 -2
- package/client/index.d.ts +2 -2
- package/client/index.js +1 -1
- package/client/page-dispatch.js +5 -0
- package/client/run-session.d.ts +15 -0
- package/client/run-session.js +31 -1
- package/client/tool-result.d.ts +12 -5
- package/client/tool-result.js +16 -42
- package/client/transcript-schema.js +5 -3
- package/client/transport.d.ts +20 -0
- package/client/transport.js +12 -0
- package/client/turn-client.d.ts +3 -1
- package/client/turn-client.js +8 -0
- package/package.json +2 -2
- package/server/conversation.d.ts +17 -0
- package/server/conversation.js +37 -4
- package/server/handler.d.ts +11 -0
- package/server/handler.js +64 -8
- package/server/mcp-handler.js +16 -9
- package/server/mod.d.ts +2 -2
- package/server/mod.js +2 -2
- package/server/session-store.d.ts +2 -0
- package/server/session-store.js +1 -0
package/README.md
CHANGED
|
@@ -103,7 +103,7 @@ export const mcp = createTheoremMcpHandler({ profile: docsTools, version: '1.0.0
|
|
|
103
103
|
|
|
104
104
|
- `tools/list` gives each allowed tool with its input schema. A tool's `access` becomes the read-only and destructive hints of MCP.
|
|
105
105
|
- Clients of the current revision may cache the tool list for 5 minutes and the discovery result for an hour. Neither holds anything about the caller, so a shared cache may keep them.
|
|
106
|
-
- `tools/call` runs the tool through the gates, the guardrails, and the trace of the kernel. The client receives the text a model would read, not the raw output.
|
|
106
|
+
- `tools/call` runs the tool through the gates, the guardrails, and the trace of the kernel. The client receives the text and media a model would read, not the raw output. A reference a tool returned, which no model reads, is left out. So is all the media of a hidden tool (`exposeToModel: false`), whose model reads only that the call completed.
|
|
107
107
|
- A tool that fails returns a result marked `isError`, so the model can read it and try again.
|
|
108
108
|
- No one can approve a call over MCP. The handler refuses a profile when an allowed tool has a permission other than `auto`.
|
|
109
109
|
- A browser page on another origin is refused unless `origins` lists it.
|
|
@@ -271,6 +271,7 @@ const transport = withPageToolDispatch(
|
|
|
271
271
|
| `pageStatesTurn` | Let the page say which prompt lines a turn gets, through `stated` on a turn or a live call. Set it only for a page you trust as yourself, such as a builder's own tool. Without it, a request with `stated` is refused. |
|
|
272
272
|
| `conversationStore` | Where the conversation is kept. Required, except for a stateless profile, which must not have one. See [Keep the conversation](#keep-the-conversation). |
|
|
273
273
|
| `sessionStore`, `steerInbox` | Where open gates are kept, and where steers and stops reach a running turn. Default: process memory, which reaches only turns this process runs. On more than one instance, give a shared `SteerInbox`. |
|
|
274
|
+
| `authorizeWake` | Called with `{ request, conversation }` before a wake turn runs. Return `false` to skip it, for example to cap wakes. The results stay unread for the next message. Unset, every due wake runs. See [the background section](#share-session-authority). |
|
|
274
275
|
| `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). |
|
|
275
276
|
| `credentialStore` | Where tool credentials are kept, by session. Default: process memory. |
|
|
276
277
|
| `authorizationUrl` | Returns the sign-in URL for an OAuth gate. Without it, an OAuth gate has no URL. |
|
|
@@ -457,7 +458,11 @@ Browser dispatch uses a host-owned `PageToolExecution` service beside the execut
|
|
|
457
458
|
`createTheoremHandler` supplies both services. Live relays put the session boundary's `pageExecution` and `toolExecution` on `SessionRequest`.
|
|
458
459
|
|
|
459
460
|
A tool with a `background` setting runs inline until you pass the `background` option to `createTheoremHandler`, or return `background` from `prepare`, with an `execution` of your own that has `detach`, when the same turns run elsewhere in your app too. The option takes `{ request, sessionId }` and returns a `ToolBackgroundService`, which receives each detached call and its late events. The session keeps the call as `background` until it settles, and a late settlement does not invalidate a checkpoint. A conversation read shows the call as it stands: running, then its result, or an error for a marked call. An open page reads it on its next turn or reload, unless you set `notifier`. When the session has dropped a settled operation, the block reads an error with the code `outcome_not_retained`. On a durable store, a worker that dies leaves the operation as `background`, so your sweep marks it `uncertain` with `worker_lost` through `compareAndSwap`. Keep the service's values valid after the request ends. A live relay passes its service to `runSession`.
|
|
460
|
-
To show an open page that a background call ended, with no turn or reload, pass `notifier: createMemoryNotifier()` to `createTheoremHandler`. While a call runs, the conversation read tells the page to open `POST <base>/notify`. The handler sends one `changed` line when the stream opens, and one when each background call in the session ends. The line carries no content, so the page calls the same conversation read as before. The page closes the stream when no call runs. The model reads the result
|
|
461
|
+
To show an open page that a background call ended, with no turn or reload, pass `notifier: createMemoryNotifier()` to `createTheoremHandler`. While a call runs, the conversation read tells the page to open `POST <base>/notify`. The handler sends one `changed` line when the stream opens, and one when each background call in the session ends. The line carries no content, so the page calls the same conversation read as before. The page closes the stream when no call runs. The model reads the result without a new message. When results are due, the conversation read says `wake: true`, and the page posts `<base>/wake` once it is idle. The handler runs a turn with no message: it passes the session's stored outcome in `input.lateResults`, and the model answers. The turn is the wake. A result is due when its call settled, the transcript does not end on a person's message, no `late-results` block names the call, and no wake took the result up before. The handler marks each result taken (`wokenAt` on the session's operation) before the model runs, so one result wakes the conversation once. Two pages that post at once run one turn, and a wake that fails is not tried again. The next message still reads any result that no `late-results` block names, so nothing is lost. A message the person sends during a wake wins: the wake writes nothing, and its stream ends with no error. `authorizeWake` decides whether a wake runs, for example to cap wakes for each person. A refused wake still marks its results taken. A call `authorizeToolReplay` withholds from the request stays unread and does not wake.
|
|
462
|
+
|
|
463
|
+
The late-results feed is the one way a result reaches the model. If your `background` service told the model a result some other way, such as with your own `onStage`, remove that, or the model reads it twice.
|
|
464
|
+
|
|
465
|
+
To wake a conversation with no page open, post `<base>/wake` through the handler from your server, with your own `Request` and the conversation's current reference. Your `conversationStore` must give that reference: `createSealedConversationStore` gives a new one on each write, which only the page holds.
|
|
461
466
|
|
|
462
467
|
`createMemoryNotifier` reaches only pages connected to the process that ran the call. On more than one instance, give a shared `TheoremNotifier`. Your sweep calls `publish` with the session id after it marks a call `worker_lost`, because that write does not pass through the handler. Hosting platforms cut long responses. Set `notifyRetryMs` so that the page reopens the stream after that wait. Unset, the page does not reopen it, and reads the end on its next turn or reload.
|
|
463
468
|
|
package/client/chat.js
CHANGED
|
@@ -8,7 +8,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
10
|
import { sessionAfter, stampWorked, stoppedReply } from "./run-commit.js";
|
|
11
|
-
import { keepsConversation, resumeInterfaceTool, streamInterfaceDraftTurn, streamInterfaceTurn, } from "./run-session.js";
|
|
11
|
+
import { keepsConversation, resumeInterfaceTool, streamInterfaceDraftTurn, streamInterfaceTurn, streamInterfaceWake, } from "./run-session.js";
|
|
12
12
|
import { isUnknownConversation, } from "./transport.js";
|
|
13
13
|
import { foldAssistantTurn, issuedOperationId } from "./turn-client.js";
|
|
14
14
|
const DELIVERY_ORDER = ['sending', 'sent', 'delivered', 'read'];
|
|
@@ -123,6 +123,8 @@ class Chat {
|
|
|
123
123
|
/** What the last view said about the host's push; unset, nothing is listened for. */
|
|
124
124
|
#notify;
|
|
125
125
|
#listening = null;
|
|
126
|
+
/** The last view said results wait that no reply has read: the chat wakes once it is idle. */
|
|
127
|
+
#wakeDue = false;
|
|
126
128
|
#reading = null;
|
|
127
129
|
#readAgain = false;
|
|
128
130
|
constructor(options) {
|
|
@@ -495,6 +497,28 @@ class Chat {
|
|
|
495
497
|
this.#resume(iface);
|
|
496
498
|
this.#answerPageGate();
|
|
497
499
|
this.#drain();
|
|
500
|
+
this.#wake();
|
|
501
|
+
}
|
|
502
|
+
/**
|
|
503
|
+
* Wakes the conversation when the host said results wait. A message the queue sends goes first:
|
|
504
|
+
* its reply reads them. The host takes each result once, so a wake is never run twice for it.
|
|
505
|
+
*/
|
|
506
|
+
#wake() {
|
|
507
|
+
const ref = this.#conversation;
|
|
508
|
+
if (!this.#wakeDue || ref === undefined || this.#busy || this.#draining)
|
|
509
|
+
return;
|
|
510
|
+
if (this.#state.phase !== 'idle' || !this.#options.transport.wake)
|
|
511
|
+
return;
|
|
512
|
+
this.#wakeDue = false;
|
|
513
|
+
void this.#runTurn(({ iface, view, transport, scope, signal }) => streamInterfaceWake({
|
|
514
|
+
iface,
|
|
515
|
+
transport,
|
|
516
|
+
session: this.#state.session,
|
|
517
|
+
scope: { ...scope, conversation: ref },
|
|
518
|
+
view,
|
|
519
|
+
signal,
|
|
520
|
+
began: () => this.#set({ failure: null, streaming: true }),
|
|
521
|
+
}), { turn: true, wake: true });
|
|
498
522
|
}
|
|
499
523
|
#clearedComposer() {
|
|
500
524
|
return { draftText: '', pendingFiles: [], pendingVoice: [] };
|
|
@@ -537,6 +561,7 @@ class Chat {
|
|
|
537
561
|
session: this.#sessionAfter(session, view.paused?.events ?? events),
|
|
538
562
|
chatStarted: view.transcript.length > 0 || view.paused !== undefined,
|
|
539
563
|
});
|
|
564
|
+
this.#wakeDue = view.wake === true;
|
|
540
565
|
this.#setPush(view.notify);
|
|
541
566
|
}
|
|
542
567
|
/**
|
|
@@ -780,6 +805,25 @@ class Chat {
|
|
|
780
805
|
...base,
|
|
781
806
|
turn: (request, onLine, signal) => base.turn(this.#withValues(request), tap(onLine), signal),
|
|
782
807
|
invoke: (request, onLine, signal) => base.invoke(request, tap(onLine), signal),
|
|
808
|
+
...(base.wake
|
|
809
|
+
? {
|
|
810
|
+
wake: (request, onLine, signal) => base.wake?.(this.#wakeValues(request), tap(onLine), signal) ?? Promise.resolve(),
|
|
811
|
+
}
|
|
812
|
+
: {}),
|
|
813
|
+
};
|
|
814
|
+
}
|
|
815
|
+
/** A wake carries the option picks and context a message would. */
|
|
816
|
+
#wakeValues(request) {
|
|
817
|
+
const { iface, options: fixed, context } = this.#options;
|
|
818
|
+
const options = picksOf(iface, fixed, this.#picked).values;
|
|
819
|
+
if (options === undefined && context === undefined)
|
|
820
|
+
return request;
|
|
821
|
+
return {
|
|
822
|
+
...request,
|
|
823
|
+
input: {
|
|
824
|
+
...(options === undefined ? {} : { options }),
|
|
825
|
+
...(context === undefined ? {} : { context }),
|
|
826
|
+
},
|
|
783
827
|
};
|
|
784
828
|
}
|
|
785
829
|
#withValues(request) {
|
|
@@ -846,7 +890,9 @@ class Chat {
|
|
|
846
890
|
this.#stopped = false;
|
|
847
891
|
this.#drainArmed = false;
|
|
848
892
|
// why: A message streams once it posts, so the previous reply never shows as streaming before it.
|
|
849
|
-
|
|
893
|
+
// A wake shows only once the host's reply begins; one with nothing to wake for shows nothing.
|
|
894
|
+
if (!options.wake)
|
|
895
|
+
this.#set({ failure: null, ...(message ? {} : { streaming: true }) });
|
|
850
896
|
const start = { blocks: this.#state.blocks, streamBlocks: this.#state.streamBlocks };
|
|
851
897
|
// why: A run that answers a gate continues its reply; any other starts one.
|
|
852
898
|
if (!this.#state.session.gatedTool)
|
package/client/index.d.ts
CHANGED
|
@@ -29,9 +29,9 @@ export { fieldLabel, fieldReading, humanize, isPart, isPlain, isProse, isRow, js
|
|
|
29
29
|
export { citationsFromBlock, type SourceCitation, type SourceCitationBlock, } from './source-citations.ts';
|
|
30
30
|
export type { QueryMatch } from './space-geometry.ts';
|
|
31
31
|
export { DOT_FLOATS, FRAME_SLOT, queryGeometry, SEGMENT_FLOATS, type SpaceGeometry, spaceGeometry, } from './space-geometry.ts';
|
|
32
|
-
export { hasLead, layoutResult, type ResultChart, type ResultFigure, type ResultImage, type ResultLayout, type ResultMedia, returnedMedia, timeFormats, } from './tool-result.ts';
|
|
32
|
+
export { hasLead, layoutResult, type ResultChart, type ResultFigure, type ResultImage, type ResultLayout, type ResultMedia, referencesIn, returnedMedia, timeFormats, } from './tool-result.ts';
|
|
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, readNdjsonStream, type StatedTurn, type TheoremConversationRequest, type TheoremInvokeRequest, type TheoremReplay, type TheoremRewindRequest, type TheoremRewound, type TheoremStartRequest, type TheoremSteerRequest, type TheoremStopRequest, TheoremStreamError, type TheoremTransport, type TheoremTurnInput, type TheoremTurnRequest, 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, readNdjsonStream, type StatedTurn, type TheoremConversationRequest, type TheoremInvokeRequest, type TheoremReplay, type TheoremRewindRequest, type TheoremRewound, type TheoremStartRequest, 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/index.js
CHANGED
|
@@ -24,7 +24,7 @@ export { blankRow, missingFields, sampleFromSchema, schemaControl, schemaFields,
|
|
|
24
24
|
export { fieldLabel, fieldReading, humanize, isPart, isPlain, isProse, isRow, json, layoutChars, MAX_ROWS, plainReading, rowHeading, shapeOf, splitFields, unpacked, withUnit, } from "./shaped-data.js";
|
|
25
25
|
export { citationsFromBlock, } from "./source-citations.js";
|
|
26
26
|
export { DOT_FLOATS, FRAME_SLOT, queryGeometry, SEGMENT_FLOATS, spaceGeometry, } from "./space-geometry.js";
|
|
27
|
-
export { hasLead, layoutResult, returnedMedia, timeFormats, } from "./tool-result.js";
|
|
27
|
+
export { hasLead, layoutResult, referencesIn, returnedMedia, timeFormats, } from "./tool-result.js";
|
|
28
28
|
export { continueGatedToolInvocation } from "./tool-resume.js";
|
|
29
29
|
export { createTraceFeed, recordedFeed } from "./trace-feed.js";
|
|
30
30
|
export { CHAT_LINES, createHttpTransport, fetchConversation, fetchRewound, fetchStarted, hostError, isTheoremStreamError, postJson, postNdjson, readNdjsonStream, TheoremStreamError, } from "./transport.js";
|
package/client/page-dispatch.js
CHANGED
|
@@ -55,6 +55,11 @@ export function withPageToolDispatch(transport, tools) {
|
|
|
55
55
|
describe: transport.describe.bind(transport),
|
|
56
56
|
invoke: (request, onLine, signal) => transport.invoke(request, chatSink(onLine, signal), signal),
|
|
57
57
|
turn: (request, onLine, signal) => transport.turn(request, chatSink(onLine, signal), signal),
|
|
58
|
+
...(transport.wake
|
|
59
|
+
? {
|
|
60
|
+
wake: (request, onLine, signal) => transport.wake?.(request, chatSink(onLine, signal), signal) ?? Promise.resolve(),
|
|
61
|
+
}
|
|
62
|
+
: {}),
|
|
58
63
|
steer: transport.steer.bind(transport),
|
|
59
64
|
stop: transport.stop.bind(transport),
|
|
60
65
|
conversation: transport.conversation.bind(transport),
|
package/client/run-session.d.ts
CHANGED
|
@@ -77,3 +77,18 @@ export declare function resumeInterfaceTool(args: {
|
|
|
77
77
|
resolution: ToolGateResolution;
|
|
78
78
|
view: StreamView;
|
|
79
79
|
}): Promise<RunOutcome>;
|
|
80
|
+
/**
|
|
81
|
+
* Wake the conversation: stream the reply the host runs for results no reply has read. `began`
|
|
82
|
+
* fires on its first line; a host with nothing to wake for sends none, and the run leaves nothing.
|
|
83
|
+
*/
|
|
84
|
+
export declare function streamInterfaceWake(args: {
|
|
85
|
+
iface: ComposerProfileInterface;
|
|
86
|
+
transport: TheoremTransport;
|
|
87
|
+
session: InterfaceTurnSession;
|
|
88
|
+
scope: RunScope & {
|
|
89
|
+
conversation: string;
|
|
90
|
+
};
|
|
91
|
+
view: StreamView;
|
|
92
|
+
signal?: AbortSignal;
|
|
93
|
+
began(): void;
|
|
94
|
+
}): Promise<RunOutcome>;
|
package/client/run-session.js
CHANGED
|
@@ -5,7 +5,7 @@ import { turnFailure } from "./failure.js";
|
|
|
5
5
|
import { streamFoldedTurn } from "./run-commit.js";
|
|
6
6
|
import { continueGatedToolInvocation } from "./tool-resume.js";
|
|
7
7
|
import { isUnknownConversation, } from "./transport.js";
|
|
8
|
-
import { buildInvokeRequest, buildTurnRequest, foldAssistantTurn, issuedOperationId, prepareComposerTurn, projectUserTurn, } from "./turn-client.js";
|
|
8
|
+
import { buildInvokeRequest, buildTurnRequest, buildWakeRequest, foldAssistantTurn, issuedOperationId, prepareComposerTurn, projectUserTurn, } from "./turn-client.js";
|
|
9
9
|
/**
|
|
10
10
|
* Whether the host keeps this chat's conversation. A stateless profile keeps
|
|
11
11
|
* none: the page holds its transcript, and nothing goes on from a ref.
|
|
@@ -205,3 +205,33 @@ export async function resumeInterfaceTool(args) {
|
|
|
205
205
|
}
|
|
206
206
|
return { session, events, posted: true };
|
|
207
207
|
}
|
|
208
|
+
/**
|
|
209
|
+
* Wake the conversation: stream the reply the host runs for results no reply has read. `began`
|
|
210
|
+
* fires on its first line; a host with nothing to wake for sends none, and the run leaves nothing.
|
|
211
|
+
*/
|
|
212
|
+
export async function streamInterfaceWake(args) {
|
|
213
|
+
const { iface, transport, session, scope, signal } = args;
|
|
214
|
+
const events = [];
|
|
215
|
+
const wake = transport.wake?.bind(transport);
|
|
216
|
+
if (!wake)
|
|
217
|
+
return { session, events, posted: false };
|
|
218
|
+
let begun = false;
|
|
219
|
+
try {
|
|
220
|
+
await streamFoldedTurn({
|
|
221
|
+
iface,
|
|
222
|
+
view: args.view,
|
|
223
|
+
events,
|
|
224
|
+
stream: (onLine) => wake(buildWakeRequest(iface, session, scope.conversation, scope), (line) => {
|
|
225
|
+
if (!begun) {
|
|
226
|
+
begun = true;
|
|
227
|
+
args.began();
|
|
228
|
+
}
|
|
229
|
+
onLine(line);
|
|
230
|
+
}, signal),
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
catch (err) {
|
|
234
|
+
return { session, events, posted: false, failure: turnFailure(err, iface.labels, signal) };
|
|
235
|
+
}
|
|
236
|
+
return { session, events, posted: false };
|
|
237
|
+
}
|
package/client/tool-result.d.ts
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
*
|
|
7
7
|
* @module
|
|
8
8
|
*/
|
|
9
|
+
import { type MediaInputKind } from '@theoremjs/agents';
|
|
9
10
|
import { type Row } from './shaped-data.ts';
|
|
10
11
|
/** One number that answers the call, as a stat card shows it. */
|
|
11
12
|
export type ResultFigure = {
|
|
@@ -45,15 +46,15 @@ export type ResultImage = {
|
|
|
45
46
|
export type ResultLayout = {
|
|
46
47
|
figures: ResultFigure[];
|
|
47
48
|
charts: ResultChart[];
|
|
48
|
-
images: ResultImage[];
|
|
49
49
|
};
|
|
50
|
-
/** Media a tool returned beside its value, as the complete event carries it. */
|
|
50
|
+
/** Media a tool returned beside its value, as the complete event carries it: bytes, or a reference (`uri`). */
|
|
51
51
|
export type ResultMedia = {
|
|
52
52
|
type: string;
|
|
53
53
|
mimeType?: string;
|
|
54
54
|
data?: string;
|
|
55
|
+
uri?: string;
|
|
55
56
|
};
|
|
56
|
-
/** What a call returned to see or hear: its image parts
|
|
57
|
+
/** What a call returned to see or hear: its image parts and its audio parts. */
|
|
57
58
|
export type ReturnedMedia = {
|
|
58
59
|
images: ResultImage[];
|
|
59
60
|
audio: {
|
|
@@ -63,8 +64,14 @@ export type ReturnedMedia = {
|
|
|
63
64
|
};
|
|
64
65
|
/** What a tool's output leads with. Empty when nothing stands out: the data alone reads best. */
|
|
65
66
|
export declare function layoutResult(output: unknown): ResultLayout;
|
|
66
|
-
/** The images and audio a call returned, each with its bytes; parts without them are left out. */
|
|
67
|
-
export declare function returnedMedia(
|
|
67
|
+
/** The images and audio a call returned, each with its bytes; parts without them (references) are left out. */
|
|
68
|
+
export declare function returnedMedia(parts: readonly ResultMedia[], imageAlt: string): ReturnedMedia;
|
|
69
|
+
/** The references a call returned, which only the app's resolver turns into something to show. */
|
|
70
|
+
export declare function referencesIn(parts: readonly ResultMedia[]): {
|
|
71
|
+
type: MediaInputKind;
|
|
72
|
+
mimeType: string;
|
|
73
|
+
uri: string;
|
|
74
|
+
}[];
|
|
68
75
|
/** Whether the result has anything to lead with above its data. */
|
|
69
76
|
export declare function hasLead(layout: ResultLayout, media: ReturnedMedia): boolean;
|
|
70
77
|
/**
|
package/client/tool-result.js
CHANGED
|
@@ -6,6 +6,7 @@
|
|
|
6
6
|
*
|
|
7
7
|
* @module
|
|
8
8
|
*/
|
|
9
|
+
import { MEDIA_INPUT_KIND_VALUES } from '@theoremjs/agents';
|
|
9
10
|
import { columnStore, fieldLabel, humanize, ISO_DATE, isPlain, isRow, printableUnit, shownEntries, storeRows, titleKey, unitsOf, unpacked, } from "./shaped-data.js";
|
|
10
11
|
const MAX_FIGURES = 4;
|
|
11
12
|
const MAX_CHARTS = 3;
|
|
@@ -13,25 +14,12 @@ const MAX_CHARTS = 3;
|
|
|
13
14
|
const MAX_SERIES = 3;
|
|
14
15
|
/** Bars a category chart ranks. */
|
|
15
16
|
const MAX_BARS = 8;
|
|
16
|
-
const MAX_IMAGES = 6;
|
|
17
17
|
/** Rows a list needs before it reads as a chart. */
|
|
18
18
|
const MIN_POINTS = 3;
|
|
19
|
-
/** Levels searched for charts
|
|
19
|
+
/** Levels searched for charts. */
|
|
20
20
|
const MAX_SEARCH_DEPTH = 3;
|
|
21
21
|
/** Numbers that locate or name a thing rather than measure it. */
|
|
22
22
|
const NOT_A_MEASURE = /(^|_)(id|ids|lat|lon|lng|latitude|longitude|offset|interval|index|rank|order)$|Id$|^(generationtime_ms|utc_offset_seconds)$/i;
|
|
23
|
-
const IMAGE_PATH = /\.(png|jpe?g|gif|webp|avif|svg)$/i;
|
|
24
|
-
function isImageUrl(text) {
|
|
25
|
-
if (/\s/.test(text))
|
|
26
|
-
return false;
|
|
27
|
-
try {
|
|
28
|
-
const url = new URL(text);
|
|
29
|
-
return (url.protocol === 'http:' || url.protocol === 'https:') && IMAGE_PATH.test(url.pathname);
|
|
30
|
-
}
|
|
31
|
-
catch {
|
|
32
|
-
return false;
|
|
33
|
-
}
|
|
34
|
-
}
|
|
35
23
|
function isMeasure(key) {
|
|
36
24
|
return !NOT_A_MEASURE.test(key);
|
|
37
25
|
}
|
|
@@ -215,55 +203,41 @@ function chartsIn(value, path, title, units, depth) {
|
|
|
215
203
|
}
|
|
216
204
|
return entries.flatMap(([key, entry]) => chartsIn(unpacked(entry), path ? `${path}.${key}` : key, depth === 0 ? humanize(key) : `${title} › ${humanize(key)}`, unitsOf(value, key), depth + 1));
|
|
217
205
|
}
|
|
218
|
-
/** Image URLs anywhere in the value, first found first, each once. */
|
|
219
|
-
function imagesIn(value, key, depth, found) {
|
|
220
|
-
if (found.size >= MAX_IMAGES || depth > MAX_SEARCH_DEPTH + 1)
|
|
221
|
-
return;
|
|
222
|
-
const inner = unpacked(value);
|
|
223
|
-
if (typeof inner === 'string') {
|
|
224
|
-
if (isImageUrl(inner) && !found.has(inner))
|
|
225
|
-
found.set(inner, { src: inner, alt: humanize(key || 'image') });
|
|
226
|
-
return;
|
|
227
|
-
}
|
|
228
|
-
if (Array.isArray(inner)) {
|
|
229
|
-
for (const item of inner)
|
|
230
|
-
imagesIn(item, key, depth + 1, found);
|
|
231
|
-
return;
|
|
232
|
-
}
|
|
233
|
-
if (isRow(inner))
|
|
234
|
-
for (const [child, entry] of Object.entries(inner))
|
|
235
|
-
imagesIn(entry, child, depth + 1, found);
|
|
236
|
-
}
|
|
237
206
|
/** What a tool's output leads with. Empty when nothing stands out: the data alone reads best. */
|
|
238
207
|
export function layoutResult(output) {
|
|
239
208
|
const value = unpacked(output);
|
|
240
|
-
const images = new Map();
|
|
241
|
-
imagesIn(value, '', 0, images);
|
|
242
209
|
return {
|
|
243
210
|
figures: leadFigures(value),
|
|
244
211
|
charts: chartsIn(value, '', '', undefined, 0).slice(0, MAX_CHARTS),
|
|
245
|
-
images: [...images.values()],
|
|
246
212
|
};
|
|
247
213
|
}
|
|
248
214
|
function mediaSrc(part) {
|
|
249
215
|
return part.mimeType && part.data ? `data:${part.mimeType};base64,${part.data}` : undefined;
|
|
250
216
|
}
|
|
251
|
-
/** The images and audio a call returned, each with its bytes; parts without them are left out. */
|
|
252
|
-
export function returnedMedia(
|
|
217
|
+
/** The images and audio a call returned, each with its bytes; parts without them (references) are left out. */
|
|
218
|
+
export function returnedMedia(parts, imageAlt) {
|
|
253
219
|
const sourced = parts.flatMap((part) => {
|
|
254
220
|
const src = mediaSrc(part);
|
|
255
221
|
return src ? [{ type: part.type, src, mimeType: part.mimeType }] : [];
|
|
256
222
|
});
|
|
257
223
|
return {
|
|
258
|
-
images:
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
],
|
|
224
|
+
images: sourced
|
|
225
|
+
.filter((part) => part.type === 'image')
|
|
226
|
+
.map(({ src }) => ({ src, alt: imageAlt })),
|
|
262
227
|
audio: sourced
|
|
263
228
|
.filter((part) => part.type === 'audio')
|
|
264
229
|
.map(({ src, mimeType }) => ({ src, ...(mimeType ? { mimeType } : {}) })),
|
|
265
230
|
};
|
|
266
231
|
}
|
|
232
|
+
/** The references a call returned, which only the app's resolver turns into something to show. */
|
|
233
|
+
export function referencesIn(parts) {
|
|
234
|
+
return parts.flatMap((part) => part.uri !== undefined && part.mimeType !== undefined && isMediaKind(part.type)
|
|
235
|
+
? [{ type: part.type, mimeType: part.mimeType, uri: part.uri }]
|
|
236
|
+
: []);
|
|
237
|
+
}
|
|
238
|
+
function isMediaKind(type) {
|
|
239
|
+
return MEDIA_INPUT_KIND_VALUES.includes(type);
|
|
240
|
+
}
|
|
267
241
|
/** Whether the result has anything to lead with above its data. */
|
|
268
242
|
export function hasLead(layout, media) {
|
|
269
243
|
return (layout.figures.length + layout.charts.length + media.images.length + media.audio.length > 0);
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
*
|
|
5
5
|
* @module
|
|
6
6
|
*/
|
|
7
|
-
import { reasoningPartSchema, TURN_STOP_KINDS, turnEventSchema, z, } from '@theoremjs/agents';
|
|
7
|
+
import { MEDIA_INPUT_KIND_VALUES, reasoningPartSchema, TURN_STOP_KINDS, turnEventSchema, z, } from '@theoremjs/agents';
|
|
8
8
|
import { guardrailEventSchema } from '@theoremjs/agents/guardrails';
|
|
9
9
|
// why: The block shapes' event parts have one schema, the turn event's; a probe event reuses it.
|
|
10
10
|
function eventPart(probe) {
|
|
@@ -74,8 +74,10 @@ const transcriptBlock = z.discriminatedUnion('kind', [
|
|
|
74
74
|
kind: z.literal('media'),
|
|
75
75
|
mimeType: z.string(),
|
|
76
76
|
data: z.string().optional(),
|
|
77
|
-
|
|
78
|
-
|
|
77
|
+
uri: z.string().optional(),
|
|
78
|
+
type: z.enum(MEDIA_INPUT_KIND_VALUES).optional(),
|
|
79
|
+
fromTool: z.literal(true).optional(),
|
|
80
|
+
sent: z.literal(true).optional(),
|
|
79
81
|
}),
|
|
80
82
|
z.object({
|
|
81
83
|
...blockId,
|
package/client/transport.d.ts
CHANGED
|
@@ -160,6 +160,8 @@ export type ConversationView = {
|
|
|
160
160
|
notify?: {
|
|
161
161
|
retryMs?: number;
|
|
162
162
|
};
|
|
163
|
+
/** Results wait that no reply has read: the page wakes the conversation (`transport.wake`). */
|
|
164
|
+
wake?: true;
|
|
163
165
|
};
|
|
164
166
|
/** Read a conversation: a `/conversation` body. */
|
|
165
167
|
export type TheoremConversationRequest = {
|
|
@@ -167,6 +169,22 @@ export type TheoremConversationRequest = {
|
|
|
167
169
|
};
|
|
168
170
|
/** A `/conversation` body as `createTheoremHandler` reads it. */
|
|
169
171
|
export declare const theoremConversationRequestSchema: z.ZodType<TheoremConversationRequest>;
|
|
172
|
+
/**
|
|
173
|
+
* Wake the conversation: the model takes up the results of its background calls that ended and it
|
|
174
|
+
* has not read, in a reply to no message. A `/wake` body. The host does nothing when no result
|
|
175
|
+
* waits, a reply waits on gates or answers a message, or another wake took them already.
|
|
176
|
+
*/
|
|
177
|
+
export type TheoremWakeRequest = {
|
|
178
|
+
conversation: string;
|
|
179
|
+
/** What the page sends with every message: its option picks and context. */
|
|
180
|
+
input?: Pick<TheoremTurnInput, 'options' | 'context'>;
|
|
181
|
+
model?: string;
|
|
182
|
+
effort?: string;
|
|
183
|
+
/** Client-generated id so the page can stop this reply, as it stops a message's. */
|
|
184
|
+
turnId?: string;
|
|
185
|
+
};
|
|
186
|
+
/** A `/wake` body as `createTheoremHandler` reads it. */
|
|
187
|
+
export declare const theoremWakeRequestSchema: z.ZodType<TheoremWakeRequest>;
|
|
170
188
|
/** Listen for the ends of this session's background calls: a `/notify` body. */
|
|
171
189
|
export type TheoremNotifyRequest = Record<string, never>;
|
|
172
190
|
/** A `/notify` body as `createTheoremHandler` reads it. */
|
|
@@ -214,6 +232,8 @@ export interface TheoremTransport {
|
|
|
214
232
|
conversation(request: TheoremConversationRequest, signal?: AbortSignal): Promise<ConversationView>;
|
|
215
233
|
/** Calls `changed` for each line of the host's push, and settles when the push ends. */
|
|
216
234
|
notify?(changed: () => void, signal: AbortSignal): Promise<void>;
|
|
235
|
+
/** Streams the reply a wake runs; no line at all when the host had nothing to wake for. */
|
|
236
|
+
wake?(request: TheoremWakeRequest, onLine: ChatLineSink, signal?: AbortSignal): Promise<void>;
|
|
217
237
|
/** The conversation cut after a transcript block, under the ref the host issued for it. */
|
|
218
238
|
rewind(request: TheoremRewindRequest, signal?: AbortSignal): Promise<TheoremRewound>;
|
|
219
239
|
pageResult?(result: PageDispatchResult, signal?: AbortSignal): Promise<void>;
|
package/client/transport.js
CHANGED
|
@@ -112,12 +112,23 @@ const conversationView = z.object({
|
|
|
112
112
|
.object({ events: z.array(turnEventSchema), blocks: z.array(transcriptBlockSchema) })
|
|
113
113
|
.optional(),
|
|
114
114
|
notify: z.object({ retryMs: z.number().optional() }).optional(),
|
|
115
|
+
wake: z.literal(true).optional(),
|
|
115
116
|
});
|
|
116
117
|
true;
|
|
117
118
|
const theoremConversationRequest = z.object({ conversation: z.string().min(1) });
|
|
118
119
|
true;
|
|
119
120
|
/** A `/conversation` body as `createTheoremHandler` reads it. */
|
|
120
121
|
export const theoremConversationRequestSchema = theoremConversationRequest;
|
|
122
|
+
const theoremWakeRequest = z.object({
|
|
123
|
+
conversation: z.string().min(1),
|
|
124
|
+
input: theoremTurnInput.pick({ options: true, context: true }).optional(),
|
|
125
|
+
model: z.string().optional(),
|
|
126
|
+
effort: z.string().optional(),
|
|
127
|
+
turnId: clientId.optional(),
|
|
128
|
+
});
|
|
129
|
+
true;
|
|
130
|
+
/** A `/wake` body as `createTheoremHandler` reads it. */
|
|
131
|
+
export const theoremWakeRequestSchema = theoremWakeRequest;
|
|
121
132
|
const theoremNotifyRequest = z.strictObject({});
|
|
122
133
|
/** A `/notify` body as `createTheoremHandler` reads it. */
|
|
123
134
|
export const theoremNotifyRequestSchema = theoremNotifyRequest;
|
|
@@ -353,6 +364,7 @@ export function createHttpTransport(options = {}) {
|
|
|
353
364
|
turn: ({ replay: _replay, ...body }, onEvent, signal) => postNdjson(`${base}/turn`, body, CHAT_LINES, onEvent, { ...options, signal }),
|
|
354
365
|
invoke: ({ replay: _replay, ...body }, onEvent, signal) => postNdjson(`${base}/invoke`, body, CHAT_LINES, onEvent, { ...options, signal }),
|
|
355
366
|
conversation: (body, signal) => fetchConversation(`${base}/conversation`, body, { ...options, signal }),
|
|
367
|
+
wake: (body, onLine, signal) => postNdjson(`${base}/wake`, body, CHAT_LINES, onLine, { ...options, signal }),
|
|
356
368
|
notify: (changed, signal) => postNdjson(`${base}/notify`, {}, NOTIFY_LINES, (line) => {
|
|
357
369
|
if (line.type === 'changed')
|
|
358
370
|
changed();
|
package/client/turn-client.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { type TurnEvent } from '@theoremjs/agents';
|
|
2
2
|
import { type AttachmentValidationIssue, type ComposerProfileInterface, type GatedToolContext, type InterfaceTurnSession, type TranscriptBlock, type UserTurnDraft } from '@theoremjs/agents/interface';
|
|
3
3
|
import type { PagePart } from './tool-resume.ts';
|
|
4
|
-
import type { TheoremInvokeRequest, TheoremReplay, TheoremTurnInput, TheoremTurnRequest } from './transport.ts';
|
|
4
|
+
import type { TheoremInvokeRequest, TheoremReplay, TheoremTurnInput, TheoremTurnRequest, TheoremWakeRequest } from './transport.ts';
|
|
5
5
|
export declare function issuedOperationId(call: {
|
|
6
6
|
operationId?: string;
|
|
7
7
|
}): string;
|
|
@@ -25,6 +25,8 @@ export type RunScope = {
|
|
|
25
25
|
export declare function buildTurnRequest(iface: ComposerProfileInterface, session: InterfaceTurnSession, input: TheoremTurnInput, options?: RunScope & {
|
|
26
26
|
walkAway?: WalkAway;
|
|
27
27
|
}): TheoremTurnRequest;
|
|
28
|
+
/** A wake of `conversation` with the model and effort picked now, as a message would carry them. */
|
|
29
|
+
export declare function buildWakeRequest(iface: ComposerProfileInterface, session: InterfaceTurnSession, conversation: string, scope?: RunScope): TheoremWakeRequest;
|
|
28
30
|
export declare function buildInvokeRequest(iface: ComposerProfileInterface, session: InterfaceTurnSession, args: HeldCall & {
|
|
29
31
|
gateId: string;
|
|
30
32
|
operationId: string;
|
package/client/turn-client.js
CHANGED
|
@@ -60,6 +60,14 @@ export function buildTurnRequest(iface, session, input, options = {}) {
|
|
|
60
60
|
replay: { sessionPermissions: session.sessionPermissions },
|
|
61
61
|
};
|
|
62
62
|
}
|
|
63
|
+
/** A wake of `conversation` with the model and effort picked now, as a message would carry them. */
|
|
64
|
+
export function buildWakeRequest(iface, session, conversation, scope = {}) {
|
|
65
|
+
return {
|
|
66
|
+
conversation,
|
|
67
|
+
...(scope.turnId ? { turnId: scope.turnId } : {}),
|
|
68
|
+
...generationFields(iface, session),
|
|
69
|
+
};
|
|
70
|
+
}
|
|
63
71
|
export function buildInvokeRequest(iface, session, args, scope = {}) {
|
|
64
72
|
return {
|
|
65
73
|
...scopeFields(scope),
|
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.927.g1f89ea0",
|
|
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.927.g1f89ea0"
|
|
29
29
|
}
|
|
30
30
|
}
|
package/server/conversation.d.ts
CHANGED
|
@@ -130,6 +130,11 @@ export type DetachedCall = {
|
|
|
130
130
|
callId: string;
|
|
131
131
|
operationId: string;
|
|
132
132
|
};
|
|
133
|
+
/**
|
|
134
|
+
* The calls a wake would read: none while a reply waits on gates or answers a message just posted.
|
|
135
|
+
* invariant: A wake never runs beside a reply, so it never takes a person's message from one.
|
|
136
|
+
*/
|
|
137
|
+
export declare function wakeableCalls(conversation: StoredConversation): DetachedCall[];
|
|
133
138
|
/** What a reply's model run takes from the host. */
|
|
134
139
|
export type ReplyRunner = {
|
|
135
140
|
/** The reply's events for one run (`runTurn` with the host's own options). */
|
|
@@ -174,6 +179,18 @@ export declare function messageReply(args: {
|
|
|
174
179
|
walkAway?: readonly IssuedWalkAway[];
|
|
175
180
|
runner: ReplyRunner;
|
|
176
181
|
}): AsyncGenerator<ReplyLine>;
|
|
182
|
+
/**
|
|
183
|
+
* The model takes up the results of calls that ended while nothing ran: a reply to no message.
|
|
184
|
+
* It writes nothing until it ends, so a message posted meanwhile keeps the conversation, and this
|
|
185
|
+
* reply ends with no write: that message's reply read the same results.
|
|
186
|
+
*/
|
|
187
|
+
export declare function wakeReply(args: {
|
|
188
|
+
host: ConversationHost;
|
|
189
|
+
opened: OpenedConversation;
|
|
190
|
+
runner: ReplyRunner;
|
|
191
|
+
/** What the page sends with every message: its option picks and context. */
|
|
192
|
+
input?: Pick<TurnInput, 'options' | 'context'>;
|
|
193
|
+
}): AsyncGenerator<ReplyLine>;
|
|
177
194
|
/**
|
|
178
195
|
* The person answers one call the reply waits on. `settling` streams the
|
|
179
196
|
* call's events; once no call waits, the reply goes on in the same stream.
|
package/server/conversation.js
CHANGED
|
@@ -131,13 +131,14 @@ export function conversationView(host, conversation) {
|
|
|
131
131
|
: {}),
|
|
132
132
|
};
|
|
133
133
|
}
|
|
134
|
+
const CONFLICT = { code: 'conversation_conflict' };
|
|
134
135
|
/** Writes `next` over what the request read; a write another request beat is refused. */
|
|
135
136
|
async function save(host, opened, next) {
|
|
136
137
|
const result = await host.store.write(host.sessionId, opened.ref, opened.revision, next);
|
|
137
138
|
if (!result.written) {
|
|
138
139
|
// labels-exempt: internal diagnostic; the user reads error.unavailable
|
|
139
140
|
throw new TheoremError('unavailable', 'the conversation changed while this reply ran', {
|
|
140
|
-
cause:
|
|
141
|
+
cause: CONFLICT,
|
|
141
142
|
});
|
|
142
143
|
}
|
|
143
144
|
return { ref: result.ref, revision: result.revision, conversation: next };
|
|
@@ -161,6 +162,18 @@ function unreadDetachedCalls(transcript) {
|
|
|
161
162
|
? [{ callId: block.tool.callId, operationId: block.tool.operationId }]
|
|
162
163
|
: []);
|
|
163
164
|
}
|
|
165
|
+
/**
|
|
166
|
+
* The calls a wake would read: none while a reply waits on gates or answers a message just posted.
|
|
167
|
+
* invariant: A wake never runs beside a reply, so it never takes a person's message from one.
|
|
168
|
+
*/
|
|
169
|
+
export function wakeableCalls(conversation) {
|
|
170
|
+
if (conversation.paused)
|
|
171
|
+
return [];
|
|
172
|
+
const last = conversation.transcript.at(-1);
|
|
173
|
+
if (!last || last.kind.startsWith('user-'))
|
|
174
|
+
return [];
|
|
175
|
+
return unreadDetachedCalls(conversation.transcript);
|
|
176
|
+
}
|
|
164
177
|
/** The model's history once the reply's events enter it. */
|
|
165
178
|
function replyHistory(reply) {
|
|
166
179
|
return appendAssistantEventsToHistory(reply.base, reply.events.slice(reply.baseEvents));
|
|
@@ -457,14 +470,34 @@ export async function* messageReply(args) {
|
|
|
457
470
|
baseEvents: 0,
|
|
458
471
|
workedMs: 0,
|
|
459
472
|
};
|
|
460
|
-
yield* runReply(host, opened, reply, runner, {
|
|
461
|
-
|
|
473
|
+
yield* runReply(host, opened, reply, runner, { ...message.input, ...historyInput(conversation) }, withMessage);
|
|
474
|
+
}
|
|
475
|
+
/** The conversation's history as a run reads it, with its meters. */
|
|
476
|
+
function historyInput(conversation) {
|
|
477
|
+
return {
|
|
462
478
|
history: conversation.history,
|
|
463
479
|
...(conversation.inputTokens === undefined ? {} : { inputTokens: conversation.inputTokens }),
|
|
464
480
|
...(conversation.historyTokens === undefined
|
|
465
481
|
? {}
|
|
466
482
|
: { historyTokens: conversation.historyTokens }),
|
|
467
|
-
}
|
|
483
|
+
};
|
|
484
|
+
}
|
|
485
|
+
/**
|
|
486
|
+
* The model takes up the results of calls that ended while nothing ran: a reply to no message.
|
|
487
|
+
* It writes nothing until it ends, so a message posted meanwhile keeps the conversation, and this
|
|
488
|
+
* reply ends with no write: that message's reply read the same results.
|
|
489
|
+
*/
|
|
490
|
+
export async function* wakeReply(args) {
|
|
491
|
+
const { host, opened, runner } = args;
|
|
492
|
+
const { conversation } = opened;
|
|
493
|
+
const reply = { base: conversation.history, events: [], baseEvents: 0, workedMs: 0 };
|
|
494
|
+
try {
|
|
495
|
+
yield* runReply(host, opened, reply, runner, { ...args.input, ...historyInput(conversation) }, (history) => history);
|
|
496
|
+
}
|
|
497
|
+
catch (err) {
|
|
498
|
+
if (!(err instanceof TheoremError && err.cause === CONFLICT))
|
|
499
|
+
throw err;
|
|
500
|
+
}
|
|
468
501
|
}
|
|
469
502
|
/**
|
|
470
503
|
* The person answers one call the reply waits on. `settling` streams the
|
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 each time a background
|
|
17
17
|
* call in this session ends. Set `notifier` to serve it
|
|
18
18
|
* - `POST <base>/rewind` → `{ conversation, view }` the conversation cut after one block, and its new ref
|
|
19
|
+
* - `POST <base>/wake` → NDJSON for a reply to no message: the model takes up the results of
|
|
20
|
+
* background calls that ended since it last ran. Empty when none waits
|
|
19
21
|
*
|
|
20
22
|
* `createTheoremHostHandler` serves a host profile the same way, with no model:
|
|
21
23
|
*
|
|
@@ -151,6 +153,15 @@ export type TheoremHandlerOptions = {
|
|
|
151
153
|
status: 'settled';
|
|
152
154
|
}>;
|
|
153
155
|
}) => boolean | Promise<boolean>;
|
|
156
|
+
/**
|
|
157
|
+
* Whether this wake may run its reply: your limit on replies no person asked for. A wake you
|
|
158
|
+
* refuse is not tried again for the same results; the next message reads them. Unset, every wake
|
|
159
|
+
* runs.
|
|
160
|
+
*/
|
|
161
|
+
authorizeWake?: (context: {
|
|
162
|
+
request: Request;
|
|
163
|
+
conversation: string;
|
|
164
|
+
}) => boolean | Promise<boolean>;
|
|
154
165
|
/**
|
|
155
166
|
* Tool credentials by session. Your OAuth callback route saves the token here
|
|
156
167
|
* under the same session id; every turn reads from here. Default: in-process
|
package/server/handler.js
CHANGED
|
@@ -17,6 +17,8 @@ import { checkPageToolTimeout, createMemoryPageToolBroker, pageToolResultSchema,
|
|
|
17
17
|
* - `POST <base>/notify` → NDJSON that stays open: one line now, and one each time a background
|
|
18
18
|
* call in this session ends. Set `notifier` to serve it
|
|
19
19
|
* - `POST <base>/rewind` → `{ conversation, view }` the conversation cut after one block, and its new ref
|
|
20
|
+
* - `POST <base>/wake` → NDJSON for a reply to no message: the model takes up the results of
|
|
21
|
+
* background calls that ended since it last ran. Empty when none waits
|
|
20
22
|
*
|
|
21
23
|
* `createTheoremHostHandler` serves a host profile the same way, with no model:
|
|
22
24
|
*
|
|
@@ -42,12 +44,13 @@ import { caughtStatus, clientError, forClient, HTTP_NOT_FOUND, } from '@theoremj
|
|
|
42
44
|
import { clientProfileInterface, gatedToolsFromEvents, interfaceFromProfile, promotedToolIdsFromEvents, toolSnapshotFromEvents, } from '@theoremjs/agents/interface';
|
|
43
45
|
import { answerGatedCall, resolveGateTtlMs, } from '@theoremjs/agents/kernel';
|
|
44
46
|
import { hostInterface, theoremHostCallRequestSchema, } from "../client/host-transport.js";
|
|
45
|
-
import { theoremConversationRequestSchema, theoremInvokeRequestSchema, theoremNotifyRequestSchema, theoremRewindRequestSchema, theoremSteerRequestSchema, theoremStopRequestSchema, theoremTurnRequestSchema, } from "../client/transport.js";
|
|
46
|
-
import { answerReply, conversationView, messageReply, openConversation, postedMessage, readerConversationHost, requiredOperationId, rewindConversation, statelessRefusal, waitingCalls, } from "./conversation.js";
|
|
47
|
+
import { theoremConversationRequestSchema, theoremInvokeRequestSchema, theoremNotifyRequestSchema, theoremRewindRequestSchema, theoremSteerRequestSchema, theoremStopRequestSchema, theoremTurnRequestSchema, theoremWakeRequestSchema, } from "../client/transport.js";
|
|
48
|
+
import { answerReply, conversationView, messageReply, openConversation, postedMessage, readerConversationHost, requiredOperationId, rewindConversation, statelessRefusal, waitingCalls, wakeableCalls, wakeReply, } from "./conversation.js";
|
|
47
49
|
import { unknownConversation, } from "./conversation-store.js";
|
|
48
50
|
import { createMemoryCredentialStore, } from "./credential-store.js";
|
|
49
51
|
import { sessionStateStore, } from "./session-authority.js";
|
|
50
52
|
import { theoremSession } from "./session-identity.js";
|
|
53
|
+
import { kernelTurnInput } from "./turn-input.js";
|
|
51
54
|
export { theoremSession, theoremSessionId } from "./session-identity.js";
|
|
52
55
|
import { jsonResponse } from "./json-response.js";
|
|
53
56
|
import { boundedRequestJson, requestByteLimit } from "./request-body.js";
|
|
@@ -98,6 +101,7 @@ function routeOf(request) {
|
|
|
98
101
|
last === 'conversation' ||
|
|
99
102
|
last === 'notify' ||
|
|
100
103
|
last === 'rewind' ||
|
|
104
|
+
last === 'wake' ||
|
|
101
105
|
last === 'call' ||
|
|
102
106
|
last === 'page-result'
|
|
103
107
|
? last
|
|
@@ -439,19 +443,30 @@ async function* once(event, labels) {
|
|
|
439
443
|
* A call the host does not let this request replay stays unread, as its block stays withheld.
|
|
440
444
|
*/
|
|
441
445
|
async function withLateResults(ctx, request, turn, operations) {
|
|
442
|
-
const
|
|
443
|
-
|
|
446
|
+
const settled = await readableResults(ctx, request, turn.unread ?? [], operations);
|
|
447
|
+
if (settled.length === 0)
|
|
448
|
+
return turn.input;
|
|
449
|
+
const outcomes = settled.map((operation) => operation.outcome);
|
|
450
|
+
return { ...turn.input, lateResults: [...(turn.input.lateResults ?? []), ...outcomes] };
|
|
451
|
+
}
|
|
452
|
+
/** The calls among `unread` that ended, as this request may read them. */
|
|
453
|
+
async function readableResults(ctx, request, unread, operations) {
|
|
454
|
+
const readable = [];
|
|
455
|
+
for (const { operationId } of unread) {
|
|
444
456
|
const operation = Object.hasOwn(operations, operationId) ? operations[operationId] : undefined;
|
|
445
457
|
if (operation?.status !== 'settled')
|
|
446
458
|
continue;
|
|
447
459
|
const { authorizeToolReplay } = ctx.options;
|
|
448
460
|
if (authorizeToolReplay && !(await authorizeToolReplay({ request, operation })))
|
|
449
461
|
continue;
|
|
450
|
-
|
|
462
|
+
readable.push(operation);
|
|
451
463
|
}
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
464
|
+
return readable;
|
|
465
|
+
}
|
|
466
|
+
/** The results a wake would take up: readable, and no wake has taken them. */
|
|
467
|
+
async function wakeResults(ctx, request, conversation, operations) {
|
|
468
|
+
const readable = await readableResults(ctx, request, wakeableCalls(conversation), operations);
|
|
469
|
+
return readable.filter((operation) => operation.wokenAt === undefined);
|
|
455
470
|
}
|
|
456
471
|
/** One model run of a chat's reply, its gates recorded in the session as they pause. */
|
|
457
472
|
async function* chatTurn(ctx, request, session, turn, key, stop) {
|
|
@@ -573,6 +588,43 @@ async function conversation(ctx, request, session) {
|
|
|
573
588
|
const opened = await openConversation(host, body.conversation, { kind: 'read' });
|
|
574
589
|
return jsonResponse(200, await currentView(ctx, request, session, host, opened.conversation));
|
|
575
590
|
}
|
|
591
|
+
/**
|
|
592
|
+
* A reply to no message, for results that ended since the model last ran. Each result is taken by
|
|
593
|
+
* one wake, before the model runs, so two pages that wake at once run it once, and a wake that
|
|
594
|
+
* fails or is refused is not tried again; the next message reads what it left.
|
|
595
|
+
*/
|
|
596
|
+
async function wake(ctx, request, session) {
|
|
597
|
+
const body = await readBody(request, theoremWakeRequestSchema, ctx.options.maxRequestBytes);
|
|
598
|
+
const host = conversationHost(ctx, session);
|
|
599
|
+
if (!host)
|
|
600
|
+
throw statelessRefusal('wake');
|
|
601
|
+
const opened = await openConversation(host, body.conversation, { kind: 'read' });
|
|
602
|
+
const { operations } = await ctx.sessions.read(session.id);
|
|
603
|
+
const due = await wakeResults(ctx, request, opened.conversation, operations);
|
|
604
|
+
const now = Date.now();
|
|
605
|
+
const taken = due.length
|
|
606
|
+
? await ctx.sessions.mutate(session.id, (state) => due.filter(({ operationId }) => {
|
|
607
|
+
const operation = state.operations[operationId];
|
|
608
|
+
if (operation?.status !== 'settled' || operation.wokenAt !== undefined)
|
|
609
|
+
return false;
|
|
610
|
+
state.operations[operationId] = { ...operation, wokenAt: now };
|
|
611
|
+
return true;
|
|
612
|
+
}))
|
|
613
|
+
: [];
|
|
614
|
+
const { authorizeWake } = ctx.options;
|
|
615
|
+
const allowed = taken.length > 0 &&
|
|
616
|
+
(!authorizeWake || (await authorizeWake({ request, conversation: body.conversation })));
|
|
617
|
+
if (!allowed)
|
|
618
|
+
return eventStream(ctx, request, async function* () { });
|
|
619
|
+
const runner = chatRunner(ctx, request, session, body);
|
|
620
|
+
const input = kernelTurnInput(body.input ?? {}, await ctx.options.context?.(request));
|
|
621
|
+
const { notifier } = ctx.options;
|
|
622
|
+
return eventStream(ctx, request, async function* () {
|
|
623
|
+
yield* wakeReply({ host, opened, runner, input });
|
|
624
|
+
// why: The page that woke draws its reply; any other page open on the session reads it now.
|
|
625
|
+
notifier?.publish(session.id);
|
|
626
|
+
});
|
|
627
|
+
}
|
|
576
628
|
const CHANGED_LINE = new TextEncoder().encode('{"type":"changed"}\n');
|
|
577
629
|
/**
|
|
578
630
|
* One line now, then one for each background call that ends. The stream names no conversation,
|
|
@@ -624,12 +676,14 @@ async function currentView(ctx, request, session, host, conversation) {
|
|
|
624
676
|
const { operations } = await ctx.sessions.read(session.id);
|
|
625
677
|
const transcript = await Promise.all(view.transcript.map((block) => isDetachedBlock(block) ? lateBlock(ctx, request, block, operations, host) : block));
|
|
626
678
|
const { notifier, notifyRetryMs } = ctx.options;
|
|
679
|
+
const due = await wakeResults(ctx, request, conversation, operations);
|
|
627
680
|
return {
|
|
628
681
|
...view,
|
|
629
682
|
transcript,
|
|
630
683
|
...(notifier && transcript.some(isDetachedBlock)
|
|
631
684
|
? { notify: notifyRetryMs === undefined ? {} : { retryMs: notifyRetryMs } }
|
|
632
685
|
: {}),
|
|
686
|
+
...(due.length > 0 ? { wake: true } : {}),
|
|
633
687
|
};
|
|
634
688
|
}
|
|
635
689
|
function isDetachedBlock(block) {
|
|
@@ -908,6 +962,8 @@ async function route(ctx, request, session) {
|
|
|
908
962
|
}
|
|
909
963
|
if (target === 'rewind')
|
|
910
964
|
return rewind(ctx, request, session);
|
|
965
|
+
if (target === 'wake')
|
|
966
|
+
return wake(ctx, request, session);
|
|
911
967
|
if (target === 'stop')
|
|
912
968
|
return stop(ctx, request, session);
|
|
913
969
|
return steer(ctx, request, session);
|
package/server/mcp-handler.js
CHANGED
|
@@ -144,7 +144,8 @@ function callResult(events, labels) {
|
|
|
144
144
|
return {
|
|
145
145
|
content: [
|
|
146
146
|
{ type: 'text', text: tool.readBack ?? '' },
|
|
147
|
-
|
|
147
|
+
// why: A hidden tool's model read only `readBack`; what it sent is for the person, not this agent.
|
|
148
|
+
...(tool.hidden ? [] : (tool.parts ?? []).flatMap(partContent)),
|
|
148
149
|
],
|
|
149
150
|
isError: false,
|
|
150
151
|
};
|
|
@@ -165,17 +166,23 @@ function callResult(events, labels) {
|
|
|
165
166
|
isError: true,
|
|
166
167
|
};
|
|
167
168
|
}
|
|
169
|
+
/**
|
|
170
|
+
* A part as MCP content, as a model reads it: text and bytes. The client is another agent, so a
|
|
171
|
+
* reference, which no model reads, is left out.
|
|
172
|
+
*/
|
|
168
173
|
function partContent(part, index) {
|
|
169
174
|
if (part.type === 'text')
|
|
170
|
-
return { type: 'text', text: part.text };
|
|
171
|
-
if ('
|
|
172
|
-
return
|
|
175
|
+
return [{ type: 'text', text: part.text }];
|
|
176
|
+
if (!('data' in part))
|
|
177
|
+
return [];
|
|
173
178
|
if (part.type === 'image' || part.type === 'audio')
|
|
174
|
-
return { type: part.type, data: part.data, mimeType: part.mimeType };
|
|
175
|
-
return
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
+
return [{ type: part.type, data: part.data, mimeType: part.mimeType }];
|
|
180
|
+
return [
|
|
181
|
+
{
|
|
182
|
+
type: 'resource',
|
|
183
|
+
resource: { uri: `part:${index}`, mimeType: part.mimeType, blob: part.data },
|
|
184
|
+
},
|
|
185
|
+
];
|
|
179
186
|
}
|
|
180
187
|
/** Same origin, or one the host lists; a request with no `Origin` is not from a page. */
|
|
181
188
|
function originAllowed(request, origins) {
|
package/server/mod.d.ts
CHANGED
|
@@ -7,8 +7,8 @@
|
|
|
7
7
|
*/
|
|
8
8
|
export { theoremHostCallRequestSchema } from '../client/host-transport.ts';
|
|
9
9
|
export type { LiveClientMessage, LiveOpenMessage } from '../client/live-messages.ts';
|
|
10
|
-
export { type StatedTurn, theoremConversationRequestSchema, theoremInvokeRequestSchema, theoremNotifyRequestSchema, theoremReplaySchema, theoremRewindRequestSchema, theoremStartRequestSchema, theoremSteerRequestSchema, theoremStopRequestSchema, theoremTurnRequestSchema, } from '../client/transport.ts';
|
|
11
|
-
export { answerReply, type ConversationHost, type ConversationUse, conversationView, type IssuedWalkAway, messageReply, type OpenedConversation, openConversation, type PostedMessage, postedMessage, type ReplyLine, type ReplyRunner, type ReplyTurn, readerConversationHost, rewindConversation, startConversation, statelessRefusal, type WalkedAwayCall, waitingCalls, } from './conversation.ts';
|
|
10
|
+
export { type StatedTurn, theoremConversationRequestSchema, theoremInvokeRequestSchema, theoremNotifyRequestSchema, theoremReplaySchema, theoremRewindRequestSchema, theoremStartRequestSchema, theoremSteerRequestSchema, theoremStopRequestSchema, theoremTurnRequestSchema, theoremWakeRequestSchema, } from '../client/transport.ts';
|
|
11
|
+
export { answerReply, type ConversationHost, type ConversationUse, conversationView, type IssuedWalkAway, messageReply, type OpenedConversation, openConversation, type PostedMessage, postedMessage, type ReplyLine, type ReplyRunner, type ReplyTurn, readerConversationHost, rewindConversation, startConversation, statelessRefusal, type WalkedAwayCall, waitingCalls, wakeableCalls, wakeReply, } from './conversation.ts';
|
|
12
12
|
export { type ConversationSnapshot, type ConversationWriteResult, createMemoryConversationStore, createSealedConversationStore, emptyConversation, type PausedReply, type SealedConversationStoreOptions, type StoredConversation, storedConversationSchema, type TheoremConversationStore, unknownConversation, } from './conversation-store.ts';
|
|
13
13
|
export { createMemoryCredentialStore, type TheoremCredentialStore, type TheoremCredentials, } from './credential-store.ts';
|
|
14
14
|
export { createTheoremDecisionHandler, type DecisionQuestionsBuilder, isQuestionsBuilder, type TheoremDecisionHandlerOptions, } from './decision-handler.ts';
|
package/server/mod.js
CHANGED
|
@@ -6,8 +6,8 @@
|
|
|
6
6
|
* @module
|
|
7
7
|
*/
|
|
8
8
|
export { theoremHostCallRequestSchema } from "../client/host-transport.js";
|
|
9
|
-
export { theoremConversationRequestSchema, theoremInvokeRequestSchema, theoremNotifyRequestSchema, theoremReplaySchema, theoremRewindRequestSchema, theoremStartRequestSchema, theoremSteerRequestSchema, theoremStopRequestSchema, theoremTurnRequestSchema, } from "../client/transport.js";
|
|
10
|
-
export { answerReply, conversationView, messageReply, openConversation, postedMessage, readerConversationHost, rewindConversation, startConversation, statelessRefusal, waitingCalls, } from "./conversation.js";
|
|
9
|
+
export { theoremConversationRequestSchema, theoremInvokeRequestSchema, theoremNotifyRequestSchema, theoremReplaySchema, theoremRewindRequestSchema, theoremStartRequestSchema, theoremSteerRequestSchema, theoremStopRequestSchema, theoremTurnRequestSchema, theoremWakeRequestSchema, } from "../client/transport.js";
|
|
10
|
+
export { answerReply, conversationView, messageReply, openConversation, postedMessage, readerConversationHost, rewindConversation, startConversation, statelessRefusal, waitingCalls, wakeableCalls, wakeReply, } from "./conversation.js";
|
|
11
11
|
export { createMemoryConversationStore, createSealedConversationStore, emptyConversation, storedConversationSchema, unknownConversation, } from "./conversation-store.js";
|
|
12
12
|
export { createMemoryCredentialStore, } from "./credential-store.js";
|
|
13
13
|
export { createTheoremDecisionHandler, isQuestionsBuilder, } from "./decision-handler.js";
|
|
@@ -61,6 +61,8 @@ export type SessionToolOperation = {
|
|
|
61
61
|
reply?: ToolOperationReply;
|
|
62
62
|
settledAt: number;
|
|
63
63
|
retainUntil?: number;
|
|
64
|
+
/** When a wake took this result up. invariant: one wake per result; a message still reads it. */
|
|
65
|
+
wokenAt?: number;
|
|
64
66
|
}) | (ToolOperationIdentity & {
|
|
65
67
|
status: 'uncertain';
|
|
66
68
|
pageGrant?: SessionPageGrant;
|
package/server/session-store.js
CHANGED
|
@@ -144,6 +144,7 @@ const operationSchema = z.discriminatedUnion('status', [
|
|
|
144
144
|
reply: toolOperationReplySchema.optional(),
|
|
145
145
|
settledAt: z.number().finite().nonnegative(),
|
|
146
146
|
retainUntil: z.number().finite().nonnegative().optional(),
|
|
147
|
+
wokenAt: z.number().finite().nonnegative().optional(),
|
|
147
148
|
}),
|
|
148
149
|
z.strictObject({
|
|
149
150
|
...identityFields,
|