@theoremjs/studio 0.3.5-next.897.g1c14afe → 0.3.5-next.899.g4d53f7b

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/package.json +4 -4
  2. package/page/assets/{BottomSheet-BrqVIG3q.js → BottomSheet-CYjGeSxH.js} +1 -1
  3. package/page/assets/{ConsoleFrame-BHSpIlxr.js → ConsoleFrame-C6oKheIJ.js} +1 -1
  4. package/page/assets/{DateInput-LfhqCpkG.js → DateInput-C_GKmPlP.js} +1 -1
  5. package/page/assets/{MenuBottomSheet-CCwSxsx7.js → MenuBottomSheet-C5aySdbf.js} +1 -1
  6. package/page/assets/{RankedBars-kn41W08M.js → RankedBars-CzseKVGW.js} +1 -1
  7. package/page/assets/{SchemaFields-yVN_ZWRi.js → SchemaFields-Bn1FlZ9h.js} +1 -1
  8. package/page/assets/{TokenizerBottomSheet-DQyvjjS8.js → TokenizerBottomSheet-nUC-r50S.js} +1 -1
  9. package/page/assets/{ToolResultCharts-BL50wIPJ.js → ToolResultCharts-D-yS3nPf.js} +1 -1
  10. package/page/assets/{Toolbar-CWmIMLeV.js → Toolbar-D1ZTKRRs.js} +1 -1
  11. package/page/assets/{TraceInspector-j_-zxt-J.js → TraceInspector-kd573aZs.js} +1 -1
  12. package/page/assets/{TraceOverview-CFeKCBMG.js → TraceOverview-C4aC107k.js} +7 -7
  13. package/page/assets/{_virtual_studio-type-sources-Bs53zyy5.js → _virtual_studio-type-sources-CeP1lh8X.js} +52 -15
  14. package/page/assets/browser-connection-D_lN2asL.js +1 -0
  15. package/page/assets/browser-engine-C1BQ7JLI.js +16 -0
  16. package/page/assets/{browser-transport-Bu8d-ypL.js → browser-transport-Cx2jhgL2.js} +2 -2
  17. package/page/assets/{compile-DOVavMGs.js → compile-sDVAeWRn.js} +1 -1
  18. package/page/assets/{encode-files-DwhTSEvK.js → encode-files-kIrEhKfy.js} +1 -1
  19. package/page/assets/{export-agent-ghSdqs4C.js → export-agent-BCiXtsad.js} +1 -1
  20. package/page/assets/{getRadiusAndStrokeWidthFromDot-BPcdJZld.js → getRadiusAndStrokeWidthFromDot-DKPY5zvD.js} +1 -1
  21. package/page/assets/{guardrail-health-BdKHj6H2.js → guardrail-health-DA4L7hiL.js} +1 -1
  22. package/page/assets/{guardrail-tester-CyKcFBHE.js → guardrail-tester-el2lmTQX.js} +1 -1
  23. package/page/assets/{index-COigXW7d.js → index-1uaUcgQp.js} +11 -11
  24. package/page/assets/{json-code-CFljGCSe.js → json-code-GzwznvYh.js} +1 -1
  25. package/page/assets/{labels-provider-g5BoRCPe.js → labels-provider-BTXBWLwp.js} +1 -1
  26. package/page/assets/{live-messages-DnkJoi21.js → live-messages-fu3eH91T.js} +1 -1
  27. package/page/assets/{prompt-row-DbGC9SO5.js → prompt-row-Dp1_UynC.js} +1 -1
  28. package/page/assets/{reader-rgsnlepB.js → reader-DZ_YIRM1.js} +3 -3
  29. package/page/assets/{registry-DetG0tAi.js → registry-CTpu-bdw.js} +1 -1
  30. package/page/assets/schema-5LN5ovk9.js +3 -0
  31. package/page/assets/shaped-data-BPVQeZF7.js +25 -0
  32. package/page/assets/{stub-CKTnnraF.js → stub-BwR5uljZ.js} +1 -1
  33. package/page/assets/{studio-code-pane-BrtdT2kP.js → studio-code-pane-Bh4VA6HZ.js} +3 -3
  34. package/page/assets/{studio-console-BL903sOl.js → studio-console-CxPicqS7.js} +1 -1
  35. package/page/assets/{studio-decision-BZjQ-fkT.js → studio-decision-DP782BZF.js} +1 -1
  36. package/page/assets/{studio-embedding-DPYN-vTz.js → studio-embedding-OjJmB1J5.js} +1 -1
  37. package/page/assets/{studio-host-console-KndVg5RH.js → studio-host-console-ljNprW3w.js} +2 -2
  38. package/page/assets/{studio-labels-C7YUq2SE.js → studio-labels-DJvzMLMM.js} +1 -1
  39. package/page/assets/{studio-live-Qcj_FIiY.js → studio-live-mvuvdm_x.js} +1 -1
  40. package/page/assets/{studio-map-CEosluru.js → studio-map-6s987-4d.js} +1 -1
  41. package/page/assets/{studio-trace-replay-CBqq_J4T.js → studio-trace-replay-Vdb-R8gF.js} +1 -1
  42. package/page/assets/{studio-type-checker-yaoqlViI.js → studio-type-checker-UnXz6LGA.js} +1 -1
  43. package/page/assets/{tool-schema-D9oQJ_Yc.js → tool-schema-kC7sCJbX.js} +1 -1
  44. package/page/assets/{trace-record-CFEQvoUx.js → trace-record-BrtFWrPa.js} +1 -1
  45. package/page/assets/{tree-CQOtBCj_.js → tree-iTFAG9HK.js} +1 -1
  46. package/page/assets/{turn-client-Bna6NFNB.js → turn-client-Ijnv3PVz.js} +1 -1
  47. package/page/assets/{types-D0Qg5IhA.js → types-BONQrLx-.js} +1 -1
  48. package/page/assets/{use-one-call-Bbdd7UUS.js → use-one-call-CGTLluoc.js} +1 -1
  49. package/page/assets/{workspace-Ck3qcAQG.js → workspace-Dri6_R-8.js} +1 -1
  50. package/page/index.html +17 -17
  51. package/page/assets/browser-connection-CefuxbkX.js +0 -1
  52. package/page/assets/browser-engine-BEJdq39c.js +0 -16
  53. package/page/assets/schema-Dfb-HTKf.js +0 -3
  54. package/page/assets/shaped-data-Dp3FW2xr.js +0 -25
@@ -5458,7 +5458,8 @@ export interface CompactionSpec {
5458
5458
  */
5459
5459
  meter?: CompactionMeter;
5460
5460
  /**
5461
- * Your function that decides when to compact, in place of compactAt and maxTokens.
5461
+ * Your function that decides when to compact, in place of compactAt and maxTokens. A throw is
5462
+ * reported as hook_failed, and compactAt and maxTokens decide.
5462
5463
  *
5463
5464
  * @remarks Replaces the default \`tokens > compactAt * maxTokens\` check.
5464
5465
  */
@@ -5610,7 +5611,8 @@ export type ProfileItemCheck = (item: unknown, turn: ItemCheckTurn) => Validatio
5610
5611
  export interface ProfileItemRule {
5611
5612
  /**
5612
5613
  * Your check on one item, given what the tools of the turn returned (turn.toolResults); its error
5613
- * is the reason the model reads on a rewrite and the host reads on the removed item.
5614
+ * is the reason the model reads on a rewrite and the host reads on the removed item. A throw
5615
+ * refuses the item, reported as hook_failed.
5614
5616
  */
5615
5617
  check: ProfileItemCheck;
5616
5618
  /**
@@ -5630,7 +5632,7 @@ export interface ProfileValidationSpec {
5630
5632
  * \`diagram.mermaid\`). Presence/required is owned by the JSON Schema; these run only for required
5631
5633
  * paths and for optional paths that are present.
5632
5634
  *
5633
- * @catalog outputs.validation.fields.* Your check on this part of the reply, reached through object properties only; a failure sends its error back to the model to rewrite while retries remain.
5635
+ * @catalog outputs.validation.fields.* Your check on this part of the reply, reached through object properties only; a failure sends its error back to the model to rewrite while retries remain. A throw is a failure, reported as hook_failed.
5634
5636
  */
5635
5637
  fields?: Record<string, ProfileValidator>;
5636
5638
  /**
@@ -6402,11 +6404,15 @@ export interface TurnTraceLink {
6402
6404
  }
6403
6405
  /** What \`runTurn\` and \`runSession\` both take: an agent's profile, its model, and the host's hooks and keys. */
6404
6406
  export interface AgentRunRequest extends RunControls, ModelChoice {
6405
- /** Host-owned atomic tool claims and outcomes. Never sent to providers. */
6407
+ /**
6408
+ * Host-owned atomic tool claims and outcomes. Never sent to providers. A throw before the call
6409
+ * runs fails the call. A throw after it ran keeps the result, marks the call uncertain and is
6410
+ * reported as hook_failed. A TheoremError is its answer and ends the turn.
6411
+ */
6406
6412
  execution?: ToolExecutionCoordinator;
6407
6413
  /**
6408
6414
  * Host-issued service for tool calls that go on after their reply. It needs a coordinator with
6409
- * detach. Without it every tool runs inline.
6415
+ * detach. Without it every tool runs inline. A throw from its event goes on the call's own trace.
6410
6416
  */
6411
6417
  background?: ToolBackgroundService;
6412
6418
  /** Host-issued browser dispatch with a claimed operation and correlated result. */
@@ -6478,7 +6484,8 @@ export interface AgentRunRequest extends RunControls, ModelChoice {
6478
6484
  fetch?: typeof fetch;
6479
6485
  /**
6480
6486
  * Your function that sees each stage of a text turn or a live session, and can answer with what
6481
- * the stage allows.
6487
+ * the stage allows. A throw at pre_tool fails that call. A throw at any other stage is reported as
6488
+ * hook_failed, and the turn goes on without its answer.
6482
6489
  *
6483
6490
  * @remarks Text \`runTurn\` and \`runSession\` emit stages and apply the returned affordances. A
6484
6491
  * session's is set once.
@@ -6542,13 +6549,13 @@ export interface TurnRequest extends AgentRunRequest {
6542
6549
  */
6543
6550
  stepsTaken?: number;
6544
6551
  /**
6545
- * Reads each of the turn's events as it leaves runTurn, before the caller gets it. A throw ends
6546
- * the turn with that error.
6552
+ * Reads each of the turn's events as it leaves runTurn, before the caller gets it. A throw goes
6553
+ * to the caller as hook_failed, which this function does not read, and the turn goes on.
6547
6554
  *
6548
6555
  * @remarks Reads each of this turn's events as it leaves \`runTurn\`, before the caller gets it.
6549
6556
  * The app sets it in \`TurnWiring.prepare\` to act on a turn someone else runs, such as saving the
6550
- * reply when \`done\` arrives. A throw ends the turn with that error. \`invokeTool\` does not call
6551
- * it.
6557
+ * reply when \`done\` arrives. A throw is reported to the caller as \`hook_failed\`, and the turn
6558
+ * goes on. \`invokeTool\` does not call it.
6552
6559
  */
6553
6560
  onEvent?: (event: TurnEvent) => void | Promise<void>;
6554
6561
  /**
@@ -7194,6 +7201,10 @@ export type SessionEventKind = SessionEvent['kind'];
7194
7201
  export type SessionEventOf<K extends SessionEventKind> = Extract<SessionEvent, {
7195
7202
  kind: K;
7196
7203
  }>;
7204
+ /** The host hooks whose crash the turn survives and reports as \`hook_failed\`. */
7205
+ declare const HOOK_NAMES: readonly ["execution", "background", "onStage", "onEvent", "onAgentCall", "tools.preTool", "tools.t1Policy", "outputs.validation", "compaction.trigger"];
7206
+ /** A host hook a \`hook_failed\` event names. */
7207
+ export type HookName = (typeof HOOK_NAMES)[number];
7197
7208
  /** Why a tool call failed, for the builder and for the user. */
7198
7209
  export interface ToolFailure {
7199
7210
  /** What went wrong, for the builder. Stable per failure site. */
@@ -7680,7 +7691,22 @@ export type TurnEvent = {
7680
7691
  errorInternal?: string;
7681
7692
  } | ({
7682
7693
  type: 'done';
7683
- } & DoneEvent) | {
7694
+ } & DoneEvent)
7695
+ /**
7696
+ * A host hook threw, and the turn went on without its answer. A crash at a tool call's gate
7697
+ * also fails that call, which the model reads in the profile's wording.
7698
+ */
7699
+ | {
7700
+ type: 'hook_failed';
7701
+ hook: HookName;
7702
+ /** The stage whose \`onStage\` threw. */
7703
+ stage?: TurnStage;
7704
+ /** The tool call the hook ran for. */
7705
+ callId?: string;
7706
+ errorKind: ErrorKind;
7707
+ /** The thrown reason and its causes, for the builder only (\`forClient\` strips it). */
7708
+ errorInternal?: string;
7709
+ } | {
7684
7710
  type: 'error';
7685
7711
  errorKind: ErrorKind;
7686
7712
  /** Public-safe failure text for hosts to show users: the wording for \`errorKind\`. */
@@ -8529,7 +8555,7 @@ export { applySpans, blobAt, mergeSpans, OMIT_CANARY, OMIT_INJECTION, OMIT_PROMP
8529
8555
  `,"file:///node_modules/@theoremjs/agents/src/guardrails/labels.d.ts":`/** Values that fill a label template's \`{param}\` placeholders. */
8530
8556
  export type LabelParams = Record<string, string | number>;
8531
8557
  /** Keys are stable API. */
8532
- 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", "turn.media_refused_image", "turn.media_refused_video", "turn.media_refused_file", "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.cut_off_guidance", "repair.reply_cut_off", "repair.call_cut_off", "repair.call_cut_off_guidance", "repair.nothing_written", "repair.nothing_written_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", "structured.cut_off", "structured.not_json", "compaction.request", "compaction.tool_call", "compaction.tool_result", "compaction.tool_files", "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.email", "detect.hint.phone", "detect.hint.bank_account", "detect.hint.injection", "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.full", "session.busy", "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", "stop.answer_missing", "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.unreachable", "tool.page_no_answer", "tool.page_timed_out", "tool.output_invalid", "tool.not_loaded_t2", "tool.wait_unknown", "tool.wait_cycle", "tool.after_field", "tool.background_field", "tool.background_started", "tool.late_result", "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"];
8558
+ 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", "turn.media_refused_image", "turn.media_refused_video", "turn.media_refused_file", "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.cut_off_guidance", "repair.reply_cut_off", "repair.call_cut_off", "repair.call_cut_off_guidance", "repair.nothing_written", "repair.nothing_written_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", "structured.cut_off", "structured.not_json", "compaction.request", "compaction.tool_call", "compaction.tool_result", "compaction.tool_files", "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.email", "detect.hint.phone", "detect.hint.bank_account", "detect.hint.injection", "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.full", "session.busy", "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", "stop.answer_missing", "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.hook_failed", "tool.input_invalid_after_mutate", "tool.output_invalid_after_mutate", "tool.handler_no_output", "tool.did_not_run", "tool.unreachable", "tool.page_no_answer", "tool.page_timed_out", "tool.output_invalid", "tool.not_loaded_t2", "tool.wait_unknown", "tool.wait_cycle", "tool.after_field", "tool.background_field", "tool.background_started", "tool.late_result", "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"];
8533
8559
  /** One of {@linkcode LABEL_KEYS}. */
8534
8560
  export type LabelKey = (typeof LABEL_KEYS)[number];
8535
8561
  /**
@@ -9881,7 +9907,7 @@ export interface ToolHostHooks<TIn = unknown> {
9881
9907
  */
9882
9908
  outputSchema: Record<string, unknown>;
9883
9909
  /**
9884
- * Runs before the host's pre_tool onStage.
9910
+ * Runs before the host's pre_tool onStage. A throw fails the call, reported as hook_failed.
9885
9911
  *
9886
9912
  * @remarks Runs before the host's \`pre_tool\` \`onStage\`.
9887
9913
  */
@@ -10203,7 +10229,7 @@ export interface AgentToolDef extends ToolBase {
10203
10229
  * them.
10204
10230
  */
10205
10231
  hostOnly?: AgentToolChannel[];
10206
- /** Runs before the host's pre_tool onStage. */
10232
+ /** Runs before the host's pre_tool onStage. A throw fails the call, reported as hook_failed. */
10207
10233
  preTool?: ToolHostHooks<AgentToolInput>['preTool'];
10208
10234
  /**
10209
10235
  * Gives the model an after field on this tool: the tools called in the same step that must settle
@@ -10401,7 +10427,7 @@ export interface ProfileToolsSpec {
10401
10427
  allow: ToolId[];
10402
10428
  /**
10403
10429
  * Your function that picks, at the start of each turn, which T2 tools to load up front; the rest
10404
- * wait for tools.t2Loader.
10430
+ * wait for tools.t2Loader. A throw loads none up front, reported as hook_failed.
10405
10431
  *
10406
10432
  * @remarks Returns ids already allowed with \`loadTier: 'T2'\` to load at turn start. Not supported
10407
10433
  * on \`type: 'live'\`.
@@ -10693,6 +10719,10 @@ export interface RunStageArgs extends StageCallBag {
10693
10719
  /** Applied stage output: every handler's inject, in call order, sanitized. */
10694
10720
  export interface RunStageOutput extends Omit<StageApplyOutput, 'inject'> {
10695
10721
  inject: InjectUnit[];
10722
+ /** At \`pre_tool\`, what a handler threw: the call fails with it, and no other handler runs. */
10723
+ crashed?: {
10724
+ error: unknown;
10725
+ };
10696
10726
  }
10697
10727
  /** Stage events always emit, even with no handlers. */
10698
10728
  export declare function runStage(args: RunStageArgs): AsyncGenerator<TurnEvent, RunStageOutput>;
@@ -10823,6 +10853,7 @@ export declare function operationWireValue(value: unknown): JsonValue;
10823
10853
  `,"file:///node_modules/@theoremjs/agents/src/guardrails/error.d.ts":"import type { TurnEventOf } from '../kernel/turn-events.js';\nimport type { TurnEvent } from '../kernel/types.js';\nimport { type LabelOverrides } from './labels.js';\nimport { type ErrorCopies, type ErrorKind, TheoremError } from './theorem-error.js';\n/** True when the value is an error named `AbortError`. */\ndeclare function isAbortError(err: unknown): boolean;\n/** `AbortSignal.timeout` rejects with a `TimeoutError`, not an `AbortError`. */\ndeclare function isTimeoutError(err: unknown): boolean;\n/** Throws when the signal has aborted: its framework, abort or timeout reason, else an `AbortError`. */\ndeclare function throwIfAborted(signal?: AbortSignal): void;\n/** Anything that is not a `TheoremError` or an abort escaped every boundary that names kinds: a THEOREM bug. */\ndeclare function errorKind(err: unknown): ErrorKind;\n/** 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`. */\ndeclare function kindOfHttpStatus(status: number): ErrorKind;\n/** The named reasons an error carries, one line each, in the profile's wording. */\ndeclare function errorCopyText(copy: ErrorCopies, labels?: LabelOverrides): string;\n/** Pass the profile's `labels`, or the profile's wording is skipped. */\ndeclare function publicError(err: unknown, labels?: LabelOverrides): string;\n/** Raw diagnostic for hosts, traces, and logs; never shown to end users. Each cause that says something new follows on its own line. */\ndeclare function describeError(err: unknown): string;\n/** fetch rejects only when no response came back, so any non-abort, non-timeout rejection is `network`. */\ndeclare function networkError(err: unknown): unknown;\n/** `send`, with a failed send or body read named as `networkError` names it. */\ndeclare function sendOrNetworkError(send: typeof fetch, ...args: Parameters<typeof fetch>): Promise<Response>;\ntype ProducedError = TurnEventOf<'error'> & {\n errorInternal: string;\n};\n/** No user wording yet: `withPublicLabels` adds it where the event reaches the host, the one place that knows the profile. */\ndeclare function toErrorEvent(err: unknown): ProducedError;\n/** Wording already set (host copy) is kept. */\ndeclare function withPublicLabels(event: TurnEvent, labels?: LabelOverrides): TurnEvent;\nexport type { ErrorCopies, ErrorCopy, ErrorKind, TheoremErrorOptions } from './theorem-error.js';\nexport { ERROR_KINDS } from './theorem-error.js';\nexport type { ProducedError };\nexport { describeError, errorCopyText, errorKind, isAbortError, isTimeoutError, kindOfHttpStatus, networkError, publicError, sendOrNetworkError, TheoremError, throwIfAborted, toErrorEvent, withPublicLabels, };\n","file:///node_modules/@theoremjs/agents/src/kernel/tools/background.d.ts":`import { z } from 'zod';
10824
10854
  import { labelText } from '../../guardrails/labels.js';
10825
10855
  import type { SpanHandle, TraceAttributes } from '../../observability/trace-span.js';
10856
+ import type { HookName } from '../turn-events.js';
10826
10857
  import type { TurnEvent } from '../types.js';
10827
10858
  import type { AgentCaller } from './agent.js';
10828
10859
  import { type ToolCallBase } from './events.js';
@@ -10884,6 +10915,8 @@ export interface ToolBackgroundService {
10884
10915
  /** A detached call's own trace record, joined to its turn through \`traceparent\`. */
10885
10916
  export interface DetachedToolTrace {
10886
10917
  open: (name: string, attributes: TraceAttributes) => SpanHandle;
10918
+ /** Records a host hook's crash on the call's span, where no turn is left to read it. */
10919
+ hookFailed: (hook: HookName, err: unknown) => void;
10887
10920
  end: () => void | Promise<void>;
10888
10921
  }
10889
10922
  /** The service with what a request adds: its event projection and where a detached trace goes. */
@@ -12153,6 +12186,10 @@ export declare function resolveTurnTools(tools: ToolRegistry, profile: Profile,
12153
12186
  export declare function prepareTurnToolSnapshot(tools: ToolRegistry, profile: Profile, req: TurnRequest, modelId: ModelId | undefined): Promise<TurnToolSnapshot>;
12154
12187
  /** So concurrent host invokes do not share mutable state. */
12155
12188
  export declare function cloneTurnToolSnapshot(state: TurnToolSnapshot): TurnToolSnapshot;
12189
+ /** Applies the profile's \`t1Policy\`. A policy that throws or answers wrongly leaves the T0 tools, and its error comes back. */
12190
+ export declare function applyT1Policy(tools: ToolRegistry, state: TurnToolSnapshot, profile: Profile, req: TurnRequest): Promise<{
12191
+ crashed: unknown;
12192
+ } | undefined>;
12156
12193
  export declare function expandT1Policy(tools: ToolRegistry, state: TurnToolSnapshot, profile: Profile, req: TurnRequest): Promise<void>;
12157
12194
  /** Puts the T2 tools among \`ids\` that the turn may call on its list; any other id is left out. */
12158
12195
  export declare function promoteTurnTools(tools: ToolRegistry, state: TurnToolSnapshot, ids?: readonly ToolId[]): void;
@@ -0,0 +1 @@
1
+ import{E as e,d as t,x as n}from"./schemas-D7cgkv3L.js";import{H as r}from"./tool-schema-kC7sCJbX.js";import{At as i,Bi as a,Fa as o,Ii as s,Ja as c,Ta as l,Ti as u,Ut as ee,Vi as te,Wa as ne,Wt as re,Ya as ie,Zi as d,aa as ae,bi as oe,di as f,dn as se,fa as ce,fi as le,fn as p,gn as m,hi as ue,ka as de,mn as h,pa as fe,pn as g,qt as pe,xi as _,zi as me}from"./shaped-data-BPVQeZF7.js";import{c as v}from"./host-patterns-F-KZIzkF.js";import{A as he,C as ge,O as _e,T as ve,_ as y,y as ye}from"./schema-5LN5ovk9.js";import{a as be,n as xe}from"./live-ingress-OuSlQ6q7.js";var Se=2,Ce=4,we=3,Te=/(^|,)(\s*)("?)(?:([=@])|([+-])(?![0-9."]))/gm,Ee=/^[A-Za-z0-9+/]*={0,2}$/,De=new Set([`text/csv`,`text/plain`,`text/markdown`]);function b(e){let{maxFiles:t,maxBytes:n,maxTurnBytes:r,limitsByMime:i}=e;if(t&&n&&r)return{maxFiles:t,maxBytes:n,maxTurnBytes:r,limitsByMime:i}}function Oe(e,t){if(t.limitsByMime){let n=m(e);if(t.limitsByMime[n])return t.limitsByMime[n];let[r]=n.split(`/`),i=`${r}/*`;if(t.limitsByMime[i])return t.limitsByMime[i]}return t.maxBytes}function x(e){return`uri`in e}function ke(e){if(e.type===`speech`)throw new v(`request`,`Profile ${e.id} (speech) does not accept media input`);if(e.type===`live`)throw new v(`request`,`Profile ${e.id} (live) does not accept turn attachment input`);if(e.type===`host`||e.type===`decision`||e.type===`embedding`)throw new v(`request`,`Profile ${e.id} (${e.type}) does not accept turn input`);let t=b(e.inputs??{});if(!t)throw new v(`config`,`Profile ${e.id} must set maxFiles, maxBytes, and maxTurnBytes`);return t}function Ae(e){let t=0;return e.endsWith(`==`)?t=Se:e.endsWith(`=`)&&(t=1),Math.floor(e.length*we/Ce)-t}function je(e){try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(e)}catch{return new TextDecoder(`latin1`).decode(e)}}function Me(e){return e.replace(Te,(e,...t)=>{let[n,r,i,a,o]=t;return`${n}${r}${i}'${a??``}${o??``}`})}function Ne(e,t,n){let r=je(t);return e===`text/csv`&&(r=Me(r)),new TextEncoder().encode(n.read(r))}function S(e,t){return t?{...e,fileName:t}:e}function Pe(e,t,n){return t.filter(t=>!p(e,t.mimeType)).map(e=>S({code:`mime_not_allowed`,params:{mimeType:e.mimeType,channel:n}},e.name))}function Fe(e,t){let n=[];e.length>t.maxFiles&&n.push({code:`too_many_files`,params:{maxFiles:t.maxFiles}});let r=0;for(let i of e){if(i.sizeBytes===void 0)continue;let e=Oe(i.mimeType,t);i.sizeBytes>e&&n.push(S({code:`file_too_large`,params:{maxBytes:e}},i.name)),r+=i.sizeBytes}return r>t.maxTurnBytes&&n.push({code:`turn_too_large`,params:{maxTurnBytes:t.maxTurnBytes}}),n}function Ie(e,t,n){let r=[];return t.length>0&&!e.attachments&&r.push({code:`attachments_not_accepted`,params:{channel:`attachment`}}),n.length>0&&!e.voice&&r.push({code:`voice_not_accepted`,params:{channel:`voice`}}),r.length>0||t.length===0&&n.length===0?r:(e.attachments&&r.push(...Pe(e.attachments,t,`attachment`)),e.voice&&r.push(...Pe(e.voice,n,`voice`)),e.limits?[...r,...Fe([...t,...n],e.limits)]:[...r,{code:`limits_unconfigured`}])}var Le={mime_not_allowed:`attachments.mime_not_allowed`,too_many_files:`attachments.too_many_files`,too_many_of_kind:`attachments.too_many_of_kind`,file_too_large:`attachments.file_too_large`,turn_too_large:`attachments.turn_too_large`,attachments_not_accepted:`attachments.not_accepted`,voice_not_accepted:`attachments.not_accepted`,limits_unconfigured:`attachments.limits_unconfigured`};function C(e){let t={};for(let[n,r]of Object.entries(e.params??{}))r!==void 0&&(t[n]=r);return e.fileName!==void 0&&(t.fileName=e.fileName),{key:Le[e.code],params:t}}function Re(e,t){let n=C(e);return c(n.key,n.params,t)}function w(e){return new v(`input`,`attachments refused: ${e.map(e=>e.code).join(`, `)}`,{copy:e.map(C)})}function T(e){if(!Ee.test(e))throw new v(`request`,`attachment data must be base64`);return Ae(e)}function E(e){let t={mimeType:e.mimeType,name:e.name};return x(e)||(t.sizeBytes=T(e.data)),t}function ze(e,t,n){if(!Be(t,n))return;let r=ke(e),i=Ie({attachments:g(e,`attachments`),voice:g(e,`voice`),limits:r},(t??[]).map(E),(n??[]).map(E));if(i.length>0)throw w(i)}function D(e,t){if(x(e))return e;let{mimeType:n,data:r}=e;if(!De.has(m(n)))return e;let i=Ne(n,ce(r),t);return{...e,data:fe(i)}}function Be(e,t){return(e?.length??0)>0||(t?.length??0)>0}function Ve(e,t,n,r){return ze(e,t,n),{attachments:t?.length?t.map(e=>D(e,r.attachment)):t,voice:n?.length?n.map(e=>D(e,r.voice)):n}}function O(e){let t=Object.keys(e);return t.length===1?t[0]:void 0}function k(e){return e==null}function A(e){return k(e)||typeof e!=`object`||Array.isArray(e)?null:e}function j(e){let t=A(e);return!t||t.type!==void 0&&t.type!==`object`?null:t}function M(e){let t=e.required;return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}function N(e){let t=e.properties;return A(t)??{}}function He(e,t){return e?`${e}.${t}`:t}function P(e,t){t.push({path:e,error:`required field '${e}' is missing`})}async function Ue(e,t,n,r,i,a){if(!n)return;let o;try{o=await n(t,r)}catch(e){a.push(e),o={isValid:!1}}o.isValid||i.push({path:e,error:o.error||o.finding||`Validation failed for '${e}'`})}async function We(e){let{path:t,propSchema:n,child:r,isRequired:i,fields:a,options:o,failures:s,crashes:c}=e;if(k(r)){i&&P(t,s);return}await Ue(t,r,a?.[t],o,s,c);let l=j(n),u=l?A(r):null;l&&u&&await F(l,u,t,a,o,s,c)}async function F(e,t,n,r,i,a,o){let s=N(e),c=new Set(M(e)),l=new Set([...Object.keys(s),...c]),u=A(t);for(let e of l)await We({path:He(n,e),propSchema:s[e],child:u?.[e],isRequired:c.has(e),fields:r,options:i,failures:a,crashes:o})}async function Ge(e,t,n,r,i=[]){let a=j(e);if(!a)throw new v(`config`,`structured validation requires a JSON Schema object root`);let o=[];if(!A(t)){for(let e of M(a))P(e,o);return o}return await F(a,t,``,n,r,o,i),o}function Ke(e,t){let n=e;for(let e of t.split(`.`)){let t=j(n);if(!t)return!1;let r=N(t);if(!Object.hasOwn(r,e)&&!M(t).includes(e))return!1;n=r[e]}return!0}function qe(e){return e.map(e=>e.error).join(`; `)}function I(e,t){let n=e;for(let e of t.split(`.`))n=A(n)?.[e];return n}function L(e,t,n){let[r,...i]=t.split(`.`),a=A(e)??{};return r===void 0?e:{...a,[r]:i.length?L(a[r],i.join(`.`),n):n}}async function Je(e,t,n,r=[]){let i=[];for(let[a,o]of Object.entries(t??{})){let t=I(e,a);if(Array.isArray(t))for(let[e,s]of t.entries()){let t;try{t=await o.check(s,n)}catch(e){r.push(e),t={isValid:!1}}t.isValid||i.push({path:a,index:e,item:s,reason:t.error||t.finding||`Validation failed for '${a}'`,onFail:o.onFail})}}return i}function R(e,t){let n=e;for(let e of t.split(`.`)){let t=j(n);if(!t)return;n=N(t)[e]}let r=A(n);if(r?.type===`array`)return A(r.items)??void 0}function Ye(e,t,n,r){if(!n.provider?.trim()||!n.apiId?.trim())throw new v(`config`,c(`provider.binding_identity`))}function Xe(e){B(e.id,e.models),Y(e.id,e.observability),Q(e.id,e.inputs);for(let[t,n]of Object.entries(e.models))H(e.id,t,n);return{type:`embedding`,id:e.id,identity:{handle:e.identity.handle},models:e.models,defaultModel:V(e.id,e),allowModelSelect:e.allowModelSelect,inputs:e.inputs,guardrails:e.guardrails,observability:e.observability,labels:e.labels}}function Ze(e){B(e.id,e.models),q(e.id,e.guardrails),Y(e.id,e.observability);for(let[t,n]of Object.entries(e.models))H(e.id,t,n);if(`text`in e.inputs&&e.inputs.text!==!1)throw new v(`config`,`Profile ${e.id}: a transcription takes a voice clip, so inputs.text must be false`);return{type:`transcription`,id:e.id,identity:{handle:e.identity.handle},...W(e),providerContinuation:void 0,maxSteps:void 0,inputs:{...e.inputs,text:!1},guardrails:e.guardrails,observability:e.observability,labels:e.labels}}function Qe(e,t,n,r){let i=r.safeParse(n);if(!i.success)throw new v(`config`,`Profile ${e} model '${t}': ${i.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `)}`)}function $e(e,t,n){if(Qe(e,t,n,re),Ye(e,t,n,`decision`),`retry`in n)throw new v(`config`,`Profile ${e} model '${t}': a decision binding takes no retry; a decision retries only a transient failure, by the kernel's rule`);if(n.timeoutMs!==void 0&&(!Number.isFinite(n.timeoutMs)||n.timeoutMs<=0))throw new v(`config`,`Profile ${e} model '${t}' timeoutMs must be > 0`)}function et(e){let t=e.models?O(e.models):void 0;if(!t)throw new v(`config`,`Profile ${e.id}: type 'decision' must declare exactly one model`);$e(e.id,t,e.models[t])}function tt(e){if(e.inputs.state!==`json`)throw new v(`config`,`Profile ${e.id}: decision inputs.state must be 'json'`);let t=e.inputs.maxStateBytes;if(t!==void 0&&!(Number.isInteger(t)&&t>0))throw new v(`config`,`Profile ${e.id}: decision inputs.maxStateBytes must be a positive integer`);if(!e.decision.contract.trim())throw new v(`config`,`Profile ${e.id}: decision.contract must be non-empty`)}function nt(e){return et(e),tt(e),Y(e.id,e.observability),{...e,identity:{handle:e.identity.handle}}}function z(e){return e===void 0?{}:{parallel:e}}function rt(e){return it(e.id,e.tools),Y(e.id,e.observability),{type:`host`,id:e.id,tools:{allow:e.tools.allow,...z(e.tools.parallel)},guardrails:e.guardrails,observability:e.observability,labels:e.labels}}function it(e,t){if(!Array.isArray(t.allow))throw new v(`config`,`Profile ${e}: type 'host' must set tools.allow`)}function B(e,t){if(Object.keys(t).length===0)throw new v(`config`,`Profile ${e} must declare at least one model`)}function V(e,t){let n=t.defaultModel??O(t.models);if(!n)throw new v(`config`,`Profile ${e} must set defaultModel when more than one model is declared`);if(!t.models[n])throw new v(`config`,`Profile ${e} defaultModel '${n}' is not declared`);return n}function H(e,t,n){U(e,t,n),Qe(e,t,n,pe),U(e,t,n)}function U(e,t,n){let r=n.efforts;if(!r||Object.keys(r).length===0){if(n.defaultEffort||n.allowEffortSelect)throw new v(`config`,`Profile ${e} model '${t}': defaultEffort and allowEffortSelect require efforts`);return}for(let[n,i]of Object.entries(r))if(!u.includes(i))throw new v(`config`,`Profile ${e} model '${t}' effort '${n}': '${i}' is not a thinking level (${u.join(`, `)})`);let i=Object.keys(r),a=n.defaultEffort??(i.length===1?i[0]:void 0);if(!a)throw new v(`config`,`Profile ${e} model '${t}' must set defaultEffort when more than one effort is declared`);if(!r[a])throw new v(`config`,`Profile ${e} model '${t}' defaultEffort '${a}' is not declared`);if(n.allowEffortSelect&&i.length<2)throw new v(`config`,`Profile ${e} model '${t}' allowEffortSelect requires at least two efforts`)}function W(e){return{providerContinuation:e.providerContinuation?ae.parse(e.providerContinuation):{},models:e.models,defaultModel:V(e.id,e),allowModelSelect:e.allowModelSelect,maxSteps:e.maxSteps}}function G(e,t,n){if(n?.length){for(let r of n)if(!i(r))throw new v(`config`,`Profile ${e}: turnBehaviour.resumption.${t} may only include ContinueStopKind (${le.join(` | `)}); got '${r}'`)}}function at(e,t){t&&(G(e,`allowContinue`,t.allowContinue),G(e,`autoContinue`,t.autoContinue))}function K(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ot(e,t){let n=[e];for(let e of t)n=n.flatMap(t=>K(t)?e===`*`?Object.values(t):[t[e]]:[]);return n}var st=Object.entries(oe).filter(([,e])=>e.required===!0).map(([e,t])=>[e,t.profileTypes]).sort(([e],[t])=>e.split(`.`).length-t.split(`.`).length);function ct(e){if(!K(e))throw new v(`config`,`Profile definition must be an object`);let t=typeof e.id==`string`&&e.id.trim()?e.id:void 0;if(!t)throw new v(`config`,`Profile definition must set id`);if(!_.find(t=>t===e.type))throw new v(`config`,`Profile ${t}: type must be one of ${_.join(`, `)}`)}function lt(e){let t=e.identity?.handle,n=[[`id`,e.id,64],[`identity.handle`,typeof t==`string`?t:``,32]];for(let[t,r,i]of n)if(!(Array.from(r).length<=i))throw new v(`config`,`Profile ${e.id.slice(0,64)}: ${t} must be at most ${i} characters`)}function ut(e){let{id:t,type:n}=e,r=e;for(let[e,i]of st){if(i&&!i.includes(n))continue;let o=a(e),s=ot(r,o.slice(0,-1)),c=o[o.length-1];if(s.some(e=>{if(!K(e))return!1;let t=e[c];return t==null||t===``}))throw new v(`config`,`Profile ${t}: type '${n}' must set ${o.join(`.`)}`)}}function dt(e){let{id:t,type:n}=e;if(n!==`live`&&te(`inputs`).includes(n)&&e.inputs==null)throw new v(`config`,`Profile ${t}: type '${n}' must set inputs`)}function ft(e){let[t]=me(e);if(!t)return;let{offValue:n,reason:r}=t.scope,i=n===void 0?``:` (other than ${n})`;throw new v(`config`,`Profile ${e.id}: type '${e.type}' must not set ${t.path}${i} — ${r}`)}function pt(e,t){let n=t.turnBehaviour;at(e,n?.resumption)}function mt(e,t){let n=t=>new v(`config`,`Profile ${e}: ${t}`),r=t?.maxRetries;if(r!==void 0&&(!Number.isInteger(r)||r<0))throw n(`outputs.validation.maxRetries must be a non-negative integer`)}function q(e,t){let n=t=>new v(`config`,`Profile ${e}: ${t}`),r=Object.keys(t??{}).find(e=>!J.includes(e));if(r!==void 0)throw n(`guardrails.${r} is not a setting; it takes ${J.join(`, `)}`);gt(t?.blockedReply,n)}var J=[`quota`,`detect`,`blockedReply`,`network`,`taint`],ht=[`onBlock`,`maxRetries`];function gt(e,t){if(e===void 0)return;let n=Object.keys(e).find(e=>!ht.includes(e));if(n!==void 0)throw t(`guardrails.blockedReply.${n} is not a setting; it takes onBlock and maxRetries`);let{onBlock:r,maxRetries:i}=e;if(r!==void 0&&!l.includes(r))throw t(`guardrails.blockedReply.onBlock must be one of ${l.join(`, `)}`);if(i!==void 0&&(!Number.isInteger(i)||i<0))throw t(`guardrails.blockedReply.maxRetries must be a non-negative integer`)}function _t(e){let t=e.guardrails?.detect,n=e.type===`host`?d(`guardrails.detect`,t,de):d(`guardrails.detect`,t);if(n!==void 0)throw new v(`config`,`Profile ${e.id}: ${n}`)}function Y(e,t){try{let n=be(t);if(!Number.isFinite(n.retainForDays))throw new v(`config`,`Profile ${e}: observability.retainForDays must be a finite number`);if(n.rotateAfterMiB<=0||!Number.isFinite(n.rotateAfterMiB))throw new v(`config`,`Profile ${e}: observability.rotateAfterMiB must be a positive number`)}catch(t){if(t instanceof v&&t.message.startsWith(`Profile `))throw t;let n=t instanceof Error?t.message:String(t);throw new v(o(t),`Profile ${e}: ${n}`,{cause:t})}}function vt(e){if(e.type===`host`||e.type===`decision`||e.type===`speech`||e.type===`transcription`||e.type===`embedding`)return;let{options:t,system:n}=e.identity,r=n??``;ge(r,`Profile ${e.id} identity.system`);let i=ve(r,t,e.inputs?.options);if(i)throw new v(`config`,`Profile ${e.id} identity.system: ${i}`)}function X(e){let t=yt(e),[n]=s(e);if(n)throw new v(`config`,`Profile ${e.id}: ${n.path} ${n.message}`);return t}function yt(e){ct(e);for(let t of[`key`,`fallbackKey`,`protocol`,`provider`])if(t in e)throw new v(`config`,c(`provider.profile_configuration`,{profile:e.id,field:t}));ft(e),dt(e),ut(e),lt(e),e.labels&&ie(e.labels,`Profile ${e.id}`);for(let t of ne)if(e.labels?.[t]!==void 0)throw new v(`config`,`Profile ${e.id}: labels '${t}' is a host line, which a profile cannot change; set it with overrideLabels`);if(vt(e),_t(e),e.type===`host`)return rt(e);if(e.type===`decision`)return nt(e);if(e.type===`embedding`)return Xe(e);if(e.type===`transcription`)return Ze(e);B(e.id,e.models),pt(e.id,e),q(e.id,e.guardrails),e.type===`text`&&mt(e.id,e.outputs?.validation),Y(e.id,e.observability);for(let[t,n]of Object.entries(e.models))H(e.id,t,n);let t=e.type===`speech`?{handle:e.identity.handle}:{handle:e.identity.handle,options:e.identity.options,system:e.identity.system},n=e.guardrails,r=e.observability,i=e.labels,a=W(e),o;switch(e.type){case`text`:o={type:`text`,id:e.id,identity:t,...a,tools:e.tools,inputs:e.inputs,outputs:e.outputs,turnBehaviour:e.turnBehaviour,guardrails:n,observability:r,labels:i};break;case`image`:o={type:`image`,id:e.id,identity:t,...a,image:e.image,tools:e.tools,inputs:e.inputs,outputs:e.outputs,turnBehaviour:e.turnBehaviour,guardrails:n,observability:r,labels:i},Tt(o.id,o.inputs.attachments?.accept),wt(o.id,o.image);break;case`speech`:o={type:`speech`,id:e.id,identity:t,...a,speech:e.speech,outputs:e.outputs,turnBehaviour:e.turnBehaviour,guardrails:n,observability:r,labels:i};break;case`live`:o={type:`live`,id:e.id,identity:t,...a,live:e.live,inputs:e.inputs,tools:{allow:e.tools.allow,...z(e.tools.parallel)},turnBehaviour:e.turnBehaviour,guardrails:n,observability:r,labels:i},xe(o),Dt(o.id,o.live.contextCompression),Et(o);break;default:throw new v(`config`,`Unknown profile type '${String(e)}'`)}return St(o),bt(o),xt(o),o}function bt(e){let{maxSteps:t}=e;if(!(t===void 0||Number.isInteger(t)&&t>0))throw new v(`config`,`Profile ${e.id}: maxSteps must be a whole number of 1 or more; leave it out for the default of 20`)}function xt(e){if(e.type===`text`&&e.turnBehaviour?.atStepLimit===`answer`&&e.maxSteps===1)throw new v(`config`,`Profile ${e.id}: turnBehaviour.atStepLimit 'answer' with maxSteps 1 leaves no step that can call a tool`)}function St(e){if(e.type===`live`)return;let t=e.outputs?.structured;if(!t||typeof t==`string`)return;let n=he(e,t.by);if(!n)throw new v(`config`,`Profile ${e.id}: outputs.structured.by '${t.by}' is not one of the profile's options`);let r=_e(n),i=Object.keys(t.map).filter(e=>!r.includes(e));if(i.length)throw new v(`config`,`Profile ${e.id}: outputs.structured.map maps ${i.join(`, `)}, not a choice of option '${t.by}'`)}var Ct={n:{ok:e=>Number.isInteger(e)&&e>=1,rule:`a whole number of 1 or more`},seed:{ok:Number.isInteger,rule:`a whole number`},outputCompression:{ok:e=>Number.isInteger(e)&&e>=0&&e<=100,rule:`a whole number from 0 to 100`}};function wt(e,t){for(let[n,{ok:r,rule:i}]of Object.entries(Ct)){let a=t[n];if(a!==void 0&&!r(a))throw new v(`config`,`Profile ${e}: image.${n} must be ${i}`)}t.references?.forEach((t,n)=>{let r=`Profile ${e}: image.references[${n}]`;if(se(t.mimeType)!==`image`)throw new v(`config`,`${r} must be an image, not '${t.mimeType}'`);if(!(x(t)?t.uri:t.data))throw new v(`config`,`${r} needs its bytes or its uri`)})}function Tt(e,t){let n=t?.filter(e=>!p(ue,e));if(n?.length)throw new v(`config`,`Profile ${e}: an image profile's attachments take images, video, and PDF only, not ${n.join(`, `)}`)}function Et(e){let{greeting:t,resumed:n,sessionResumption:r}=e.live,i=`Profile ${e.id} live`;if(t!==void 0&&(typeof t!=`string`||!t.trim()))throw new v(`config`,`${i}.greeting must be a prompt; leave it out to wait`);if(!n)return;if(typeof n.prompt!=`string`||!n.prompt.trim())throw new v(`config`,`${i}.resumed.prompt must be a prompt`);let{afterMs:a}=n;if(a!==void 0&&!(Number.isFinite(a)&&a>=0))throw new v(`config`,`${i}.resumed.afterMs must be 0 or more milliseconds`);if(!r)throw new v(`config`,`${i}.resumed needs live.sessionResumption: without it no call resumes`)}function Dt(e,t){if(!t)return;let n=`Profile ${e} live.contextCompression`,r=t.triggerTokens,i=t.slidingWindow.targetTokens;if(Z(`${n}.triggerTokens`,r),Z(`${n}.slidingWindow.targetTokens`,i),r!==void 0&&i!==void 0&&i>=r)throw new v(`config`,`${n}: slidingWindow.targetTokens must be below triggerTokens`)}function Z(e,t){if(!(t===void 0||Number.isInteger(t)&&t>0))throw new v(`config`,`${e} must be a whole number above 0`)}function Ot(e,t,n,r){let i=`Profile ${t.id} model ${n} compaction`;if(kt(i,r),At(i,r),r.profile===void 0){if(t.type!==`text`||t.inputs.text===!1)throw new v(`config`,`${i}: a profile that compacts itself must be a text profile that takes text`);return}let a=e.get(r.profile);if(!a)throw new v(`config`,`${i}: compaction profile '${r.profile}' must be registered before '${t.id}'`);if(a.type!==`text`||a.inputs.text===!1)throw new v(`config`,`${i}: compaction profile '${r.profile}' must be a text profile that takes text`)}function kt(e,t){if(t.maxTokens<=0)throw new v(`config`,`${e}: maxTokens must be > 0`);if(t.compactAt<=0||t.compactAt>=1)throw new v(`config`,`${e}: compactAt must be in (0, 1)`)}function At(e,t){if(t.previousExchanges<0)throw new v(`config`,`${e}: previousExchanges must be >= 0`);if(t.previousExchanges<1&&t.previousExchanges>=t.compactAt)throw new v(`config`,`${e}: previousExchanges as fraction (${t.previousExchanges}) must be < compactAt (${t.compactAt})`);if(t.previousExchanges>1&&!Number.isInteger(t.previousExchanges))throw new v(`config`,`${e}: previousExchanges >= 1 must be an integer`)}function jt(e,t){for(let n of y(t))if(e.get(n)?.type===`builtin`)throw new v(`config`,t.type===`host`?`Profile ${t.id} lists builtin '${n}' in tools.allow — type 'host' never runs a model`:`Profile ${t.id} lists builtin '${n}' in tools.allow — declare it on models.*.builtInTools instead`)}function Mt(e,t){let n=ye(t)?.t2Loader;if(n){if(!y(t).includes(n))throw new v(`config`,`Profile ${t.id} tools.t2Loader '${n}' must also be listed in tools.allow`);if(e.get(n)?.type!==`function`)throw new v(`config`,`Profile ${t.id} tools.t2Loader '${n}' must be a registered type: 'function' tool`)}}function*Nt(e){for(let[t,n]of Object.entries(e.models))for(let e of n.builtInTools??[])yield{modelId:t,id:e}}function Pt(e,t){for(let{modelId:n,id:r}of Nt(t))if(e.get(r)?.type!==`builtin`)throw new v(`config`,`Profile ${t.id} model '${n}' lists '${r}' in builtInTools — not a registered builtin`)}function Ft(e){let t=e.type===`text`?e.outputs?.structured:void 0;return t?typeof t==`string`?[t]:[...new Set([...Object.values(t.map),t.fallback])]:[]}function It(e,t){let n=Ft(t).map(n=>{let r=e.find(n);if(!r)throw new v(`config`,`Profile ${t.id}: outputs.structured names '${n}', which is not a registered schema; register it before the profile`);return r}),r=t.type===`text`?t.outputs?.validation:void 0,i=Object.keys(r?.fields??{}),a=Object.keys(r?.items??{});if(!i.length&&!a.length)return;if(!n.length)throw new v(`config`,`Profile ${t.id}: outputs.validation checks a structured reply, so it needs outputs.structured`);let o=a.filter(e=>!n.some(t=>R(t.jsonSchema,e)));if(o.length)throw new v(`config`,`Profile ${t.id}: outputs.validation.items has ${o.join(`, `)}, which no structured schema reaches as a list with an items schema`);let s=i.filter(e=>!n.some(t=>Ke(t.jsonSchema,e)));if(s.length)throw new v(`config`,`Profile ${t.id}: outputs.validation.fields has ${s.join(`, `)}, which no structured schema reaches through object properties`)}function Lt(e){let t=h(e)?.context;if(!t)return;let n=f;if(t.from.length===0||t.from.some(e=>!n.includes(e)))throw new v(`config`,`Profile ${e.id}: inputs.context.from must list ${f.join(` or `)}`);if(!(Number.isInteger(t.maxChars)&&t.maxChars>0))throw new v(`config`,`Profile ${e.id}: inputs.context.maxChars must be a positive integer`)}function Q(e,t){if(!t)return;let{attachments:n,voice:r,maxFiles:i,maxBytes:a,maxTurnBytes:o,limitsByMime:s}=t,c={maxFiles:i,maxBytes:a,maxTurnBytes:o};if((n||r)&&Object.values(c).some(e=>e===void 0))throw new v(`config`,`Profile ${e} must set maxFiles, maxBytes, and maxTurnBytes`);for(let[e,t]of Object.entries(s??{}))c[`limitsByMime['${e}']`]=t;for(let[t,n]of Object.entries(c))if(n!==void 0&&!(Number.isInteger(n)&&n>0))throw new v(`config`,`Profile ${e}: inputs.${t} must be a positive integer`)}function Rt(e,t,n){let r=new Map,i=i=>{let a=X(i),o=n&&a.type!==`host`?{...a,models:Object.fromEntries(Object.entries(a.models).map(([e,t])=>[e,ee(n.require(t.provider,t.apiId),t,a.type)]))}:a;if(jt(e,o),Mt(e,o),o.type!==`host`&&o.type!==`decision`&&o.type!==`embedding`){Pt(e,o),Q(o.id,h(o)),Lt(o),It(t,o);for(let[e,t]of Object.entries(o.models))t.compaction&&Ot(r,o,e,t.compaction)}r.set(o.id,o)};return{register:i,registerMany(e){for(let t of e)i(t)},get(e){let t=r.get(e);if(!t)throw new v(`config`,`Unknown profile '${e}'`);return t},find:e=>r.get(e),has:e=>r.has(e),list:()=>[...r.values()],clear:()=>r.clear()}}function zt(e){let t=e?.trim()??``;if(t.startsWith(`AIza`))return`gemini`;if(t.startsWith(`sk-or-`))return`openrouter`}function Bt(e){let t;try{t=new URL(e.baseUrl)}catch{throw new v(`config`,`Enter a valid localhost URL.`)}if(![`http:`,`https:`].includes(t.protocol)||![`localhost`,`127.0.0.1`,`[::1]`].includes(t.hostname)||t.username||t.password||t.search||t.hash)throw new v(`config`,`Use a localhost URL without credentials, query parameters or a fragment.`);return{baseUrl:t.href.replace(/\/$/,``),fetch:(e,n)=>new URL(e instanceof Request?e.url:String(e)).origin===t.origin?fetch(e,{...n,redirect:`error`,credentials:`omit`}):Promise.reject(new v(`blocked`,`Local requests must stay on the configured origin.`))}}var Vt=n({data:t(n({id:e().min(1)}))});async function Ht(e,t){let n=Bt(e);if(!n?.fetch)throw new v(`config`,`Enter a local endpoint.`);let r=await n.fetch(`${n.baseUrl}/v1/models`,{signal:t,headers:{Accept:`application/json`}});if(!r.ok)throw new v(`network`,`Local model list returned HTTP ${r.status}.`);let i=Vt.safeParse(await r.json());if(!i.success)throw new v(`request`,`The endpoint returned an invalid model list.`);return[...new Set(i.data.data.map(e=>e.id))]}var Ut=`https://openrouter.ai/api/v1/models`,Wt=`https://openrouter.ai/api/v1/embeddings/models`,Gt=[{id:`gemini-embedding-2-preview`,label:`Gemini Embeddings 2 (preview)`},{id:`gemini-embedding-001`,label:`Gemini Embedding 001`}],Kt=[{id:`liquid/lfm-2.5-embedding-350m:free`,label:`Liquid LFM 2.5 Embedding 350M (free)`},{id:`nvidia/nemotron-3-embed-1b:free`,label:`NVIDIA Nemotron 3 Embed 1B (free)`},{id:`nvidia/llama-nemotron-embed-vl-1b-v2:free`,label:`NVIDIA Llama Nemotron Embed VL 1B v2 (free)`}],qt={text:`text`,image:`image`,speech:`speech`,transcription:`transcription`,live:void 0,embedding:void 0},Jt=n({data:t(n({id:e().min(1),name:e().optional(),architecture:n({output_modalities:t(e()).optional()}).optional()}))}),Yt=n({data:t(n({id:e().min(1),name:e().optional()}))}),Xt=n({models:t(n({name:e().min(1),displayName:e().optional(),supportedGenerationMethods:t(e()).optional()})).optional(),nextPageToken:e().optional()}),Zt=5;async function $(e,t,n){let r=await fetch(t,{...n,redirect:`error`,credentials:`omit`});if(r.status===400||r.status===401||r.status===403)throw new v(`auth`,`${e} refused the key.`);if(!r.ok)throw new v(`network`,`${e} model list returned HTTP ${r.status}.`);return await r.json()}async function Qt(e,t,n,r){let i=n?.trim();if(t===`embedding`&&!i)return[...e===`openrouter`?Kt:Gt];if(e===`openrouter`)return await $t(t,i,r);if(!i)throw new v(`auth`,`Choose a key to list Gemini models.`);return await tn(t,i,r)}async function $t(e,t,n){let r={signal:n,headers:{Accept:`application/json`,...t?{Authorization:[`Bearer`,t].join(` `)}:{}}};if(e===`embedding`){let e=Yt.safeParse(await $(`OpenRouter`,Wt,r));if(!e.success)throw new v(`bad_response`,`OpenRouter returned an invalid embedding model list.`);return e.data.data.map(e=>({id:e.id,label:e.name??e.id}))}let i=qt[e];if(!i)return[];let a=Jt.safeParse(await $(`OpenRouter`,`${Ut}?output_modalities=${i}`,r));if(!a.success)throw new v(`bad_response`,`OpenRouter returned an invalid model list.`);return a.data.data.filter(e=>e.architecture?.output_modalities?.includes(i)??!0).map(e=>({id:e.id,label:e.name??e.id}))}var en={live:`bidiGenerateContent`,embedding:`embedContent`};async function tn(e,t,n){let i=en[e]??`generateContent`,a=[],o;for(let e=0;e<Zt;e++){let e=new URL(r);e.searchParams.set(`pageSize`,`1000`),o&&e.searchParams.set(`pageToken`,o);let s=Xt.safeParse(await $(`Google`,e.href,{signal:n,headers:{Accept:`application/json`,"x-goog-api-key":t}}));if(!s.success)throw new v(`bad_response`,`Google returned an invalid model list.`);for(let e of s.data.models??[]){if(!e.supportedGenerationMethods?.includes(i))continue;let t=e.name.replace(/^models\//,``);a.push({id:t,label:e.displayName??t})}if(o=s.data.nextPageToken,!o)break}return a}function nn(e){return[...new Set([e.key,e.fallbackKey,...Object.values(e.models??{}).flatMap(e=>[e.keySlot,e.fallbackKeySlot])].filter(e=>!!e))]}function rn(e,t){return Object.fromEntries(e.map(e=>[e,Object.hasOwn(t,e)?t[e]:void 0]))}export{Ve as S,Ie as _,nn as a,x as b,X as c,qe as d,R as f,Re as g,O as h,Bt as i,Je as l,L as m,Ht as n,rn as o,I as p,Qt as r,Rt as s,zt as t,Ge as u,w as v,b as x,T as y};