@theoremjs/web 0.0.0-stage → 0.3.4-next.375.ga2d1878
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +493 -2
- package/client/audio-level.d.ts +5 -0
- package/client/audio-level.js +24 -0
- package/client/chat.d.ts +144 -0
- package/client/chat.js +760 -0
- package/client/composer-drawer.d.ts +19 -0
- package/client/composer-drawer.js +15 -0
- package/client/composer-hints.d.ts +25 -0
- package/client/composer-hints.js +20 -0
- package/client/composer-primary.d.ts +18 -0
- package/client/composer-primary.js +29 -0
- package/client/decision-transport.d.ts +70 -0
- package/client/decision-transport.js +175 -0
- package/client/decode-composer-draft.d.ts +11 -0
- package/client/decode-composer-draft.js +12 -0
- package/client/embedding-input.d.ts +84 -0
- package/client/embedding-input.js +194 -0
- package/client/embedding-space.d.ts +82 -0
- package/client/embedding-space.js +389 -0
- package/client/embedding-transport.d.ts +40 -0
- package/client/embedding-transport.js +71 -0
- package/client/encode-composer-draft.d.ts +9 -0
- package/client/encode-composer-draft.js +34 -0
- package/client/encode-files.d.ts +18 -0
- package/client/encode-files.js +54 -0
- package/client/failure.d.ts +29 -0
- package/client/failure.js +34 -0
- package/client/generation-selection.d.ts +15 -0
- package/client/generation-selection.js +24 -0
- package/client/host-transport.d.ts +70 -0
- package/client/host-transport.js +75 -0
- package/client/index.d.ts +37 -0
- package/client/index.js +31 -0
- package/client/live/live-mic-forward.d.ts +30 -0
- package/client/live/live-mic-forward.js +46 -0
- package/client/live/live-page-tool.d.ts +39 -0
- package/client/live/live-page-tool.js +26 -0
- package/client/live/live-state.d.ts +13 -0
- package/client/live/live-state.js +22 -0
- package/client/live/live-tool.d.ts +11 -0
- package/client/live/live-tool.js +1 -0
- package/client/live-client.d.ts +189 -0
- package/client/live-client.js +829 -0
- package/client/live-errors.d.ts +2 -0
- package/client/live-errors.js +9 -0
- package/client/live-messages.d.ts +148 -0
- package/client/live-messages.js +100 -0
- package/client/mic-capture.d.ts +4 -0
- package/client/mic-capture.js +6 -0
- package/client/oauth-popup.d.ts +26 -0
- package/client/oauth-popup.js +30 -0
- package/client/page-dispatch.d.ts +15 -0
- package/client/page-dispatch.js +63 -0
- package/client/pcm-downsample.d.ts +4 -0
- package/client/pcm-downsample.js +45 -0
- package/client/run-commit.d.ts +34 -0
- package/client/run-commit.js +49 -0
- package/client/run-session.d.ts +79 -0
- package/client/run-session.js +207 -0
- package/client/schema-fields.d.ts +63 -0
- package/client/schema-fields.js +199 -0
- package/client/shaped-data.d.ts +118 -0
- package/client/shaped-data.js +343 -0
- package/client/source-citations.d.ts +13 -0
- package/client/source-citations.js +56 -0
- package/client/space-geometry.d.ts +39 -0
- package/client/space-geometry.js +183 -0
- package/client/tool-result.d.ts +78 -0
- package/client/tool-result.js +293 -0
- package/client/tool-resume.d.ts +50 -0
- package/client/tool-resume.js +14 -0
- package/client/trace-feed.d.ts +13 -0
- package/client/trace-feed.js +18 -0
- package/client/transcript-schema.d.ts +10 -0
- package/client/transcript-schema.js +120 -0
- package/client/transport.d.ts +264 -0
- package/client/transport.js +330 -0
- package/client/turn-client.d.ts +44 -0
- package/client/turn-client.js +88 -0
- package/client/wire-line.d.ts +56 -0
- package/client/wire-line.js +90 -0
- package/client/worklets/mic-capture.js +16 -0
- package/package.json +28 -4
- package/server/checkpoint-ownership.d.ts +6 -0
- package/server/checkpoint-ownership.js +42 -0
- package/server/conversation-store.d.ts +92 -0
- package/server/conversation-store.js +131 -0
- package/server/conversation.d.ts +193 -0
- package/server/conversation.js +552 -0
- package/server/credential-store.d.ts +24 -0
- package/server/credential-store.js +14 -0
- package/server/decision-handler.d.ts +42 -0
- package/server/decision-handler.js +46 -0
- package/server/embedding-handler.d.ts +33 -0
- package/server/embedding-handler.js +45 -0
- package/server/handler.d.ts +158 -0
- package/server/handler.js +775 -0
- package/server/json-response.d.ts +2 -0
- package/server/json-response.js +7 -0
- package/server/mcp-handler.d.ts +46 -0
- package/server/mcp-handler.js +312 -0
- package/server/mod.d.ts +27 -0
- package/server/mod.js +25 -0
- package/server/page-dispatch.d.ts +22 -0
- package/server/page-dispatch.js +127 -0
- package/server/request-body.d.ts +2 -0
- package/server/request-body.js +42 -0
- package/server/request-check.d.ts +21 -0
- package/server/request-check.js +49 -0
- package/server/session-authority.d.ts +8 -0
- package/server/session-authority.js +78 -0
- package/server/session-boundary.d.ts +26 -0
- package/server/session-boundary.js +64 -0
- package/server/session-identity.d.ts +16 -0
- package/server/session-identity.js +41 -0
- package/server/session-limits.d.ts +12 -0
- package/server/session-limits.js +59 -0
- package/server/session-store.d.ts +123 -0
- package/server/session-store.js +264 -0
- package/server/single-action.d.ts +21 -0
- package/server/single-action.js +30 -0
- package/server/steer-inbox.d.ts +35 -0
- package/server/steer-inbox.js +52 -0
- package/server/tool-operations.d.ts +6 -0
- package/server/tool-operations.js +132 -0
- package/server/turn-input.d.ts +10 -0
- package/server/turn-input.js +29 -0
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
import { type GateReference, type ToolGate } from '@theoremjs/agents';
|
|
2
|
+
import type { PageDispatchResult } from './page-dispatch.ts';
|
|
3
|
+
/**
|
|
4
|
+
* Transport contract between a Theorem chat UI and the host that runs turns.
|
|
5
|
+
*
|
|
6
|
+
* The browser never holds the profile: it asks the transport to `describe` the
|
|
7
|
+
* profile's client-safe interface, then streams turns / tool invokes through it.
|
|
8
|
+
* `createHttpTransport` speaks to `createTheoremHandler` (`@theoremjs/web/server`);
|
|
9
|
+
* hosts with their own wire format implement {@link TheoremTransport} directly.
|
|
10
|
+
*
|
|
11
|
+
* @module
|
|
12
|
+
*/
|
|
13
|
+
import { type ErrorKind, type TurnEvent, type TurnHistoryMessage, type TurnToolSnapshot, z } from '@theoremjs/agents';
|
|
14
|
+
import { type ErrorCopies } from '@theoremjs/agents/guardrails';
|
|
15
|
+
import { type ProfileInterface, type TranscriptBlock } from '@theoremjs/agents/interface';
|
|
16
|
+
import type { PagePart } from './tool-resume.ts';
|
|
17
|
+
import type { TraceFeed } from './trace-feed.ts';
|
|
18
|
+
import { type MalformedEvent, type UnsupportedEvent, type WireLines } from './wire-line.ts';
|
|
19
|
+
export type { MalformedEvent, UnsupportedEvent, WireLines } from './wire-line.ts';
|
|
20
|
+
export type EncodedBlob = {
|
|
21
|
+
name: string;
|
|
22
|
+
mimeType: string;
|
|
23
|
+
data: string;
|
|
24
|
+
};
|
|
25
|
+
/** Turn input as sent over the wire (media is base64-encoded). */
|
|
26
|
+
export type TheoremTurnInput = {
|
|
27
|
+
text?: string;
|
|
28
|
+
attachments?: EncodedBlob[];
|
|
29
|
+
voice?: EncodedBlob[];
|
|
30
|
+
/** The value chosen for each of the profile's `inputs.slots`. */
|
|
31
|
+
slots?: Record<string, string>;
|
|
32
|
+
/** What the page wants the agent to know: any JSON. The host reads it as untrusted. */
|
|
33
|
+
context?: unknown;
|
|
34
|
+
};
|
|
35
|
+
/**
|
|
36
|
+
* State only the client holds, for hosts whose profile also lives in the browser
|
|
37
|
+
* (the studio). `createHttpTransport` never sends it: `createTheoremHandler`
|
|
38
|
+
* keeps permissions, paused calls, and tool snapshots in its own session.
|
|
39
|
+
*/
|
|
40
|
+
export type TheoremReplay = {
|
|
41
|
+
gateKind?: ToolGate['kind'];
|
|
42
|
+
sessionPermissions?: string[];
|
|
43
|
+
name?: string;
|
|
44
|
+
input?: unknown;
|
|
45
|
+
snapshot?: TurnToolSnapshot;
|
|
46
|
+
promoted?: string[];
|
|
47
|
+
model?: string;
|
|
48
|
+
effort?: string;
|
|
49
|
+
};
|
|
50
|
+
/** For a host that reads the studio's client-held state. */
|
|
51
|
+
export declare const theoremReplaySchema: z.ZodType<TheoremReplay>;
|
|
52
|
+
/**
|
|
53
|
+
* One message. The host resolves the profile and owns the conversation: the
|
|
54
|
+
* client sends only the message and the ref of the conversation it continues.
|
|
55
|
+
*
|
|
56
|
+
* A message sent while the reply waits on gates walks away from them: `abandon`
|
|
57
|
+
* names the waiting calls. The host settles each one cancelled, streams those
|
|
58
|
+
* events first, and gives the model each call's answer before the message.
|
|
59
|
+
*/
|
|
60
|
+
export type TheoremTurnRequest = {
|
|
61
|
+
input: TheoremTurnInput;
|
|
62
|
+
/** The ref of the conversation this message continues; none starts one. */
|
|
63
|
+
conversation?: string;
|
|
64
|
+
model?: string;
|
|
65
|
+
effort?: string;
|
|
66
|
+
/** Client-generated id so mid-turn steers can find this turn's inbox. */
|
|
67
|
+
turnId?: string;
|
|
68
|
+
/** invariant: Both issued IDs identify each paused action that this message abandons. */
|
|
69
|
+
abandon?: GateReference[];
|
|
70
|
+
/** The tools the person allowed for the page, for a host without a session (the studio). */
|
|
71
|
+
replay?: Pick<TheoremReplay, 'sessionPermissions'>;
|
|
72
|
+
/**
|
|
73
|
+
* The page's transcript before this message, sent only after the host answered that it can no
|
|
74
|
+
* longer open `conversation` (`session.conversation_unknown`). A host that restores from it (the
|
|
75
|
+
* studio) goes on from it under a new ref; `createTheoremHandler` keeps the conversation its own
|
|
76
|
+
* and does not.
|
|
77
|
+
*/
|
|
78
|
+
transcript?: TranscriptBlock[];
|
|
79
|
+
};
|
|
80
|
+
/** A `/turn` body as `createTheoremHandler` reads it. */
|
|
81
|
+
export declare const theoremTurnRequestSchema: z.ZodType<TheoremTurnRequest>;
|
|
82
|
+
/** What the user answers a gate with; walking away rides on the next message (`TheoremTurnRequest.abandon`). */
|
|
83
|
+
declare const INVOKE_DECISIONS: readonly ["approve", "deny"];
|
|
84
|
+
/**
|
|
85
|
+
* The user's answer to a tool call the host paused on a gate. `approve` runs it
|
|
86
|
+
* (with `input` when the user edited it); `deny` refuses it. The host settles
|
|
87
|
+
* each one, so the model and the trace read what the user chose. The tool's
|
|
88
|
+
* registered permission decides how long an approval lasts, not the client.
|
|
89
|
+
*/
|
|
90
|
+
export type TheoremInvokeRequest = {
|
|
91
|
+
/** Call id of the paused tool call (`tool.callId` on its gate event). */
|
|
92
|
+
gateId: string;
|
|
93
|
+
operationId: string;
|
|
94
|
+
decision: (typeof INVOKE_DECISIONS)[number];
|
|
95
|
+
/** The user's edit of the model's input; only with `approve`. */
|
|
96
|
+
input?: unknown;
|
|
97
|
+
/**
|
|
98
|
+
* The key or token the user typed at a bearer or API-key sign-in gate, only
|
|
99
|
+
* with `approve`. The server saves it for the session and never sends it
|
|
100
|
+
* back; an OAuth gate resumes with the gate id alone, once the host's
|
|
101
|
+
* callback saved the token.
|
|
102
|
+
*/
|
|
103
|
+
secret?: string;
|
|
104
|
+
/** The page's answer to a `page` gate, only with `approve`: the tool's output schema checks it. */
|
|
105
|
+
page?: PagePart;
|
|
106
|
+
/** The ref of the conversation whose reply waits on the gate. */
|
|
107
|
+
conversation?: string;
|
|
108
|
+
/** Client-generated id so steers sent while the reply goes on find its inbox. */
|
|
109
|
+
turnId?: string;
|
|
110
|
+
replay?: TheoremReplay;
|
|
111
|
+
};
|
|
112
|
+
/** An `/invoke` body as `createTheoremHandler` reads it. */
|
|
113
|
+
export declare const theoremInvokeRequestSchema: z.ZodType<TheoremInvokeRequest>;
|
|
114
|
+
/** Inject user messages into an in-flight turn. */
|
|
115
|
+
export type TheoremSteerRequest = {
|
|
116
|
+
turnId: string;
|
|
117
|
+
/** The client's id for this steer; the turn's `stage` event names it in `injected` once it lands. */
|
|
118
|
+
id: string;
|
|
119
|
+
inject: TurnHistoryMessage[];
|
|
120
|
+
};
|
|
121
|
+
/** A `/steer` body as `createTheoremHandler` reads it. */
|
|
122
|
+
export declare const theoremSteerRequestSchema: z.ZodType<TheoremSteerRequest>;
|
|
123
|
+
/**
|
|
124
|
+
* The ref the store issued for the conversation a run wrote: the client sends
|
|
125
|
+
* it with its next request. It comes before the run's error, which ends the stream.
|
|
126
|
+
* `posted` marks the write that holds the person's new message: a run that
|
|
127
|
+
* fails before it leaves the message unsent.
|
|
128
|
+
*/
|
|
129
|
+
export type ConversationLine = {
|
|
130
|
+
type: 'conversation';
|
|
131
|
+
ref: string;
|
|
132
|
+
posted?: true;
|
|
133
|
+
};
|
|
134
|
+
/** The lines a chat's reply streams: turn events, and the conversation's ref. */
|
|
135
|
+
export declare const CHAT_LINES: WireLines<TurnEvent | ConversationLine>;
|
|
136
|
+
/** What the browser draws: the transcript, and the reply that waits on gates. */
|
|
137
|
+
export type ConversationView = {
|
|
138
|
+
transcript: TranscriptBlock[];
|
|
139
|
+
/** The reply that waits on gates: its events, and its blocks as the transcript will keep them. */
|
|
140
|
+
paused?: {
|
|
141
|
+
events: TurnEvent[];
|
|
142
|
+
blocks: TranscriptBlock[];
|
|
143
|
+
};
|
|
144
|
+
};
|
|
145
|
+
/** Read a conversation: a `/conversation` body. */
|
|
146
|
+
export type TheoremConversationRequest = {
|
|
147
|
+
conversation: string;
|
|
148
|
+
};
|
|
149
|
+
/** A `/conversation` body as `createTheoremHandler` reads it. */
|
|
150
|
+
export declare const theoremConversationRequestSchema: z.ZodType<TheoremConversationRequest>;
|
|
151
|
+
/**
|
|
152
|
+
* Cut the conversation after transcript block `at` (-1 empties it): a
|
|
153
|
+
* `/rewind` body. A reply waiting on gates is walked away from first.
|
|
154
|
+
*/
|
|
155
|
+
export type TheoremRewindRequest = {
|
|
156
|
+
conversation: string;
|
|
157
|
+
at: number;
|
|
158
|
+
};
|
|
159
|
+
/** A `/rewind` body as `createTheoremHandler` reads it. */
|
|
160
|
+
export declare const theoremRewindRequestSchema: z.ZodType<TheoremRewindRequest>;
|
|
161
|
+
/** A rewound conversation: its new ref, and what the browser draws. */
|
|
162
|
+
export type TheoremRewound = {
|
|
163
|
+
conversation: string;
|
|
164
|
+
view: ConversationView;
|
|
165
|
+
};
|
|
166
|
+
/** A turn event, one of a kind this client does not know (`unsupported`), or one that failed its check (`malformed`). */
|
|
167
|
+
export type ClientTurnEvent = TurnEvent | UnsupportedEvent | MalformedEvent;
|
|
168
|
+
export type TurnEventSink = (event: ClientTurnEvent) => void;
|
|
169
|
+
/** A line of a chat's reply: a turn event, or the ref of the conversation it wrote. */
|
|
170
|
+
export type ChatLine = ClientTurnEvent | ConversationLine;
|
|
171
|
+
export type ChatLineSink = (line: ChatLine) => void;
|
|
172
|
+
export interface TheoremTransport {
|
|
173
|
+
/** Client-safe interface for the host's profile (inputs, models, guardrail view). */
|
|
174
|
+
describe(signal?: AbortSignal): Promise<ProfileInterface>;
|
|
175
|
+
turn(request: TheoremTurnRequest, onLine: ChatLineSink, signal?: AbortSignal): Promise<void>;
|
|
176
|
+
invoke(request: TheoremInvokeRequest, onLine: ChatLineSink, signal?: AbortSignal): Promise<void>;
|
|
177
|
+
steer(request: TheoremSteerRequest): Promise<void>;
|
|
178
|
+
/** The conversation under `ref`, as the host shows it. */
|
|
179
|
+
conversation(request: TheoremConversationRequest, signal?: AbortSignal): Promise<ConversationView>;
|
|
180
|
+
/** The conversation cut after a transcript block, under the ref the host issued for it. */
|
|
181
|
+
rewind(request: TheoremRewindRequest, signal?: AbortSignal): Promise<TheoremRewound>;
|
|
182
|
+
pageResult?(result: PageDispatchResult, signal?: AbortSignal): Promise<void>;
|
|
183
|
+
/** Trace records the host sends back, when it delivers them (the studio does). */
|
|
184
|
+
traces?: TraceFeed;
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* A failure the host reported: its kind, the host's wording when it sent one
|
|
188
|
+
* (the profile's labels, applied on the host), and raw detail when the host
|
|
189
|
+
* exposes it. `clientFailure` words it for the user.
|
|
190
|
+
*/
|
|
191
|
+
export declare class TheoremStreamError extends Error {
|
|
192
|
+
readonly kind: ErrorKind;
|
|
193
|
+
readonly publicMessage?: string;
|
|
194
|
+
readonly internalMessage?: string;
|
|
195
|
+
/** The labels key behind `publicMessage`, when the host gave one: what failed, more exactly than `kind`. */
|
|
196
|
+
readonly copy?: ErrorCopies;
|
|
197
|
+
constructor(kind: ErrorKind, publicMessage?: string, internalMessage?: string, copy?: ErrorCopies);
|
|
198
|
+
}
|
|
199
|
+
export declare function isTheoremStreamError(err: unknown): err is TheoremStreamError;
|
|
200
|
+
/** A host error reply's body (JSON reply or `{ type: 'error' }` stream line). */
|
|
201
|
+
export type HostErrorBody = {
|
|
202
|
+
error?: string;
|
|
203
|
+
errorKind?: ErrorKind;
|
|
204
|
+
/** The labels key behind `error`, when more specific than the kind's. */
|
|
205
|
+
errorCopy?: ErrorCopies;
|
|
206
|
+
errorInternal?: string;
|
|
207
|
+
};
|
|
208
|
+
/** A host's error body, as the transport and the live client read it. */
|
|
209
|
+
export declare const hostErrorBodySchema: z.ZodType<HostErrorBody>;
|
|
210
|
+
/** A host's error body as a failure: its kind (else `fallbackKind`), wording, and detail. */
|
|
211
|
+
export declare function hostError(body: HostErrorBody, fallbackKind: ErrorKind): TheoremStreamError;
|
|
212
|
+
/** The host could not open the message's conversation (`session.conversation_unknown`). */
|
|
213
|
+
export declare function isUnknownConversation(err: unknown): boolean;
|
|
214
|
+
/**
|
|
215
|
+
* Read an NDJSON reply, checking each line against `lines`: a kind it doesn't
|
|
216
|
+
* list reaches `onLine` as `unsupported`, and a line that fails its check as
|
|
217
|
+
* `malformed`; the stream goes on. An `error` line ends it.
|
|
218
|
+
*/
|
|
219
|
+
export declare function readNdjsonStream<Line extends {
|
|
220
|
+
type: string;
|
|
221
|
+
}>(response: Response, lines: WireLines<Line>, onLine: (line: Line | UnsupportedEvent | MalformedEvent) => void, signal?: AbortSignal): Promise<void>;
|
|
222
|
+
export type HttpOptions = {
|
|
223
|
+
fetch?: typeof fetch;
|
|
224
|
+
/** Extra request headers (auth tokens, CSRF). A function is re-read per request. */
|
|
225
|
+
headers?: HeadersInit | (() => HeadersInit | Promise<HeadersInit>);
|
|
226
|
+
/** Cookie policy. Default `same-origin`; use `include` when the handler is on another origin. */
|
|
227
|
+
credentials?: RequestCredentials;
|
|
228
|
+
};
|
|
229
|
+
/**
|
|
230
|
+
* POST JSON and stream NDJSON lines back, each checked against `lines`: turn
|
|
231
|
+
* events ({@link TURN_EVENT_SCHEMAS}), or a host's own schema beside them.
|
|
232
|
+
*/
|
|
233
|
+
export declare function postNdjson<Line extends {
|
|
234
|
+
type: string;
|
|
235
|
+
}>(url: string, body: unknown, lines: WireLines<Line>, onLine: (line: Line | UnsupportedEvent | MalformedEvent) => void, options?: HttpOptions & {
|
|
236
|
+
signal?: AbortSignal;
|
|
237
|
+
}): Promise<void>;
|
|
238
|
+
/** POST JSON; a non-OK reply throws its failure. The OK reply's body is not read. */
|
|
239
|
+
export declare function postJson(url: string, body: unknown, options?: HttpOptions & {
|
|
240
|
+
signal?: AbortSignal;
|
|
241
|
+
}): Promise<void>;
|
|
242
|
+
/**
|
|
243
|
+
* GET, or POST `body` as JSON, and read the JSON reply; a non-OK reply throws its failure, after
|
|
244
|
+
* `failed` has read whatever else its JSON body carries.
|
|
245
|
+
*/
|
|
246
|
+
export declare function fetchJson(url: string, init: {
|
|
247
|
+
body?: unknown;
|
|
248
|
+
signal?: AbortSignal;
|
|
249
|
+
failed?: (body: unknown) => void;
|
|
250
|
+
}, options?: HttpOptions): Promise<unknown>;
|
|
251
|
+
/** POST a conversation's read to `url`, and check the view the host answers. */
|
|
252
|
+
export declare function fetchConversation(url: string, body: unknown, options?: HttpOptions & {
|
|
253
|
+
signal?: AbortSignal;
|
|
254
|
+
}): Promise<ConversationView>;
|
|
255
|
+
/** POST a rewind to `url`, and check the rewound conversation the host answers. */
|
|
256
|
+
export declare function fetchRewound(url: string, body: unknown, options?: HttpOptions & {
|
|
257
|
+
signal?: AbortSignal;
|
|
258
|
+
}): Promise<TheoremRewound>;
|
|
259
|
+
export type HttpTransportOptions = HttpOptions & {
|
|
260
|
+
/** Base URL where `createTheoremHandler` is mounted. Default `/api/theorem`. */
|
|
261
|
+
endpoint?: string;
|
|
262
|
+
};
|
|
263
|
+
/** Transport for a host mounted with `createTheoremHandler`. */
|
|
264
|
+
export declare function createHttpTransport(options?: HttpTransportOptions): TheoremTransport;
|
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
import { gateReferenceSchema, TOOL_GATE_KINDS, } from '@theoremjs/agents';
|
|
2
|
+
/**
|
|
3
|
+
* Transport contract between a Theorem chat UI and the host that runs turns.
|
|
4
|
+
*
|
|
5
|
+
* The browser never holds the profile: it asks the transport to `describe` the
|
|
6
|
+
* profile's client-safe interface, then streams turns / tool invokes through it.
|
|
7
|
+
* `createHttpTransport` speaks to `createTheoremHandler` (`@theoremjs/web/server`);
|
|
8
|
+
* hosts with their own wire format implement {@link TheoremTransport} directly.
|
|
9
|
+
*
|
|
10
|
+
* @module
|
|
11
|
+
*/
|
|
12
|
+
import { describeError, errorKindSchema, isAbortError, TheoremError, TURN_EVENT_SCHEMAS, throwIfAborted, turnEventSchema, turnHistoryMessageSchema, turnToolSnapshotSchema, z, } from '@theoremjs/agents';
|
|
13
|
+
import { errorCopiesSchema, kindOfHttpStatus, } from '@theoremjs/agents/guardrails';
|
|
14
|
+
import { profileInterfaceSchema, } from '@theoremjs/agents/interface';
|
|
15
|
+
import { transcriptBlockSchema } from "./transcript-schema.js";
|
|
16
|
+
import { checkWire, parseWireJson, readWireLine, } from "./wire-line.js";
|
|
17
|
+
const encodedBlob = z.object({ name: z.string(), mimeType: z.string(), data: z.string() });
|
|
18
|
+
true;
|
|
19
|
+
const theoremTurnInput = z.object({
|
|
20
|
+
slots: z.record(z.string(), z.string()).optional(),
|
|
21
|
+
context: z.unknown().optional(),
|
|
22
|
+
text: z.string().optional(),
|
|
23
|
+
attachments: z.array(encodedBlob).optional(),
|
|
24
|
+
voice: z.array(encodedBlob).optional(),
|
|
25
|
+
});
|
|
26
|
+
true;
|
|
27
|
+
const theoremReplay = z.object({
|
|
28
|
+
gateKind: z.enum(TOOL_GATE_KINDS).optional(),
|
|
29
|
+
sessionPermissions: z.array(z.string()).optional(),
|
|
30
|
+
name: z.string().optional(),
|
|
31
|
+
input: z.unknown().optional(),
|
|
32
|
+
snapshot: turnToolSnapshotSchema.optional(),
|
|
33
|
+
promoted: z.array(z.string()).optional(),
|
|
34
|
+
model: z.string().optional(),
|
|
35
|
+
effort: z.string().optional(),
|
|
36
|
+
});
|
|
37
|
+
true;
|
|
38
|
+
/** For a host that reads the studio's client-held state. */
|
|
39
|
+
export const theoremReplaySchema = theoremReplay;
|
|
40
|
+
/** An id the client made: trimmed, never blank. */
|
|
41
|
+
const clientId = z.string().trim().min(1);
|
|
42
|
+
const theoremTurnRequest = z.object({
|
|
43
|
+
input: theoremTurnInput,
|
|
44
|
+
conversation: z.string().min(1).optional(),
|
|
45
|
+
model: z.string().optional(),
|
|
46
|
+
effort: z.string().optional(),
|
|
47
|
+
turnId: clientId.optional(),
|
|
48
|
+
abandon: z.array(gateReferenceSchema).min(1).optional(),
|
|
49
|
+
replay: theoremReplay.pick({ sessionPermissions: true }).optional(),
|
|
50
|
+
transcript: z.array(transcriptBlockSchema).optional(),
|
|
51
|
+
});
|
|
52
|
+
true;
|
|
53
|
+
/** A `/turn` body as `createTheoremHandler` reads it. */
|
|
54
|
+
export const theoremTurnRequestSchema = theoremTurnRequest;
|
|
55
|
+
/** What the user answers a gate with; walking away rides on the next message (`TheoremTurnRequest.abandon`). */
|
|
56
|
+
const INVOKE_DECISIONS = ['approve', 'deny'];
|
|
57
|
+
const pagePart = z.union([
|
|
58
|
+
z.strictObject({ unanswered: z.literal(true) }),
|
|
59
|
+
z
|
|
60
|
+
.strictObject({ output: z.unknown() })
|
|
61
|
+
.refine((part) => 'output' in part)
|
|
62
|
+
.transform((part) => ({ output: part.output })),
|
|
63
|
+
]);
|
|
64
|
+
const theoremInvokeRequest = z.object({
|
|
65
|
+
gateId: z.string().min(1),
|
|
66
|
+
operationId: z.string().min(1).max(256),
|
|
67
|
+
decision: z.enum(INVOKE_DECISIONS),
|
|
68
|
+
input: z.unknown().optional(),
|
|
69
|
+
secret: z.string().optional(),
|
|
70
|
+
page: pagePart.optional(),
|
|
71
|
+
conversation: z.string().min(1).optional(),
|
|
72
|
+
turnId: clientId.optional(),
|
|
73
|
+
replay: theoremReplay.optional(),
|
|
74
|
+
});
|
|
75
|
+
true;
|
|
76
|
+
/** An `/invoke` body as `createTheoremHandler` reads it. */
|
|
77
|
+
export const theoremInvokeRequestSchema = theoremInvokeRequest;
|
|
78
|
+
const theoremSteerRequest = z.object({
|
|
79
|
+
turnId: clientId,
|
|
80
|
+
id: clientId,
|
|
81
|
+
inject: z.array(turnHistoryMessageSchema).min(1),
|
|
82
|
+
});
|
|
83
|
+
true;
|
|
84
|
+
/** A `/steer` body as `createTheoremHandler` reads it. */
|
|
85
|
+
export const theoremSteerRequestSchema = theoremSteerRequest;
|
|
86
|
+
const conversationLine = z.object({
|
|
87
|
+
type: z.literal('conversation'),
|
|
88
|
+
ref: z.string().min(1),
|
|
89
|
+
posted: z.literal(true).optional(),
|
|
90
|
+
});
|
|
91
|
+
true;
|
|
92
|
+
/** The lines a chat's reply streams: turn events, and the conversation's ref. */
|
|
93
|
+
export const CHAT_LINES = {
|
|
94
|
+
...TURN_EVENT_SCHEMAS,
|
|
95
|
+
conversation: conversationLine,
|
|
96
|
+
};
|
|
97
|
+
const conversationView = z.object({
|
|
98
|
+
transcript: z.array(transcriptBlockSchema),
|
|
99
|
+
paused: z
|
|
100
|
+
.object({ events: z.array(turnEventSchema), blocks: z.array(transcriptBlockSchema) })
|
|
101
|
+
.optional(),
|
|
102
|
+
});
|
|
103
|
+
true;
|
|
104
|
+
const theoremConversationRequest = z.object({ conversation: z.string().min(1) });
|
|
105
|
+
true;
|
|
106
|
+
/** A `/conversation` body as `createTheoremHandler` reads it. */
|
|
107
|
+
export const theoremConversationRequestSchema = theoremConversationRequest;
|
|
108
|
+
const theoremRewindRequest = z.object({
|
|
109
|
+
conversation: z.string().min(1),
|
|
110
|
+
at: z.number().int().min(-1),
|
|
111
|
+
});
|
|
112
|
+
true;
|
|
113
|
+
/** A `/rewind` body as `createTheoremHandler` reads it. */
|
|
114
|
+
export const theoremRewindRequestSchema = theoremRewindRequest;
|
|
115
|
+
const theoremRewound = z.object({ conversation: z.string().min(1), view: conversationView });
|
|
116
|
+
true;
|
|
117
|
+
/**
|
|
118
|
+
* A failure the host reported: its kind, the host's wording when it sent one
|
|
119
|
+
* (the profile's labels, applied on the host), and raw detail when the host
|
|
120
|
+
* exposes it. `clientFailure` words it for the user.
|
|
121
|
+
*/
|
|
122
|
+
export class TheoremStreamError extends Error {
|
|
123
|
+
kind;
|
|
124
|
+
publicMessage;
|
|
125
|
+
internalMessage;
|
|
126
|
+
/** The labels key behind `publicMessage`, when the host gave one: what failed, more exactly than `kind`. */
|
|
127
|
+
copy;
|
|
128
|
+
constructor(kind, publicMessage, internalMessage, copy) {
|
|
129
|
+
super(internalMessage ?? publicMessage ?? kind);
|
|
130
|
+
this.name = 'TheoremStreamError';
|
|
131
|
+
this.kind = kind;
|
|
132
|
+
if (publicMessage)
|
|
133
|
+
this.publicMessage = publicMessage;
|
|
134
|
+
if (internalMessage)
|
|
135
|
+
this.internalMessage = internalMessage;
|
|
136
|
+
if (copy)
|
|
137
|
+
this.copy = copy;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
export function isTheoremStreamError(err) {
|
|
141
|
+
return err instanceof TheoremStreamError;
|
|
142
|
+
}
|
|
143
|
+
/** The trimmed string, or undefined when absent or blank. */
|
|
144
|
+
function textOf(value) {
|
|
145
|
+
return value?.trim() || undefined;
|
|
146
|
+
}
|
|
147
|
+
const hostErrorBody = z.object({
|
|
148
|
+
error: z.string().optional(),
|
|
149
|
+
errorKind: errorKindSchema.optional(),
|
|
150
|
+
errorCopy: errorCopiesSchema.optional(),
|
|
151
|
+
errorInternal: z.string().optional(),
|
|
152
|
+
});
|
|
153
|
+
true;
|
|
154
|
+
/** A host's error body, as the transport and the live client read it. */
|
|
155
|
+
export const hostErrorBodySchema = hostErrorBody;
|
|
156
|
+
/** A host's error body as a failure: its kind (else `fallbackKind`), wording, and detail. */
|
|
157
|
+
export function hostError(body, fallbackKind) {
|
|
158
|
+
const publicMessage = textOf(body.error);
|
|
159
|
+
const internal = textOf(body.errorInternal);
|
|
160
|
+
return new TheoremStreamError(body.errorKind ?? fallbackKind, publicMessage, internal && internal !== publicMessage ? internal : undefined, body.errorCopy);
|
|
161
|
+
}
|
|
162
|
+
/** The host could not open the message's conversation (`session.conversation_unknown`). */
|
|
163
|
+
export function isUnknownConversation(err) {
|
|
164
|
+
if (!isTheoremStreamError(err) || err.copy === undefined)
|
|
165
|
+
return false;
|
|
166
|
+
const copies = Array.isArray(err.copy) ? err.copy : [err.copy];
|
|
167
|
+
return copies.some((copy) => copy.key === 'session.conversation_unknown');
|
|
168
|
+
}
|
|
169
|
+
/** One NDJSON line checked against `lines`; an `error` line ends the stream as a {@link TheoremStreamError}. */
|
|
170
|
+
function parseStreamLine(lines, text) {
|
|
171
|
+
const line = readWireLine(lines, text);
|
|
172
|
+
// why: An `error` line passed the error event's schema, whose fields include the body's.
|
|
173
|
+
if (line.type === 'error')
|
|
174
|
+
throw hostError(hostErrorBody.parse(line), 'internal');
|
|
175
|
+
return line;
|
|
176
|
+
}
|
|
177
|
+
function flushNdjsonChunk(buffer, lines, onLine) {
|
|
178
|
+
const chunks = buffer.split('\n');
|
|
179
|
+
const rest = chunks.pop() ?? '';
|
|
180
|
+
for (const chunk of chunks) {
|
|
181
|
+
if (!chunk.trim())
|
|
182
|
+
continue;
|
|
183
|
+
onLine(parseStreamLine(lines, chunk));
|
|
184
|
+
}
|
|
185
|
+
return rest;
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* Read an NDJSON reply, checking each line against `lines`: a kind it doesn't
|
|
189
|
+
* list reaches `onLine` as `unsupported`, and a line that fails its check as
|
|
190
|
+
* `malformed`; the stream goes on. An `error` line ends it.
|
|
191
|
+
*/
|
|
192
|
+
export async function readNdjsonStream(response, lines, onLine, signal) {
|
|
193
|
+
if (!response.body)
|
|
194
|
+
throw new TheoremError('bad_response', 'stream reply has no body'); // labels-exempt: internal diagnostic
|
|
195
|
+
const reader = response.body.getReader();
|
|
196
|
+
const decoder = new TextDecoder();
|
|
197
|
+
let buffer = '';
|
|
198
|
+
const onAbort = () => {
|
|
199
|
+
void reader.cancel();
|
|
200
|
+
};
|
|
201
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
202
|
+
try {
|
|
203
|
+
for (;;) {
|
|
204
|
+
throwIfAborted(signal);
|
|
205
|
+
const { done, value } = await reader.read();
|
|
206
|
+
if (done)
|
|
207
|
+
break;
|
|
208
|
+
buffer = flushNdjsonChunk(buffer + decoder.decode(value, { stream: true }), lines, onLine);
|
|
209
|
+
}
|
|
210
|
+
const tail = buffer.trim();
|
|
211
|
+
if (tail)
|
|
212
|
+
onLine(parseStreamLine(lines, tail));
|
|
213
|
+
}
|
|
214
|
+
finally {
|
|
215
|
+
signal?.removeEventListener('abort', onAbort);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
async function resolveHeaders(options) {
|
|
219
|
+
const extra = typeof options.headers === 'function' ? await options.headers() : options.headers;
|
|
220
|
+
const headers = new Headers(extra);
|
|
221
|
+
headers.set('content-type', 'application/json');
|
|
222
|
+
return headers;
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* A non-OK reply as a failure: the host's kind and wording, else the status's
|
|
226
|
+
* kind. A body that is not JSON (a proxy's page) leaves the status to speak; a
|
|
227
|
+
* JSON body that fails the error body's schema is `bad_response`.
|
|
228
|
+
*/
|
|
229
|
+
async function failureFromResponse(response, failed) {
|
|
230
|
+
const text = await response.text();
|
|
231
|
+
let raw;
|
|
232
|
+
try {
|
|
233
|
+
raw = JSON.parse(text);
|
|
234
|
+
failed?.(raw);
|
|
235
|
+
}
|
|
236
|
+
catch {
|
|
237
|
+
return hostError({ errorInternal: `HTTP ${String(response.status)}` }, kindOfHttpStatus(response.status));
|
|
238
|
+
}
|
|
239
|
+
const body = hostErrorBody.safeParse(raw);
|
|
240
|
+
if (!body.success) {
|
|
241
|
+
// labels-exempt: internal diagnostic; the user reads error.bad_response
|
|
242
|
+
return new TheoremError('bad_response', `HTTP ${String(response.status)} error body failed its wire check`);
|
|
243
|
+
}
|
|
244
|
+
return hostError({ ...body.data, errorInternal: body.data.errorInternal ?? `HTTP ${String(response.status)}` }, kindOfHttpStatus(response.status));
|
|
245
|
+
}
|
|
246
|
+
async function request(url, init, options) {
|
|
247
|
+
const doFetch = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
248
|
+
try {
|
|
249
|
+
return await doFetch(url, {
|
|
250
|
+
...init,
|
|
251
|
+
headers: await resolveHeaders(options),
|
|
252
|
+
credentials: options.credentials ?? 'same-origin',
|
|
253
|
+
});
|
|
254
|
+
}
|
|
255
|
+
catch (err) {
|
|
256
|
+
if (isAbortError(err))
|
|
257
|
+
throw err;
|
|
258
|
+
throw new TheoremError('network', describeError(err), { cause: err });
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* POST JSON and stream NDJSON lines back, each checked against `lines`: turn
|
|
263
|
+
* events ({@link TURN_EVENT_SCHEMAS}), or a host's own schema beside them.
|
|
264
|
+
*/
|
|
265
|
+
export async function postNdjson(url, body, lines, onLine, options = {}) {
|
|
266
|
+
const response = await jsonPostResponse(url, body, options);
|
|
267
|
+
await readNdjsonStream(response, lines, onLine, options.signal);
|
|
268
|
+
}
|
|
269
|
+
async function jsonPostResponse(url, body, options) {
|
|
270
|
+
const response = await request(url, { method: 'POST', body: JSON.stringify(body), signal: options.signal }, options);
|
|
271
|
+
if (!response.ok)
|
|
272
|
+
throw await failureFromResponse(response);
|
|
273
|
+
return response;
|
|
274
|
+
}
|
|
275
|
+
/** POST JSON; a non-OK reply throws its failure. The OK reply's body is not read. */
|
|
276
|
+
export async function postJson(url, body, options = {}) {
|
|
277
|
+
await jsonPostResponse(url, body, options);
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* GET, or POST `body` as JSON, and read the JSON reply; a non-OK reply throws its failure, after
|
|
281
|
+
* `failed` has read whatever else its JSON body carries.
|
|
282
|
+
*/
|
|
283
|
+
export async function fetchJson(url, init, options = {}) {
|
|
284
|
+
const method = init.body === undefined
|
|
285
|
+
? { method: 'GET' }
|
|
286
|
+
: { method: 'POST', body: JSON.stringify(init.body) };
|
|
287
|
+
const response = await request(url, { ...method, signal: init.signal }, options);
|
|
288
|
+
if (!response.ok)
|
|
289
|
+
throw await failureFromResponse(response, init.failed);
|
|
290
|
+
return parseWireJson(await response.text());
|
|
291
|
+
}
|
|
292
|
+
/** POST a conversation's read to `url`, and check the view the host answers. */
|
|
293
|
+
export async function fetchConversation(url, body, options = {}) {
|
|
294
|
+
const { signal, ...http } = options;
|
|
295
|
+
// labels-exempt: internal diagnostic; the user reads error.bad_response
|
|
296
|
+
return checkWire(conversationView, await fetchJson(url, { body, signal }, http), 'the conversation');
|
|
297
|
+
}
|
|
298
|
+
/** POST a rewind to `url`, and check the rewound conversation the host answers. */
|
|
299
|
+
export async function fetchRewound(url, body, options = {}) {
|
|
300
|
+
const { signal, ...http } = options;
|
|
301
|
+
return checkWire(theoremRewound, await fetchJson(url, { body, signal }, http), 'the rewound conversation');
|
|
302
|
+
}
|
|
303
|
+
/** Drops trailing '/'s by scanning back, not with a regex (a `/\/+$/` scan is quadratic on long runs of '/'). */
|
|
304
|
+
function withoutTrailingSlashes(url) {
|
|
305
|
+
let end = url.length;
|
|
306
|
+
while (end > 0 && url[end - 1] === '/')
|
|
307
|
+
end -= 1;
|
|
308
|
+
return url.slice(0, end);
|
|
309
|
+
}
|
|
310
|
+
/** The host's `describe` reply. */
|
|
311
|
+
const describedSchema = z.object({ interface: profileInterfaceSchema });
|
|
312
|
+
/** Transport for a host mounted with `createTheoremHandler`. */
|
|
313
|
+
export function createHttpTransport(options = {}) {
|
|
314
|
+
const base = withoutTrailingSlashes(options.endpoint ?? '/api/theorem');
|
|
315
|
+
return {
|
|
316
|
+
async describe(signal) {
|
|
317
|
+
const response = await request(base, { method: 'GET', signal }, options);
|
|
318
|
+
if (!response.ok)
|
|
319
|
+
throw await failureFromResponse(response);
|
|
320
|
+
// labels-exempt: internal diagnostic; the user reads error.bad_response
|
|
321
|
+
return checkWire(describedSchema, parseWireJson(await response.text()), 'the profile description').interface;
|
|
322
|
+
},
|
|
323
|
+
turn: ({ replay: _replay, ...body }, onEvent, signal) => postNdjson(`${base}/turn`, body, CHAT_LINES, onEvent, { ...options, signal }),
|
|
324
|
+
invoke: ({ replay: _replay, ...body }, onEvent, signal) => postNdjson(`${base}/invoke`, body, CHAT_LINES, onEvent, { ...options, signal }),
|
|
325
|
+
conversation: (body, signal) => fetchConversation(`${base}/conversation`, body, { ...options, signal }),
|
|
326
|
+
rewind: (body, signal) => fetchRewound(`${base}/rewind`, body, { ...options, signal }),
|
|
327
|
+
pageResult: (body, signal) => postJson(`${base}/page-result`, body, { ...options, signal }),
|
|
328
|
+
steer: (body) => postJson(`${base}/steer`, body, options),
|
|
329
|
+
};
|
|
330
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { type TurnEvent } from '@theoremjs/agents';
|
|
2
|
+
import { type AttachmentValidationIssue, type ComposerProfileInterface, type GatedToolContext, type InterfaceTurnSession, type TranscriptBlock, type UserTurnDraft } from '@theoremjs/agents/interface';
|
|
3
|
+
import type { PagePart } from './tool-resume.ts';
|
|
4
|
+
import type { TheoremInvokeRequest, TheoremReplay, TheoremTurnInput, TheoremTurnRequest } from './transport.ts';
|
|
5
|
+
export declare function issuedOperationId(call: {
|
|
6
|
+
operationId?: string;
|
|
7
|
+
}): string;
|
|
8
|
+
/** A gated call as the client holds it, for a host without a session (the studio). */
|
|
9
|
+
export type HeldCall = {
|
|
10
|
+
name: string;
|
|
11
|
+
/** The model's input to the call. */
|
|
12
|
+
input: unknown;
|
|
13
|
+
gateKind?: TheoremReplay['gateKind'];
|
|
14
|
+
sessionPermissions?: string[];
|
|
15
|
+
};
|
|
16
|
+
/** The calls a paused reply waits on that a message walks away from. */
|
|
17
|
+
export type WalkAway = {
|
|
18
|
+
calls: readonly GatedToolContext[];
|
|
19
|
+
};
|
|
20
|
+
/** Where a request goes on from: the ref of the conversation the host keeps, and the run's id for steers. */
|
|
21
|
+
export type RunScope = {
|
|
22
|
+
conversation?: string;
|
|
23
|
+
turnId?: string;
|
|
24
|
+
};
|
|
25
|
+
export declare function buildTurnRequest(iface: ComposerProfileInterface, session: InterfaceTurnSession, input: TheoremTurnInput, options?: RunScope & {
|
|
26
|
+
walkAway?: WalkAway;
|
|
27
|
+
}): TheoremTurnRequest;
|
|
28
|
+
export declare function buildInvokeRequest(iface: ComposerProfileInterface, session: InterfaceTurnSession, args: HeldCall & {
|
|
29
|
+
gateId: string;
|
|
30
|
+
operationId: string;
|
|
31
|
+
decision: TheoremInvokeRequest['decision'];
|
|
32
|
+
secret?: string;
|
|
33
|
+
page?: PagePart;
|
|
34
|
+
}, scope?: RunScope): TheoremInvokeRequest;
|
|
35
|
+
export declare function projectUserTurn(iface: ComposerProfileInterface, draft: UserTurnDraft): {
|
|
36
|
+
ok: true;
|
|
37
|
+
blocks: TranscriptBlock[];
|
|
38
|
+
draft: UserTurnDraft;
|
|
39
|
+
} | {
|
|
40
|
+
ok: false;
|
|
41
|
+
issues: AttachmentValidationIssue[];
|
|
42
|
+
};
|
|
43
|
+
export declare function prepareComposerTurn(iface: ComposerProfileInterface, text: string, pendingFiles: readonly File[], pendingVoice?: readonly File[]): ReturnType<typeof projectUserTurn>;
|
|
44
|
+
export declare function foldAssistantTurn(iface: ComposerProfileInterface, events: readonly TurnEvent[]): TranscriptBlock[];
|