@theoremjs/agents 0.3.5-next.904.g8358918 → 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.
@@ -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(
@@ -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,7 +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, outputForModel } from './model-view.js';
21
+ import { agentOutputSchema, markedFieldsIn, outputForModel } from './model-view.js';
22
22
  import { operationBroken, operationWireValue } from './operation.js';
23
23
  import { checkPermission, gateDetails, isGateResumeDenied, isGateResumeGranted, isResumeContinuation, } from './permission.js';
24
24
  import { executeHttpTool, executeMcpTool, failureWithoutSecret, modelResultFromOutput, omitSecret, outcomeFromUnauth, parseToolOutput, refusedCredentialOutcome, resolveToolAuth, withMedia, } from './remote.js';
@@ -137,6 +137,12 @@ export function projectForModel(tool, output, labels) {
137
137
  : modelResultFromOutput(lean, undefined);
138
138
  return { ...result, ...(parts ? { parts } : {}) };
139
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
+ }
140
146
  function loadsT2(tool, ctx) {
141
147
  return profileToolsSpec(ctx.profile)?.t2Loader === tool.name;
142
148
  }
@@ -246,7 +252,7 @@ function completeEvent(base, settled) {
246
252
  * output (the T2 loader), which makes a host `mutate` a warning instead of a replacement.
247
253
  */
248
254
  async function* settleToolCall(args) {
249
- const { base, toolName, callId, input, stages, provisional, guard, reproject, sources } = args;
255
+ const { base, input, stages, provisional, guard, sources } = args;
250
256
  const guarded = yield* 'failure' in provisional
251
257
  ? guard.failure(provisional.failure)
252
258
  : guard.result(provisional.modelResult);
@@ -258,22 +264,14 @@ async function* settleToolCall(args) {
258
264
  let awaiting = !failure && isAwaitingUserInput(outputRaw);
259
265
  let post;
260
266
  if (stages) {
261
- const activityPast = failure ? undefined : pastActivity(args.labels, input, outputRaw);
262
- post = yield* runPostToolStages({
263
- stages,
264
- toolName,
265
- callId,
266
- input,
267
+ let revised;
268
+ ({ post, revised } = yield* postToolOf(args, stages, {
267
269
  callNotStarted,
268
270
  outputRaw,
269
- outputModel: modelResult,
270
- ...(activityPast ? { activityPast } : {}),
271
- activityFailed: failedActivityOf(base),
271
+ modelResult,
272
272
  failure,
273
- awaiting: awaiting || undefined,
274
- mutable: !failure && reproject !== undefined,
275
- });
276
- const revised = yield* reviseAfterStages(post, guard, reproject);
273
+ awaiting,
274
+ }));
277
275
  if (revised) {
278
276
  ({ failure, outputRaw, modelResult, awaiting } = revised);
279
277
  if (post.deny)
@@ -307,6 +305,28 @@ async function* settleToolCall(args) {
307
305
  ...stageSettlement(post),
308
306
  };
309
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
+ }
310
330
  /** The settled output's cited sources, then the pictures its tool names; the result carrying them. */
311
331
  async function* citeAndShow(args) {
312
332
  const { base, sources, images, outputRaw, modelResult } = args;
@@ -619,6 +639,7 @@ agent, beginBody) {
619
639
  },
620
640
  sources: tool.sources,
621
641
  labels: tool.labels,
642
+ ...forModelOf(tool),
622
643
  ...(ownsOutput
623
644
  ? {}
624
645
  : {
@@ -688,6 +709,20 @@ function registeredEligibilityFailure(args) {
688
709
  }
689
710
  return undefined;
690
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
+ }
691
726
  export function authorizeToolReplay(args) {
692
727
  const tool = args.tools.get(args.name);
693
728
  if (!tool || tool.type === 'builtin') {
@@ -748,6 +783,7 @@ async function* settleBodyOutcome(args) {
748
783
  guard,
749
784
  provisional: { outputRaw: outcome.outputRaw, modelResult: outcome.modelResult },
750
785
  sources: tool.sources,
786
+ ...forModelOf(tool),
751
787
  ...(tool.type !== 'function' && tool.images
752
788
  ? {
753
789
  images: (output) => fetchToolImages(tool.images, output, ctx, tool.imageLimits),
@@ -971,7 +1007,7 @@ async function* runRegisteredTool(args, tool) {
971
1007
  resume: ctx.resume,
972
1008
  snapshot,
973
1009
  visible: ctx.turn?.visible,
974
- });
1010
+ }) ?? hostFieldsFailure(args, tool, safeInput);
975
1011
  if (eligibility) {
976
1012
  yield failureEvent(base, eligibility);
977
1013
  return earlyFailure(eligibility);
@@ -2,10 +2,20 @@ import type { JsonSchema } from './schema.js';
2
2
  /** The schema with the mark taken off every field: the mark is Theorem's, never a provider's. */
3
3
  export declare function withoutModelMarks(schema: JsonSchema): JsonSchema;
4
4
  /**
5
- * Refuses a mark the kernel cannot honour: one that is not `false`, one on the whole output,
6
- * and any on an input, which the model fills itself.
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.
7
8
  */
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;
9
19
  /**
10
20
  * The output as the model reads it: every field whose schema says `exposeToModel: false` is left
11
21
  * out, at any depth. The output itself is not changed.
@@ -57,9 +57,12 @@ export function withoutModelMarks(schema) {
57
57
  delete node[MODEL_MARK];
58
58
  return copy;
59
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\/[^/]+$/;
60
62
  /**
61
- * Refuses a mark the kernel cannot honour: one that is not `false`, one on the whole output,
62
- * and any on an input, which the model fills itself.
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.
63
66
  */
64
67
  export function assertModelMarks(schema, where, io) {
65
68
  const refuse = (at, problem) => {
@@ -68,21 +71,67 @@ export function assertModelMarks(schema, where, io) {
68
71
  for (const [node, at] of eachSchema(schema)) {
69
72
  if (!Object.hasOwn(node, MODEL_MARK))
70
73
  continue;
71
- if (io === 'input') {
72
- // labels-exempt: developer contract — a registration error, not end-user or model copy
73
- refuse(at, `${MODEL_MARK} marks output fields only; the model fills every input field`);
74
- }
75
74
  if (node[MODEL_MARK] !== false) {
76
75
  // labels-exempt: developer contract — a registration error, not end-user or model copy
77
76
  refuse(at, `${MODEL_MARK} takes false only`);
78
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
+ }
79
94
  }
80
- if (io === 'output' && hidden(nodesAt(schema, schema))) {
95
+ else if (hidden(nodesAt(schema, schema))) {
81
96
  refuse('#',
82
97
  // labels-exempt: developer contract — a registration error, not end-user or model copy
83
98
  `${MODEL_MARK}: false on the whole output hides every field; set exposeToModel: false on the tool instead`);
84
99
  }
85
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
+ }
86
135
  function resolvePointer(root, ref) {
87
136
  if (!ref.startsWith('#'))
88
137
  return undefined;
@@ -145,21 +194,29 @@ function itemNodes(nodes, index) {
145
194
  return schema.items;
146
195
  });
147
196
  }
148
- function cut(value, nodes) {
197
+ function cut(value, nodes, onHidden, path = '') {
149
198
  if (nodes.length === 0)
150
199
  return value;
151
200
  if (Array.isArray(value)) {
152
201
  return value.flatMap((item, index) => {
153
202
  const children = itemNodes(nodes, index);
154
- return hidden(children) ? [] : [cut(item, children)];
203
+ const at = `${path}[${String(index)}]`;
204
+ if (hidden(children)) {
205
+ onHidden?.(at);
206
+ return [];
207
+ }
208
+ return [cut(item, children, onHidden, at)];
155
209
  });
156
210
  }
157
211
  if (isSchema(value)) {
158
212
  const kept = {};
159
213
  for (const [key, child] of Object.entries(value)) {
160
214
  const children = propertyNodes(nodes, key);
161
- if (!hidden(children))
162
- kept[key] = cut(child, children);
215
+ const at = path ? `${path}.${key}` : key;
216
+ if (hidden(children))
217
+ onHidden?.(at);
218
+ else
219
+ kept[key] = cut(child, children, onHidden, at);
163
220
  }
164
221
  return kept;
165
222
  }
@@ -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 { 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.904.g8358918",
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",