@theoremjs/agents 0.3.4-next.528.g44c76f9 → 0.3.4-next.538.gb556343

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 (54) hide show
  1. package/README.md +4 -7
  2. package/esm/mod.d.ts +0 -1
  3. package/esm/mod.js +0 -1
  4. package/esm/src/cli/commands/fuzz-canary.js +7 -0
  5. package/esm/src/guardrails/corpus/fuzz-inbound.js +11 -2
  6. package/esm/src/guardrails/detectors.js +12 -13
  7. package/esm/src/guardrails/error.d.ts +1 -1
  8. package/esm/src/guardrails/error.js +3 -1
  9. package/esm/src/guardrails/labels.d.ts +2 -2
  10. package/esm/src/guardrails/labels.js +8 -0
  11. package/esm/src/guardrails/network.d.ts +2 -0
  12. package/esm/src/guardrails/network.js +1 -0
  13. package/esm/src/guardrails/theorem-error.d.ts +1 -1
  14. package/esm/src/guardrails/theorem-error.js +4 -0
  15. package/esm/src/host/reply.js +2 -0
  16. package/esm/src/kernel/engine/decision.d.ts +2 -0
  17. package/esm/src/kernel/engine/decision.js +4 -0
  18. package/esm/src/kernel/engine/session/mod.d.ts +1 -1
  19. package/esm/src/kernel/engine/session/mod.js +5 -8
  20. package/esm/src/kernel/engine/tree.d.ts +2 -1
  21. package/esm/src/kernel/engine/tree.js +17 -6
  22. package/esm/src/kernel/protocols/protocol.d.ts +2 -1
  23. package/esm/src/kernel/protocols/runtime.js +8 -1
  24. package/esm/src/kernel/schema.js +1 -2
  25. package/esm/src/kernel/tools/coordinate.js +13 -13
  26. package/esm/src/kernel/tools/events.d.ts +11 -1
  27. package/esm/src/kernel/tools/events.js +22 -2
  28. package/esm/src/kernel/tools/execute.js +5 -3
  29. package/esm/src/kernel/tools/operation.d.ts +5 -1
  30. package/esm/src/kernel/tools/operation.js +8 -0
  31. package/esm/src/kernel/tools/remote.js +15 -6
  32. package/esm/src/observability/spans.d.ts +2 -1
  33. package/esm/src/observability/spans.js +1 -1
  34. package/esm/src/observability/trace-catalog.js +8 -0
  35. package/esm/src/providers/google/interactions/framing.js +1 -1
  36. package/esm/src/providers/google/limits.d.ts +4 -0
  37. package/esm/src/providers/google/limits.js +4 -0
  38. package/esm/src/providers/google/thinking.js +1 -1
  39. package/esm/src/providers/google/urls.d.ts +1 -3
  40. package/esm/src/providers/google/urls.js +1 -3
  41. package/esm/src/providers/open-ai/protocol.js +5 -0
  42. package/package.json +1 -10
  43. package/esm/src/presets/google/speech-voices.d.ts +0 -9
  44. package/esm/src/presets/google/speech-voices.js +0 -38
  45. package/esm/src/presets/google-limits.d.ts +0 -13
  46. package/esm/src/presets/google-limits.js +0 -18
  47. package/esm/src/presets/google.d.ts +0 -119
  48. package/esm/src/presets/google.js +0 -197
  49. package/esm/src/presets/local.d.ts +0 -26
  50. package/esm/src/presets/local.js +0 -30
  51. package/esm/src/presets/mod.d.ts +0 -11
  52. package/esm/src/presets/mod.js +0 -9
  53. package/esm/src/presets/openrouter.d.ts +0 -26
  54. package/esm/src/presets/openrouter.js +0 -31
package/README.md CHANGED
@@ -277,8 +277,8 @@ Theorem scans each piece of text according to where it came from.
277
277
  | `assembled` | `TurnRequest.system`, built by your code per turn | Full scan |
278
278
  | `untrusted` | User text, history, slots, attachments, steering, stage injections | Full injection and sensitive-data scan |
279
279
 
280
- - **Coming in.** `guardrails.detect` replaces prompt-injection phrasing, secrets, and personal data with a placeholder before the model sees them.
281
- - **Going out.** A **canary** is a secret token that Theorem hides in the system prompt. If the token appears in a reply, the prompt leaked, and the `canary_leak` detector stops the reply. The `prompt_leak` detector also stops a reply that repeats 12 words of the prompt. Both are set in `guardrails.detect`, like every other detector. When a check blocks a reply, `guardrails.blockedReply` decides what happens: the model rewrites it (`retry`) or the user gets a refusal (`refuse`).
280
+ - **Coming in.** `guardrails.detect` finds prompt-injection phrasing, secrets, and personal data before the model sees them. By default it flags each one and the text goes in as written. Set a detector to `redact` to replace it with a placeholder, or to `block` to stop the turn.
281
+ - **Going out.** A **canary** is a secret token that Theorem hides in the system prompt. If the token appears in a reply, the prompt leaked, and the `canary_leak` detector reports it. The `prompt_leak` detector also reports a reply that repeats 12 or more words of the prompt. By default, both flag the leak and the reply goes out as written. Set them to `redact` or `block` in `guardrails.detect` to keep the leak from the user. When a check blocks a reply, `guardrails.blockedReply` decides what happens: the model rewrites it (`retry`) or the user gets a refusal (`refuse`).
282
282
  - **Tool results.** Remote content is data. Theorem fences it, scans it, and refuses destructive calls after a remote read when `guardrails.taint.afterRemoteRead` is set. `guardrails.taint.remoteDestination` gates a call that sends to an address only remote content named.
283
283
  - **Network.** HTTP and MCP tools cannot reach private and metadata addresses by default. `guardrails.network.allowedHosts` names the hosts that may resolve to a private address, and `guardrails.network.allowPrivateNetworks` lifts the rule for local development.
284
284
 
@@ -407,9 +407,6 @@ Import from the narrowest entrypoint that has what you need. Each row gives the
407
407
  | `jsr:@theoremjs/agents/interface` / `@theoremjs/agents/interface` | Headless interface projection of a profile (transcript, composer, gates) that UI packages such as `@theoremjs/react` render. |
408
408
  | `jsr:@theoremjs/agents/surface` / `@theoremjs/agents/surface` | Surfaces: the agent sees and works in a client's screen through two tools, `look` and `act`. Secrets reach the agent only as cards. |
409
409
  | `jsr:@theoremjs/agents/cli` / `@theoremjs/agents/cli` | Profile inspection and stress-test CLI (`agents` binary on npm). |
410
- | `jsr:@theoremjs/agents/presets` / `@theoremjs/agents/presets` | Optional convenience packs (`registerGooglePreset`, …). |
411
- | `jsr:@theoremjs/agents/presets/google` / `@theoremjs/agents/presets/google` | Google builtins (search/maps/urlContext/codeExecution) as tool-list entries. |
412
- | `jsr:@theoremjs/agents/presets/google/speech-voices` / `@theoremjs/agents/presets/google/speech-voices` | Gemini TTS voice names for `speech.voice` (`GOOGLE_SPEECH_VOICES`); no registry imports. |
413
410
  | `jsr:@theoremjs/agents/schema` / `@theoremjs/agents/schema` | Profile vocabulary and field catalog (closed unions, field metadata) for host UIs and docs; no Deno APIs. |
414
411
  | `jsr:@theoremjs/agents/evals` / `@theoremjs/agents/evals` | Graders that read trace records and write their results as trace records through the same sink. |
415
412
 
@@ -465,7 +462,7 @@ Named exports from the root barrel (same symbols hosts get from `@theoremjs/agen
465
462
  | Provider vault | `ProviderHostOptions`, `KeyVault`, `KeyCredential`, `CredentialContext`, `CredentialResolver`, `OpenWebSocket`, `plainWebSocket` |
466
463
  | Provider output | `ProviderCheckpoint`, `ProviderWarning`, `ProviderStateRebuilt`, `ProviderContinuationPolicy`, `providerCheckpointSchema`, `providerWarningSchema`, `providerContinuationSchema` |
467
464
  | Provider limits | `ProviderLimits`, `providerLimitsSchema` |
468
- | Re-exported whole | Everything that `@theoremjs/agents/providers` and `@theoremjs/agents/presets` export. Their contracts list each name. |
465
+ | Re-exported whole | Everything that `@theoremjs/agents/providers` exports. Its contract lists each name. |
469
466
 
470
467
  </details>
471
468
 
@@ -492,7 +489,7 @@ live_sessions = "registered provider via runSession; host owns mic, camera, and
492
489
  session_memory_in_kernel = false
493
490
  ```
494
491
 
495
- **Facts and policy.** Provider facts may ship, such as prices, wire shapes, and protocol metadata. For example, see `@theoremjs/agents/presets/google`. Product policy may not ship: prompts, personas, end-user copy, demo apps, and channel behaviour. Every string that a user or a model reads is either supplied by the host or is an overridable default in the kernel labels (`overrideLabels`). Behavioural defaults are typed profile-schema fields. Optional packages, such as `studio/`, are inert extras. If you delete one, no kernel behaviour changes.
492
+ **Facts and policy.** Provider wire shapes and protocol metadata may ship in `@theoremjs/agents/providers`. Product policy may not ship: prompts, personas, end-user copy, demo apps, and channel behaviour. Every string that a user or a model reads is either supplied by the host or is an overridable default in the kernel labels (`overrideLabels`). Behavioural defaults are typed profile-schema fields. Optional packages, such as `studio/`, are inert extras. If you delete one, no kernel behaviour changes.
496
493
 
497
494
  Four properties are invariant. Where a test or a lint checks one, the table names it.
498
495
 
package/esm/mod.d.ts CHANGED
@@ -77,5 +77,4 @@ export { awaitingUserInputSchema, type GateReference, gateReferenceSchema, isAwa
77
77
  export type * from './src/kernel/types.js';
78
78
  export type { OtlpAnyValue, OtlpKeyValue, OtlpSpan, OtlpTraceRequest, ProfileObservabilitySpec, ResolvedObservabilityPolicy, ResolvedScrubSwitch, ResolvedTraceInclude, ResolvedTraceScrub, ScrubSwitch, SpanHandle, SpanLinkInput, SpanOptions, TraceAttributeGroup, TraceAttributeMeta, TraceAttributes, TraceAttributeValue, TraceBytes, TraceClock, TraceContent, TraceEventMeta, TraceIncludeSpec, TraceJson, TraceOptionMeta, TraceRecord, TraceScrubSpec, TraceSink, TraceSpan, TraceSpanEvent, TraceSpanKind, TraceSpanLink, TraceSpanMeta, TraceSpanStatus, TraceSpanType, TraceTree, TraceValueFormat, TraceWriteContext, } from './src/observability/mod.js';
79
79
  export { buildRecord, clearTraceDestinations, contentOf, getTraceDestination, inlineContent, isTraceSink, listTraceDestinationIds, memorySink, noopSink, readTraceparent, registerTraceDestination, requireTraceDestination, resolveObservabilityPolicy, resolveTraceWriter, startTrace, TRACE_ATTRIBUTE_GROUPS, TRACE_FIELDS, TRACE_SPAN_TYPES, TRACE_STATUS, toOtlpJson, traceAttributeMeta, traceBytes, traceContent, traceEventAttributeMeta, traceEventMeta, traceJson, traceRecordSchema, traceSpanMeta, writeTrace, } from './src/observability/mod.js';
80
- export * from './src/presets/mod.js';
81
80
  export * from './src/providers/mod.js';
package/esm/mod.js CHANGED
@@ -46,5 +46,4 @@ export { askUserTool, buildHttpToolTarget, createToolRegistry, credentialPlaceme
46
46
  export { savedToolInvocationSchema, toolInvocationHash, toolOperationOutcomeSchema, } from './src/kernel/tools/operation.js';
47
47
  export { awaitingUserInputSchema, gateReferenceSchema, isAwaitingUserInput, keptReply, reasoningPartSchema, TURN_EVENT_SCHEMAS, toolGateSchema, turnDoneOf, turnEventSchema, turnHistoryMessageSchema, turnToolSnapshotSchema, } from './src/kernel/turn-events.js';
48
48
  export { buildRecord, clearTraceDestinations, contentOf, getTraceDestination, inlineContent, isTraceSink, listTraceDestinationIds, memorySink, noopSink, readTraceparent, registerTraceDestination, requireTraceDestination, resolveObservabilityPolicy, resolveTraceWriter, startTrace, TRACE_ATTRIBUTE_GROUPS, TRACE_FIELDS, TRACE_SPAN_TYPES, TRACE_STATUS, toOtlpJson, traceAttributeMeta, traceBytes, traceContent, traceEventAttributeMeta, traceEventMeta, traceJson, traceRecordSchema, traceSpanMeta, writeTrace, } from './src/observability/mod.js';
49
- export * from './src/presets/mod.js';
50
49
  export * from './src/providers/mod.js';
@@ -37,6 +37,13 @@ function registerFuzzCanaryProfile() {
37
37
  defaultModel: 'fuzz-model',
38
38
  tools: { allow: [] },
39
39
  inputs: { text: true },
40
+ // why: The fuzz measures what a profile that stops its leaks lets through; the defaults only flag them.
41
+ guardrails: {
42
+ detect: {
43
+ canary_leak: { action: 'block', at: { thought: 'redact' } },
44
+ prompt_leak: { action: 'block', at: { thought: 'redact' } },
45
+ },
46
+ },
40
47
  });
41
48
  }
42
49
  function resolveFuzzGeneration(canary) {
@@ -2,12 +2,20 @@
2
2
  import { clearProfiles, getProfile, getProvider, registerProfile, registerProvider, } from '../../kernel/default-scope.js';
3
3
  import { openRouterProvider } from '../../providers/openrouter/provider.js';
4
4
  import { detectAt } from '../detect-at.js';
5
- import { DETECT_DEFAULTS } from '../detectors.js';
5
+ import { resolveDetect } from '../detectors.js';
6
6
  import { injectionSpans } from '../injection.js';
7
7
  import { sanitizeTurnRequest } from '../sanitize.js';
8
8
  import { sensitiveSpans } from '../sensitive.js';
9
9
  import { inboundFuzzPayloads } from './inbound-payloads.js';
10
10
  const FUZZ_PROFILE_ID = '__fuzz__';
11
+ // why: The defaults only flag, so the fuzz measures what a profile that takes data and injection out lets through.
12
+ const FUZZ_DETECT = {
13
+ ids: 'redact',
14
+ financial: 'redact',
15
+ network: 'redact',
16
+ credentials: 'redact',
17
+ injection: 'redact',
18
+ };
11
19
  function registerFuzzProfile() {
12
20
  if (!getProvider('openrouter'))
13
21
  registerProvider(openRouterProvider);
@@ -31,12 +39,13 @@ function registerFuzzProfile() {
31
39
  defaultModel: 'fuzz-model',
32
40
  tools: { allow: [] },
33
41
  inputs: { text: true },
42
+ guardrails: { detect: FUZZ_DETECT },
34
43
  });
35
44
  }
36
45
  function testDetectAt(payloads) {
37
46
  const results = [];
38
47
  for (const p of payloads) {
39
- const output = detectAt(p.text, 'user', DETECT_DEFAULTS).text ?? '';
48
+ const output = detectAt(p.text, 'user', resolveDetect(FUZZ_DETECT)).text ?? '';
40
49
  results.push({
41
50
  payload: p,
42
51
  channel: 'detectAt',
@@ -52,13 +52,13 @@ const DETECTOR_GROUP_META = {
52
52
  const TOOL_ARGUMENT_BOUNDARIES = TOOL_KINDS.map((kind) => toolBoundary('tool_arguments', kind));
53
53
  const TOOL_SHOWN_BOUNDARIES = TOOL_KINDS.map((kind) => toolBoundary('tool_shown', kind));
54
54
  /**
55
- * Text on its way to the model is redacted, a tool call takes `toTool`, and what the model writes
55
+ * Text on its way to the model is flagged, a tool call takes `toTool`, and what the model writes
56
56
  * or a tool shows the person is not read.
57
57
  */
58
58
  function everywhere(toTool) {
59
59
  return {
60
- ...recordOf(INBOUND_BOUNDARIES, () => 'redact'),
61
- ...recordOf(TOOL_BOUNDARIES, () => 'redact'),
60
+ ...recordOf(INBOUND_BOUNDARIES, () => 'flag'),
61
+ ...recordOf(TOOL_BOUNDARIES, () => 'flag'),
62
62
  ...recordOf(TOOL_ARGUMENT_BOUNDARIES, () => toTool),
63
63
  ...recordOf(TOOL_SHOWN_BOUNDARIES, () => 'ignore'),
64
64
  ...recordOf(OUTBOUND_BOUNDARIES, () => 'ignore'),
@@ -113,14 +113,13 @@ const DETECTOR_META = {
113
113
  label: 'Credentials',
114
114
  doc: 'API keys, tokens, passwords, and private keys.',
115
115
  group: 'data',
116
- // why: A key the model was handed (in its instructions or a tool's output) is a key the person
117
- // reading the reply should not get, nor one a tool returned; the rest still shows. A thought and
118
- // a Live reply stay unread, so neither holds its stream nor turns transcription on for every turn.
116
+ // why: A thought and a Live reply stay unread, so neither holds its stream nor turns
117
+ // transcription on for every turn.
119
118
  defaults: {
120
119
  ...everywhere('flag'),
121
- ...recordOf(TOOL_SHOWN_BOUNDARIES, () => 'redact'),
122
- reply: 'redact',
123
- reply_structured: 'redact',
120
+ ...recordOf(TOOL_SHOWN_BOUNDARIES, () => 'flag'),
121
+ reply: 'flag',
122
+ reply_structured: 'flag',
124
123
  },
125
124
  patterns: true,
126
125
  },
@@ -143,26 +142,26 @@ const DETECTOR_META = {
143
142
  label: 'Canary leak',
144
143
  doc: 'The canary token, plain or encoded. Planted only above Ignore.',
145
144
  group: 'setup',
146
- defaults: leaving('block', 'block', 'redact'),
145
+ defaults: leaving('flag', 'flag', 'flag'),
147
146
  },
148
147
  prompt_leak: {
149
148
  label: 'Prompt leak',
150
149
  doc: 'Private system-instruction text, plain or disguised.',
151
150
  group: 'setup',
152
- defaults: leaving('flag', 'block', 'redact'),
151
+ defaults: leaving('flag', 'flag', 'flag'),
153
152
  },
154
153
  marker_leak: {
155
154
  label: 'Marker leak',
156
155
  doc: "The kernel's data markers and canary note.",
157
156
  group: 'setup',
158
- defaults: shown('block', 'redact'),
157
+ defaults: shown('flag', 'flag'),
159
158
  },
160
159
  ungiven_images: {
161
160
  label: 'Ungiven images',
162
161
  short: 'Images',
163
162
  doc: 'An image at an address not given. Loads with no click.',
164
163
  group: 'addresses',
165
- defaults: shown('block', 'redact'),
164
+ defaults: shown('flag', 'flag'),
166
165
  allow: 'urls',
167
166
  },
168
167
  ungiven_links: {
@@ -10,7 +10,7 @@ declare function isTimeoutError(err: unknown): boolean;
10
10
  declare function throwIfAborted(signal?: AbortSignal): void;
11
11
  /** Anything that is not a `TheoremError` or an abort escaped every boundary that names kinds: a THEOREM bug. */
12
12
  declare function errorKind(err: unknown): ErrorKind;
13
- /** The error kind for an HTTP status: 401, 402 and 403 are `auth`; 408, 504 and 524 `timeout`; 429 `rate_limit`; 503 and 529 (overloaded) `busy`; 500 and above `unavailable`; the rest `unsupported`. */
13
+ /** The error kind for an HTTP status: 401, 402 and 403 are `auth`; 408, 504 and 524 `timeout`; 409 `conflict`; 429 `rate_limit`; 503 and 529 (overloaded) `busy`; 500 and above `unavailable`; the rest `unsupported`. */
14
14
  declare function kindOfHttpStatus(status: number): ErrorKind;
15
15
  /** The named reasons an error carries, one line each, in the profile's wording. */
16
16
  declare function errorCopyText(copy: ErrorCopies, labels?: LabelOverrides): string;
@@ -32,12 +32,14 @@ function errorKind(err) {
32
32
  return 'cancelled';
33
33
  return 'internal';
34
34
  }
35
- /** The error kind for an HTTP status: 401, 402 and 403 are `auth`; 408, 504 and 524 `timeout`; 429 `rate_limit`; 503 and 529 (overloaded) `busy`; 500 and above `unavailable`; the rest `unsupported`. */
35
+ /** The error kind for an HTTP status: 401, 402 and 403 are `auth`; 408, 504 and 524 `timeout`; 409 `conflict`; 429 `rate_limit`; 503 and 529 (overloaded) `busy`; 500 and above `unavailable`; the rest `unsupported`. */
36
36
  function kindOfHttpStatus(status) {
37
37
  if (status === 401 || status === 402 || status === 403)
38
38
  return 'auth';
39
39
  if (status === 408 || status === 504 || status === 524)
40
40
  return 'timeout';
41
+ if (status === 409)
42
+ return 'conflict';
41
43
  if (status === 429)
42
44
  return 'rate_limit';
43
45
  if (status === 503 || status === 529)
@@ -1,7 +1,7 @@
1
1
  /** Values that fill a label template's `{param}` placeholders. */
2
2
  export type LabelParams = Record<string, string | number>;
3
3
  /** Keys are stable API. */
4
- export declare const LABEL_KEYS: readonly ["provider.decision_failed", "provider.decision_unavailable", "provider.decision_model_missing", "provider.decision_ended", "provider.decision_images_off", "provider.decision_box_model", "provider.budget_exhausted", "provider.adapter_version", "provider.adapter_methods", "provider.adapter_schemas", "provider.fallback_slot", "provider.model_fallback_slot", "provider.host_model", "provider.turn_profile", "provider.model_binding_missing", "provider.session_closed", "provider.settled_call", "provider.session_unavailable", "provider.live_input", "provider.tool_cancel_missing", "provider.kernel_gate", "provider.event_invalid", "provider.response_identity", "provider.credential_resolution", "provider.credential_shape", "provider.stored_continuation", "provider.continuation_mismatch", "provider.continuation_contract", "provider.stateless_history", "provider.events_after_completion", "provider.duplicate_call", "provider.tool_cancel_live", "provider.complete_unavailable", "provider.parallel_tools", "provider.binding_identity", "provider.profile_type", "provider.event_type", "provider.feature", "provider.input_kind", "provider.output_kind", "provider.builtin", "provider.credential_missing", "provider.profile_configuration", "continue.instruction", "canary.bind_note", "user_data.note", "context.note", "taint.blocked", "taint.reason_steered", "taint.reason_tainted", "taint.destination_blocked", "taint.destination_confirm", "advisory.notice_elevated", "advisory.notice_high", "advisory.guidance", "attachments.too_many_files", "attachments.too_many_of_kind", "attachments.file_too_large", "attachments.turn_too_large", "attachments.not_accepted", "attachments.mime_not_allowed", "attachments.limits_unconfigured", "quota.exhausted", "quota.busy", "error.config", "error.request", "error.input", "error.action", "error.auth", "error.rate_limit", "error.busy", "error.unsupported", "error.unavailable", "error.bad_response", "error.network", "error.timeout", "error.safety", "error.blocked", "error.declined", "error.failed", "error.cancelled", "error.internal", "repair.default_guidance", "repair.items_guidance", "repair.prompt_header", "repair.prompt_intro", "repair.prompt_instructions", "repair.history_heading", "repair.section_previous_output", "repair.section_validator_rejection", "repair.section_repair_guidance", "repair.section_instructions", "structured.answer_tool", "structured.answer_missing", "compaction.request", "compaction.tool_call", "compaction.tool_result", "decision.box_image", "detect.blocked", "detect.call_blocked", "detect.output_blocked", "detect.shown_blocked", "detect.hint.ids", "detect.hint.financial", "detect.hint.network", "detect.hint.credentials", "detect.hint.injection", "detect.hint.tool_instructions", "detect.hint.canary_leak", "detect.hint.prompt_leak", "detect.hint.marker_leak", "detect.hint.ungiven_images", "detect.hint.ungiven_links", "detect.hint.tool_leak", "detect.hint.own", "egress.default_repair_guidance", "egress.refusal", "egress.refusal_cut", "egress.rejection", "egress.rejection_found", "egress.hint_unscannable", "egress.hint_provider_tool_leak", "thought.omitted_image", "thought.omitted_link", "thought.omitted_instructions", "session.abandon_gated", "session.tool_denied", "session.tool_aborted", "session.sign_in", "sign_in.link", "sign_in.pending", "sign_in.done", "sign_in.declined", "sign_in.expired", "sign_in.out_of_scope", "session.gate_expired", "session.provider_state_unowned", "session.conversation_unknown", "session.turn_ended", "session.gate_pending", "session.part_skipped", "live.session_ended", "voice.unsupported", "voice.permission", "voice.unavailable", "voice.failed", "voice.empty", "stop.cancelled", "stop.interrupted", "stop.length", "stop.filtered", "stop.provider_error", "stop.stream_incomplete", "stop.step_limit", "composer.model", "composer.effort", "tool.awaiting_user", "tool.completed_hidden", "tool.t2_loader_needs_snapshot", "tool.t2_loader_shape", "tool.t2_loader_output_invalid", "tool.execution_uncertain", "tool.input_invalid", "tool.input_invalid_after_mutate", "tool.output_invalid_after_mutate", "tool.handler_no_output", "tool.did_not_run", "tool.page_no_answer", "tool.page_timed_out", "tool.output_invalid", "tool.not_loaded_t2", "tool.wait_unknown", "tool.wait_cycle", "tool.not_visible", "tool.builtin_not_enabled", "tool.provider_native", "tool.not_registered", "tool.builtin_needs_snapshot", "tool.not_allowed", "tool.not_eligible", "tool.unsupported_type", "tool.agent_call_limit", "tool.agent_failed", "tool.activity_failed", "protocol.not_served", "protocol.profile_type", "protocol.options", "protocol.option_clash", "protocol.base_options", "protocol.id_clash", "protocol.ws_headers", "protocol.builtin_unwritten", "protocol.provider_missing", "protocol.connection", "protocol.part_schema", "protocol.part_invalid", "protocol.key_invalid", "protocol.no_key", "protocol.reply_shape", "protocol.endpoint_url", "protocol.endpoint_host", "protocol.http", "protocol.no_operation", "protocol.definition", "protocol.provider_id_clash", "protocol.history_needed"];
4
+ export declare const LABEL_KEYS: readonly ["provider.decision_failed", "provider.decision_unavailable", "provider.decision_model_missing", "provider.decision_ended", "provider.decision_images_off", "provider.decision_box_model", "provider.budget_exhausted", "provider.adapter_version", "provider.adapter_methods", "provider.adapter_schemas", "provider.fallback_slot", "provider.model_fallback_slot", "provider.host_model", "provider.turn_profile", "provider.model_binding_missing", "provider.session_closed", "provider.settled_call", "provider.session_unavailable", "provider.live_input", "provider.tool_cancel_missing", "provider.kernel_gate", "provider.event_invalid", "provider.response_identity", "provider.credential_resolution", "provider.credential_shape", "provider.stored_continuation", "provider.continuation_mismatch", "provider.continuation_contract", "provider.stateless_history", "provider.events_after_completion", "provider.duplicate_call", "provider.tool_cancel_live", "provider.complete_unavailable", "provider.parallel_tools", "provider.binding_identity", "provider.profile_type", "provider.event_type", "provider.feature", "provider.input_kind", "provider.output_kind", "provider.builtin", "provider.credential_missing", "provider.profile_configuration", "continue.instruction", "canary.bind_note", "user_data.note", "context.note", "taint.blocked", "taint.reason_steered", "taint.reason_tainted", "taint.destination_blocked", "taint.destination_confirm", "advisory.notice_elevated", "advisory.notice_high", "advisory.guidance", "attachments.too_many_files", "attachments.too_many_of_kind", "attachments.file_too_large", "attachments.turn_too_large", "attachments.not_accepted", "attachments.mime_not_allowed", "attachments.limits_unconfigured", "quota.exhausted", "quota.busy", "error.config", "error.request", "error.conflict", "error.not_found", "error.input", "error.action", "error.auth", "error.rate_limit", "error.busy", "error.unsupported", "error.unavailable", "error.bad_response", "error.network", "error.timeout", "error.safety", "error.blocked", "error.declined", "error.failed", "error.cancelled", "error.internal", "repair.default_guidance", "repair.items_guidance", "repair.prompt_header", "repair.prompt_intro", "repair.prompt_instructions", "repair.history_heading", "repair.section_previous_output", "repair.section_validator_rejection", "repair.section_repair_guidance", "repair.section_instructions", "structured.answer_tool", "structured.answer_missing", "compaction.request", "compaction.tool_call", "compaction.tool_result", "decision.box_image", "detect.blocked", "detect.call_blocked", "detect.output_blocked", "detect.shown_blocked", "detect.hint.ids", "detect.hint.financial", "detect.hint.network", "detect.hint.credentials", "detect.hint.injection", "detect.hint.tool_instructions", "detect.hint.canary_leak", "detect.hint.prompt_leak", "detect.hint.marker_leak", "detect.hint.ungiven_images", "detect.hint.ungiven_links", "detect.hint.tool_leak", "detect.hint.own", "egress.default_repair_guidance", "egress.refusal", "egress.refusal_cut", "egress.rejection", "egress.rejection_found", "egress.hint_unscannable", "egress.hint_provider_tool_leak", "thought.omitted_image", "thought.omitted_link", "thought.omitted_instructions", "session.abandon_gated", "session.tool_denied", "session.tool_aborted", "session.sign_in", "sign_in.link", "sign_in.pending", "sign_in.done", "sign_in.declined", "sign_in.expired", "sign_in.out_of_scope", "session.gate_expired", "session.provider_state_unowned", "session.conversation_unknown", "session.turn_ended", "session.gate_pending", "session.part_skipped", "live.session_ended", "voice.unsupported", "voice.permission", "voice.unavailable", "voice.failed", "voice.empty", "stop.cancelled", "stop.interrupted", "stop.length", "stop.filtered", "stop.provider_error", "stop.stream_incomplete", "stop.step_limit", "composer.model", "composer.effort", "tool.awaiting_user", "tool.completed_hidden", "tool.t2_loader_needs_snapshot", "tool.t2_loader_shape", "tool.t2_loader_output_invalid", "tool.execution_uncertain", "tool.input_invalid", "tool.input_invalid_after_mutate", "tool.output_invalid_after_mutate", "tool.handler_no_output", "tool.did_not_run", "tool.page_no_answer", "tool.page_timed_out", "tool.output_invalid", "tool.not_loaded_t2", "tool.wait_unknown", "tool.wait_cycle", "tool.not_visible", "tool.builtin_not_enabled", "tool.provider_native", "tool.not_registered", "tool.builtin_needs_snapshot", "tool.not_allowed", "tool.not_eligible", "tool.unsupported_type", "tool.agent_call_limit", "tool.agent_failed", "tool.activity_failed", "protocol.not_served", "protocol.profile_type", "protocol.options", "protocol.option_clash", "protocol.base_options", "protocol.id_clash", "protocol.ws_headers", "protocol.builtin_unwritten", "protocol.provider_missing", "protocol.connection", "protocol.part_schema", "protocol.part_invalid", "protocol.key_invalid", "protocol.no_key", "protocol.reply_shape", "protocol.endpoint_url", "protocol.endpoint_host", "protocol.http", "protocol.no_operation", "protocol.definition", "protocol.provider_id_clash", "protocol.history_needed"];
5
5
  /** One of {@linkcode LABEL_KEYS}. */
6
6
  export type LabelKey = (typeof LABEL_KEYS)[number];
7
7
  /**
@@ -10,7 +10,7 @@ export type LabelKey = (typeof LABEL_KEYS)[number];
10
10
  * puts into history. Only these overrides travel to the browser; the rest
11
11
  * (repair prompts, canary, taint, egress) stay on the host.
12
12
  */
13
- export declare const CLIENT_LABEL_KEYS: readonly ["attachments.too_many_files", "attachments.too_many_of_kind", "attachments.file_too_large", "attachments.turn_too_large", "attachments.not_accepted", "attachments.mime_not_allowed", "attachments.limits_unconfigured", "detect.blocked", "error.config", "error.request", "error.input", "error.action", "error.auth", "error.rate_limit", "error.busy", "error.unsupported", "error.unavailable", "error.bad_response", "error.network", "error.timeout", "error.safety", "error.blocked", "error.declined", "error.failed", "error.cancelled", "error.internal", "session.abandon_gated", "session.tool_denied", "session.sign_in", "session.gate_expired", "session.turn_ended", "session.gate_pending", "session.part_skipped", "live.session_ended", "tool.awaiting_user", "tool.completed_hidden", "tool.execution_uncertain", "voice.unsupported", "voice.permission", "voice.unavailable", "voice.failed", "voice.empty", "stop.cancelled", "stop.interrupted", "stop.length", "stop.filtered", "stop.provider_error", "stop.stream_incomplete", "stop.step_limit", "composer.model", "composer.effort"];
13
+ export declare const CLIENT_LABEL_KEYS: readonly ["attachments.too_many_files", "attachments.too_many_of_kind", "attachments.file_too_large", "attachments.turn_too_large", "attachments.not_accepted", "attachments.mime_not_allowed", "attachments.limits_unconfigured", "detect.blocked", "error.config", "error.request", "error.conflict", "error.not_found", "error.input", "error.action", "error.auth", "error.rate_limit", "error.busy", "error.unsupported", "error.unavailable", "error.bad_response", "error.network", "error.timeout", "error.safety", "error.blocked", "error.declined", "error.failed", "error.cancelled", "error.internal", "session.abandon_gated", "session.tool_denied", "session.sign_in", "session.gate_expired", "session.turn_ended", "session.gate_pending", "session.part_skipped", "live.session_ended", "tool.awaiting_user", "tool.completed_hidden", "tool.execution_uncertain", "voice.unsupported", "voice.permission", "voice.unavailable", "voice.failed", "voice.empty", "stop.cancelled", "stop.interrupted", "stop.length", "stop.filtered", "stop.provider_error", "stop.stream_incomplete", "stop.step_limit", "composer.model", "composer.effort"];
14
14
  /** One of {@linkcode CLIENT_LABEL_KEYS}. */
15
15
  export type ClientLabelKey = (typeof CLIENT_LABEL_KEYS)[number];
16
16
  /** Host-supplied replacement templates, `{param}` placeholders included. */
@@ -69,6 +69,8 @@ export const LABEL_KEYS = [
69
69
  'quota.busy',
70
70
  'error.config',
71
71
  'error.request',
72
+ 'error.conflict',
73
+ 'error.not_found',
72
74
  'error.input',
73
75
  'error.action',
74
76
  'error.auth',
@@ -227,6 +229,8 @@ export const CLIENT_LABEL_KEYS = [
227
229
  'detect.blocked',
228
230
  'error.config',
229
231
  'error.request',
232
+ 'error.conflict',
233
+ 'error.not_found',
230
234
  'error.input',
231
235
  'error.action',
232
236
  'error.auth',
@@ -387,6 +391,8 @@ const DEFAULTS = {
387
391
  'quota.busy': 'Sorry, your last message is still being answered. Please wait for it to finish.',
388
392
  'error.config': 'Sorry, something went wrong.',
389
393
  'error.request': 'Sorry, something went wrong.',
394
+ 'error.conflict': 'Sorry, something else is still in progress. Please try again shortly.',
395
+ 'error.not_found': "Sorry, that couldn't be found.",
390
396
  'error.input': "Sorry, that file can't be used here.",
391
397
  'error.action': "Sorry, that isn't available here.",
392
398
  'error.auth': "Sorry, the assistant can't connect at the moment.",
@@ -600,6 +606,8 @@ export const LABEL_NOTES = {
600
606
  'quota.busy': 'Shown to the user who sends a message while their last one is still being answered (`quotaBusy`).',
601
607
  'error.config': "Shown to the user when the turn fails because the agent's profile, a tool, or a schema is set up wrong. Takes {tool} when one step failed.",
602
608
  'error.request': 'Shown to the user when the turn fails because the host called Theorem wrongly. Takes {tool} when one step failed.',
609
+ 'error.conflict': 'Shown to the user when the call conflicts with something still in progress, such as a step that is not settled (HTTP 409). Takes {tool} when one step failed.',
610
+ 'error.not_found': 'Shown to the user when something the call names is not there, such as a conversation that is no longer kept (HTTP 404). Takes {tool} when one step failed.',
603
611
  'error.input': 'Shown to the user when they sent something the agent does not accept. Takes {tool} when one step failed.',
604
612
  'error.action': 'Shown to the user when they asked for something the agent does not allow. Takes {tool} when one step failed.',
605
613
  'error.auth': 'Shown to the user when a model key is missing or rejected, or its account cannot be billed. Takes {tool} when one step failed.',
@@ -24,6 +24,8 @@ export interface GuardedFetchOptions {
24
24
  fetchFn?: typeof fetch;
25
25
  /** Told how long each hop's checks took: its address, and its lookup when `resolveHost` is set. */
26
26
  onCheck?: (ms: number) => void;
27
+ /** Awaited once, after the first hop's checks pass and before anything is sent; what it throws passes unchanged. */
28
+ beforeSend?: () => Promise<void>;
27
29
  }
28
30
  /** A host name's IPv4 and IPv6 addresses; empty when the name does not exist. */
29
31
  export type ResolveHost = (hostname: string, signal?: AbortSignal) => Promise<readonly string[]>;
@@ -253,6 +253,7 @@ export async function fetchGuarded(url, init, options) {
253
253
  }
254
254
  };
255
255
  let target = await clearHop(url);
256
+ await options.beforeSend?.();
256
257
  const origin = target.origin;
257
258
  const headers = new Headers(init.headers);
258
259
  let method = init.method ?? 'GET';
@@ -5,7 +5,7 @@ export type { ErrorCopies, ErrorCopy };
5
5
  * the builder in code and traces (`errorKind`, `error.type`), the user through
6
6
  * the kind's wording (`error.<kind>` in the labels).
7
7
  */
8
- export declare const ERROR_KINDS: readonly ["config", "request", "input", "action", "auth", "rate_limit", "busy", "unsupported", "unavailable", "bad_response", "network", "timeout", "safety", "blocked", "declined", "failed", "cancelled", "internal"];
8
+ export declare const ERROR_KINDS: readonly ["config", "request", "conflict", "not_found", "input", "action", "auth", "rate_limit", "busy", "unsupported", "unavailable", "bad_response", "network", "timeout", "safety", "blocked", "declined", "failed", "cancelled", "internal"];
9
9
  /** Why an operation failed; the user's wording and the HTTP status follow from it. */
10
10
  export type ErrorKind = (typeof ERROR_KINDS)[number];
11
11
  /** Options for a `TheoremError`: the cause and, optionally, wording for the user. */
@@ -9,6 +9,10 @@ export const ERROR_KINDS = [
9
9
  'config',
10
10
  /** The host called THEOREM wrongly. */
11
11
  'request',
12
+ /** The call conflicts with the state it acts on, such as an operation that is still running or not settled. */
13
+ 'conflict',
14
+ /** Something the call names by id is not there, such as a conversation the store no longer holds. */
15
+ 'not_found',
12
16
  /** The user sent input the profile does not accept. */
13
17
  'input',
14
18
  /** The user asked for something the profile does not allow. */
@@ -10,6 +10,8 @@ const HTTP_BUSY = 429;
10
10
  const STATUS_BY_KIND = {
11
11
  config: 500,
12
12
  request: 400,
13
+ conflict: 409,
14
+ not_found: HTTP_NOT_FOUND,
13
15
  input: 422,
14
16
  action: 403,
15
17
  auth: 401,
@@ -7,6 +7,8 @@ import type { DecisionProfile, DecisionRequest, DecisionResult } from '../types.
7
7
  declare const DECISION_ERROR_KINDS: {
8
8
  readonly invalid_config: "config";
9
9
  readonly invalid_request: "request";
10
+ readonly conflict: "conflict";
11
+ readonly not_found: "not_found";
10
12
  readonly invalid_input: "input";
11
13
  readonly not_allowed: "action";
12
14
  readonly authentication: "auth";
@@ -10,6 +10,8 @@ import { referencedAssets } from './decision-references.js';
10
10
  const DECISION_ERROR_KINDS = {
11
11
  invalid_config: 'config',
12
12
  invalid_request: 'request',
13
+ conflict: 'conflict',
14
+ not_found: 'not_found',
13
15
  invalid_input: 'input',
14
16
  not_allowed: 'action',
15
17
  authentication: 'auth',
@@ -33,6 +35,8 @@ const DECISION_ERROR_KINDS = {
33
35
  const DECISION_CODES = {
34
36
  config: 'invalid_config',
35
37
  request: 'invalid_request',
38
+ conflict: 'conflict',
39
+ not_found: 'not_found',
36
40
  input: 'invalid_input',
37
41
  action: 'not_allowed',
38
42
  auth: 'authentication',
@@ -1,7 +1,7 @@
1
1
  import type { TraceSink } from '../../../observability/trace-sink.js';
2
2
  import type { ProviderHostOptions } from '../../protocols/runtime.js';
3
3
  import type { KernelRegistry } from '../../registry/kernel-registry.js';
4
- import type { PageToolExecution, ToolExecutionCoordinator } from '../../tools/operation.js';
4
+ import { type PageToolExecution, type ToolExecutionCoordinator } from '../../tools/operation.js';
5
5
  import type { KeyVault, LiveSession, SessionRequest } from '../../types.js';
6
6
  export type { LiveSession, SessionRequest };
7
7
  /** Options for opening a live session: the key vault, a provider's own settings, a WebSocket opener, how long a gated call waits for its decision, and the sign-in gate policy. */
@@ -25,6 +25,7 @@ import { failedActivity, failureEvent } from '../../tools/events.js';
25
25
  import { executeRegisteredTool, lapsedGateFailure, shownToolArguments, } from '../../tools/execute.js';
26
26
  import { answerGatedCall, gateExpired, resolveGateTtlMs, resumeForAnswer, } from '../../tools/gate-answer.js';
27
27
  import { formatToolFailureForModel, formatToolResult } from '../../tools/model-text.js';
28
+ import { heldOperation, unresolvedOperation, } from '../../tools/operation.js';
28
29
  import { ownToolsOf } from '../../tools/project.js';
29
30
  import { cloneTurnToolSnapshot } from '../../tools/resolve.js';
30
31
  import { turnDoneOf } from '../../turn-events.js';
@@ -699,11 +700,9 @@ function buildLiveSession(args) {
699
700
  // invariant: A dispatched call with no outcome cannot regain approval authority.
700
701
  const unresolved = dispatched || isUnresolvedOperationError(err);
701
702
  held.state = unresolved ? 'uncertain' : waiting;
702
- if (unresolved)
703
- throw new TheoremError('unavailable', labelText('tool.execution_uncertain', {}, profile.labels), {
704
- copy: { key: 'tool.execution_uncertain' },
705
- cause: err,
706
- });
703
+ if (unresolved && !isUnresolvedOperationError(err))
704
+ throw unresolvedOperation(errorKind(err), 'The held call was dispatched and did not settle, so its effects are unknown', // labels-exempt: developer contract / internal diagnostic — not end-user or model copy (P2)
705
+ err);
707
706
  throw err;
708
707
  }
709
708
  finally {
@@ -799,9 +798,7 @@ function buildLiveSession(args) {
799
798
  });
800
799
  }
801
800
  if (held.state === 'uncertain')
802
- throw new TheoremError('unavailable', labelText('tool.execution_uncertain', {}, profile.labels), {
803
- copy: { key: 'tool.execution_uncertain' },
804
- });
801
+ throw heldOperation('uncertain');
805
802
  if (gateLapsed(held)) {
806
803
  if (isReleased(held))
807
804
  lapseReleased(callId, held);
@@ -1,2 +1,3 @@
1
- declare function mapStrings(value: unknown, map: (text: string) => string): unknown;
1
+ /** `value` with every string in it put through `map`. A value that contains itself becomes `CIRCULAR` where it repeats, as `textForScan` renders it. */
2
+ declare function mapStrings(value: unknown, map: (text: string) => string, within?: Set<object>): unknown;
2
3
  export { mapStrings };
@@ -1,17 +1,28 @@
1
- function mapStrings(value, map) {
1
+ import { CIRCULAR } from '../../guardrails/serialize.js';
2
+ /** `value` with every string in it put through `map`. A value that contains itself becomes `CIRCULAR` where it repeats, as `textForScan` renders it. */
3
+ function mapStrings(value, map, within = new Set()) {
2
4
  if (typeof value === 'string') {
3
5
  return map(value);
4
6
  }
5
- if (Array.isArray(value)) {
6
- return value.map((item) => mapStrings(item, map));
7
+ if (!value || typeof value !== 'object') {
8
+ return value;
7
9
  }
8
- if (value && typeof value === 'object') {
10
+ if (within.has(value)) {
11
+ return CIRCULAR;
12
+ }
13
+ within.add(value);
14
+ try {
15
+ if (Array.isArray(value)) {
16
+ return value.map((item) => mapStrings(item, map, within));
17
+ }
9
18
  const out = {};
10
19
  for (const [key, nested] of Object.entries(value)) {
11
- out[key] = mapStrings(nested, map);
20
+ out[key] = mapStrings(nested, map, within);
12
21
  }
13
22
  return out;
14
23
  }
15
- return value;
24
+ finally {
25
+ within.delete(value);
26
+ }
16
27
  }
17
28
  export { mapStrings };
@@ -179,7 +179,8 @@ export interface ProtocolDefinition<O = unknown, S = unknown> {
179
179
  custom?: Readonly<Record<string, z.ZodType<JsonObject>>>;
180
180
  /**
181
181
  * Turns the reply's framing into rows. Absent: SSE for a stream, one JSON row otherwise, and a
182
- * body that is not JSON as one `{ eventType: 'http_body', mime_type, data }` row, base64.
182
+ * body that is not JSON as one `{ eventType: 'http_body', mime_type, data }` row, base64, with
183
+ * `id` when the reply names itself in `X-Generation-Id`.
183
184
  */
184
185
  framing?(response: Response, stream: boolean): AsyncIterable<JsonObject>;
185
186
  /** Types a failed answer. Absent: the kind follows the HTTP status. */
@@ -84,7 +84,14 @@ async function* defaultFraming(response, stream) {
84
84
  if (!stream && !/json/i.test(type)) {
85
85
  // why: a body that is not JSON (audio, an image) is one row; the tape keeps its hash, not its bytes.
86
86
  const bytes = new Uint8Array(await response.arrayBuffer());
87
- yield { eventType: 'http_body', mime_type: type, data: bytesToBase64(bytes) };
87
+ // probed 2026-10-24: OpenRouter `/audio/speech` names the answer in `X-Generation-Id` (no JSON `id`).
88
+ const id = response.headers.get('x-generation-id')?.trim();
89
+ yield {
90
+ eventType: 'http_body',
91
+ mime_type: type,
92
+ data: bytesToBase64(bytes),
93
+ ...(id ? { id } : {}),
94
+ };
88
95
  return;
89
96
  }
90
97
  if (!stream) {
@@ -9,7 +9,6 @@ import { BOUNDARIES, BOUNDARY_META, recordOf } from '../guardrails/boundaries.js
9
9
  import { DETECT_ACTION_META, DETECT_ACTIONS, DETECT_DEFAULTS, DETECTOR_BOUNDARIES, DETECTOR_META, DETECTORS, } from '../guardrails/detectors.js';
10
10
  import { LABEL_NOTES } from '../guardrails/labels.js';
11
11
  import { BLOCKED_REPLY_ON_BLOCK, DESTINATION_GATES, TAINT_GATES, } from '../guardrails/types.js';
12
- import { GOOGLE_SPEECH_VOICES } from '../presets/google/speech-voices.js';
13
12
  import { PROFILE_FIELD_PRESENCE } from './profile-presence.js';
14
13
  import { isProfileRootField, profileFieldScope } from './profile-scope.js';
15
14
  export { BLOCKED_REPLY_ON_BLOCK };
@@ -620,7 +619,7 @@ export const PROFILE_FIELDS = withScopeAndPresence({
620
619
  'live.ingress.audio': field('boolean', 'Whether the session accepts microphone audio.'),
621
620
  'live.ingress.video': field('boolean', 'Whether the session accepts camera frames.'),
622
621
  'live.ingress.text': field('boolean', 'Whether the session accepts typed text.'),
623
- 'live.voice': field('string', 'The voice the model speaks in.', GOOGLE_SPEECH_VOICES, 'Voice names to pick from; any other name is sent as written.'),
622
+ 'live.voice': field('string', 'The voice the model speaks in.'),
624
623
  'live.vad': field('LiveVadSpec', 'How the session detects when the user starts and stops speaking.'),
625
624
  'live.vad.activityHandling': field(unionType(LIVE_ACTIVITY_HANDLINGS), "Whether the user speaking interrupts the model's reply.", LIVE_ACTIVITY_HANDLINGS, {
626
625
  START_OF_ACTIVITY_INTERRUPTS: 'The user speaking cuts the reply off.',
@@ -1,18 +1,15 @@
1
- import { TheoremError, throwIfAborted } from '../../guardrails/error.js';
2
- import { labelText } from '../../guardrails/labels.js';
1
+ import { errorKind, throwIfAborted } from '../../guardrails/error.js';
3
2
  import { jsonObjectSchema } from '../json.js';
4
- import { operationBroken, operationWireValue, toolInvocationHash, toolOperationOutcomeSchema, } from './operation.js';
3
+ import { heldOperation, operationBroken, operationWireValue, toolInvocationHash, toolOperationOutcomeSchema, unresolvedOperation, } from './operation.js';
5
4
  class ReplayedOperation {
6
5
  outcome;
7
6
  constructor(outcome) {
8
7
  this.outcome = outcome;
9
8
  }
10
9
  }
11
- function uncertainError(cause) {
12
- return new TheoremError('unavailable', labelText('tool.execution_uncertain'), {
13
- copy: { key: 'tool.execution_uncertain' },
14
- cause,
15
- });
10
+ /** A gate after the claim cannot pause a call that was already sent; only a sign-in can ask for one there. */
11
+ function gateAfterClaim(gate) {
12
+ return unresolvedOperation(gate.kind === 'auth' ? 'auth' : 'internal', `The tool asked for a ${gate.kind} gate after it was sent, so its effects are unknown`);
16
13
  }
17
14
  class CoordinatedExecution {
18
15
  coordinator;
@@ -39,7 +36,7 @@ class CoordinatedExecution {
39
36
  if (result.kind === 'settled')
40
37
  throw new ReplayedOperation(result.outcome);
41
38
  if (result.kind === 'running' || result.kind === 'uncertain')
42
- throw uncertainError();
39
+ throw heldOperation(result.kind);
43
40
  if (result.kind !== 'acquired' || typeof result.claimToken !== 'string' || !result.claimToken)
44
41
  throw operationBroken("The tool coordinator's begin returned no claim"); // labels-exempt: developer contract / internal diagnostic — not end-user or model copy (P2)
45
42
  this.claim = { ...operation, claimToken: result.claimToken };
@@ -54,13 +51,13 @@ class CoordinatedExecution {
54
51
  return false;
55
52
  }
56
53
  if (this.claim && event.tool.phase === 'gate')
57
- throw uncertainError();
54
+ throw gateAfterClaim(event.tool.gate);
58
55
  return true;
59
56
  }
60
57
  async finish(settlement) {
61
58
  if (settlement.gated) {
62
59
  if (this.claim)
63
- throw uncertainError();
60
+ throw gateAfterClaim(settlement.gated);
64
61
  return undefined;
65
62
  }
66
63
  if (!this.terminal)
@@ -101,7 +98,10 @@ class CoordinatedExecution {
101
98
  return saved;
102
99
  }
103
100
  failure(error) {
104
- return this.claim && !this.committed ? uncertainError(error) : error;
101
+ if (!this.claim || this.committed)
102
+ return error;
103
+ return unresolvedOperation(errorKind(error), 'The tool was sent and did not settle, so its effects are unknown', // labels-exempt: developer contract / internal diagnostic — not end-user or model copy (P2)
104
+ error);
105
105
  }
106
106
  async close() {
107
107
  if (this.claim && !this.committed) {
@@ -119,7 +119,7 @@ export async function* coordinateTool(coordinator, identity, invocation, signal,
119
119
  const existing = await coordinator.lookup(operation);
120
120
  throwIfAborted(signal);
121
121
  if (existing?.kind === 'running' || existing?.kind === 'uncertain')
122
- throw uncertainError();
122
+ throw heldOperation(existing.kind);
123
123
  if (existing?.kind === 'settled') {
124
124
  if (!authorizeReplay)
125
125
  throw operationBroken('A settled tool operation has no replay check'); // labels-exempt: developer contract / internal diagnostic — not end-user or model copy (P2)
@@ -30,9 +30,19 @@ export declare function newCallId(name: string): string;
30
30
  export declare function toolCallArguments(safeInput: unknown): Record<string, unknown>;
31
31
  export declare function messageOf(err: unknown): string;
32
32
  export declare function sourceEvents(base: ToolCallBase, sources: (output: unknown) => Source[], output: unknown): Generator<TurnEvent>;
33
+ /** A call's claim, taken once at the hand-off: right before the destination is asked. */
34
+ export declare class HandOff {
35
+ private begin?;
36
+ private taken?;
37
+ private failed?;
38
+ constructor(begin?: (() => Promise<ToolOperationClaim | undefined>) | undefined);
39
+ claim(): Promise<ToolOperationClaim | undefined>;
40
+ /** The claim's own failure is the coordinator's, so no tool catch may turn it into a tool failure. */
41
+ rethrowClaimFailure(): void;
42
+ }
33
43
  export declare function dispatchToolBody(tool: {
34
44
  labels?: ToolLabels;
35
- }, input: unknown, ctx: ToolContext, base: ToolCallBase, beginBody?: (preparedInput: unknown) => Promise<ToolOperationClaim | undefined>): AsyncGenerator<TurnEvent, ToolOperationClaim | undefined>;
45
+ }, input: unknown, ctx: ToolContext, base: ToolCallBase, beginBody?: (preparedInput: unknown) => Promise<ToolOperationClaim | undefined>): AsyncGenerator<TurnEvent, HandOff>;
36
46
  export declare function startToolExecution<T>(tool: {
37
47
  input: z.ZodType<T>;
38
48
  }, rawInput: unknown, ctx: ToolContext): {