@theoremjs/studio 0.3.4-next.693.g4ab1526 → 0.3.4-next.711.g78e504a
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.
- package/agreement.js +35 -5
- package/compile.d.ts +3 -3
- package/compile.js +43 -20
- package/cookbooks/catalog.js +8 -10
- package/draft.d.ts +12 -9
- package/draft.js +4 -4
- package/mod.d.ts +1 -2
- package/mod.js +1 -2
- package/package.json +4 -4
- package/page/assets/Banner-GFaYsfrc.js +3 -0
- package/page/assets/{ConsoleFrame-BvgFGqp2.js → ConsoleFrame-KmyDVQkS.js} +1 -1
- package/page/assets/{MenuBottomSheet-BZecY8fw.js → MenuBottomSheet-BSQO5V7g.js} +1 -1
- package/page/assets/{SchemaFields-BNNkvyyO.js → SchemaFields-CIsMisSq.js} +1 -1
- package/page/assets/{ToolResultCharts-C3CPsfXl.js → ToolResultCharts-95plvcj4.js} +1 -1
- package/page/assets/{TraceInspector-36e6ozKD.js → TraceInspector-D2113s73.js} +1 -1
- package/page/assets/{TraceOverview-CSdJ_cYY.js → TraceOverview-Bz2EnBzL.js} +1 -1
- package/page/assets/{_virtual_studio-type-sources-DSpwr3WK.js → _virtual_studio-type-sources-La9AcR1O.js} +218 -85
- package/page/assets/browser-connection-B2a2EaIg.js +3 -0
- package/page/assets/browser-engine--lGbAmPM.js +13 -0
- package/page/assets/{browser-transport-GzhRiBdm.js → browser-transport-h1KAGUN4.js} +3 -3
- package/page/assets/{crypto-B8dqEoWf.js → crypto-BnoW7FFO.js} +1 -1
- package/page/assets/{encode-files-CHeRLBO8.js → encode-files-DoLGXgup.js} +1 -1
- package/page/assets/{export-agent-botXSyoH.js → export-agent-CA42Pf8A.js} +1 -1
- package/page/assets/{guardrail-tester-DYR7EPIy.js → guardrail-tester-fDJlewVB.js} +1 -1
- package/page/assets/{index-B7sK7d-l.js → index-Bd7U_fu_.js} +72 -76
- package/page/assets/{labels-provider-t4c-5JMk.js → labels-provider-uONlWExD.js} +1 -1
- package/page/assets/{live-messages-DN_q2nBN.js → live-messages-CTL-QEqM.js} +1 -1
- package/page/assets/people-CIsR0-5R.js +1 -0
- package/page/assets/reader-COeSYhdZ.js +5 -0
- package/page/assets/{shaped-data-CJQ3W_RE.js → shaped-data-7q5Be8sp.js} +3 -3
- package/page/assets/{stub-U6wDGe3P.js → stub-DJBcKncO.js} +1 -1
- package/page/assets/studio-code-pane-MXm30Ppv.js +10 -0
- package/page/assets/{studio-console-B7zL133d.js → studio-console-dHEr6mr5.js} +1 -1
- package/page/assets/{studio-decision-CbRjfbvG.js → studio-decision-BoSmTyjn.js} +1 -1
- package/page/assets/{studio-embedding-DQ0QrEsu.js → studio-embedding-B5E__vsY.js} +1 -1
- package/page/assets/studio-host-console-CadL7PPh.js +2 -0
- package/page/assets/{studio-labels-jYWBoEyP.js → studio-labels-sxDmOFeL.js} +1 -1
- package/page/assets/{studio-live-D0YRu2zQ.js → studio-live-Cgt4zKeL.js} +1 -1
- package/page/assets/{studio-map-C4Ra1QqL.js → studio-map-BgeqrIh_.js} +1 -1
- package/page/assets/studio-session-ClF2iNCX.js +1 -0
- package/page/assets/{studio-trace-replay-D-f2p7k9.js → studio-trace-replay-BqYGBZ1t.js} +1 -1
- package/page/assets/{studio-type-checker-CVNPnko-.js → studio-type-checker-DutkTKte.js} +1 -1
- package/page/assets/{tool-schema-BDG2_rlP.js → tool-schema-m1KPujBp.js} +2 -2
- package/page/assets/{trace-record-DoXjxrmJ.js → trace-record-Dm2jEhUR.js} +1 -1
- package/page/assets/tree-5tuw5ISS.js +3 -0
- package/page/assets/turn-client-BmadRouD.js +2 -0
- package/page/assets/{use-one-call-B3t-kfc5.js → use-one-call-IXfdRlUH.js} +1 -1
- package/page/assets/use-second-ticker-D6JSf9B3.js +1 -0
- package/page/assets/{workspace-DUfaxr-g.js → workspace-CMUi6xcQ.js} +1 -1
- package/page/index.html +18 -17
- package/read-source.js +41 -8
- package/registrations.d.ts +9 -1
- package/runtime.js +1 -0
- package/section-notes.d.ts +1 -0
- package/section-notes.js +1 -0
- package/serve-page.mjs +8 -4
- package/server/handler.d.ts +0 -3
- package/server/handler.js +4 -26
- package/server/live.d.ts +1 -2
- package/server/live.js +3 -4
- package/server/save-plan.js +2 -1
- package/system-markup.d.ts +9 -7
- package/system-markup.js +38 -19
- package/tools.js +1 -0
- package/types.d.ts +3 -0
- package/ui/inspector-context.d.ts +1 -8
- package/ui/inspector-context.js +0 -7
- package/ui/inspector.d.ts +43 -1
- package/ui/inspector.js +50 -9
- package/ui/lib/entries.d.ts +13 -0
- package/ui/lib/entries.js +43 -0
- package/ui/lib/project-traces.js +2 -10
- package/ui/lib/studio-prefs.d.ts +0 -4
- package/ui/lib/studio-prefs.js +0 -7
- package/ui/lib/studio-project.d.ts +2 -5
- package/ui/lib/studio-project.js +1 -4
- package/ui/profile-editor.js +37 -49
- package/ui/studio-screen.d.ts +0 -1
- package/ui/studio-screen.js +8 -18
- package/ui/studio-settings.js +1 -12
- package/asks.d.ts +0 -61
- package/asks.js +0 -78
- package/page/assets/Banner-DrRNC3MG.js +0 -4
- package/page/assets/browser-connection-dads1eyK.js +0 -3
- package/page/assets/browser-engine-CugH58NS.js +0 -13
- package/page/assets/reader-DHN96tSr.js +0 -5
- package/page/assets/studio-code-pane-Boy63AK2.js +0 -8
- package/page/assets/studio-host-console-DDA2Um2-.js +0 -2
- package/page/assets/studio-session-CPnJaHc-.js +0 -1
- package/page/assets/tree-CcEbNvms.js +0 -3
- package/page/assets/turn-client-BmOSpCgw.js +0 -2
- package/page/assets/use-second-ticker-CWjCHLG6.js +0 -1
- package/ui/confirm-write.d.ts +0 -12
- package/ui/confirm-write.js +0 -45
|
@@ -4760,14 +4760,15 @@ export { applyStageResult, STAGE_AFFORDANCE_MATRIX, STAGE_AFFORDANCES, stageAllo
|
|
|
4760
4760
|
export type { MediaTurnBehaviourSpec, ProfileTurnBehaviourSpec, ProfileTurnResumptionSpec, TurnContinueFrom, TurnStop, } from './src/kernel/stop.js';
|
|
4761
4761
|
export { AUTO_CONTINUE_DELAY_MS, DEFAULT_ALLOW_CONTINUE, DEFAULT_AUTO_CONTINUE, GenerationStopError, isContinueStopKind, isGenerationStopError, isResumeableStop, isUserCancelledStop, profileAllowsInject, profileAllowsSteering, profileTurnResumption, shouldAutoContinue, turnStopFromClientStreamEnd, turnStopFromInteractionStatus, turnStopFromOpenAiFinishReason, } from './src/kernel/stop.js';
|
|
4762
4762
|
export { systemLinesProblem } from './src/kernel/system-lines.js';
|
|
4763
|
+
export type { ToolBackground, ToolBackgroundCall, ToolBackgroundHandle, ToolBackgroundService, } from './src/kernel/tools/background.js';
|
|
4763
4764
|
export { authorizeToolReplay } from './src/kernel/tools/execute.js';
|
|
4764
4765
|
export { GATE_DECISIONS, type GateDecision } from './src/kernel/tools/gate-answer.js';
|
|
4765
4766
|
export type { MemoryToolExecutionOptions } from './src/kernel/tools/memory-execution.js';
|
|
4766
4767
|
export { createMemoryToolExecution } from './src/kernel/tools/memory-execution.js';
|
|
4767
4768
|
export type { CredentialQuery, McpProtocolVersion, McpRpcResponse, ToolRegistry, } from './src/kernel/tools/mod.js';
|
|
4768
4769
|
export { askUserTool, buildHttpToolTarget, createToolRegistry, credentialPlacement, executeHttpTool, executeMcpTool, formatToolResult, isUnsupportedMcpProtocolError, MCP_PROTOCOL_VERSIONS, mcpRequestMeta, parseMcpRpcResponse, prepareTurnToolSnapshot, registerHarnessTools, resolveToolAuth, UncheckedOutput, uncheckedOutput, withCredentialQuery, } from './src/kernel/tools/mod.js';
|
|
4769
|
-
export type { BeginToolOperationResult, PageToolDispatch, PageToolExecution, SavedToolInvocation, TerminalToolEvent, ToolExecutionCoordinator, ToolOperationClaim, ToolOperationIdentity, ToolOperationOutcome, ToolOperationUncertainty, } from './src/kernel/tools/operation.js';
|
|
4770
|
-
export { savedToolInvocationSchema, toolInvocationHash, toolOperationOutcomeSchema, } from './src/kernel/tools/operation.js';
|
|
4770
|
+
export type { BackgroundToolEvent, BeginToolOperationResult, PageToolDispatch, PageToolExecution, SavedToolInvocation, TerminalToolEvent, ToolExecutionCoordinator, ToolOperationClaim, ToolOperationIdentity, ToolOperationOutcome, ToolOperationReply, ToolOperationUncertainty, } from './src/kernel/tools/operation.js';
|
|
4771
|
+
export { savedToolInvocationSchema, toolInvocationHash, toolOperationOutcomeSchema, toolOperationReplySchema, } from './src/kernel/tools/operation.js';
|
|
4771
4772
|
export type { SettledToolCall, ToolCallResult, ToolStepCallResult, } from './src/kernel/tools/run.js';
|
|
4772
4773
|
export type { ModelToolResult, PageAnswer, ToolContext } from './src/kernel/tools/types.js';
|
|
4773
4774
|
export { awaitingUserInputSchema, type GateReference, gateReferenceSchema, isAwaitingUserInput, keptReply, reasoningPartSchema, TURN_EVENT_SCHEMAS, toolGateSchema, turnDoneOf, turnEventSchema, turnHistoryMessageSchema, turnToolSnapshotSchema, } from './src/kernel/turn-events.js';
|
|
@@ -5217,6 +5218,7 @@ export declare const providerLimitsSchema: z.ZodType<ProviderLimits>;
|
|
|
5217
5218
|
import type { JsonObject } from './json.js';
|
|
5218
5219
|
import type { CacheMode, CacheTtl, CompactionMeter, CompactionOutcome, CompactionTiming, ContextSender, ContinueStopKind, FieldMeta, KeySlot, KeyVault, LiveActivityHandling, LiveEndSensitivity, LiveStartSensitivity, MediaInputKind, ProfileType, SpeechAudioFormat, StreamMode, SummaryMode, ThinkingLevel, ToolLoadTier, TurnStage, TurnStopKind } from './schema.js';
|
|
5219
5220
|
import type { StageHandler } from './stages.js';
|
|
5221
|
+
import type { ToolBackgroundService } from './tools/background.js';
|
|
5220
5222
|
import type { GateDecision } from './tools/gate-answer.js';
|
|
5221
5223
|
import type { PageToolExecution, ToolExecutionCoordinator } from './tools/operation.js';
|
|
5222
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';
|
|
@@ -5974,6 +5976,7 @@ export interface TurnTraceLink {
|
|
|
5974
5976
|
/** A request to \`runTurn\`: the profile, the input, and the host's hooks and keys. */
|
|
5975
5977
|
export interface TurnRequest {
|
|
5976
5978
|
execution?: ToolExecutionCoordinator;
|
|
5979
|
+
background?: ToolBackgroundService;
|
|
5977
5980
|
pageExecution?: PageToolExecution;
|
|
5978
5981
|
providerState?: ProviderCheckpoint;
|
|
5979
5982
|
profile: ProfileId;
|
|
@@ -6035,6 +6038,12 @@ export interface TurnRequest {
|
|
|
6035
6038
|
* Compared to \`profile.turnBehaviour.resumption.maxContinues\` when that cap is set.
|
|
6036
6039
|
*/
|
|
6037
6040
|
continuation?: number;
|
|
6041
|
+
/**
|
|
6042
|
+
* Tools this reply already had when an earlier run of it paused. The turn opens with them on its
|
|
6043
|
+
* list, so an answered call does not take back what the model loaded. An id \`tools.allow\` or the
|
|
6044
|
+
* path does not grant is left out, as for \`tools.t1Policy\`.
|
|
6045
|
+
*/
|
|
6046
|
+
promoted?: ToolId[];
|
|
6038
6047
|
input?: TurnInput;
|
|
6039
6048
|
/** Credentials for authenticated HTTP / MCP tools, read by auth slot when a tool needs one. */
|
|
6040
6049
|
credentials?: ToolCredentialSource;
|
|
@@ -6796,6 +6805,8 @@ export interface TurnToolSnapshot {
|
|
|
6796
6805
|
path?: string;
|
|
6797
6806
|
sessionPermissions?: string[];
|
|
6798
6807
|
wire: WireFunctionTool[];
|
|
6808
|
+
/** The request has a background service, so \`ask\` tools offer the \`background\` argument. */
|
|
6809
|
+
modelBackground?: boolean;
|
|
6799
6810
|
}
|
|
6800
6811
|
/** The schema a tool snapshot parses against. */
|
|
6801
6812
|
export declare const turnToolSnapshotSchema: z.ZodType<TurnToolSnapshot>;
|
|
@@ -6901,12 +6912,17 @@ export type ToolPhaseEvent = ToolPhaseBase & ({
|
|
|
6901
6912
|
readBack?: string;
|
|
6902
6913
|
parts?: InteractionPart[];
|
|
6903
6914
|
activityPast?: string;
|
|
6904
|
-
/** An agent tool's call: the called agent's own usage
|
|
6915
|
+
/** An agent tool's call: the called agent's own usage. The caller's \`done.tokens\` includes it, unless the call settled after \`done\`. */
|
|
6905
6916
|
tokens?: TurnTokens;
|
|
6906
6917
|
} | {
|
|
6907
6918
|
phase: 'gate';
|
|
6908
6919
|
gate: ToolGate;
|
|
6909
6920
|
readBack?: string;
|
|
6921
|
+
}
|
|
6922
|
+
/** The model reads \`readBack\` now and the call goes on; its real end reaches the host alone. */
|
|
6923
|
+
| {
|
|
6924
|
+
phase: 'background';
|
|
6925
|
+
readBack: string;
|
|
6910
6926
|
} | {
|
|
6911
6927
|
phase: 'error';
|
|
6912
6928
|
failure: ToolFailure;
|
|
@@ -7993,7 +8009,7 @@ export { applySpans, blobAt, mergeSpans, OMIT_CANARY, OMIT_INJECTION, OMIT_PROMP
|
|
|
7993
8009
|
`,"file:///node_modules/@theoremjs/agents/src/guardrails/labels.d.ts":`/** Values that fill a label template's \`{param}\` placeholders. */
|
|
7994
8010
|
export type LabelParams = Record<string, string | number>;
|
|
7995
8011
|
/** Keys are stable API. */
|
|
7996
|
-
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.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"];
|
|
8012
|
+
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"];
|
|
7997
8013
|
/** One of {@linkcode LABEL_KEYS}. */
|
|
7998
8014
|
export type LabelKey = (typeof LABEL_KEYS)[number];
|
|
7999
8015
|
/**
|
|
@@ -9000,6 +9016,7 @@ import type { AuthUnauthenticatedPolicy, HttpMethod, ToolAccess, ToolAuthType, T
|
|
|
9000
9016
|
import type { RemovedItem, Source, ToolCallEdit, ToolCallEvent, ToolCallRequest, ToolFailure, ToolGate, ToolPhaseEvent, ToolTraceStep, ToolWarning, TurnToolSnapshot, WireFunctionTool } from '../turn-events.js';
|
|
9001
9017
|
import type { InteractionPart, ModelId, Profile, ProfileId, ToolId, TurnInput, TurnRequest, TurnSpeech, TurnTraceLink } from '../types.js';
|
|
9002
9018
|
import type { LabelTemplate } from './activity-label.js';
|
|
9019
|
+
import type { ToolBackground, ToolBackgroundService } from './background.js';
|
|
9003
9020
|
import type { PageToolExecution, ToolExecutionCoordinator } from './operation.js';
|
|
9004
9021
|
import type { UncheckedOutput } from './unchecked-output.js';
|
|
9005
9022
|
export type { AuthUnauthenticatedPolicy, HttpMethod, ToolAccess, ToolAuthType, ToolCallEdit, ToolCallEvent, ToolCallRequest, ToolFailure, ToolGate, ToolPermission, ToolPhaseEvent, ToolTraceStep, ToolWarning, TurnToolSnapshot, WireFunctionTool, };
|
|
@@ -9149,6 +9166,10 @@ export interface ToolHostHooks<TIn = unknown> {
|
|
|
9149
9166
|
exposeToModel?: boolean;
|
|
9150
9167
|
/** The model gets an \`after\` field: the tools in the same step that must settle before this call starts. */
|
|
9151
9168
|
after?: boolean;
|
|
9169
|
+
/** When the model gets its reply. Unset is \`never\`: when the body ends. A turn without a background service runs inline. */
|
|
9170
|
+
background?: ToolBackground;
|
|
9171
|
+
/** \`inputSchema\` with the \`background\` argument. The registry sets it on an \`ask\` tool. */
|
|
9172
|
+
askInputSchema?: Record<string, unknown>;
|
|
9152
9173
|
}
|
|
9153
9174
|
export interface ToolOutputHooks<TOut = unknown> {
|
|
9154
9175
|
/** A source that fails \`sourceSchema\`, or a throw, is a \`sources_invalid\` warning and is not cited. */
|
|
@@ -9311,6 +9332,7 @@ export interface AgentToolDef extends ToolBase {
|
|
|
9311
9332
|
hostOnly?: AgentToolChannel[];
|
|
9312
9333
|
preTool?: ToolHostHooks<AgentToolInput>['preTool'];
|
|
9313
9334
|
after?: ToolHostHooks<AgentToolInput>['after'];
|
|
9335
|
+
background?: ToolHostHooks<AgentToolInput>['background'];
|
|
9314
9336
|
exposeToModel?: boolean;
|
|
9315
9337
|
}
|
|
9316
9338
|
export interface RegisteredAgentTool extends AgentToolDef, ToolHostHooks<AgentToolInput>, ToolOutputHooks<AgentToolOutput> {
|
|
@@ -9392,6 +9414,7 @@ export type ToolPolicy = (ctx: ToolLoadContext) => ToolId[] | Promise<ToolId[]>;
|
|
|
9392
9414
|
/** A request to run a held tool call outside a turn. */
|
|
9393
9415
|
export interface InvokeToolRequest {
|
|
9394
9416
|
execution?: ToolExecutionCoordinator;
|
|
9417
|
+
background?: ToolBackgroundService;
|
|
9395
9418
|
/** invariant: Only the trusted host restores the kernel-issued identity from saved authority. */
|
|
9396
9419
|
operationId?: string;
|
|
9397
9420
|
profile: string;
|
|
@@ -9767,6 +9790,18 @@ export interface PageToolDispatch {
|
|
|
9767
9790
|
export interface PageToolExecution {
|
|
9768
9791
|
dispatch(claim: ToolOperationClaim, signal?: AbortSignal): Promise<PageToolDispatch>;
|
|
9769
9792
|
}
|
|
9793
|
+
export type BackgroundToolEvent = TurnEventOf<'tool'> & {
|
|
9794
|
+
tool: Extract<TurnEventOf<'tool'>['tool'], {
|
|
9795
|
+
phase: 'background';
|
|
9796
|
+
}>;
|
|
9797
|
+
};
|
|
9798
|
+
/** What the model reads when a call goes on after its turn. */
|
|
9799
|
+
export interface ToolOperationReply {
|
|
9800
|
+
event: BackgroundToolEvent;
|
|
9801
|
+
replay: {
|
|
9802
|
+
modelResult: ModelToolResult;
|
|
9803
|
+
};
|
|
9804
|
+
}
|
|
9770
9805
|
export interface ToolOperationOutcome {
|
|
9771
9806
|
event: TerminalToolEvent;
|
|
9772
9807
|
effects: 'not_started' | 'completed' | 'unknown';
|
|
@@ -9790,6 +9825,9 @@ export type BeginToolOperationResult = {
|
|
|
9790
9825
|
} | {
|
|
9791
9826
|
kind: 'settled';
|
|
9792
9827
|
outcome: ToolOperationOutcome;
|
|
9828
|
+
} | {
|
|
9829
|
+
kind: 'background';
|
|
9830
|
+
reply: ToolOperationReply;
|
|
9793
9831
|
} | {
|
|
9794
9832
|
kind: 'running';
|
|
9795
9833
|
} | {
|
|
@@ -9806,6 +9844,11 @@ export interface ToolExecutionCoordinator {
|
|
|
9806
9844
|
kind: 'acquired';
|
|
9807
9845
|
}> | undefined>;
|
|
9808
9846
|
begin(operation: ToolOperationIdentity): Promise<BeginToolOperationResult>;
|
|
9847
|
+
/**
|
|
9848
|
+
* Keeps the reply the model reads for a call that goes on after its turn. The claim stays held
|
|
9849
|
+
* for \`settle\` or \`markUncertain\`. A coordinator without it cannot take a background service.
|
|
9850
|
+
*/
|
|
9851
|
+
detach?(claim: ToolOperationClaim, reply: ToolOperationReply): Promise<void>;
|
|
9809
9852
|
settle(claim: ToolOperationClaim, outcome: ToolOperationOutcome): Promise<void>;
|
|
9810
9853
|
settleNotStarted(operation: ToolOperationIdentity, outcome: ToolOperationOutcome): Promise<void>;
|
|
9811
9854
|
markUncertain(claim: ToolOperationClaim, reason: ToolOperationUncertainty): Promise<void>;
|
|
@@ -9817,9 +9860,167 @@ export declare function unresolvedOperation(kind: ErrorKind, reason: string, cau
|
|
|
9817
9860
|
/** The host asked to run an operation that is still running or uncertain, so the host settles it first. */
|
|
9818
9861
|
export declare function heldOperation(state: 'running' | 'uncertain'): TheoremError;
|
|
9819
9862
|
export declare function toolInvocationHash(value: unknown): Promise<string>;
|
|
9863
|
+
export declare const toolOperationReplySchema: z.ZodType<ToolOperationReply>;
|
|
9820
9864
|
export declare const toolOperationOutcomeSchema: z.ZodType<ToolOperationOutcome>;
|
|
9821
9865
|
export declare function operationWireValue(value: unknown): JsonValue;
|
|
9822
|
-
`,"file:///node_modules/@theoremjs/agents/src/guardrails/error.d.ts":"import type { TurnEventOf } from '../kernel/turn-events.js';\nimport type { TurnEvent } from '../kernel/types.js';\nimport { type LabelOverrides } from './labels.js';\nimport { type ErrorCopies, type ErrorKind, TheoremError } from './theorem-error.js';\n/** True when the value is an error named `AbortError`. */\ndeclare function isAbortError(err: unknown): boolean;\n/** `AbortSignal.timeout` rejects with a `TimeoutError`, not an `AbortError`. */\ndeclare function isTimeoutError(err: unknown): boolean;\n/** Throws when the signal has aborted: its framework, abort or timeout reason, else an `AbortError`. */\ndeclare function throwIfAborted(signal?: AbortSignal): void;\n/** Anything that is not a `TheoremError` or an abort escaped every boundary that names kinds: a THEOREM bug. */\ndeclare function errorKind(err: unknown): ErrorKind;\n/** The error kind for an HTTP status: 401, 402 and 403 are `auth`; 408, 504 and 524 `timeout`; 409 `conflict`; 429 `rate_limit`; 503 and 529 (overloaded) `busy`; 500 and above `unavailable`; the rest `unsupported`. */\ndeclare function kindOfHttpStatus(status: number): ErrorKind;\n/** The named reasons an error carries, one line each, in the profile's wording. */\ndeclare function errorCopyText(copy: ErrorCopies, labels?: LabelOverrides): string;\n/** Pass the profile's `labels`, or the profile's wording is skipped. */\ndeclare function publicError(err: unknown, labels?: LabelOverrides): string;\n/** Raw diagnostic for hosts, traces, and logs; never shown to end users. Each cause that says something new follows on its own line. */\ndeclare function describeError(err: unknown): string;\n/** fetch rejects only when no response came back, so any non-abort, non-timeout rejection is `network`. */\ndeclare function networkError(err: unknown): unknown;\n/** `send`, with a failed send or body read named as `networkError` names it. */\ndeclare function sendOrNetworkError(send: typeof fetch, ...args: Parameters<typeof fetch>): Promise<Response>;\ntype ProducedError = TurnEventOf<'error'> & {\n errorInternal: string;\n};\n/** No user wording yet: `withPublicLabels` adds it where the event reaches the host, the one place that knows the profile. */\ndeclare function toErrorEvent(err: unknown): ProducedError;\n/** Wording already set (host copy) is kept. */\ndeclare function withPublicLabels(event: TurnEvent, labels?: LabelOverrides): TurnEvent;\nexport type { ErrorCopies, ErrorCopy, ErrorKind, TheoremErrorOptions } from './theorem-error.js';\nexport { ERROR_KINDS } from './theorem-error.js';\nexport type { ProducedError };\nexport { describeError, errorCopyText, errorKind, isAbortError, isTimeoutError, kindOfHttpStatus, networkError, publicError, sendOrNetworkError, TheoremError, throwIfAborted, toErrorEvent, withPublicLabels, };\n","file:///node_modules/@theoremjs/agents/src/kernel/tools/
|
|
9866
|
+
`,"file:///node_modules/@theoremjs/agents/src/guardrails/error.d.ts":"import type { TurnEventOf } from '../kernel/turn-events.js';\nimport type { TurnEvent } from '../kernel/types.js';\nimport { type LabelOverrides } from './labels.js';\nimport { type ErrorCopies, type ErrorKind, TheoremError } from './theorem-error.js';\n/** True when the value is an error named `AbortError`. */\ndeclare function isAbortError(err: unknown): boolean;\n/** `AbortSignal.timeout` rejects with a `TimeoutError`, not an `AbortError`. */\ndeclare function isTimeoutError(err: unknown): boolean;\n/** Throws when the signal has aborted: its framework, abort or timeout reason, else an `AbortError`. */\ndeclare function throwIfAborted(signal?: AbortSignal): void;\n/** Anything that is not a `TheoremError` or an abort escaped every boundary that names kinds: a THEOREM bug. */\ndeclare function errorKind(err: unknown): ErrorKind;\n/** The error kind for an HTTP status: 401, 402 and 403 are `auth`; 408, 504 and 524 `timeout`; 409 `conflict`; 429 `rate_limit`; 503 and 529 (overloaded) `busy`; 500 and above `unavailable`; the rest `unsupported`. */\ndeclare function kindOfHttpStatus(status: number): ErrorKind;\n/** The named reasons an error carries, one line each, in the profile's wording. */\ndeclare function errorCopyText(copy: ErrorCopies, labels?: LabelOverrides): string;\n/** Pass the profile's `labels`, or the profile's wording is skipped. */\ndeclare function publicError(err: unknown, labels?: LabelOverrides): string;\n/** Raw diagnostic for hosts, traces, and logs; never shown to end users. Each cause that says something new follows on its own line. */\ndeclare function describeError(err: unknown): string;\n/** fetch rejects only when no response came back, so any non-abort, non-timeout rejection is `network`. */\ndeclare function networkError(err: unknown): unknown;\n/** `send`, with a failed send or body read named as `networkError` names it. */\ndeclare function sendOrNetworkError(send: typeof fetch, ...args: Parameters<typeof fetch>): Promise<Response>;\ntype ProducedError = TurnEventOf<'error'> & {\n errorInternal: string;\n};\n/** No user wording yet: `withPublicLabels` adds it where the event reaches the host, the one place that knows the profile. */\ndeclare function toErrorEvent(err: unknown): ProducedError;\n/** Wording already set (host copy) is kept. */\ndeclare function withPublicLabels(event: TurnEvent, labels?: LabelOverrides): TurnEvent;\nexport type { ErrorCopies, ErrorCopy, ErrorKind, TheoremErrorOptions } from './theorem-error.js';\nexport { ERROR_KINDS } from './theorem-error.js';\nexport type { ProducedError };\nexport { describeError, errorCopyText, errorKind, isAbortError, isTimeoutError, kindOfHttpStatus, networkError, publicError, sendOrNetworkError, TheoremError, throwIfAborted, toErrorEvent, withPublicLabels, };\n","file:///node_modules/@theoremjs/agents/src/kernel/tools/background.d.ts":`import { z } from 'zod';
|
|
9867
|
+
import { labelText } from '../../guardrails/labels.js';
|
|
9868
|
+
import type { SpanHandle, TraceAttributes } from '../../observability/trace-span.js';
|
|
9869
|
+
import type { TurnEvent } from '../types.js';
|
|
9870
|
+
import { type ToolCallBase } from './events.js';
|
|
9871
|
+
import { type ToolExecutionCoordinator, type ToolOperationReply } from './operation.js';
|
|
9872
|
+
/** When the model gets its reply: at the hand-off, past a time, if it asks, or when the body ends. */
|
|
9873
|
+
export type ToolBackground = 'always' | {
|
|
9874
|
+
afterMs: number;
|
|
9875
|
+
} | 'ask' | 'never';
|
|
9876
|
+
/** The call a detached event belongs to. */
|
|
9877
|
+
export interface ToolBackgroundCall {
|
|
9878
|
+
operationId: string;
|
|
9879
|
+
callId: string;
|
|
9880
|
+
toolId: string;
|
|
9881
|
+
}
|
|
9882
|
+
/** The host's hold on one detached call. */
|
|
9883
|
+
export interface ToolBackgroundHandle extends ToolBackgroundCall {
|
|
9884
|
+
/**
|
|
9885
|
+
* Stops the call. It settles as a \`cancelled\` failure with \`reason\` as its code, whatever the
|
|
9886
|
+
* body does. With no reason this is a shutdown: the call ends \`execution_interrupted\`. With
|
|
9887
|
+
* \`graceMs\`, a body that ignores its signal past that time settles anyway.
|
|
9888
|
+
*/
|
|
9889
|
+
stop(reason?: string, options?: {
|
|
9890
|
+
graceMs?: number;
|
|
9891
|
+
}): void;
|
|
9892
|
+
/** Resolves when the call has settled or been marked. */
|
|
9893
|
+
done: Promise<void>;
|
|
9894
|
+
}
|
|
9895
|
+
/** The host's service for detached calls. Without it every tool runs inline. */
|
|
9896
|
+
export interface ToolBackgroundService {
|
|
9897
|
+
detached(call: ToolBackgroundHandle): void;
|
|
9898
|
+
event(event: TurnEvent, call: ToolBackgroundCall): void | Promise<void>;
|
|
9899
|
+
}
|
|
9900
|
+
/** A detached call's own trace record, joined to its turn through \`traceparent\`. */
|
|
9901
|
+
export interface DetachedToolTrace {
|
|
9902
|
+
open: (name: string, attributes: TraceAttributes) => SpanHandle;
|
|
9903
|
+
end: () => void | Promise<void>;
|
|
9904
|
+
}
|
|
9905
|
+
/** The service with what a request adds: its event projection and where a detached trace goes. */
|
|
9906
|
+
export interface ToolBackgroundSupport {
|
|
9907
|
+
service: ToolBackgroundService;
|
|
9908
|
+
project: (event: TurnEvent) => TurnEvent;
|
|
9909
|
+
openTrace: (callId: string) => DetachedToolTrace;
|
|
9910
|
+
}
|
|
9911
|
+
export interface ToolDetach {
|
|
9912
|
+
at: 'claim' | {
|
|
9913
|
+
afterMs: number;
|
|
9914
|
+
};
|
|
9915
|
+
support: ToolBackgroundSupport;
|
|
9916
|
+
trace: DetachedToolTrace;
|
|
9917
|
+
reply: () => ToolOperationReply;
|
|
9918
|
+
}
|
|
9919
|
+
/** The \`ask\` argument, as the model reads it. */
|
|
9920
|
+
export declare function backgroundField(): z.ZodOptional<z.ZodBoolean>;
|
|
9921
|
+
/** The call's input without \`background\`, and whether the model asked for it. */
|
|
9922
|
+
export declare function splitBackground(tool: {
|
|
9923
|
+
background?: ToolBackground;
|
|
9924
|
+
} | undefined, input: unknown): {
|
|
9925
|
+
input: unknown;
|
|
9926
|
+
asked: boolean;
|
|
9927
|
+
};
|
|
9928
|
+
/** How this call detaches, or \`undefined\` when it runs inline. */
|
|
9929
|
+
export declare function planDetach(args: {
|
|
9930
|
+
tool: {
|
|
9931
|
+
background?: ToolBackground;
|
|
9932
|
+
name: string;
|
|
9933
|
+
} | undefined;
|
|
9934
|
+
input: unknown;
|
|
9935
|
+
support: ToolBackgroundSupport | undefined;
|
|
9936
|
+
base: ToolCallBase;
|
|
9937
|
+
labels: Parameters<typeof labelText>[2];
|
|
9938
|
+
}): ToolDetach | undefined;
|
|
9939
|
+
/** A late result needs a coordinator to keep it. */
|
|
9940
|
+
export declare function assertBackgroundCoordinator(service: ToolBackgroundService | undefined, execution: ToolExecutionCoordinator | undefined): void;
|
|
9941
|
+
/** A tool that must answer in an open turn cannot detach; only an object input takes \`background\`. */
|
|
9942
|
+
export declare function assertBackgroundSetting(tool: {
|
|
9943
|
+
name: string;
|
|
9944
|
+
background?: ToolBackground;
|
|
9945
|
+
answeredBy?: string;
|
|
9946
|
+
}): void;
|
|
9947
|
+
`,"file:///node_modules/@theoremjs/agents/src/kernel/tools/events.d.ts":`import type { z } from 'zod';
|
|
9948
|
+
import { type LabelOverrides } from '../../guardrails/labels.js';
|
|
9949
|
+
import type { GuardrailEvent, NetworkGuardrailSpec } from '../../guardrails/types.js';
|
|
9950
|
+
import type { SpanHandle } from '../../observability/trace-span.js';
|
|
9951
|
+
import { type Source } from '../turn-events.js';
|
|
9952
|
+
import type { TurnEvent, TurnEventOf } from '../types.js';
|
|
9953
|
+
import type { ToolOperationClaim } from './operation.js';
|
|
9954
|
+
import type { ToolCallRequest, ToolContext, ToolFailure, ToolLabels, ToolPhaseEvent } from './types.js';
|
|
9955
|
+
export type ToolCallBase = Pick<ToolPhaseEvent, 'name' | 'callId'> & {
|
|
9956
|
+
operationId?: string;
|
|
9957
|
+
/** The call's failed label, from {@linkcode failedActivity}; absent, a failure names the tool. */
|
|
9958
|
+
activityFailed?: string;
|
|
9959
|
+
};
|
|
9960
|
+
export type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;
|
|
9961
|
+
export type ToolPhasePatch = DistributiveOmit<ToolPhaseEvent, keyof ToolCallBase | 'at'>;
|
|
9962
|
+
export declare function toolEvent(base: ToolCallBase, patch: ToolPhasePatch): TurnEventOf<'tool'>;
|
|
9963
|
+
/**
|
|
9964
|
+
* The label a failed call shows: the tool's own, filled from the input the model sent, else the
|
|
9965
|
+
* labels' line naming the tool in words.
|
|
9966
|
+
*/
|
|
9967
|
+
export declare function failedActivity(name: string, profileLabels?: LabelOverrides, labels?: ToolLabels, input?: unknown): string;
|
|
9968
|
+
/** The failed label of the call \`base\` names. */
|
|
9969
|
+
export declare function failedActivityOf(base: ToolCallBase): string;
|
|
9970
|
+
/** \`readBack\` is passed when the call's result guard already wrote the model's text. */
|
|
9971
|
+
export declare function failureEvent(base: ToolCallBase, failure: ToolFailure, readBack?: string): TurnEventOf<'tool'>;
|
|
9972
|
+
/** The first event of every call. */
|
|
9973
|
+
export declare function toolCallRequestEvent(base: ToolCallBase, args: Record<string, unknown>, { reasoning, stepId, stepCallCount, }?: Pick<ToolCallRequest, 'reasoning' | 'stepId' | 'stepCallCount'>): TurnEventOf<'tool'>;
|
|
9974
|
+
/** Unique: readers join a call's events by it. */
|
|
9975
|
+
export declare function newCallId(name: string): string;
|
|
9976
|
+
export declare function toolCallArguments(safeInput: unknown): Record<string, unknown>;
|
|
9977
|
+
export declare function messageOf(err: unknown): string;
|
|
9978
|
+
export declare function sourceEvents(base: ToolCallBase, sources: (output: unknown) => Source[], output: unknown): Generator<TurnEvent>;
|
|
9979
|
+
/** A call's claim, taken once at the hand-off: right before the destination is asked. */
|
|
9980
|
+
export declare class HandOff {
|
|
9981
|
+
private begin?;
|
|
9982
|
+
private taken?;
|
|
9983
|
+
private failed?;
|
|
9984
|
+
constructor(begin?: (() => Promise<ToolOperationClaim | undefined>) | undefined);
|
|
9985
|
+
claim(): Promise<ToolOperationClaim | undefined>;
|
|
9986
|
+
/** The claim's own failure is the coordinator's, so no tool catch may turn it into a tool failure. */
|
|
9987
|
+
rethrowClaimFailure(): void;
|
|
9988
|
+
}
|
|
9989
|
+
export declare function dispatchToolBody(tool: {
|
|
9990
|
+
labels?: ToolLabels;
|
|
9991
|
+
}, input: unknown, ctx: ToolContext, base: ToolCallBase, beginBody?: (preparedInput: unknown) => Promise<ToolOperationClaim | undefined>): AsyncGenerator<TurnEvent, HandOff>;
|
|
9992
|
+
export declare function startToolExecution<T>(tool: {
|
|
9993
|
+
input: z.ZodType<T>;
|
|
9994
|
+
}, rawInput: unknown, ctx: ToolContext): {
|
|
9995
|
+
ok: true;
|
|
9996
|
+
data: T;
|
|
9997
|
+
} | {
|
|
9998
|
+
ok: false;
|
|
9999
|
+
failure: ToolFailure;
|
|
10000
|
+
};
|
|
10001
|
+
export declare function networkBlockedEvent(): GuardrailEvent;
|
|
10002
|
+
export declare function networkBlocked(err: unknown, guardrail?: GuardrailEvent): Generator<TurnEvent, ToolFailure>;
|
|
10003
|
+
/**
|
|
10004
|
+
* Shared by HTTP and MCP so they cannot diverge on what SSRF enforcement means.
|
|
10005
|
+
* The check's time goes on the tool's span, when the call is traced.
|
|
10006
|
+
*/
|
|
10007
|
+
export declare function guardToolTarget(url: string, ctx: ToolContext, span?: SpanHandle): Generator<TurnEvent, {
|
|
10008
|
+
ok: true;
|
|
10009
|
+
url: URL;
|
|
10010
|
+
} | {
|
|
10011
|
+
ok: false;
|
|
10012
|
+
failure: ToolFailure;
|
|
10013
|
+
}>;
|
|
10014
|
+
/** The checks a guarded request runs on its way, timed together: each hop's address, and its lookup. */
|
|
10015
|
+
export interface RequestChecks {
|
|
10016
|
+
/** Pass as \`fetchGuarded\`'s \`onCheck\`. */
|
|
10017
|
+
onCheck: (ms: number) => void;
|
|
10018
|
+
/** Records the checks once, when any ran, with the block they raised. */
|
|
10019
|
+
record: (blocked?: GuardrailEvent) => void;
|
|
10020
|
+
}
|
|
10021
|
+
export declare function requestChecks(span: SpanHandle | undefined): RequestChecks;
|
|
10022
|
+
export declare function toolNetworkPolicy(ctx: ToolContext): NetworkGuardrailSpec | undefined;
|
|
10023
|
+
`,"file:///node_modules/@theoremjs/agents/src/kernel/tools/activity-label.d.ts":`/** One line of wording, or a list of lines read top to bottom: the first that fits is shown. */
|
|
9823
10024
|
export type LabelTemplate = string | readonly string[];
|
|
9824
10025
|
/** \`expected: null\` is the check "is null". */
|
|
9825
10026
|
export type Check = {
|
|
@@ -10412,9 +10613,9 @@ export { clearTraceDestinations, getTraceDestination, isTraceSink, listTraceDest
|
|
|
10412
10613
|
*/
|
|
10413
10614
|
import type { ToolPhaseEvent, TurnEvent } from '../turn-events.js';
|
|
10414
10615
|
import type { StartedInvoke, StartedStep } from './invoke.js';
|
|
10415
|
-
/** The phase a call ends on: it completed, a gate held it, or it
|
|
10616
|
+
/** The phase a call ends on: it completed, a gate held it, it failed, or it went on in the background. */
|
|
10416
10617
|
export type SettledToolCall = Extract<ToolPhaseEvent, {
|
|
10417
|
-
phase: 'complete' | 'gate' | 'error';
|
|
10618
|
+
phase: 'complete' | 'gate' | 'error' | 'background';
|
|
10418
10619
|
}> & {
|
|
10419
10620
|
/** Kernel-issued identity; a gate's resume carries it. */
|
|
10420
10621
|
operationId?: string;
|
|
@@ -10694,8 +10895,8 @@ export declare function profileToolsSpec(profile: Profile): ProfileToolsSpec | u
|
|
|
10694
10895
|
export declare function profileToolsParallel(profile: Profile): boolean | undefined;
|
|
10695
10896
|
export declare function resolveAllowedCustomToolIds(tools: ToolRegistry, profile: Profile, req: TurnRequest): ToolId[];
|
|
10696
10897
|
export declare function resolveModelBuiltinIds(tools: ToolRegistry, profile: ModelProfile, req: TurnRequest, modelId: ModelId): ToolId[];
|
|
10697
|
-
export declare function wireForTool(tools: ToolRegistry, name: string): WireFunctionTool | undefined;
|
|
10698
|
-
export declare function buildWire(tools: ToolRegistry, visible: ToolId[]): WireFunctionTool[];
|
|
10898
|
+
export declare function wireForTool(tools: ToolRegistry, name: string, modelBackground?: boolean): WireFunctionTool | undefined;
|
|
10899
|
+
export declare function buildWire(tools: ToolRegistry, visible: ToolId[], modelBackground?: boolean): WireFunctionTool[];
|
|
10699
10900
|
export declare function promoteTool(tools: ToolRegistry, state: TurnToolSnapshot, id: ToolId): void;
|
|
10700
10901
|
export declare function promoteBuiltin(tools: ToolRegistry, state: TurnToolSnapshot, id: ToolId): void;
|
|
10701
10902
|
/** Live declarations are fixed at session setup, so every allowed tool there is effectively T0. */
|
|
@@ -10707,6 +10908,8 @@ export declare function prepareTurnToolSnapshot(tools: ToolRegistry, profile: Pr
|
|
|
10707
10908
|
/** So concurrent host invokes do not share mutable state. */
|
|
10708
10909
|
export declare function cloneTurnToolSnapshot(state: TurnToolSnapshot): TurnToolSnapshot;
|
|
10709
10910
|
export declare function expandT1Policy(tools: ToolRegistry, state: TurnToolSnapshot, profile: Profile, req: TurnRequest): Promise<void>;
|
|
10911
|
+
/** Puts the T2 tools among \`ids\` that the turn may call on its list; any other id is left out. */
|
|
10912
|
+
export declare function promoteTurnTools(tools: ToolRegistry, state: TurnToolSnapshot, ids?: readonly ToolId[]): void;
|
|
10710
10913
|
export declare function extractLoadedIds(output: unknown): string[] | undefined;
|
|
10711
10914
|
export declare function promoteLoadedTools(tools: ToolRegistry, state: TurnToolSnapshot, loaded: string[], profile: Profile): PromoteLoadedResult;
|
|
10712
10915
|
export declare function promotionTarget(tools: ToolRegistry, id: string, profile: Profile): {
|
|
@@ -10897,6 +11100,8 @@ export interface ToolStageSupport {
|
|
|
10897
11100
|
wait?: StepWait;
|
|
10898
11101
|
/** The host sees a handler's drafts: \`outputs.streaming.mode\` \`sse\`. Unset outside a turn's step. */
|
|
10899
11102
|
drafts?: boolean;
|
|
11103
|
+
/** Told when the body has ended, before \`post_tool\` reads it. */
|
|
11104
|
+
bodyEnded?: () => void;
|
|
10900
11105
|
}
|
|
10901
11106
|
export type PreBodyOutcome = {
|
|
10902
11107
|
ok: true;
|
|
@@ -10977,82 +11182,6 @@ export declare function emitGateSettlement(args: {
|
|
|
10977
11182
|
toolName: string;
|
|
10978
11183
|
labels: LabelOverrides | undefined;
|
|
10979
11184
|
}): AsyncGenerator<TurnEvent, string | undefined>;
|
|
10980
|
-
`,"file:///node_modules/@theoremjs/agents/src/kernel/tools/events.d.ts":`import type { z } from 'zod';
|
|
10981
|
-
import { type LabelOverrides } from '../../guardrails/labels.js';
|
|
10982
|
-
import type { GuardrailEvent, NetworkGuardrailSpec } from '../../guardrails/types.js';
|
|
10983
|
-
import type { SpanHandle } from '../../observability/trace-span.js';
|
|
10984
|
-
import { type Source } from '../turn-events.js';
|
|
10985
|
-
import type { TurnEvent, TurnEventOf } from '../types.js';
|
|
10986
|
-
import type { ToolOperationClaim } from './operation.js';
|
|
10987
|
-
import type { ToolCallRequest, ToolContext, ToolFailure, ToolLabels, ToolPhaseEvent } from './types.js';
|
|
10988
|
-
export type ToolCallBase = Pick<ToolPhaseEvent, 'name' | 'callId'> & {
|
|
10989
|
-
operationId?: string;
|
|
10990
|
-
/** The call's failed label, from {@linkcode failedActivity}; absent, a failure names the tool. */
|
|
10991
|
-
activityFailed?: string;
|
|
10992
|
-
};
|
|
10993
|
-
export type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;
|
|
10994
|
-
export type ToolPhasePatch = DistributiveOmit<ToolPhaseEvent, keyof ToolCallBase | 'at'>;
|
|
10995
|
-
export declare function toolEvent(base: ToolCallBase, patch: ToolPhasePatch): TurnEventOf<'tool'>;
|
|
10996
|
-
/**
|
|
10997
|
-
* The label a failed call shows: the tool's own, filled from the input the model sent, else the
|
|
10998
|
-
* labels' line naming the tool in words.
|
|
10999
|
-
*/
|
|
11000
|
-
export declare function failedActivity(name: string, profileLabels?: LabelOverrides, labels?: ToolLabels, input?: unknown): string;
|
|
11001
|
-
/** The failed label of the call \`base\` names. */
|
|
11002
|
-
export declare function failedActivityOf(base: ToolCallBase): string;
|
|
11003
|
-
/** \`readBack\` is passed when the call's result guard already wrote the model's text. */
|
|
11004
|
-
export declare function failureEvent(base: ToolCallBase, failure: ToolFailure, readBack?: string): TurnEventOf<'tool'>;
|
|
11005
|
-
/** The first event of every call. */
|
|
11006
|
-
export declare function toolCallRequestEvent(base: ToolCallBase, args: Record<string, unknown>, { reasoning, stepId, stepCallCount, }?: Pick<ToolCallRequest, 'reasoning' | 'stepId' | 'stepCallCount'>): TurnEventOf<'tool'>;
|
|
11007
|
-
/** Unique: readers join a call's events by it. */
|
|
11008
|
-
export declare function newCallId(name: string): string;
|
|
11009
|
-
export declare function toolCallArguments(safeInput: unknown): Record<string, unknown>;
|
|
11010
|
-
export declare function messageOf(err: unknown): string;
|
|
11011
|
-
export declare function sourceEvents(base: ToolCallBase, sources: (output: unknown) => Source[], output: unknown): Generator<TurnEvent>;
|
|
11012
|
-
/** A call's claim, taken once at the hand-off: right before the destination is asked. */
|
|
11013
|
-
export declare class HandOff {
|
|
11014
|
-
private begin?;
|
|
11015
|
-
private taken?;
|
|
11016
|
-
private failed?;
|
|
11017
|
-
constructor(begin?: (() => Promise<ToolOperationClaim | undefined>) | undefined);
|
|
11018
|
-
claim(): Promise<ToolOperationClaim | undefined>;
|
|
11019
|
-
/** The claim's own failure is the coordinator's, so no tool catch may turn it into a tool failure. */
|
|
11020
|
-
rethrowClaimFailure(): void;
|
|
11021
|
-
}
|
|
11022
|
-
export declare function dispatchToolBody(tool: {
|
|
11023
|
-
labels?: ToolLabels;
|
|
11024
|
-
}, input: unknown, ctx: ToolContext, base: ToolCallBase, beginBody?: (preparedInput: unknown) => Promise<ToolOperationClaim | undefined>): AsyncGenerator<TurnEvent, HandOff>;
|
|
11025
|
-
export declare function startToolExecution<T>(tool: {
|
|
11026
|
-
input: z.ZodType<T>;
|
|
11027
|
-
}, rawInput: unknown, ctx: ToolContext): {
|
|
11028
|
-
ok: true;
|
|
11029
|
-
data: T;
|
|
11030
|
-
} | {
|
|
11031
|
-
ok: false;
|
|
11032
|
-
failure: ToolFailure;
|
|
11033
|
-
};
|
|
11034
|
-
export declare function networkBlockedEvent(): GuardrailEvent;
|
|
11035
|
-
export declare function networkBlocked(err: unknown, guardrail?: GuardrailEvent): Generator<TurnEvent, ToolFailure>;
|
|
11036
|
-
/**
|
|
11037
|
-
* Shared by HTTP and MCP so they cannot diverge on what SSRF enforcement means.
|
|
11038
|
-
* The check's time goes on the tool's span, when the call is traced.
|
|
11039
|
-
*/
|
|
11040
|
-
export declare function guardToolTarget(url: string, ctx: ToolContext, span?: SpanHandle): Generator<TurnEvent, {
|
|
11041
|
-
ok: true;
|
|
11042
|
-
url: URL;
|
|
11043
|
-
} | {
|
|
11044
|
-
ok: false;
|
|
11045
|
-
failure: ToolFailure;
|
|
11046
|
-
}>;
|
|
11047
|
-
/** The checks a guarded request runs on its way, timed together: each hop's address, and its lookup. */
|
|
11048
|
-
export interface RequestChecks {
|
|
11049
|
-
/** Pass as \`fetchGuarded\`'s \`onCheck\`. */
|
|
11050
|
-
onCheck: (ms: number) => void;
|
|
11051
|
-
/** Records the checks once, when any ran, with the block they raised. */
|
|
11052
|
-
record: (blocked?: GuardrailEvent) => void;
|
|
11053
|
-
}
|
|
11054
|
-
export declare function requestChecks(span: SpanHandle | undefined): RequestChecks;
|
|
11055
|
-
export declare function toolNetworkPolicy(ctx: ToolContext): NetworkGuardrailSpec | undefined;
|
|
11056
11185
|
`,"file:///node_modules/@theoremjs/agents/src/kernel/tools/handler-events.d.ts":`import type { ToolBoundary } from '../../guardrails/boundaries.js';
|
|
11057
11186
|
import type { Provenance, ResolvedGuardrailPolicy } from '../../guardrails/types.js';
|
|
11058
11187
|
import type { TurnEvent } from '../types.js';
|
|
@@ -11139,6 +11268,7 @@ import { type ToolCallEnd } from '../engine/tool-trace.js';
|
|
|
11139
11268
|
import type { InjectUnit } from '../stages.js';
|
|
11140
11269
|
import type { InteractionPart, Profile, TurnEvent } from '../types.js';
|
|
11141
11270
|
import { type AgentCaller } from './agent.js';
|
|
11271
|
+
import { type ToolBackgroundSupport } from './background.js';
|
|
11142
11272
|
import { startToolExecution, type ToolCallBase } from './events.js';
|
|
11143
11273
|
import type { ToolExecutionCoordinator, ToolOperationClaim, ToolOperationOutcome } from './operation.js';
|
|
11144
11274
|
import type { ToolRegistry } from './registry.js';
|
|
@@ -11194,6 +11324,7 @@ export declare function authorizeToolReplay(args: {
|
|
|
11194
11324
|
}): void;
|
|
11195
11325
|
interface RegisteredToolCall {
|
|
11196
11326
|
execution?: ToolExecutionCoordinator;
|
|
11327
|
+
background?: ToolBackgroundSupport;
|
|
11197
11328
|
invocation?: unknown;
|
|
11198
11329
|
onDispatch?: () => void;
|
|
11199
11330
|
beginBody?: (preparedInput: unknown) => Promise<ToolOperationClaim | undefined>;
|
|
@@ -11798,12 +11929,14 @@ export { isModelProfile, pickModel, projectProfileInRegistry, projectProfileObje
|
|
|
11798
11929
|
`,"file:///node_modules/@theoremjs/agents/src/kernel/engine/session/mod.d.ts":`import type { TraceSink } from '../../../observability/trace-sink.js';
|
|
11799
11930
|
import type { ProviderHostOptions } from '../../protocols/runtime.js';
|
|
11800
11931
|
import type { KernelRegistry } from '../../registry/kernel-registry.js';
|
|
11932
|
+
import { type ToolBackgroundService } from '../../tools/background.js';
|
|
11801
11933
|
import { type PageToolExecution, type ToolExecutionCoordinator } from '../../tools/operation.js';
|
|
11802
11934
|
import type { KeyVault, LiveSession, SessionRequest } from '../../types.js';
|
|
11803
11935
|
export type { LiveSession, SessionRequest };
|
|
11804
11936
|
/** Options for opening a live session: the key vault, a provider's own settings, a WebSocket opener, how long a gated call waits for its decision, and the sign-in gate policy. */
|
|
11805
11937
|
export interface RunSessionOptions extends ProviderHostOptions {
|
|
11806
11938
|
execution?: ToolExecutionCoordinator;
|
|
11939
|
+
background?: ToolBackgroundService;
|
|
11807
11940
|
pageExecution?: PageToolExecution;
|
|
11808
11941
|
/** The host's keys by slot; the session uses the slots its profile names. */
|
|
11809
11942
|
vault?: KeyVault;
|
|
@@ -0,0 +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,H as te,Ht as ne,Qn as re,Sn as d,Un as ie,Vn as ae,_n as oe,bn as f,ln as se,on as ce,qt as le,sn as ue,vn as p,wt as de,yn as fe,zn as pe}from"./tool-schema-m1KPujBp.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 g,an as ye,er as be,fn as xe,jn as Se,lr as Ce,pn as _,tn as v,tr as we,vn as y,vr as Te,wr as Ee}from"./shaped-data-7q5Be8sp.js";import{a as De,n as Oe}from"./live-ingress-OuSlQ6q7.js";var ke=2,Ae=4,je=3,Me=/(^|,)(\s*)("?)(?:([=@])|([+-])(?![0-9."]))/gm,Ne=/^[A-Za-z0-9+/]*={0,2}$/,Pe=new Set([`text/csv`,`text/plain`,`text/markdown`]);function b(e){let{maxFiles:t,maxBytes:n,maxTurnBytes:r,limitsByMime:i}=e;if(t&&n&&r)return{maxFiles:t,maxBytes:n,maxTurnBytes:r,limitsByMime:i}}function Fe(e,t){if(t.limitsByMime){let n=d(e);if(t.limitsByMime[n])return t.limitsByMime[n];let[r]=n.split(`/`),i=`${r}/*`;if(t.limitsByMime[i])return t.limitsByMime[i]}return t.maxBytes}function x(e){return`uri`in e}function Ie(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=b(e.inputs??{});if(!t)throw new m(`config`,`Profile ${e.id} must set maxFiles, maxBytes, and maxTurnBytes`);return t}function Le(e){let t=0;return e.endsWith(`==`)?t=ke:e.endsWith(`=`)&&(t=1),Math.floor(e.length*je/Ae)-t}function Re(e){try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(e)}catch{return new TextDecoder(`latin1`).decode(e)}}function ze(e){return e.replace(Me,(e,...t)=>{let[n,r,i,a,o]=t;return`${n}${r}${i}'${a??``}${o??``}`})}function Be(e,t,n){let r=Re(t);return e===`text/csv`&&(r=ze(r)),new TextEncoder().encode(n.read(r))}function Ve(e,t){return t?{...e,fileName:t}:e}function He(e,t,n){return t.filter(t=>!p(e,t.mimeType)).map(e=>Ve({code:`mime_not_allowed`,params:{mimeType:e.mimeType,channel:n}},e.name))}function Ue(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=Fe(i.mimeType,t);i.sizeBytes>e&&n.push(Ve({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 We(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(...He(e.attachments,t,`attachment`)),e.voice&&r.push(...He(e.voice,n,`voice`)),e.limits?[...r,...Ue([...t,...n],e.limits)]:[...r,{code:`limits_unconfigured`}])}var Ge={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 S(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:Ge[e.code],params:t}}function Ke(e,t){let n=S(e);return h(n.key,n.params,t)}function C(e){return new m(`input`,`attachments refused: ${e.map(e=>e.code).join(`, `)}`,{copy:e.map(S)})}function w(e){if(!Ne.test(e))throw new m(`request`,`attachment data must be base64`);return Le(e)}function T(e){let t={mimeType:e.mimeType,name:e.name};return x(e)||(t.sizeBytes=w(e.data)),t}function qe(e,t,n){if(!Ye(t,n))return;let r=Ie(e),i=We({attachments:fe(e,`attachments`),voice:fe(e,`voice`),limits:r},(t??[]).map(T),(n??[]).map(T));if(i.length>0)throw C(i)}function Je(e,t){if(x(e))return e;let{mimeType:n,data:r}=e;if(!Pe.has(d(n)))return e;let i=Be(n,be(r),t);return{...e,data:we(i)}}function Ye(e,t){return(e?.length??0)>0||(t?.length??0)>0}function Xe(e,t,n,r){return qe(e,t,n),{attachments:t?.length?t.map(e=>Je(e,r.attachment)):t,voice:n?.length?n.map(e=>Je(e,r.voice)):n}}var Ze=`
|
|
2
|
+
|
|
3
|
+
`;function Qe(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 $e(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=Qe(r);if(e)return`${t}[${n}]${typeof r==`object`&&r&&`private`in r?`.private`:``} ${e}`}}}function et(e,t){let n=$e(e,t);if(n)throw new m(`config`,n)}function tt(e,t,n){return et(e,t),typeof e==`string`?n(e):e.map(e=>typeof e==`string`?n(e):{private:n(e.private)})}function nt(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 rt(e){let t=[];for(let n of e)n.some(e=>e.text)&&(t.length>0&&t.push({text:Ze,private:!0}),t.push(...n));return t}function it(e){return e.map(e=>e.text).join(``)}function at(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:it(e),private:t}}function ot(e,t){return at(rt([e,...t.map(e=>e?[{text:e,private:!0}]:[])]))}function E(e){let t=Object.keys(e);return t.length===1?t[0]:void 0}var st=/^[A-Za-z_][\w-]*$/,ct=/^\S+$/;function lt(e){return typeof e==`string`?[[e]]:e.map(e=>typeof e==`string`?[e]:e)}function ut(e){return typeof e==`string`?e:e.private}function D(e){return ee(e[0]===void 0?``:ut(e[0]))}function dt(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 ft(e,t){for(let[n,r]of Object.entries(e??{})){if(!st.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=>!ct.test(e)||e===`null`);if(e!==void 0)return`Condition "${n}" can't take the value "${e}".`}}function pt(e,t){if(e.length===0)return`It has no wording to send.`;let n=D(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 O(e,t,n){let r=ft(t,n);if(r)return r;let i=dt(t,n);for(let[t,n]of lt(e).entries()){let e=pt(n,i);if(e)return`Line ${t+1}: ${e}`}}function mt(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 ht(e,t){return e.when!==`unreadable`&&e.when.every(e=>u(e,t))}function gt(e,t,n){let r=lt(e),i=r.flat().some(e=>typeof e!=`string`),a=[];for(let[e,o]of r.entries()){let r=D(o);if(!ht(r,t))continue;let s=[];for(let[e,t]of o.entries()){let a=n(e===0?r.text:ut(t));a&&s.push({text:a,private:typeof t!=`string`||!i})}a.push({line:e+1,pieces:s})}return a}function _t(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`);et(r,`${t}[${n}]`)}}}function vt(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 k(e,t){let n=e.get(t);return n!==void 0&&n.type!==`builtin`}function A(e,t){return!e||e.includes(`*`)?!0:t?e.includes(t):!1}function yt(e,t){return t.filter(n=>{let r=e.get(n);return r?.type!==`builtin`||!(r.conflictsWith??[]).some(e=>t.includes(e))})}function j(e){return`tools`in e?e.tools.allow:[]}function M(e){return e.type===`text`||e.type===`image`?e.tools:void 0}function bt(e){return`tools`in e?e.tools.parallel:void 0}function xt(e,t,n){return j(t).filter(r=>{let i=e.get(r);return!i||i.type===`builtin`?!1:t.type===`host`||A(i.paths,n.path)})}function St(e,t,n,r){let i=t.models[r];return i?(i.builtInTools??[]).filter(t=>{let r=e.get(t);return r?.type===`builtin`&&A(r.paths,n.path)}):[]}function N(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 Ct(e,t,n){let r=[];for(let i of t){let t=N(e,i,n);t&&r.push(t)}return r}function P(e,t,n){if(t.visible.includes(n))return;t.visible.push(n);let r=N(e,n,t.modelBackground);r&&!t.wire.some(e=>e.name===n)&&t.wire.push(r)}function wt(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 Tt(e,t,n){return t.type===`live`||t.type===`host`?[...n]:n.filter(t=>e.get(t)?.loadTier===`T0`)}function Et(e,t,n){return yt(e,n.filter(n=>{let r=e.get(n);return r?.type===`builtin`&&(t.type===`live`||r.loadTier===`T0`)}))}function Dt(e,t){if(t.type!==`text`&&t.type!==`image`&&t.type!==`live`)return;let n=j(t).flatMap(t=>e.get(t)??[]),r=vt(t.identity.conditions,n);if(r)throw new m(`config`,`Profile ${t.id}: ${r}`)}function Ot(e,t){let n=M(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 F(e,t,n,r){Dt(e,t),Ot(e,t);let i=xt(e,t,n),a=t.type===`host`||t.type===`decision`||t.type===`embedding`||r===void 0?[]:St(e,t,n,r),o=[...i,...a],s=Et(e,t,o),c=Tt(e,t,o),l=c.filter(t=>k(e,t)),u=n.background!==void 0;return{builtins:s,gated:o,visible:c,executable:l,path:n.path,sessionPermissions:n.sessionPermissions,wire:Ct(e,c,u),...u?{modelBackground:u}:{}}}async function kt(e,t,n,r){let i=F(e,t,n,r);return await I(e,i,t,n),i}function At(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 I(e,t,n,r){let i=M(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[]`);L(e,t,a)}function L(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`?wt(e,t,r):P(e,t,r))}t.executable=t.visible.filter(t=>k(e,t))}var jt=new Set([`__proto__`,`constructor`,`prototype`]);function Mt(e){if(!me(e))return;let{loaded:t}=e;if(Array.isArray(t)&&t.every(e=>typeof e==`string`))return t}function Nt(e,t,n,r){if(r.type===`live`||r.type===`host`)return{promoted:[]};let i=[];for(let a of n){if(typeof a!=`string`||jt.has(a))return{promoted:[],failure:{code:`invalid_output`,kind:`bad_response`,message:`tools.t2Loader loaded ids must be plain strings`}};let n=Pt(e,a,r);if(`failure`in n)return{promoted:[],failure:n.failure};let{tool:o}=n;A(o.paths,t.path)&&t.gated.includes(a)&&i.push(a)}let a=[];for(let n of i)P(e,t,n),a.push(n);return t.executable=t.visible.filter(t=>k(e,t)),{promoted:a}}function R(e){return{failure:{code:`invalid_output`,kind:`bad_response`,message:e}}}function Pt(e,t,n){if(!j(n).includes(t))return R(`tools.t2Loader attempted to promote tool '${t}' outside profile allow`);let r=e.get(t);return r?r.type===`builtin`?R(`tools.t2Loader attempted to promote builtin '${t}' — only custom tools may be promoted`):r.loadTier===`T2`?{tool:r}:R(`tools.t2Loader attempted to promote tool '${t}' with loadTier '${r.loadTier}' — only T2 tools may be promoted`):R(`tools.t2Loader attempted to promote unknown tool '${t}'`)}function z(e){return Array.isArray(e)?[...e]:e.choices.map(e=>e.value)}function Ft(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 B(e){if(e)return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,Ft(t)]))}function V(e){return e?.slots?{...e,slots:B(e.slots)}:e}function H(e){return e==null}function U(e){return H(e)||typeof e!=`object`||Array.isArray(e)?null:e}function W(e){let t=U(e);return!t||t.type!==void 0&&t.type!==`object`?null:t}function G(e){let t=e.required;return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}function K(e){let t=e.properties;return U(t)??{}}function It(e,t){return e?`${e}.${t}`:t}function Lt(e,t){t.push({path:e,error:`required field '${e}' is missing`})}async function Rt(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 zt(e){let{path:t,propSchema:n,child:r,isRequired:i,fields:a,slots:o,failures:s}=e;if(H(r)){i&&Lt(t,s);return}await Rt(t,r,a?.[t],o,s);let c=W(n),l=c?U(r):null;c&&l&&await Bt(c,l,t,a,o,s)}async function Bt(e,t,n,r,i,a){let o=K(e),s=new Set(G(e)),c=new Set([...Object.keys(o),...s]),l=U(t);for(let e of c)await zt({path:It(n,e),propSchema:o[e],child:l?.[e],isRequired:s.has(e),fields:r,slots:i,failures:a})}async function Vt(e,t,n,r){let i=W(e);if(!i)throw new m(`config`,`structured validation requires a JSON Schema object root`);let a=[];if(!U(t)){for(let e of G(i))Lt(e,a);return a}return await Bt(i,t,``,n,r,a),a}function Ht(e,t){let n=e;for(let e of t.split(`.`)){let t=W(n);if(!t)return!1;let r=K(t);if(!Object.hasOwn(r,e)&&!G(t).includes(e))return!1;n=r[e]}return!0}function Ut(e){return e.map(e=>e.error).join(`; `)}function Wt(e,t){let n=e;for(let e of t.split(`.`))n=U(n)?.[e];return n}function Gt(e,t,n){let[r,...i]=t.split(`.`),a=U(e)??{};return r===void 0?e:{...a,[r]:i.length?Gt(a[r],i.join(`.`),n):n}}async function Kt(e,t,n){let r=[];for(let[i,a]of Object.entries(t??{})){let t=Wt(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 qt(e,t){let n=e;for(let e of t.split(`.`)){let t=W(n);if(!t)return;n=K(t)[e]}let r=U(n);if(r?.type===`array`)return U(r.items)??void 0}var Jt=class extends Error{failure;constructor(e){super(e.message),this.failure=e}},Yt=new Set([`text`,`image`,`speech`]),Xt=n().regex(/\S/),Zt=i({mimeType:n(),data:c(),name:n().optional()}),Qt=i({mimeType:n(),uri:n(),name:n().optional()}),$t=i({voice:n().optional(),style:n().optional(),speed:a().positive().optional()});function en(e){return i(Object.fromEntries(Object.entries(e).map(([e,t])=>{let n=z(t);return[e,o(n).optional()]})))}var tn=new Set([`text`,`attachments`,`voice`,`slots`,`speech`]);function nn(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 rn(e,n){let{inputs:r}=e,a={text:Xt};r?.attachments&&(a.attachments=s(t([Zt,Qt])).optional()),r?.voice&&(a.voice=s(Zt).optional()),r?.slots&&(a.slots=en(r.slots).optional()),e.type===`speech`&&(a.speech=$t.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(tn.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 an=l({text:n().optional(),structured:r().optional(),removed:s(l({path:n(),reason:n(),item:r()})).optional(),parts:s(pe).optional(),sources:s(ie).optional()});function on(e){return e.type===`speech`||(e.type===`text`||e.type===`image`)&&e.inputs.text!==!1}function sn(e){return e.type===`builtin`?!1:e.permission!==`auto`||`auth`in e&&e.auth!==void 0&&(e.auth.onUnauthenticated??`gate`)===`gate`}function cn(e,t){if(!Yt.has(e.type))return`it is a ${e.type} profile; an agent tool runs a text, image, or speech profile`;if(!on(e))return`it does not take text`;for(let n of j(e)){let e=t(n);if(!e)return`its tool '${n}' is not registered; register it first`;if(sn(e))return`its tool '${n}' can stop on a gate; give it permission 'auto' and no sign-in`}}function ln(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=cn(a,n);if(o)throw new m(`config`,`${r} can't run '${e.profile}': ${o}`);return a}function un(e){if(!e)return`delegated`;let t=`models`in e&&Object.values(e.models).some(e=>(e.builtInTools?.length??0)>0);return j(e).length===0&&!t?`local`:`delegated`}function dn(e){let t=ae(e),n=t.flatMap(e=>e.type===`text`?[e.text]:[]).join(``),r=ne(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 fn(e,t,n){return{...e,type:`agent`,input:t,output:an,sources:e=>e.sources??[],...n}}function pn(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 mn(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`&&q(i,`${n}.properties.${t}`,r)}function q(e,t,n){if(!pn(e,t,n))return;let r=e.properties;r&&typeof r==`object`&&!Array.isArray(r)&&mn(r,e.required,t,n),e.items&&typeof e.items==`object`&&!Array.isArray(e.items)&&q(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`&&q(e,`${t}.${r}[${i}]`,n)})}}function hn(e,t){let n=[];if(q(e,`$`,n),n.length>0)throw new m(`config`,`Invalid tool ${t} schema: ${n.join(`; `)}`)}function gn(t,n=`output`){let r=e(t,{target:`draft-7`,io:n});return delete r.$schema,r.type||=`object`,r}function J(e){if(typeof e!=`object`||!e)return e;if(Array.isArray(e))return e.map(J);let t={};for(let n of Object.keys(e))n!==`__proto__`&&n!==`constructor`&&n!==`prototype`&&(t[n]=J(e[n]));return t}function _n(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 vn(e,t,n,r){if(!n.provider?.trim()||!n.apiId?.trim())throw new m(`config`,h(`provider.binding_identity`))}function yn(e){Y(e.id,e.models),Q(e.id,e.observability),hr(e.id,e.inputs);for(let[t,n]of Object.entries(e.models))X(e.id,t,n);return{type:`embedding`,id:e.id,identity:{handle:e.identity.handle},models:e.models,defaultModel:kn(e.id,e),allowModelSelect:e.allowModelSelect,inputs:e.inputs,guardrails:e.guardrails,observability:e.observability,labels:e.labels}}function bn(e){Y(e.id,e.models),Un(e.id,e.guardrails),Q(e.id,e.observability);for(let[t,n]of Object.entries(e.models))X(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},...jn(e),providerContinuation:void 0,maxSteps:void 0,inputs:{...e.inputs,text:!1},guardrails:e.guardrails,observability:e.observability,labels:e.labels}}function xn(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 Sn(e,t,n){if(xn(e,t,n,ue),vn(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 Cn(e){let t=e.models?E(e.models):void 0;if(!t)throw new m(`config`,`Profile ${e.id}: type 'decision' must declare exactly one model`);Sn(e.id,t,e.models[t])}function wn(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 Tn(e){return Cn(e),wn(e),Q(e.id,e.observability),{...e,identity:{handle:e.identity.handle}}}function En(e){return e===void 0?{}:{parallel:e}}function Dn(e){return On(e.id,e.tools),Q(e.id,e.observability),{type:`host`,id:e.id,tools:{allow:e.tools.allow,...En(e.tools.parallel)},guardrails:e.guardrails,observability:e.observability,labels:e.labels}}function On(e,t){if(!Array.isArray(t.allow))throw new m(`config`,`Profile ${e}: type 'host' must set tools.allow`)}function Y(e,t){if(Object.keys(t).length===0)throw new m(`config`,`Profile ${e} must declare at least one model`)}function kn(e,t){let n=t.defaultModel??E(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 X(e,t,n){An(e,t,n),xn(e,t,n,se),An(e,t,n)}function An(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(!y.includes(i))throw new m(`config`,`Profile ${e} model '${t}' effort '${n}': '${i}' is not a thinking level (${y.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 jn(e){return{providerContinuation:e.providerContinuation?re.parse(e.providerContinuation):{},models:e.models,defaultModel:kn(e.id,e),allowModelSelect:e.allowModelSelect,maxSteps:e.maxSteps}}function Mn(e,t,n){if(n?.length){for(let r of n)if(!le(r))throw new m(`config`,`Profile ${e}: turnBehaviour.resumption.${t} may only include ContinueStopKind (length | stream_incomplete | provider_error); got '${r}'`)}}function Nn(e,t){t&&(Mn(e,`allowContinue`,t.allowContinue),Mn(e,`autoContinue`,t.autoContinue))}function Z(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Pn(e,t){let n=[e];for(let e of t)n=n.flatMap(t=>Z(t)?e===`*`?Object.values(t):[t[e]]:[]);return n}var Fn=Object.entries(xe).filter(([,e])=>e.required===!0).map(([e,t])=>[e,t.profileTypes]).sort(([e],[t])=>e.split(`.`).length-t.split(`.`).length);function In(e){if(!Z(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(!_.find(t=>t===e.type))throw new m(`config`,`Profile ${t}: type must be one of ${_.join(`, `)}`)}function Ln(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 Rn(e){let{id:t,type:n}=e,r=e;for(let[e,i]of Fn){if(i&&!i.includes(n))continue;let a=he(e),o=Pn(r,a.slice(0,-1)),s=a[a.length-1];if(o.some(e=>{if(!Z(e))return!1;let t=e[s];return t==null||t===``}))throw new m(`config`,`Profile ${t}: type '${n}' must set ${a.join(`.`)}`)}}function zn(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 Bn(e){let[t]=Se(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 Vn(e,t){let n=t.turnBehaviour;Nn(e,n?.resumption)}function Hn(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 Un(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&&!Ce.includes(r))throw t(`guardrails.blockedReply.onBlock must be one of ${Ce.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`?g(`guardrails.detect`,t,Te):g(`guardrails.detect`,t);if(n!==void 0)throw new m(`config`,`Profile ${e.id}: ${n}`)}function Q(e,t){try{let n=De(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(Ee(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(V(e.inputs)?.slots??{}))r[t]=z(n);let i=n??``;_t(i,`Profile ${e.id} identity.system`);let a=O(i,t,r);if(a)throw new m(`config`,`Profile ${e.id} identity.system: ${a}`)}function Yn(e){In(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}));Bn(e),zn(e),Rn(e),Ln(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 Dn(e);if(e.type===`decision`)return Tn(e);if(e.type===`embedding`)return yn(e);if(e.type===`transcription`)return bn(e);Y(e.id,e.models),Vn(e.id,e),Un(e.id,e.guardrails),e.type===`text`&&Hn(e.id,e.outputs?.validation),Q(e.id,e.observability);for(let[t,n]of Object.entries(e.models))X(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=jn(e),o;switch(e.type){case`text`:o={type:`text`,id:e.id,identity:t,...a,tools:e.tools,inputs:V(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:V(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?V(e.inputs):e.inputs,tools:{allow:e.tools.allow,...En(e.tools.parallel)},turnBehaviour:e.turnBehaviour,guardrails:n,observability:r,labels:i},Oe(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=f(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=z(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(oe(t.mimeType)!==`image`)throw new m(`config`,`${r} must be an image, not '${t.mimeType}'`);if(!(x(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=>!p(ye,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 j(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=M(t)?.t2Loader;if(n){if(!j(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=>qt(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=>Ht(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=f(e)?.context;if(!t)return;let n=v;if(t.from.length===0||t.from.some(e=>!n.includes(e)))throw new m(`config`,`Profile ${e.id}: inputs.context.from must list ${v.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,ce(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,f(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(te);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{b as $,At as A,gt as B,Vt as C,Gt as D,Wt as E,bt as F,rt as G,mt as H,M as I,Ke as J,tt as K,Nt as L,Mt as M,kt as N,B as O,j as P,x as Q,L as R,Kt as S,qt as T,E as U,O as V,ot as W,C as X,We as Y,w as Z,an as _,Pr as a,fn as b,Yn as c,J as d,Xe as et,hn as f,un as g,rn as h,vr as i,I as j,z as k,_n as l,cn as m,br as n,Fr as o,Jt as p,nt as q,Ar as r,gr as s,_r as t,gn as u,dn as v,Ut as w,nn as x,ln as y,F as z};
|