@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
@@ -6,18 +6,19 @@
6
6
  * @module
7
7
  */
8
8
  import { TheoremError } from '@theoremjs/agents';
9
+ import { appendUserDraftToHistory } from '@theoremjs/agents/interface';
9
10
  /** The stages a steer can land at. */
10
11
  const STEER_STAGES = new Set(['pre_turn', 'post_tool', 'before_end']);
11
12
  /**
12
- * A steer as a client posts it (a checked `TheoremSteerRequest`): its user
13
- * messages. Other roles are dropped — a client never injects system,
14
- * assistant or tool turns — and a steer with no user message is refused.
13
+ * A steer as a client posts it (a checked `TheoremSteerRequest`): its message as the one user
14
+ * message the model reads. A steer with no text and no file is refused.
15
15
  */
16
16
  export function steerUnitOf(steer) {
17
- const messages = steer.inject.filter((message) => message.role === 'user');
17
+ const { text, attachments, voice } = steer.input;
18
+ const messages = appendUserDraftToHistory([], { ...(text === undefined ? {} : { text }) }, { ...(attachments ? { attachments } : {}), ...(voice ? { voice } : {}) });
18
19
  // labels-exempt: internal diagnostic; the user reads the error kind's (or copy key's) wording
19
20
  if (!messages.length)
20
- throw new TheoremError('request', 'inject must contain user messages');
21
+ throw new TheoremError('request', 'a steer needs text or a file');
21
22
  return { id: steer.id, messages };
22
23
  }
23
24
  /** Lands the inbox's next steer, one per steerable stage, named by its id. */
@@ -0,0 +1,11 @@
1
+ /**
2
+ * @module
3
+ * The ready-made decider for an app with no server of its own: the page open on the chat wakes it.
4
+ */
5
+ import type { LateResultsDecider } from '@theoremjs/agents';
6
+ /**
7
+ * Each late result is told to the first reply that runs, and the page open on the chat wakes it
8
+ * when one waits. A result two replies read without telling is given up, and reported once as
9
+ * `late_results_given_up`, so a model that keeps failing does not reply again and again.
10
+ */
11
+ export declare const tellEveryResult: LateResultsDecider;
@@ -0,0 +1,17 @@
1
+ /** Replies that may read one result: the first, and one more after a reply that failed or lost the chat. */
2
+ const READS_PER_RESULT_COUNT = 2;
3
+ /**
4
+ * Each late result is told to the first reply that runs, and the page open on the chat wakes it
5
+ * when one waits. A result two replies read without telling is given up, and reported once as
6
+ * `late_results_given_up`, so a model that keeps failing does not reply again and again.
7
+ */
8
+ export const tellEveryResult = {
9
+ policy: (items) => ({
10
+ tell: items
11
+ .filter((item) => item.handovers.length < READS_PER_RESULT_COUNT)
12
+ .map((item) => item.id),
13
+ giveUp: items
14
+ .filter((item) => item.handovers.length >= READS_PER_RESULT_COUNT)
15
+ .map((item) => item.id),
16
+ }),
17
+ };
@@ -6,4 +6,12 @@ export declare function sessionToolCoordinator(store: {
6
6
  };
7
7
  mutate<T>(id: string, change: (state: TheoremSessionState) => T): Promise<T>;
8
8
  }, sessionId: string): ToolExecutionCoordinator;
9
+ /**
10
+ * The application's coordinator, with the session's record kept beside it. The application's
11
+ * decides each call and holds it first; the session's records the same call after it, so the page
12
+ * shows the call and its late end, and a resend reads it back.
13
+ * invariant: A call the application holds and the session already knows breaks the contract; the
14
+ * application's claim stays open for its own sweep.
15
+ */
16
+ export declare function layeredToolCoordinator(owner: ToolExecutionCoordinator, session: ToolExecutionCoordinator): ToolExecutionCoordinator;
9
17
  export declare function sameAcceptedAnswer(left: unknown, right: unknown): boolean;
@@ -73,6 +73,15 @@ function saveOutcome(state, identity, outcome) {
73
73
  outcome,
74
74
  settledAt,
75
75
  };
76
+ if (reply)
77
+ movedInbox(state);
78
+ }
79
+ /** why: A detached call's end is an item in its conversation's inbox; a hold reads again before it lets go. */
80
+ function movedInbox(state) {
81
+ state.inbox = {
82
+ version: (state.inbox?.version ?? 0) + 1,
83
+ conversations: state.inbox?.conversations ?? {},
84
+ };
76
85
  }
77
86
  export function sessionToolCoordinator(store, sessionId) {
78
87
  return {
@@ -150,10 +159,72 @@ export function sessionToolCoordinator(store, sessionId) {
150
159
  reason,
151
160
  detectedAt: Date.now(),
152
161
  };
162
+ if (reply)
163
+ movedInbox(state);
153
164
  });
154
165
  },
155
166
  };
156
167
  }
168
+ /**
169
+ * The application's coordinator, with the session's record kept beside it. The application's
170
+ * decides each call and holds it first; the session's records the same call after it, so the page
171
+ * shows the call and its late end, and a resend reads it back.
172
+ * invariant: A call the application holds and the session already knows breaks the contract; the
173
+ * application's claim stays open for its own sweep.
174
+ */
175
+ export function layeredToolCoordinator(owner, session) {
176
+ // why: The kernel hands back the owner's claim; the session's token for the same call is kept here.
177
+ const sessionTokens = new Map();
178
+ const sessionClaim = (claim) => {
179
+ const claimToken = sessionTokens.get(claim.operationId);
180
+ // labels-exempt: internal diagnostic; the user reads tool.execution_uncertain
181
+ if (!claimToken)
182
+ unavailable(`The session holds no claim on tool operation ${claim.operationId}`);
183
+ return { ...claim, claimToken };
184
+ };
185
+ const limits = [owner.maxOutcomeBytes, session.maxOutcomeBytes].filter((limit) => limit !== undefined);
186
+ const { detach } = owner;
187
+ return {
188
+ ...(limits.length > 0 ? { maxOutcomeBytes: Math.min(...limits) } : {}),
189
+ async lookup(identity) {
190
+ return (await owner.lookup(identity)) ?? (await session.lookup(identity));
191
+ },
192
+ async begin(identity) {
193
+ const held = await owner.begin(identity);
194
+ if (held.kind !== 'acquired')
195
+ return held;
196
+ const recorded = await session.begin(identity);
197
+ if (recorded.kind !== 'acquired')
198
+ unavailable(
199
+ // labels-exempt: internal diagnostic; the user reads tool.execution_uncertain
200
+ `The session already holds tool operation ${identity.operationId}, which its owner had not`);
201
+ sessionTokens.set(identity.operationId, recorded.claimToken);
202
+ return held;
203
+ },
204
+ ...(detach
205
+ ? {
206
+ async detach(claim, reply) {
207
+ await detach.call(owner, claim, reply);
208
+ await session.detach?.(sessionClaim(claim), reply);
209
+ },
210
+ }
211
+ : {}),
212
+ async settle(claim, outcome) {
213
+ await owner.settle(claim, outcome);
214
+ await session.settle(sessionClaim(claim), outcome);
215
+ sessionTokens.delete(claim.operationId);
216
+ },
217
+ async settleNotStarted(identity, outcome) {
218
+ await owner.settleNotStarted(identity, outcome);
219
+ await session.settleNotStarted(identity, outcome);
220
+ },
221
+ async markUncertain(claim, reason) {
222
+ await owner.markUncertain(claim, reason);
223
+ await session.markUncertain(sessionClaim(claim), reason);
224
+ sessionTokens.delete(claim.operationId);
225
+ },
226
+ };
227
+ }
157
228
  export function sameAcceptedAnswer(left, right) {
158
229
  const canonical = (value) => {
159
230
  if (Array.isArray(value))
@@ -1,10 +1,12 @@
1
1
  import type { SessionRequest, TurnInput } from '@theoremjs/agents';
2
+ import { refuseInterfacePick } from '@theoremjs/agents/interface';
2
3
  import type { LiveOpenMessage } from '../client/live-messages.ts';
3
4
  import type { TheoremTurnInput } from '../client/transport.ts';
4
5
  /** A turn input off the wire as the kernel takes it: the page's context is the client's. */
5
6
  export declare function kernelTurnInput(input: TheoremTurnInput, server?: unknown): TurnInput;
6
7
  /**
7
8
  * What a live call's first message asks of the session, as `runSession` takes
8
- * it: the page's context is the client's, and `server` is the host's own.
9
+ * it: the page's context is the client's, and `server` is the host's own. A model
10
+ * or effort the page picks is refused unless `profile` lets the interface pick it.
9
11
  */
10
- export declare function liveSessionOpen(open: LiveOpenMessage, server?: unknown): Pick<SessionRequest, 'inputOptions' | 'context' | 'providerState' | 'awayMs' | 'history' | 'path' | 'options' | 'model' | 'effort'>;
12
+ export declare function liveSessionOpen(open: LiveOpenMessage, profile: Parameters<typeof refuseInterfacePick>[0], server?: unknown): Pick<SessionRequest, 'inputOptions' | 'context' | 'providerState' | 'awayMs' | 'history' | 'path' | 'options' | 'model' | 'effort'>;
@@ -1,3 +1,4 @@
1
+ import { refuseInterfacePick } from '@theoremjs/agents/interface';
1
2
  /** The page's context as the client's and the host's as the server's; nothing when neither gave any. */
2
3
  function turnContext(client, server) {
3
4
  const context = {
@@ -14,9 +15,11 @@ export function kernelTurnInput(input, server) {
14
15
  }
15
16
  /**
16
17
  * What a live call's first message asks of the session, as `runSession` takes
17
- * it: the page's context is the client's, and `server` is the host's own.
18
+ * it: the page's context is the client's, and `server` is the host's own. A model
19
+ * or effort the page picks is refused unless `profile` lets the interface pick it.
18
20
  */
19
- export function liveSessionOpen(open, server) {
21
+ export function liveSessionOpen(open, profile, server) {
22
+ refuseInterfacePick(profile, open);
20
23
  const context = turnContext(open.context, server);
21
24
  return {
22
25
  ...(open.history ? { history: open.history } : {}),
@@ -1,24 +1,48 @@
1
1
  /**
2
2
  * The application's turn wiring (`TurnWiring.prepare`) laid over the turn the handler builds.
3
3
  * The handler keeps the fields it owns; the application's stage handler and credentials go
4
- * first, and the handler's own run when the application's have nothing.
4
+ * first, and the handler's own run when the application's have nothing. An application's own
5
+ * tool record, background service, and late results run with the session's, never in place of it.
5
6
  *
6
7
  * @module
7
8
  */
8
- import type { NormalizedTurnRequest, StageHandler, TurnRequest, TurnWiring } from '@theoremjs/agents';
9
- import type { ToolCredentialSource } from '@theoremjs/agents/kernel';
9
+ import type { NormalizedTurnRequest, StageHandler, TurnRequest } from '@theoremjs/agents';
10
+ import { type JsonObject, type ToolBackgroundService, type ToolCredentialSource } from '@theoremjs/agents/kernel';
11
+ /**
12
+ * The app's refusal of a reply, in place of a turn: its own line is the reply, with no model run.
13
+ * `host` is the app's own values for the line's block.
14
+ */
15
+ export type ReplyRefusal = {
16
+ refuse: {
17
+ text: string;
18
+ host?: JsonObject;
19
+ };
20
+ };
21
+ /** The app's `prepare` for a turn the server runs: the turn, or its refusal of the reply. */
22
+ export type AppPrepare = (turn: NormalizedTurnRequest) => TurnRequest | ReplyRefusal | Promise<TurnRequest | ReplyRefusal>;
23
+ /** Whether `prepare` refused the reply. */
24
+ export declare function isRefusal(prepared: TurnRequest | ReplyRefusal): prepared is ReplyRefusal;
10
25
  /** The fields a handler sets on every turn, which `prepare` cannot replace. */
11
- export type HandlerOwned = Pick<TurnRequest, 'profile' | 'execution' | 'pageExecution' | 'background' | 'providerState' | 'signal'>;
26
+ export type HandlerOwned = Pick<TurnRequest, 'profile' | 'pageExecution' | 'providerState' | 'signal'>;
27
+ /**
28
+ * The session's tool record, the handler's background service, and the session's late results,
29
+ * which `prepare` can add to.
30
+ */
31
+ export type HandlerTools = Pick<TurnRequest, 'execution' | 'background' | 'lateResults'>;
12
32
  /** What the handler adds to a turn of its own: the session's credentials and its steering. */
13
33
  export type HandlerTurnParts = {
14
34
  credentials: ToolCredentialSource;
15
35
  onStage?: StageHandler;
36
+ /** Tells an open page when a call of the service it is given ends. */
37
+ announce?: (service: ToolBackgroundService) => ToolBackgroundService;
16
38
  };
17
39
  /**
18
40
  * The turn to run: `turn` through the application's `prepare`, with the handler's own fields
19
- * kept, and its credentials and steering after the application's.
41
+ * kept, its credentials and steering after the application's, and the application's tool record
42
+ * and background service, when it gives them, joined with the session's. The application's
43
+ * refusal is returned as it is.
20
44
  */
21
- export declare function preparedTurn(prepare: TurnWiring['prepare'], turn: NormalizedTurnRequest & HandlerOwned, handler: HandlerTurnParts): Promise<TurnRequest>;
45
+ export declare function preparedTurn(prepare: AppPrepare | undefined, turn: NormalizedTurnRequest & HandlerOwned & HandlerTools, handler: HandlerTurnParts): Promise<TurnRequest | ReplyRefusal>;
22
46
  /**
23
47
  * The application's stage handler, then the handler's own when the application's asks for
24
48
  * nothing. What the second one would have done waits for the next stage that allows it.
@@ -27,5 +51,6 @@ export declare function stagesInOrder(app: StageHandler | undefined, own: StageH
27
51
  /**
28
52
  * The application's credentials, then the session's. A credential is saved where the slot
29
53
  * already lives: a refreshed token back to the application, a sign-in at a gate to the session.
54
+ * A delete forgets the slot in both, so neither copy answers after it.
30
55
  */
31
56
  export declare function credentialsInOrder(app: ToolCredentialSource | undefined, session: ToolCredentialSource): ToolCredentialSource;
@@ -1,32 +1,74 @@
1
1
  /**
2
2
  * The application's turn wiring (`TurnWiring.prepare`) laid over the turn the handler builds.
3
3
  * The handler keeps the fields it owns; the application's stage handler and credentials go
4
- * first, and the handler's own run when the application's have nothing.
4
+ * first, and the handler's own run when the application's have nothing. An application's own
5
+ * tool record, background service, and late results run with the session's, never in place of it.
5
6
  *
6
7
  * @module
7
8
  */
9
+ import { isSealedSource, } from '@theoremjs/agents/kernel';
10
+ import { layeredToolCoordinator } from "./tool-operations.js";
11
+ /** Whether `prepare` refused the reply. */
12
+ export function isRefusal(prepared) {
13
+ return 'refuse' in prepared;
14
+ }
8
15
  /**
9
16
  * The turn to run: `turn` through the application's `prepare`, with the handler's own fields
10
- * kept, and its credentials and steering after the application's.
17
+ * kept, its credentials and steering after the application's, and the application's tool record
18
+ * and background service, when it gives them, joined with the session's. The application's
19
+ * refusal is returned as it is.
11
20
  */
12
21
  export async function preparedTurn(prepare, turn, handler) {
13
22
  const app = prepare ? await prepare(turn) : turn;
23
+ if (isRefusal(app))
24
+ return app;
14
25
  const owned = {
15
26
  profile: turn.profile,
16
- ...(turn.execution ? { execution: turn.execution } : {}),
17
27
  ...(turn.pageExecution ? { pageExecution: turn.pageExecution } : {}),
18
- ...(turn.background ? { background: turn.background } : {}),
19
28
  ...(turn.providerState ? { providerState: turn.providerState } : {}),
20
29
  ...(turn.signal ? { signal: turn.signal } : {}),
21
30
  };
22
31
  const onStage = stagesInOrder(app.onStage, handler.onStage);
32
+ const execution = toolsInOrder(app.execution, turn.execution);
33
+ const background = backgroundInOrder(app.background, turn.background, handler.announce);
34
+ const lateResults = lateResultsInOrder(app.lateResults, turn.lateResults);
23
35
  return {
24
36
  ...app,
25
37
  ...owned,
26
- credentials: credentialsInOrder(app.credentials, handler.credentials),
38
+ ...(execution ? { execution } : {}),
39
+ ...(background ? { background } : {}),
40
+ ...(lateResults ? { lateResults } : {}),
41
+ credentials: turnCredentials(app.credentials, handler.credentials),
27
42
  ...(onStage ? { onStage } : {}),
28
43
  };
29
44
  }
45
+ /**
46
+ * The application's tool record, then the session's. The application's decides each call; the
47
+ * session's keeps the same call, so the page shows it and a resend reads it back.
48
+ */
49
+ function toolsInOrder(app, session) {
50
+ if (!app || !session || app === session)
51
+ return session ?? app;
52
+ return layeredToolCoordinator(app, session);
53
+ }
54
+ /**
55
+ * The application's background service in place of the handler's, told to the open page as the
56
+ * handler's is. The handler's runs when the application gives none.
57
+ */
58
+ function backgroundInOrder(app, own, announce) {
59
+ if (!app || app === own)
60
+ return own;
61
+ return announce ? announce(app) : app;
62
+ }
63
+ /**
64
+ * The application's late results, then the session's, at each moment the turn asks. The session's
65
+ * are the results it marked given, so an application's `prepare` cannot drop them.
66
+ */
67
+ function lateResultsInOrder(app, session) {
68
+ if (!app || !session || app === session)
69
+ return session ?? app;
70
+ return async (moment) => [...(await app(moment)), ...(await session(moment))];
71
+ }
30
72
  /**
31
73
  * The application's stage handler, then the handler's own when the application's asks for
32
74
  * nothing. What the second one would have done waits for the next stage that allows it.
@@ -36,9 +78,17 @@ export function stagesInOrder(app, own) {
36
78
  return app ?? own;
37
79
  return async (ctx) => (await app(ctx)) ?? (await own(ctx));
38
80
  }
81
+ /**
82
+ * A sealed application source stands alone: its keys never reach this process, so the session
83
+ * holds none beside it. Any other source goes before the session's.
84
+ */
85
+ function turnCredentials(app, session) {
86
+ return app && isSealedSource(app) ? app : credentialsInOrder(app, session);
87
+ }
39
88
  /**
40
89
  * The application's credentials, then the session's. A credential is saved where the slot
41
90
  * already lives: a refreshed token back to the application, a sign-in at a gate to the session.
91
+ * A delete forgets the slot in both, so neither copy answers after it.
42
92
  */
43
93
  export function credentialsInOrder(app, session) {
44
94
  if (!app)
@@ -48,6 +98,10 @@ export function credentialsInOrder(app, session) {
48
98
  return {
49
99
  get: async (slot) => (await app.get(slot)) ?? (await session.get(slot)),
50
100
  set: async (slot, credential) => (await app.get(slot)) ? await app.set(slot, credential) : await session.set(slot, credential),
101
+ delete: async (slot) => {
102
+ await app.delete(slot);
103
+ await session.delete(slot);
104
+ },
51
105
  ...(secrets.clientSecret
52
106
  ? { clientSecret: async (clientId) => await secrets.clientSecret?.(clientId) }
53
107
  : {}),