@theoremjs/agents 0.3.5-next.902.g334d23a → 0.3.5-next.906.g6f050f4

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 (36) hide show
  1. package/esm/src/host/mod.d.ts +2 -1
  2. package/esm/src/host/mod.js +2 -1
  3. package/esm/src/kernel/engine/runner/steps.js +1 -0
  4. package/esm/src/kernel/engine/session/mod.js +1 -0
  5. package/esm/src/kernel/field-docs.js +5 -5
  6. package/esm/src/kernel/mod.d.ts +2 -1
  7. package/esm/src/kernel/mod.js +1 -1
  8. package/esm/src/kernel/profile-presence.js +1 -1
  9. package/esm/src/kernel/protocols/binding.d.ts +6 -6
  10. package/esm/src/kernel/protocols/binding.js +1 -1
  11. package/esm/src/kernel/registry/kernel-registry.js +2 -2
  12. package/esm/src/kernel/registry/profiles.d.ts +3 -1
  13. package/esm/src/kernel/registry/profiles.js +10 -1
  14. package/esm/src/kernel/registry/resolve.js +6 -1
  15. package/esm/src/kernel/registry/schemas.js +2 -0
  16. package/esm/src/kernel/schema.js +1 -1
  17. package/esm/src/kernel/stages.d.ts +6 -0
  18. package/esm/src/kernel/system-lines.d.ts +12 -0
  19. package/esm/src/kernel/system-lines.js +25 -0
  20. package/esm/src/kernel/tools/events.d.ts +1 -0
  21. package/esm/src/kernel/tools/events.js +9 -1
  22. package/esm/src/kernel/tools/execute.d.ts +2 -0
  23. package/esm/src/kernel/tools/execute.js +60 -21
  24. package/esm/src/kernel/tools/model-view.d.ts +28 -0
  25. package/esm/src/kernel/tools/model-view.js +261 -0
  26. package/esm/src/kernel/tools/project.js +4 -2
  27. package/esm/src/kernel/tools/registry.d.ts +4 -1
  28. package/esm/src/kernel/tools/registry.js +5 -1
  29. package/esm/src/kernel/tools/remote.d.ts +6 -2
  30. package/esm/src/kernel/tools/remote.js +16 -11
  31. package/esm/src/kernel/tools/resolve.js +2 -1
  32. package/esm/src/kernel/tools/stage-run.d.ts +2 -0
  33. package/esm/src/kernel/tools/stage-run.js +3 -1
  34. package/esm/src/kernel/types.d.ts +3 -4
  35. package/esm/src/providers/openrouter/protocol.js +1 -0
  36. package/package.json +1 -1
@@ -1,10 +1,11 @@
1
1
  /**
2
2
  * Optional host-application helpers, not part of the turn kernel: HTTP reply status, cutout-trace
3
- * flush, and live structured-output preview.
3
+ * flush, live structured-output preview, and a tool's input as a model reads it.
4
4
  *
5
5
  * @module
6
6
  */
7
7
  import "../../_dnt.polyfills.js";
8
+ export { inputSchemaForModel, markedFieldsIn } from '../kernel/tools/model-view.js';
8
9
  export type { ClientError, ClientTurnOptions } from './client-turn.js';
9
10
  export { clientError, forClient, forClientEvents } from './client-turn.js';
10
11
  export type { CutoutTape } from './mint-trace.js';
@@ -1,10 +1,11 @@
1
1
  /**
2
2
  * Optional host-application helpers, not part of the turn kernel: HTTP reply status, cutout-trace
3
- * flush, and live structured-output preview.
3
+ * flush, live structured-output preview, and a tool's input as a model reads it.
4
4
  *
5
5
  * @module
6
6
  */
7
7
  import "../../_dnt.polyfills.js";
8
+ export { inputSchemaForModel, markedFieldsIn } from '../kernel/tools/model-view.js';
8
9
  export { clientError, forClient, forClientEvents } from './client-turn.js';
9
10
  export { flushMintTrace } from './mint-trace.js';
10
11
  export { readStreamingJsonStringField } from './readStreamingJsonStringField.js';
@@ -580,6 +580,7 @@ async function* handleModelCalls(outcome, generation, profile, state, system, {
580
580
  name: call.name,
581
581
  input: call.arguments,
582
582
  callId: call.callId,
583
+ fromModel: true,
583
584
  ctx: {
584
585
  operationId: call.operationId,
585
586
  pageExecution: generation.pageExecution,
@@ -818,6 +818,7 @@ function buildLiveSession(args) {
818
818
  name: held.name,
819
819
  input,
820
820
  callId,
821
+ fromModel: resume === undefined,
821
822
  ctx: {
822
823
  operationId: held.operationId,
823
824
  sessionPermissions,
@@ -224,8 +224,8 @@ export const FIELD_DOCS = {
224
224
  models: 'The trained AI systems that turn input into results. Each entry binds a local name to an upstream model and its call settings.',
225
225
  'models.*': 'One model: how to reach it and the settings sent with it.',
226
226
  'models.*.allowEffortSelect': 'Lets a turn pick an effort; needs two or more efforts.',
227
- 'models.*.apiId': "The model's id as the provider lists it, such as gemini-2.5-flash; sent on every call. The name this model has in the profile is its key in models.",
228
- 'models.*.builtInTools': "The provider's own tools, such as Google Search, this model may use; each must be registered as a builtin tool and declared by the provider's adapter.",
227
+ 'models.*.apiId': "The model's id as the provider lists it; sent on every call. The name this model has in the profile is its key in models.",
228
+ 'models.*.builtInTools': "The provider's own tools, such as its web search, this model may use; each must be registered as a builtin tool and declared by the provider's adapter.",
229
229
  'models.*.compaction': 'Summarises history past a threshold. A text agent can write the summary. Other types name a compaction profile.',
230
230
  'models.*.compaction.compactAt': 'The fraction of maxTokens, between 0 and 1, at which compaction starts, unless trigger decides.',
231
231
  'models.*.compaction.maxTokens': 'The token budget compactAt is a fraction of.',
@@ -252,7 +252,7 @@ export const FIELD_DOCS = {
252
252
  'models.*.maxOutputTokens': 'The token limit for one reply. Some providers never send it for speech, or for image without includeText.',
253
253
  'models.*.options': "Settings only this model's protocol has, such as a task type or vector size. Each is checked when the profile loads. Any left out keep the provider's default.",
254
254
  'models.*.protocol': 'The API shape this model is spoken to in.',
255
- 'models.*.provider': 'The service that runs the model or routes requests to one, such as Gemini or OpenRouter. Its registration supplies the endpoint and authentication.',
255
+ 'models.*.provider': 'The service that runs the model or routes requests to one. Its registration supplies the endpoint and authentication.',
256
256
  'models.*.summaries': 'Asks the model for summaries of its thinking, which not every model sends; with some providers, off only hides thoughts, and others ignore it.',
257
257
  'models.*.temperature': "How varied the model's wording is; higher is more random. Some providers never send it for speech, or for image without includeText.",
258
258
  'models.*.timeoutMs': 'How long a decision waits for its provider, in milliseconds. Omit for no timeout.',
@@ -393,7 +393,7 @@ export const FIELD_DOCS = {
393
393
  'runTurn.promoted': 'Tools this reply already had when an earlier run of it paused; the turn opens with them on its list.',
394
394
  'runTurn.providerState': 'Native provider state saved alongside portable history.',
395
395
  'runTurn.resolveHost': 'Resolves the host name of a remote tool before each request; a name that resolves to a private address is refused.',
396
- 'runTurn.sessionId': 'A session key that OpenRouter uses for routing and caching.',
396
+ 'runTurn.sessionId': "A session key a provider may use to route and cache this session's calls together.",
397
397
  'runTurn.sessionPermissions': 'The tools the user has already approved for this session.',
398
398
  'runTurn.signal': 'Stops the run when it aborts, and cancels its provider call where the provider can.',
399
399
  'runTurn.speech': "This turn's voice, style, and speed; each one given replaces the profile's speech field of that name. Refused on a profile that is not speech.",
@@ -591,7 +591,7 @@ export const OPTION_DOCS = {
591
591
  always_confirm: 'Asks every time.',
592
592
  },
593
593
  TOOL_TYPES: {
594
- builtin: "The provider's own tool, such as Google Search, run by the provider.",
594
+ builtin: "The provider's own tool, such as its web search, run by the provider.",
595
595
  function: 'Your handler runs it.',
596
596
  http: 'The kernel calls your HTTP endpoint.',
597
597
  mcp: 'The kernel calls a tool on a remote MCP server.',
@@ -59,7 +59,8 @@ export type { AwaitingUserInput, StageAffordance, StageApplyInput, StageApplyOut
59
59
  export { applyStageResult, STAGE_AFFORDANCE_MATRIX, STAGE_AFFORDANCES, stageAllowsAffordance, stageEventFields, } from './stages.js';
60
60
  export type { MediaTurnBehaviourSpec, ProfileTurnBehaviourSpec, ProfileTurnResumptionSpec, TurnContinueFrom, TurnStop, } from './stop.js';
61
61
  export { AUTO_CONTINUE_DELAY_MS, CONTINUE_INSTRUCTION_TYPES, DEFAULT_ALLOW_CONTINUE, DEFAULT_AUTO_CONTINUE, GenerationStopError, isContinueStopKind, isGenerationStopError, isResumeableStop, isUserCancelledStop, profileAllowsInject, profileAllowsSteering, profileTurnResumption, shouldAutoContinue, turnStopFromClientStreamEnd, turnStopFromInteractionStatus, turnStopFromOpenAiFinishReason, } from './stop.js';
62
- export { systemLinesProblem } from './system-lines.js';
62
+ export type { SystemReadingLine } from './system-lines.js';
63
+ export { systemLinesProblem, systemReading } from './system-lines.js';
63
64
  export { systemPromptProblem } from './system-parts.js';
64
65
  export { activityLabelProblem } from './tools/activity-label.js';
65
66
  export { agentToolInputFor, agentToolOutput } from './tools/agent.js';
@@ -35,7 +35,7 @@ export { API_EXPORTS, ATTACHMENT_ACCEPT_MIMES, AUTH_UNAUTHENTICATED_POLICIES, AW
35
35
  export { createKernelScope, defaultKernelScope } from './scope.js';
36
36
  export { applyStageResult, STAGE_AFFORDANCE_MATRIX, STAGE_AFFORDANCES, stageAllowsAffordance, stageEventFields, } from './stages.js';
37
37
  export { AUTO_CONTINUE_DELAY_MS, CONTINUE_INSTRUCTION_TYPES, DEFAULT_ALLOW_CONTINUE, DEFAULT_AUTO_CONTINUE, GenerationStopError, isContinueStopKind, isGenerationStopError, isResumeableStop, isUserCancelledStop, profileAllowsInject, profileAllowsSteering, profileTurnResumption, shouldAutoContinue, turnStopFromClientStreamEnd, turnStopFromInteractionStatus, turnStopFromOpenAiFinishReason, } from './stop.js';
38
- export { systemLinesProblem } from './system-lines.js';
38
+ export { systemLinesProblem, systemReading } from './system-lines.js';
39
39
  export { systemPromptProblem } from './system-parts.js';
40
40
  export { activityLabelProblem } from './tools/activity-label.js';
41
41
  export { agentToolInputFor, agentToolOutput } from './tools/agent.js';
@@ -134,7 +134,7 @@ export const PROFILE_FIELD_PRESENCE = {
134
134
  'image.outputCompression': { unset: 'Provider default' },
135
135
  'image.references': { unset: 'None' },
136
136
  'image.includeText': { unset: 'Off', value: false },
137
- 'speech.voice': { unset: "The turn's speech.voice; Gemini refuses speech without one" },
137
+ 'speech.voice': { unset: "The turn's speech.voice, else the provider's own, if it has one" },
138
138
  'speech.style': { unset: "The turn's speech.style, else no direction" },
139
139
  'speech.speed': { unset: "The turn's speech.speed, else the voice's own pace" },
140
140
  'speech.format': { unset: 'Provider default' },
@@ -43,8 +43,8 @@ export declare const commonModelSettingsSchema: z.ZodObject<{
43
43
  */
44
44
  summaries: z.ZodOptional<z.ZodBoolean>;
45
45
  /**
46
- * The provider's own tools, such as Google Search, this model may use; each must be registered as
47
- * a builtin tool and declared by the provider's adapter.
46
+ * The provider's own tools, such as its web search, this model may use; each must be registered
47
+ * as a builtin tool and declared by the provider's adapter.
48
48
  */
49
49
  builtInTools: z.ZodOptional<z.ZodArray<z.ZodString>>;
50
50
  /**
@@ -58,13 +58,13 @@ export interface ModelBinding extends z.infer<typeof commonModelSettingsSchema>
58
58
  /** The API shape this model is spoken to in. */
59
59
  protocol: string;
60
60
  /**
61
- * The service that runs the model or routes requests to one, such as Gemini or OpenRouter. Its
62
- * registration supplies the endpoint and authentication.
61
+ * The service that runs the model or routes requests to one. Its registration supplies the
62
+ * endpoint and authentication.
63
63
  */
64
64
  provider: string;
65
65
  /**
66
- * The model's id as the provider lists it, such as gemini-2.5-flash; sent on every call. The name
67
- * this model has in the profile is its key in models.
66
+ * The model's id as the provider lists it; sent on every call. The name this model has in the
67
+ * profile is its key in models.
68
68
  */
69
69
  apiId: string;
70
70
  /**
@@ -27,7 +27,7 @@ const modelBinding = z.strictObject({
27
27
  protocol: z.string().min(1).describe('The API shape this model is spoken to in.'),
28
28
  provider: z.string().min(1).describe(
29
29
  // labels-exempt: builder field description, read by the studio and docs
30
- 'The service that runs the model or routes requests to one, such as Gemini or OpenRouter. Its registration supplies the endpoint and authentication.'),
30
+ 'The service that runs the model or routes requests to one. Its registration supplies the endpoint and authentication.'),
31
31
  // labels-exempt: builder field description, read by the studio and docs
32
32
  apiId: z.string().min(1).describe('The id the provider knows the model by.'),
33
33
  maxOutputTokens: shared.maxOutputTokens.describe(
@@ -1,13 +1,13 @@
1
1
  import { createProviderRegistry } from '../protocols/provider.js';
2
2
  import { createToolRegistry } from '../tools/registry.js';
3
- import { createProfileRegistry } from './profiles.js';
3
+ import { createProfileRegistry, structuredReplySchemas } from './profiles.js';
4
4
  import { createSchemaRegistry } from './schemas.js';
5
5
  /** Creates an empty registry of tools, profiles, and schemas, wired so a tool that names a profile can find it. */
6
6
  function createKernelRegistry() {
7
7
  // why: An agent tool names a profile, and a profile allows tools: each registry reads
8
8
  // the other. Tools look profiles up only when one registers, after both exist.
9
- const tools = createToolRegistry((id) => profiles.find(id));
10
9
  const schemas = createSchemaRegistry();
10
+ const tools = createToolRegistry((id) => profiles.find(id), (id) => structuredReplySchemas(schemas, profiles.find(id)));
11
11
  const providers = createProviderRegistry();
12
12
  const profiles = createProfileRegistry(tools, schemas, providers);
13
13
  return { tools, profiles, schemas, providers };
@@ -258,6 +258,8 @@ declare function defineProfile(input: EmbeddingProfileDefinition): EmbeddingProf
258
258
  declare function defineProfile(input: Exclude<ProfileDefinition, LiveProfileDefinition | HostProfileDefinition>): Exclude<Profile, LiveProfile | HostProfile>;
259
259
  /** Validate any definition and return the profile. */
260
260
  declare function defineProfile(input: ProfileDefinition): Profile;
261
+ /** The reply schemas a profile can give, for the agent tools that call it. */
262
+ declare function structuredReplySchemas(schemas: SchemaRegistry, profile: Profile | undefined): Record<string, unknown>[];
261
263
  /** A set of registered profiles, kept by id. */
262
264
  interface ProfileRegistry {
263
265
  register(profileInput: Profile | ProfileDefinition): void;
@@ -272,4 +274,4 @@ interface ProfileRegistry {
272
274
  /** Profiles are checked against `tools` and `schemas`, so register a scope's tools and schemas before its profiles. */
273
275
  declare function createProfileRegistry(tools: ToolRegistry, schemas: SchemaRegistry, providers?: ProviderRegistry): ProfileRegistry;
274
276
  export type { ProfileRegistry };
275
- export { createProfileRegistry, defineProfile };
277
+ export { createProfileRegistry, defineProfile, structuredReplySchemas };
@@ -699,6 +699,15 @@ function structuredIds(profile) {
699
699
  return [structured];
700
700
  return [...new Set([...Object.values(structured.map), structured.fallback])];
701
701
  }
702
+ /** The reply schemas a profile can give, for the agent tools that call it. */
703
+ function structuredReplySchemas(schemas, profile) {
704
+ if (profile?.type !== 'text')
705
+ return [];
706
+ return structuredIds(profile).flatMap((id) => {
707
+ const spec = schemas.find(id);
708
+ return spec ? [spec.jsonSchema] : [];
709
+ });
710
+ }
702
711
  /**
703
712
  * Every schema `outputs.structured` names is registered, and every
704
713
  * `outputs.validation.fields` path reaches a property of one of them.
@@ -808,4 +817,4 @@ function createProfileRegistry(tools, schemas, providers) {
808
817
  clear: () => profiles.clear(),
809
818
  };
810
819
  }
811
- export { createProfileRegistry, defineProfile };
820
+ export { createProfileRegistry, defineProfile, structuredReplySchemas };
@@ -8,6 +8,7 @@ import { ANSWER_TOOL } from '../answer-tool.js';
8
8
  import { DEFAULT_MAX_STEPS } from '../profile-presence.js';
9
9
  import { operationNameOf } from '../protocols/binding.js';
10
10
  import { profileTurnResumption } from '../stop.js';
11
+ import { withoutModelMarks } from '../tools/model-view.js';
11
12
  import { projectTools } from '../tools/project.js';
12
13
  import { resolveTurnTools } from '../tools/resolve.js';
13
14
  import { profileInputs, requireModelBinding } from './catalog.js';
@@ -207,7 +208,11 @@ function resolveTurnInRegistry(registry, req, model) {
207
208
  history: input.history,
208
209
  maxSteps: profile.maxSteps ?? DEFAULT_MAX_STEPS,
209
210
  structured: structuredId
210
- ? { id: structuredId, jsonSchema: registry.schemas.get(structuredId).jsonSchema }
211
+ ? {
212
+ id: structuredId,
213
+ // why: The mark is for the agent tools that read this reply; the provider never sees it.
214
+ jsonSchema: withoutModelMarks(registry.schemas.get(structuredId).jsonSchema),
215
+ }
211
216
  : null,
212
217
  image: resolveImageFormat(profile),
213
218
  speech: resolveSpeech(profile, safe),
@@ -1,4 +1,5 @@
1
1
  import { TheoremError } from '../../guardrails/error.js';
2
+ import { assertModelMarks } from '../tools/model-view.js';
2
3
  /** Creates an empty schema registry; `register` rejects a spec that still carries the removed `enforced` field. */
3
4
  function createSchemaRegistry() {
4
5
  const schemas = new Map();
@@ -12,6 +13,7 @@ function createSchemaRegistry() {
12
13
  Array.isArray(spec.jsonSchema)) {
13
14
  throw new TheoremError('config', `registerStructured '${id}': jsonSchema must be a JSON Schema object`);
14
15
  }
16
+ assertModelMarks(spec.jsonSchema, `registerStructured '${id}'`, 'output');
15
17
  schemas.set(id, spec);
16
18
  },
17
19
  get(id) {
@@ -268,7 +268,7 @@ export const AUTH_UNAUTHENTICATED_POLICIES = [
268
268
  ];
269
269
  /** The kinds of tool a profile can list. */
270
270
  export const TOOL_TYPES = [
271
- /** The provider's own tool, such as Google Search, run by the provider. */
271
+ /** The provider's own tool, such as its web search, run by the provider. */
272
272
  'builtin',
273
273
  /** Your handler runs it. */
274
274
  'function',
@@ -33,6 +33,12 @@ export type StageCallBag = {
33
33
  approved?: true;
34
34
  callNotStarted?: boolean;
35
35
  outputRaw?: unknown;
36
+ /**
37
+ * `post_tool`: the output as the model reads it, before it becomes text: `outputRaw` without
38
+ * the fields its schema marks `exposeToModel: false`. Absent when the call failed or the tool
39
+ * is hidden from the model.
40
+ */
41
+ outputForModel?: unknown;
36
42
  outputModel?: ModelToolResult;
37
43
  /** `post_tool`: the tool's past activity label, filled from the input and `outputRaw`. */
38
44
  activityPast?: string;
@@ -1,3 +1,4 @@
1
+ import { type Line } from './tools/activity-label.js';
1
2
  import type { ProfileOptions, ProfileSystem, SystemPiece } from './types.js';
2
3
  /** What is wrong with a prompt's options and lines, or undefined. */
3
4
  export declare function systemLinesProblem(prompt: ProfileSystem, code: ProfileOptions | undefined, person: ProfileOptions | undefined): string | undefined;
@@ -11,6 +12,17 @@ export type KeptSystemLine = {
11
12
  * line dropped on this turn never changes the marks of one that stayed.
12
13
  */
13
14
  export declare function pickSystemLines(prompt: ProfileSystem, facts: Record<string, string>, fill: (text: string) => string | undefined): KeptSystemLine[];
15
+ /** One line of a prompt as the kernel reads it: the turns it fits, and its pieces. */
16
+ export type SystemReadingLine = {
17
+ when: Line['when'];
18
+ pieces: SystemPiece[];
19
+ };
20
+ /**
21
+ * A prompt as the kernel reads it: each line's `when`, and its pieces, plain text marked the way
22
+ * the whole prompt settles it, with pieces of one mark side by side joined and empty ones left
23
+ * out. Two prompts with the same reading send the same words, with the same marks, on every turn.
24
+ */
25
+ export declare function systemReading(prompt: ProfileSystem): SystemReadingLine[];
14
26
  /** `where` names the prompt in the error. A bare `{ private }` must sit inside a line's own list. */
15
27
  export declare function assertSystemLines(prompt: unknown, where: string): asserts prompt is ProfileSystem;
16
28
  /** The first tool in `tools` with a path `options.path` does not list, as a sentence. */
@@ -87,6 +87,31 @@ export function pickSystemLines(prompt, facts, fill) {
87
87
  }
88
88
  return kept;
89
89
  }
90
+ /**
91
+ * A prompt as the kernel reads it: each line's `when`, and its pieces, plain text marked the way
92
+ * the whole prompt settles it, with pieces of one mark side by side joined and empty ones left
93
+ * out. Two prompts with the same reading send the same words, with the same marks, on every turn.
94
+ */
95
+ export function systemReading(prompt) {
96
+ const lines = linesOf(prompt);
97
+ const marked = lines.flat().some((part) => typeof part !== 'string');
98
+ return lines.map((parts) => {
99
+ const line = headOf(parts);
100
+ const pieces = [];
101
+ parts.forEach((part, at) => {
102
+ const text = at === 0 ? line.text : textOf(part);
103
+ if (!text)
104
+ return;
105
+ const isPrivate = typeof part === 'string' ? !marked : true;
106
+ const last = pieces.at(-1);
107
+ if (last?.private === isPrivate)
108
+ last.text += text;
109
+ else
110
+ pieces.push({ text, private: isPrivate });
111
+ });
112
+ return { when: line.when, pieces };
113
+ });
114
+ }
90
115
  /** `where` names the prompt in the error. A bare `{ private }` must sit inside a line's own list. */
91
116
  export function assertSystemLines(prompt, where) {
92
117
  if (typeof prompt === 'string')
@@ -42,6 +42,7 @@ export declare class HandOff {
42
42
  }
43
43
  export declare function dispatchToolBody(tool: {
44
44
  labels?: ToolLabels;
45
+ inputSchema?: Record<string, unknown>;
45
46
  }, input: unknown, ctx: ToolContext, base: ToolCallBase, beginBody?: (preparedInput: unknown) => Promise<ToolOperationClaim | undefined>): AsyncGenerator<TurnEvent, HandOff>;
46
47
  export declare function startToolExecution<T>(tool: {
47
48
  input: z.ZodType<T>;
@@ -8,6 +8,7 @@ import { sourceSchema } from '../turn-events.js';
8
8
  import { isRecord } from '../util/record.js';
9
9
  import { fillActivityLabel, toolNameInWords } from './activity-label.js';
10
10
  import { formatToolFailureForModel, formatToolResult } from './model-text.js';
11
+ import { inputForModel } from './model-view.js';
11
12
  export function toolEvent(base, patch) {
12
13
  return {
13
14
  type: 'tool',
@@ -107,7 +108,14 @@ function toolRunningEvent(tool, rawInput, ctx, base) {
107
108
  const activity = fillActivityLabel(tool.labels?.activity, { input: rawInput });
108
109
  return toolEvent(base, {
109
110
  phase: 'running',
110
- ...(edited ? { edited: { from: edited.from, to: toolCallArguments(rawInput) } } : {}),
111
+ ...(edited
112
+ ? {
113
+ edited: {
114
+ from: edited.from,
115
+ to: toolCallArguments(inputForModel(tool.inputSchema ?? {}, rawInput)),
116
+ },
117
+ }
118
+ : {}),
111
119
  ...(activity ? { activity } : {}),
112
120
  });
113
121
  }
@@ -86,6 +86,8 @@ interface RegisteredToolCall {
86
86
  agents?: AgentCaller;
87
87
  /** The canary and system instruction of the turn the model called from, read for in the arguments. */
88
88
  scope?: DetectScope;
89
+ /** The model made the call: a field its input schema keeps from the model is refused. */
90
+ fromModel?: boolean;
89
91
  }
90
92
  /**
91
93
  * A gate nobody answered: a sign-in for `expiredService` whose link expired, or any other gate
@@ -18,6 +18,7 @@ import { dispatchToolBody, failedActivity, failedActivityOf, failureEvent, messa
18
18
  import { HandlerEvents } from './handler-events.js';
19
19
  import { fetchToolImages } from './image-fetch.js';
20
20
  import { formatToolFailureForModel, formatToolResult, frameToolFailure } from './model-text.js';
21
+ import { agentOutputSchema, markedFieldsIn, outputForModel } from './model-view.js';
21
22
  import { operationBroken, operationWireValue } from './operation.js';
22
23
  import { checkPermission, gateDetails, isGateResumeDenied, isGateResumeGranted, isResumeContinuation, } from './permission.js';
23
24
  import { executeHttpTool, executeMcpTool, failureWithoutSecret, modelResultFromOutput, omitSecret, outcomeFromUnauth, parseToolOutput, refusedCredentialOutcome, resolveToolAuth, withMedia, } from './remote.js';
@@ -117,14 +118,15 @@ export function projectForModel(tool, output, labels) {
117
118
  if (tool.exposeToModel === false) {
118
119
  return { finding: labelText('tool.completed_hidden', {}, labels) };
119
120
  }
121
+ const seen = outputForModel(tool.outputSchema, output);
120
122
  if (isAwaitingUserInput(output)) {
121
123
  return {
122
124
  finding: labelText('tool.awaiting_user', { kind: output.kind, prompt: output.prompt }, labels),
123
- data: leanToolResultData(output),
125
+ data: leanToolResultData(seen),
124
126
  };
125
127
  }
126
- const parts = isRecord(output) && 'parts' in output ? coerceToolResultParts(output.parts) : undefined;
127
- const lean = leanToolResultData(output);
128
+ const parts = isRecord(seen) && 'parts' in seen ? coerceToolResultParts(seen.parts) : undefined;
129
+ const lean = leanToolResultData(seen);
128
130
  const summarized = isRecord(lean) && 'finding' in lean;
129
131
  const { finding: summary, ...rest } = summarized ? lean : {};
130
132
  const result = summarized
@@ -132,9 +134,15 @@ export function projectForModel(tool, output, labels) {
132
134
  finding: String(summary),
133
135
  ...(Object.keys(rest).length > 0 ? { data: rest } : {}),
134
136
  }
135
- : modelResultFromOutput(lean);
137
+ : modelResultFromOutput(lean, undefined);
136
138
  return { ...result, ...(parts ? { parts } : {}) };
137
139
  }
140
+ /** How the call's `post_tool` stage gets the output as the model reads it; nothing when the model reads none. */
141
+ function forModelOf(tool) {
142
+ if (tool.exposeToModel === false)
143
+ return {};
144
+ return { forModel: (output) => outputForModel(tool.outputSchema, output) };
145
+ }
138
146
  function loadsT2(tool, ctx) {
139
147
  return profileToolsSpec(ctx.profile)?.t2Loader === tool.name;
140
148
  }
@@ -244,7 +252,7 @@ function completeEvent(base, settled) {
244
252
  * output (the T2 loader), which makes a host `mutate` a warning instead of a replacement.
245
253
  */
246
254
  async function* settleToolCall(args) {
247
- const { base, toolName, callId, input, stages, provisional, guard, reproject, sources } = args;
255
+ const { base, input, stages, provisional, guard, sources } = args;
248
256
  const guarded = yield* 'failure' in provisional
249
257
  ? guard.failure(provisional.failure)
250
258
  : guard.result(provisional.modelResult);
@@ -256,22 +264,14 @@ async function* settleToolCall(args) {
256
264
  let awaiting = !failure && isAwaitingUserInput(outputRaw);
257
265
  let post;
258
266
  if (stages) {
259
- const activityPast = failure ? undefined : pastActivity(args.labels, input, outputRaw);
260
- post = yield* runPostToolStages({
261
- stages,
262
- toolName,
263
- callId,
264
- input,
267
+ let revised;
268
+ ({ post, revised } = yield* postToolOf(args, stages, {
265
269
  callNotStarted,
266
270
  outputRaw,
267
- outputModel: modelResult,
268
- ...(activityPast ? { activityPast } : {}),
269
- activityFailed: failedActivityOf(base),
271
+ modelResult,
270
272
  failure,
271
- awaiting: awaiting || undefined,
272
- mutable: !failure && reproject !== undefined,
273
- });
274
- const revised = yield* reviseAfterStages(post, guard, reproject);
273
+ awaiting,
274
+ }));
275
275
  if (revised) {
276
276
  ({ failure, outputRaw, modelResult, awaiting } = revised);
277
277
  if (post.deny)
@@ -305,6 +305,28 @@ async function* settleToolCall(args) {
305
305
  ...stageSettlement(post),
306
306
  };
307
307
  }
308
+ /** The host's post_tool stages on the call as it stands, and what their deny or `mutate` settles it with instead. */
309
+ async function* postToolOf(args, stages, now) {
310
+ const { base, toolName, callId, input, guard, reproject, forModel } = args;
311
+ const { outputRaw, failure } = now;
312
+ const activityPast = failure ? undefined : pastActivity(args.labels, input, outputRaw);
313
+ const post = yield* runPostToolStages({
314
+ stages,
315
+ toolName,
316
+ callId,
317
+ input,
318
+ callNotStarted: now.callNotStarted,
319
+ outputRaw,
320
+ ...(outputRaw !== undefined && forModel ? { outputForModel: forModel(outputRaw) } : {}),
321
+ outputModel: now.modelResult,
322
+ ...(activityPast ? { activityPast } : {}),
323
+ activityFailed: failedActivityOf(base),
324
+ failure,
325
+ awaiting: now.awaiting || undefined,
326
+ mutable: !failure && reproject !== undefined,
327
+ });
328
+ return { post, revised: yield* reviseAfterStages(post, guard, reproject) };
329
+ }
308
330
  /** The settled output's cited sources, then the pictures its tool names; the result carrying them. */
309
331
  async function* citeAndShow(args) {
310
332
  const { base, sources, images, outputRaw, modelResult } = args;
@@ -617,6 +639,7 @@ agent, beginBody) {
617
639
  },
618
640
  sources: tool.sources,
619
641
  labels: tool.labels,
642
+ ...forModelOf(tool),
620
643
  ...(ownsOutput
621
644
  ? {}
622
645
  : {
@@ -686,6 +709,20 @@ function registeredEligibilityFailure(args) {
686
709
  }
687
710
  return undefined;
688
711
  }
712
+ /** A model's call that sets a field the input schema keeps from the model: the host fills those. */
713
+ function hostFieldsFailure(args, tool, input) {
714
+ if (!args.fromModel)
715
+ return undefined;
716
+ const notInputs = markedFieldsIn(tool.inputSchema, input);
717
+ if (notInputs.length === 0)
718
+ return undefined;
719
+ return {
720
+ code: 'invalid_input',
721
+ kind: 'bad_response',
722
+ message: labelText('tool.input_invalid', {}, args.profile.labels),
723
+ details: { notInputs },
724
+ };
725
+ }
689
726
  export function authorizeToolReplay(args) {
690
727
  const tool = args.tools.get(args.name);
691
728
  if (!tool || tool.type === 'builtin') {
@@ -746,6 +783,7 @@ async function* settleBodyOutcome(args) {
746
783
  guard,
747
784
  provisional: { outputRaw: outcome.outputRaw, modelResult: outcome.modelResult },
748
785
  sources: tool.sources,
786
+ ...forModelOf(tool),
749
787
  ...(tool.type !== 'function' && tool.images
750
788
  ? {
751
789
  images: (output) => fetchToolImages(tool.images, output, ctx, tool.imageLimits),
@@ -754,7 +792,7 @@ async function* settleBodyOutcome(args) {
754
792
  labels: tool.labels,
755
793
  reproject: makeReproject((v) => parseToolOutput(tool.output, v),
756
794
  // why: A hook's edit replaces the value; the media the tool returned stays.
757
- (data) => withMedia(modelResultFromOutput(data), outcome.modelResult.parts), labels),
795
+ (data) => withMedia(modelResultFromOutput(data, tool.outputSchema), outcome.modelResult.parts), labels),
758
796
  });
759
797
  }
760
798
  function turnReadBack({ modelResult }) {
@@ -969,7 +1007,7 @@ async function* runRegisteredTool(args, tool) {
969
1007
  resume: ctx.resume,
970
1008
  snapshot,
971
1009
  visible: ctx.turn?.visible,
972
- });
1010
+ }) ?? hostFieldsFailure(args, tool, safeInput);
973
1011
  if (eligibility) {
974
1012
  yield failureEvent(base, eligibility);
975
1013
  return earlyFailure(eligibility);
@@ -1129,7 +1167,8 @@ async function* executeAgentTool(args) {
1129
1167
  }
1130
1168
  };
1131
1169
  // why: Its hooks take `AgentToolInput`, which the input schema has already checked.
1132
- const asFunction = { ...tool, type: 'function', handler };
1170
+ const outputSchema = agentOutputSchema(tool.outputSchema, args.tools.structuredReplies(tool.profile));
1171
+ const asFunction = { ...tool, type: 'function', handler, outputSchema };
1133
1172
  const exec = executeFunction(args.tools, asFunction, args.safeInput, ctx, base, args.snapshot, args.stages, tool, args.beginBody);
1134
1173
  for (;;) {
1135
1174
  const next = await exec.next();
@@ -0,0 +1,28 @@
1
+ import type { JsonSchema } from './schema.js';
2
+ /** The schema with the mark taken off every field: the mark is Theorem's, never a provider's. */
3
+ export declare function withoutModelMarks(schema: JsonSchema): JsonSchema;
4
+ /**
5
+ * Refuses a mark the kernel cannot honour: one that is not `false`, one on the whole output or
6
+ * input, and on an input one that is not on an optional field of an object, which the model,
7
+ * never seeing it, could not fill.
8
+ */
9
+ export declare function assertModelMarks(schema: JsonSchema, where: string, io: 'input' | 'output'): void;
10
+ /**
11
+ * An input schema as the model reads it: the fields marked `exposeToModel: false` left out and
12
+ * the mark taken off. The host fills those fields; the model never sees them.
13
+ */
14
+ export declare function inputSchemaForModel(schema: JsonSchema): JsonSchema;
15
+ /** Where a model's input sets a field the schema keeps from the model, as dotted paths; none when it sets none. */
16
+ export declare function markedFieldsIn(schema: JsonSchema, input: unknown): string[];
17
+ /** An input as the model reads it back: the fields marked `exposeToModel: false` left out. */
18
+ export declare function inputForModel(schema: JsonSchema, input: unknown): unknown;
19
+ /**
20
+ * The output as the model reads it: every field whose schema says `exposeToModel: false` is left
21
+ * out, at any depth. The output itself is not changed.
22
+ */
23
+ export declare function outputForModel(schema: JsonSchema | undefined, output: unknown): unknown;
24
+ /**
25
+ * An agent tool's output schema with `structured` read as any reply schema the called agent can
26
+ * give, so a field one of them marks is kept from the calling model.
27
+ */
28
+ export declare function agentOutputSchema(outputSchema: JsonSchema, structured: readonly JsonSchema[]): JsonSchema;
@@ -0,0 +1,261 @@
1
+ import { TheoremError } from '../../guardrails/error.js';
2
+ /** The keyword on an output field's schema that keeps the field from the model. */
3
+ const MODEL_MARK = 'exposeToModel';
4
+ const SCHEMA_MAPS = ['properties', 'patternProperties', '$defs', 'definitions'];
5
+ const SCHEMA_LISTS = ['allOf', 'anyOf', 'oneOf', 'prefixItems'];
6
+ const SCHEMA_ONE = [
7
+ 'items',
8
+ 'additionalProperties',
9
+ 'additionalItems',
10
+ 'not',
11
+ 'contains',
12
+ 'propertyNames',
13
+ 'if',
14
+ 'then',
15
+ 'else',
16
+ ];
17
+ function isSchema(value) {
18
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
19
+ }
20
+ /** Every schema inside `schema`, itself first, with its JSON Pointer from the root. */
21
+ function* eachSchema(schema, at = '#') {
22
+ if (!isSchema(schema))
23
+ return;
24
+ yield [schema, at];
25
+ for (const key of SCHEMA_MAPS) {
26
+ const map = schema[key];
27
+ if (!isSchema(map))
28
+ continue;
29
+ for (const [name, child] of Object.entries(map))
30
+ yield* eachSchema(child, `${at}/${key}/${name}`);
31
+ }
32
+ for (const key of [...SCHEMA_LISTS, ...SCHEMA_ONE]) {
33
+ const child = schema[key];
34
+ if (Array.isArray(child)) {
35
+ for (const [index, entry] of child.entries())
36
+ yield* eachSchema(entry, `${at}/${key}/${index}`);
37
+ }
38
+ else {
39
+ yield* eachSchema(child, `${at}/${key}`);
40
+ }
41
+ }
42
+ }
43
+ /** Whether any field of the schema carries the mark. */
44
+ function hasModelMark(schema) {
45
+ for (const [node] of eachSchema(schema)) {
46
+ if (Object.hasOwn(node, MODEL_MARK))
47
+ return true;
48
+ }
49
+ return false;
50
+ }
51
+ /** The schema with the mark taken off every field: the mark is Theorem's, never a provider's. */
52
+ export function withoutModelMarks(schema) {
53
+ if (!hasModelMark(schema))
54
+ return schema;
55
+ const copy = structuredClone(schema);
56
+ for (const [node] of eachSchema(copy))
57
+ delete node[MODEL_MARK];
58
+ return copy;
59
+ }
60
+ /** The mark sits on a field of an object: the last step of its pointer is `properties/<name>`. */
61
+ const FIELD_AT = /\/properties\/[^/]+$/;
62
+ /**
63
+ * Refuses a mark the kernel cannot honour: one that is not `false`, one on the whole output or
64
+ * input, and on an input one that is not on an optional field of an object, which the model,
65
+ * never seeing it, could not fill.
66
+ */
67
+ export function assertModelMarks(schema, where, io) {
68
+ const refuse = (at, problem) => {
69
+ throw new TheoremError('config', `${where} at ${at}: ${problem}`); // labels-exempt: developer contract / internal diagnostic — not end-user or model copy (P2)
70
+ };
71
+ for (const [node, at] of eachSchema(schema)) {
72
+ if (!Object.hasOwn(node, MODEL_MARK))
73
+ continue;
74
+ if (node[MODEL_MARK] !== false) {
75
+ // labels-exempt: developer contract — a registration error, not end-user or model copy
76
+ refuse(at, `${MODEL_MARK} takes false only`);
77
+ }
78
+ if (io === 'input' && !FIELD_AT.test(at)) {
79
+ // labels-exempt: developer contract — a registration error, not end-user or model copy
80
+ refuse(at, `on an input, ${MODEL_MARK}: false marks a field of an object`);
81
+ }
82
+ }
83
+ if (io === 'input') {
84
+ for (const [node, at] of eachSchema(schema)) {
85
+ const required = Array.isArray(node.required) ? node.required : [];
86
+ for (const [key, child] of Object.entries(fieldsOf(node))) {
87
+ if (hasOwnMark(child) && required.includes(key)) {
88
+ refuse(`${at}/properties/${key}`,
89
+ // labels-exempt: developer contract — a registration error, not end-user or model copy
90
+ `an input field marked ${MODEL_MARK}: false must be optional; the model cannot fill it`);
91
+ }
92
+ }
93
+ }
94
+ }
95
+ else if (hidden(nodesAt(schema, schema))) {
96
+ refuse('#',
97
+ // labels-exempt: developer contract — a registration error, not end-user or model copy
98
+ `${MODEL_MARK}: false on the whole output hides every field; set exposeToModel: false on the tool instead`);
99
+ }
100
+ }
101
+ function fieldsOf(node) {
102
+ return isSchema(node.properties) ? node.properties : {};
103
+ }
104
+ function hasOwnMark(schema) {
105
+ return isSchema(schema) && schema[MODEL_MARK] === false;
106
+ }
107
+ /**
108
+ * An input schema as the model reads it: the fields marked `exposeToModel: false` left out and
109
+ * the mark taken off. The host fills those fields; the model never sees them.
110
+ */
111
+ export function inputSchemaForModel(schema) {
112
+ if (!hasModelMark(schema))
113
+ return schema;
114
+ const copy = structuredClone(schema);
115
+ for (const [node] of eachSchema(copy)) {
116
+ const fields = fieldsOf(node);
117
+ for (const [key, child] of Object.entries(fields))
118
+ if (hasOwnMark(child))
119
+ delete fields[key];
120
+ }
121
+ return withoutModelMarks(copy);
122
+ }
123
+ /** Where a model's input sets a field the schema keeps from the model, as dotted paths; none when it sets none. */
124
+ export function markedFieldsIn(schema, input) {
125
+ if (!hasModelMark(schema))
126
+ return [];
127
+ const found = [];
128
+ cut(input, nodesAt(schema, schema), (path) => found.push(path));
129
+ return found;
130
+ }
131
+ /** An input as the model reads it back: the fields marked `exposeToModel: false` left out. */
132
+ export function inputForModel(schema, input) {
133
+ return outputForModel(schema, input);
134
+ }
135
+ function resolvePointer(root, ref) {
136
+ if (!ref.startsWith('#'))
137
+ return undefined;
138
+ let node = root;
139
+ for (const raw of ref.slice(1).split('/').slice(1)) {
140
+ const key = decodeURIComponent(raw).replaceAll('~1', '/').replaceAll('~0', '~');
141
+ node =
142
+ isSchema(node) || Array.isArray(node) ? node[key] : undefined;
143
+ }
144
+ return isSchema(node) ? node : undefined;
145
+ }
146
+ /** The schemas that apply to one value: a reference followed, every branch of a combinator opened. */
147
+ function nodesAt(schema, root, seen = new Set()) {
148
+ if (!isSchema(schema) || seen.has(schema))
149
+ return [];
150
+ seen.add(schema);
151
+ const nodes = [{ schema, root }];
152
+ if (typeof schema.$ref === 'string') {
153
+ nodes.push(...nodesAt(resolvePointer(root, schema.$ref), root, seen));
154
+ }
155
+ for (const key of ['allOf', 'anyOf', 'oneOf']) {
156
+ const branches = schema[key];
157
+ if (Array.isArray(branches)) {
158
+ for (const branch of branches)
159
+ nodes.push(...nodesAt(branch, root, seen));
160
+ }
161
+ }
162
+ return nodes;
163
+ }
164
+ /** invariant: A field one branch of a union marks is kept from the model in every branch. */
165
+ function hidden(nodes) {
166
+ return nodes.some((node) => node.schema[MODEL_MARK] === false);
167
+ }
168
+ function childNodes(nodes, pick) {
169
+ return nodes.flatMap((node) => nodesAt(pick(node.schema), node.root));
170
+ }
171
+ function propertyNodes(nodes, key) {
172
+ return childNodes(nodes, (schema) => {
173
+ const props = schema.properties;
174
+ if (isSchema(props) && Object.hasOwn(props, key))
175
+ return props[key];
176
+ const patterns = schema.patternProperties;
177
+ if (isSchema(patterns)) {
178
+ const match = Object.entries(patterns).find(([pattern]) => new RegExp(pattern, 'u').test(key));
179
+ if (match)
180
+ return match[1];
181
+ }
182
+ return schema.additionalProperties;
183
+ });
184
+ }
185
+ function itemNodes(nodes, index) {
186
+ return childNodes(nodes, (schema) => {
187
+ const tuple = Array.isArray(schema.prefixItems)
188
+ ? schema.prefixItems
189
+ : Array.isArray(schema.items)
190
+ ? schema.items
191
+ : undefined;
192
+ if (tuple)
193
+ return index < tuple.length ? tuple[index] : (schema.additionalItems ?? schema.items);
194
+ return schema.items;
195
+ });
196
+ }
197
+ function cut(value, nodes, onHidden, path = '') {
198
+ if (nodes.length === 0)
199
+ return value;
200
+ if (Array.isArray(value)) {
201
+ return value.flatMap((item, index) => {
202
+ const children = itemNodes(nodes, index);
203
+ const at = `${path}[${String(index)}]`;
204
+ if (hidden(children)) {
205
+ onHidden?.(at);
206
+ return [];
207
+ }
208
+ return [cut(item, children, onHidden, at)];
209
+ });
210
+ }
211
+ if (isSchema(value)) {
212
+ const kept = {};
213
+ for (const [key, child] of Object.entries(value)) {
214
+ const children = propertyNodes(nodes, key);
215
+ const at = path ? `${path}.${key}` : key;
216
+ if (hidden(children))
217
+ onHidden?.(at);
218
+ else
219
+ kept[key] = cut(child, children, onHidden, at);
220
+ }
221
+ return kept;
222
+ }
223
+ return value;
224
+ }
225
+ /**
226
+ * The output as the model reads it: every field whose schema says `exposeToModel: false` is left
227
+ * out, at any depth. The output itself is not changed.
228
+ */
229
+ export function outputForModel(schema, output) {
230
+ if (!schema || !hasModelMark(schema))
231
+ return output;
232
+ return cut(output, nodesAt(schema, schema));
233
+ }
234
+ function prefixRefs(schema, base) {
235
+ const copy = structuredClone(schema);
236
+ for (const [node] of eachSchema(copy)) {
237
+ if (typeof node.$ref === 'string' && node.$ref.startsWith('#')) {
238
+ node.$ref = `${base}${node.$ref.slice(1)}`;
239
+ }
240
+ }
241
+ return copy;
242
+ }
243
+ /**
244
+ * An agent tool's output schema with `structured` read as any reply schema the called agent can
245
+ * give, so a field one of them marks is kept from the calling model.
246
+ */
247
+ export function agentOutputSchema(outputSchema, structured) {
248
+ const marked = structured.filter(hasModelMark);
249
+ if (marked.length === 0)
250
+ return outputSchema;
251
+ const defs = Object.fromEntries(marked.map((spec, index) => [`reply${index}`, prefixRefs(spec, `#/$defs/reply${index}`)]));
252
+ const properties = isSchema(outputSchema.properties) ? outputSchema.properties : {};
253
+ return {
254
+ ...outputSchema,
255
+ properties: {
256
+ ...properties,
257
+ structured: { anyOf: marked.map((_, index) => ({ $ref: `#/$defs/reply${index}` })) },
258
+ },
259
+ $defs: { ...(isSchema(outputSchema.$defs) ? outputSchema.$defs : {}), ...defs },
260
+ };
261
+ }
@@ -1,3 +1,4 @@
1
+ import { inputSchemaForModel } from './model-view.js';
1
2
  import { profileToolAllow } from './resolve.js';
2
3
  function projectTool(tools, name) {
3
4
  const tool = tools.get(name);
@@ -47,9 +48,10 @@ function ownToolsOf(tools, profile) {
47
48
  if (projected.length === 0)
48
49
  return undefined;
49
50
  const params = new Set();
50
- for (const tool of projected)
51
+ for (const tool of projected) {
51
52
  if ('inputSchema' in tool)
52
- addParams(tool.inputSchema, params);
53
+ addParams(inputSchemaForModel(tool.inputSchema), params);
54
+ }
53
55
  return { names: projected.map(({ name }) => name), params: [...params] };
54
56
  }
55
57
  export { ownToolsOf, projectTools };
@@ -1,6 +1,7 @@
1
1
  import type { Profile, ProfileId } from '../types.js';
2
2
  import { type ToolBackground } from './background.js';
3
3
  import { type McpSessionCache } from './mcp-sessions.js';
4
+ import { type JsonSchema } from './schema.js';
4
5
  import type { FunctionToolDef, HttpToolDef, McpToolDef, RegisteredTool, ToolDefinitionInput } from './types.js';
5
6
  /** The settings of a tool's definition that are plain values: every check `register` makes without running or converting anything. */
6
7
  declare function assertToolSettings(def: Pick<HttpToolDef, 'name'> & Partial<Pick<HttpToolDef, 'endpoint' | 'auth' | 'mapping' | 'limit' | 'timeoutMs'> & Pick<HttpToolDef, 'maxResponseBytes' | 'imageLimits'> & Pick<McpToolDef, 'session'> & Pick<FunctionToolDef, 'answeredBy'>> & {
@@ -19,6 +20,8 @@ interface ToolRegistry {
19
20
  list(): RegisteredTool[];
20
21
  /** A profile in this scope, for the agent tools that run one. */
21
22
  findProfile(id: ProfileId): Profile | undefined;
23
+ /** The reply schemas a profile in this scope can give, read when an agent tool's call settles. */
24
+ structuredReplies(id: ProfileId): JsonSchema[];
22
25
  /** Also forgets the MCP sessions. */
23
26
  reset(): void;
24
27
  /** Sessions for this scope's MCP servers that require one; never shared across scopes. */
@@ -28,6 +31,6 @@ interface ToolRegistry {
28
31
  * Registration is not synchronized: register a scope's tools before its turns or invokes run.
29
32
  * `findProfile` is the scope's profiles, which an agent tool names; without it none registers.
30
33
  */
31
- declare function createToolRegistry(findProfile?: (id: ProfileId) => Profile | undefined): ToolRegistry;
34
+ declare function createToolRegistry(findProfile?: (id: ProfileId) => Profile | undefined, structuredReplies?: (id: ProfileId) => JsonSchema[]): ToolRegistry;
32
35
  export type { ToolRegistry };
33
36
  export { assertToolSettings, createToolRegistry };
@@ -6,6 +6,7 @@ import { agentToolInputFor, agentToolOutput, agentToolProfile, normalizeAgent }
6
6
  import { assertBackgroundSetting, backgroundField } from './background.js';
7
7
  import { withCallOrder, withModelField } from './call-order.js';
8
8
  import { createMcpSessionCache } from './mcp-sessions.js';
9
+ import { assertModelMarks } from './model-view.js';
9
10
  import { pageAnswerHandler } from './page-answer.js';
10
11
  import { assertFixedEndpointOrigin, jsonSchemaFromZod, validateToolSchema, } from './schema.js';
11
12
  /** Each zod pair's JSON Schemas, as converted and checked: a zod schema is never changed. */
@@ -31,6 +32,8 @@ function checkedSchemas(input, output) {
31
32
  function schemasFromZod(def) {
32
33
  // why: A studio compile registers each tool once for every agent that uses it, again on each edit that settles.
33
34
  const { inputSchema, outputSchema } = checkedSchemas(def.input, def.output);
35
+ assertModelMarks(inputSchema, `Tool "${def.name}" input`, 'input');
36
+ assertModelMarks(outputSchema, `Tool "${def.name}" output`, 'output');
34
37
  const labels = {
35
38
  activity: { input: inputSchema },
36
39
  activityPast: { input: inputSchema, output: outputSchema },
@@ -188,7 +191,7 @@ function normalizeDefinition(def, findProfile, findTool) {
188
191
  * Registration is not synchronized: register a scope's tools before its turns or invokes run.
189
192
  * `findProfile` is the scope's profiles, which an agent tool names; without it none registers.
190
193
  */
191
- function createToolRegistry(findProfile = () => undefined) {
194
+ function createToolRegistry(findProfile = () => undefined, structuredReplies = () => []) {
192
195
  const tools = new Map();
193
196
  const mcpSessions = createMcpSessionCache();
194
197
  const get = (name) => tools.get(name);
@@ -211,6 +214,7 @@ function createToolRegistry(findProfile = () => undefined) {
211
214
  has: (name) => tools.has(name),
212
215
  list: () => [...tools.values()],
213
216
  findProfile,
217
+ structuredReplies,
214
218
  reset: () => {
215
219
  tools.clear();
216
220
  mcpSessions.clear();
@@ -5,6 +5,7 @@ import { type ToolCallBase } from './events.js';
5
5
  import type { HandlerEvents } from './handler-events.js';
6
6
  import { type McpSessionCache } from './mcp-sessions.js';
7
7
  import type { ToolOperationClaim } from './operation.js';
8
+ import { type JsonSchema } from './schema.js';
8
9
  import { type ToolStageSupport } from './stage-run.js';
9
10
  import type { HttpToolDef, McpToolDef, ModelToolResult, ToolAuthConfig, ToolBodyOutcome, ToolContext, ToolFailure, ToolGate } from './types.js';
10
11
  export type AuthResolveResult = {
@@ -65,8 +66,11 @@ export declare function parseToolOutput<T>(schema: {
65
66
  flatten: () => unknown;
66
67
  };
67
68
  };
68
- /** Not repeated as `data`, which `composeToolText` would append a second time. */
69
- export declare function modelResultFromOutput(data: unknown): ModelToolResult;
69
+ /**
70
+ * Not repeated as `data`, which `composeToolText` would append a second time. A field the tool's
71
+ * output schema marks `exposeToModel: false` is left out.
72
+ */
73
+ export declare function modelResultFromOutput(data: unknown, outputSchema: JsonSchema | undefined): ModelToolResult;
70
74
  /** The result with the media a tool returned beside its value, when it returned any. */
71
75
  export declare function withMedia(result: ModelToolResult, parts: InteractionPart[] | undefined): ModelToolResult;
72
76
  /** `sent`: the service refused a request the call already sent, so the call has started. */
@@ -7,6 +7,7 @@ import { mapStrings } from '../engine/tree.js';
7
7
  import { dispatchToolBody, guardToolTarget, messageOf, networkBlocked, networkBlockedEvent, requestChecks, startToolExecution, toolEvent, toolNetworkPolicy, } from './events.js';
8
8
  import { answeredIn, takeLimitPlace } from './http-limit.js';
9
9
  import { createMcpSessionCache, isMcpSessionId, mcpSessionKey, } from './mcp-sessions.js';
10
+ import { outputForModel } from './model-view.js';
10
11
  import { checkPermission, gateDetails } from './permission.js';
11
12
  import { assertFixedEndpointOrigin } from './schema.js';
12
13
  import { runPreToolPipeline } from './stage-run.js';
@@ -250,9 +251,13 @@ export function parseToolOutput(schema, responseData) {
250
251
  }
251
252
  return checked;
252
253
  }
253
- /** Not repeated as `data`, which `composeToolText` would append a second time. */
254
- export function modelResultFromOutput(data) {
255
- return { finding: typeof data === 'string' ? data : JSON.stringify(data) };
254
+ /**
255
+ * Not repeated as `data`, which `composeToolText` would append a second time. A field the tool's
256
+ * output schema marks `exposeToModel: false` is left out.
257
+ */
258
+ export function modelResultFromOutput(data, outputSchema) {
259
+ const seen = outputForModel(outputSchema, data);
260
+ return { finding: typeof seen === 'string' ? seen : JSON.stringify(seen) };
256
261
  }
257
262
  /** The result with the media a tool returned beside its value, when it returned any. */
258
263
  export function withMedia(result, parts) {
@@ -501,7 +506,7 @@ export function failureWithoutSecret(failure, secret) {
501
506
  };
502
507
  }
503
508
  /** An echo endpoint or debug page can repeat the credential; it must never reach the model, trace, or client. */
504
- function withoutSecret(outcome, secret) {
509
+ function withoutSecret(outcome, secret, outputSchema) {
505
510
  if (!secret)
506
511
  return outcome;
507
512
  if (outcome.kind === 'ok') {
@@ -509,7 +514,7 @@ function withoutSecret(outcome, secret) {
509
514
  return {
510
515
  kind: 'ok',
511
516
  outputRaw,
512
- modelResult: withMedia(modelResultFromOutput(outputRaw), outcome.modelResult.parts),
517
+ modelResult: withMedia(modelResultFromOutput(outputRaw, outputSchema), outcome.modelResult.parts),
513
518
  };
514
519
  }
515
520
  if (outcome.kind === 'failed') {
@@ -527,12 +532,12 @@ export function audienceMismatch(audience, url) {
527
532
  * An OAuth token goes only to the resource it was issued for (RFC 8707); any other target gets no
528
533
  * request. `send` gets the URL with any key the tool puts in the query, after the target's checks.
529
534
  */
530
- async function* sendWithCredential(prepared, url, send) {
535
+ async function* sendWithCredential(prepared, outputSchema, url, send) {
531
536
  const mismatch = audienceMismatch(prepared.audience, url);
532
537
  if (mismatch) {
533
538
  return failureOutcome({ code: 'credential_audience_mismatch', kind: 'config', message: mismatch }, true);
534
539
  }
535
- return withoutSecret(yield* send(withCredentialQuery(url, prepared.query)), prepared.secret);
540
+ return withoutSecret(yield* send(withCredentialQuery(url, prepared.query)), prepared.secret, outputSchema);
536
541
  }
537
542
  /**
538
543
  * Order: schema → permission → auth → preTool/host stages → body. `shown` takes the body while it
@@ -563,7 +568,7 @@ export async function* executeHttpTool(tool, rawInput, ctx, base, stages, beginB
563
568
  if (!guarded.ok)
564
569
  return failureOutcome(guarded.failure, true);
565
570
  const handOff = yield* dispatchToolBody(tool, input, ctx, base, beginBody);
566
- return yield* sendWithCredential(prepared, guarded.url, (url) => sendHttpRequest(tool, url, target.body, prepared, ctx, base, stages?.span, shown, handOff));
571
+ return yield* sendWithCredential(prepared, tool.outputSchema, guarded.url, (url) => sendHttpRequest(tool, url, target.body, prepared, ctx, base, stages?.span, shown, handOff));
567
572
  }
568
573
  /** A body that is text, read so far: what a successful call's drafts show. */
569
574
  function isDraftable(response) {
@@ -633,7 +638,7 @@ async function* sendHttpRequest(tool, targetUrl, body, { authHeaders, secret },
633
638
  }
634
639
  return {
635
640
  kind: 'ok',
636
- modelResult: modelResultFromOutput(checked.data),
641
+ modelResult: modelResultFromOutput(checked.data, tool.outputSchema),
637
642
  outputRaw: checked.data,
638
643
  };
639
644
  }
@@ -1089,7 +1094,7 @@ sessions = createMcpSessionCache(), beginBody) {
1089
1094
  if (!('ok' in prepared))
1090
1095
  return prepared;
1091
1096
  const handOff = yield* dispatchToolBody(tool, prepared.input, ctx, base, beginBody);
1092
- return yield* sendWithCredential(prepared, guarded.url, (url) => sendMcpRequest(tool, url, prepared.input, prepared, ctx, base, stages?.span, sessions, handOff));
1097
+ return yield* sendWithCredential(prepared, tool.outputSchema, guarded.url, (url) => sendMcpRequest(tool, url, prepared.input, prepared, ctx, base, stages?.span, sessions, handOff));
1093
1098
  }
1094
1099
  async function* sendMcpRequest(tool, url, input, { authHeaders, secret }, ctx, base, span, sessions, handOff) {
1095
1100
  const checks = requestChecks(span);
@@ -1141,7 +1146,7 @@ async function* sendMcpRequest(tool, url, input, { authHeaders, secret }, ctx, b
1141
1146
  }
1142
1147
  return {
1143
1148
  kind: 'ok',
1144
- modelResult: withMedia(modelResultFromOutput(interpreted.data), interpreted.parts),
1149
+ modelResult: withMedia(modelResultFromOutput(interpreted.data, tool.outputSchema), interpreted.parts),
1145
1150
  outputRaw: interpreted.data,
1146
1151
  };
1147
1152
  }
@@ -1,6 +1,7 @@
1
1
  import { TheoremError } from '../../guardrails/error.js';
2
2
  import { toolPathProblem } from '../system-lines.js';
3
3
  import { isRecord } from '../util/record.js';
4
+ import { inputSchemaForModel } from './model-view.js';
4
5
  /** Callable by the host: registered, and not a provider-run builtin. */
5
6
  function isExecutable(tools, id) {
6
7
  const tool = tools.get(id);
@@ -66,7 +67,7 @@ export function wireForTool(tools, name, modelBackground) {
66
67
  type: 'function',
67
68
  name: tool.name,
68
69
  description: tool.description,
69
- parameters: (modelBackground && tool.askInputSchema) || tool.inputSchema,
70
+ parameters: inputSchemaForModel((modelBackground && tool.askInputSchema) || tool.inputSchema),
70
71
  };
71
72
  }
72
73
  export function buildWire(tools, visible, modelBackground) {
@@ -85,6 +85,7 @@ export declare function runPreToolPipeline(args: {
85
85
  input: {
86
86
  safeParse: (value: unknown) => z.ZodSafeParseResult<unknown>;
87
87
  };
88
+ inputSchema?: Record<string, unknown>;
88
89
  access: ToolAccess;
89
90
  labels?: ToolLabels;
90
91
  after?: boolean;
@@ -102,6 +103,7 @@ export declare function runPostToolStages(args: {
102
103
  input?: unknown;
103
104
  callNotStarted?: boolean;
104
105
  outputRaw?: unknown;
106
+ outputForModel?: unknown;
105
107
  outputModel?: ModelToolResult;
106
108
  activityPast?: string;
107
109
  activityFailed?: string;
@@ -5,6 +5,7 @@ import { jsonObjectSchema } from '../json.js';
5
5
  import { runStage, stageEventFields, } from '../stages.js';
6
6
  import { splitCallOrder, stepCallIds } from './call-order.js';
7
7
  import { toolEvent } from './events.js';
8
+ import { inputForModel } from './model-view.js';
8
9
  import { operationWireValue } from './operation.js';
9
10
  import { gateDetails, isGateResumeGranted } from './permission.js';
10
11
  import { plainToolInput } from './schema.js';
@@ -85,7 +86,8 @@ export async function* runPreToolPipeline(args) {
85
86
  pre.gate = {
86
87
  ...pre.gate,
87
88
  ...gateDetails(tool, parsed.data),
88
- preparedArguments: jsonObjectSchema.parse(operationWireValue(plainToolInput(candidate))),
89
+ // why: The model reads these back as its call; the host's pre_tool fills a marked field again when the call resumes.
90
+ preparedArguments: jsonObjectSchema.parse(operationWireValue(inputForModel(tool.inputSchema ?? {}, plainToolInput(candidate)))),
89
91
  };
90
92
  }
91
93
  yield stageEventFields('pre_tool', {
@@ -1195,10 +1195,9 @@ export interface AgentRunRequest extends RunControls, ModelChoice {
1195
1195
  /** A request to `runTurn`: the shared controls and the turn's input. */
1196
1196
  export interface TurnRequest extends AgentRunRequest {
1197
1197
  /**
1198
- * A session key that OpenRouter uses for routing and caching.
1198
+ * A session key a provider may use to route and cache this session's calls together.
1199
1199
  *
1200
- * @remarks Sticky routing / cache session key for OpenRouter (`session_id`). Not the same as
1201
- * `projectId` or Gemini `previousInteractionId`.
1200
+ * @remarks Not the same as `projectId`.
1202
1201
  */
1203
1202
  sessionId?: string;
1204
1203
  /**
@@ -1307,7 +1306,7 @@ export interface ProviderGenerationConfig {
1307
1306
  maxOutputTokens?: number;
1308
1307
  temperature?: number;
1309
1308
  builtins: BuiltinToolId[];
1310
- /** Forwarded as OpenRouter `session_id`. */
1309
+ /** The turn's `sessionId`, for a provider that routes or caches by it. */
1311
1310
  sessionId?: string;
1312
1311
  }
1313
1312
  /** The transport a provider adapter speaks. */
@@ -176,6 +176,7 @@ export const openRouterOpenAi = extendProtocol(openAi, {
176
176
  ],
177
177
  };
178
178
  replay(messages, at.request?.history ?? []);
179
+ // why: OpenRouter routes and caches the calls of one session_id together.
179
180
  if (at.request?.sessionId)
180
181
  out.session_id = at.request.sessionId;
181
182
  const web = at.builtInTools.includes('webSearch');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theoremjs/agents",
3
- "version": "0.3.5-next.902.g334d23a",
3
+ "version": "0.3.5-next.906.g6f050f4",
4
4
  "description": "A flat TypeScript agent kernel for typed profiles, deterministic turn execution, registered tools, provider adapters, guardrails, and host-injected traces.",
5
5
  "keywords": [
6
6
  "agent",