@theoremjs/agents 0.3.5-next.906.g6f050f4 → 0.3.5-next.911.g193d75c

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 (48) hide show
  1. package/README.md +3 -3
  2. package/esm/mod.d.ts +1 -1
  3. package/esm/mod.js +1 -1
  4. package/esm/src/guardrails/labels.d.ts +1 -1
  5. package/esm/src/guardrails/labels.js +4 -0
  6. package/esm/src/guardrails/sanitize.js +1 -1
  7. package/esm/src/interface/history.js +2 -2
  8. package/esm/src/kernel/auth/types.d.ts +2 -2
  9. package/esm/src/kernel/engine/runner/steps.js +0 -5
  10. package/esm/src/kernel/engine/usage.d.ts +1 -1
  11. package/esm/src/kernel/engine/usage.js +1 -1
  12. package/esm/src/kernel/field-docs.js +2 -2
  13. package/esm/src/kernel/interaction-parts.d.ts +0 -2
  14. package/esm/src/kernel/interaction-parts.js +0 -10
  15. package/esm/src/kernel/mod.d.ts +3 -3
  16. package/esm/src/kernel/mod.js +3 -3
  17. package/esm/src/kernel/registry/profiles.js +2 -1
  18. package/esm/src/kernel/schema.d.ts +2 -12
  19. package/esm/src/kernel/schema.js +3 -9
  20. package/esm/src/kernel/stop.d.ts +0 -4
  21. package/esm/src/kernel/stop.js +0 -50
  22. package/esm/src/kernel/tools/events.js +3 -2
  23. package/esm/src/kernel/tools/execute.js +5 -4
  24. package/esm/src/kernel/tools/remote.d.ts +3 -2
  25. package/esm/src/kernel/tools/remote.js +4 -3
  26. package/esm/src/kernel/tools/schema-issues.d.ts +24 -0
  27. package/esm/src/kernel/tools/schema-issues.js +28 -0
  28. package/esm/src/kernel/tools/stage-run.js +2 -1
  29. package/esm/src/kernel/tools/types.d.ts +10 -8
  30. package/esm/src/kernel/turn-events.d.ts +8 -10
  31. package/esm/src/kernel/types.d.ts +7 -22
  32. package/esm/src/observability/trace-catalog.js +6 -9
  33. package/esm/src/providers/built-in.d.ts +2 -0
  34. package/esm/src/providers/built-in.js +11 -0
  35. package/esm/src/providers/google/interactions/framing.d.ts +2 -1
  36. package/esm/src/providers/google/interactions/framing.js +15 -8
  37. package/esm/src/providers/google/interactions/status.d.ts +3 -0
  38. package/esm/src/providers/google/interactions/status.js +23 -0
  39. package/esm/src/providers/google/interactions/steps.js +1 -1
  40. package/esm/src/providers/mod.d.ts +5 -1
  41. package/esm/src/providers/mod.js +4 -1
  42. package/esm/src/providers/open-ai/finish-reason.d.ts +3 -0
  43. package/esm/src/providers/open-ai/finish-reason.js +27 -0
  44. package/esm/src/providers/open-ai/protocol.js +1 -1
  45. package/esm/src/providers/openrouter/images-protocol.js +1 -1
  46. package/esm/src/providers/openrouter/protocol.d.ts +19 -1
  47. package/esm/src/providers/openrouter/protocol.js +4 -1
  48. package/package.json +1 -1
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Where a schema refused a value, as text. Every issue keeps its whole path.
3
+ *
4
+ * why: zod's `flatten()` keys each issue by the first segment of its path and drops the rest,
5
+ * so a bad key inside `action.save` read as a bad `action`.
6
+ *
7
+ * @module
8
+ */
9
+ /** One schema issue: the place in the value, and what was wrong there. */
10
+ export type SchemaIssue = {
11
+ readonly path: readonly PropertyKey[];
12
+ readonly message: string;
13
+ };
14
+ /** A failure's `details` when a schema refuses a value. */
15
+ export type SchemaIssueDetails = {
16
+ /** Issues on the value itself. */
17
+ formErrors: string[];
18
+ /** Issues by top-level field. A line names the place below that field first: `save.from: …`. */
19
+ fieldErrors: Record<string, string[]>;
20
+ };
21
+ /** A path as dotted text; empty at the root. */
22
+ export declare function issuePath(path: readonly PropertyKey[]): string;
23
+ /** The details of a refused value, keyed like zod's `flatten()` but with no part of a path lost. */
24
+ export declare function schemaIssueDetails(issues: readonly SchemaIssue[]): SchemaIssueDetails;
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Where a schema refused a value, as text. Every issue keeps its whole path.
3
+ *
4
+ * why: zod's `flatten()` keys each issue by the first segment of its path and drops the rest,
5
+ * so a bad key inside `action.save` read as a bad `action`.
6
+ *
7
+ * @module
8
+ */
9
+ /** A path as dotted text; empty at the root. */
10
+ export function issuePath(path) {
11
+ return path.map(String).join('.');
12
+ }
13
+ /** The details of a refused value, keyed like zod's `flatten()` but with no part of a path lost. */
14
+ export function schemaIssueDetails(issues) {
15
+ const formErrors = [];
16
+ const fieldErrors = {};
17
+ for (const { path, message } of issues) {
18
+ const [field, ...below] = path;
19
+ if (field === undefined) {
20
+ formErrors.push(message);
21
+ continue;
22
+ }
23
+ const line = below.length > 0 ? `${issuePath(below)}: ${message}` : message;
24
+ const key = String(field);
25
+ fieldErrors[key] = [...(fieldErrors[key] ?? []), line];
26
+ }
27
+ return { formErrors, fieldErrors };
28
+ }
@@ -9,6 +9,7 @@ import { inputForModel } from './model-view.js';
9
9
  import { operationWireValue } from './operation.js';
10
10
  import { gateDetails, isGateResumeGranted } from './permission.js';
11
11
  import { plainToolInput } from './schema.js';
12
+ import { schemaIssueDetails } from './schema-issues.js';
12
13
  function defaultToolStageSupport(ctx) {
13
14
  return {
14
15
  handlers: [],
@@ -41,7 +42,7 @@ function invalidAfterMutate(error, ctx) {
41
42
  code: 'invalid_input',
42
43
  kind: 'bad_response',
43
44
  message: labelText('tool.input_invalid_after_mutate', {}, ctx.profile.labels),
44
- details: error.flatten(),
45
+ details: schemaIssueDetails(error.issues),
45
46
  },
46
47
  };
47
48
  }
@@ -479,8 +479,8 @@ export interface AgentToolOutput {
479
479
  /** What the called agent cited; the caller's turn cites them too. */
480
480
  sources?: Source[];
481
481
  }
482
- /** A channel of an agent tool's input that the called profile's `inputs` declares. */
483
- export type AgentToolChannel = 'attachments' | 'voice' | 'options';
482
+ /** A channel of an agent tool's input: one the called profile's `inputs` declares, or `speech` on a speech profile. */
483
+ export type AgentToolChannel = 'attachments' | 'voice' | 'options' | 'speech';
484
484
  /**
485
485
  * A tool whose call runs one turn of another registered agent. That agent is a
486
486
  * standalone profile; the tool is how another agent's model calls it. Its input
@@ -512,13 +512,15 @@ export interface AgentToolDef extends ToolBase {
512
512
  */
513
513
  fieldText?: Partial<Record<keyof AgentToolInput, string>>;
514
514
  /**
515
- * Fields the calling model fills on an agent tool that only the host reads. onAgentCall gets them
516
- * as hostInput and turns them into what the agent is sent; the agent never sees them. A name the
517
- * input already has is refused when the tool registers.
515
+ * Fields on an agent tool that only the host reads. The calling model fills them, or the host
516
+ * does when a field is marked exposeToModel: false. onAgentCall gets them as hostInput and turns
517
+ * them into what the agent is sent; the agent never sees them. A name the input already has is
518
+ * refused when the tool registers.
518
519
  *
519
- * @remarks Fields the calling model fills that only the host reads. `onAgentCall` gets them as
520
- * `hostInput` and turns them into the agent's input; they are never sent to the agent. A name the
521
- * input already has is refused, and a call without the hook is a config error.
520
+ * @remarks Fields only the host reads. The calling model fills them, or the host when a field is
521
+ * marked `exposeToModel: false`. `onAgentCall` gets them as `hostInput` and turns them into the
522
+ * agent's input; they are never sent to the agent. A name the input already has is refused, and a
523
+ * call without the hook is a config error.
522
524
  */
523
525
  hostFields?: Record<string, z.ZodType>;
524
526
  /**
@@ -33,8 +33,7 @@ export interface ReasoningOrigin {
33
33
  apiId?: string;
34
34
  }
35
35
  /**
36
- * Signed reasoning a model wrote, kept word for word: Gemini's thought signatures, OpenRouter's
37
- * `reasoning_details`. It goes back only to the protocol that wrote it, or one extended from it;
36
+ * Signed reasoning a model wrote, kept word for word. It goes back only to the protocol that wrote it, or one extended from it;
38
37
  * `data` is that protocol's own shape, checked against its `reasoning` schema.
39
38
  */
40
39
  export interface ReasoningPart {
@@ -105,7 +104,7 @@ export type TurnTokenSide = (typeof TURN_TOKEN_SIDES)[number];
105
104
  export interface TurnCost {
106
105
  /** What the provider charged, in US dollars. */
107
106
  usd: number;
108
- /** What the upstream model vendor charged the provider, when reported (OpenRouter). */
107
+ /** What the upstream model vendor charged the provider, when the provider reports it. */
109
108
  upstreamUsd?: number;
110
109
  /**
111
110
  * Set on a sum (`sumTokens`) when some summed calls reported a cost and
@@ -134,7 +133,7 @@ export interface TurnTokens {
134
133
  output: number;
135
134
  /** Reasoning share of `output`. */
136
135
  thinking?: number;
137
- /** Provider tool-use share of `input` (Google code execution / URL context results). */
136
+ /** Share of `input` that the provider's own tools added, such as their results. */
138
137
  toolUse?: number;
139
138
  /** Share of `input` read from provider cache (cache hit). */
140
139
  cached?: number;
@@ -169,7 +168,7 @@ export interface TurnTokens {
169
168
  }
170
169
  /** A provider response's identity, as the wire sent it. Live sends neither field. */
171
170
  export interface TurnResponse {
172
- /** Provider response id (OpenAI-compatible `id`, Interactions `id`). */
171
+ /** The provider's id for the response. */
173
172
  id?: string;
174
173
  model?: string;
175
174
  }
@@ -180,11 +179,11 @@ export interface Source {
180
179
  title: string;
181
180
  uri: string;
182
181
  type: SourceType;
183
- /** Google Place id when the source is a Maps place / place_citation. */
182
+ /** The place's id, when the source is a place on a map. */
184
183
  placeId?: string;
185
184
  }
186
185
  export declare const sourceSchema: z.ZodType<Source>;
187
- /** Google grounding search metadata. Sources travel as `citation` events. */
186
+ /** Search metadata a provider grounded its answer on. Sources travel as `citation` events. */
188
187
  export interface GroundingEvent {
189
188
  metadata?: Record<string, unknown>;
190
189
  chunks?: unknown[];
@@ -228,7 +227,7 @@ export type ProviderEvidence = (EvidenceBase & {
228
227
  resumable: boolean;
229
228
  }) | (EvidenceBase & {
230
229
  kind: 'provider_step';
231
- /** The provider's own step type, e.g. `google_search_call`. */
230
+ /** The provider's own name for the step type. */
232
231
  step: string;
233
232
  });
234
233
  /** A session the provider ended after warning it would. */
@@ -401,8 +400,7 @@ export interface ToolCallRequest extends ToolEventBase {
401
400
  */
402
401
  arguments: Record<string, unknown>;
403
402
  /**
404
- * On a step's first call: the signed reasoning the model wrote before the step's calls (a Gemini
405
- * thought signature, OpenRouter's `reasoning_details`). It goes back on the assistant message
403
+ * On a step's first call: the signed reasoning the model wrote before the step's calls. It goes back on the assistant message
406
404
  * holding the step's calls, word for word; a host keeping its own history keeps it there.
407
405
  */
408
406
  reasoning?: ReasoningPart[];
@@ -1,13 +1,13 @@
1
1
  import type { ProviderCheckpoint, ProviderContinuationPolicy } from './checkpoint.js';
2
2
  import type { JsonObject } from './json.js';
3
- import type { CacheMode, CacheTtl, CompactionMeter, CompactionOutcome, CompactionTiming, ContextSender, ContinueStopKind, FieldMeta, KeySlot, KeyVault, LiveActivityHandling, LiveEndSensitivity, LiveStartSensitivity, MediaInputKind, ProfileType, SpeechAudioFormat, StreamMode, SummaryMode, ThinkingLevel, ToolLoadTier, TurnStage, TurnStopKind } from './schema.js';
3
+ import type { CompactionMeter, CompactionOutcome, CompactionTiming, ContextSender, ContinueStopKind, FieldMeta, KeySlot, KeyVault, LiveActivityHandling, LiveEndSensitivity, LiveStartSensitivity, MediaInputKind, ProfileType, SpeechAudioFormat, StreamMode, SummaryMode, ThinkingLevel, ToolLoadTier, TurnStage, TurnStopKind } from './schema.js';
4
4
  import type { StageHandler } from './stages.js';
5
5
  import type { ToolBackgroundService } from './tools/background.js';
6
6
  import type { GateDecision } from './tools/gate-answer.js';
7
7
  import type { PageToolExecution, ToolExecutionCoordinator, ToolOperationOutcome } from './tools/operation.js';
8
8
  import type { AgentCall, AgentCallHook, AgentCallRequest, AgentToolDef, AgentToolInput, AgentToolOutput, HostProfileToolsSpec, InvokeToolRequest, InvokeToolResume, InvokeToolStepCall, InvokeToolStepRequest, LiveProfileToolsSpec, ModelToolResult, PageAnswer, ProfileToolsSpec, RegisteredTool, ToolCallEvent, ToolFailure, ToolGate, ToolLoadContext, ToolPolicy, TurnToolSnapshot, WireFunctionTool } from './tools/types.js';
9
9
  import type { AttemptReason, CallDone, CompactionFailure, CompactionResult, CompactionSignal, DoneFields, GroundingEvent, InjectedMessages, InteractionMediaPart, InteractionMediaRefPart, InteractionPart, InteractionTextPart, InvalidField, ModelEvent, ProviderEvidence, RemovedItem, SessionEnded, SessionEvent, SessionEventKind, SessionEventOf, Source, TurnCost, TurnEvent, TurnEventOf, TurnEventType, TurnGroundingCount, TurnHistoryMessage, TurnResponse, TurnTokenSide, TurnTokens } from './turn-events.js';
10
- export type { AgentCall, AgentCallHook, AgentCallRequest, AgentToolDef, AgentToolInput, AgentToolOutput, AttemptReason, CacheMode, CacheTtl, CallDone, CompactionFailure, CompactionMeter, CompactionOutcome, CompactionResult, CompactionSignal, CompactionTiming, ContinueStopKind, DoneFields, FieldMeta, GroundingEvent, HostProfileToolsSpec, InjectedMessages, InteractionMediaPart, InteractionMediaRefPart, InteractionPart, InteractionTextPart, InvalidField, InvokeToolRequest, InvokeToolResume, InvokeToolStepCall, InvokeToolStepRequest, KeySlot, KeyVault, LiveActivityHandling, LiveEndSensitivity, LiveProfileToolsSpec, LiveStartSensitivity, MediaInputKind, ModelEvent, ProfileToolsSpec, ProfileType, ProviderEvidence, RegisteredTool, RemovedItem, SessionEnded, SessionEvent, SessionEventKind, SessionEventOf, Source, SpeechAudioFormat, StreamMode, SummaryMode, ThinkingLevel, ToolCallEvent, ToolFailure, ToolGate, ToolLoadContext, ToolLoadTier, ToolPolicy, TurnCost, TurnEvent, TurnEventOf, TurnEventType, TurnGroundingCount, TurnHistoryMessage, TurnResponse, TurnStage, TurnStopKind, TurnTokenSide, TurnTokens, TurnToolSnapshot, WireFunctionTool, };
10
+ export type { AgentCall, AgentCallHook, AgentCallRequest, AgentToolDef, AgentToolInput, AgentToolOutput, AttemptReason, CallDone, CompactionFailure, CompactionMeter, CompactionOutcome, CompactionResult, CompactionSignal, CompactionTiming, ContinueStopKind, DoneFields, FieldMeta, GroundingEvent, HostProfileToolsSpec, InjectedMessages, InteractionMediaPart, InteractionMediaRefPart, InteractionPart, InteractionTextPart, InvalidField, InvokeToolRequest, InvokeToolResume, InvokeToolStepCall, InvokeToolStepRequest, KeySlot, KeyVault, LiveActivityHandling, LiveEndSensitivity, LiveProfileToolsSpec, LiveStartSensitivity, MediaInputKind, ModelEvent, ProfileToolsSpec, ProfileType, ProviderEvidence, RegisteredTool, RemovedItem, SessionEnded, SessionEvent, SessionEventKind, SessionEventOf, Source, SpeechAudioFormat, StreamMode, SummaryMode, ThinkingLevel, ToolCallEvent, ToolFailure, ToolGate, ToolLoadContext, ToolLoadTier, ToolPolicy, TurnCost, TurnEvent, TurnEventOf, TurnEventType, TurnGroundingCount, TurnHistoryMessage, TurnResponse, TurnStage, TurnStopKind, TurnTokenSide, TurnTokens, TurnToolSnapshot, WireFunctionTool, };
11
11
  /** A host-chosen key naming one model binding in a profile's `models`. */
12
12
  export type ModelId = string;
13
13
  /** The id of a provider-side tool such as web search. */
@@ -67,26 +67,12 @@ export interface ProfileImageSpec {
67
67
  /**
68
68
  * Whether the model may write text alongside its images; with some providers this also sends the
69
69
  * system instruction and history.
70
- *
71
- * @remarks Also request interleaved text with the images (Google: text + image
72
- * `response_format`).
73
70
  */
74
71
  includeText?: boolean;
75
72
  }
76
73
  import type { DecisionModelBinding, ModelBinding } from './protocols/binding.js';
77
74
  import type { ProviderHostOptions } from './protocols/runtime.js';
78
75
  export type { DecisionModelBinding, ModelBinding };
79
- /**
80
- * OpenRouter prompt-cache policy (`models.*.options.cache`).
81
- *
82
- * - `automatic` — top-level `cache_control`; breakpoint advances with the conversation.
83
- * - `system` — explicit breakpoint on the system instruction only.
84
- */
85
- export interface CacheSpec {
86
- mode: CacheMode;
87
- /** Ephemeral TTL. Omit → provider default (typically 5m on Anthropic). */
88
- ttl?: CacheTtl;
89
- }
90
76
  /** What a compaction trigger sees when it decides whether to compact. */
91
77
  export interface CompactionTriggerContext {
92
78
  tokens: number;
@@ -384,21 +370,20 @@ export interface LiveVadSpec {
384
370
  }
385
371
  /**
386
372
  * Context window compression for a live session: once the context reaches the
387
- * trigger, the mechanism shrinks it. Without it, Gemini ends audio sessions at
388
- * 15 minutes and audio-video sessions at 2.
373
+ * trigger, the mechanism shrinks it. Without it, a provider may end a long session.
389
374
  */
390
375
  export interface LiveContextCompressionSpec {
391
376
  /**
392
377
  * The context size, in tokens, that starts trimming.
393
378
  *
394
379
  * @remarks Context tokens, counted before a turn, that start compression. A whole number above 0.
395
- * Omit → provider default (Gemini: 80% of the model's context window).
380
+ * Omit → the provider's default.
396
381
  */
397
382
  triggerTokens?: number;
398
383
  /**
399
384
  * Trims by dropping the oldest turns; the system instruction stays.
400
385
  *
401
- * @remarks Drops the oldest turns; the system instruction stays. Gemini's only mechanism.
386
+ * @remarks Drops the oldest turns; the system instruction stays.
402
387
  */
403
388
  slidingWindow: LiveSlidingWindowSpec;
404
389
  }
@@ -408,7 +393,7 @@ export interface LiveSlidingWindowSpec {
408
393
  * The context size, in tokens, to trim down to; below the trigger.
409
394
  *
410
395
  * @remarks Tokens to keep after compressing. A whole number above 0, below `triggerTokens`. Omit
411
- * → provider default (Gemini: half of `triggerTokens`).
396
+ * → the provider's default.
412
397
  */
413
398
  targetTokens?: number;
414
399
  }
@@ -984,7 +969,7 @@ export interface ImageResponseFormat {
984
969
  type: 'image';
985
970
  mimeType?: string;
986
971
  aspectRatio?: string;
987
- /** Adapters map it to the provider wire key (Google `imageSize`, OpenRouter `resolution`). */
972
+ /** Each protocol sends it under its provider's own name for it. */
988
973
  resolution?: string;
989
974
  quality?: string;
990
975
  background?: string;
@@ -1,9 +1,6 @@
1
1
  // invariant: A key with no entry is still a real attribute: viewers show it under its raw name.
2
2
  import { OPTION_DOCS } from '../kernel/field-docs.js';
3
- import { geminiProvider } from '../providers/gemini/provider.js';
4
- import { localProvider } from '../providers/local/provider.js';
5
- import { openRouterProvider } from '../providers/openrouter/provider.js';
6
- import { typesafeProvider } from '../providers/typesafe/provider.js';
3
+ import { BUILT_IN_PROVIDERS } from '../providers/built-in.js';
7
4
  /** Labels and descriptions for each attribute group. */
8
5
  const TRACE_ATTRIBUTE_GROUPS = {
9
6
  agent: { label: 'Agent', doc: 'Which agent ran, for which conversation, and how it ended.' },
@@ -166,7 +163,7 @@ const OPERATIONS = {
166
163
  chat: { label: 'Chat', doc: 'A model call to a chat-completions endpoint.' },
167
164
  generate_content: {
168
165
  label: 'Generate content',
169
- doc: 'A model call that generates content other than over chat completions: Gemini, speech, or images.',
166
+ doc: 'A model call that generates content other than over chat completions, such as speech or images.',
170
167
  },
171
168
  transcribe: { label: 'Transcribe', doc: 'One transcription call: a voice clip in, text out.' },
172
169
  execute_tool: { label: 'Run tool', doc: 'A tool call theorem ran.' },
@@ -182,7 +179,7 @@ const OUTPUT_TYPES = {
182
179
  image: { label: 'Image', doc: 'The model answers with an image.' },
183
180
  speech: { label: 'Speech', doc: 'The model answers in audio.' },
184
181
  };
185
- const PROVIDERS = Object.fromEntries([geminiProvider, localProvider, openRouterProvider, typesafeProvider].map((provider) => [
182
+ const PROVIDERS = Object.fromEntries(BUILT_IN_PROVIDERS.map((provider) => [
186
183
  provider.traceName ?? provider.id,
187
184
  { label: provider.name, doc: provider.description },
188
185
  ]));
@@ -529,7 +526,7 @@ const SPAN_ATTRIBUTES = {
529
526
  'gen_ai.usage.reasoning.output_tokens': attr('usage', 'Thinking tokens', 'tokens', 'Output tokens spent thinking.'),
530
527
  'gen_ai.usage.cache_read.input_tokens': attr('usage', 'Cached input tokens', 'tokens', 'Input tokens read from the prompt cache.'),
531
528
  'gen_ai.usage.cache_write.input_tokens': attr('usage', 'Cache write tokens', 'tokens', 'Input tokens written to the prompt cache.'),
532
- 'theorem.usage.tool_use.input_tokens': attr('usage', 'Tool-use input tokens', 'tokens', 'Input tokens Google counts for tool use; already inside input tokens.'),
529
+ 'theorem.usage.tool_use.input_tokens': attr('usage', 'Tool-use input tokens', 'tokens', 'Input tokens the provider counts for its own tools; already inside input tokens.'),
533
530
  'theorem.usage.grounding': fields('usage', 'Grounding', 'Grounding tool uses, per tool.', {
534
531
  type: attr('usage', 'Tool', 'id', "The provider's name for the tool."),
535
532
  count: attr('usage', 'Uses', 'number', 'Times the tool ran.'),
@@ -756,7 +753,7 @@ const TRACE_EVENTS = {
756
753
  attributes: {
757
754
  provider: attr('response', 'Provider', 'id', 'Who supplied the evidence.'),
758
755
  sources: attr('response', 'Sources', 'json', 'The sources.'),
759
- search_html: attr('response', 'Search suggestions', 'content', "Google's search widget."),
756
+ search_html: attr('response', 'Search suggestions', 'content', "The provider's search suggestions, as HTML."),
760
757
  raw: attr('response', 'Raw', 'json', "The provider's raw grounding payload."),
761
758
  },
762
759
  },
@@ -830,7 +827,7 @@ const TRACE_EVENTS = {
830
827
  doc: "One case's pass or fail after its trials, by the suite's pass rule. Every case is here, zeros included.",
831
828
  attributes: {
832
829
  case: attr('evaluation', 'Case', 'id', 'The case judged.'),
833
- kind: attr('evaluation', 'Kind', 'text', "Anthropic's split of cases.", CASE_KINDS),
830
+ kind: attr('evaluation', 'Kind', 'text', 'Whether the case asks for something new or guards something that works.', CASE_KINDS),
834
831
  difficulty: attr('evaluation', 'Difficulty', 'number', 'The case’s 1–5 difficulty, when the suite set one.'),
835
832
  passed: attr('evaluation', 'Passed', 'boolean', 'The pass rule was met.'),
836
833
  trials: attr('evaluation', 'Trials', 'number', 'Trials run.'),
@@ -0,0 +1,2 @@
1
+ /** The providers this package ships, for code that lists or labels them without naming one. */
2
+ export declare const BUILT_IN_PROVIDERS: readonly [Readonly<import("./mod.js").ProviderDefinition<import("./gemini/provider.js").GeminiConnection, string>>, Readonly<import("./mod.js").ProviderDefinition<import("./local/provider.js").LocalConnection, string>>, Readonly<import("./mod.js").ProviderDefinition<import("./openrouter/provider.js").OpenRouterConnection, string>>, Readonly<import("./mod.js").ProviderDefinition<import("./typesafe/provider.js").TypesafeConnection, string>>];
@@ -0,0 +1,11 @@
1
+ import { geminiProvider } from './gemini/provider.js';
2
+ import { localProvider } from './local/provider.js';
3
+ import { openRouterProvider } from './openrouter/provider.js';
4
+ import { typesafeProvider } from './typesafe/provider.js';
5
+ /** The providers this package ships, for code that lists or labels them without naming one. */
6
+ export const BUILT_IN_PROVIDERS = [
7
+ geminiProvider,
8
+ localProvider,
9
+ openRouterProvider,
10
+ typesafeProvider,
11
+ ];
@@ -9,7 +9,8 @@ export type InteractionsRequest = ModelRequest & {
9
9
  };
10
10
  export declare function camelToSnake(key: string): string;
11
11
  export declare function toGoogleValue(value: unknown): unknown;
12
- export declare function wirePart(part: InteractionPart): Record<string, string>;
12
+ /** A part in camel case; `toGoogleValue` snake-cases `mimeType` to the documented `mime_type`. */
13
+ export declare function wireInteractionPart(part: InteractionPart): Record<string, string>;
13
14
  export declare function userInputStep(parts: InteractionPart[]): Record<string, unknown>;
14
15
  /** A thought's signature, for the tool call at `call` in the same assistant message. */
15
16
  export declare const thoughtSignature: z.ZodType<{
@@ -1,6 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import { TheoremError } from '../../../guardrails/error.js';
3
- import { historyMessageParts, wireInteractionPart } from '../../../kernel/interaction-parts.js';
3
+ import { historyMessageParts } from '../../../kernel/interaction-parts.js';
4
4
  import { withCarriedToolFiles } from '../../shared/carried-tool-files.js';
5
5
  import { historyToolArguments, historyToolIdentity } from '../../shared/tool-args.js';
6
6
  import { interactionsBuiltinTool } from '../builtins.js';
@@ -27,16 +27,23 @@ export function toGoogleValue(value) {
27
27
  }
28
28
  return value;
29
29
  }
30
- export function wirePart(part) {
31
- return wireInteractionPart(part);
30
+ /** A part in camel case; `toGoogleValue` snake-cases `mimeType` to the documented `mime_type`. */
31
+ export function wireInteractionPart(part) {
32
+ if (part.type === 'text') {
33
+ return { type: 'text', text: part.text };
34
+ }
35
+ if ('uri' in part) {
36
+ return { type: part.type, mimeType: part.mimeType, uri: part.uri };
37
+ }
38
+ return { type: part.type, mimeType: part.mimeType, data: part.data };
32
39
  }
33
40
  const USER_INPUT = 'user_input';
34
41
  export function userInputStep(parts) {
35
- return { type: USER_INPUT, content: parts.map(wirePart) };
42
+ return { type: USER_INPUT, content: parts.map(wireInteractionPart) };
36
43
  }
37
44
  function historyContent(msg) {
38
45
  const parts = historyMessageParts(msg);
39
- return parts.length > 0 ? parts.map(wirePart) : [{ type: 'text', text: '' }];
46
+ return parts.length > 0 ? parts.map(wireInteractionPart) : [{ type: 'text', text: '' }];
40
47
  }
41
48
  // why: Google refuses any other part inside a `function_result`: "The value 'document' is not supported for 'type' at 'input[8].result[2]'. Supported values: 'function', 'image', 'text', 'video'." (live, 13/10/2026, gemini-3.5-flash-lite).
42
49
  const FUNCTION_RESULT_PART_TYPES = new Set([
@@ -49,7 +56,7 @@ function functionResultStep(msg) {
49
56
  return {
50
57
  type: 'function_result',
51
58
  ...historyToolIdentity({ name: msg.name, call_id: msg.tool_call_id }),
52
- result: parts.length > 0 ? parts.map(wirePart) : [{ type: 'text', text: '' }],
59
+ result: parts.length > 0 ? parts.map(wireInteractionPart) : [{ type: 'text', text: '' }],
53
60
  };
54
61
  }
55
62
  /**
@@ -196,7 +203,7 @@ function speechInputStep(parts, style, apiId) {
196
203
  type: USER_INPUT,
197
204
  content: [
198
205
  { type: 'text', text: `Read the following aloud. ${style.trim()}\n` },
199
- ...parts.map(wirePart),
206
+ ...parts.map(wireInteractionPart),
200
207
  ],
201
208
  };
202
209
  }
@@ -205,7 +212,7 @@ function speechInputStep(parts, style, apiId) {
205
212
  return {
206
213
  type: USER_INPUT,
207
214
  content: parts
208
- .map(wirePart)
215
+ .map(wireInteractionPart)
209
216
  .map((part) => (part.type === 'text' ? { ...part, annotations } : part)),
210
217
  };
211
218
  }
@@ -0,0 +1,3 @@
1
+ import type { TurnStop } from '../../../kernel/turn-events.js';
2
+ /** The stop an Interactions `status` reports when the call ends. */
3
+ export declare function turnStopFromInteractionStatus(status: string | null | undefined): TurnStop;
@@ -0,0 +1,23 @@
1
+ /** The stop an Interactions `status` reports when the call ends. */
2
+ export function turnStopFromInteractionStatus(status) {
3
+ const s = (status || '').toLowerCase();
4
+ const native = status || undefined;
5
+ switch (s) {
6
+ case 'completed':
7
+ return { kind: 'completed', native };
8
+ case 'incomplete':
9
+ case 'budget_exceeded':
10
+ return { kind: 'length', native };
11
+ case 'requires_action':
12
+ return { kind: 'tool', native };
13
+ case 'cancelled':
14
+ return { kind: 'cancelled', native };
15
+ case 'failed':
16
+ return { kind: 'provider_error', native };
17
+ case 'in_progress':
18
+ case 'queued':
19
+ return { kind: 'stream_incomplete', native };
20
+ default:
21
+ return { kind: 'stream_incomplete', native };
22
+ }
23
+ }
@@ -1,8 +1,8 @@
1
1
  import { asRecord, nonEmptyString } from '../../../kernel/engine/record.js';
2
2
  import { reportedTokens, usageCount } from '../../../kernel/engine/usage.js';
3
- import { turnStopFromInteractionStatus } from '../../../kernel/stop.js';
4
3
  import { groundingFromSteps } from '../grounding.js';
5
4
  import { byModality, groundingCounts, modalityCounts } from '../usage.js';
5
+ import { turnStopFromInteractionStatus } from './status.js';
6
6
  /* probed 2026-09-23:
7
7
  * Interactions steps and deltas read only the shapes recorded from the wire
8
8
  * (probes 23/09/2026, gemini-3.8-flash, gemini-3.1-pro-preview, image, and TTS
@@ -21,13 +21,17 @@ export { geminiEmbeddings } from './gemini/embeddings-protocol.js';
21
21
  export { geminiInteractions } from './gemini/interactions-protocol.js';
22
22
  export { geminiLive } from './gemini/live-protocol.js';
23
23
  export { geminiProvider } from './gemini/provider.js';
24
+ export { wireInteractionPart } from './google/interactions/framing.js';
25
+ export { turnStopFromInteractionStatus } from './google/interactions/status.js';
24
26
  export { ollamaEmbeddings } from './local/embeddings-protocol.js';
25
27
  export { localProvider } from './local/provider.js';
28
+ export { turnStopFromOpenAiFinishReason } from './open-ai/finish-reason.js';
26
29
  export { openAi } from './open-ai/protocol.js';
27
30
  export { openRouterDecisions } from './openrouter/decisions-protocol.js';
28
31
  export { openRouterEmbeddings } from './openrouter/embeddings-protocol.js';
29
32
  export { openRouterImages } from './openrouter/images-protocol.js';
30
- export { openRouterOpenAi } from './openrouter/protocol.js';
33
+ export type { CacheMode, CacheSpec, CacheTtl } from './openrouter/protocol.js';
34
+ export { CACHE_MODES, CACHE_TTLS, openRouterOpenAi } from './openrouter/protocol.js';
31
35
  export { openRouterProvider } from './openrouter/provider.js';
32
36
  export type { OpenRouterTranscriptionsOptions } from './openrouter/transcriptions-protocol.js';
33
37
  export { openRouterTranscriptions } from './openrouter/transcriptions-protocol.js';
@@ -12,13 +12,16 @@ export { geminiEmbeddings } from './gemini/embeddings-protocol.js';
12
12
  export { geminiInteractions } from './gemini/interactions-protocol.js';
13
13
  export { geminiLive } from './gemini/live-protocol.js';
14
14
  export { geminiProvider } from './gemini/provider.js';
15
+ export { wireInteractionPart } from './google/interactions/framing.js';
16
+ export { turnStopFromInteractionStatus } from './google/interactions/status.js';
15
17
  export { ollamaEmbeddings } from './local/embeddings-protocol.js';
16
18
  export { localProvider } from './local/provider.js';
19
+ export { turnStopFromOpenAiFinishReason } from './open-ai/finish-reason.js';
17
20
  export { openAi } from './open-ai/protocol.js';
18
21
  export { openRouterDecisions } from './openrouter/decisions-protocol.js';
19
22
  export { openRouterEmbeddings } from './openrouter/embeddings-protocol.js';
20
23
  export { openRouterImages } from './openrouter/images-protocol.js';
21
- export { openRouterOpenAi } from './openrouter/protocol.js';
24
+ export { CACHE_MODES, CACHE_TTLS, openRouterOpenAi } from './openrouter/protocol.js';
22
25
  export { openRouterProvider } from './openrouter/provider.js';
23
26
  export { openRouterTranscriptions } from './openrouter/transcriptions-protocol.js';
24
27
  export { systemOne } from './system-one/protocol.js';
@@ -0,0 +1,3 @@
1
+ import type { TurnStop } from '../../kernel/turn-events.js';
2
+ /** OpenAI-compatible normalized `finish_reason` (+ optional `native_finish_reason`). */
3
+ export declare function turnStopFromOpenAiFinishReason(finishReason: string | null | undefined, nativeFinishReason?: string | null): TurnStop;
@@ -0,0 +1,27 @@
1
+ /** OpenAI-compatible normalized `finish_reason` (+ optional `native_finish_reason`). */
2
+ export function turnStopFromOpenAiFinishReason(finishReason, nativeFinishReason) {
3
+ const native = nativeFinishReason?.trim() || finishReason?.trim() || undefined;
4
+ const effective = (nativeFinishReason || finishReason || '').toLowerCase();
5
+ if (!effective)
6
+ return { kind: 'stream_incomplete', native };
7
+ if (effective === 'network_error' || effective.includes('network')) {
8
+ return { kind: 'provider_error', native };
9
+ }
10
+ return openAiFinishKind((finishReason || '').toLowerCase(), effective, native);
11
+ }
12
+ function openAiFinishKind(finish, effective, native) {
13
+ if (finish === 'stop') {
14
+ return /error|fail/.test(effective)
15
+ ? { kind: 'provider_error', native }
16
+ : { kind: 'completed', native };
17
+ }
18
+ // probed 2026-11-04: OpenRouter ends a call the output limit cut off with `tool_calls`; only the upstream's own reason says `length`.
19
+ if (finish === 'length' || effective === 'length')
20
+ return { kind: 'length', native };
21
+ if (finish === 'tool_calls' || finish === 'tool-calls')
22
+ return { kind: 'tool', native };
23
+ if (finish === 'content_filter' || finish === 'content-filter') {
24
+ return { kind: 'filtered', native };
25
+ }
26
+ return { kind: 'provider_error', native };
27
+ }
@@ -2,7 +2,6 @@ import { z } from 'zod';
2
2
  import { kindOfHttpStatus, TheoremError } from '../../guardrails/error.js';
3
3
  import { asRecord } from '../../kernel/engine/record.js';
4
4
  import { defineProtocol, } from '../../kernel/protocols/mod.js';
5
- import { turnStopFromOpenAiFinishReason } from '../../kernel/stop.js';
6
5
  import { base64ToBytes, bytesToBase64 } from '../../kernel/util/base64.js';
7
6
  import { mimeEssence } from '../../kernel/util/mime.js';
8
7
  import { buildChatMessages, httpError, resolveResponseFormat, statedError, wireTools, } from '../openrouter/openai/compat.js';
@@ -13,6 +12,7 @@ import { foldResponse } from '../shared/response-identity.js';
13
12
  import { structuredEvent } from '../shared/structured-output.js';
14
13
  import { toolCallEvents } from '../shared/tool-args.js';
15
14
  import { toolDraftEvents } from '../shared/tool-draft.js';
15
+ import { turnStopFromOpenAiFinishReason } from './finish-reason.js';
16
16
  /** Old-shape events from the shared helpers, as protocol events. */
17
17
  function asProtocolEvents(events) {
18
18
  return events.flatMap((event) => asProtocolEvent(event) ?? []);
@@ -2,7 +2,7 @@ import { z } from 'zod';
2
2
  import { TheoremError } from '../../guardrails/error.js';
3
3
  import { asRecord, nonEmptyString } from '../../kernel/engine/record.js';
4
4
  import { defineProtocol, } from '../../kernel/protocols/mod.js';
5
- import { turnStopFromOpenAiFinishReason } from '../../kernel/stop.js';
5
+ import { turnStopFromOpenAiFinishReason } from '../open-ai/finish-reason.js';
6
6
  import { imagesFromChatMessage, imagesFromImagesBody, OPENROUTER_IMAGE_TOOL } from './image.js';
7
7
  import { buildChatMessages } from './openai/compat.js';
8
8
  import { buildImagesPayload, extractPromptText, imageToolParameters, } from './openai/image-payload.js';
@@ -1,6 +1,24 @@
1
1
  import { type JsonObject } from '../../kernel/json.js';
2
2
  import { type Protocol } from '../../kernel/protocols/mod.js';
3
- import type { CacheSpec } from '../../kernel/types.js';
3
+ /** What is cached: the whole request (`automatic`) or the system instruction only (`system`). */
4
+ export declare const CACHE_MODES: readonly ["automatic", "system"];
5
+ /** One of {@linkcode CACHE_MODES}. */
6
+ export type CacheMode = (typeof CACHE_MODES)[number];
7
+ /** How long OpenRouter's upstream keeps a cached prompt. */
8
+ export declare const CACHE_TTLS: readonly ["5m", "1h"];
9
+ /** One of {@linkcode CACHE_TTLS}. */
10
+ export type CacheTtl = (typeof CACHE_TTLS)[number];
11
+ /**
12
+ * Prompt-cache policy (`models.*.options.cache`).
13
+ *
14
+ * - `automatic` — top-level `cache_control`; breakpoint advances with the conversation.
15
+ * - `system` — explicit breakpoint on the system instruction only.
16
+ */
17
+ export interface CacheSpec {
18
+ mode: CacheMode;
19
+ /** How long the cache lives. Omit → the upstream's default, typically 5 minutes on Anthropic. */
20
+ ttl?: CacheTtl;
21
+ }
4
22
  /** What an `openRouterOpenAi` binding sets in `options`. */
5
23
  export interface OpenRouterOptions {
6
24
  cache?: CacheSpec;
@@ -2,9 +2,12 @@ import { z } from 'zod';
2
2
  import { asRecord } from '../../kernel/engine/record.js';
3
3
  import { jsonObjectSchema } from '../../kernel/json.js';
4
4
  import { extendProtocol } from '../../kernel/protocols/mod.js';
5
- import { CACHE_MODES, CACHE_TTLS } from '../../kernel/schema.js';
6
5
  import { openAi } from '../open-ai/protocol.js';
7
6
  import { collectReasoning } from './openai/reasoning-state.js';
7
+ /** What is cached: the whole request (`automatic`) or the system instruction only (`system`). */
8
+ export const CACHE_MODES = ['automatic', 'system'];
9
+ /** How long OpenRouter's upstream keeps a cached prompt. */
10
+ export const CACHE_TTLS = ['5m', '1h'];
8
11
  // labels-exempt: builder field description, read by the studio and docs
9
12
  const cache = z
10
13
  .strictObject({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theoremjs/agents",
3
- "version": "0.3.5-next.906.g6f050f4",
3
+ "version": "0.3.5-next.911.g193d75c",
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",