@theoremjs/web 0.3.4 → 0.3.5-next.1001.g68d8dcf

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.md +330 -13
  2. package/client/chat.d.ts +14 -2
  3. package/client/chat.js +302 -34
  4. package/client/composer-hints.d.ts +18 -10
  5. package/client/composer-hints.js +23 -6
  6. package/client/host-transport.d.ts +7 -2
  7. package/client/host-transport.js +9 -3
  8. package/client/index.d.ts +4 -4
  9. package/client/index.js +3 -3
  10. package/client/page-dispatch.js +5 -0
  11. package/client/run-session.d.ts +27 -2
  12. package/client/run-session.js +34 -4
  13. package/client/schema-fields.d.ts +28 -1
  14. package/client/schema-fields.js +172 -13
  15. package/client/tool-result.d.ts +9 -5
  16. package/client/tool-result.js +23 -42
  17. package/client/transcript-schema.d.ts +4 -0
  18. package/client/transcript-schema.js +25 -6
  19. package/client/transport.d.ts +90 -9
  20. package/client/transport.js +56 -11
  21. package/client/turn-client.d.ts +8 -2
  22. package/client/turn-client.js +9 -0
  23. package/package.json +2 -2
  24. package/server/conversation-core.d.ts +273 -0
  25. package/server/conversation-core.js +797 -0
  26. package/server/conversation-inbox.d.ts +45 -0
  27. package/server/conversation-inbox.js +240 -0
  28. package/server/conversation-store.d.ts +43 -2
  29. package/server/conversation-store.js +15 -2
  30. package/server/conversation.d.ts +82 -2
  31. package/server/conversation.js +357 -60
  32. package/server/create-conversation-core.d.ts +28 -0
  33. package/server/create-conversation-core.js +46 -0
  34. package/server/embedding-handler.js +2 -0
  35. package/server/handler.d.ts +84 -20
  36. package/server/handler.js +279 -659
  37. package/server/mcp-handler.js +25 -11
  38. package/server/mod.d.ts +11 -4
  39. package/server/mod.js +6 -2
  40. package/server/notifier.d.ts +3 -2
  41. package/server/notifier.js +3 -2
  42. package/server/session-authority.d.ts +3 -1
  43. package/server/session-authority.js +26 -1
  44. package/server/session-boundary.d.ts +5 -3
  45. package/server/session-boundary.js +2 -2
  46. package/server/session-calls.d.ts +122 -0
  47. package/server/session-calls.js +512 -0
  48. package/server/session-store.d.ts +33 -0
  49. package/server/session-store.js +37 -2
  50. package/server/steer-inbox.d.ts +3 -4
  51. package/server/steer-inbox.js +6 -5
  52. package/server/tell-every-result.d.ts +11 -0
  53. package/server/tell-every-result.js +17 -0
  54. package/server/tool-operations.d.ts +8 -0
  55. package/server/tool-operations.js +71 -0
  56. package/server/turn-input.d.ts +4 -2
  57. package/server/turn-input.js +5 -2
  58. package/server/turn-wiring.d.ts +31 -6
  59. package/server/turn-wiring.js +59 -5
@@ -13,7 +13,7 @@
13
13
  * @module
14
14
  */
15
15
  import { invokeTool, labelText, registerProfile, } from '@theoremjs/agents';
16
- import { caughtStatus, clientError } from '@theoremjs/agents/host';
16
+ import { caughtStatus, clientError, inputSchemaForModel, markedFieldsIn, } from '@theoremjs/agents/host';
17
17
  import { hostInterface } from "../client/host-transport.js";
18
18
  import { defineHostProfile, hostTool } from "./handler.js";
19
19
  import { boundedRequestJson, requestByteLimit } from "./request-body.js";
@@ -144,7 +144,8 @@ function callResult(events, labels) {
144
144
  return {
145
145
  content: [
146
146
  { type: 'text', text: tool.readBack ?? '' },
147
- ...(tool.parts ?? []).map(partContent),
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 ('uri' in part)
172
- return { type: 'resource_link', uri: part.uri, name: part.uri, mimeType: part.mimeType };
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
- type: 'resource',
177
- resource: { uri: `part:${index}`, mimeType: part.mimeType, blob: part.data },
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) {
@@ -202,7 +209,7 @@ export function createTheoremMcpHandler(options) {
202
209
  const listed = () => hostInterface(host, hostTool).tools.map((tool) => ({
203
210
  name: tool.name,
204
211
  description: tool.description,
205
- inputSchema: tool.inputSchema,
212
+ inputSchema: inputSchemaForModel(tool.inputSchema),
206
213
  annotations: {
207
214
  readOnlyHint: tool.access === 'read-only',
208
215
  ...(tool.access === 'destructive' ? { destructiveHint: true } : {}),
@@ -213,6 +220,13 @@ export function createTheoremMcpHandler(options) {
213
220
  if (typeof name !== 'string' || !listed().some((tool) => tool.name === name))
214
221
  // labels-exempt: protocol diagnostic for the MCP client, not end-user copy
215
222
  throw new RpcError(200, INVALID_PARAMS, `Unknown tool: ${String(name)}`);
223
+ const inputSchema = hostTool(name)?.inputSchema;
224
+ const hostFields = inputSchema ? markedFieldsIn(inputSchema, params.arguments) : [];
225
+ if (hostFields.length > 0) {
226
+ const fields = hostFields.join(', ');
227
+ const message = labelText('tool.input_host_fields', { tool: name, fields }, host.labels);
228
+ throw new RpcError(200, INVALID_PARAMS, message);
229
+ }
216
230
  const events = [];
217
231
  for await (const event of invokeTool({
218
232
  profile: host.id,
package/server/mod.d.ts CHANGED
@@ -7,21 +7,28 @@
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';
12
- export { type ConversationSnapshot, type ConversationWriteResult, createMemoryConversationStore, createSealedConversationStore, emptyConversation, type PausedReply, type SealedConversationStoreOptions, type StoredConversation, storedConversationSchema, type TheoremConversationStore, unknownConversation, } from './conversation-store.ts';
10
+ export { transcriptBlockSchema } from '../client/transcript-schema.ts';
11
+ export { type StatedTurn, theoremConversationRequestSchema, theoremInvokeRequestSchema, theoremNotifyRequestSchema, theoremReplaySchema, theoremRewindRequestSchema, theoremStartRequestSchema, theoremSteerRequestSchema, theoremStopRequestSchema, theoremTurnRequestSchema, theoremWakeRequestSchema, } from '../client/transport.ts';
12
+ export { answerReply, type ConversationHost, type ConversationUse, conversationView, type IssuedWalkAway, messageReply, type OpenedConversation, openConversation, type PostedMessage, postedMessage, type ReplyLine, type ReplyRunner, type ReplySaving, type ReplyToSave, type ReplyTurn, readerConversationHost, rewindConversation, type ShapedReply, startConversation, statelessRefusal, type WalkedAwayCall, waitingCalls, wakeReply, } from './conversation.ts';
13
+ export type { AppInbox, ContinueChoice, ConversationCore, FollowUpArgs, Generation, HoldStop, MessageArgs, Reply, ReplyPrepare, ReplyWiring, RunEnd, SaveHooks, WakeArgs, } from './conversation-core.ts';
14
+ export { followedUp } from './conversation-core.ts';
15
+ export { type ConversationSnapshot, type ConversationWriteResult, createMemoryConversationStore, createSealedConversationStore, emptyConversation, type PausedReply, type ReplyEnd, type SealedConversationStoreOptions, type StoredConversation, storedConversationSchema, type TheoremConversationStore, type UncompactedBase, unknownConversation, type WriteContext, } from './conversation-store.ts';
16
+ export { createTheoremConversationCore, type TheoremConversationCoreOptions, } from './create-conversation-core.ts';
13
17
  export { createMemoryCredentialStore, type TheoremCredentialStore, type TheoremCredentials, } from './credential-store.ts';
14
18
  export { createTheoremDecisionHandler, type DecisionQuestionsBuilder, isQuestionsBuilder, type TheoremDecisionHandlerOptions, } from './decision-handler.ts';
15
19
  export { createTheoremEmbeddingHandler, embedBodySchema, embedRequest, type TheoremEmbeddingHandlerOptions, } from './embedding-handler.ts';
16
- export { createTheoremHandler, createTheoremHostHandler, readBody, type TheoremHandlerOptions, type TheoremHostHandlerOptions, type TheoremRequestContext, theoremSession, theoremSessionId, } from './handler.ts';
20
+ export { createTheoremHandler, createTheoremHostHandler, type MessageIntake, readBody, type TheoremHandlerOptions, type TheoremHostHandlerOptions, type TheoremRequestContext, theoremSession, theoremSessionId, } from './handler.ts';
17
21
  export { createTheoremMcpHandler, type TheoremMcpHandlerOptions } from './mcp-handler.ts';
18
22
  export { createMemoryNotifier, type TheoremNotifier } from './notifier.ts';
19
23
  export { createMemoryPageToolBroker, type PageToolBroker, type PageToolResult, pageToolResultSchema, sessionPageDispatch, } from './page-dispatch.ts';
20
24
  export { checkRequest, parseLiveClientMessage, parseLiveOpenMessage } from './request-check.ts';
21
25
  export { sessionStateStore } from './session-authority.ts';
22
26
  export { createTheoremSessionBoundary, type PreparedLiveOpen, type SessionBoundaryOptions, type TheoremSessionBoundary, } from './session-boundary.ts';
27
+ export type { CoreContext } from './session-calls.ts';
23
28
  export type { TheoremSessionCapacity } from './session-limits.ts';
24
29
  export { createMemorySessionStore, DEFAULT_OPERATION_RETENTION_MS, type MemorySessionStoreOptions, type PendingToolGate, type SessionSnapshot, type SessionToolOperation, type SessionWriteResult, type TheoremSessionState, type TheoremSessionStore, theoremSessionStateSchema, } from './session-store.ts';
25
30
  export { createMemorySteerInbox, type SteerInbox, type SteerUnit, steerStage, steerUnitOf, stopOnRequest, } from './steer-inbox.ts';
31
+ export { tellEveryResult } from './tell-every-result.ts';
26
32
  export { sessionToolCoordinator } from './tool-operations.ts';
27
33
  export { kernelTurnInput, liveSessionOpen } from './turn-input.ts';
34
+ export type { ReplyRefusal } from './turn-wiring.ts';
package/server/mod.js CHANGED
@@ -6,9 +6,12 @@
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 { transcriptBlockSchema } from "../client/transcript-schema.js";
10
+ export { theoremConversationRequestSchema, theoremInvokeRequestSchema, theoremNotifyRequestSchema, theoremReplaySchema, theoremRewindRequestSchema, theoremStartRequestSchema, theoremSteerRequestSchema, theoremStopRequestSchema, theoremTurnRequestSchema, theoremWakeRequestSchema, } from "../client/transport.js";
11
+ export { answerReply, conversationView, messageReply, openConversation, postedMessage, readerConversationHost, rewindConversation, startConversation, statelessRefusal, waitingCalls, wakeReply, } from "./conversation.js";
12
+ export { followedUp } from "./conversation-core.js";
11
13
  export { createMemoryConversationStore, createSealedConversationStore, emptyConversation, storedConversationSchema, unknownConversation, } from "./conversation-store.js";
14
+ export { createTheoremConversationCore, } from "./create-conversation-core.js";
12
15
  export { createMemoryCredentialStore, } from "./credential-store.js";
13
16
  export { createTheoremDecisionHandler, isQuestionsBuilder, } from "./decision-handler.js";
14
17
  export { createTheoremEmbeddingHandler, embedBodySchema, embedRequest, } from "./embedding-handler.js";
@@ -21,5 +24,6 @@ export { sessionStateStore } from "./session-authority.js";
21
24
  export { createTheoremSessionBoundary, } from "./session-boundary.js";
22
25
  export { createMemorySessionStore, DEFAULT_OPERATION_RETENTION_MS, theoremSessionStateSchema, } from "./session-store.js";
23
26
  export { createMemorySteerInbox, steerStage, steerUnitOf, stopOnRequest, } from "./steer-inbox.js";
27
+ export { tellEveryResult } from "./tell-every-result.js";
24
28
  export { sessionToolCoordinator } from "./tool-operations.js";
25
29
  export { kernelTurnInput, liveSessionOpen } from "./turn-input.js";
@@ -1,6 +1,7 @@
1
1
  /**
2
- * Where a session's open pages hear that a background call ended. The line carries no content: a
3
- * page that hears it reads the conversation, so one read decides what a reader sees.
2
+ * Where a session's open pages hear that a background call ended or the app saved a reply. The line
3
+ * carries no content: a page that hears it reads the conversation, so one read decides what a
4
+ * reader sees.
4
5
  *
5
6
  * @module
6
7
  */
@@ -1,6 +1,7 @@
1
1
  /**
2
- * Where a session's open pages hear that a background call ended. The line carries no content: a
3
- * page that hears it reads the conversation, so one read decides what a reader sees.
2
+ * Where a session's open pages hear that a background call ended or the app saved a reply. The line
3
+ * carries no content: a page that hears it reads the conversation, so one read decides what a
4
+ * reader sees.
4
5
  *
5
6
  * @module
6
7
  */
@@ -1,5 +1,5 @@
1
1
  import { type TheoremSessionCapacity } from './session-limits.ts';
2
- import { type TheoremSessionState, type TheoremSessionStore } from './session-store.ts';
2
+ import { type PerSessionStore, type TheoremSessionState, type TheoremSessionStore } from './session-store.ts';
3
3
  export type MutableStore<T> = {
4
4
  read(sessionId: string): Promise<T>;
5
5
  mutate<R>(sessionId: string, change: (value: T) => R | Promise<R>): Promise<R>;
@@ -10,3 +10,5 @@ export type SessionStateStore = MutableStore<TheoremSessionState> & {
10
10
  };
11
11
  /** Session state, with expired gates dropped as it loads so they can't be answered. */
12
12
  export declare function sessionStateStore(store: TheoremSessionStore, gateTtlMs: number | undefined, operationRetentionMs: number): SessionStateStore;
13
+ /** A store read and changed one session at a time: each change waits for the one before it. */
14
+ export declare function lockedStore<T>(store: PerSessionStore<T>, loaded: (value: T | undefined) => T): MutableStore<T>;
@@ -1,6 +1,6 @@
1
1
  import { labelText, TheoremError, z } from '@theoremjs/agents';
2
2
  import { checkedCapacity, fitSession } from "./session-limits.js";
3
- import { emptySessionState, pruneGates, theoremSessionStateSchema, } from "./session-store.js";
3
+ import { emptySessionState, pruneGates, pruneInbox, theoremSessionStateSchema, } from "./session-store.js";
4
4
  /** Session state, with expired gates dropped as it loads so they can't be answered. */
5
5
  export function sessionStateStore(store, gateTtlMs, operationRetentionMs) {
6
6
  if (typeof store.compareAndSwap !== 'function') {
@@ -33,6 +33,7 @@ export function sessionStateStore(store, gateTtlMs, operationRetentionMs) {
33
33
  }
34
34
  state.operations = Object.fromEntries(Object.entries(state.operations).filter(([, operation]) => operation.status !== 'settled' ||
35
35
  now < (operation.retainUntil ?? operation.settledAt + operationRetentionMs)));
36
+ pruneInbox(state, now);
36
37
  return { revision: snapshot?.revision ?? null, state };
37
38
  };
38
39
  return {
@@ -54,6 +55,7 @@ export function sessionStateStore(store, gateTtlMs, operationRetentionMs) {
54
55
  }
55
56
  if (capacity)
56
57
  fitSession(state, capacity);
58
+ pruneInbox(state, now);
57
59
  const next = theoremSessionStateSchema.safeParse(state);
58
60
  if (!next.success) {
59
61
  throw new TheoremError('config', labelText('error.config'), {
@@ -80,3 +82,26 @@ export function sessionStateStore(store, gateTtlMs, operationRetentionMs) {
80
82
  },
81
83
  };
82
84
  }
85
+ /** A store read and changed one session at a time: each change waits for the one before it. */
86
+ export function lockedStore(store, loaded) {
87
+ const locks = new Map();
88
+ const read = async (sessionId) => loaded(await store.load(sessionId));
89
+ return {
90
+ read,
91
+ mutate(sessionId, change) {
92
+ const next = (locks.get(sessionId) ?? Promise.resolve()).then(async () => {
93
+ const value = await read(sessionId);
94
+ const result = change(value);
95
+ await store.save(sessionId, value);
96
+ return result;
97
+ });
98
+ const settled = next.catch(() => { });
99
+ locks.set(sessionId, settled);
100
+ void settled.then(() => {
101
+ if (locks.get(sessionId) === settled)
102
+ locks.delete(sessionId);
103
+ });
104
+ return next;
105
+ },
106
+ };
107
+ }
@@ -1,7 +1,8 @@
1
- import { type PageToolExecution, type ProviderCheckpoint, type SessionRequest, type ToolExecutionCoordinator, type TurnHistoryMessage } from '@theoremjs/agents';
1
+ import { type PageToolExecution, type ProviderCheckpoint, type ToolExecutionCoordinator, type TurnHistoryMessage } from '@theoremjs/agents';
2
2
  import { type LiveOpenMessage } from '../client/live-messages.ts';
3
3
  import { type PageToolBroker, type PageToolResult } from './page-dispatch.ts';
4
4
  import { type TheoremSessionStore } from './session-store.ts';
5
+ import { liveSessionOpen } from './turn-input.ts';
5
6
  export interface SessionBoundaryOptions {
6
7
  request: Request;
7
8
  session?: (request: Request) => string | undefined | Promise<string | undefined>;
@@ -14,11 +15,12 @@ export interface SessionBoundaryOptions {
14
15
  /** How long the page has to answer a tool call it runs, in milliseconds. Unset, it waits. */
15
16
  pageToolTimeoutMs?: number;
16
17
  }
17
- export type PreparedLiveOpen = Pick<SessionRequest, 'history' | 'inputOptions' | 'context' | 'providerState' | 'awayMs' | 'path' | 'options'>;
18
+ export type PreparedLiveOpen = ReturnType<typeof liveSessionOpen>;
18
19
  export interface TheoremSessionBoundary {
19
20
  sessionId: string;
20
21
  setCookie?: string;
21
- prepareLiveOpen(open: LiveOpenMessage, serverContext?: unknown): Promise<PreparedLiveOpen>;
22
+ /** Checks the page's open message against the profile the call opens on. */
23
+ prepareLiveOpen(open: LiveOpenMessage, profile: Parameters<typeof liveSessionOpen>[1], serverContext?: unknown): Promise<PreparedLiveOpen>;
22
24
  prepareProviderState(checkpoint: ProviderCheckpoint | undefined, history?: readonly TurnHistoryMessage[]): Promise<ProviderCheckpoint | undefined>;
23
25
  recordCheckpoint(checkpoint: ProviderCheckpoint): Promise<void>;
24
26
  toolExecution: ToolExecutionCoordinator;
@@ -29,12 +29,12 @@ export async function createTheoremSessionBoundary(options) {
29
29
  sessionId: id,
30
30
  ...(cookie?.setCookie ? { setCookie: cookie.setCookie } : {}),
31
31
  toolExecution: sessionToolCoordinator(store, id),
32
- async prepareLiveOpen(raw, server) {
32
+ async prepareLiveOpen(raw, profile, server) {
33
33
  const open = checkRequest(liveOpenMessageSchema, raw, 'live open');
34
34
  if (open.stated && !options.pageStatesTurn) {
35
35
  throw new TheoremError('request', labelText('error.request'));
36
36
  }
37
- const prepared = liveSessionOpen(open, server);
37
+ const prepared = liveSessionOpen(open, profile, server);
38
38
  const state = await store.read(id);
39
39
  const providerState = await requireOwnedCheckpoint(state.providerCheckpoints, prepared.providerState, state.operations);
40
40
  if (providerState &&
@@ -0,0 +1,122 @@
1
+ /**
2
+ * A session's tool calls, with no `Request`: each call recorded in the session, its gates saved
3
+ * as they pause, an answered call run on, and a background call announced as it ends. The HTTP
4
+ * handlers and the conversation core both run their calls through here.
5
+ *
6
+ * @module
7
+ */
8
+ import { type GateReference, type Profile, type StageHandler, type ToolGate, type TurnEvent, type TurnInput, type TurnWiring } from '@theoremjs/agents';
9
+ import { type ToolBackgroundService, type ToolCredentialSource } from '@theoremjs/agents/kernel';
10
+ import type { TheoremHostCallRequest } from '../client/host-transport.ts';
11
+ import type { TheoremInvokeRequest } from '../client/transport.ts';
12
+ import { type IssuedWalkAway } from './conversation.ts';
13
+ import { type SettledOperation } from './conversation-inbox.ts';
14
+ import type { StoredConversation } from './conversation-store.ts';
15
+ import { type TheoremCredentialStore, type TheoremCredentials } from './credential-store.ts';
16
+ import type { TheoremNotifier } from './notifier.ts';
17
+ import { type PageToolBroker } from './page-dispatch.ts';
18
+ import { type MutableStore, type SessionStateStore } from './session-authority.ts';
19
+ import { type SessionToolOperation, type TheoremSessionState, type TheoremSessionStore } from './session-store.ts';
20
+ import { type AppPrepare } from './turn-wiring.ts';
21
+ /** What a run reads in place of the request that started it. */
22
+ export type CoreContext = {
23
+ sessionId: string;
24
+ /**
25
+ * The app's context for tool handlers (`ctx.host`). A promise is awaited where a run reads it.
26
+ */
27
+ host?: unknown;
28
+ /** Aborts the run. */
29
+ signal: AbortSignal;
30
+ };
31
+ /** What a session's tool calls read from whoever serves them. */
32
+ export type CallsContext = {
33
+ profile: Profile;
34
+ sessions: SessionStateStore;
35
+ credentials: MutableStore<TheoremCredentials>;
36
+ pageToolBroker: PageToolBroker;
37
+ options: {
38
+ prepare?: AppPrepare;
39
+ onStage?: StageHandler;
40
+ pageToolTimeoutMs?: number;
41
+ notifier?: TheoremNotifier;
42
+ lateResultsDecider?: TurnWiring['lateResultsDecider'];
43
+ /** The decider's wake, with no page: a reply to no message on a run of its own. */
44
+ wake: (at: CoreContext, ref: string) => Promise<void>;
45
+ } & CallHooks;
46
+ };
47
+ /** The app's own steps that a session's tool calls run, each for the session of `at`. */
48
+ export type CallHooks = {
49
+ /** The service for tools with a `background` setting, for the session of `at`. */
50
+ background?: (at: CoreContext) => ToolBackgroundService;
51
+ /** Check current resource access before disclosing a saved tool result. Read-only. */
52
+ authorizeToolReplay?: (at: CoreContext, operation: SettledOperation) => boolean | Promise<boolean>;
53
+ /** The sign-in URL for an OAuth gate. */
54
+ authorizationUrl?: (challenge: Extract<ToolGate, {
55
+ kind: 'auth';
56
+ }>['authChallenge'], at: CoreContext) => string | Promise<string>;
57
+ /** Called with any error a run reports and does not throw. */
58
+ onError?: (err: unknown, at: CoreContext) => void;
59
+ };
60
+ /** The stores and limits a session's calls run on; each is the handler option of the same name. */
61
+ export type SessionOptions = {
62
+ sessionStore?: TheoremSessionStore;
63
+ credentialStore?: TheoremCredentialStore;
64
+ gateTtlMs?: number;
65
+ operationRetentionMs?: number;
66
+ pageToolBroker?: PageToolBroker;
67
+ pageToolTimeoutMs?: number;
68
+ notifyRetryMs?: number;
69
+ };
70
+ /**
71
+ * The profile, registered, and the session's stores as its calls read them. `name` is the
72
+ * function the app called, for the error a wrong option throws.
73
+ */
74
+ export declare function sessionParts(name: string, profile: Profile, options: SessionOptions): Pick<CallsContext, 'profile' | 'sessions' | 'credentials' | 'pageToolBroker'>;
75
+ /** What a turn's saved outcome records beside its events. */
76
+ export type OutcomeContext = {
77
+ profileId: string;
78
+ turnInput: TurnInput;
79
+ model?: string;
80
+ promoted?: string[];
81
+ };
82
+ export declare function recorded(sessions: MutableStore<TheoremSessionState>, sessionId: string, events: AsyncIterable<TurnEvent>, context: OutcomeContext, seed?: TurnEvent[]): AsyncGenerator<TurnEvent>;
83
+ /**
84
+ * The session's credentials as a call reads them: one slot when a tool needs it,
85
+ * saved the moment the kernel sets one, so a rotated refresh token is never lost
86
+ * to a closed stream.
87
+ */
88
+ export declare function sessionCredentials(ctx: CallsContext, sessionId: string): ToolCredentialSource;
89
+ /** Every OAuth gate in the stream, given the host's sign-in URL. */
90
+ export declare function withAuthorizationUrls(ctx: CallsContext, at: CoreContext, events: AsyncIterable<TurnEvent>): AsyncGenerator<TurnEvent>;
91
+ /** {@link stillWaits} for `conversation`'s paused reply, read from the session. Writes nothing. */
92
+ export declare function pausedWaits(ctx: CallsContext, at: CoreContext, conversation: StoredConversation): Promise<{
93
+ until?: number;
94
+ } | undefined>;
95
+ /**
96
+ * Take the calls of a paused reply whose gates have all lapsed out of the session, each settled
97
+ * as `expired`. Undefined, with nothing taken, while one still waits ({@link stillWaits}).
98
+ */
99
+ export declare function takeLapsed(ctx: CallsContext, at: CoreContext, conversation: StoredConversation): Promise<IssuedWalkAway[] | undefined>;
100
+ /**
101
+ * Take the calls a message or a rewind walks away from out of the session,
102
+ * answered `abandon`: every one of them, or none when one is neither waiting
103
+ * nor settled. Each comes back with the run that settles it.
104
+ */
105
+ export declare function takeWalkedAway(ctx: CallsContext, at: CoreContext, abandon: readonly GateReference[], conversation: StoredConversation): Promise<IssuedWalkAway[]>;
106
+ /** The host's service for a call in this session, for a request that runs a tool. */
107
+ export declare function backgroundWiring(ctx: CallsContext, at: CoreContext): {
108
+ background?: ToolBackgroundService;
109
+ };
110
+ /**
111
+ * `service`, telling the session's open pages when each of its calls ends, and the decider's
112
+ * `ended`, with the wake and the notify it may use.
113
+ */
114
+ export declare function announced(ctx: CallsContext, at: CoreContext, service: ToolBackgroundService): ToolBackgroundService;
115
+ /** Whether this request may read a settled call's result: the host's `authorizeToolReplay`. */
116
+ export declare function replayAllowed(ctx: CallsContext, at: CoreContext, operation: Extract<SessionToolOperation, {
117
+ status: 'settled';
118
+ }>): Promise<boolean>;
119
+ /** One call of one of a host's tools, run as the page asked it; a gate it pauses on waits in the session. */
120
+ export declare function callEvents(ctx: CallsContext, at: CoreContext, body: TheoremHostCallRequest): AsyncGenerator<TurnEvent>;
121
+ /** The answered call's events: its saved outcome again, or the call run as answered. */
122
+ export declare function settlingOf(ctx: CallsContext, at: CoreContext, body: TheoremInvokeRequest): Promise<() => AsyncIterable<TurnEvent>>;