@theoremjs/studio 0.3.4-next.731.g189a95d → 0.3.4-next.733.g0520b79

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 (42) hide show
  1. package/cookbooks/sources.js +8 -4
  2. package/package.json +4 -4
  3. package/page/assets/{Banner-WNqr2yCF.js → Banner-DQKrIFWf.js} +3 -3
  4. package/page/assets/{ConsoleFrame-B1bqVn4G.js → ConsoleFrame-Wp3BTrp2.js} +1 -1
  5. package/page/assets/{MenuBottomSheet-OS5OKbhf.js → MenuBottomSheet-CNkEqMTY.js} +1 -1
  6. package/page/assets/{SchemaFields-CXLZbi--.js → SchemaFields-9IqN6I21.js} +1 -1
  7. package/page/assets/{ToolResultCharts-DV7gLwNL.js → ToolResultCharts-Bw4xs9nI.js} +1 -1
  8. package/page/assets/{TraceInspector-CQMH5heH.js → TraceInspector-DoFUSkVL.js} +1 -1
  9. package/page/assets/{TraceOverview-C1GNUfl_.js → TraceOverview-wd3yXtB6.js} +1 -1
  10. package/page/assets/{_virtual_studio-type-sources-CUVY6pAU.js → _virtual_studio-type-sources-MW25ShGl.js} +26 -5
  11. package/page/assets/{browser-connection-IC3QKsFq.js → browser-connection-a8Bk27jZ.js} +2 -2
  12. package/page/assets/browser-engine-BnOeaKVs.js +16 -0
  13. package/page/assets/{browser-transport-BCDOmlL6.js → browser-transport-ptuvI9AO.js} +3 -3
  14. package/page/assets/{crypto-DjhcOJmp.js → crypto-D2c07scB.js} +1 -1
  15. package/page/assets/{encode-files-BF1rsZES.js → encode-files-D70Gn7wT.js} +1 -1
  16. package/page/assets/{export-agent-igFjv0RF.js → export-agent-nl1hJr1f.js} +1 -1
  17. package/page/assets/{guardrail-tester-B3f3FHxl.js → guardrail-tester-RjCP9FIV.js} +1 -1
  18. package/page/assets/{index-DqQozW4e.js → index-B7otLQ2d.js} +7 -7
  19. package/page/assets/{live-messages-ConwEl7T.js → live-messages-DkEHq8VK.js} +1 -1
  20. package/page/assets/{reader-Ql1nrrAA.js → reader-zKIQ-g2z.js} +4 -4
  21. package/page/assets/{shaped-data-BRffby3g.js → shaped-data-DA7qODSD.js} +2 -2
  22. package/page/assets/{stub-U8WThytR.js → stub-BhSqKDat.js} +1 -1
  23. package/page/assets/{studio-code-pane-2QGVHbuQ.js → studio-code-pane-BiNzaafk.js} +3 -3
  24. package/page/assets/{studio-console-CIxC-kxg.js → studio-console-6yiL1kmd.js} +1 -1
  25. package/page/assets/{studio-decision-CCWhiKUC.js → studio-decision-DLjvjNri.js} +1 -1
  26. package/page/assets/{studio-embedding-D2Ws0QQV.js → studio-embedding-COsi333A.js} +1 -1
  27. package/page/assets/{studio-host-console-B_Dfb6LS.js → studio-host-console-ObLnNOnt.js} +2 -2
  28. package/page/assets/{studio-labels-iVEd2v7z.js → studio-labels-BTl6Rqu5.js} +1 -1
  29. package/page/assets/{studio-live-OtB0C2Rm.js → studio-live-MQhG66Xz.js} +1 -1
  30. package/page/assets/{studio-map-DozGHVh3.js → studio-map-DQhfj2Sl.js} +1 -1
  31. package/page/assets/{studio-trace-replay-CsYUrLS_.js → studio-trace-replay-BoFlsfdT.js} +1 -1
  32. package/page/assets/{studio-type-checker-BpnhAgSR.js → studio-type-checker-b95brWbQ.js} +1 -1
  33. package/page/assets/tool-schema-DuHTHSTd.js +19 -0
  34. package/page/assets/{trace-record-Doo6lYDI.js → trace-record-S_zZ4kQP.js} +1 -1
  35. package/page/assets/{tree-DveW6zCH.js → tree-DT3AX2ou.js} +1 -1
  36. package/page/assets/{turn-client-D36i6KKG.js → turn-client-YxD9bIq7.js} +2 -2
  37. package/page/assets/{use-one-call-CpSFtvZZ.js → use-one-call-Cp32Q3b_.js} +1 -1
  38. package/page/assets/{use-second-ticker-sszFj3Ez.js → use-second-ticker-CU80-r-e.js} +1 -1
  39. package/page/assets/{workspace-BmMSRE4E.js → workspace-D77o7YPN.js} +1 -1
  40. package/page/index.html +15 -15
  41. package/page/assets/browser-engine-uuanEizS.js +0 -13
  42. package/page/assets/tool-schema-BHHcOFff.js +0 -17
@@ -5220,7 +5220,7 @@ import type { CacheMode, CacheTtl, CompactionMeter, CompactionOutcome, Compactio
5220
5220
  import type { StageHandler } from './stages.js';
5221
5221
  import type { ToolBackgroundService } from './tools/background.js';
5222
5222
  import type { GateDecision } from './tools/gate-answer.js';
5223
- import type { PageToolExecution, ToolExecutionCoordinator } from './tools/operation.js';
5223
+ import type { PageToolExecution, ToolExecutionCoordinator, ToolOperationOutcome } from './tools/operation.js';
5224
5224
  import type { AgentCall, AgentCallHook, AgentCallRequest, AgentToolDef, AgentToolInput, AgentToolOutput, HostProfileToolsSpec, InvokeToolRequest, InvokeToolResume, InvokeToolStepCall, InvokeToolStepRequest, LiveProfileToolsSpec, ModelToolResult, PageAnswer, ProfileToolsSpec, RegisteredTool, ToolCallEvent, ToolFailure, ToolGate, ToolLoadContext, ToolPolicy, TurnToolSnapshot, WireFunctionTool } from './tools/types.js';
5225
5225
  import type { AttemptReason, CallDone, CompactionFailure, CompactionResult, CompactionSignal, DoneFields, GroundingEvent, InjectedMessages, InteractionMediaPart, InteractionMediaRefPart, InteractionPart, InteractionTextPart, InvalidField, ModelEvent, ProviderEvidence, RemovedItem, SessionEnded, SessionEvent, SessionEventKind, SessionEventOf, Source, TurnCost, TurnEvent, TurnEventOf, TurnEventType, TurnGroundingCount, TurnHistoryMessage, TurnResponse, TurnTokenSide, TurnTokens } from './turn-events.js';
5226
5226
  export type { AgentCall, AgentCallHook, AgentCallRequest, AgentToolDef, AgentToolInput, AgentToolOutput, AttemptReason, CacheMode, CacheTtl, CallDone, CompactionFailure, CompactionMeter, CompactionOutcome, CompactionResult, CompactionSignal, CompactionTiming, ContinueStopKind, DoneFields, FieldMeta, GroundingEvent, HostProfileToolsSpec, InjectedMessages, InteractionMediaPart, InteractionMediaRefPart, InteractionPart, InteractionTextPart, InvalidField, InvokeToolRequest, InvokeToolResume, InvokeToolStepCall, InvokeToolStepRequest, KeySlot, KeyVault, LiveActivityHandling, LiveEndSensitivity, LiveProfileToolsSpec, LiveStartSensitivity, MediaInputKind, ModelEvent, ProfileToolsSpec, ProfileType, ProviderEvidence, RegisteredTool, RemovedItem, SessionEnded, SessionEvent, SessionEventKind, SessionEventOf, Source, SpeechAudioFormat, StreamMode, SummaryMode, ThinkingLevel, ToolCallEvent, ToolFailure, ToolGate, ToolLoadContext, ToolLoadTier, ToolPolicy, TurnCost, TurnEvent, TurnEventOf, TurnEventType, TurnGroundingCount, TurnHistoryMessage, TurnResponse, TurnStage, TurnStopKind, TurnTokenSide, TurnTokens, TurnToolSnapshot, WireFunctionTool, };
@@ -5953,6 +5953,8 @@ export interface TurnInput {
5953
5953
  attachments?: Array<TurnBlob | TurnMediaRef>;
5954
5954
  voice?: TurnBlob[];
5955
5955
  history?: TurnHistoryMessage[];
5956
+ /** Tool calls that settled after their turn, as the host stored them. Each counts as read in this reply. */
5957
+ lateResults?: ToolOperationOutcome[];
5956
5958
  repair?: TurnRepairRequest;
5957
5959
  /**
5958
5960
  * Optional host-supplied history token count for \`meter: 'history'\`.
@@ -7976,7 +7978,7 @@ export { applySpans, blobAt, mergeSpans, OMIT_CANARY, OMIT_INJECTION, OMIT_PROMP
7976
7978
  `,"file:///node_modules/@theoremjs/agents/src/guardrails/labels.d.ts":`/** Values that fill a label template's \`{param}\` placeholders. */
7977
7979
  export type LabelParams = Record<string, string | number>;
7978
7980
  /** Keys are stable API. */
7979
- 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", "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.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.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", "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.after_field", "tool.background_field", "tool.background_started", "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"];
7981
+ 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", "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.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.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", "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.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"];
7980
7982
  /** One of {@linkcode LABEL_KEYS}. */
7981
7983
  export type LabelKey = (typeof LABEL_KEYS)[number];
7982
7984
  /**
@@ -10053,6 +10055,11 @@ declare function addResultDestinations(turn: TurnDestinations, result: {
10053
10055
  finding: string;
10054
10056
  data?: unknown;
10055
10057
  }, provenance: Provenance): void;
10058
+ /**
10059
+ * Notes a remote result read back from its fence. \`composeToolText\` put any \`data\` on the last
10060
+ * line, and without it a field reads as running text, which is the stricter way.
10061
+ */
10062
+ declare function addFencedDestinations(turn: TurnDestinations, text: string, provenance: Provenance): void;
10056
10063
  /** A call's verdict, and what an approval card says when the profile asks the user first. */
10057
10064
  interface DestinationVerdict {
10058
10065
  verdict: Verdict;
@@ -10065,7 +10072,7 @@ interface DestinationVerdict {
10065
10072
  */
10066
10073
  declare function checkDestinationGate(turn: TurnDestinations | undefined, args: unknown, policy: ResolvedGuardrailPolicy, labels?: LabelOverrides): DestinationVerdict;
10067
10074
  export type { DestinationVerdict, TurnDestinations };
10068
- export { addGivenDestinations, addHistoryDestinations, addRequestDestinations, addResultDestinations, checkDestinationGate, turnDestinations, };
10075
+ export { addFencedDestinations, addGivenDestinations, addHistoryDestinations, addRequestDestinations, addResultDestinations, checkDestinationGate, turnDestinations, };
10069
10076
  `,"file:///node_modules/@theoremjs/agents/src/kernel/tools/gate-answer.d.ts":`import type { ApiKeyCredential, BearerCredential } from '../auth/types.js';
10070
10077
  import type { ToolPermission } from '../schema.js';
10071
10078
  import type { ToolAuthChallenge } from '../turn-events.js';
@@ -11232,6 +11239,7 @@ export { askUserTool, registerHarnessTools };
11232
11239
  `,"file:///node_modules/@theoremjs/agents/src/kernel/tools/execute.d.ts":`import { type ToolBoundary } from '../../guardrails/boundaries.js';
11233
11240
  import { type DetectScope } from '../../guardrails/detect-at.js';
11234
11241
  import { type LabelOverrides } from '../../guardrails/labels.js';
11242
+ import type { ToolOrigin } from '../../guardrails/types.js';
11235
11243
  import type { SpanHandle, TraceAttributes } from '../../observability/trace-span.js';
11236
11244
  import { type ToolCallEnd } from '../engine/tool-trace.js';
11237
11245
  import type { InjectUnit } from '../stages.js';
@@ -11242,8 +11250,9 @@ import { startToolExecution, type ToolCallBase } from './events.js';
11242
11250
  import type { ToolExecutionCoordinator, ToolOperationClaim, ToolOperationOutcome } from './operation.js';
11243
11251
  import type { ToolRegistry } from './registry.js';
11244
11252
  import { type ToolStageSupport } from './stage-run.js';
11245
- import type { FunctionToolDef, ModelToolResult, RegisteredAgentTool, ToolContext, ToolFailure, ToolGate, TurnToolSnapshot } from './types.js';
11253
+ import type { FunctionToolDef, ModelToolResult, RegisteredAgentTool, RegisteredTool, ToolContext, ToolFailure, ToolGate, TurnToolSnapshot } from './types.js';
11246
11254
  export { checkPermission, isGateResumeGranted, isResumeContinuation, permissionGranted, } from './permission.js';
11255
+ export declare function originOfTool(tool: RegisteredTool, tools: ToolRegistry): ToolOrigin;
11247
11256
  /**
11248
11257
  * The boundary a call of \`name\` is read at before its tool gets it: none for a provider builtin,
11249
11258
  * whose text the kernel never reads. A call no tool takes is read as a function tool's.
@@ -12450,6 +12459,18 @@ declare function isRemoteOrigin(origin: ToolOrigin): boolean;
12450
12459
  * friendlier provenance than it has by writing one into its own body.
12451
12460
  */
12452
12461
  declare function wrapToolData(text: string, provenance: Provenance, advisory?: AdvisoryLevel, labels?: LabelOverrides): string;
12462
+ /** What a fence from \`wrapToolData\` says of the text inside it. */
12463
+ export interface ToolDataRead {
12464
+ provenance: Provenance;
12465
+ suspicious: GuardrailHit[];
12466
+ /** The result as \`composeToolText\` joined it. */
12467
+ text: string;
12468
+ }
12469
+ /**
12470
+ * Reads the fence at the start of a tool message. \`stripToolFences\` has taken any forged tag out of
12471
+ * the body, so what the tag says is the kernel's. \`undefined\` when \`content\` is not one whole fence.
12472
+ */
12473
+ declare function readToolData(content: string): ToolDataRead | undefined;
12453
12474
  /** A tool result after the guard: the text the model sees, any event, and the suspicious hits. */
12454
12475
  export interface GuardedToolText {
12455
12476
  /** Absent when a match blocks: the model does not read the text. */
@@ -12528,7 +12549,7 @@ declare function isSuspicious(taint: TurnTaint | undefined): boolean;
12528
12549
  * or not enforcement is configured, so the risk is visible before a host opts in.
12529
12550
  */
12530
12551
  declare function checkTaintGate(taint: TurnTaint | undefined, access: string, policy: ResolvedGuardrailPolicy, labels?: LabelOverrides): Verdict;
12531
- export { checkTaintGate, composeToolText, guardShownValue, guardToolFailureText, guardToolResult, inspectToolArguments, isRemoteOrigin, isSuspicious, isTainted, recordTaint, TOOL_CLOSE, toolCallEvent, wrapToolData, };
12552
+ export { checkTaintGate, composeToolText, guardShownValue, guardToolFailureText, guardToolResult, inspectToolArguments, isRemoteOrigin, isSuspicious, isTainted, readToolData, recordTaint, TOOL_CLOSE, toolCallEvent, wrapToolData, };
12532
12553
  `,"file:///node_modules/@theoremjs/agents/src/guardrails/tool-directives.d.ts":`import type { AdvisoryLevel } from './types.js';
12533
12554
  /**
12534
12555
  * What of a tool's text reads as an instruction to the agent: an order to set its instructions
@@ -1,3 +1,3 @@
1
- import{A as e,D as t,E as n,O as r,T as i,b as a,c as o,d as s,f as c,x as l}from"./schemas-D7cgkv3L.js";import{Ct as u,Et as ee,Gn as te,H as ne,Sn as d,Un as re,Vn as ie,Wt as ae,Yt as oe,bn as f,cn as se,dn as ce,er as le,ln as ue,wn as p,wt as de,xn as fe,yn as pe}from"./tool-schema-BHHcOFff.js";import{c as m}from"./host-patterns-F-KZIzkF.js";import{A as me,Lr as h,Mn as he,Nn as ge,Nr as _e,Rr as ve,Un as ye,an as be,er as xe,fn as Se,jn as Ce,lr as g,pn as we,tn as _,tr as Te,vn as v,vr as Ee,wr as De}from"./shaped-data-BRffby3g.js";import{a as Oe,n as ke}from"./live-ingress-OuSlQ6q7.js";var Ae=2,je=4,Me=3,Ne=/(^|,)(\s*)("?)(?:([=@])|([+-])(?![0-9."]))/gm,Pe=/^[A-Za-z0-9+/]*={0,2}$/,Fe=new Set([`text/csv`,`text/plain`,`text/markdown`]);function y(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 Ie(e,t){if(t.limitsByMime){let n=p(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 b(e){return`uri`in e}function Le(e){if(e.type===`speech`)throw new m(`request`,`Profile ${e.id} (speech) does not accept media input`);if(e.type===`live`)throw new m(`request`,`Profile ${e.id} (live) does not accept turn attachment input`);if(e.type===`host`||e.type===`decision`||e.type===`embedding`)throw new m(`request`,`Profile ${e.id} (${e.type}) does not accept turn input`);let t=y(e.inputs??{});if(!t)throw new m(`config`,`Profile ${e.id} must set maxFiles, maxBytes, and maxTurnBytes`);return t}function Re(e){let t=0;return e.endsWith(`==`)?t=Ae:e.endsWith(`=`)&&(t=1),Math.floor(e.length*Me/je)-t}function ze(e){try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(e)}catch{return new TextDecoder(`latin1`).decode(e)}}function Be(e){return e.replace(Ne,(e,...t)=>{let[n,r,i,a,o]=t;return`${n}${r}${i}'${a??``}${o??``}`})}function Ve(e,t,n){let r=ze(t);return e===`text/csv`&&(r=Be(r)),new TextEncoder().encode(n.read(r))}function x(e,t){return t?{...e,fileName:t}:e}function S(e,t,n){return t.filter(t=>!f(e,t.mimeType)).map(e=>x({code:`mime_not_allowed`,params:{mimeType:e.mimeType,channel:n}},e.name))}function He(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=Ie(i.mimeType,t);i.sizeBytes>e&&n.push(x({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 C(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(...S(e.attachments,t,`attachment`)),e.voice&&r.push(...S(e.voice,n,`voice`)),e.limits?[...r,...He([...t,...n],e.limits)]:[...r,{code:`limits_unconfigured`}])}var Ue={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 w(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:Ue[e.code],params:t}}function We(e,t){let n=w(e);return h(n.key,n.params,t)}function Ge(e){return new m(`input`,`attachments refused: ${e.map(e=>e.code).join(`, `)}`,{copy:e.map(w)})}function Ke(e){if(!Pe.test(e))throw new m(`request`,`attachment data must be base64`);return Re(e)}function qe(e){let t={mimeType:e.mimeType,name:e.name};return b(e)||(t.sizeBytes=Ke(e.data)),t}function Je(e,t,n){if(!Xe(t,n))return;let r=Le(e),i=C({attachments:fe(e,`attachments`),voice:fe(e,`voice`),limits:r},(t??[]).map(qe),(n??[]).map(qe));if(i.length>0)throw Ge(i)}function Ye(e,t){if(b(e))return e;let{mimeType:n,data:r}=e;if(!Fe.has(p(n)))return e;let i=Ve(n,xe(r),t);return{...e,data:Te(i)}}function Xe(e,t){return(e?.length??0)>0||(t?.length??0)>0}function Ze(e,t,n,r){return Je(e,t,n),{attachments:t?.length?t.map(e=>Ye(e,r.attachment)):t,voice:n?.length?n.map(e=>Ye(e,r.voice)):n}}var Qe=`
1
+ import{A as e,D as t,E as n,O as r,T as i,b as a,c as o,d as s,f as c,x as l}from"./schemas-D7cgkv3L.js";import{Ct as u,Et as ee,Gn as te,H as ne,Sn as d,Un as re,Wt as ie,Yt as ae,bn as f,cn as oe,dn as se,ln as ce,nr as le,qn as ue,wn as p,wt as de,xn as fe,yn as pe}from"./tool-schema-DuHTHSTd.js";import{c as m}from"./host-patterns-F-KZIzkF.js";import{A as me,Lr as h,Mn as he,Nn as ge,Nr as _e,Rr as ve,Un as ye,an as be,er as xe,fn as Se,jn as Ce,lr as g,pn as we,tn as _,tr as Te,vn as v,vr as Ee,wr as De}from"./shaped-data-DA7qODSD.js";import{a as Oe,n as ke}from"./live-ingress-OuSlQ6q7.js";var Ae=2,je=4,Me=3,Ne=/(^|,)(\s*)("?)(?:([=@])|([+-])(?![0-9."]))/gm,Pe=/^[A-Za-z0-9+/]*={0,2}$/,Fe=new Set([`text/csv`,`text/plain`,`text/markdown`]);function y(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 Ie(e,t){if(t.limitsByMime){let n=p(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 b(e){return`uri`in e}function Le(e){if(e.type===`speech`)throw new m(`request`,`Profile ${e.id} (speech) does not accept media input`);if(e.type===`live`)throw new m(`request`,`Profile ${e.id} (live) does not accept turn attachment input`);if(e.type===`host`||e.type===`decision`||e.type===`embedding`)throw new m(`request`,`Profile ${e.id} (${e.type}) does not accept turn input`);let t=y(e.inputs??{});if(!t)throw new m(`config`,`Profile ${e.id} must set maxFiles, maxBytes, and maxTurnBytes`);return t}function Re(e){let t=0;return e.endsWith(`==`)?t=Ae:e.endsWith(`=`)&&(t=1),Math.floor(e.length*Me/je)-t}function ze(e){try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(e)}catch{return new TextDecoder(`latin1`).decode(e)}}function Be(e){return e.replace(Ne,(e,...t)=>{let[n,r,i,a,o]=t;return`${n}${r}${i}'${a??``}${o??``}`})}function Ve(e,t,n){let r=ze(t);return e===`text/csv`&&(r=Be(r)),new TextEncoder().encode(n.read(r))}function x(e,t){return t?{...e,fileName:t}:e}function S(e,t,n){return t.filter(t=>!f(e,t.mimeType)).map(e=>x({code:`mime_not_allowed`,params:{mimeType:e.mimeType,channel:n}},e.name))}function He(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=Ie(i.mimeType,t);i.sizeBytes>e&&n.push(x({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 C(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(...S(e.attachments,t,`attachment`)),e.voice&&r.push(...S(e.voice,n,`voice`)),e.limits?[...r,...He([...t,...n],e.limits)]:[...r,{code:`limits_unconfigured`}])}var Ue={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 w(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:Ue[e.code],params:t}}function We(e,t){let n=w(e);return h(n.key,n.params,t)}function Ge(e){return new m(`input`,`attachments refused: ${e.map(e=>e.code).join(`, `)}`,{copy:e.map(w)})}function Ke(e){if(!Pe.test(e))throw new m(`request`,`attachment data must be base64`);return Re(e)}function qe(e){let t={mimeType:e.mimeType,name:e.name};return b(e)||(t.sizeBytes=Ke(e.data)),t}function Je(e,t,n){if(!Xe(t,n))return;let r=Le(e),i=C({attachments:fe(e,`attachments`),voice:fe(e,`voice`),limits:r},(t??[]).map(qe),(n??[]).map(qe));if(i.length>0)throw Ge(i)}function Ye(e,t){if(b(e))return e;let{mimeType:n,data:r}=e;if(!Fe.has(p(n)))return e;let i=Ve(n,xe(r),t);return{...e,data:Te(i)}}function Xe(e,t){return(e?.length??0)>0||(t?.length??0)>0}function Ze(e,t,n,r){return Je(e,t,n),{attachments:t?.length?t.map(e=>Ye(e,r.attachment)):t,voice:n?.length?n.map(e=>Ye(e,r.voice)):n}}var Qe=`
2
2
 
3
- `;function $e(e){if(typeof e==`string`)return;if(typeof e!=`object`||!e||Array.isArray(e))return`must be a string or { private: string }`;let t=Object.keys(e);if(t.length!==1||t[0]!==`private`)return`must have exactly one key, private`;let n=e.private;if(typeof n!=`string`)return`must be a string`;if(n===``)return`must not be empty`}function et(e,t){if(typeof e!=`string`){if(!Array.isArray(e))return`${t} must be a string or an array of parts`;if(e.length===0)return`${t} must not be an empty array`;for(let[n,r]of e.entries()){let e=$e(r);if(e)return`${t}[${n}]${typeof r==`object`&&r&&`private`in r?`.private`:``} ${e}`}}}function tt(e,t){let n=et(e,t);if(n)throw new m(`config`,n)}function nt(e,t,n){return tt(e,t),typeof e==`string`?n(e):e.map(e=>typeof e==`string`?n(e):{private:n(e.private)})}function rt(e){if(typeof e==`string`)return[{text:e,private:!0}];let t=e.some(e=>typeof e!=`string`);return e.map(e=>typeof e==`string`?{text:e,private:!t}:{text:e.private,private:!0})}function it(e){let t=[];for(let n of e)n.some(e=>e.text)&&(t.length>0&&t.push({text:Qe,private:!0}),t.push(...n));return t}function at(e){return e.map(e=>e.text).join(``)}function ot(e){let t=[],n=``;for(let r of e)r.private?n+=r.text:(n.trim()&&t.push(n),n=``);return n.trim()&&t.push(n),{text:at(e),private:t}}function st(e,t){return ot(it([e,...t.map(e=>e?[{text:e,private:!0}]:[])]))}function T(e){let t=Object.keys(e);return t.length===1?t[0]:void 0}var ct=/^[A-Za-z_][\w-]*$/,lt=/^\S+$/;function ut(e){return typeof e==`string`?[[e]]:e.map(e=>typeof e==`string`?[e]:e)}function dt(e){return typeof e==`string`?e:e.private}function E(e){return ee(e[0]===void 0?``:dt(e[0]))}function ft(e,t){let n={};for(let[r,i]of Object.entries({...e,...t}))n[r]={type:`string`,enum:[...i]};return{type:`object`,properties:n}}function pt(e,t){for(let[n,r]of Object.entries(e??{})){if(!ct.test(n))return`Condition "${n}" needs a plain name.`;if(n===`input`||n===`output`)return`Condition "${n}" is a reserved name.`;if(Object.hasOwn(t,n))return`"${n}" is both a condition and a slot.`;if(r.length===0)return`Condition "${n}" lists no values.`;let e=r.find(e=>!lt.test(e)||e===`null`);if(e!==void 0)return`Condition "${n}" can't take the value "${e}".`}}function mt(e,t){if(e.length===0)return`It has no wording to send.`;let n=E(e);if(n.joined)return`A prompt line can't start with "+"; every line that fits is sent.`;if(n.when===`unreadable`)return`A line that opens with "when" needs a condition and a colon, like "when path is web: …".`;for(let e of n.when){if(e.path.includes(`.`))return`"${e.path}" isn't one condition or slot.`;if(e.expected===null)return`A condition always has a value, so "is null" never fits.`;let n=de(e,t,`this profile’s conditions or slots`);if(n)return n}if(n.when.length>0&&!n.text&&e.length===1)return`It has no wording to send.`}function D(e,t,n){let r=pt(t,n);if(r)return r;let i=ft(t,n);for(let[t,n]of ut(e).entries()){let e=mt(n,i);if(e)return`Line ${t+1}: ${e}`}}function ht(e,t,n,r){let i=n.conditions??{};if(t===void 0){if(n.conditions)throw new m(`request`,`Profile ${e} declares no conditions`);return{...r}}if(Object.hasOwn(i,`path`))throw new m(`request`,`Profile ${e}: the turn's own path states path`);for(let n of Object.keys(i))if(!Object.hasOwn(t,n))throw new m(`request`,`Profile ${e} has no condition '${n}'`);let a={...r};for(let[r,o]of Object.entries(t)){let t=r===`path`?n.path:i[r];if(t===void 0)throw new m(`request`,`Profile ${e}: the turn left condition '${r}' unset`);if(!o.includes(t))throw new m(`request`,`Profile ${e}: '${t}' is no value of condition '${r}'`);a[r]=t}return a}function gt(e,t){return e.when!==`unreadable`&&e.when.every(e=>u(e,t))}function _t(e,t,n){let r=ut(e),i=r.flat().some(e=>typeof e!=`string`),a=[];for(let[e,o]of r.entries()){let r=E(o);if(!gt(r,t))continue;let s=[];for(let[e,t]of o.entries()){let a=n(e===0?r.text:dt(t));a&&s.push({text:a,private:typeof t!=`string`||!i})}a.push({line:e+1,pieces:s})}return a}function vt(e,t){if(typeof e!=`string`){if(!Array.isArray(e))throw new m(`config`,`${t} must be a string or an array of lines`);if(e.length===0)throw new m(`config`,`${t} must not be an empty array`);for(let[n,r]of e.entries())if(typeof r!=`string`){if(!Array.isArray(r))throw new m(`config`,`${t}[${n}] must be a string or a list of parts; put { private } inside the list`);tt(r,`${t}[${n}]`)}}}function yt(e,t){let n=e?.path;if(n)for(let e of t){let t=e.paths?.find(e=>e!==`*`&&!n.includes(e));if(t!==void 0)return`Tool ${e.name} lists path "${t}", which is not one of ${n.join(`, `)}.`}}function O(e,t){let n=e.get(t);return n!==void 0&&n.type!==`builtin`}function k(e,t){return!e||e.includes(`*`)?!0:t?e.includes(t):!1}function bt(e,t){return t.filter(n=>{let r=e.get(n);return r?.type!==`builtin`||!(r.conflictsWith??[]).some(e=>t.includes(e))})}function A(e){return`tools`in e?e.tools.allow:[]}function j(e){return e.type===`text`||e.type===`image`?e.tools:void 0}function xt(e){return`tools`in e?e.tools.parallel:void 0}function St(e,t,n){return A(t).filter(r=>{let i=e.get(r);return!i||i.type===`builtin`?!1:t.type===`host`||k(i.paths,n.path)})}function Ct(e,t,n,r){let i=t.models[r];return i?(i.builtInTools??[]).filter(t=>{let r=e.get(t);return r?.type===`builtin`&&k(r.paths,n.path)}):[]}function M(e,t,n){let r=e.get(t);if(r&&r.type!==`builtin`)return{type:`function`,name:r.name,description:r.description,parameters:n&&r.askInputSchema||r.inputSchema}}function wt(e,t,n){let r=[];for(let i of t){let t=M(e,i,n);t&&r.push(t)}return r}function N(e,t,n){if(t.visible.includes(n))return;t.visible.push(n);let r=M(e,n,t.modelBackground);r&&!t.wire.some(e=>e.name===n)&&t.wire.push(r)}function Tt(e,t,n){if(t.builtins.includes(n))return;let r=e.get(n);if(r?.type!==`builtin`)return;let i=r.conflictsWith??[];t.builtins=t.builtins.filter(t=>{if(i.includes(t))return!1;let r=e.get(t);return!(r?.type===`builtin`&&r.conflictsWith?.includes(n))}),t.builtins.push(n)}function Et(e,t,n){return t.type===`live`||t.type===`host`?[...n]:n.filter(t=>e.get(t)?.loadTier===`T0`)}function Dt(e,t,n){return bt(e,n.filter(n=>{let r=e.get(n);return r?.type===`builtin`&&(t.type===`live`||r.loadTier===`T0`)}))}function Ot(e,t){if(t.type!==`text`&&t.type!==`image`&&t.type!==`live`)return;let n=A(t).flatMap(t=>e.get(t)??[]),r=yt(t.identity.conditions,n);if(r)throw new m(`config`,`Profile ${t.id}: ${r}`)}function kt(e,t){let n=j(t)?.t2Loader,r=n===void 0?void 0:e.get(n);if(r&&r.type!==`builtin`&&(r.background??`never`)!==`never`)throw new m(`config`,`Profile ${t.id}: tools.t2Loader '${r.name}' sets background, and a loader cannot detach`)}function P(e,t,n,r){Ot(e,t),kt(e,t);let i=St(e,t,n),a=t.type===`host`||t.type===`decision`||t.type===`embedding`||r===void 0?[]:Ct(e,t,n,r),o=[...i,...a],s=Dt(e,t,o),c=Et(e,t,o),l=c.filter(t=>O(e,t)),u=n.background!==void 0;return{builtins:s,gated:o,visible:c,executable:l,path:n.path,sessionPermissions:n.sessionPermissions,wire:wt(e,c,u),...u?{modelBackground:u}:{}}}async function At(e,t,n,r){let i=P(e,t,n,r);return await F(e,i,t,n),i}function jt(e){return{builtins:[...e.builtins],gated:[...e.gated],visible:[...e.visible],executable:[...e.executable],path:e.path,sessionPermissions:e.sessionPermissions?[...e.sessionPermissions]:void 0,wire:e.wire.map(e=>({...e,parameters:structuredClone(e.parameters)})),...e.modelBackground?{modelBackground:e.modelBackground}:{}}}async function F(e,t,n,r){let i=j(n)?.t1Policy;if(!i)return;let a;try{a=await i({profile:n,input:r.input,path:r.path,sessionPermissions:r.sessionPermissions,gated:t.gated,host:r.host})}catch(e){let t=e instanceof Error?e.message:String(e);throw new m(`config`,`Profile '${n.id}' tools.t1Policy rejected: ${t}`,{cause:e})}if(!Array.isArray(a))throw new m(`config`,`Profile '${n.id}' tools.t1Policy must return ToolId[]`);I(e,t,a)}function I(e,t,n=[]){for(let r of n){if(!t.gated.includes(r))continue;let n=e.get(r);n?.loadTier===`T2`&&(n.type===`builtin`?Tt(e,t,r):N(e,t,r))}t.executable=t.visible.filter(t=>O(e,t))}var Mt=new Set([`__proto__`,`constructor`,`prototype`]);function Nt(e){if(!me(e))return;let{loaded:t}=e;if(Array.isArray(t)&&t.every(e=>typeof e==`string`))return t}function Pt(e,t,n,r){if(r.type===`live`||r.type===`host`)return{promoted:[]};let i=[];for(let a of n){if(typeof a!=`string`||Mt.has(a))return{promoted:[],failure:{code:`invalid_output`,kind:`bad_response`,message:`tools.t2Loader loaded ids must be plain strings`}};let n=Ft(e,a,r);if(`failure`in n)return{promoted:[],failure:n.failure};let{tool:o}=n;k(o.paths,t.path)&&t.gated.includes(a)&&i.push(a)}let a=[];for(let n of i)N(e,t,n),a.push(n);return t.executable=t.visible.filter(t=>O(e,t)),{promoted:a}}function L(e){return{failure:{code:`invalid_output`,kind:`bad_response`,message:e}}}function Ft(e,t,n){if(!A(n).includes(t))return L(`tools.t2Loader attempted to promote tool '${t}' outside profile allow`);let r=e.get(t);return r?r.type===`builtin`?L(`tools.t2Loader attempted to promote builtin '${t}' — only custom tools may be promoted`):r.loadTier===`T2`?{tool:r}:L(`tools.t2Loader attempted to promote tool '${t}' with loadTier '${r.loadTier}' — only T2 tools may be promoted`):L(`tools.t2Loader attempted to promote unknown tool '${t}'`)}function R(e){return Array.isArray(e)?[...e]:e.choices.map(e=>e.value)}function It(e){return Array.isArray(e)?{choices:e.map(e=>({value:e}))}:{...e.label!==void 0&&e.label!==``?{label:e.label}:{},choices:e.choices.map(e=>({value:e.value,...e.description!==void 0&&e.description!==``?{description:e.description}:{}}))}}function z(e){if(e)return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,It(t)]))}function B(e){return e?.slots?{...e,slots:z(e.slots)}:e}function V(e){return e==null}function H(e){return V(e)||typeof e!=`object`||Array.isArray(e)?null:e}function U(e){let t=H(e);return!t||t.type!==void 0&&t.type!==`object`?null:t}function W(e){let t=e.required;return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}function G(e){let t=e.properties;return H(t)??{}}function Lt(e,t){return e?`${e}.${t}`:t}function Rt(e,t){t.push({path:e,error:`required field '${e}' is missing`})}async function zt(e,t,n,r,i){if(!n)return;let a=await n(t,r);a.isValid||i.push({path:e,error:a.error||a.finding||`Validation failed for '${e}'`})}async function Bt(e){let{path:t,propSchema:n,child:r,isRequired:i,fields:a,slots:o,failures:s}=e;if(V(r)){i&&Rt(t,s);return}await zt(t,r,a?.[t],o,s);let c=U(n),l=c?H(r):null;c&&l&&await Vt(c,l,t,a,o,s)}async function Vt(e,t,n,r,i,a){let o=G(e),s=new Set(W(e)),c=new Set([...Object.keys(o),...s]),l=H(t);for(let e of c)await Bt({path:Lt(n,e),propSchema:o[e],child:l?.[e],isRequired:s.has(e),fields:r,slots:i,failures:a})}async function Ht(e,t,n,r){let i=U(e);if(!i)throw new m(`config`,`structured validation requires a JSON Schema object root`);let a=[];if(!H(t)){for(let e of W(i))Rt(e,a);return a}return await Vt(i,t,``,n,r,a),a}function Ut(e,t){let n=e;for(let e of t.split(`.`)){let t=U(n);if(!t)return!1;let r=G(t);if(!Object.hasOwn(r,e)&&!W(t).includes(e))return!1;n=r[e]}return!0}function Wt(e){return e.map(e=>e.error).join(`; `)}function Gt(e,t){let n=e;for(let e of t.split(`.`))n=H(n)?.[e];return n}function Kt(e,t,n){let[r,...i]=t.split(`.`),a=H(e)??{};return r===void 0?e:{...a,[r]:i.length?Kt(a[r],i.join(`.`),n):n}}async function qt(e,t,n){let r=[];for(let[i,a]of Object.entries(t??{})){let t=Gt(e,i);if(Array.isArray(t))for(let[e,o]of t.entries()){let t=await a.check(o,n);t.isValid||r.push({path:i,index:e,item:o,reason:t.error||t.finding||`Validation failed for '${i}'`,onFail:a.onFail})}}return r}function Jt(e,t){let n=e;for(let e of t.split(`.`)){let t=U(n);if(!t)return;n=G(t)[e]}let r=H(n);if(r?.type===`array`)return H(r.items)??void 0}var Yt=class extends Error{failure;constructor(e){super(e.message),this.failure=e}},Xt=new Set([`text`,`image`,`speech`]),Zt=n().regex(/\S/),Qt=i({mimeType:n(),data:c(),name:n().optional()}),$t=i({mimeType:n(),uri:n(),name:n().optional()}),en=i({voice:n().optional(),style:n().optional(),speed:a().positive().optional()});function tn(e){return i(Object.fromEntries(Object.entries(e).map(([e,t])=>{let n=R(t);return[e,o(n).optional()]})))}var nn=new Set([`text`,`attachments`,`voice`,`slots`,`speech`]);function rn(e,t){if(!e.hostFields)return{sent:t};let n={...t},r={};for(let t of Object.keys(e.hostFields))n[t]!==void 0&&(r[t]=n[t]);let{text:i,attachments:a,voice:o,slots:s,speech:c}=t;return{sent:{text:i,...a?{attachments:a}:{},...o?{voice:o}:{},...s?{slots:s}:{},...c?{speech:c}:{}},hostInput:r}}function an(e,n){let{inputs:r}=e,a={text:Zt};r?.attachments&&(a.attachments=s(t([Qt,$t])).optional()),r?.voice&&(a.voice=s(Qt).optional()),r?.slots&&(a.slots=tn(r.slots).optional()),e.type===`speech`&&(a.speech=en.optional());for(let e of n?.hostOnly??[]){if(!a[e])throw new m(`config`,`Tool '${n?.name}' keeps '${e}' for the host, which its profile does not take`);delete a[e]}for(let[e,t]of Object.entries(n?.fieldText??{})){let r=a[e];if(!r)throw new m(`config`,`Tool '${n?.name}' describes '${e}', which its profile does not take`);a[e]=r.describe(t)}for(let[e,t]of Object.entries(n?.hostFields??{})){if(nn.has(e))throw new m(`config`,`Tool '${n?.name}' declares the host field '${e}', which is a field of every agent tool`);a[e]=t}return i(a)}var on=l({text:n().optional(),structured:r().optional(),removed:s(l({path:n(),reason:n(),item:r()})).optional(),parts:s(ie).optional(),sources:s(te).optional()});function sn(e){return e.type===`speech`||(e.type===`text`||e.type===`image`)&&e.inputs.text!==!1}function cn(e){return e.type===`builtin`?!1:e.permission!==`auto`||`auth`in e&&e.auth!==void 0&&(e.auth.onUnauthenticated??`gate`)===`gate`}function ln(e,t){if(!Xt.has(e.type))return`it is a ${e.type} profile; an agent tool runs a text, image, or speech profile`;if(!sn(e))return`it does not take text`;for(let n of A(e)){let e=t(n);if(!e)return`its tool '${n}' is not registered; register it first`;if(cn(e))return`its tool '${n}' can stop on a gate; give it permission 'auto' and no sign-in`}}function un(e,t,n){let r=`Agent tool "${e.name}"`,i=e.maxCallsPerTurn;if(i!==void 0&&!(Number.isInteger(i)&&i>0))throw new m(`config`,`${r}: maxCallsPerTurn must be a whole number above 0`);let a=t(e.profile);if(!a)throw new m(`config`,`${r}: profile '${e.profile}' must be registered before the tool`);let o=ln(a,n);if(o)throw new m(`config`,`${r} can't run '${e.profile}': ${o}`);return a}function dn(e){if(!e)return`delegated`;let t=`models`in e&&Object.values(e.models).some(e=>(e.builtInTools?.length??0)>0);return A(e).length===0&&!t?`local`:`delegated`}function fn(e){let t=re(e),n=t.flatMap(e=>e.type===`text`?[e.text]:[]).join(``),r=ae(t,e=>e.type===`structured`),i=r?.structured,a=t.flatMap(e=>e.type===`media`?[{type:e.media.mimeType.startsWith(`audio/`)?`audio`:`image`,mimeType:e.media.mimeType,data:e.media.data}]:[]),o=t.flatMap(e=>e.type===`citation`?e.sources:[]);return{...i===void 0?{text:n}:{structured:i},...r?.removed?.length?{removed:r.removed}:{},...a.length>0?{parts:a}:{},...o.length>0?{sources:o}:{}}}function pn(e,t,n){return{...e,type:`agent`,input:t,output:on,sources:e=>e.sources??[],...n}}function mn(e,t,n){if(!e||typeof e!=`object`||Array.isArray(e))return n.push(`${t}: schema must be an object`),!1;let r=typeof e.type==`string`||Array.isArray(e.type),i=e.anyOf!==void 0||e.oneOf!==void 0;if(!r&&!i){if(t!==`$`)return!0;n.push(`${t}: missing type or combinator`)}return e.type===`array`&&e.items===void 0&&n.push(`${t}: array schema must define items`),!0}function hn(e,t,n,r){let i=Array.isArray(t)?t:[];for(let t of i)typeof t==`string`&&!Object.hasOwn(e,t)&&r.push(`${n}: required key '${t}' missing from properties`);for(let[t,i]of Object.entries(e))i&&typeof i==`object`&&K(i,`${n}.properties.${t}`,r)}function K(e,t,n){if(!mn(e,t,n))return;let r=e.properties;r&&typeof r==`object`&&!Array.isArray(r)&&hn(r,e.required,t,n),e.items&&typeof e.items==`object`&&!Array.isArray(e.items)&&K(e.items,`${t}.items`,n);for(let r of[`anyOf`,`oneOf`]){let i=e[r];Array.isArray(i)&&i.forEach((e,i)=>{e&&typeof e==`object`&&K(e,`${t}.${r}[${i}]`,n)})}}function gn(e,t){let n=[];if(K(e,`$`,n),n.length>0)throw new m(`config`,`Invalid tool ${t} schema: ${n.join(`; `)}`)}function _n(t,n=`output`){let r=e(t,{target:`draft-7`,io:n});return delete r.$schema,r.type||=`object`,r}function q(e){if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return e.map(q);let t={};for(let n of Object.keys(e))n!==`__proto__`&&n!==`constructor`&&n!==`prototype`&&(t[n]=q(e[n]));return t}function vn(e){let t=/^[a-z][a-z0-9+.-]*:\/\/[^/?#]*/i.exec(e)?.[0];if(!t||/[{}]/.test(t))throw new m(`config`,`Endpoint "${e}" must start with a fixed scheme and host; placeholders belong in the path or query`)}function yn(e,t,n,r){if(!n.provider?.trim()||!n.apiId?.trim())throw new m(`config`,h(`provider.binding_identity`))}function bn(e){J(e.id,e.models),Q(e.id,e.observability),hr(e.id,e.inputs);for(let[t,n]of Object.entries(e.models))Y(e.id,t,n);return{type:`embedding`,id:e.id,identity:{handle:e.identity.handle},models:e.models,defaultModel:An(e.id,e),allowModelSelect:e.allowModelSelect,inputs:e.inputs,guardrails:e.guardrails,observability:e.observability,labels:e.labels}}function xn(e){J(e.id,e.models),Z(e.id,e.guardrails),Q(e.id,e.observability);for(let[t,n]of Object.entries(e.models))Y(e.id,t,n);if(`text`in e.inputs&&e.inputs.text!==!1)throw new m(`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},...Mn(e),providerContinuation:void 0,maxSteps:void 0,inputs:{...e.inputs,text:!1},guardrails:e.guardrails,observability:e.observability,labels:e.labels}}function Sn(e,t,n,r){let i=r.safeParse(n);if(!i.success)throw new m(`config`,`Profile ${e} model '${t}': ${i.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `)}`)}function Cn(e,t,n){if(Sn(e,t,n,ue),yn(e,t,n,`decision`),`retry`in n)throw new m(`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 m(`config`,`Profile ${e} model '${t}' timeoutMs must be > 0`)}function wn(e){let t=e.models?T(e.models):void 0;if(!t)throw new m(`config`,`Profile ${e.id}: type 'decision' must declare exactly one model`);Cn(e.id,t,e.models[t])}function Tn(e){if(e.inputs.state!==`json`)throw new m(`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 m(`config`,`Profile ${e.id}: decision inputs.maxStateBytes must be a positive integer`);if(!e.decision.contract.trim())throw new m(`config`,`Profile ${e.id}: decision.contract must be non-empty`)}function En(e){return wn(e),Tn(e),Q(e.id,e.observability),{...e,identity:{handle:e.identity.handle}}}function Dn(e){return e===void 0?{}:{parallel:e}}function On(e){return kn(e.id,e.tools),Q(e.id,e.observability),{type:`host`,id:e.id,tools:{allow:e.tools.allow,...Dn(e.tools.parallel)},guardrails:e.guardrails,observability:e.observability,labels:e.labels}}function kn(e,t){if(!Array.isArray(t.allow))throw new m(`config`,`Profile ${e}: type 'host' must set tools.allow`)}function J(e,t){if(Object.keys(t).length===0)throw new m(`config`,`Profile ${e} must declare at least one model`)}function An(e,t){let n=t.defaultModel??T(t.models);if(!n)throw new m(`config`,`Profile ${e} must set defaultModel when more than one model is declared`);if(!t.models[n])throw new m(`config`,`Profile ${e} defaultModel '${n}' is not declared`);return n}function Y(e,t,n){jn(e,t,n),Sn(e,t,n,ce),jn(e,t,n)}function jn(e,t,n){let r=n.efforts;if(!r||Object.keys(r).length===0){if(n.defaultEffort||n.allowEffortSelect)throw new m(`config`,`Profile ${e} model '${t}': defaultEffort and allowEffortSelect require efforts`);return}for(let[n,i]of Object.entries(r))if(!v.includes(i))throw new m(`config`,`Profile ${e} model '${t}' effort '${n}': '${i}' is not a thinking level (${v.join(`, `)})`);let i=Object.keys(r),a=n.defaultEffort??(i.length===1?i[0]:void 0);if(!a)throw new m(`config`,`Profile ${e} model '${t}' must set defaultEffort when more than one effort is declared`);if(!r[a])throw new m(`config`,`Profile ${e} model '${t}' defaultEffort '${a}' is not declared`);if(n.allowEffortSelect&&i.length<2)throw new m(`config`,`Profile ${e} model '${t}' allowEffortSelect requires at least two efforts`)}function Mn(e){return{providerContinuation:e.providerContinuation?le.parse(e.providerContinuation):{},models:e.models,defaultModel:An(e.id,e),allowModelSelect:e.allowModelSelect,maxSteps:e.maxSteps}}function Nn(e,t,n){if(n?.length){for(let r of n)if(!oe(r))throw new m(`config`,`Profile ${e}: turnBehaviour.resumption.${t} may only include ContinueStopKind (length | stream_incomplete | provider_error); got '${r}'`)}}function Pn(e,t){t&&(Nn(e,`allowContinue`,t.allowContinue),Nn(e,`autoContinue`,t.autoContinue))}function X(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Fn(e,t){let n=[e];for(let e of t)n=n.flatMap(t=>X(t)?e===`*`?Object.values(t):[t[e]]:[]);return n}var In=Object.entries(Se).filter(([,e])=>e.required===!0).map(([e,t])=>[e,t.profileTypes]).sort(([e],[t])=>e.split(`.`).length-t.split(`.`).length);function Ln(e){if(!X(e))throw new m(`config`,`Profile definition must be an object`);let t=typeof e.id==`string`&&e.id.trim()?e.id:void 0;if(!t)throw new m(`config`,`Profile definition must set id`);if(!we.find(t=>t===e.type))throw new m(`config`,`Profile ${t}: type must be one of ${we.join(`, `)}`)}function Rn(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 m(`config`,`Profile ${e.id.slice(0,64)}: ${t} must be at most ${i} characters`)}function zn(e){let{id:t,type:n}=e,r=e;for(let[e,i]of In){if(i&&!i.includes(n))continue;let a=he(e),o=Fn(r,a.slice(0,-1)),s=a[a.length-1];if(o.some(e=>{if(!X(e))return!1;let t=e[s];return t==null||t===``}))throw new m(`config`,`Profile ${t}: type '${n}' must set ${a.join(`.`)}`)}}function Bn(e){let{id:t,type:n}=e;if(n!==`live`&&ge(`inputs`).includes(n)&&e.inputs==null)throw new m(`config`,`Profile ${t}: type '${n}' must set inputs`)}function Vn(e){let[t]=Ce(e);if(!t)return;let{offValue:n,reason:r}=t.scope,i=n===void 0?``:` (other than ${n})`;throw new m(`config`,`Profile ${e.id}: type '${e.type}' must not set ${t.path}${i} — ${r}`)}function Hn(e,t){let n=t.turnBehaviour;Pn(e,n?.resumption)}function Un(e,t){let n=t=>new m(`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 Z(e,t){let n=t=>new m(`config`,`Profile ${e}: ${t}`),r=Object.keys(t??{}).find(e=>!Wn.includes(e));if(r!==void 0)throw n(`guardrails.${r} is not a setting; it takes ${Wn.join(`, `)}`);Kn(t?.blockedReply,n)}var Wn=[`quota`,`detect`,`blockedReply`,`network`,`taint`],Gn=[`onBlock`,`maxRetries`];function Kn(e,t){if(e===void 0)return;let n=Object.keys(e).find(e=>!Gn.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&&!g.includes(r))throw t(`guardrails.blockedReply.onBlock must be one of ${g.join(`, `)}`);if(i!==void 0&&(!Number.isInteger(i)||i<0))throw t(`guardrails.blockedReply.maxRetries must be a non-negative integer`)}function qn(e){let t=e.guardrails?.detect,n=e.type===`host`?ye(`guardrails.detect`,t,Ee):ye(`guardrails.detect`,t);if(n!==void 0)throw new m(`config`,`Profile ${e.id}: ${n}`)}function Q(e,t){try{let n=Oe(t);if(!Number.isFinite(n.retainForDays))throw new m(`config`,`Profile ${e}: observability.retainForDays must be a finite number`);if(n.rotateAfterMiB<=0||!Number.isFinite(n.rotateAfterMiB))throw new m(`config`,`Profile ${e}: observability.rotateAfterMiB must be a positive number`)}catch(t){if(t instanceof m&&t.message.startsWith(`Profile `))throw t;let n=t instanceof Error?t.message:String(t);throw new m(De(t),`Profile ${e}: ${n}`,{cause:t})}}function Jn(e){if(e.type===`host`||e.type===`decision`||e.type===`speech`||e.type===`transcription`||e.type===`embedding`)return;let{conditions:t,system:n}=e.identity,r={};for(let[t,n]of Object.entries(B(e.inputs)?.slots??{}))r[t]=R(n);let i=n??``;vt(i,`Profile ${e.id} identity.system`);let a=D(i,t,r);if(a)throw new m(`config`,`Profile ${e.id} identity.system: ${a}`)}function Yn(e){Ln(e);for(let t of[`key`,`fallbackKey`,`protocol`,`provider`])if(t in e)throw new m(`config`,h(`provider.profile_configuration`,{profile:e.id,field:t}));Vn(e),Bn(e),zn(e),Rn(e),e.labels&&ve(e.labels,`Profile ${e.id}`);for(let t of _e)if(e.labels?.[t]!==void 0)throw new m(`config`,`Profile ${e.id}: labels '${t}' is a host line, which a profile cannot change; set it with overrideLabels`);if(Jn(e),qn(e),e.type===`host`)return On(e);if(e.type===`decision`)return En(e);if(e.type===`embedding`)return bn(e);if(e.type===`transcription`)return xn(e);J(e.id,e.models),Hn(e.id,e),Z(e.id,e.guardrails),e.type===`text`&&Un(e.id,e.outputs?.validation),Q(e.id,e.observability);for(let[t,n]of Object.entries(e.models))Y(e.id,t,n);let t=e.type===`speech`?{handle:e.identity.handle}:{handle:e.identity.handle,conditions:e.identity.conditions,system:e.identity.system},n=e.guardrails,r=e.observability,i=e.labels,a=Mn(e),o;switch(e.type){case`text`:o={type:`text`,id:e.id,identity:t,...a,tools:e.tools,inputs:B(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:B(e.inputs),outputs:e.outputs,turnBehaviour:e.turnBehaviour,guardrails:n,observability:r,labels:i},tr(o.id,o.inputs.attachments?.accept),er(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?B(e.inputs):e.inputs,tools:{allow:e.tools.allow,...Dn(e.tools.parallel)},turnBehaviour:e.turnBehaviour,guardrails:n,observability:r,labels:i},ke(o),rr(o.id,o.live.contextCompression),nr(o);break;default:throw new m(`config`,`Unknown profile type '${String(e)}'`)}return Qn(o),Xn(o),Zn(o),o}function Xn(e){let{maxSteps:t}=e;if(!(t===void 0||Number.isInteger(t)&&t>0))throw new m(`config`,`Profile ${e.id}: maxSteps must be a whole number of 1 or more; leave it out for the default of 20`)}function Zn(e){if(e.type===`text`&&e.turnBehaviour?.atStepLimit===`answer`&&e.maxSteps===1)throw new m(`config`,`Profile ${e.id}: turnBehaviour.atStepLimit 'answer' with maxSteps 1 leaves no step that can call a tool`)}function Qn(e){if(e.type===`live`)return;let t=e.outputs?.structured;if(!t||typeof t==`string`)return;let n=d(e)?.slots?.[t.by];if(!n)throw new m(`config`,`Profile ${e.id}: outputs.structured.by '${t.by}' is not a slot in inputs.slots`);let r=R(n),i=Object.keys(t.map).filter(e=>!r.includes(e));if(i.length)throw new m(`config`,`Profile ${e.id}: outputs.structured.map maps ${i.join(`, `)}, not a choice of slot '${t.by}'`)}var $n={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 er(e,t){for(let[n,{ok:r,rule:i}]of Object.entries($n)){let a=t[n];if(a!==void 0&&!r(a))throw new m(`config`,`Profile ${e}: image.${n} must be ${i}`)}t.references?.forEach((t,n)=>{let r=`Profile ${e}: image.references[${n}]`;if(pe(t.mimeType)!==`image`)throw new m(`config`,`${r} must be an image, not '${t.mimeType}'`);if(!(b(t)?t.uri:t.data))throw new m(`config`,`${r} needs its bytes or its uri`)})}function tr(e,t){let n=t?.filter(e=>!f(be,e));if(n?.length)throw new m(`config`,`Profile ${e}: an image profile's attachments take images, video, and PDF only, not ${n.join(`, `)}`)}function nr(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 m(`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 m(`config`,`${i}.resumed.prompt must be a prompt`);let{afterMs:a}=n;if(a!==void 0&&!(Number.isFinite(a)&&a>=0))throw new m(`config`,`${i}.resumed.afterMs must be 0 or more milliseconds`);if(!r)throw new m(`config`,`${i}.resumed needs live.sessionResumption: without it no call resumes`)}function rr(e,t){if(!t)return;let n=`Profile ${e} live.contextCompression`,r=t.triggerTokens,i=t.slidingWindow.targetTokens;if(ir(`${n}.triggerTokens`,r),ir(`${n}.slidingWindow.targetTokens`,i),r!==void 0&&i!==void 0&&i>=r)throw new m(`config`,`${n}: slidingWindow.targetTokens must be below triggerTokens`)}function ir(e,t){if(!(t===void 0||Number.isInteger(t)&&t>0))throw new m(`config`,`${e} must be a whole number above 0`)}function ar(e,t,n,r){let i=`Profile ${t.id} model ${n} compaction`;if(or(i,r),sr(i,r),r.meter!=null&&r.meter!==`history`&&r.meter!==`input`)throw new m(`config`,`${i}: meter must be 'history' or 'input'`);if(r.profile===void 0){if(t.type!==`text`||t.inputs.text===!1)throw new m(`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 m(`config`,`${i}: compaction profile '${r.profile}' must be registered before '${t.id}'`);if(a.type!==`text`||a.inputs.text===!1)throw new m(`config`,`${i}: compaction profile '${r.profile}' must be a text profile that takes text`)}function or(e,t){if(t.maxTokens<=0)throw new m(`config`,`${e}: maxTokens must be > 0`);if(t.compactAt<=0||t.compactAt>=1)throw new m(`config`,`${e}: compactAt must be in (0, 1)`)}function sr(e,t){if(t.previousExchanges<0)throw new m(`config`,`${e}: previousExchanges must be >= 0`);if(t.previousExchanges<1&&t.previousExchanges>=t.compactAt)throw new m(`config`,`${e}: previousExchanges as fraction (${t.previousExchanges}) must be < compactAt (${t.compactAt})`);if(t.previousExchanges>1&&!Number.isInteger(t.previousExchanges))throw new m(`config`,`${e}: previousExchanges >= 1 must be an integer`)}function cr(e,t){for(let n of A(t))if(e.get(n)?.type===`builtin`)throw new m(`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 lr(e,t){let n=j(t)?.t2Loader;if(n){if(!A(t).includes(n))throw new m(`config`,`Profile ${t.id} tools.t2Loader '${n}' must also be listed in tools.allow`);if(e.get(n)?.type!==`function`)throw new m(`config`,`Profile ${t.id} tools.t2Loader '${n}' must be a registered type: 'function' tool`)}}function*ur(e){for(let[t,n]of Object.entries(e.models))for(let e of n.builtInTools??[])yield{modelId:t,id:e}}function dr(e,t){for(let{modelId:n,id:r}of ur(t))if(e.get(r)?.type!==`builtin`)throw new m(`config`,`Profile ${t.id} model '${n}' lists '${r}' in builtInTools — not a registered builtin`)}function fr(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 pr(e,t){let n=fr(t).map(n=>{let r=e.find(n);if(!r)throw new m(`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 m(`config`,`Profile ${t.id}: outputs.validation checks a structured reply, so it needs outputs.structured`);let o=a.filter(e=>!n.some(t=>Jt(t.jsonSchema,e)));if(o.length)throw new m(`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=>Ut(t.jsonSchema,e)));if(s.length)throw new m(`config`,`Profile ${t.id}: outputs.validation.fields has ${s.join(`, `)}, which no structured schema reaches through object properties`)}function mr(e){let t=d(e)?.context;if(!t)return;let n=_;if(t.from.length===0||t.from.some(e=>!n.includes(e)))throw new m(`config`,`Profile ${e.id}: inputs.context.from must list ${_.join(` or `)}`);if(!(Number.isInteger(t.maxChars)&&t.maxChars>0))throw new m(`config`,`Profile ${e.id}: inputs.context.maxChars must be a positive integer`)}function hr(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 m(`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 m(`config`,`Profile ${e}: inputs.${t} must be a positive integer`)}function gr(e,t,n){let r=new Map,i=i=>{let a=Yn(i),o=n&&a.type!==`host`?{...a,models:Object.fromEntries(Object.entries(a.models).map(([e,t])=>[e,se(n.require(t.provider,t.apiId),t,a.type)]))}:a;if(cr(e,o),lr(e,o),o.type!==`host`&&o.type!==`decision`&&o.type!==`embedding`){dr(e,o),hr(o.id,d(o)),mr(o),pr(t,o);for(let[e,t]of Object.entries(o.models))t.compaction&&ar(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 m(`config`,`Unknown profile '${e}'`);return t},find:e=>r.get(e),has:e=>r.has(e),list:()=>[...r.values()],clear:()=>r.clear()}}function _r(e){let t=e?.trim()??``;if(t.startsWith(`AIza`))return`gemini`;if(t.startsWith(`sk-or-`))return`openrouter`}function vr(e){let t;try{t=new URL(e.baseUrl)}catch{throw new m(`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 m(`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 m(`blocked`,`Local requests must stay on the configured origin.`))}}var yr=l({data:s(l({id:n().min(1)}))});async function br(e,t){let n=vr(e);if(!n?.fetch)throw new m(`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 m(`network`,`Local model list returned HTTP ${r.status}.`);let i=yr.safeParse(await r.json());if(!i.success)throw new m(`request`,`The endpoint returned an invalid model list.`);return[...new Set(i.data.data.map(e=>e.id))]}var xr=`https://openrouter.ai/api/v1/models`,Sr=`https://openrouter.ai/api/v1/embeddings/models`,Cr=[{id:`gemini-embedding-2-preview`,label:`Gemini Embeddings 2 (preview)`},{id:`gemini-embedding-001`,label:`Gemini Embedding 001`}],wr=[{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)`}],Tr={text:`text`,image:`image`,speech:`speech`,transcription:`transcription`,live:void 0,embedding:void 0},Er=l({data:s(l({id:n().min(1),name:n().optional(),architecture:l({output_modalities:s(n()).optional()}).optional()}))}),Dr=l({data:s(l({id:n().min(1),name:n().optional()}))}),Or=l({models:s(l({name:n().min(1),displayName:n().optional(),supportedGenerationMethods:s(n()).optional()})).optional(),nextPageToken:n().optional()}),kr=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 m(`auth`,`${e} refused the key.`);if(!r.ok)throw new m(`network`,`${e} model list returned HTTP ${r.status}.`);return await r.json()}async function Ar(e,t,n,r){let i=n?.trim();if(t===`embedding`&&!i)return[...e===`openrouter`?wr:Cr];if(e===`openrouter`)return await jr(t,i,r);if(!i)throw new m(`auth`,`Choose a key to list Gemini models.`);return await Nr(t,i,r)}async function jr(e,t,n){let r={signal:n,headers:{Accept:`application/json`,...t?{Authorization:[`Bearer`,t].join(` `)}:{}}};if(e===`embedding`){let e=Dr.safeParse(await $(`OpenRouter`,Sr,r));if(!e.success)throw new m(`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=Tr[e];if(!i)return[];let a=Er.safeParse(await $(`OpenRouter`,`${xr}?output_modalities=${i}`,r));if(!a.success)throw new m(`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 Mr={live:`bidiGenerateContent`,embedding:`embedContent`};async function Nr(e,t,n){let r=Mr[e]??`generateContent`,i=[],a;for(let e=0;e<kr;e++){let e=new URL(ne);e.searchParams.set(`pageSize`,`1000`),a&&e.searchParams.set(`pageToken`,a);let o=Or.safeParse(await $(`Google`,e.href,{signal:n,headers:{Accept:`application/json`,"x-goog-api-key":t}}));if(!o.success)throw new m(`bad_response`,`Google returned an invalid model list.`);for(let e of o.data.models??[]){if(!e.supportedGenerationMethods?.includes(r))continue;let t=e.name.replace(/^models\//,``);i.push({id:t,label:e.displayName??t})}if(a=o.data.nextPageToken,!a)break}return i}function Pr(e){return[...new Set([e.key,e.fallbackKey,...Object.values(e.models??{}).flatMap(e=>[e.keySlot,e.fallbackKeySlot])].filter(e=>!!e))]}function Fr(e,t){return Object.fromEntries(e.map(e=>[e,Object.hasOwn(t,e)?t[e]:void 0]))}export{y as $,jt as A,_t as B,Ht as C,Kt as D,Gt as E,xt as F,it as G,ht as H,j as I,We as J,nt as K,Pt as L,Nt as M,At as N,z as O,A as P,b as Q,I as R,qt as S,Jt as T,T as U,D as V,st as W,Ge as X,C as Y,Ke as Z,on as _,Pr as a,pn as b,Yn as c,q as d,Ze as et,gn as f,dn as g,an as h,vr as i,F as j,R as k,vn as l,ln as m,br as n,Fr as o,Yt as p,rt as q,Ar as r,gr as s,_r as t,_n as u,fn as v,Wt as w,rn as x,un as y,P as z};
3
+ `;function $e(e){if(typeof e==`string`)return;if(typeof e!=`object`||!e||Array.isArray(e))return`must be a string or { private: string }`;let t=Object.keys(e);if(t.length!==1||t[0]!==`private`)return`must have exactly one key, private`;let n=e.private;if(typeof n!=`string`)return`must be a string`;if(n===``)return`must not be empty`}function et(e,t){if(typeof e!=`string`){if(!Array.isArray(e))return`${t} must be a string or an array of parts`;if(e.length===0)return`${t} must not be an empty array`;for(let[n,r]of e.entries()){let e=$e(r);if(e)return`${t}[${n}]${typeof r==`object`&&r&&`private`in r?`.private`:``} ${e}`}}}function tt(e,t){let n=et(e,t);if(n)throw new m(`config`,n)}function nt(e,t,n){return tt(e,t),typeof e==`string`?n(e):e.map(e=>typeof e==`string`?n(e):{private:n(e.private)})}function rt(e){if(typeof e==`string`)return[{text:e,private:!0}];let t=e.some(e=>typeof e!=`string`);return e.map(e=>typeof e==`string`?{text:e,private:!t}:{text:e.private,private:!0})}function it(e){let t=[];for(let n of e)n.some(e=>e.text)&&(t.length>0&&t.push({text:Qe,private:!0}),t.push(...n));return t}function at(e){return e.map(e=>e.text).join(``)}function ot(e){let t=[],n=``;for(let r of e)r.private?n+=r.text:(n.trim()&&t.push(n),n=``);return n.trim()&&t.push(n),{text:at(e),private:t}}function st(e,t){return ot(it([e,...t.map(e=>e?[{text:e,private:!0}]:[])]))}function T(e){let t=Object.keys(e);return t.length===1?t[0]:void 0}var ct=/^[A-Za-z_][\w-]*$/,lt=/^\S+$/;function ut(e){return typeof e==`string`?[[e]]:e.map(e=>typeof e==`string`?[e]:e)}function dt(e){return typeof e==`string`?e:e.private}function E(e){return ee(e[0]===void 0?``:dt(e[0]))}function ft(e,t){let n={};for(let[r,i]of Object.entries({...e,...t}))n[r]={type:`string`,enum:[...i]};return{type:`object`,properties:n}}function pt(e,t){for(let[n,r]of Object.entries(e??{})){if(!ct.test(n))return`Condition "${n}" needs a plain name.`;if(n===`input`||n===`output`)return`Condition "${n}" is a reserved name.`;if(Object.hasOwn(t,n))return`"${n}" is both a condition and a slot.`;if(r.length===0)return`Condition "${n}" lists no values.`;let e=r.find(e=>!lt.test(e)||e===`null`);if(e!==void 0)return`Condition "${n}" can't take the value "${e}".`}}function mt(e,t){if(e.length===0)return`It has no wording to send.`;let n=E(e);if(n.joined)return`A prompt line can't start with "+"; every line that fits is sent.`;if(n.when===`unreadable`)return`A line that opens with "when" needs a condition and a colon, like "when path is web: …".`;for(let e of n.when){if(e.path.includes(`.`))return`"${e.path}" isn't one condition or slot.`;if(e.expected===null)return`A condition always has a value, so "is null" never fits.`;let n=de(e,t,`this profile’s conditions or slots`);if(n)return n}if(n.when.length>0&&!n.text&&e.length===1)return`It has no wording to send.`}function D(e,t,n){let r=pt(t,n);if(r)return r;let i=ft(t,n);for(let[t,n]of ut(e).entries()){let e=mt(n,i);if(e)return`Line ${t+1}: ${e}`}}function ht(e,t,n,r){let i=n.conditions??{};if(t===void 0){if(n.conditions)throw new m(`request`,`Profile ${e} declares no conditions`);return{...r}}if(Object.hasOwn(i,`path`))throw new m(`request`,`Profile ${e}: the turn's own path states path`);for(let n of Object.keys(i))if(!Object.hasOwn(t,n))throw new m(`request`,`Profile ${e} has no condition '${n}'`);let a={...r};for(let[r,o]of Object.entries(t)){let t=r===`path`?n.path:i[r];if(t===void 0)throw new m(`request`,`Profile ${e}: the turn left condition '${r}' unset`);if(!o.includes(t))throw new m(`request`,`Profile ${e}: '${t}' is no value of condition '${r}'`);a[r]=t}return a}function gt(e,t){return e.when!==`unreadable`&&e.when.every(e=>u(e,t))}function _t(e,t,n){let r=ut(e),i=r.flat().some(e=>typeof e!=`string`),a=[];for(let[e,o]of r.entries()){let r=E(o);if(!gt(r,t))continue;let s=[];for(let[e,t]of o.entries()){let a=n(e===0?r.text:dt(t));a&&s.push({text:a,private:typeof t!=`string`||!i})}a.push({line:e+1,pieces:s})}return a}function vt(e,t){if(typeof e!=`string`){if(!Array.isArray(e))throw new m(`config`,`${t} must be a string or an array of lines`);if(e.length===0)throw new m(`config`,`${t} must not be an empty array`);for(let[n,r]of e.entries())if(typeof r!=`string`){if(!Array.isArray(r))throw new m(`config`,`${t}[${n}] must be a string or a list of parts; put { private } inside the list`);tt(r,`${t}[${n}]`)}}}function yt(e,t){let n=e?.path;if(n)for(let e of t){let t=e.paths?.find(e=>e!==`*`&&!n.includes(e));if(t!==void 0)return`Tool ${e.name} lists path "${t}", which is not one of ${n.join(`, `)}.`}}function O(e,t){let n=e.get(t);return n!==void 0&&n.type!==`builtin`}function k(e,t){return!e||e.includes(`*`)?!0:t?e.includes(t):!1}function bt(e,t){return t.filter(n=>{let r=e.get(n);return r?.type!==`builtin`||!(r.conflictsWith??[]).some(e=>t.includes(e))})}function A(e){return`tools`in e?e.tools.allow:[]}function j(e){return e.type===`text`||e.type===`image`?e.tools:void 0}function xt(e){return`tools`in e?e.tools.parallel:void 0}function St(e,t,n){return A(t).filter(r=>{let i=e.get(r);return!i||i.type===`builtin`?!1:t.type===`host`||k(i.paths,n.path)})}function Ct(e,t,n,r){let i=t.models[r];return i?(i.builtInTools??[]).filter(t=>{let r=e.get(t);return r?.type===`builtin`&&k(r.paths,n.path)}):[]}function M(e,t,n){let r=e.get(t);if(r&&r.type!==`builtin`)return{type:`function`,name:r.name,description:r.description,parameters:n&&r.askInputSchema||r.inputSchema}}function wt(e,t,n){let r=[];for(let i of t){let t=M(e,i,n);t&&r.push(t)}return r}function N(e,t,n){if(t.visible.includes(n))return;t.visible.push(n);let r=M(e,n,t.modelBackground);r&&!t.wire.some(e=>e.name===n)&&t.wire.push(r)}function Tt(e,t,n){if(t.builtins.includes(n))return;let r=e.get(n);if(r?.type!==`builtin`)return;let i=r.conflictsWith??[];t.builtins=t.builtins.filter(t=>{if(i.includes(t))return!1;let r=e.get(t);return!(r?.type===`builtin`&&r.conflictsWith?.includes(n))}),t.builtins.push(n)}function Et(e,t,n){return t.type===`live`||t.type===`host`?[...n]:n.filter(t=>e.get(t)?.loadTier===`T0`)}function Dt(e,t,n){return bt(e,n.filter(n=>{let r=e.get(n);return r?.type===`builtin`&&(t.type===`live`||r.loadTier===`T0`)}))}function Ot(e,t){if(t.type!==`text`&&t.type!==`image`&&t.type!==`live`)return;let n=A(t).flatMap(t=>e.get(t)??[]),r=yt(t.identity.conditions,n);if(r)throw new m(`config`,`Profile ${t.id}: ${r}`)}function kt(e,t){let n=j(t)?.t2Loader,r=n===void 0?void 0:e.get(n);if(r&&r.type!==`builtin`&&(r.background??`never`)!==`never`)throw new m(`config`,`Profile ${t.id}: tools.t2Loader '${r.name}' sets background, and a loader cannot detach`)}function P(e,t,n,r){Ot(e,t),kt(e,t);let i=St(e,t,n),a=t.type===`host`||t.type===`decision`||t.type===`embedding`||r===void 0?[]:Ct(e,t,n,r),o=[...i,...a],s=Dt(e,t,o),c=Et(e,t,o),l=c.filter(t=>O(e,t)),u=n.background!==void 0;return{builtins:s,gated:o,visible:c,executable:l,path:n.path,sessionPermissions:n.sessionPermissions,wire:wt(e,c,u),...u?{modelBackground:u}:{}}}async function At(e,t,n,r){let i=P(e,t,n,r);return await F(e,i,t,n),i}function jt(e){return{builtins:[...e.builtins],gated:[...e.gated],visible:[...e.visible],executable:[...e.executable],path:e.path,sessionPermissions:e.sessionPermissions?[...e.sessionPermissions]:void 0,wire:e.wire.map(e=>({...e,parameters:structuredClone(e.parameters)})),...e.modelBackground?{modelBackground:e.modelBackground}:{}}}async function F(e,t,n,r){let i=j(n)?.t1Policy;if(!i)return;let a;try{a=await i({profile:n,input:r.input,path:r.path,sessionPermissions:r.sessionPermissions,gated:t.gated,host:r.host})}catch(e){let t=e instanceof Error?e.message:String(e);throw new m(`config`,`Profile '${n.id}' tools.t1Policy rejected: ${t}`,{cause:e})}if(!Array.isArray(a))throw new m(`config`,`Profile '${n.id}' tools.t1Policy must return ToolId[]`);I(e,t,a)}function I(e,t,n=[]){for(let r of n){if(!t.gated.includes(r))continue;let n=e.get(r);n?.loadTier===`T2`&&(n.type===`builtin`?Tt(e,t,r):N(e,t,r))}t.executable=t.visible.filter(t=>O(e,t))}var Mt=new Set([`__proto__`,`constructor`,`prototype`]);function Nt(e){if(!me(e))return;let{loaded:t}=e;if(Array.isArray(t)&&t.every(e=>typeof e==`string`))return t}function Pt(e,t,n,r){if(r.type===`live`||r.type===`host`)return{promoted:[]};let i=[];for(let a of n){if(typeof a!=`string`||Mt.has(a))return{promoted:[],failure:{code:`invalid_output`,kind:`bad_response`,message:`tools.t2Loader loaded ids must be plain strings`}};let n=Ft(e,a,r);if(`failure`in n)return{promoted:[],failure:n.failure};let{tool:o}=n;k(o.paths,t.path)&&t.gated.includes(a)&&i.push(a)}let a=[];for(let n of i)N(e,t,n),a.push(n);return t.executable=t.visible.filter(t=>O(e,t)),{promoted:a}}function L(e){return{failure:{code:`invalid_output`,kind:`bad_response`,message:e}}}function Ft(e,t,n){if(!A(n).includes(t))return L(`tools.t2Loader attempted to promote tool '${t}' outside profile allow`);let r=e.get(t);return r?r.type===`builtin`?L(`tools.t2Loader attempted to promote builtin '${t}' — only custom tools may be promoted`):r.loadTier===`T2`?{tool:r}:L(`tools.t2Loader attempted to promote tool '${t}' with loadTier '${r.loadTier}' — only T2 tools may be promoted`):L(`tools.t2Loader attempted to promote unknown tool '${t}'`)}function R(e){return Array.isArray(e)?[...e]:e.choices.map(e=>e.value)}function It(e){return Array.isArray(e)?{choices:e.map(e=>({value:e}))}:{...e.label!==void 0&&e.label!==``?{label:e.label}:{},choices:e.choices.map(e=>({value:e.value,...e.description!==void 0&&e.description!==``?{description:e.description}:{}}))}}function z(e){if(e)return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,It(t)]))}function B(e){return e?.slots?{...e,slots:z(e.slots)}:e}function V(e){return e==null}function H(e){return V(e)||typeof e!=`object`||Array.isArray(e)?null:e}function U(e){let t=H(e);return!t||t.type!==void 0&&t.type!==`object`?null:t}function W(e){let t=e.required;return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}function G(e){let t=e.properties;return H(t)??{}}function Lt(e,t){return e?`${e}.${t}`:t}function Rt(e,t){t.push({path:e,error:`required field '${e}' is missing`})}async function zt(e,t,n,r,i){if(!n)return;let a=await n(t,r);a.isValid||i.push({path:e,error:a.error||a.finding||`Validation failed for '${e}'`})}async function Bt(e){let{path:t,propSchema:n,child:r,isRequired:i,fields:a,slots:o,failures:s}=e;if(V(r)){i&&Rt(t,s);return}await zt(t,r,a?.[t],o,s);let c=U(n),l=c?H(r):null;c&&l&&await Vt(c,l,t,a,o,s)}async function Vt(e,t,n,r,i,a){let o=G(e),s=new Set(W(e)),c=new Set([...Object.keys(o),...s]),l=H(t);for(let e of c)await Bt({path:Lt(n,e),propSchema:o[e],child:l?.[e],isRequired:s.has(e),fields:r,slots:i,failures:a})}async function Ht(e,t,n,r){let i=U(e);if(!i)throw new m(`config`,`structured validation requires a JSON Schema object root`);let a=[];if(!H(t)){for(let e of W(i))Rt(e,a);return a}return await Vt(i,t,``,n,r,a),a}function Ut(e,t){let n=e;for(let e of t.split(`.`)){let t=U(n);if(!t)return!1;let r=G(t);if(!Object.hasOwn(r,e)&&!W(t).includes(e))return!1;n=r[e]}return!0}function Wt(e){return e.map(e=>e.error).join(`; `)}function Gt(e,t){let n=e;for(let e of t.split(`.`))n=H(n)?.[e];return n}function Kt(e,t,n){let[r,...i]=t.split(`.`),a=H(e)??{};return r===void 0?e:{...a,[r]:i.length?Kt(a[r],i.join(`.`),n):n}}async function qt(e,t,n){let r=[];for(let[i,a]of Object.entries(t??{})){let t=Gt(e,i);if(Array.isArray(t))for(let[e,o]of t.entries()){let t=await a.check(o,n);t.isValid||r.push({path:i,index:e,item:o,reason:t.error||t.finding||`Validation failed for '${i}'`,onFail:a.onFail})}}return r}function Jt(e,t){let n=e;for(let e of t.split(`.`)){let t=U(n);if(!t)return;n=G(t)[e]}let r=H(n);if(r?.type===`array`)return H(r.items)??void 0}var Yt=class extends Error{failure;constructor(e){super(e.message),this.failure=e}},Xt=new Set([`text`,`image`,`speech`]),Zt=n().regex(/\S/),Qt=i({mimeType:n(),data:c(),name:n().optional()}),$t=i({mimeType:n(),uri:n(),name:n().optional()}),en=i({voice:n().optional(),style:n().optional(),speed:a().positive().optional()});function tn(e){return i(Object.fromEntries(Object.entries(e).map(([e,t])=>{let n=R(t);return[e,o(n).optional()]})))}var nn=new Set([`text`,`attachments`,`voice`,`slots`,`speech`]);function rn(e,t){if(!e.hostFields)return{sent:t};let n={...t},r={};for(let t of Object.keys(e.hostFields))n[t]!==void 0&&(r[t]=n[t]);let{text:i,attachments:a,voice:o,slots:s,speech:c}=t;return{sent:{text:i,...a?{attachments:a}:{},...o?{voice:o}:{},...s?{slots:s}:{},...c?{speech:c}:{}},hostInput:r}}function an(e,n){let{inputs:r}=e,a={text:Zt};r?.attachments&&(a.attachments=s(t([Qt,$t])).optional()),r?.voice&&(a.voice=s(Qt).optional()),r?.slots&&(a.slots=tn(r.slots).optional()),e.type===`speech`&&(a.speech=en.optional());for(let e of n?.hostOnly??[]){if(!a[e])throw new m(`config`,`Tool '${n?.name}' keeps '${e}' for the host, which its profile does not take`);delete a[e]}for(let[e,t]of Object.entries(n?.fieldText??{})){let r=a[e];if(!r)throw new m(`config`,`Tool '${n?.name}' describes '${e}', which its profile does not take`);a[e]=r.describe(t)}for(let[e,t]of Object.entries(n?.hostFields??{})){if(nn.has(e))throw new m(`config`,`Tool '${n?.name}' declares the host field '${e}', which is a field of every agent tool`);a[e]=t}return i(a)}var on=l({text:n().optional(),structured:r().optional(),removed:s(l({path:n(),reason:n(),item:r()})).optional(),parts:s(re).optional(),sources:s(ue).optional()});function sn(e){return e.type===`speech`||(e.type===`text`||e.type===`image`)&&e.inputs.text!==!1}function cn(e){return e.type===`builtin`?!1:e.permission!==`auto`||`auth`in e&&e.auth!==void 0&&(e.auth.onUnauthenticated??`gate`)===`gate`}function ln(e,t){if(!Xt.has(e.type))return`it is a ${e.type} profile; an agent tool runs a text, image, or speech profile`;if(!sn(e))return`it does not take text`;for(let n of A(e)){let e=t(n);if(!e)return`its tool '${n}' is not registered; register it first`;if(cn(e))return`its tool '${n}' can stop on a gate; give it permission 'auto' and no sign-in`}}function un(e,t,n){let r=`Agent tool "${e.name}"`,i=e.maxCallsPerTurn;if(i!==void 0&&!(Number.isInteger(i)&&i>0))throw new m(`config`,`${r}: maxCallsPerTurn must be a whole number above 0`);let a=t(e.profile);if(!a)throw new m(`config`,`${r}: profile '${e.profile}' must be registered before the tool`);let o=ln(a,n);if(o)throw new m(`config`,`${r} can't run '${e.profile}': ${o}`);return a}function dn(e){if(!e)return`delegated`;let t=`models`in e&&Object.values(e.models).some(e=>(e.builtInTools?.length??0)>0);return A(e).length===0&&!t?`local`:`delegated`}function fn(e){let t=te(e),n=t.flatMap(e=>e.type===`text`?[e.text]:[]).join(``),r=ie(t,e=>e.type===`structured`),i=r?.structured,a=t.flatMap(e=>e.type===`media`?[{type:e.media.mimeType.startsWith(`audio/`)?`audio`:`image`,mimeType:e.media.mimeType,data:e.media.data}]:[]),o=t.flatMap(e=>e.type===`citation`?e.sources:[]);return{...i===void 0?{text:n}:{structured:i},...r?.removed?.length?{removed:r.removed}:{},...a.length>0?{parts:a}:{},...o.length>0?{sources:o}:{}}}function pn(e,t,n){return{...e,type:`agent`,input:t,output:on,sources:e=>e.sources??[],...n}}function mn(e,t,n){if(!e||typeof e!=`object`||Array.isArray(e))return n.push(`${t}: schema must be an object`),!1;let r=typeof e.type==`string`||Array.isArray(e.type),i=e.anyOf!==void 0||e.oneOf!==void 0;if(!r&&!i){if(t!==`$`)return!0;n.push(`${t}: missing type or combinator`)}return e.type===`array`&&e.items===void 0&&n.push(`${t}: array schema must define items`),!0}function hn(e,t,n,r){let i=Array.isArray(t)?t:[];for(let t of i)typeof t==`string`&&!Object.hasOwn(e,t)&&r.push(`${n}: required key '${t}' missing from properties`);for(let[t,i]of Object.entries(e))i&&typeof i==`object`&&K(i,`${n}.properties.${t}`,r)}function K(e,t,n){if(!mn(e,t,n))return;let r=e.properties;r&&typeof r==`object`&&!Array.isArray(r)&&hn(r,e.required,t,n),e.items&&typeof e.items==`object`&&!Array.isArray(e.items)&&K(e.items,`${t}.items`,n);for(let r of[`anyOf`,`oneOf`]){let i=e[r];Array.isArray(i)&&i.forEach((e,i)=>{e&&typeof e==`object`&&K(e,`${t}.${r}[${i}]`,n)})}}function gn(e,t){let n=[];if(K(e,`$`,n),n.length>0)throw new m(`config`,`Invalid tool ${t} schema: ${n.join(`; `)}`)}function _n(t,n=`output`){let r=e(t,{target:`draft-7`,io:n});return delete r.$schema,r.type||=`object`,r}function q(e){if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return e.map(q);let t={};for(let n of Object.keys(e))n!==`__proto__`&&n!==`constructor`&&n!==`prototype`&&(t[n]=q(e[n]));return t}function vn(e){let t=/^[a-z][a-z0-9+.-]*:\/\/[^/?#]*/i.exec(e)?.[0];if(!t||/[{}]/.test(t))throw new m(`config`,`Endpoint "${e}" must start with a fixed scheme and host; placeholders belong in the path or query`)}function yn(e,t,n,r){if(!n.provider?.trim()||!n.apiId?.trim())throw new m(`config`,h(`provider.binding_identity`))}function bn(e){J(e.id,e.models),Q(e.id,e.observability),hr(e.id,e.inputs);for(let[t,n]of Object.entries(e.models))Y(e.id,t,n);return{type:`embedding`,id:e.id,identity:{handle:e.identity.handle},models:e.models,defaultModel:An(e.id,e),allowModelSelect:e.allowModelSelect,inputs:e.inputs,guardrails:e.guardrails,observability:e.observability,labels:e.labels}}function xn(e){J(e.id,e.models),Z(e.id,e.guardrails),Q(e.id,e.observability);for(let[t,n]of Object.entries(e.models))Y(e.id,t,n);if(`text`in e.inputs&&e.inputs.text!==!1)throw new m(`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},...Mn(e),providerContinuation:void 0,maxSteps:void 0,inputs:{...e.inputs,text:!1},guardrails:e.guardrails,observability:e.observability,labels:e.labels}}function Sn(e,t,n,r){let i=r.safeParse(n);if(!i.success)throw new m(`config`,`Profile ${e} model '${t}': ${i.error.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`; `)}`)}function Cn(e,t,n){if(Sn(e,t,n,ce),yn(e,t,n,`decision`),`retry`in n)throw new m(`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 m(`config`,`Profile ${e} model '${t}' timeoutMs must be > 0`)}function wn(e){let t=e.models?T(e.models):void 0;if(!t)throw new m(`config`,`Profile ${e.id}: type 'decision' must declare exactly one model`);Cn(e.id,t,e.models[t])}function Tn(e){if(e.inputs.state!==`json`)throw new m(`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 m(`config`,`Profile ${e.id}: decision inputs.maxStateBytes must be a positive integer`);if(!e.decision.contract.trim())throw new m(`config`,`Profile ${e.id}: decision.contract must be non-empty`)}function En(e){return wn(e),Tn(e),Q(e.id,e.observability),{...e,identity:{handle:e.identity.handle}}}function Dn(e){return e===void 0?{}:{parallel:e}}function On(e){return kn(e.id,e.tools),Q(e.id,e.observability),{type:`host`,id:e.id,tools:{allow:e.tools.allow,...Dn(e.tools.parallel)},guardrails:e.guardrails,observability:e.observability,labels:e.labels}}function kn(e,t){if(!Array.isArray(t.allow))throw new m(`config`,`Profile ${e}: type 'host' must set tools.allow`)}function J(e,t){if(Object.keys(t).length===0)throw new m(`config`,`Profile ${e} must declare at least one model`)}function An(e,t){let n=t.defaultModel??T(t.models);if(!n)throw new m(`config`,`Profile ${e} must set defaultModel when more than one model is declared`);if(!t.models[n])throw new m(`config`,`Profile ${e} defaultModel '${n}' is not declared`);return n}function Y(e,t,n){jn(e,t,n),Sn(e,t,n,se),jn(e,t,n)}function jn(e,t,n){let r=n.efforts;if(!r||Object.keys(r).length===0){if(n.defaultEffort||n.allowEffortSelect)throw new m(`config`,`Profile ${e} model '${t}': defaultEffort and allowEffortSelect require efforts`);return}for(let[n,i]of Object.entries(r))if(!v.includes(i))throw new m(`config`,`Profile ${e} model '${t}' effort '${n}': '${i}' is not a thinking level (${v.join(`, `)})`);let i=Object.keys(r),a=n.defaultEffort??(i.length===1?i[0]:void 0);if(!a)throw new m(`config`,`Profile ${e} model '${t}' must set defaultEffort when more than one effort is declared`);if(!r[a])throw new m(`config`,`Profile ${e} model '${t}' defaultEffort '${a}' is not declared`);if(n.allowEffortSelect&&i.length<2)throw new m(`config`,`Profile ${e} model '${t}' allowEffortSelect requires at least two efforts`)}function Mn(e){return{providerContinuation:e.providerContinuation?le.parse(e.providerContinuation):{},models:e.models,defaultModel:An(e.id,e),allowModelSelect:e.allowModelSelect,maxSteps:e.maxSteps}}function Nn(e,t,n){if(n?.length){for(let r of n)if(!ae(r))throw new m(`config`,`Profile ${e}: turnBehaviour.resumption.${t} may only include ContinueStopKind (length | stream_incomplete | provider_error); got '${r}'`)}}function Pn(e,t){t&&(Nn(e,`allowContinue`,t.allowContinue),Nn(e,`autoContinue`,t.autoContinue))}function X(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Fn(e,t){let n=[e];for(let e of t)n=n.flatMap(t=>X(t)?e===`*`?Object.values(t):[t[e]]:[]);return n}var In=Object.entries(Se).filter(([,e])=>e.required===!0).map(([e,t])=>[e,t.profileTypes]).sort(([e],[t])=>e.split(`.`).length-t.split(`.`).length);function Ln(e){if(!X(e))throw new m(`config`,`Profile definition must be an object`);let t=typeof e.id==`string`&&e.id.trim()?e.id:void 0;if(!t)throw new m(`config`,`Profile definition must set id`);if(!we.find(t=>t===e.type))throw new m(`config`,`Profile ${t}: type must be one of ${we.join(`, `)}`)}function Rn(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 m(`config`,`Profile ${e.id.slice(0,64)}: ${t} must be at most ${i} characters`)}function zn(e){let{id:t,type:n}=e,r=e;for(let[e,i]of In){if(i&&!i.includes(n))continue;let a=he(e),o=Fn(r,a.slice(0,-1)),s=a[a.length-1];if(o.some(e=>{if(!X(e))return!1;let t=e[s];return t==null||t===``}))throw new m(`config`,`Profile ${t}: type '${n}' must set ${a.join(`.`)}`)}}function Bn(e){let{id:t,type:n}=e;if(n!==`live`&&ge(`inputs`).includes(n)&&e.inputs==null)throw new m(`config`,`Profile ${t}: type '${n}' must set inputs`)}function Vn(e){let[t]=Ce(e);if(!t)return;let{offValue:n,reason:r}=t.scope,i=n===void 0?``:` (other than ${n})`;throw new m(`config`,`Profile ${e.id}: type '${e.type}' must not set ${t.path}${i} — ${r}`)}function Hn(e,t){let n=t.turnBehaviour;Pn(e,n?.resumption)}function Un(e,t){let n=t=>new m(`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 Z(e,t){let n=t=>new m(`config`,`Profile ${e}: ${t}`),r=Object.keys(t??{}).find(e=>!Wn.includes(e));if(r!==void 0)throw n(`guardrails.${r} is not a setting; it takes ${Wn.join(`, `)}`);Kn(t?.blockedReply,n)}var Wn=[`quota`,`detect`,`blockedReply`,`network`,`taint`],Gn=[`onBlock`,`maxRetries`];function Kn(e,t){if(e===void 0)return;let n=Object.keys(e).find(e=>!Gn.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&&!g.includes(r))throw t(`guardrails.blockedReply.onBlock must be one of ${g.join(`, `)}`);if(i!==void 0&&(!Number.isInteger(i)||i<0))throw t(`guardrails.blockedReply.maxRetries must be a non-negative integer`)}function qn(e){let t=e.guardrails?.detect,n=e.type===`host`?ye(`guardrails.detect`,t,Ee):ye(`guardrails.detect`,t);if(n!==void 0)throw new m(`config`,`Profile ${e.id}: ${n}`)}function Q(e,t){try{let n=Oe(t);if(!Number.isFinite(n.retainForDays))throw new m(`config`,`Profile ${e}: observability.retainForDays must be a finite number`);if(n.rotateAfterMiB<=0||!Number.isFinite(n.rotateAfterMiB))throw new m(`config`,`Profile ${e}: observability.rotateAfterMiB must be a positive number`)}catch(t){if(t instanceof m&&t.message.startsWith(`Profile `))throw t;let n=t instanceof Error?t.message:String(t);throw new m(De(t),`Profile ${e}: ${n}`,{cause:t})}}function Jn(e){if(e.type===`host`||e.type===`decision`||e.type===`speech`||e.type===`transcription`||e.type===`embedding`)return;let{conditions:t,system:n}=e.identity,r={};for(let[t,n]of Object.entries(B(e.inputs)?.slots??{}))r[t]=R(n);let i=n??``;vt(i,`Profile ${e.id} identity.system`);let a=D(i,t,r);if(a)throw new m(`config`,`Profile ${e.id} identity.system: ${a}`)}function Yn(e){Ln(e);for(let t of[`key`,`fallbackKey`,`protocol`,`provider`])if(t in e)throw new m(`config`,h(`provider.profile_configuration`,{profile:e.id,field:t}));Vn(e),Bn(e),zn(e),Rn(e),e.labels&&ve(e.labels,`Profile ${e.id}`);for(let t of _e)if(e.labels?.[t]!==void 0)throw new m(`config`,`Profile ${e.id}: labels '${t}' is a host line, which a profile cannot change; set it with overrideLabels`);if(Jn(e),qn(e),e.type===`host`)return On(e);if(e.type===`decision`)return En(e);if(e.type===`embedding`)return bn(e);if(e.type===`transcription`)return xn(e);J(e.id,e.models),Hn(e.id,e),Z(e.id,e.guardrails),e.type===`text`&&Un(e.id,e.outputs?.validation),Q(e.id,e.observability);for(let[t,n]of Object.entries(e.models))Y(e.id,t,n);let t=e.type===`speech`?{handle:e.identity.handle}:{handle:e.identity.handle,conditions:e.identity.conditions,system:e.identity.system},n=e.guardrails,r=e.observability,i=e.labels,a=Mn(e),o;switch(e.type){case`text`:o={type:`text`,id:e.id,identity:t,...a,tools:e.tools,inputs:B(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:B(e.inputs),outputs:e.outputs,turnBehaviour:e.turnBehaviour,guardrails:n,observability:r,labels:i},tr(o.id,o.inputs.attachments?.accept),er(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?B(e.inputs):e.inputs,tools:{allow:e.tools.allow,...Dn(e.tools.parallel)},turnBehaviour:e.turnBehaviour,guardrails:n,observability:r,labels:i},ke(o),rr(o.id,o.live.contextCompression),nr(o);break;default:throw new m(`config`,`Unknown profile type '${String(e)}'`)}return Qn(o),Xn(o),Zn(o),o}function Xn(e){let{maxSteps:t}=e;if(!(t===void 0||Number.isInteger(t)&&t>0))throw new m(`config`,`Profile ${e.id}: maxSteps must be a whole number of 1 or more; leave it out for the default of 20`)}function Zn(e){if(e.type===`text`&&e.turnBehaviour?.atStepLimit===`answer`&&e.maxSteps===1)throw new m(`config`,`Profile ${e.id}: turnBehaviour.atStepLimit 'answer' with maxSteps 1 leaves no step that can call a tool`)}function Qn(e){if(e.type===`live`)return;let t=e.outputs?.structured;if(!t||typeof t==`string`)return;let n=d(e)?.slots?.[t.by];if(!n)throw new m(`config`,`Profile ${e.id}: outputs.structured.by '${t.by}' is not a slot in inputs.slots`);let r=R(n),i=Object.keys(t.map).filter(e=>!r.includes(e));if(i.length)throw new m(`config`,`Profile ${e.id}: outputs.structured.map maps ${i.join(`, `)}, not a choice of slot '${t.by}'`)}var $n={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 er(e,t){for(let[n,{ok:r,rule:i}]of Object.entries($n)){let a=t[n];if(a!==void 0&&!r(a))throw new m(`config`,`Profile ${e}: image.${n} must be ${i}`)}t.references?.forEach((t,n)=>{let r=`Profile ${e}: image.references[${n}]`;if(pe(t.mimeType)!==`image`)throw new m(`config`,`${r} must be an image, not '${t.mimeType}'`);if(!(b(t)?t.uri:t.data))throw new m(`config`,`${r} needs its bytes or its uri`)})}function tr(e,t){let n=t?.filter(e=>!f(be,e));if(n?.length)throw new m(`config`,`Profile ${e}: an image profile's attachments take images, video, and PDF only, not ${n.join(`, `)}`)}function nr(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 m(`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 m(`config`,`${i}.resumed.prompt must be a prompt`);let{afterMs:a}=n;if(a!==void 0&&!(Number.isFinite(a)&&a>=0))throw new m(`config`,`${i}.resumed.afterMs must be 0 or more milliseconds`);if(!r)throw new m(`config`,`${i}.resumed needs live.sessionResumption: without it no call resumes`)}function rr(e,t){if(!t)return;let n=`Profile ${e} live.contextCompression`,r=t.triggerTokens,i=t.slidingWindow.targetTokens;if(ir(`${n}.triggerTokens`,r),ir(`${n}.slidingWindow.targetTokens`,i),r!==void 0&&i!==void 0&&i>=r)throw new m(`config`,`${n}: slidingWindow.targetTokens must be below triggerTokens`)}function ir(e,t){if(!(t===void 0||Number.isInteger(t)&&t>0))throw new m(`config`,`${e} must be a whole number above 0`)}function ar(e,t,n,r){let i=`Profile ${t.id} model ${n} compaction`;if(or(i,r),sr(i,r),r.meter!=null&&r.meter!==`history`&&r.meter!==`input`)throw new m(`config`,`${i}: meter must be 'history' or 'input'`);if(r.profile===void 0){if(t.type!==`text`||t.inputs.text===!1)throw new m(`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 m(`config`,`${i}: compaction profile '${r.profile}' must be registered before '${t.id}'`);if(a.type!==`text`||a.inputs.text===!1)throw new m(`config`,`${i}: compaction profile '${r.profile}' must be a text profile that takes text`)}function or(e,t){if(t.maxTokens<=0)throw new m(`config`,`${e}: maxTokens must be > 0`);if(t.compactAt<=0||t.compactAt>=1)throw new m(`config`,`${e}: compactAt must be in (0, 1)`)}function sr(e,t){if(t.previousExchanges<0)throw new m(`config`,`${e}: previousExchanges must be >= 0`);if(t.previousExchanges<1&&t.previousExchanges>=t.compactAt)throw new m(`config`,`${e}: previousExchanges as fraction (${t.previousExchanges}) must be < compactAt (${t.compactAt})`);if(t.previousExchanges>1&&!Number.isInteger(t.previousExchanges))throw new m(`config`,`${e}: previousExchanges >= 1 must be an integer`)}function cr(e,t){for(let n of A(t))if(e.get(n)?.type===`builtin`)throw new m(`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 lr(e,t){let n=j(t)?.t2Loader;if(n){if(!A(t).includes(n))throw new m(`config`,`Profile ${t.id} tools.t2Loader '${n}' must also be listed in tools.allow`);if(e.get(n)?.type!==`function`)throw new m(`config`,`Profile ${t.id} tools.t2Loader '${n}' must be a registered type: 'function' tool`)}}function*ur(e){for(let[t,n]of Object.entries(e.models))for(let e of n.builtInTools??[])yield{modelId:t,id:e}}function dr(e,t){for(let{modelId:n,id:r}of ur(t))if(e.get(r)?.type!==`builtin`)throw new m(`config`,`Profile ${t.id} model '${n}' lists '${r}' in builtInTools — not a registered builtin`)}function fr(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 pr(e,t){let n=fr(t).map(n=>{let r=e.find(n);if(!r)throw new m(`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 m(`config`,`Profile ${t.id}: outputs.validation checks a structured reply, so it needs outputs.structured`);let o=a.filter(e=>!n.some(t=>Jt(t.jsonSchema,e)));if(o.length)throw new m(`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=>Ut(t.jsonSchema,e)));if(s.length)throw new m(`config`,`Profile ${t.id}: outputs.validation.fields has ${s.join(`, `)}, which no structured schema reaches through object properties`)}function mr(e){let t=d(e)?.context;if(!t)return;let n=_;if(t.from.length===0||t.from.some(e=>!n.includes(e)))throw new m(`config`,`Profile ${e.id}: inputs.context.from must list ${_.join(` or `)}`);if(!(Number.isInteger(t.maxChars)&&t.maxChars>0))throw new m(`config`,`Profile ${e.id}: inputs.context.maxChars must be a positive integer`)}function hr(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 m(`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 m(`config`,`Profile ${e}: inputs.${t} must be a positive integer`)}function gr(e,t,n){let r=new Map,i=i=>{let a=Yn(i),o=n&&a.type!==`host`?{...a,models:Object.fromEntries(Object.entries(a.models).map(([e,t])=>[e,oe(n.require(t.provider,t.apiId),t,a.type)]))}:a;if(cr(e,o),lr(e,o),o.type!==`host`&&o.type!==`decision`&&o.type!==`embedding`){dr(e,o),hr(o.id,d(o)),mr(o),pr(t,o);for(let[e,t]of Object.entries(o.models))t.compaction&&ar(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 m(`config`,`Unknown profile '${e}'`);return t},find:e=>r.get(e),has:e=>r.has(e),list:()=>[...r.values()],clear:()=>r.clear()}}function _r(e){let t=e?.trim()??``;if(t.startsWith(`AIza`))return`gemini`;if(t.startsWith(`sk-or-`))return`openrouter`}function vr(e){let t;try{t=new URL(e.baseUrl)}catch{throw new m(`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 m(`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 m(`blocked`,`Local requests must stay on the configured origin.`))}}var yr=l({data:s(l({id:n().min(1)}))});async function br(e,t){let n=vr(e);if(!n?.fetch)throw new m(`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 m(`network`,`Local model list returned HTTP ${r.status}.`);let i=yr.safeParse(await r.json());if(!i.success)throw new m(`request`,`The endpoint returned an invalid model list.`);return[...new Set(i.data.data.map(e=>e.id))]}var xr=`https://openrouter.ai/api/v1/models`,Sr=`https://openrouter.ai/api/v1/embeddings/models`,Cr=[{id:`gemini-embedding-2-preview`,label:`Gemini Embeddings 2 (preview)`},{id:`gemini-embedding-001`,label:`Gemini Embedding 001`}],wr=[{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)`}],Tr={text:`text`,image:`image`,speech:`speech`,transcription:`transcription`,live:void 0,embedding:void 0},Er=l({data:s(l({id:n().min(1),name:n().optional(),architecture:l({output_modalities:s(n()).optional()}).optional()}))}),Dr=l({data:s(l({id:n().min(1),name:n().optional()}))}),Or=l({models:s(l({name:n().min(1),displayName:n().optional(),supportedGenerationMethods:s(n()).optional()})).optional(),nextPageToken:n().optional()}),kr=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 m(`auth`,`${e} refused the key.`);if(!r.ok)throw new m(`network`,`${e} model list returned HTTP ${r.status}.`);return await r.json()}async function Ar(e,t,n,r){let i=n?.trim();if(t===`embedding`&&!i)return[...e===`openrouter`?wr:Cr];if(e===`openrouter`)return await jr(t,i,r);if(!i)throw new m(`auth`,`Choose a key to list Gemini models.`);return await Nr(t,i,r)}async function jr(e,t,n){let r={signal:n,headers:{Accept:`application/json`,...t?{Authorization:[`Bearer`,t].join(` `)}:{}}};if(e===`embedding`){let e=Dr.safeParse(await $(`OpenRouter`,Sr,r));if(!e.success)throw new m(`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=Tr[e];if(!i)return[];let a=Er.safeParse(await $(`OpenRouter`,`${xr}?output_modalities=${i}`,r));if(!a.success)throw new m(`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 Mr={live:`bidiGenerateContent`,embedding:`embedContent`};async function Nr(e,t,n){let r=Mr[e]??`generateContent`,i=[],a;for(let e=0;e<kr;e++){let e=new URL(ne);e.searchParams.set(`pageSize`,`1000`),a&&e.searchParams.set(`pageToken`,a);let o=Or.safeParse(await $(`Google`,e.href,{signal:n,headers:{Accept:`application/json`,"x-goog-api-key":t}}));if(!o.success)throw new m(`bad_response`,`Google returned an invalid model list.`);for(let e of o.data.models??[]){if(!e.supportedGenerationMethods?.includes(r))continue;let t=e.name.replace(/^models\//,``);i.push({id:t,label:e.displayName??t})}if(a=o.data.nextPageToken,!a)break}return i}function Pr(e){return[...new Set([e.key,e.fallbackKey,...Object.values(e.models??{}).flatMap(e=>[e.keySlot,e.fallbackKeySlot])].filter(e=>!!e))]}function Fr(e,t){return Object.fromEntries(e.map(e=>[e,Object.hasOwn(t,e)?t[e]:void 0]))}export{y as $,jt as A,_t as B,Ht as C,Kt as D,Gt as E,xt as F,it as G,ht as H,j as I,We as J,nt as K,Pt as L,Nt as M,At as N,z as O,A as P,b as Q,I as R,qt as S,Jt as T,T as U,D as V,st as W,Ge as X,C as Y,Ke as Z,on as _,Pr as a,pn as b,Yn as c,q as d,Ze as et,gn as f,dn as g,an as h,vr as i,F as j,R as k,vn as l,ln as m,br as n,Fr as o,Yt as p,rt as q,Ar as r,gr as s,_r as t,_n as u,fn as v,Wt as w,rn as x,un as y,P as z};