@theoremjs/agents 0.3.5-next.950.g9bb8f33 → 0.3.5-next.952.gac12130

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.
@@ -317,7 +317,7 @@ export const FIELD_DOCS = {
317
317
  'registerTool.conflictsWith': 'The built-in tools a builtin tool cannot run beside.',
318
318
  'registerTool.description': 'Tells the model what the tool does (custom tools only).',
319
319
  'registerTool.endpoint': 'The URL the tool calls, with {name} placeholders for mapping.pathParams; the scheme and host must be written out.',
320
- 'registerTool.exposeToModel': 'Whether the model can see and call the tool.',
320
+ 'registerTool.exposeToModel': 'false: the model can call the tool but reads only `Completed.` (the tool.completed_hidden label); the person still sees the media it sends.',
321
321
  'registerTool.fieldText': 'What the calling model reads on a field of an agent tool input, such as text. A field the profile does not take is refused when the tool registers.',
322
322
  'registerTool.handler': 'Your function that runs the tool; it can also yield progress as it goes.',
323
323
  'registerTool.headers': "Headers sent with every request to the tool's own origin, never once a redirect leaves it.",
@@ -378,12 +378,12 @@ export const FIELD_DOCS = {
378
378
  'runTurn.input.repair': 'A reply your host rejected and why, so that the model writes it again.',
379
379
  'runTurn.input.text': "The user's message.",
380
380
  'runTurn.input.voice': "Recorded speech sent with the turn; each must pass the profile's inputs.voice.",
381
+ 'runTurn.lateResults': 'Your function that gives the background tool calls that settled after their turn, as you stored them. A text turn asks it when it opens, after each step whose calls settled, and once the model has answered. The model reads each result as a tool result, and the turn counts it as a remote read when the call was remote. A result lands once: one the conversation already holds is not read again. Each landing is a late_results event, so a history built from events holds it, and the event names the moment it landed. Once the model has answered, a landing runs another step, so the model answers what it read.',
381
382
  'runTurn.links': 'Earlier traces this run follows: a resume, a continue, or a retry.',
382
383
  'runTurn.metadata': 'Your own values, kept on the trace; Theorem does not read them.',
383
384
  'runTurn.model': "The model id the turn or session picks from the profile's models; refused unless the profile sets allowModelSelect.",
384
385
  'runTurn.onAgentCall': 'Runs before each agent tool call, to shape the request to the called agent or to refuse the call.',
385
386
  'runTurn.onEvent': "Reads each of the turn's events as it leaves runTurn, before the caller gets it. A throw goes to the caller as hook_failed, which this function does not read, and the turn goes on.",
386
- 'runTurn.lateResults': 'Your function that gives the background tool calls that settled after their turn, as you stored them. A text turn asks it when it opens, after each step whose calls settled, and once the model has answered. The model reads each result as a tool result, and the turn counts it as a remote read when the call was remote. A result lands once: one the conversation already holds is not read again. Each landing is a late_results event, so a history built from events holds it, and the event names the moment it landed. Once the model has answered, a landing runs another step, so the model answers what it read.',
387
387
  'runTurn.onStage': 'Your function that sees each stage of a text turn or a live session, and can answer with what the stage allows. A throw at pre_tool fails that call. A throw at any other stage is reported as hook_failed, and the turn goes on without its answer.',
388
388
  'runTurn.options': "The value the host's code sets for each option in the profile's identity.options but path; an option or a value the profile does not declare is refused.",
389
389
  'runTurn.pageExecution': 'Host-issued browser dispatch with a claimed operation and correlated result.',
@@ -1,6 +1,9 @@
1
1
  import { z } from 'zod';
2
2
  import type { StepCall } from '../stages.js';
3
- /** `input` with a field the kernel adds for the model. A tool's own field of that name is refused, never replaced. */
3
+ /**
4
+ * `input` with a field the kernel adds for the model. A tool's own field of that name is refused,
5
+ * never replaced. A field the kernel added before stays, so a registered tool registers again.
6
+ */
4
7
  export declare function withModelField<TIn>(name: string, input: z.ZodType<TIn>, field: string, shape: () => z.ZodType): z.ZodType<TIn>;
5
8
  /** `input` with the model's `after` field. */
6
9
  export declare function withCallOrder<TIn>(name: string, input: z.ZodType<TIn>): z.ZodType<TIn>;
@@ -6,14 +6,26 @@ const FIELD = 'after';
6
6
  function orderField() {
7
7
  return z.array(z.string()).optional().describe(labelText('tool.after_field'));
8
8
  }
9
- /** `input` with a field the kernel adds for the model. A tool's own field of that name is refused, never replaced. */
9
+ /** The fields the kernel added for the model, so a registered tool registered again keeps the one it has. */
10
+ const kernelFields = new WeakSet();
11
+ /**
12
+ * `input` with a field the kernel adds for the model. A tool's own field of that name is refused,
13
+ * never replaced. A field the kernel added before stays, so a registered tool registers again.
14
+ */
10
15
  export function withModelField(name, input, field, shape) {
16
+ const added = () => {
17
+ const made = shape();
18
+ kernelFields.add(made);
19
+ return made;
20
+ };
11
21
  const ordered = (schema) => {
12
22
  if (schema instanceof z.ZodObject) {
23
+ if (field in schema.shape && kernelFields.has(schema.shape[field]))
24
+ return schema;
13
25
  if (field in schema.shape) {
14
26
  throw new TheoremError('config', `Tool '${name}' sets ${field}, and its input already has a field of that name`);
15
27
  }
16
- return schema.safeExtend({ [field]: shape() });
28
+ return schema.safeExtend({ [field]: added() });
17
29
  }
18
30
  if (schema instanceof z.ZodDiscriminatedUnion) {
19
31
  const options = schema.options.map(ordered);
@@ -94,15 +94,8 @@ async function* runHandler(handler, input, ctx, shown) {
94
94
  /** What the model is told of a function tool's output: a fixed finding for a hidden tool, a finding plus the output for an awaiting-user result, otherwise the tool's own summary or finding and its data. */
95
95
  export function projectForModel(tool, output, labels) {
96
96
  const media = checkedToolOutputParts(output);
97
- if (tool.exposeToModel === false) {
98
- // why: The model reads none of a hidden tool's output, its media included; what it sent, the person is shown.
99
- const sent = media?.filter((part) => part.type !== 'text' && ('uri' in part || part.sent));
100
- return {
101
- finding: labelText('tool.completed_hidden', {}, labels),
102
- hidden: true,
103
- ...(sent?.length ? { media: sent } : {}),
104
- };
105
- }
97
+ if (tool.exposeToModel === false)
98
+ return hiddenResult(media, labels);
106
99
  const seen = outputForModel(tool.outputSchema, output);
107
100
  if (isAwaitingUserInput(output)) {
108
101
  return {
@@ -121,6 +114,25 @@ export function projectForModel(tool, output, labels) {
121
114
  : modelResultFromOutput(lean, undefined);
122
115
  return withMedia(result, media);
123
116
  }
117
+ /** Whether the person is shown a part of a hidden tool's media: what it sent, and each reference. */
118
+ const isShownPart = (part) => part.type !== 'text' && ('uri' in part || part.sent === true);
119
+ /**
120
+ * What the model is told of a hidden tool's call (`exposeToModel: false`), whatever its type: only
121
+ * `Completed.`. Of its media, the person is shown what it sent and its references.
122
+ * invariant: every tool type hides through here, so a hidden tool reads the same on every transport.
123
+ */
124
+ function hiddenResult(media, labels) {
125
+ const shown = media?.filter(isShownPart);
126
+ return {
127
+ finding: labelText('tool.completed_hidden', {}, labels),
128
+ hidden: true,
129
+ ...(shown?.length ? { media: shown } : {}),
130
+ };
131
+ }
132
+ /** A media hook for a hidden tool: only the entries the person is shown, so no picture is fetched for the model. */
133
+ function shownEntries(media) {
134
+ return (output) => media(output).filter((entry) => !('url' in entry) || entry.sent === true);
135
+ }
124
136
  /** How the call's `post_tool` stage gets the output as the model reads it; nothing when the model reads none. */
125
137
  function forModelOf(tool) {
126
138
  if (tool.exposeToModel === false)
@@ -343,6 +355,10 @@ async function* withNamedMedia(base, result, named, outputRaw) {
343
355
  yield toolEvent(base, { phase: 'warning', warning: fetched.warning });
344
356
  if (fetched.media.length === 0)
345
357
  return result;
358
+ if (result.hidden) {
359
+ const shown = [...(result.media ?? []), ...fetched.media.filter(isShownPart)];
360
+ return { ...result, ...(shown.length ? { media: shown } : {}) };
361
+ }
346
362
  const withAll = withMedia(result, [...(result.media ?? []), ...fetched.media]);
347
363
  if (fetched.urls.length === 0)
348
364
  return withAll;
@@ -746,7 +762,7 @@ export function authorizeToolReplay(args) {
746
762
  function authorizeSavedDisclosure(args, tool, outcome) {
747
763
  const blocked = () => new TheoremError('blocked', labelText('detect.output_blocked', {}, args.profile.labels));
748
764
  const result = outcome.replay.modelResult;
749
- if (tool.type === 'function' &&
765
+ if (tool.type !== 'builtin' &&
750
766
  tool.exposeToModel === false &&
751
767
  result?.finding !== labelText('tool.completed_hidden', {}, args.profile.labels))
752
768
  throw blocked();
@@ -783,6 +799,10 @@ async function* settleBodyOutcome(args) {
783
799
  ...(outcome.denied ? { denied: true } : {}),
784
800
  });
785
801
  }
802
+ // why: a sign-in message is the kernel's, not the tool's result, so a hidden tool still says it.
803
+ const hidden = tool.exposeToModel === false && !outcome.unauthenticated;
804
+ const seen = (result) => (hidden ? hiddenResult(result.media, labels) : result);
805
+ const named = tool.type !== 'function' && tool.media;
786
806
  return yield* settleToolCall({
787
807
  base,
788
808
  toolName: name,
@@ -790,18 +810,18 @@ async function* settleBodyOutcome(args) {
790
810
  input: safeInput,
791
811
  stages,
792
812
  guard,
793
- provisional: { outputRaw: outcome.outputRaw, modelResult: outcome.modelResult },
813
+ provisional: { outputRaw: outcome.outputRaw, modelResult: seen(outcome.modelResult) },
794
814
  sources: tool.sources,
795
815
  ...forModelOf(tool),
796
- ...(tool.type !== 'function' && tool.media
816
+ ...(named
797
817
  ? {
798
- media: (output) => fetchToolMedia(tool.media, output, ctx, tool.imageLimits),
818
+ media: (output) => fetchToolMedia(hidden ? shownEntries(named) : named, output, ctx, tool.imageLimits),
799
819
  }
800
820
  : {}),
801
821
  labels: tool.labels,
802
822
  reproject: makeReproject((v) => parseToolOutput(tool.output, v),
803
823
  // why: A hook's edit replaces the value; the media the tool returned stays.
804
- (data) => withMedia(modelResultFromOutput(data, tool.outputSchema), outcome.modelResult.media), labels),
824
+ (data) => seen(withMedia(modelResultFromOutput(data, tool.outputSchema), outcome.modelResult.media)), labels),
805
825
  });
806
826
  }
807
827
  function turnReadBack({ modelResult }) {
@@ -321,6 +321,7 @@ export function outcomeFromUnauth(authRes, sent = false) {
321
321
  kind: 'ok',
322
322
  modelResult: { finding: authRes.modelMessage },
323
323
  outputRaw: { unauthenticated: true, message: authRes.modelMessage },
324
+ unauthenticated: true,
324
325
  };
325
326
  }
326
327
  if (authRes.failureMessage === undefined) {
@@ -533,7 +534,7 @@ function withoutSecret(outcome, secret, outputSchema) {
533
534
  if (outcome.kind === 'ok') {
534
535
  const outputRaw = omitSecret(outcome.outputRaw, secret);
535
536
  return {
536
- kind: 'ok',
537
+ ...outcome,
537
538
  outputRaw,
538
539
  modelResult: withMedia(modelResultFromOutput(outputRaw, outputSchema), outcome.modelResult.media),
539
540
  };
@@ -209,7 +209,7 @@ export interface ToolHostHooks<TIn = unknown> {
209
209
  * @remarks Runs before the host's `pre_tool` `onStage`.
210
210
  */
211
211
  preTool?: (input: TIn, ctx: ToolContext) => import('../stages.js').StageResult | undefined | Promise<import('../stages.js').StageResult | undefined>;
212
- /** Whether the model can see and call the tool. */
212
+ /** false: the model can call the tool but reads only `Completed.` (the tool.completed_hidden label); the person still sees the media it sends. */
213
213
  exposeToModel?: boolean;
214
214
  /**
215
215
  * Gives the model an after field on this tool: the tools called in the same step that must settle
@@ -553,7 +553,7 @@ export interface AgentToolDef extends ToolBase {
553
553
  * argument. A turn with no background service runs the tool inline.
554
554
  */
555
555
  background?: ToolHostHooks<AgentToolInput>['background'];
556
- /** Whether the model can see and call the tool. */
556
+ /** false: the model can call the tool but reads only `Completed.` (the tool.completed_hidden label); the person still sees the media it sends. */
557
557
  exposeToModel?: boolean;
558
558
  }
559
559
  export interface RegisteredAgentTool extends AgentToolDef, ToolHostHooks<AgentToolInput>, ToolOutputHooks<AgentToolOutput> {
@@ -807,6 +807,8 @@ export type ToolBodyOutcome = {
807
807
  kind: 'ok';
808
808
  outputRaw: unknown;
809
809
  modelResult: ModelToolResult;
810
+ /** The tool is not signed in, and `modelResult` is the kernel's own words saying so; `exposeToModel: false` does not hide them. */
811
+ unauthenticated?: true;
810
812
  } | {
811
813
  kind: 'gated';
812
814
  gate: ToolGate;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theoremjs/agents",
3
- "version": "0.3.5-next.950.g9bb8f33",
3
+ "version": "0.3.5-next.952.gac12130",
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",