@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
@@ -9,8 +9,11 @@ import { type Profile, type ToolAccess, type ToolPermission, z } from '@theoremj
9
9
  import type { PageDispatchResult } from './page-dispatch.ts';
10
10
  import type { TraceFeed } from './trace-feed.ts';
11
11
  import { type HttpOptions, type TheoremInvokeRequest, type TurnEventSink } from './transport.ts';
12
- /** How a tool reaches its work: a function on the host, an HTTP endpoint, or an MCP server. */
13
- export declare const HOST_TOOL_KINDS: readonly ["function", "http", "mcp"];
12
+ /**
13
+ * How a tool reaches its work: a function on the host, an HTTP endpoint, an MCP server, or
14
+ * another agent. Every tool type the host defines; only the provider's own tools are left out.
15
+ */
16
+ export declare const HOST_TOOL_KINDS: readonly ["function", "http", "mcp", "agent"];
14
17
  export type HostToolKind = (typeof HOST_TOOL_KINDS)[number];
15
18
  /** One tool as the page sees it. Its endpoint, headers, and credentials stay on the host. */
16
19
  export type HostToolView = {
@@ -40,6 +43,8 @@ export type HostToolSource = {
40
43
  description: string;
41
44
  access: ToolAccess;
42
45
  permission: ToolPermission;
46
+ /** Whether the kernel added the model's `after` field to `inputSchema`. */
47
+ after?: boolean;
43
48
  inputSchema: Record<string, unknown>;
44
49
  outputSchema: Record<string, unknown>;
45
50
  };
@@ -6,10 +6,15 @@
6
6
  * @module
7
7
  */
8
8
  import { resolveObservabilityPolicy, TOOL_ACCESS, TOOL_PERMISSION, TURN_EVENT_SCHEMAS, z, } from '@theoremjs/agents';
9
+ import { declaredInputSchema } from '@theoremjs/agents/kernel';
9
10
  import { fetchJson, postJson, postNdjson, } from "./transport.js";
10
11
  import { checkWire } from "./wire-line.js";
11
- /** How a tool reaches its work: a function on the host, an HTTP endpoint, or an MCP server. */
12
- export const HOST_TOOL_KINDS = ['function', 'http', 'mcp'];
12
+ /**
13
+ * How a tool reaches its work: a function on the host, an HTTP endpoint, an MCP server, or
14
+ * another agent. Every tool type the host defines; only the provider's own tools are left out.
15
+ */
16
+ export const HOST_TOOL_KINDS = ['function', 'http', 'mcp', 'agent'];
17
+ true;
13
18
  function isHostToolKind(type) {
14
19
  return HOST_TOOL_KINDS.includes(type);
15
20
  }
@@ -29,7 +34,8 @@ export function hostInterface(profile, tools) {
29
34
  kind: tool.type,
30
35
  access: tool.access,
31
36
  permission: tool.permission,
32
- inputSchema: tool.inputSchema,
37
+ // why: A call from the page is one call in no step, so the model's `after` field has nothing to order.
38
+ inputSchema: declaredInputSchema(tool),
33
39
  outputSchema: tool.outputSchema,
34
40
  },
35
41
  ];
package/client/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  export { float32Rms, float32RmsToLevel, INPUT_LEVEL_GAIN, timeDomainBytesToLevel, } from './audio-level.ts';
2
2
  export { type ChatController, type ChatOptionPicks, type ChatOptions, type ChatState, type ChatUpdate, createChatController, type MessageDelivery, type SendTextOptions, type SentTurn, } from './chat.ts';
3
3
  export { type ComposerDrawerKind, type ComposerDrawerSummary, composerDrawerSummary, } from './composer-drawer.ts';
4
- export { type ComposerHint, isStashShortcut, resolveComposerHint, STASH_SHORTCUT, } from './composer-hints.ts';
4
+ export { COMPOSER_SHORTCUTS, type ComposerHint, composerShortcut, resolveComposerHint, } from './composer-hints.ts';
5
5
  export { type ComposerActionState, composerActionState, composerHasPayload, } from './composer-primary.ts';
6
6
  export { createDecisionTransport, type DecisionInterface, type DecisionQuestionView, type DecisionReply, type DecisionReplyResult, type DecisionTransport, decisionAssets, decisionInterface, failedTraces, postDecision, questionViews, readDecisionReply, withFailedTraces, } from './decision-transport.ts';
7
7
  export { type ComposerDraftFields, composerFieldsFromDraft } from './decode-composer-draft.ts';
@@ -24,14 +24,14 @@ export { isOAuthComplete, notifyOAuthComplete } from './oauth-popup.ts';
24
24
  export { type PageDispatchResult, withPageToolDispatch } from './page-dispatch.ts';
25
25
  export { sessionAfter, stampWorked } from './run-commit.ts';
26
26
  export { keepsConversation, type RunOutcome, resumeInterfaceTool, type StreamView, streamInterfaceDraftTurn, streamInterfaceTurn, } from './run-session.ts';
27
- export { blankRow, type JsonSchema, missingFields, type SchemaControl, type SchemaField, sampleFromSchema, schemaControl, schemaFields, withField, } from './schema-fields.ts';
27
+ export { blankRow, branchField, branchSample, branchValue, chosenBranch, inBranch, type JsonSchema, missingFields, type SchemaBranch, type SchemaControl, type SchemaField, sampleFromSchema, schemaControl, schemaFields, withField, } from './schema-fields.ts';
28
28
  export { fieldLabel, fieldReading, humanize, isPart, isPlain, isProse, isRow, json, type ListRow, layoutChars, MAX_ROWS, type PlainReading, plainReading, type Row, rowHeading, type Section, type Shape, shapeOf, splitFields, unpacked, withUnit, } from './shaped-data.ts';
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, type RunningReply, readNdjsonStream, type StatedTurn, type TheoremConversationRequest, type TheoremInvokeRequest, type TheoremReplay, type TheoremRewindRequest, type TheoremRewound, type TheoremSavedMessage, type TheoremStartRequest, type TheoremSteerReply, type TheoremSteerRequest, type TheoremStopRequest, TheoremStreamError, type TheoremTransport, type TheoremTurnInput, type TheoremTurnRequest, type TheoremWakeRequest, type TurnEventSink, type UnsupportedEvent, type WireLines, } from './transport.ts';
37
37
  export { buildInvokeRequest, buildTurnRequest, foldAssistantTurn, issuedOperationId, type RunScope, type WalkAway, } from './turn-client.ts';
package/client/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  export { float32Rms, float32RmsToLevel, INPUT_LEVEL_GAIN, timeDomainBytesToLevel, } from "./audio-level.js";
2
2
  export { createChatController, } from "./chat.js";
3
3
  export { composerDrawerSummary, } from "./composer-drawer.js";
4
- export { isStashShortcut, resolveComposerHint, STASH_SHORTCUT, } from "./composer-hints.js";
4
+ export { COMPOSER_SHORTCUTS, composerShortcut, resolveComposerHint, } from "./composer-hints.js";
5
5
  export { composerActionState, composerHasPayload, } from "./composer-primary.js";
6
6
  export { createDecisionTransport, decisionAssets, decisionInterface, failedTraces, postDecision, questionViews, readDecisionReply, withFailedTraces, } from "./decision-transport.js";
7
7
  export { composerFieldsFromDraft } from "./decode-composer-draft.js";
@@ -20,11 +20,11 @@ export { isOAuthComplete, notifyOAuthComplete } from "./oauth-popup.js";
20
20
  export { withPageToolDispatch } from "./page-dispatch.js";
21
21
  export { sessionAfter, stampWorked } from "./run-commit.js";
22
22
  export { keepsConversation, resumeInterfaceTool, streamInterfaceDraftTurn, streamInterfaceTurn, } from "./run-session.js";
23
- export { blankRow, missingFields, sampleFromSchema, schemaControl, schemaFields, withField, } from "./schema-fields.js";
23
+ export { blankRow, branchField, branchSample, branchValue, chosenBranch, inBranch, missingFields, sampleFromSchema, schemaControl, schemaFields, withField, } from "./schema-fields.js";
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";
@@ -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),
@@ -35,9 +35,10 @@ export type StreamInterfaceTurnBaseArgs = {
35
35
  /**
36
36
  * Fires once the message posts, with the blocks the transcript gains: a
37
37
  * walked-away reply's settled blocks, then the message's own (with media
38
- * preview data). Walking away, it posts once the host has it.
38
+ * preview data). Walking away, it posts once the host has it. `own` is how many of the blocks,
39
+ * at the end, are the message's.
39
40
  */
40
- onUserBlocks: (blocks: TranscriptBlock[]) => void;
41
+ onUserBlocks: (blocks: TranscriptBlock[], own: number) => void;
41
42
  signal?: AbortSignal;
42
43
  /**
43
44
  * Send while the reply waits on gates: the message walks away from every
@@ -60,6 +61,15 @@ export type StreamInterfaceTurnArgs = StreamInterfaceTurnBaseArgs & {
60
61
  export type StreamInterfaceDraftTurnArgs = StreamInterfaceTurnBaseArgs & {
61
62
  draft: UserTurnDraft;
62
63
  };
64
+ export declare function extractInlineEncodedAttachments(attachments?: readonly {
65
+ name: string;
66
+ mimeType: string;
67
+ data?: unknown;
68
+ }[]): Array<{
69
+ name: string;
70
+ mimeType: string;
71
+ data: string;
72
+ }> | undefined;
63
73
  export declare function streamInterfaceTurn(args: StreamInterfaceTurnArgs): Promise<RunOutcome>;
64
74
  /** Send a turn from an already-encoded pending draft (queue drain / send now). */
65
75
  export declare function streamInterfaceDraftTurn(args: StreamInterfaceDraftTurnArgs): Promise<RunOutcome>;
@@ -77,3 +87,18 @@ export declare function resumeInterfaceTool(args: {
77
87
  resolution: ToolGateResolution;
78
88
  view: StreamView;
79
89
  }): Promise<RunOutcome>;
90
+ /**
91
+ * Wake the conversation: stream the reply the host runs for results no reply has read. `began`
92
+ * fires on its first line; a host with nothing to wake for sends none, and the run leaves nothing.
93
+ */
94
+ export declare function streamInterfaceWake(args: {
95
+ iface: ComposerProfileInterface;
96
+ transport: TheoremTransport;
97
+ session: InterfaceTurnSession;
98
+ scope: RunScope & {
99
+ conversation: string;
100
+ };
101
+ view: StreamView;
102
+ signal?: AbortSignal;
103
+ began(): void;
104
+ }): Promise<RunOutcome>;
@@ -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.
@@ -41,13 +41,13 @@ async function streamPreparedTurn(args) {
41
41
  const events = walking ? [...paused] : [];
42
42
  let posted = !keeps;
43
43
  if (!walking)
44
- args.onUserBlocks(userBlocks);
44
+ args.onUserBlocks(userBlocks, userBlocks.length);
45
45
  const onConversation = (line) => {
46
46
  if (!line.posted)
47
47
  return;
48
48
  posted = true;
49
49
  if (walking) {
50
- args.onUserBlocks([...foldAssistantTurn(args.iface, events), ...userBlocks]);
50
+ args.onUserBlocks([...foldAssistantTurn(args.iface, events), ...userBlocks], userBlocks.length);
51
51
  events.length = 0;
52
52
  }
53
53
  };
@@ -87,7 +87,7 @@ async function streamPreparedTurn(args) {
87
87
  }
88
88
  return { session: args.session, events, posted };
89
89
  }
90
- function extractInlineEncodedAttachments(attachments) {
90
+ export function extractInlineEncodedAttachments(attachments) {
91
91
  const filtered = attachments
92
92
  ?.filter((a) => typeof a.data === 'string')
93
93
  .map((a) => ({ name: a.name, mimeType: a.mimeType, data: a.data }));
@@ -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
+ }
@@ -39,18 +39,45 @@ export type SchemaControl = {
39
39
  } | {
40
40
  kind: 'group';
41
41
  schema: JsonSchema;
42
+ } | {
43
+ kind: 'branches';
44
+ branches: SchemaBranch[];
45
+ isMenu: boolean;
42
46
  } | {
43
47
  kind: 'json';
44
48
  };
49
+ /**
50
+ * One of the shapes a field of several (`anyOf` or `oneOf`) can take, and how its value shows
51
+ * which: `key` holds the constant `is`, or, with no `is`, the object holds `key` alone.
52
+ */
53
+ export type SchemaBranch = {
54
+ label: string;
55
+ key: string;
56
+ is?: string | number | boolean;
57
+ /** What the form asks for in this shape: the rest of the object, or the value under `key`. */
58
+ body: JsonSchema;
59
+ };
45
60
  export type SchemaField = {
46
61
  key: string;
47
62
  label: string;
48
63
  description?: string;
49
64
  isRequired: boolean;
65
+ /** The field also takes `null`, which the form sends only when asked: left out stays left out. */
66
+ isNullable?: true;
50
67
  control: SchemaControl;
51
68
  };
69
+ /** The shape `value` is in, if it is in one. */
70
+ export declare function chosenBranch(branches: readonly SchemaBranch[], value: unknown): SchemaBranch | undefined;
71
+ /** The part of `value` a shape's body edits. */
72
+ export declare function branchValue(branch: SchemaBranch, value: unknown): unknown;
73
+ /** The value in `branch` with `body` as its body. */
74
+ export declare function inBranch(branch: SchemaBranch, body: unknown): Record<string, unknown>;
75
+ /** A shape's body as a field of its own, labelled as the shape. */
76
+ export declare function branchField(branch: SchemaBranch): SchemaField;
77
+ /** A value in `branch`, its body at its sample. */
78
+ export declare function branchSample(branch: SchemaBranch): Record<string, unknown>;
52
79
  /** The input a field's schema asks for. */
53
- export declare function schemaControl(prop: JsonSchema): SchemaControl;
80
+ export declare function schemaControl(field: JsonSchema): SchemaControl;
54
81
  /** An object schema's fields in the order it declares them, each with its input. */
55
82
  export declare function schemaFields(schema: JsonSchema): SchemaField[];
56
83
  /** Required fields, and optional ones the schema gives an example for; a plain value of the field's type when the schema declares no sample. */
@@ -37,6 +37,130 @@ function enumOf(prop) {
37
37
  ? options
38
38
  : undefined;
39
39
  }
40
+ function optionsOf(prop) {
41
+ const options = Array.isArray(prop.anyOf)
42
+ ? prop.anyOf
43
+ : Array.isArray(prop.oneOf)
44
+ ? prop.oneOf
45
+ : undefined;
46
+ return options?.filter(isRow);
47
+ }
48
+ const isNullSchema = (prop) => prop.type === 'null';
49
+ /** The field's schema without its `null` option, and whether it has one. */
50
+ function withoutNull(prop) {
51
+ if (Array.isArray(prop.type) && prop.type.includes('null')) {
52
+ return { schema: prop, isNullable: true };
53
+ }
54
+ const options = optionsOf(prop);
55
+ if (!options?.some(isNullSchema))
56
+ return { schema: prop, isNullable: false };
57
+ const rest = options.filter((option) => !isNullSchema(option));
58
+ const { anyOf: _anyOf, oneOf: _oneOf, ...own } = prop;
59
+ const [only] = rest;
60
+ return {
61
+ schema: rest.length === 1 && only ? { ...only, ...own } : { ...own, anyOf: rest },
62
+ isNullable: true,
63
+ };
64
+ }
65
+ function constOf(prop) {
66
+ if (!isRow(prop))
67
+ return undefined;
68
+ const value = 'const' in prop
69
+ ? prop.const
70
+ : Array.isArray(prop.enum) && prop.enum.length === 1
71
+ ? prop.enum[0]
72
+ : undefined;
73
+ return typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean'
74
+ ? value
75
+ : undefined;
76
+ }
77
+ function titleOf(prop) {
78
+ return typeof prop.title === 'string' && prop.title ? prop.title : undefined;
79
+ }
80
+ const isDistinct = (values) => new Set(values).size === values.length;
81
+ /** Shapes told apart by a property each holds a different constant in. */
82
+ function taggedBranches(options) {
83
+ const shapes = options.map((option) => option.properties);
84
+ for (const key of Object.keys(shapes[0] ?? {})) {
85
+ const tags = shapes.map((shape) => constOf(shape[key]));
86
+ if (!isDistinct(tags))
87
+ continue;
88
+ const branches = options.map((option, at) => {
89
+ const is = tags[at];
90
+ if (is === undefined)
91
+ return undefined;
92
+ const { [key]: _tag, ...rest } = shapes[at] ?? {};
93
+ const required = Array.isArray(option.required)
94
+ ? { required: option.required.filter((name) => name !== key) }
95
+ : {};
96
+ return {
97
+ label: titleOf(option) ?? humanize(String(is)),
98
+ key,
99
+ is,
100
+ body: { ...option, properties: rest, ...required },
101
+ };
102
+ });
103
+ if (branches.every((branch) => branch !== undefined))
104
+ return branches;
105
+ }
106
+ return undefined;
107
+ }
108
+ /** Shapes that each hold one key of their own: the key says which. */
109
+ function keyedBranches(options) {
110
+ const branches = options.map((option) => {
111
+ const entries = Object.entries(option.properties);
112
+ const [entry] = entries;
113
+ if (entries.length !== 1 || !entry || !isRow(entry[1]))
114
+ return undefined;
115
+ const [key, body] = entry;
116
+ return { label: titleOf(option) ?? humanize(key), key, body };
117
+ });
118
+ if (!branches.every((branch) => branch !== undefined))
119
+ return undefined;
120
+ return isDistinct(branches.map((branch) => branch.key)) ? branches : undefined;
121
+ }
122
+ /** The shapes of a field of several objects, when its value shows which one it is in. */
123
+ function branchesOf(prop) {
124
+ const options = optionsOf(prop);
125
+ if (!options || options.length < 2 || !options.every((option) => isRow(option.properties))) {
126
+ return undefined;
127
+ }
128
+ return taggedBranches(options) ?? keyedBranches(options);
129
+ }
130
+ /** The shape `value` is in, if it is in one. */
131
+ export function chosenBranch(branches, value) {
132
+ if (!isRow(value))
133
+ return undefined;
134
+ return branches.find((branch) => branch.is === undefined ? Object.hasOwn(value, branch.key) : value[branch.key] === branch.is);
135
+ }
136
+ /** The part of `value` a shape's body edits. */
137
+ export function branchValue(branch, value) {
138
+ if (!isRow(value))
139
+ return undefined;
140
+ if (branch.is === undefined)
141
+ return value[branch.key];
142
+ const { [branch.key]: _tag, ...rest } = value;
143
+ return rest;
144
+ }
145
+ /** The value in `branch` with `body` as its body. */
146
+ export function inBranch(branch, body) {
147
+ if (branch.is === undefined)
148
+ return { [branch.key]: body };
149
+ return { ...(isRow(body) ? body : {}), [branch.key]: branch.is };
150
+ }
151
+ /** A shape's body as a field of its own, labelled as the shape. */
152
+ export function branchField(branch) {
153
+ return {
154
+ key: branch.key,
155
+ label: branch.label,
156
+ isRequired: true,
157
+ control: branch.is === undefined ? schemaControl(branch.body) : { kind: 'group', schema: branch.body },
158
+ };
159
+ }
160
+ /** A value in `branch`, its body at its sample. */
161
+ export function branchSample(branch) {
162
+ return inBranch(branch, sampleValue(branch.body));
163
+ }
40
164
  function numberAt(prop, key) {
41
165
  const value = prop[key];
42
166
  return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
@@ -80,10 +204,14 @@ function listControl(prop) {
80
204
  return { kind: 'json' };
81
205
  }
82
206
  /** The input a field's schema asks for. */
83
- export function schemaControl(prop) {
207
+ export function schemaControl(field) {
208
+ const prop = withoutNull(field).schema;
84
209
  const options = enumOf(prop);
85
210
  if (options)
86
211
  return { kind: 'choice', options, isMenu: options.length > MAX_SEGMENTS };
212
+ const branches = branchesOf(prop);
213
+ if (branches)
214
+ return { kind: 'branches', branches, isMenu: branches.length > MAX_SEGMENTS };
87
215
  switch (kindOf(prop)) {
88
216
  case 'boolean':
89
217
  return { kind: 'switch' };
@@ -121,6 +249,7 @@ export function schemaFields(schema) {
121
249
  ? { description: prop.description }
122
250
  : {}),
123
251
  isRequired: required.has(key),
252
+ ...(withoutNull(prop).isNullable ? { isNullable: true } : {}),
124
253
  control: schemaControl(prop),
125
254
  },
126
255
  ];
@@ -138,10 +267,14 @@ function declaredSample(prop) {
138
267
  return { value: prop.enum[0] };
139
268
  return undefined;
140
269
  }
141
- function sampleValue(prop) {
142
- const declared = declaredSample(prop);
270
+ function sampleValue(field) {
271
+ const declared = declaredSample(field);
143
272
  if (declared)
144
273
  return declared.value;
274
+ const prop = withoutNull(field).schema;
275
+ const branches = branchesOf(prop);
276
+ if (branches?.[0])
277
+ return branchSample(branches[0]);
145
278
  switch (kindOf(prop)) {
146
279
  case 'number':
147
280
  case 'integer':
@@ -153,20 +286,28 @@ function sampleValue(prop) {
153
286
  case 'object':
154
287
  return sampleFromSchema(prop);
155
288
  case 'string':
156
- case 'unknown':
157
289
  return 'example';
290
+ case 'unknown':
291
+ // why: No sample fits a value of no known shape; the field waits for the person.
292
+ return undefined;
158
293
  }
159
294
  }
160
295
  /** Required fields, and optional ones the schema gives an example for; a plain value of the field's type when the schema declares no sample. */
161
296
  export function sampleFromSchema(schema) {
297
+ const branches = branchesOf(schema);
298
+ if (branches?.[0])
299
+ return branchSample(branches[0]);
162
300
  const props = isRow(schema.properties) ? schema.properties : {};
163
301
  const required = new Set(requiredOf(schema));
164
302
  const sample = {};
165
303
  for (const [key, prop] of Object.entries(props)) {
166
304
  if (!isRow(prop))
167
305
  continue;
168
- if (required.has(key))
169
- sample[key] = sampleValue(prop);
306
+ if (required.has(key)) {
307
+ const value = sampleValue(prop);
308
+ if (value !== undefined)
309
+ sample[key] = value;
310
+ }
170
311
  else if (Array.isArray(prop.examples) && prop.examples.length)
171
312
  sample[key] = prop.examples[0];
172
313
  }
@@ -187,13 +328,31 @@ export function withField(row, key, value) {
187
328
  }
188
329
  /** The labels of required fields the request is still missing, nested ones by their path. */
189
330
  export function missingFields(schema, value, prefix = '') {
331
+ const branches = branchesOf(schema);
332
+ if (branches) {
333
+ const branch = chosenBranch(branches, value);
334
+ if (!branch)
335
+ return [];
336
+ // why: A keyed shape's one key is the field a top-level request lacks when it is empty.
337
+ const label = prefix || (branch.is === undefined ? branch.label : '');
338
+ return missingIn(branchField(branch), branchValue(branch, value), label);
339
+ }
190
340
  if (!isRow(value))
191
341
  return [];
192
- return schemaFields(schema).flatMap((field) => {
193
- const entry = value[field.key];
194
- const label = prefix ? `${prefix} › ${field.label}` : field.label;
195
- if (entry === undefined || entry === null || entry === '')
196
- return field.isRequired ? [label] : [];
197
- return field.control.kind === 'group' ? missingFields(field.control.schema, entry, label) : [];
198
- });
342
+ return schemaFields(schema).flatMap((field) => missingIn(field, value[field.key], prefix ? `${prefix} › ${field.label}` : field.label));
343
+ }
344
+ /** What `entry`, the value of `field`, still lacks: the field itself, or what its shape needs. */
345
+ function missingIn(field, entry, label) {
346
+ if (entry === null && field.isNullable)
347
+ return [];
348
+ if (entry === undefined || entry === null || entry === '')
349
+ return field.isRequired ? [label] : [];
350
+ const { control } = field;
351
+ if (control.kind === 'group')
352
+ return missingFields(control.schema, entry, label);
353
+ if (control.kind === 'branches') {
354
+ const branch = chosenBranch(control.branches, entry);
355
+ return branch ? missingIn(branchField(branch), branchValue(branch, entry), label) : [label];
356
+ }
357
+ return [];
199
358
  }
@@ -6,6 +6,7 @@
6
6
  *
7
7
  * @module
8
8
  */
9
+ import { type ToolOutputRefPart } 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,16 @@ 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;
56
+ metadata?: Record<string, unknown>;
55
57
  };
56
- /** What a call returned to see or hear: its image parts, then the images its value links; its audio parts. */
58
+ /** What a call returned to see or hear: its image parts and its audio parts. */
57
59
  export type ReturnedMedia = {
58
60
  images: ResultImage[];
59
61
  audio: {
@@ -63,8 +65,10 @@ export type ReturnedMedia = {
63
65
  };
64
66
  /** What a tool's output leads with. Empty when nothing stands out: the data alone reads best. */
65
67
  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(layout: ResultLayout, parts: readonly ResultMedia[], imageAlt: string): ReturnedMedia;
68
+ /** The images and audio a call returned, each with its bytes; parts without them (references) are left out. */
69
+ export declare function returnedMedia(parts: readonly ResultMedia[], imageAlt: string): ReturnedMedia;
70
+ /** The references a call returned, which only the app's resolver turns into something to show. */
71
+ export declare function referencesIn(parts: readonly ResultMedia[]): ToolOutputRefPart[];
68
72
  /** Whether the result has anything to lead with above its data. */
69
73
  export declare function hasLead(layout: ResultLayout, media: ReturnedMedia): boolean;
70
74
  /**