@theoremjs/studio 0.3.4-next.482.g7e608f2 → 0.3.4-next.484.g20d8b9d
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/package.json +4 -4
- package/page/assets/{Banner-CrUhb26_.js → Banner-G4u0gVOw.js} +2 -2
- package/page/assets/{ConsoleFrame-6cEEvO4i.js → ConsoleFrame-BZqxUndX.js} +1 -1
- package/page/assets/{ContextMenu-WnsgC14_.js → ContextMenu-DEnGmVYR.js} +2 -2
- package/page/assets/{ToolResultCharts-BEhuo0Z4.js → ToolResultCharts-BWBYDar4.js} +1 -1
- package/page/assets/{TraceInspector-k1w1q0XO.js → TraceInspector-B0cUdNg5.js} +1 -1
- package/page/assets/{TraceOverview-Crxd-sTS.js → TraceOverview-Bjqg7laD.js} +1 -1
- package/page/assets/{_virtual_studio-type-sources-DAabvYbE.js → _virtual_studio-type-sources-DBS0HldZ.js} +10 -4
- package/page/assets/{browser-engine-C78edv3x.js → browser-engine-CaPsakbj.js} +1 -1
- package/page/assets/{browser-transport-mGxdvtBL.js → browser-transport-BEha0XY8.js} +3 -3
- package/page/assets/{export-agent-BedkRp13.js → export-agent-Cxamh6fg.js} +1 -1
- package/page/assets/{guardrail-tester-XwnZWNsg.js → guardrail-tester-Lubrp5dY.js} +1 -1
- package/page/assets/{index-BVHT-9mR.js → index-C3n9ogf7.js} +6 -6
- package/page/assets/{live-messages-B65rUlNM.js → live-messages-BwMauTVi.js} +1 -1
- package/page/assets/{reader-XebgyCzF.js → reader-oVJF5Iqk.js} +1 -1
- package/page/assets/{stub-DG5wxM-A.js → stub-_DAX3TnJ.js} +1 -1
- package/page/assets/{studio-code-pane-p4fjtQhL.js → studio-code-pane-BqHsqd7P.js} +3 -3
- package/page/assets/{studio-console-BtZY4aUM.js → studio-console-C-rWlbSY.js} +1 -1
- package/page/assets/{studio-decision-BovTBIwV.js → studio-decision-CCpYdeOV.js} +1 -1
- package/page/assets/{studio-embedding-BY6UQk0k.js → studio-embedding-BM1yTK8B.js} +1 -1
- package/page/assets/{studio-host-console-D9NFWXxV.js → studio-host-console-D8_OCbZG.js} +2 -2
- package/page/assets/{studio-labels-C3yQoEd0.js → studio-labels-CBBymwHa.js} +1 -1
- package/page/assets/{studio-live-B_cVDiqs.js → studio-live-CgYci_ts.js} +1 -1
- package/page/assets/{studio-map-iN6-MOzK.js → studio-map-QDBMJ6x3.js} +1 -1
- package/page/assets/{studio-trace-replay-B3k21TSg.js → studio-trace-replay-BIRuiVjZ.js} +1 -1
- package/page/assets/{studio-type-checker-Bljo3amv.js → studio-type-checker-B4qvn-WC.js} +1 -1
- package/page/assets/{tool-schema-BmScISma.js → tool-schema-CvHbJyis.js} +4 -4
- package/page/assets/{tree-BiZScKs7.js → tree-DtF83caH.js} +1 -1
- package/page/assets/{turn-client-CBWNoFgo.js → turn-client-D_bUUpER.js} +1 -1
- package/page/assets/types-Bc3MMW0P.js +1 -0
- package/page/assets/{use-one-call-rh-5EjBB.js → use-one-call-DWpPEFdQ.js} +1 -1
- package/page/assets/{workspace-kAEf4Zn4.js → workspace-ILHOuESH.js} +1 -1
- package/page/index.html +12 -12
- package/page/assets/types-zRlFhC9U.js +0 -1
|
@@ -2,17 +2,17 @@ import{n as e}from"./rolldown-runtime-hePW80VL.js";import{$ as t,A as n,B as r,C
|
|
|
2
2
|
`)}function Bt(e,t){return Rt(F(e),e instanceof T?e.copy:void 0,t)}function Vt(e){return typeof e==`string`?e:e instanceof Error&&e.message?e.message:String(e)}function I(e){return{type:`error`,errorKind:F(e),...e instanceof T&&e.copy?{errorCopy:e.copy}:{},errorInternal:Vt(e)}}function Ht(e,t){if(e.type===`error`&&e.error===void 0)return{...e,error:Rt(e.errorKind,e.errorCopy,t)};if(e.type===`tool`&&e.tool.phase===`error`&&e.tool.failure.error===void 0){let{tool:n}=e,r=Lt(n.failure.kind,t,{tool:n.name});return{...e,tool:{...n,failure:{...n.failure,error:r}}}}return e}var Ut=[`trusted`,`assembled`,`untrusted`],Wt=[`input`,`history`,`system`,`attachment`,`tool_call`,`tool_result`,`output_delta`,`output_final`,`thought`,`network`,`live_inbound`,`live_outbound`,`trace`],Gt=[`info`,`low`,`medium`,`high`],Kt=[`retry`,`refuse`],qt=[`allow`,`redact`,`flag`,`block`],Jt=[`local`,`builtin`,`http`,`mcp`,`delegated`],Yt=[`off`,`destructive`,`write`],Xt=[`off`,`confirm`,`block`],Zt=[`detect`,`network`],Qt=b(Le),$t=w({key:b(Ge),params:C(S(),g([S(),x()])).optional()}),en=g([$t,y($t).readonly()]),tn=w({origin:b(Jt),tool:S(),depth:x()}),nn=w({rule:S(),severity:b(Gt),span:w({start:x(),end:x()}).optional(),match:S().optional(),label:S().optional(),doc:S().optional(),pattern:S().optional(),signal:S().optional()}),rn=w({stage:b(Wt),boundary:b(Je).optional(),trust:b(Ut),action:b(qt),hits:y(nn),provenance:tn.optional(),errorInternal:S().optional()}),an=Ce(),L=C(S(),an),on=i({protocol:S().min(1),provider:S().min(1),version:x().int().positive(),apiId:S().min(1),keySlot:S().min(1).optional(),compatibilityKey:S(),coveredHistoryLength:x().int().nonnegative(),coveredHistoryHash:S(),data:an,wireCallIds:C(S().min(1),S().min(1)).optional()}),sn=i({code:v(`provider_state_rebuilt`),reason:b([`provider_changed`,`model_changed`,`connection_changed`,`key_changed`,`history_changed`,`version_changed`])}),cn=i({history:b([`host`,`stateless`,`provider`]).optional()});async function ln(e){let t=e=>{if(Array.isArray(e))return e.map(t);if(e&&typeof e==`object`){let n={};for(let r of Object.keys(e).sort())n[r]=t(e[r]);return n}return e},n=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(JSON.stringify(t(e.map(e=>{let t=t=>e.role===`user`?t.match(/^<user_data>\n([\s\S]*)\n<\/user_data>$/)?.[1]??t:t,n=[...e.content===void 0?[]:[{type:`text`,text:t(e.content)}],...(e.parts??[]).map(e=>e.type===`text`?{...e,text:t(e.text)}:e)],{content:r,parts:i,...a}=e;return{...a,...n.length?{parts:n}:{}}}))))),r=``;for(let e of new Uint8Array(n))r+=e.toString(16).padStart(2,`0`);return r}var un=`Zephyr.Puck.Charon.Kore.Fenrir.Leda.Orus.Aoede.Callirrhoe.Autonoe.Enceladus.Iapetus.Umbriel.Algieba.Despina.Erinome.Algenib.Rasalgethi.Laomedeia.Achernar.Alnilam.Schedar.Gacrux.Pulcherrima.Achird.Zubenelgenubi.Vindemiatrix.Sadachbia.Sadaltager.Sulafat`.split(`.`),dn={"profile.id":{required:!0},"profile.type":{required:!0},identity:{required:!0},"identity.handle":{required:!0},"identity.system":{unset:`Only the kernel's notes`},tools:{required:!0},"tools.allow":{required:!0},image:{required:!0},speech:{required:!0},live:{required:!0},decision:{required:!0},"decision.contract":{required:!0},models:{required:!0},"profile.defaultModel":{required:`when more than one model is declared`,unset:`The only model`},"profile.allowModelSelect":{unset:`Off`,value:!1},"profile.maxSteps":{unset:`20 model calls`,value:20},"models.*.protocol":{required:!0},"models.*.provider":{required:!0},"models.*.options":{unset:`The protocol's defaults`},"models.*.keySlot":{unset:`Provider primary slot`},"models.*.fallbackKeySlot":{unset:`Provider fallback slot, when configured`},providerContinuation:{unset:`The host keeps the history`},"providerContinuation.history":{unset:`host`,value:`host`},"models.*.apiId":{required:!0},"models.*.builtInTools":{unset:`None`,value:[]},"models.*.maxOutputTokens":{unset:`Provider default`},"models.*.temperature":{unset:`Provider default`},"models.*.summaries":{unset:`Provider default`},"models.*.efforts":{unset:`Provider default`},"models.*.defaultEffort":{required:`when more than one effort is declared`,unset:`The only effort`},"models.*.allowEffortSelect":{unset:`Off`,value:!1},"models.*.timeoutMs":{unset:`No timeout`},"models.*.compaction":{unset:`Off`},"models.*.compaction.maxTokens":{required:!0},"models.*.compaction.compactAt":{required:!0},"models.*.compaction.previousExchanges":{required:!0},"models.*.compaction.profile":{unset:`The agent itself, on a text profile`},"models.*.compaction.trigger":{unset:`compactAt of maxTokens`},"models.*.compaction.timing":{required:!0},"models.*.compaction.meter":{unset:`history`,value:`history`},inputs:{required:`on every type that takes it but live`,unset:`No slots or context`},"inputs.text":{unset:`Accepted`,value:!0},"inputs.attachments.accept":{unset:`No attachments`},"inputs.voice.accept":{unset:`No voice`},"inputs.maxFiles":{required:`when attachments or voice is set`},"inputs.maxBytes":{required:`when attachments or voice is set`},"inputs.maxTurnBytes":{required:`when attachments or voice is set`},"inputs.state":{required:!0},"inputs.maxStateBytes":{unset:`No cap`},"inputs.limitsByMime":{unset:`maxBytes for every type`},"inputs.slots":{unset:`No slots`},"inputs.context":{unset:`No context`},"inputs.context.from":{required:!0},"inputs.context.maxChars":{required:!0},"outputs.structured":{unset:`Free text`,value:null},"outputs.validation.maxRetries":{unset:`0`,value:0},"outputs.streaming.mode":{unset:`sse`,value:`sse`},"outputs.streaming.streamThoughts":{unset:`On`,value:!0},"turnBehaviour.resumption.allowContinue":{unset:`All three`,value:[`length`,`stream_incomplete`,`provider_error`]},"turnBehaviour.resumption.autoContinue":{unset:`length and stream_incomplete`,value:[`length`,`stream_incomplete`]},"turnBehaviour.resumption.maxContinues":{unset:`No cap`},"turnBehaviour.allowSteering":{unset:`On`,value:!0},"turnBehaviour.atStepLimit":{unset:`stop`,value:`stop`},"guardrails.quota":{unset:`No limit`},"guardrails.detect":{unset:`Redacts what goes to the model`},"guardrails.detect.ungiven_images.allow.fromTools":{unset:`On`,value:!0},"guardrails.detect.ungiven_links.allow.fromTools":{unset:`On`,value:!0},"guardrails.blockedReply":{unset:`One rewrite`},"guardrails.blockedReply.onBlock":{unset:`retry`,value:`retry`},"guardrails.blockedReply.maxRetries":{unset:`1`,value:1},"guardrails.network.allowPrivateNetworks":{unset:`Off`,value:!1},"guardrails.network.allowedHosts":{unset:`None`,value:[]},"guardrails.network.allowedSchemes":{unset:`https, plus http when allowPrivateNetworks is on`},"guardrails.taint.afterRemoteRead":{unset:`off`,value:`off`},"guardrails.taint.remoteDestination":{unset:`off`,value:`off`},"guardrails.disclosure":{unset:`No check`},"observability.writeTo":{unset:`No traces, unless runTurn is given a sink`},"observability.sampleRate":{unset:`1`,value:1},"observability.include.upstreamLog":{unset:`On`,value:!0},"observability.include.outboundWire":{unset:`Off; on when the profile has no observability block`},"observability.include.evidenceRaw":{unset:`Off; on when the profile has no observability block`},"observability.include.usage":{unset:`On`,value:!0},"observability.include.guardrailDecisions":{unset:`On`,value:!0},"observability.include.guardrailMatchPreview":{unset:`Off`,value:!1},"observability.resource":{unset:`None`},"observability.scrub.sensitive":{unset:`On`,value:!0},"observability.scrub.injection":{unset:`On`,value:!0},"observability.scrub.canary":{unset:`On`,value:!0},"observability.retainForDays":{unset:`14`,value:14},"observability.rotateAfterMiB":{unset:`32`,value:32},"observability.onWriteError":{unset:`Errors are dropped`},"image.aspectRatio":{unset:`Provider default`},"image.resolution":{unset:`Provider default`},"image.mimeType":{unset:`Provider default`},"image.quality":{unset:`Provider default`},"image.background":{unset:`Provider default`},"image.n":{unset:`Provider default`},"image.seed":{unset:`Provider default`},"image.outputCompression":{unset:`Provider default`},"image.references":{unset:`None`},"image.includeText":{unset:`Off`,value:!1},"speech.voice":{unset:`The turn's speech.voice; Gemini refuses speech without one`},"speech.style":{unset:`The turn's speech.style, else no direction`},"speech.speed":{unset:`The turn's speech.speed, else the voice's own pace`},"speech.format":{unset:`Provider default`},"live.ingress.audio":{unset:`On`,value:!0},"live.ingress.video":{unset:`On`,value:!0},"live.ingress.text":{unset:`Off`,value:!1},"live.voice":{unset:`Provider default`},"live.vad.activityHandling":{unset:`Provider default`},"live.vad.startSensitivity":{unset:`Provider default`},"live.vad.endSensitivity":{unset:`Provider default`},"live.vad.prefixPaddingMs":{unset:`Provider default`},"live.vad.silenceDurationMs":{unset:`Provider default`},"live.sessionResumption":{unset:`Off`,value:!1},"live.greeting":{unset:`The agent waits for the visitor`},"live.resumed":{unset:`A resumed call is silent`},"live.resumed.prompt":{required:!0},"live.resumed.afterMs":{unset:`3000`},"live.contextCompression":{unset:`Off`},"live.contextCompression.triggerTokens":{unset:`Provider default`},"live.contextCompression.slidingWindow":{required:!0},"live.contextCompression.slidingWindow.targetTokens":{unset:`Provider default`},"live.transcription.input":{unset:`Off`},"live.transcription.output":{unset:`Off; on with a detector at live_reply`}},fn=[`text`,`image`,`speech`,`live`,`decision`,`embedding`,`host`],pn=[`text`,`image`,`speech`,`live`,`decision`,`embedding`],R=[`text`,`image`,`speech`,`live`],mn=[`text`,`image`],hn=`a decision takes JSON state, not turn text, files, or slots`,gn=[`text`,`image`,`live`],_n=`a decision takes JSON state, and speech reads its transcript only`;function vn(e){return Zt.includes(e)?[...R,`host`]:R}function yn(e){return e.replace(/^profile\./,``).split(`.`)}var bn={providerContinuation:{profileTypes:R,reason:`only model turns and live sessions use provider continuation`},...Object.fromEntries([`efforts`,`defaultEffort`,`allowEffortSelect`,`summaries`,`maxOutputTokens`,`temperature`,`builtInTools`].map(e=>[`models.*.${e}`,{profileTypes:R,reason:`only model turns use this setting; decisions send state and questions`}])),"models.*.timeoutMs":{profileTypes:[`decision`],reason:`only decision bindings configure a request timeout here`},identity:{profileTypes:pn,reason:`a host profile has no agent identity — it runs no model`},"identity.system":{profileTypes:[`text`,`image`,`live`],reason:`speech has no system channel (the input text is the transcript) and a decision is asked only through its questions`},"identity.systemByRole":{profileTypes:[`text`,`image`,`live`],reason:`speech has no system channel (the input text is the transcript) and a decision is asked only through its questions`},models:{profileTypes:pn,reason:`a host profile runs no model`},"models.*.protocol":{profileTypes:pn,reason:`a host profile runs no model`},"models.*.provider":{profileTypes:pn,reason:`a host profile runs no model`},"models.*.compaction":{profileTypes:[`text`,`image`,`speech`],reason:`live compacts with live.contextCompression`},"profile.defaultModel":{profileTypes:[...R,`embedding`],reason:`a host profile runs no model and a decision declares exactly one`},"profile.allowModelSelect":{profileTypes:[...R,`embedding`],reason:`a host profile runs no model and a decision declares exactly one`},"profile.maxSteps":{profileTypes:R,reason:`only model turns take tool-loop steps`},decision:{profileTypes:[`decision`],reason:`only decision profiles carry a contract`},image:{profileTypes:[`image`],reason:`only image profiles generate images`},speech:{profileTypes:[`speech`],reason:`only speech profiles synthesize audio`},live:{profileTypes:[`live`],reason:`only live profiles open a realtime session`},tools:{profileTypes:[`text`,`image`,`live`,`host`],reason:`speech and decision profiles call no tools`},"tools.t1Policy":{profileTypes:[`text`,`image`],reason:`live wires every allowed tool once at session setup, and a host profile can execute every allowed tool`},"tools.t2Loader":{profileTypes:[`text`,`image`],reason:`live function declarations are fixed at session setup, and a host profile can execute every allowed tool`},inputs:{profileTypes:[`text`,`image`,`live`,`decision`,`embedding`],reason:`speech input is the transcript, and a host profile takes no turns`},"inputs.voice":{profileTypes:[`text`],reason:`no image model reads audio, and a decision takes JSON state`},"inputs.text":{profileTypes:[...mn,`embedding`],reason:hn},"inputs.attachments":{profileTypes:[...mn,`embedding`],reason:hn},"inputs.maxFiles":{profileTypes:[...mn,`embedding`],reason:hn},"inputs.maxBytes":{profileTypes:[...mn,`embedding`],reason:hn},"inputs.maxTurnBytes":{profileTypes:[...mn,`embedding`],reason:hn},"inputs.limitsByMime":{profileTypes:[...mn,`embedding`],reason:hn},"inputs.slots":{profileTypes:gn,reason:_n},"inputs.context":{profileTypes:gn,reason:_n},"inputs.state":{profileTypes:[`decision`],reason:`only a decision reads JSON state; a turn takes text, files, and slots`},"inputs.maxStateBytes":{profileTypes:[`decision`],reason:`only a decision reads JSON state; a turn takes text, files, and slots`},outputs:{profileTypes:[`text`,`image`,`speech`],reason:`live output is the realtime session, and decision and host profiles produce no turn output`},"outputs.structured":{profileTypes:[`text`],reason:`only a text reply has a JSON shape; image and speech turns return media`,offValue:null},"outputs.validation":{profileTypes:[`text`],reason:`validation checks a structured reply, which only text profiles make`},turnBehaviour:{profileTypes:R,reason:`only model turns can be continued or steered`},"turnBehaviour.resumption":{profileTypes:[`text`,`image`,`speech`],reason:`live resumes through live.sessionResumption`},"turnBehaviour.allowSteering":{profileTypes:[`text`,`live`],reason:`image and speech turns take no mid-turn input`},"turnBehaviour.atStepLimit":{profileTypes:[`text`],reason:`only a text turn writes an answer after its tools`},"guardrails.quota":{profileTypes:vn(`quota`),reason:`quota counts model turns`},"guardrails.detect":{profileTypes:vn(`detect`),reason:`the decision path runs none of the turn guardrails`},"guardrails.blockedReply":{profileTypes:[`text`,`image`,`live`],reason:`only a reply can be blocked, and speech, decision, and host profiles write none`},"guardrails.network":{profileTypes:[`text`,`image`,`live`,`host`],reason:`speech and decision profiles call no tools`},"guardrails.taint":{profileTypes:[`text`,`image`,`live`],reason:`speech and decision profiles call no tools, and a host profile runs no turn to taint`},"guardrails.disclosure":{profileTypes:[`decision`],reason:`disclosure gates state leaving a decision profile for its model`}};function xn(e){let t=e.split(`.`);for(let e=t.length;e>0;e--){let n=bn[t.slice(0,e).join(`.`)];if(n)return n}}function Sn(e){return xn(e)?.profileTypes??fn}function Cn(e,t,n=``){if(!t.length)return e===void 0?[]:[[n,e]];if(typeof e!=`object`||!e)return[];let[r,...i]=t,a=e;return(r===`*`?Object.keys(a):[r]).flatMap(e=>Cn(a[e],i,n?`${n}.${e}`:e))}function wn(e){let t=[];for(let[n,r]of Object.entries(bn))if(!r.profileTypes.includes(e.type))for(let[i,a]of Cn(e,yn(n)))(r.offValue===void 0||a!==r.offValue)&&t.push({path:i,scope:r});return t}var Tn=[`text`,`image`,`speech`,`live`,`decision`,`embedding`,`host`],En=[`none`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`],Dn=/^[A-Za-z0-9][A-Za-z0-9_-]{0,31}$/;function On(e){return typeof e==`string`&&Dn.test(e)}var kn=[`image`,`audio`,`video`,`document`],An=[`sse`,`buffered`],jn=[`pcm`,`mp3`],Mn=3e3,Nn=[`client`,`server`],Pn=[`START_OF_ACTIVITY_INTERRUPTS`,`NO_INTERRUPTION`],Fn=[`START_SENSITIVITY_LOW`,`START_SENSITIVITY_HIGH`],In=[`END_SENSITIVITY_LOW`,`END_SENSITIVITY_HIGH`],Ln=[`history`,`input`],Rn=[`before`,`after`],zn=[`compacted`,`deferred`,`dropped`],Bn=[`automatic`,`system`],Vn=[`5m`,`1h`],Hn=[`completed`,`length`,`tool`,`gate`,`filtered`,`provider_error`,`cancelled`,`stream_incomplete`,`step_limit`,`interrupted`,`generation_complete`],Un=[`stop`,`answer`],Wn=[`drop`,`fix`],Gn=[`length`,`stream_incomplete`,`provider_error`],Kn=[`pre_turn`,`pre_tool`,`post_tool`,`before_end`,`post_turn`];new Set(Kn);var qn=[`confirmation`,`permission`,`auth`,`page`];new Set(qn);var Jn=[`affordance_not_allowed`,`inject_not_allowed`,`inject_rejected_max_steps`,`inject_invalid_messages`,`inject_id_invalid`,`inject_released_invalid`,`deny_invalid`,`confirm_invalid`,`mutate_invalid`,`label_failed_invalid`,`abort_invalid`,`wait_for_invalid`,`unknown_field`,`result_invalid`],Yn=`awaiting_user_input`,Xn=[`T0`,`T2`],Zn=[`GET`,`POST`,`PUT`,`PATCH`,`DELETE`],Qn=[`gate`,`report_to_model`,`fail`],$n=[`builtin`,`function`,`http`,`mcp`,`agent`],er=[`read-only`,`read-write`,`destructive`],tr=[`auto`,`session_consent`,`always_confirm`],nr=[`bearer`,`api_key`,`oauth2`],rr=[`none`,...nr],ir={"image/png":`image`,"image/jpeg":`image`,"image/jpg":`image`,"image/webp":`image`,"image/heic":`image`,"image/heif":`image`,"audio/wav":`audio`,"audio/x-wav":`audio`,"audio/mpeg":`audio`,"audio/mp3":`audio`,"audio/aiff":`audio`,"audio/aac":`audio`,"audio/ogg":`audio`,"audio/flac":`audio`,"audio/webm":`audio`,"audio/mp4":`audio`,"audio/pcm":`audio`,"audio/m4a":`audio`,"audio/opus":`audio`,"audio/l16":`audio`,"audio/alaw":`audio`,"audio/mulaw":`audio`,"video/mp4":`video`,"video/mpeg":`video`,"video/quicktime":`video`,"video/mov":`video`,"video/x-msvideo":`video`,"video/avi":`video`,"video/x-flv":`video`,"video/mpg":`video`,"video/webm":`video`,"video/wmv":`video`,"video/x-ms-wmv":`video`,"video/3gpp":`video`,"application/pdf":`document`,"text/plain":`document`,"text/csv":`document`,"text/markdown":`document`,"text/md":`document`,"text/html":`document`,"text/css":`document`,"text/xml":`document`,"text/rtf":`document`,"text/javascript":`document`,"application/x-javascript":`document`,"text/x-python":`document`,"application/x-python":`document`,"application/json":`document`};function ar(e){return Object.keys(ir).filter(t=>ir[t]===e)}var or=[`image/*`,`video/*`,...ar(`image`),...ar(`video`),...ar(`document`)],sr=[`image/*`,`video/*`,...ar(`image`),...ar(`video`),`application/pdf`],cr=[`audio/*`,...ar(`audio`)];function z(e){return e.map(e=>`'${e}'`).join(` | `)}function B(e,t,n,r,i){return n?typeof r==`object`?i?{type:e,doc:t,options:n,optionDescriptions:r,optionNote:i}:{type:e,doc:t,options:n,optionDescriptions:r}:typeof r==`string`?{type:e,doc:t,options:n,optionNote:r}:{type:e,doc:t,options:n}:{type:e,doc:t}}var lr=Ve(Re,e=>et[e].doc);function ur(e,t){if(qe[t].allow===`names`)return[[`${e}.allow`,B(`NameAllow`,`The names that are innocent in a reply.`)],[`${e}.allow.names`,{...B(`string[]`,`Names of tools or parameters that are not read for, such as a tool called search.`),unset:`None`}]];let n=t===`ungiven_links`?`Hostnames whose links pass whatever their URL; the hosts ungiven_images allows pass too.`:`Hostnames whose images load whatever their URL, such as your own CDN.`;return[[`${e}.allow`,B(`UrlAllow`,`What passes besides the URLs the model was given this turn.`)],[`${e}.allow.hosts`,{...B(`string[]`,n),unset:`None`}],[`${e}.allow.fromTools`,{...B(`boolean`,`Whether a URL a tool returned counts as given. Off keeps only what the system prompt, the user, and history gave.`),unset:`On`}]]}var dr="The table your patterns compile to, from compileDetect or `agents detect-compile`. Needed whenever patterns is set.";function fr(e){let t=`${e}.patterns.*`;return[[`${t}.name`,B(`string`,`What a match is called in the trace.`)],[`${t}.pattern`,B(`string`,`The source of a regular expression. A pattern takes this or words.`)],[`${t}.flags`,{...B(`string`,`Regular-expression flags, each a letter: i ignores case, m matches ^ and $ at each line, s lets . match a line break, u reads Unicode. Not g or y: every match is always found.`),unset:`None`}],[`${t}.words`,B(`string[]`,`Words to match whole, whatever their case. A space in one matches any run of whitespace.`)]]}function pr(e){let t=e=>B(`DetectAction`,e,Re,lr);return[[e,B(`HostDetectorConfig`,`Your own detector, keyed with a dot: acme.codenames. No default action.`)],[`${e}.label`,B(`string`,`What an editor and the trace call it.`)],[`${e}.action`,{...t(`What a match does, at every boundary.`),unset:`Only the boundaries at names are read`}],[`${e}.at`,B(`{ [boundary]: DetectAction }`,`An action per boundary, over action.`)],...Je.map(n=>[`${e}.at.${n}`,{...t(ze[n].doc),unset:et.ignore.label}]),[`${e}.patterns`,{...B(`HostPattern[]`,`Its patterns, each a name and a regular expression or a list of words, read on the text as written.`),unset:`None`}],...fr(e),[`${e}.compiled`,B(`CompiledPatterns`,dr)],[`${e}.hint`,{...B(`string`,`One line telling the model what to leave out, sent when this detector blocks a reply that is then retried.`),unset:`The labels’s detect.hint.own, which names the label`}],[`${e}.find`,B(`HostFind`,`Its own reading, for what patterns cannot say: a function that returns where the matches start and end. It runs on every text crossing a boundary the detector reads, so it returns at once.`)]]}function mr(e){return[[`${e}.theorem`,{...B(`boolean`,`Whether Theorem’s own patterns run. Off with no patterns of your own turns the detector off.`),unset:`On`}],[`${e}.patterns`,{...B(`HostPattern[]`,`Your own patterns, each a name and a regular expression or a list of words. A match takes this detector’s action.`),unset:`None`}],...fr(e),[`${e}.compiled`,B(`CompiledPatterns`,dr)],[`${e}.hint`,{...B(`string`,`One line telling the model what to leave out, sent when this detector blocks a reply that is then retried. Set it beside patterns of your own.`),unset:`The labels’s detect.hint line for this detector`}]]}function hr(e){let{allow:t,patterns:n}=qe[e];return t&&n?`action, at, allow, theorem, patterns, and hint`:t?`action, at, and allow`:n?`action, at, theorem, patterns, and hint`:`action and at`}function gr(){let e=(e,t)=>B(e,t,Re,lr),t=[[`guardrails.detect`,e(`DetectAction | { [detector]: DetectorRule }`,`What a guardrail does when a detector matches. One action covers every detector; an object sets each detector (or one of your own) apart. Absent: each detector keeps its default action.`)]];for(let n of He){let r=`guardrails.detect.${n}`;t.push([r,e(`DetectAction | DetectorConfig`,`${qe[n].doc} Set one action, or ${hr(n)}.`)]),qe[n].allow&&t.push(...ur(r,n)),qe[n].patterns&&t.push(...mr(r)),t.push([`${r}.action`,{...e(`DetectAction`,"What a match of this detector does at every boundary it reads, unless `at` names that boundary."),unset:`Each boundary keeps its default`}]),t.push([`${r}.at`,B(`{ [boundary]: DetectAction }`,`An action per boundary, over action or the default.`)]);for(let i of Ye[n]){let a=et[at[n][i]].label,o=e(`DetectAction`,ze[i].doc);t.push([`${r}.at.${i}`,{...o,unset:a}])}}return t.push(...pr(`guardrails.detect.*`)),Object.fromEntries(t)}function _r(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>{let n=xn(e);return[e,{...t,...n?{profileTypes:n.profileTypes,profileTypesReason:n.reason}:{},...dn[e]}]}))}var vr=_r({"profile.id":B(`string`,`The name this profile is registered and looked up by, at most 64 characters; registering the same id again replaces it.`),"profile.type":B(`'text' | 'image' | 'speech' | 'live' | 'decision' | 'embedding' | 'host'`,`What kind of agent this is, and so what each call gives back: text, image, speech, live, decision, embedding, or host.`,Tn,{text:`A chat or task agent. Each turn the model answers in text, or in JSON when outputs ask for a structured reply, and can call tools on the way.`,image:`Makes pictures from a prompt, in the shape, size, and format the image block sets.`,speech:`Gives your app a voice. Each turn reads text aloud in the voice the speech block names.`,live:`For talking in real time. One continuous voice and video session, rather than separate turns.`,decision:`For when your app needs a judgement, not a reply. It answers questions about a JSON state, each with a choice, a score, or a number.`,embedding:`For when your app needs vectors from text or provider-supported media.`,host:`A governed passthrough to your tool registry, with no model. It calls MCP, HTTP, and in-app function tools under the same permissions and traces as any agent, guarded by detect and network.`}),identity:B(`{ handle, system?, systemByRole? }`,`The agent's display name and the system instruction it is given.`),"identity.handle":B(`string`,`The name hosts and users see for this agent, at most 32 characters; the model never sees it. It is also the role a turn gets when it names none, so identity.systemByRole may hold an entry under it.`),"identity.system":B(`string | Array<string | { private: string }>`,`The instruction the model gets on every turn unless a systemByRole entry replaces it; some providers send it for an image profile only with includeText on. Mark what must not leak as { private: text }; only that is guarded. With none, the whole prompt is.`),"identity.systemByRole":B(`Record<string, string | Array<string | { private: string }>>`,`Other system instructions, picked by the role a turn names.`),"identity.systemByRole.*":B(`string | Array<string | { private: string }>`,`The instruction that replaces identity.system when a turn names this role.`),models:B(`Record<ModelId, ModelBinding | DecisionModelBinding>`,`The trained AI systems that turn input into results. Each entry binds a local name to an upstream model and its call settings.`),"models.*":B(`ModelBinding | DecisionModelBinding`,`One model: how to reach it and the settings sent with it.`),"models.*.protocol":B(`string`,`The API shape this model is spoken to in.`),"models.*.provider":B(`string`,`The service that runs the model or routes requests to one, such as Gemini or OpenRouter. Its registration supplies the endpoint and authentication.`),"models.*.keySlot":B(`KeySlot`,`The key slot this model's calls are signed with, instead of the provider's. Use it to bill one model to a different key. Absent: the provider's primary slot.`),"models.*.fallbackKeySlot":B(`KeySlot`,`The key slot tried once after a rate limit or a busy model on the primary slot, instead of the provider's fallback. Must differ from the primary slot. Absent: the provider's fallback slot, if it has one.`),"models.*.options":B(`JsonObject`,`Settings only this model's protocol has, such as a task type or vector size. Each is checked when the profile loads. Any left out keep the provider's default.`),providerContinuation:B(`ProviderContinuationPolicy`,`Who holds the conversation a saved provider state continues.`),"providerContinuation.history":B(`'host' | 'stateless' | 'provider'`,`Who holds the conversation a checkpoint continues: the host passes history back, the provider keeps it and the checkpoint travels alone, or the profile is stateless and every request stands alone.`,[`host`,`stateless`,`provider`]),"models.*.apiId":B(`string`,`The model's id as the provider lists it, such as gemini-2.5-flash; sent on every call. The name this model has in the profile is its key in models.`),"models.*.timeoutMs":B(`number`,`How long a decision waits for its provider, in milliseconds. Omit for no timeout.`),decision:B(`{ contract: DecisionContractId }`,`Names the host decision this profile makes.`),"decision.contract":B(`string`,`Your name for this decision, on its traces. Not sent to the model. Not checked against the questions.`),"models.*.efforts":B(`Record<string, ThinkingLevel>`,`Named thinking levels. A turn picks one when allowEffortSelect is on. A provider refuses a level its model does not take. Speech ignores them, and so may an image profile without includeText.`),"models.*.efforts.*":B(z(En),`The thinking level sent to the provider for this name.`,En,{none:`No thinking, where the provider has that level.`,minimal:`The least thinking.`,low:`Light thinking.`,medium:`Moderate thinking.`,high:`Heavy thinking.`,xhigh:`Heavier thinking, where the provider has that level.`,max:`The most thinking the model supports, where the provider has that level.`}),"models.*.defaultEffort":B(`string`,`The effort a turn gets when it doesn't pick one.`),"models.*.allowEffortSelect":B(`boolean`,`Lets a turn pick an effort; needs two or more efforts.`),"models.*.summaries":B(`boolean`,`Asks the model for summaries of its thinking, which not every model sends; with some providers, off only hides thoughts, and others ignore it.`),"models.*.maxOutputTokens":B(`number`,`The token limit for one reply. Some providers never send it for speech, or for image without includeText.`),"models.*.temperature":B(`number`,`How varied the model's wording is; higher is more random. Some providers never send it for speech, or for image without includeText.`),"models.*.builtInTools":B(`BuiltinToolId[]`,`The provider's own tools, such as Google Search, this model may use; each must be registered as a builtin tool and declared by the provider's adapter.`),"models.*.compaction":B(`CompactionSpec`,`Summarises history past a threshold. A text agent can write the summary. Other types name a compaction profile.`),"models.*.compaction.maxTokens":B(`number`,`The token budget compactAt is a fraction of.`),"models.*.compaction.trigger":B(`(ctx: CompactionTriggerContext) => boolean | Promise<boolean>`,`Your function that decides when to compact, in place of compactAt and maxTokens.`),"models.*.compaction.compactAt":B(`number`,`The fraction of maxTokens, between 0 and 1, at which compaction starts, unless trigger decides.`),"models.*.compaction.previousExchanges":B(`number`,`How much recent history compaction keeps: a number of exchanges (1 or more), a fraction of maxTokens below compactAt, or 0 to compact it all.`),"models.*.compaction.profile":{...B(`ProfileId`,`The text profile that writes the summary; register it before this one. Leave it out and a text agent summarises its own history, with its own instructions and model and no tools. Its registered model binding selects the provider independently of the calling agent.`),unset:`The agent itself`},"models.*.compaction.timing":B(z(Rn),`Whether the kernel compacts before the turn or tells the host to compact after it.`,Rn,{before:`The kernel compacts before the turn runs.`,after:`The turn's done event says compaction is due, and the host runs it.`}),"models.*.compaction.meter":B(z(Ln),`What the threshold counts.`,Ln,{history:`Tokens in the earlier conversation.`,input:`The prompt tokens the provider reported for the last call, or the count the host passes in.`}),"profile.defaultModel":B(`ModelId`,`The model a turn gets when it doesn't pick one.`),"profile.allowModelSelect":B(`boolean`,`Lets a turn name the model it runs on; a name the profile does not declare is refused.`),"profile.maxSteps":B(`number`,`The most model calls one turn may make while using tools, counted afresh for each rewrite; 1 runs the tools asked for but never sends their results back. Live sessions ignore it.`),tools:B(`{ allow: ToolId[]; t1Policy?; t2Loader?; parallel? }`,`The registered tools this profile may use, and how they load. Built-in tools are set per model.`),"tools.allow":B(`ToolId[]`,`Your registered tools this agent may use; the provider's own tools go on the model's builtInTools instead.`),"tools.t1Policy":B(`(ctx) => ToolId[] | Promise<ToolId[]>`,`Your function that picks, at the start of each turn, which T2 tools to load up front; the rest wait for tools.t2Loader.`),"tools.t2Loader":B(`ToolId`,`The function tool that loads T2 tools. It must be in allow and return { loaded: ToolId[] }. One forbidden id fails the load. Ids off the turn path are skipped. The tools it loads can be called from the next step: a step's calls see the tools as they stood when the step began.`),"tools.parallel":B(`boolean`,`true: the calls of one step run side by side, and a call whose pre_tool answers waitFor starts its body once those calls settle. Left out or false: they run one at a time, in the order the model made them. A step is the calls the model makes together in a turn, or the calls a host runs through invokeToolStep.`),inputs:B(`ProfileInputsSpec | DecisionInputsSpec`,`What a turn may send (text, files, voice, choices), or on a decision, the state it reads.`),"inputs.state":B(`'json'`,`A decision reads JSON state, passed on each call.`,[`json`]),"inputs.maxStateBytes":B(`number`,`The largest state, in bytes, a decision call may send; larger state is refused before it leaves your process.`),"inputs.text":B(`boolean`,`Whether a turn may send text.`),"inputs.attachments":B(`{ accept: string[] }`,`Lets turns send files.`),"inputs.attachments.accept":B(`string[]`,`The file types a turn may send, where type/* matches a whole family; image profiles take only images, video, and PDF.`,or,`Types the kernel knows; a listed type it doesn't know is refused when a turn sends it.`),"inputs.voice":B(`{ accept: string[] }`,`Lets turns send voice clips.`),"inputs.voice.accept":B(`string[]`,`The audio types a voice clip may be; audio/* matches them all.`,cr,`Audio types the kernel knows.`),"inputs.maxFiles":B(`number`,`The most files and voice clips one turn or embedding request may send, counted together.`),"inputs.maxBytes":B(`number`,`The largest file or clip, in bytes, a turn or embedding request may send inline.`),"inputs.maxTurnBytes":B(`number`,`The most bytes one turn or embedding request may send inline across all its files and clips.`),"inputs.limitsByMime":B(`Record<string, number>`,`Size limits by file type that replace maxBytes for those types.`),"inputs.limitsByMime.*":B(`number`,`The largest file of this type (or type/* family), in bytes, a turn or embedding request may send inline.`),"inputs.slots":B(`Record<string, string[]>`,`Named choices a turn or a call can make, such as language, each with its allowed values. {name} in a prompt becomes the chosen value.`),"inputs.slots.*":B(`string[]`,`The values a turn may choose for this slot; any other is refused.`),"inputs.context":B(`{ from: ContextSender[]; maxChars: number }`,`Lets the page or the host send the agent one package of things to know, read at the context boundary.`),"inputs.context.from":B(`Array<'client' | 'server'>`,`Who may send context; context from anyone else is refused.`,Nn,{client:`The browser. A visitor can change it, so it is untrusted.`,server:`The host's own code. It is assembled, like turn system text.`}),"inputs.context.maxChars":B(`number`,`The longest package, in characters of its JSON, each sender may send.`),outputs:B(`ProfileOutputsSpec`,`The shape of the reply, how it is checked, and how it streams.`),"outputs.structured":B(`StructuredSchemaId | StructuredBySlot | null`,`The registered JSON schema the reply must follow, which can vary by slot; register it before the profile.`),image:B(`ProfileImageSpec`,`How the images this profile generates are shaped and made: size, format, quality and references. Each setting is sent only where the provider has it; one it lacks is refused or ignored, as that setting says.`),"image.aspectRatio":B(`string`,`The shape of generated images, such as 16:9.`),"image.resolution":B(`string`,`How detailed generated images are, such as 1K, 2K or 4K.`),"image.mimeType":B(`string`,`The file type of generated images; a provider that takes a fixed set of types may use png for any other.`),"image.quality":B(`string`,`How much effort the model spends on each image: auto, low, medium, or high. A provider that has no such setting refuses it.`),"image.background":B(`string`,`The background of generated images: auto, transparent, or opaque. A provider that has no such setting refuses it.`),"image.n":B(`number`,`How many images one request makes, where the provider takes a count.`),"image.seed":B(`number`,`A seed for repeatable images, where the provider and the model honour it.`),"image.outputCompression":B(`number`,`Compression from 0 to 100 for jpeg and webp images, where the provider takes it.`),"image.references":B(`Array<TurnBlob | TurnMediaRef>`,"Images sent with every turn, before the user's. Each is bytes (`data`) or a link (`uri`). Some providers take http(s) links only, and none with includeText."),"image.includeText":B(`boolean`,`Whether the model may write text alongside its images; with some providers this also sends the system instruction and history.`),speech:B(`ProfileSpeechSpec`,`How the profile's speech sounds and is delivered: voice, style, speed and audio format. A turn may replace voice, style and speed for that turn.`),"speech.voice":B(`string`,`The voice the speech is read in, by the provider's own name for it; a turn's speech.voice replaces it.`),"speech.style":B(`string`,`How the script is delivered, in plain words (pace, mood, accent); it is never read aloud, and a turn's speech.style replaces it. A model that takes no direction ignores it.`),"speech.speed":B(`number`,`The speaking rate, where 1 is the voice's own pace; a turn's speech.speed replaces it. A provider that has no rate refuses it or ignores it.`),"speech.format":B(z(jn),`The audio encoding each turn's speech comes back in, and so what the host plays or stores.`,jn,{pcm:`Uncompressed audio, delivered as WAV.`,mp3:`Compressed audio; a provider that cannot make it refuses the turn.`}),live:B(`ProfileLiveSpec`,`How a realtime voice and video session runs: what it accepts from the user, the voice it answers in, when it hears the user start and stop, and how it resumes and trims its context.`),"live.ingress":B(`LiveIngressSpec`,`Which channels the session accepts from the user.`),"live.ingress.audio":B(`boolean`,`Whether the session accepts microphone audio.`),"live.ingress.video":B(`boolean`,`Whether the session accepts camera frames.`),"live.ingress.text":B(`boolean`,`Whether the session accepts typed text.`),"live.voice":B(`string`,`The voice the model speaks in.`,un,`Voice names to pick from; any other name is sent as written.`),"live.vad":B(`LiveVadSpec`,`How the session detects when the user starts and stops speaking.`),"live.vad.activityHandling":B(z(Pn),`Whether the user speaking interrupts the model's reply.`,Pn,{START_OF_ACTIVITY_INTERRUPTS:`The user speaking cuts the reply off.`,NO_INTERRUPTION:`The model finishes its reply.`}),"live.vad.startSensitivity":B(z(Fn),`How readily the session decides the user has started speaking.`,Fn,{START_SENSITIVITY_LOW:`Detects the start of speech less often.`,START_SENSITIVITY_HIGH:`Detects the start of speech more often.`}),"live.vad.endSensitivity":B(z(In),`How readily the session decides the user has stopped speaking.`,In,{END_SENSITIVITY_LOW:`Ends speech less often, waiting through pauses.`,END_SENSITIVITY_HIGH:`Ends speech more often, at shorter pauses.`}),"live.vad.prefixPaddingMs":B(`number`,`How long speech must last, in milliseconds, before it counts as the user starting to speak.`),"live.vad.silenceDurationMs":B(`number`,`How long a silence, in milliseconds, ends the user's speech.`),"live.sessionResumption":B(`boolean`,`Whether the provider sends resume handles, which the host can pass to a new session to carry this one on.`),"live.greeting":B(`string`,`A prompt the call sends itself when it opens new, so the agent speaks first. The visitor does not see it. It may use {slot}.`),"live.resumed":B(`{ prompt: string; afterMs?: number }`,`What happens when a call comes back after a drop. It needs live.sessionResumption.`),"live.resumed.prompt":B(`string`,`A prompt the call sends itself when it resumes, so the agent says it is back. The visitor does not see it. It may use {slot}.`),"live.resumed.afterMs":B(`number`,`The shortest time away, in milliseconds, that earns the prompt; a shorter drop resumes silently.`),"live.contextCompression":B(`LiveContextCompressionSpec`,`Trims the session's context once it grows past the trigger.`),"live.contextCompression.triggerTokens":B(`number`,`The context size, in tokens, that starts trimming.`),"live.contextCompression.slidingWindow":B(`LiveSlidingWindowSpec`,`Trims by dropping the oldest turns; the system instruction stays.`),"live.contextCompression.slidingWindow.targetTokens":B(`number`,`The context size, in tokens, to trim down to; below the trigger.`),"live.transcription":B(`LiveTranscriptionSpec`,`Text transcripts of the session's speech.`),"live.transcription.input":B(`boolean`,`Whether the user's speech is transcribed.`),"live.transcription.output":B(`boolean`,`Whether the model's speech is transcribed; always on while a detector reads live_reply, since it reads the transcript.`),"outputs.validation":B(`ProfileValidationSpec`,`Your checks on a structured reply, and how many rewrites a failure gets.`),"outputs.validation.fields":B(`Record<string, ProfileValidator>`,`Your checks, each keyed by a dotted path into the structured reply, such as diagram.mermaid; a path no structured schema reaches is refused when the profile registers.`),"outputs.validation.fields.*":B(`(candidate: unknown, slots?: Record<string, string>) => ValidationResult | Promise<ValidationResult>`,`Your check on this part of the reply, reached through object properties only; a failure sends its error back to the model to rewrite while retries remain.`),"outputs.validation.items":B(`Record<string, ProfileItemRule>`,`Your checks on the items of a list, each keyed by the dotted path of that list in the structured reply, such as claims; a path no structured schema reaches as a list is refused when the profile registers.`),"outputs.validation.items.*":B(`ProfileItemRule`,`Your check on each item of this list. A refused item never fails the reply and the rest of the reply is kept.`),"outputs.validation.items.*.check":B(`(item: unknown, turn: ItemCheckTurn) => ValidationResult | Promise<ValidationResult>`,`Your check on one item, given what the tools of the turn returned (turn.toolResults); its error is the reason the model reads on a rewrite and the host reads on the removed item.`),"outputs.validation.items.*.onFail":B(`'drop' | 'fix'`,`drop removes a refused item. fix first asks the model to rewrite the refused items alone, once and while retries remain, then removes any refused again. Removed items leave on the structured event as removed.`,Wn),"outputs.validation.maxRetries":B(`number`,`How many times the model may rewrite a reply that fails your checks or the schema's required keys before it goes out as it is; under sse, an attempt that gets rewritten has already streamed. A rewrite of a blocked reply (guardrails.blockedReply) counts against this too.`),"outputs.streaming":B(`ProfileStreamingSpec`,`How the reply reaches the host, and whether its thinking does.`),"outputs.streaming.mode":B(z(An),`Whether the reply reaches the host as the model writes it, or whole.`,An,{sse:`Events arrive as the model writes, so a reply that fails outputs.validation has already streamed when it is rewritten; some providers always answer image and speech in one piece.`,buffered:`One non-streaming call, whose events arrive together; under outputs.validation, only once the reply passes or retries run out. Thinking still streams.`}),"outputs.streaming.streamThoughts":B(`boolean`,`Whether the model's thinking reaches the host.`),turnBehaviour:B(`ProfileTurnBehaviourSpec`,`Whether a reply that stopped early can be continued, and whether a running turn can be steered.`),"turnBehaviour.resumption":B(`ProfileTurnResumptionSpec`,`Continuing a reply that stopped early; live uses sessionResumption instead.`),"turnBehaviour.resumption.allowContinue":B(`ContinueStopKind[]`,`Which early stops the host offers the user a Continue for; the kernel doesn't refuse a continue after other stops.`,Gn,{length:`The reply hit the output token limit.`,stream_incomplete:`The connection dropped mid-reply.`,provider_error:`The provider returned an error or timed out.`}),"turnBehaviour.resumption.autoContinue":B(`ContinueStopKind[]`,`Which early stops are continued without asking, whether or not allowContinue offers a Continue for them. When set, a text turn sends a listed failed model call that gave no reply again itself; the host continues the rest.`,Gn,{length:`The reply hit the output token limit.`,stream_incomplete:`The connection dropped mid-reply.`,provider_error:`The provider returned an error or timed out.`}),"turnBehaviour.resumption.maxContinues":B(`number`,`How many times one reply may be continued; once set, each continue must say which one it is. Also how many failed model calls one text turn sends again itself (one when unset).`),"turnBehaviour.allowSteering":B(`boolean`,`Lets your onStage hook add messages to a running turn. Text profiles also let the user steer.`),"turnBehaviour.atStepLimit":B(`'stop' | 'answer'`,`What happens when a turn reaches maxSteps while the model still wants tools: the turn stops with no answer, or the last call is made without tools so it answers.`,Un,{stop:`It may still call tools; if it does, they run and the turn stops as step_limit with no answer.`,answer:`It is sent without tools, so it writes the answer from what the turn has gathered.`}),guardrails:B(`ProfileGuardrailsSpec`,`Theorem checks what enters or leaves an agent’s context and generation against built-in or custom rules at each configured boundary.`),"guardrails.quota":B(`QuotaGuardrailSpec`,`A daily turn limit. Your server enforces it with takeSlot.`),"guardrails.quota.perDay":B(`number`,`Turns each client IP may run on this profile per UTC day, one at a time; counts live in the process, and a loopback caller is not counted.`),...gr(),"guardrails.blockedReply":B(`BlockedReplySpec`,`How a reply a guardrail blocked is handled: the model rewrites it, or the user gets a refusal, and how many rewrites it gets.`),"guardrails.blockedReply.onBlock":B(z(Kt),`Whether the model gets to rewrite a reply a guardrail blocked, or the user gets a refusal in its place.`,Kt,{retry:`The model reads why and rewrites the reply, up to maxRetries times; once retries run out, the reply is withheld and the turn ends with a safety error. Live never rewrites: it withholds at once.`,refuse:`The user sees the egress.refusal wording in place of the reply, and the turn ends.`}),"guardrails.blockedReply.maxRetries":B(`number`,`How many times the model may rewrite a blocked reply. Live ignores it.`),"guardrails.network":B(`NetworkGuardrailSpec`,`Addresses HTTP and MCP tools may reach.`),"guardrails.network.allowPrivateNetworks":B(`boolean`,`Lets tools reach localhost and private network addresses, for local development.`),"guardrails.network.allowedHosts":B(`string[]`,`Hostnames tools may reach even when they resolve to a private address; public hosts don't need listing. Names are resolved only when the host passes resolveHost.`),"guardrails.network.allowedSchemes":B(`string[]`,`The URL schemes tools may use.`),"guardrails.taint":B(`TaintGuardrailSpec`,`Tool limits after a remote read.`),"guardrails.taint.afterRemoteRead":B(z(Yt),`Which tool calls are refused, by each tool's access, once the turn has read a remote tool's result.`,Yt,{off:`None; risky calls are only logged.`,destructive:`Destructive calls.`,write:`Read-write and destructive calls.`}),"guardrails.taint.remoteDestination":B(z(Xt),`What happens to a tool call, read-only ones too, that sends to an email address, a link's host or a bank account number (IBAN) that only the running text of a remote tool's result named. One the user, the system prompt, or a local tool gave passes, and so does one that is a whole field of the result.`,Xt,{off:`The call runs; it is only logged.`,confirm:`The call waits for the user to approve it; an approval runs it.`,block:`The call is refused, and the model is told why.`}),"guardrails.disclosure":B(`{ enforce: DecisionDisclosureEnforcer }`,`Your check on the state before a decision sends it to the model.`),"guardrails.disclosure.enforce":B(`(state, context) => DecisionDisclosureVerdict | Promise<DecisionDisclosureVerdict>`,`Your function that allows or blocks the state before it is sent.`),labels:B(`LabelOverrides`,`This profile's own wording for error lines, notices, and notes to the model, by labels key.`),"labels.*":B(`string`,`The wording for this labels key; canary.bind_note must keep its {canary} placeholder.`),observability:B(`ProfileObservabilitySpec`,`Where this profile's traces go and what they keep.`),"observability.writeTo":B(`false | string | TraceSink`,`Where traces go: a registered destination id, your own writer, or false. An unregistered id fails the turn at the start. A sink passed to runTurn replaces it.`),"observability.sampleRate":B(`number`,`The share of traces kept, from 0 to 1, each kept or dropped whole; a sink passed straight to runTurn keeps every trace.`),"observability.include":B(`TraceIncludeSpec`,`Which optional parts of a trace are kept.`),"observability.include.upstreamLog":B(`boolean`,`Keeps each row the provider sent back, scrubbed, as it arrived, with media bytes replaced by their sha256.`),"observability.include.outboundWire":B(`boolean`,`Keeps each request body sent to the provider, scrubbed.`),"observability.include.evidenceRaw":B(`boolean`,`Keeps the provider's raw payload on grounding results such as search citations; upstreamLog rows keep their own copy.`),"observability.include.usage":B(`boolean`,`Keeps token counts and other usage figures on spans; upstreamLog rows keep their own.`),"observability.include.guardrailDecisions":B(`boolean`,`Keeps each guardrail decision.`),"observability.include.guardrailMatchPreview":B(`boolean`,`Keeps the exact text each guardrail matched, unscrubbed, on the trace and the host's event stream; for debugging only.`),"observability.resource":B(`Record<string, TraceAttributeValue>`,`Attributes stamped on every trace, such as service.name.`),"observability.scrub":B(`TraceScrubSpec`,`What is removed from stored traces, separately from the turn's guardrails.`),"observability.scrub.sensitive":B(`ScrubSwitch`,`Removes what the data detectors (IDs, Financial, Network, Credentials) and your own detectors find from stored traces. On, it cleans with the patterns each reads the turn with; { theorem, host } picks Theorem's patterns, yours, or both for the trace alone.`),"observability.scrub.injection":B(`ScrubSwitch`,`Removes what Injection and Tool instructions find from stored traces. On, it cleans with the patterns each reads the turn with; { theorem, host } picks Theorem's patterns, yours, or both for the trace alone.`),"observability.scrub.canary":B(`ScrubSwitch`,`Removes the canary token from stored traces. The canary is Theorem's, so { theorem: false } keeps it.`),"observability.retainForDays":B(`number`,`Days a trace file is kept, by its UTC day. The next write removes old files. 0 or less keeps all.`),"observability.rotateAfterMiB":B(`number`,`File size in MiB at which a file-based destination starts a new file, handed to every destination with the record. Default 32.`),"observability.onWriteError":B(`(err: unknown) => void`,`Your function called when a trace can't be built or written; the turn carries on, and a destination's own error handler takes priority. An unregistered writeTo id is a config error instead.`)}),yr=B(z($n),`How the tool runs.`,$n,{builtin:`The provider's own tool, such as Google Search, run by the provider.`,function:`Your handler runs it.`,http:`The kernel calls your HTTP endpoint.`,mcp:`The kernel calls a tool on a remote MCP server.`,agent:`The kernel runs one turn of another registered agent and returns its reply.`}),br={bearer:`A token; a secret typed in at the prompt becomes a bearer token.`,api_key:`An API key; a secret typed in at the prompt becomes an API key.`,oauth2:`An OAuth sign-in; the host supplies the token.`},xr={"done.stop.kind":B(`TurnStopKind`,`Why the turn ended, on the done event: its stop.kind.`,Hn,{completed:`The model finished its reply.`,length:`The model reached its token limit.`,tool:`The model called tools and the turn hands them to the host, in done.tools.`,gate:`A pre_tool stage held a tool call. The host resumes it with invokeTool, not continueFrom.`,filtered:`The provider filtered the reply, or the egress guardrail withheld it.`,provider_error:`The provider failed or reported an error.`,cancelled:`The turn was cancelled, by the user or by a stage that aborted it.`,stream_incomplete:`The stream ended without the provider reporting a final status.`,step_limit:`The last model call maxSteps allows asked for tools, so the turn ended with no answer.`,interrupted:`A live utterance was cut off by an interruption.`,generation_complete:`Live: the model finished generating audio or text for this utterance. The turn may still be open.`}),"registerTool.type":yr,"local.baseUrl":B(`string`,`Where your local model server listens, such as Ollama, llama.cpp or vLLM. The browser calls it directly.`),"studio.remoteTools":{...B(`boolean`,`Whether tools that reach other hosts (HTTP and MCP) may run while a local model is in use. Off, a run with a local model reaches no host.`),unset:`Off`},"decision.questions.id":B(`string`,`The question's name. Its answer comes back under it.`),"decision.questions.type":B(`'choice' | 'score' | 'noul' | 'box'`,`The kind of answer the question takes.`,[`choice`,`score`,`noul`,`box`],{choice:`One of the named options, with a confidence and a probability for each option.`,score:`A level on an ordered scale, with a confidence.`,noul:`One number, which may weigh named criteria.`,box:`Where something is in an image: its top, bottom, left and right edges, with a confidence.`}),"decision.questions.instructions":B(`DecisionEntry`,"What to ask about the state. Name a state field in backticks, such as `photo`, and one of the decision's images by its reference, such as <ginger>. A box looks in its In image, else in the image of the first field it names."),"decision.questions.image":{...B(`string`,"The image a box is in: one of the decision's images, such as <ghs02>, or a state field its instructions name, such as `photo`. The model is told it in the instructions."),unset:`The image the instructions name`},"decision.images":B(`Record<string, DecisionAsset>`,`Pictures sent with every decision, beside the state. A question names one by its reference, such as <ghs02>. A PNG or JPEG.`),"decision.images.name":B(`string`,`The reference a question writes, without its angle brackets: ghs02 is written <ghs02>. Lowercase letters, digits and _.`),"registerTool.name":B(`string`,`The tool's id, which profiles list in tools.allow (or a model's builtInTools) and the model calls a custom tool by.`),"registerTool.description":B(`string`,`Tells the model what the tool does (custom tools only).`),"registerTool.input":B(`ZodSchema`,`The Zod schema for the tool's arguments, sent to the model and checked on every call.`),"registerTool.output":B(`ZodSchema`,`The Zod schema every result the tool returns must match; the kernel's own not-signed-in note is not checked.`),"registerTool.handler":B(`ToolHandler`,`Your function that runs the tool; it can also yield progress as it goes.`),"registerTool.endpoint":B(`string`,`The URL the tool calls, with {name} placeholders for mapping.pathParams; the scheme and host must be written out.`),"registerTool.method":B(z(Zn),`The HTTP method; every method but GET sends a JSON body.`,Zn),"registerTool.headers":B(`Record<string, string>`,`Headers sent with every request to the tool's own origin, never once a redirect leaves it.`),"registerTool.mapping":B(`{ pathParams?, queryParams?, bodyParam? }`,`Where each argument goes in the request.`),"registerTool.mapping.pathParams":B(`string[]`,`Arguments that fill the {name} placeholders in the endpoint.`),"registerTool.mapping.queryParams":B(`string[]`,`Arguments added to the query string.`),"registerTool.mapping.bodyParam":B(`string`,`The one argument sent as the whole JSON body; without it, a method other than GET sends every argument the path and query leave unused.`),"registerTool.serverUrl":B(`string`,`The MCP server's URL.`),"registerTool.mcpToolName":B(`string`,`The tool's name on the MCP server.`),"registerTool.profile":B(`ProfileId`,`The profile this agent tool runs: text, image, or speech. Register it first. Nothing it calls may stop on a gate.`),"registerTool.answeredBy":{...B(`'page'`,`Who answers a call to a function tool. With page, the page the agent is on returns the output, and the tool has no handler.`,[`page`]),unset:`Its handler`},"registerTool.maxCallsPerTurn":{...B(`number`,`How many times one turn of the calling agent may run this tool.`),unset:`As many as its steps allow`},"registerTool.fieldText":{...B(`Partial<Record<keyof AgentToolInput, string>>`,`What the calling model reads on a field of an agent tool input, such as text. A field the profile does not take is refused when the tool registers.`),unset:`The fields carry no text`},"registerTool.hostFields":{...B(`Record<string, ZodType>`,`Fields the calling model fills on an agent tool that only the host reads. onAgentCall gets them as hostInput and turns them into what the agent is sent; the agent never sees them. A name the input already has is refused when the tool registers.`),unset:`The input is only what the profile takes`},"registerTool.hostOnly":{...B(`Array<'attachments' | 'voice' | 'slots'>`,`Channels the called profile takes that the calling model cannot fill on an agent tool; only onAgentCall sends them. A channel the profile does not take is refused when the tool registers.`),unset:`The model can fill every channel the profile takes`},"registerTool.auth":{...B(`ToolAuthConfig`,`How the tool gets its credential.`),unset:`No credential`},"registerTool.auth.type":B(z(nr),`The kind of credential the tool expects, shown when a turn stops to ask for one; the header follows the stored credential's own kind.`,nr,br),"registerTool.auth.slot":B(`string`,`Which of the credentials the turn passes in this tool uses.`),"registerTool.auth.service":B(`string`,`The service the person signs in to, as they know it, named when a turn stops to ask for a credential.`),"registerTool.auth.headerName":{...B(`string`,`The header the credential goes in; an API key's own headerName comes first.`),unset:`Authorization`},"registerTool.auth.headerPrefix":{...B(`string`,`Text put before the credential in the header; an API key's own headerPrefix comes first.`),unset:`"Bearer " for tokens, nothing for API keys`},"registerTool.auth.queryParam":{...B(`string`,`For a service that takes its API key in the URL: the query parameter the key goes in, in place of a header.`),unset:`The key goes in a header`},"registerTool.auth.onUnauthenticated":{...B(z(Qn),`What happens when the credential is missing, expired, can't be refreshed or is refused by the service.`,Qn,{gate:`The turn stops and asks the host for a credential.`,report_to_model:`The model is told the tool isn't signed in, and the turn goes on.`,fail:`The call fails as not signed in, for a key the host holds that no person can sign in to replace.`}),unset:`gate`},"registerTool.auth.scopes":B(`string[]`,`The OAuth scopes the tool needs, shown when a turn stops to ask for a credential. A service asking for any other scope fails the call, with no new sign-in.`),"registerTool.auth.clientId":B(`string`,`Your OAuth client id, kept for the host's sign-in flow; the kernel doesn't read it.`),"registerTool.auth.redirectUri":B(`string`,`Your OAuth redirect URI, kept for the host's sign-in flow; the kernel doesn't read it.`),"studio.authType":B(z(rr),`The kind of credential the tool expects, or none.`,rr,{none:`The tool sends no credential.`,...br}),"studio.testCredential":B(`string`,`A credential for this tool's connection tests, kept in the tab and never saved.`),"studio.stubOutput":{...B(`Record<string, unknown>`,`What a function tool returns in the studio, unless a demo handler has its name.`),unset:`A stand-in built from the output schema`},"studio.sampleInput":B(`Record<string, unknown>`,`Arguments for the connection test, never saved.`),"registerTool.inputSchema":B(`Record<string, unknown>`,`The tool's arguments as a JSON Schema, sent to the model.`),"registerTool.outputSchema":B(`Record<string, unknown>`,`The tool's result as a JSON Schema, which a function tool's stand-in result is built from.`),"registerStructured.jsonSchema":B(`Record<string, unknown>`,`The JSON Schema a structured reply must follow, sent to the model as its response format.`),"registerTool.access":B(z(er),`What the tool can change, which taint.afterRemoteRead refuses calls by after a turn reads a remote tool's result.`,er,{"read-only":`Only reads.`,"read-write":`Creates or updates things.`,destructive:`Deletes, charges, or does something else hard to undo.`}),"registerTool.loadTier":B(z(Xn),`When the tool becomes available to the model; live and host profiles load every allowed tool at the start.`,Xn,{T0:`At the start of every turn.`,T2:`On demand: when tools.t1Policy picks it at the start of a turn, or when the tools.t2Loader tool loads it mid-turn (custom tools only).`}),"registerTool.permission":B(z(tr),`Whether the host must approve a call before it runs; the provider's own tools never ask.`,tr,{auto:`Runs without asking.`,session_consent:`Asks once; the approval lasts as long as the host keeps passing it back.`,always_confirm:`Asks every time.`}),"registerTool.category":B(`string`,`A label for grouping tools; nothing reads it yet.`),"registerTool.labels":B(`ToolLabels`,`Transcript text for a call. {path} reads a value from the call. {results.0.name} reads a list item. {path|text} shows the text when the value is unusable. With no fallback, the label is dropped. A label is one line, or a list read top to bottom: the first line that fits is shown. A line fits when each {path} has a value and its condition holds, as in 'when status is archived: archiving {title}'. Neighbouring lines that open with '+ ' show together, joined in words. The last line of a list must always fit.`),"registerTool.labels.activity":{...B(`string | string[]`,`Transcript text while a call runs, e.g. 'Saving {title} to your collection'. {path} reads the call's input.`),unset:`The tool name, in words`},"registerTool.labels.activityPast":{...B(`string | string[]`,`What the transcript says once a call completes, e.g. 'Found {results.0.name}'. Each {path} is filled from the call's input, then its output.`),unset:`The tool name, in words`},"registerTool.labels.activityFailed":{...B(`string | string[]`,`What the transcript says when a call fails or the host labels it failed, e.g. 'Couldn't save {title}'. Each {path} is filled from the call's input.`),unset:`Couldn't complete, then the tool name in words`},"registerTool.labels.request":{...B(`string | string[]`,`What the approval card says the agent wants to do, e.g. 'check the weather in {city}'. Each {path} is filled from the call's input.`),unset:`The tool name, in words`},"registerTool.paths":{...B(`string[]`,`The turn paths this tool is offered on, where * means every path; a turn with no path gets only * tools. Host profiles ignore it.`),unset:`Every path`}};function Sr(e){let t=vr[e]??xr[e];if(t||!e.startsWith(`labels.`))return t;let n=e.slice(7),r=vr[`labels.*`];if(r&&Object.hasOwn(tt,n))return{...r,doc:tt[n]}}var V=C(S(),a()),H=S().trim().min(1),Cr=w({type:v(`text`),text:S()}),wr=w({type:b(kn),mimeType:S(),data:S()}),Tr=w({type:b(kn),mimeType:S(),uri:S()}),Er=g([Cr,wr,Tr]),Dr=Er,Or=w({protocol:S().min(1),provider:S().min(1).optional(),apiId:S().min(1).optional()}),kr=w({text:S().optional(),data:an,origin:Or}),Ar=w({role:b([`system`,`user`,`assistant`,`tool`]),content:S().optional(),parts:y(Er).optional(),tool_calls:y(w({id:S(),type:v(`function`),function:w({name:S(),arguments:S()})})).optional(),reasoning:y(kr).optional(),tool_call_id:S().optional(),name:S().optional(),metadata:V.optional()}),jr=Ar,Mr=w({kind:b(Hn),native:S().optional()}),Nr=Mr,Pr=[`input`,`output`],Fr=w({usd:x(),upstreamUsd:x().optional(),partial:v(!0).optional()}),Ir=w({type:S(),count:x(),searchQueryCount:x().optional()}),Lr=w({input:x(),output:x(),thinking:x().optional(),toolUse:x().optional(),cached:x().optional(),cacheWrite:x().optional(),total:x(),cost:Fr.optional(),estimated:y(b(Pr)).optional(),unknownMedia:w({input:x().optional(),output:x().optional()}).optional(),byModality:w({input:C(S(),x()).optional(),output:C(S(),x()).optional()}).optional(),grounding:y(Ir).optional()});w({id:S().optional(),model:S().optional()});var Rr=w({title:S(),uri:S(),type:b([`web`,`maps`]),placeId:S().optional()}),zr=Rr,Br=w({metadata:V.optional(),chunks:y(a()).optional(),searchHtml:S().optional()}),Vr={provider:S().min(1),raw:V.optional(),partial:_().optional()},Hr=De(`kind`,[w({...Vr,kind:v(`code_execution_call`),code:S(),language:S().optional(),id:S()}),w({...Vr,kind:v(`code_execution_result`),result:S().optional(),isError:_().optional(),callId:S().optional()}),w({...Vr,kind:b([`input_transcription`,`output_transcription`]),interim:_().optional()}),w({...Vr,kind:b([`voice_activity`,`url_context`])}),w({...Vr,kind:v(`session_resumption`),resumable:_()}),w({...Vr,kind:v(`provider_step`),step:S()})]),Ur=w({cause:v(`go_away`),code:x(),closedAfterMs:x(),errorKind:Qt.optional()}),Wr=De(`kind`,[w({kind:v(`closing_soon`),timeLeftMs:x().optional()}),w({kind:v(`ended`),timeLeftMs:x().optional(),ended:Ur,message:S()}),w({kind:b([`waiting_for_input`,`turn_complete`,`working`,`idle`])})]),Gr=w({code:S(),kind:Qt,message:S(),error:S().optional(),details:a().optional()}),Kr=w({slot:H,authType:b(nr),service:H,message:H,authorizationUrl:S().optional(),state:S().optional(),issuer:S().optional(),resource:S().optional(),requiredScopes:y(H).optional()}),qr={preparedArguments:C(S(),a()).optional(),tool:H,permission:b(tr).optional(),summary:H.optional(),request:H.optional(),access:b(er).optional()},Jr=De(`kind`,[w({...qr,kind:b([`confirmation`,`permission`,`page`])}),w({...qr,kind:v(`auth`),authChallenge:Kr})]),Yr=Jr,Xr=w({code:S(),message:S(),severity:b([`info`,`warning`,`error`]).optional()}),Zr=w({name:S(),kind:S(),status:S(),inputs:V.optional(),outputs:V.optional()}),Qr={status:v(Yn),prompt:H},$r=De(`kind`,[w({...Qr,kind:b([`confirm`,`text`]),options:y(H).optional()}),w({...Qr,kind:v(`choice`),options:y(H).min(1)})]);function ei(e){return $r.safeParse(e).success}var ti=w({type:v(`function`),name:S(),description:S(),parameters:V}),ni=w({builtins:y(S()),gated:y(S()),visible:y(S()),executable:y(S()),path:S().optional(),sessionPermissions:y(S()).optional(),wire:y(ti)}),ri=ni,ii=i({callId:S().min(1),operationId:S().min(1).max(256)}),ai={name:S(),callId:S()},oi=w({...ai,phase:pe().optional(),arguments:V,reasoning:y(kr).optional(),stepId:S().min(1).optional(),stepCallCount:x().int().min(1).optional()}),U={...ai,at:x()},si=De(`phase`,[w({...U,phase:v(`running`),edited:w({from:V,to:V}).optional(),activity:S().optional()}),w({...U,phase:v(`dispatch`),grantId:S().min(1),arguments:V}),w({...U,phase:v(`progress`),data:a()}),w({...U,phase:v(`draft`),text:S()}),w({...U,phase:v(`trace`),step:Zr}),w({...U,phase:v(`artifact`),artifact:a()}),w({...U,phase:v(`warning`),warning:Xr}),w({...U,phase:v(`complete`),output:a(),awaiting:_().optional(),readBack:S().optional(),parts:y(Er).optional(),activityPast:S().optional(),tokens:Lr.optional()}),w({...U,phase:v(`gate`),gate:Jr,readBack:S().optional()}),w({...U,phase:v(`error`),failure:Gr,readBack:S().optional(),activityPast:S().optional(),tokens:Lr.optional()}),w({...U,phase:v(`cancel`)})]),ci=g([si,oi]).and(w({operationId:S().min(1).max(256).optional()})),li=w({code:b(Jn),message:S(),field:S()}),ui=w({needed:_(),meter:b(Ln),tokens:x(),unknownMedia:x(),promptTokens:x().optional(),promptTokensEstimated:_().optional(),history:y(Ar)}),di=w({stop:b(Hn).optional(),error:Qt.optional(),empty:v(!0).optional(),unreadable:v(!0).optional()}),fi=[`tool`,`gate`];function pi(e,t){let{stop:n,...r}=e,{kind:i}=n;return i===`tool`||i===`gate`?t?{type:`done`,...r,stop:{...n,kind:i},tools:t}:void 0:{type:`done`,...r,stop:{...n,kind:i}}}var mi=b(fi),hi=b(Hn).exclude(fi),gi={providerState:on.optional(),type:v(`done`),tokens:Lr.optional(),traceparent:S().optional(),compaction:ui.optional(),interrupted:_().optional(),interactionId:S().optional()},_i=g([w({...gi,stop:w({kind:mi,native:S().optional()}),tools:ni}),w({...gi,stop:w({kind:hi,native:S().optional()}),tools:pe().optional()})]),W={provider_checkpoint:w({type:v(`provider_checkpoint`),providerState:on,history:y(jr).optional()}),provider_warning:w({type:v(`provider_warning`),warning:sn}),text:w({type:v(`text`),text:S()}),thought:w({type:v(`thought`),text:S()}),custom:w({type:v(`custom`),kind:S().min(1),data:L}),structured:w({type:v(`structured`),structured:a(),removed:y(w({path:S(),reason:S(),item:a()})).optional(),failed:y(w({path:S(),error:S()})).optional()}),structured_draft:w({type:v(`structured_draft`),text:S()}),attempt:w({type:v(`attempt`),attempt:x().int().positive(),reason:b([`validation`,`egress`])}),media:w({type:v(`media`),media:w({mimeType:S(),data:S()})}),grounding:w({type:v(`grounding`),grounding:Br}),citation:w({type:v(`citation`),sources:y(Rr),callId:S().optional()}),compaction:w({type:v(`compaction`),timing:v(`before`),meter:b(Ln),tokensBefore:x(),unknownMedia:x(),messagesBefore:x(),messagesAfter:x(),outcome:b(zn),history:y(Ar),summary:S().optional(),failure:di.optional(),droppedMedia:x(),tokens:Lr.optional()}),evidence:w({type:v(`evidence`),evidence:Hr,text:S().optional(),sessionResumptionHandle:S().optional()}),tokens:w({type:v(`tokens`),tokens:Lr,interactionId:S().optional()}),session:w({type:v(`session`),session:Wr,errorInternal:S().optional()}),guardrail:w({type:v(`guardrail`),guardrail:rn}),stage:w({type:v(`stage`),stage:b(Kn),callId:S().optional(),toolName:S().optional(),callNotStarted:_().optional(),awaiting:_().optional(),gate:Jr.optional(),stop:Nr.optional(),stageWarnings:y(li).optional(),injected:y(w({id:S().regex(/\S/),messages:y(Ar)})).min(1).optional(),released:x().int().nonnegative().optional()}),tool_draft:w({type:v(`tool_draft`),callId:S().min(1),name:S(),text:S()}),tool:w({type:v(`tool`),tool:ci,errorInternal:S().optional()}),error:w({type:v(`error`),errorKind:Qt,error:S().optional(),errorCopy:en.optional(),errorInternal:S().optional()}),done:_i},vi=g([De(`type`,[W.provider_warning,W.provider_checkpoint,W.text,W.thought,W.custom,W.structured,W.structured_draft,W.attempt,W.media,W.grounding,W.citation,W.compaction,W.evidence,W.tokens,W.session,W.guardrail,W.stage,W.tool_draft,W.tool,W.error]),W.done]),yi=W;function bi(e){return e.type===`text`||e.type===`media`||e.type===`structured`||e.type===`structured_draft`}function xi(e,t){let n=[],r=t;for(let t of e)if(!bi(t))n.push(t);else if(t.type!==`text`)r>0&&n.push(t);else if(r>0){let e=t.text.slice(0,r);r-=e.length,n.push(e===t.text?t:{...t,text:e})}return n}function Si(e){let t=[],n=0;for(let r of e){if(r.type===`attempt`){let e=t.splice(n);t.push(...e.filter(e=>!bi(e)))}r.type===`stage`&&r.released!==void 0&&t.push(...xi(t.splice(n),r.released)),t.push(r),r.type===`done`&&(n=t.length)}return t}var Ci=[`reply`,`reply_structured`];function wi(e,t,n,r={}){if(!We([t],n))return{action:`allow`,hits:[],value:e};let i=Ke(e);if(i.unscannable)return{action:`block`,hits:[{rule:st.unscannable,severity:`high`}]};let a=j(i.text,t,n,r);if(a.action!==`redact`)return{action:a.action,hits:a.hits,value:e};let o=ot(e,e=>j(e,t,n,r).text??``),s=j(Ke(o).text,t,n,r).action;return s===`redact`||s===`block`?{action:`block`,hits:a.hits}:{action:`redact`,hits:a.hits,value:o}}function Ti(e,t,{boundary:n,reportedTo:r=e.text.length,scope:i={}}){let a=j(e.text,n,t,i),o=e.structured===void 0?void 0:wi(e.structured,`reply_structured`,t,i),s=r>=e.text.length?[]:a.hits.filter(e=>!e.span||e.span.start>=r),c=[a.action===`flag`?D(n,{action:s.length>0?`flag`:`allow`,hits:s}):D(n,a),o?D(`reply_structured`,o):void 0].filter(e=>e!==void 0),l=[a,o].flatMap(e=>e?.action===`block`?e.hits:[]);return{payload:{text:a.text??e.text,...o?{structured:o.value}:{}},rewritten:a.action===`redact`,events:c,...l.length>0?{blocked:l}:{}}}function Ei(e,t=[]){if(e.blocked)return e.blocked;let n=new Set(e.events.flatMap(e=>e.hits.map(e=>e.rule))),r=t.filter(e=>!n.has(e.rule));return r.length>0?r:void 0}function Di(e,t){return e?t.startsWith(e)?t.slice(e.length):`\n\n${t}`:t}function Oi(e,t){return O(e?`egress.refusal_cut`:`egress.refusal`,{},t)}var ki=`</tool_data>`,Ai=`<tool_data`,ji=new Set([`http`,`mcp`,`delegated`]);function Mi(e){return ji.has(e)}function Ni(e){let t=e.toLowerCase(),n=``,r=0;for(;r<e.length;){let i=t.indexOf(Ai,r),a=t.indexOf(ki,r),o=-1,s=null;if(i>=0&&(a<0||i<=a)?(o=i,s=`open`):a>=0&&(o=a,s=`close`),o<0||s===null){n+=e.slice(r);break}if(n+=e.slice(r,o),s===`close`){r=o+12;continue}let c=e.indexOf(`>`,o+10);if(c<0){n+=e.slice(o);break}r=c+1}return n}function Pi(e,t,n=`none`,r){let i=O(`advisory.guidance`,{},r).trim();return`<tool_data ${`tool="${t.tool}" origin="${t.origin}"`+(n===`none`?``:` advisory="${n}"`)}>\n${n===`none`?``:`${Fi(n,r)}${i?` ${i}`:``}\n`}${Ni(e)}\n${ki}`}function Fi(e,t){return O(e===`high`?`advisory.notice_high`:`advisory.notice_elevated`,{},t)}function Ii(e,t){if(t===void 0)return e;let n=Ke(t);return n.unscannable?e:`${e}\n${n.text}`}var Li={action:`allow`,hits:[]};function Ri(e,t,n,r){return t?j(e,t,n,r):{...Li,text:e}}function zi(e,t,n,r,i,a=[],o){let s=Ri(Ii(e,t),i,r.detect,{callable:a}),c=s.hits.filter(({rule:e})=>e===Xe.tool_instructions),l=Mi(n.origin),u=s.action===`allow`?void 0:{stage:`tool_result`,...i?{boundary:i}:{},trust:`untrusted`,action:s.action,hits:s.hits,provenance:n},d={...c.length>0?{suspicious:c}:{},...u?{event:u}:{}};return s.text===void 0?d:{text:l?Pi(s.text,n,Ue(c.map(({signal:e})=>e)),o):s.text,...d}}function Bi(e,t,n,r){let i=Ri(Ni(e),r,n.detect),a=r?D(r,i,t):void 0;return{...i.text===void 0?{}:{text:i.text},...a?{event:a}:{}}}function Vi(e,t,n,r){if(!r||e===void 0)return{value:e};let i=wi(e,r,n.detect),a=D(r,i,t);return{...i.action===`block`?{}:{value:i.value},...a?{event:a}:{}}}function Hi(e,t,n,r,i={}){if(!(r&&We([r],n.detect)))return{args:e};let a=e=>{let n=D(r,{action:`block`,hits:e},t);return n?{event:n}:{}},o=Ke(e);if(o.unscannable)return a([{rule:st.unscannable,severity:`high`}]);let s=j(o.text,r,n.detect,i);if(s.action===`block`)return a(s.hits);let c=D(r,s,t);if(s.action!==`redact`)return{args:e,...c?{event:c}:{}};let l=ot(e,e=>j(e,r,n.detect,i).text??``),u=j(Ke(l).text,r,n.detect,i).action;return u===`redact`||u===`block`?a(s.hits):{args:l,...c?{event:c}:{}}}function Ui(e,t){if(e.action!==`allow`)return{stage:`tool_call`,trust:`untrusted`,action:e.action,hits:e.hits,provenance:t}}function Wi(e,t,n=[]){let r=e?.sources??[],i=e?.suspicious??[];return Mi(t.origin)?{sources:[...r,t],suspicious:[...i,...n]}:{sources:r,suspicious:i}}function Gi(e){return(e?.sources.length??0)>0}function Ki(e){return(e?.suspicious.length??0)>0}var qi={"read-only":0,"read-write":1,destructive:2},Ji={off:1/0,destructive:2,write:1};function Yi(e,t,n,r){if(!Gi(e))return{action:`allow`};let i=qi[t]??0;if(i===0)return{action:`allow`};let a=Ki(e),o=[{rule:a?Qe.steeredTurn:Qe.taintedTurn,severity:`high`}];if(i<Ji[n.taint?.afterRemoteRead??`off`])return{action:`flag`,hits:o};let s=e?.sources.map(e=>e.tool).join(`, `)??``,c=O(a?`taint.reason_steered`:`taint.reason_tainted`,{},r);return{action:`block`,hits:o,rejection:O(`taint.blocked`,{access:t,sources:s,reason:c},r)}}var Xi={onBlock:`retry`,maxRetries:1};function Zi(e){return{onBlock:e?.onBlock??Xi.onBlock,maxRetries:e?.maxRetries??Xi.maxRetries}}function Qi(e){return{detect:$e(e?.detect),allow:it(e?.detect),blockedReply:Zi(e?.blockedReply),network:e?.network,quota:e?.quota,taint:e?.taint}}function $i(e){return(e.split(`;`)[0]??``).trim().toLowerCase()}function ea(e,t){let n=$i(t);return e.some(e=>{let t=$i(e);return t.endsWith(`/*`)?n.startsWith(t.slice(0,-1)):t===n})}function ta(e){return ir[$i(e)]}function na(e){return e.type===`text`||e.type===`image`||e.type===`live`?e.inputs:void 0}function ra(e,t){let n=na(e);return t===`voice`?n?.voice?.accept:n?.attachments?.accept}function ia(e,t){if(ta(t))for(let n of[`attachments`,`voice`]){let r=ra(e,n);if(r&&ea(r,t))return n}}function aa(e,t){let n=e.models[t];if(!n)throw new T(`config`,`Profile ${e.id} has no model binding for '${t}'`);return n}var oa=/^\d{1,3}(\.\d{1,3}){3}$/,sa=[e=>e===0,e=>e===127,e=>e===10,(e,t)=>e===100&&t>=64&&t<=127,(e,t)=>e===172&&t>=16&&t<=31,(e,t)=>e===192&&t===168,(e,t)=>e===169&&t===254,(e,t,n)=>e===192&&t===0&&(n===0||n===2),(e,t)=>e===198&&(t===18||t===19),(e,t,n)=>e===198&&t===51&&n===100,(e,t,n)=>e===203&&t===0&&n===113,e=>e>=224];function ca(e,t,n,r){return sa.some(r=>r(e,t,n))}function la(e){if(!oa.test(e))return!1;let[t=0,n=0,r=0,i=0]=e.split(`.`).map(Number);return t>255||n>255||r>255||i>255?!1:ca(t,n,r,i)}function ua(e){let t=e.toLowerCase().trim(),n=t.lastIndexOf(`:`),r=[],i=t;if(n!==-1){let e=t.slice(n+1);if(e.includes(`.`)){let a=e.split(`.`).map(e=>Number.parseInt(e,10));if(a.length!==4||a.some(e=>Number.isNaN(e)||e<0||e>255))return null;let o=a[0]??0,s=a[1]??0,c=a[2]??0,l=a[3]??0;r=[o<<8|s,c<<8|l];let u=t.slice(0,n+1);i=u.endsWith(`::`)?u:u.slice(0,-1)}}let a=i.split(`::`);if(a.length>2)return null;let o=a[0]?a[0].split(`:`).filter(Boolean):[],s=a.length===2&&a[1]?a[1].split(`:`).filter(Boolean):[],c=8-r.length;if(a.length===1){if(o.length!==c)return null}else if(o.length+s.length>=c)return null;let l=c-(o.length+s.length),u=Array(l).fill(0),d=e=>/^[0-9a-f]{1,4}$/.test(e)?Number.parseInt(e,16):null,f=[];for(let e of o){let t=d(e);if(t===null)return null;f.push(t)}let p=[];for(let e of s){let t=d(e);if(t===null)return null;p.push(t)}return[...f,...u,...p,...r]}var G=(e,t,n)=>e.slice(t,n).every(e=>e===0),da=[e=>G(e,0,8),e=>G(e,0,7)&&e[7]===1,e=>((e[0]??0)&65472)==65152,e=>((e[0]??0)&65472)==65216,e=>((e[0]??0)&65024)==64512,e=>((e[0]??0)&65280)==65280,e=>e[0]===8193&&e[1]===3512,e=>e[0]===256&&G(e,1,4),e=>e[0]===100&&e[1]===65435&&e[2]===1,e=>e[0]===8193&&e[1]===0],fa=[{match:e=>G(e,0,5)&&e[5]===65535,at:6},{match:e=>G(e,0,4)&&e[4]===65535&&e[5]===0,at:6},{match:e=>G(e,0,6),at:6},{match:e=>e[0]===100&&e[1]===65435&&G(e,2,6),at:6},{match:e=>e[0]===8194,at:1}];function pa(e){let t=ua(e);return t?.length===8?da.some(e=>e(t))?!0:fa.some(({match:e,at:n})=>{if(!e(t))return!1;let r=t[n]??0,i=t[n+1]??0;return ca(r>>8&255,r&255,i>>8&255,i&255)}):!1}function ma(e){let t=e.toLowerCase();for(;t.endsWith(`.`);)t=t.slice(0,-1);return t===`localhost`||t.endsWith(`.localhost`)||t===`local`||t.endsWith(`.local`)||t===`internal`||t.endsWith(`.internal`)||t===`lan`||t.endsWith(`.lan`)||t===`home.arpa`||t.endsWith(`.home.arpa`)||t===`localdomain`||t.endsWith(`.localdomain`)||t===`127.0.0.1`||t===`::1`||t===`[::1]`}function ha(e){let t=e.startsWith(`[`)&&e.endsWith(`]`)?e.slice(1,-1):e;return la(t)||pa(t)}function ga(e,t){let n;try{n=new URL(e)}catch{throw new T(`request`,`Invalid URL provided: "${e}"`)}let r=t?.allowPrivateNetworks??!1,i=t?.allowedHosts?.map(e=>e.toLowerCase())??[],a=n.hostname.toLowerCase(),o=r?[`http:`,`https:`]:[`https:`],s=t?.allowedSchemes?t.allowedSchemes.map(e=>e.endsWith(`:`)?e.toLowerCase():`${e.toLowerCase()}:`):o;if(!s.includes(n.protocol))throw new T(`blocked`,`URL scheme "${n.protocol}" is not permitted by network policy. Allowed: ${s.join(`, `)}`);if(!r&&!i.includes(a)){if(ma(a))throw new T(`blocked`,`Access to loopback target "${a}" blocked by network guardrail. Enable allowPrivateNetworks to permit local addresses.`);if(la(a))throw new T(`blocked`,`Access to private IPv4 address "${a}" blocked by network guardrail.`);if(pa(a.startsWith(`[`)&&a.endsWith(`]`)?a.slice(1,-1):a))throw new T(`blocked`,`Access to private IPv6 address "${a}" blocked by network guardrail.`)}return n}var _a=20,va=new Set([301,302,303,307,308]);async function ya(e,t,n){let{resolveHost:r,policy:i}=t,a=e.hostname.toLowerCase();if(r===void 0||i?.allowPrivateNetworks===!0||i?.allowedHosts?.some(e=>e.toLowerCase()===a)===!0||a.startsWith(`[`)||oa.test(a))return;let o=await r(a,n??void 0);if(o.length===0)throw new T(`blocked`,`Host "${a}" did not resolve to an address.`);let s=o.find(ha);if(s!==void 0)throw new T(`blocked`,`Host "${a}" resolves to private address "${s}", blocked by network guardrail.`)}function ba(e,t){return e===303?t!==`HEAD`:(e===301||e===302)&&t===`POST`}async function xa(e,t,n){let r=n.fetchFn??fetch,i=async e=>{let r=performance.now();try{let r=ga(e,n.policy);return await ya(r,n,t.signal),r}finally{n.onCheck?.(performance.now()-r)}},a=await i(e),o=a.origin,s=new Headers(t.headers),c=t.method??`GET`,l=t.body,u=!0;for(let d=0;;d++){let f=new Headers(s);if(u)for(let[e,t]of Object.entries(n.originBoundHeaders??{}))f.set(e,t);let p=await r(a.href,{...t,method:c,headers:f,body:l,redirect:`manual`}),m=p.headers.get(`location`);if(!n.followRedirects||!va.has(p.status)||m===null)return p;if(await p.body?.cancel(),d===_a)throw new T(`network`,`Too many redirects from "${e}"`);a=await i(new URL(m,a).href),u&&=a.origin===o,ba(p.status,c)&&(c=`GET`,l=void 0,s.delete(`content-type`))}}function Sa(e){return e.type===`text`?{type:`text`,text:e.text}:`uri`in e?{type:e.type,mimeType:e.mimeType,uri:e.uri}:{type:e.type,mimeType:e.mimeType,data:e.data}}function Ca(e){return e.type!==`text`&&`uri`in e}function K(e){let t=e.parts??[];return e.content?[{type:`text`,text:e.content},...t]:[...t]}function wa(e){let t=e.structured===void 0?e.text:JSON.stringify(e.structured);return[...t?[{role:`assistant`,content:t}]:[],...e.calls.length?[Ta(e.calls)]:[]]}function Ta(e){let t=e.flatMap(e=>e.reasoning??[]),n=[];for(let t of e)n.push({id:t.callId,type:`function`,function:{name:t.name,arguments:JSON.stringify(t.arguments)}});return{role:`assistant`,tool_calls:n,...t.length?{reasoning:[...t]}:{}}}var Ea=w({id:S().regex(/^[A-Za-z][A-Za-z0-9]*$/),name:S().min(1),description:S().min(1),endpoints:fe(b([`text`,`image`,`speech`,`live`,`decision`,`embedding`]),S().min(1))});function Da(e,t){return new T(`config`,O(`protocol.definition`,{id:e,issues:t}))}function Oa(e){let t=Ea.safeParse(e);if(!t.success)throw Da(String(e.id),Fe(t.error))}function ka(e,t,n,r){if(!n)throw new T(`internal`,O(`protocol.part_schema`,{protocol:e.id,kind:t}));let i=n.safeParse(r);if(!i.success)throw new T(`bad_response`,O(`protocol.part_invalid`,{protocol:e.id,kind:t}),{cause:i.error});return i.data}function Aa(e,t){return t.type===`reasoning`?{...t,data:ka(e,`reasoning`,e.reasoning,t.data),origin:{protocol:e.id}}:t.type===`custom`?{type:`custom`,kind:`${e.id}.${t.kind}`,data:ka(e,t.kind,e.custom?.[t.kind],t.data)}:t}async function*ja(e,t){for await(let n of t)yield Aa(e,n)}function Ma(e,t){let{complete:n,openSession:r}=t;return{...t,...n?{complete:r=>ja(e,n.call(t,r))}:{},...r?{async openSession(n){let i=await r.call(t,n);return{...i,events:()=>ja(e,i.events())}}}:{}}}function Na(e,t,n){let r=n??{},i=e.options.safeParse(r),a=(e.refusedOptions?.(t)??[]).filter(e=>typeof r==`object`&&!!r&&e in r);if(i.success&&a.length===0)return i.data;let o=i.success?a.map(e=>`✖ ${t} takes no ${e}`).join(`
|
|
3
3
|
`):Fe(i.error);throw new T(`config`,O(`protocol.options`,{apiId:t,protocol:e.id,issues:o}))}function q(e){if(Oa(e),typeof e.create!=`function`||typeof e.options?.safeParse!=`function`)throw Da(e.id,`create and options are required`);return Object.freeze({...e,lineage:Object.freeze([e.id]),create:t=>Ma(e,e.create(t))})}function Pa(e){return e instanceof ue?e.shape:void 0}function Fa(e,t){let n=e??{},r={};for(let e of t)e in n&&(r[e]=n[e]);return r}function Ia(e,t){let n=Pa(e.options),r=t.options?Pa(t.options):{};if(t.options&&!n)throw new T(`config`,O(`protocol.base_options`,{protocol:t.id,base:e.id}));for(let i of Object.keys(r??{}))if(n&&i in n)throw new T(`config`,O(`protocol.option_clash`,{protocol:t.id,option:i,base:e.id}));return{schema:n?i({...n,...r}):e.options,baseKeys:n?Object.keys(n):void 0,addedKeys:Object.keys(r??{})}}function La(e,t,n,r,i){let a={profileType:r.profileType,apiId:r.apiId,options:Fa(r.options,n.addedKeys)},o=[],s=t.read?.({...a,...i?{request:i}:{}}),c=e=>{for(let n of e??[])o.push(Aa(t,n))},l=(e,n,o=[])=>{if(!t.body)return{body:e,wroteTools:o};let s=t.body(e,{...a,builtInTools:r.builtInTools,headers:n,...i?{request:i}:{}});return{body:s.body,wroteTools:[...o,...s.wroteTools??[]]}};async function*u(e){for await(let t of e){let e=s?.row(t);c(e?.events),e?.consumed||(yield t)}}let d={...r,options:n.baseKeys?Fa(r.options,n.baseKeys):r.options,send(e,t){let n=new Headers(t.headers),i=l(e,n,t.wroteTools);return u(r.send(i.body,{...t,headers:Object.fromEntries(n),wroteTools:i.wroteTools}))},async connect(e,t){let n=l(e,new Headers,t?.wroteTools),i=await r.connect(n.body,{wroteTools:n.wroteTools});return{...i,frames:()=>u(i.frames())}}};async function*f(e){for await(let t of e)yield*o.splice(0),t.type===`done`&&c(s?.finish?.().events),yield*o.splice(0),yield t;yield*o.splice(0)}return{operations:e.create(d),drained:f}}function Ra(e){let t=e().operations,n={};return t.complete&&(n.complete=t=>{let{operations:n,drained:r}=e(t);return r(n.complete(t))}),t.openSession&&(n.openSession=async t=>{let{operations:n,drained:r}=e(t),i=await n.openSession(t);return{...i,events:()=>r(i.events())}}),t.decide&&(n.decide=t=>e().operations.decide(t)),t.embed&&(n.embed=t=>e().operations.embed(t)),n}function za(e,t,n){let r=t[e]??n[e];return r?{[e]:r}:{}}function Ba(e,t){Oa({...t,endpoints:t.endpoints??{}});let n=Ia(e,t);return Object.freeze({id:t.id,name:t.name,description:t.description,endpoints:{...e.endpoints,...t.endpoints},options:n.schema,...e.continuation?{continuation:e.continuation}:{},...t.reasoning?{reasoning:t.reasoning}:{},...t.custom?{custom:t.custom}:{},...za(`framing`,t,e),...za(`error`,t,e),...za(`embeddingLimits`,t,e),...za(`refusedOptions`,t,e),base:e,lineage:Object.freeze([t.id,...e.lineage]),create:r=>Ra(i=>La(e,t,n,r,i))})}function Va(e,t){return t.lineage.includes(e)}var Ha=S().regex(Dn),J=i({maxOutputTokens:x().int().positive().optional(),temperature:x().finite().nonnegative().optional(),efforts:C(S().min(1),b([`none`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`])).optional(),defaultEffort:S().min(1).optional(),allowEffortSelect:_().optional(),summaries:_().optional(),builtInTools:y(S().min(1)).optional(),compaction:ge(e=>typeof e==`object`&&!!e&&!Array.isArray(e)).optional()}).shape,Ua=i({protocol:S().min(1).describe(`The API shape this model is spoken to in.`),provider:S().min(1).describe(`The service that runs the model or routes requests to one, such as Gemini or OpenRouter. Its registration supplies the endpoint and authentication.`),apiId:S().min(1).describe(`The id the provider knows the model by.`),maxOutputTokens:J.maxOutputTokens.describe(`The most tokens the model may write in one step.`),temperature:J.temperature.describe(`How varied the model's answers are.`),efforts:J.efforts.describe(`Effort names a turn may pick, each mapped to a thinking level.`),defaultEffort:J.defaultEffort.describe(`The effort used when a turn picks none.`),allowEffortSelect:J.allowEffortSelect.describe(`Whether a turn may pick an effort.`),summaries:J.summaries.describe(`Whether the model sends summaries of its thinking.`),builtInTools:J.builtInTools.describe(`Tools the provider runs itself, by the ids it knows them by.`),compaction:J.compaction.describe(`How the conversation is shortened when it grows too long.`),keySlot:Ha.optional().describe(`The slot this model's key is read from, in place of the provider's.`),fallbackKeySlot:Ha.optional().describe(`The slot tried once when the first key is out of quota.`),options:L.optional().describe(`What this model's protocol takes beyond the shared settings.`)}),Wa=Ua,Ga=Ua.pick({protocol:!0,provider:!0,apiId:!0,keySlot:!0,fallbackKeySlot:!0,options:!0}).extend({timeoutMs:x().positive().optional().describe(`How long a decision may take before it fails.`)});function Ka(e,t){let n=t.keySlot??e.keySlot,r=t.fallbackKeySlot??e.fallbackKeySlot;return{...n===void 0?{}:{keySlot:n},...r===void 0?{}:{fallbackKeySlot:r}}}function qa(e,t){let n=e.serves.find(e=>e.protocol.id===t.protocol);if(!n)throw new T(`config`,O(`protocol.not_served`,{provider:e.id,protocol:t.protocol}));return n}function Ja(e,t){return qa(e,t).protocol}function Ya(e,t,n,r={webSocketHeaders:!0}){let i=qa(e,t),{protocol:a}=i;if(a.endpoints[n]===void 0)throw new T(`unsupported`,O(`protocol.profile_type`,{protocol:a.id,profileType:n}));let o=L.parse(Na(a,t.apiId,t.options)),s=Ka(e,t);if(s.keySlot!==void 0&&s.keySlot===s.fallbackKeySlot)throw new T(`config`,O(`provider.model_fallback_slot`));if((t.keySlot||t.fallbackKeySlot)&&!e.definition.key)throw new T(`config`,O(`protocol.no_key`,{provider:e.id}));let c=i.authorize??e.definition.authorize;if(n===`live`&&c?.webSocketHeaders&&!r.webSocketHeaders)throw new T(`unsupported`,O(`protocol.ws_headers`,{provider:e.id}));return{...t,options:o}}var Xa=[`text`],Za=Gn,Qa=[`length`,`stream_incomplete`],$a=new Set([`egress`,`canary`,`prompt_echo`,`provider_tool_leak`]);function eo(e){return e.kind===`filtered`&&$a.has(e.native??``)}var to=1500,no=new Set(Gn);function ro(e){return no.has(e)}new Set(Za);var io=new Set([`provider_error`,`stream_incomplete`]);function ao(e){return io.has(e)}function oo(e){return typeof e==`object`&&e.reason?{kind:`cancelled`,native:e.reason}:{kind:`cancelled`}}function so(e,t){return!e||!ro(e.kind)?!1:(t?.autoContinue??Qa).includes(e.kind)}function co(e){if(e.type!==`live`)return e.turnBehaviour?.resumption}function lo(e){return e.type===`text`&&e.turnBehaviour?.allowSteering!==!1}function uo(e){return e.type===`text`||e.type===`live`?e.turnBehaviour?.allowSteering!==!1:!1}function fo(e,t){let n=t?.trim()||e?.trim()||void 0,r=(t||e||``).toLowerCase();return r?r===`network_error`||r.includes(`network`)?{kind:`provider_error`,native:n}:po((e||``).toLowerCase(),r,n):{kind:`stream_incomplete`,native:n}}function po(e,t,n){return e===`stop`?/error|fail/.test(t)?{kind:`provider_error`,native:n}:{kind:`completed`,native:n}:e===`length`?{kind:`length`,native:n}:e===`tool_calls`||e===`tool-calls`?{kind:`tool`,native:n}:e===`content_filter`||e===`content-filter`?{kind:`filtered`,native:n}:{kind:`provider_error`,native:n}}function mo(e){let t=(e||``).toLowerCase(),n=e||void 0;switch(t){case`completed`:return{kind:`completed`,native:n};case`incomplete`:case`budget_exceeded`:return{kind:`length`,native:n};case`requires_action`:return{kind:`tool`,native:n};case`cancelled`:return{kind:`cancelled`,native:n};case`failed`:return{kind:`provider_error`,native:n};case`in_progress`:case`queued`:return{kind:`stream_incomplete`,native:n};default:return{kind:`stream_incomplete`,native:n}}}function ho(e,t){for(let n=e.length-1;n>=0;--n){let r=e[n];if(r!==void 0&&t(r))return r}}function Y(e){return M(e)?e:void 0}function X(e){if(typeof e==`string`&&e.trim())return e}function Z(e){return typeof e==`number`&&Number.isFinite(e)&&e>=0?e:void 0}function go(e){let t=e.input?e.input:void 0;if(t===void 0&&!e.output)return;let n=[];t===void 0&&n.push(`input`),e.output===void 0&&n.push(`output`);let r=t??0,i=e.output??0;return{input:r,output:i,...e.thinking?{thinking:e.thinking}:{},...e.toolUse?{toolUse:e.toolUse}:{},...e.cached?{cached:e.cached}:{},...e.cacheWrite?{cacheWrite:e.cacheWrite}:{},total:r+i,...e.cost?{cost:e.cost}:{},...n.length>0?{estimated:n}:{},...e.byModality?{byModality:e.byModality}:{},...e.grounding?{grounding:e.grounding}:{}}}function _o(e){let t=e.flatMap(e=>e.cost?[e.cost]:[]);if(t.length===0)return;let n=t.flatMap(e=>e.upstreamUsd===void 0?[]:[e.upstreamUsd]),r=t.length<e.length||t.some(e=>e.partial);return{usd:t.reduce((e,t)=>e+t.usd,0),...n.length>0?{upstreamUsd:n.reduce((e,t)=>e+t,0)}:{},...r?{partial:!0}:{}}}function vo(e){let t=[`input`,`output`],n={};for(let r of t){let[t,...i]=e.map(e=>e.byModality?.[r]),a=Object.keys(t??{}).filter(e=>i.every(t=>t?.[e]!==void 0));a.length!==0&&(n[r]=Object.fromEntries(a.map(t=>[t,e.reduce((e,n)=>e+(n.byModality?.[r]?.[t]??0),0)])))}return Object.keys(n).length>0?n:void 0}function yo(e){let t=new Map;for(let n of e.flatMap(e=>e.grounding??[]))t.set(n.type,[...t.get(n.type)??[],n]);if(t.size!==0)return[...t].map(([e,t])=>{let n=t.every(e=>e.searchQueryCount!==void 0);return{type:e,count:t.reduce((e,t)=>e+t.count,0),...n?{searchQueryCount:t.reduce((e,t)=>e+(t.searchQueryCount??0),0)}:{}}})}function bo(e){return So(e.flatMap(e=>e.type===`tokens`?[e.tokens]:[]))}function xo(e){return So(e.flatMap(e=>{if(e.type===`tokens`)return[e.tokens];if(e.type!==`tool`)return[];let{tool:t}=e;return(t.phase===`complete`||t.phase===`error`)&&t.tokens?[t.tokens]:[]}))}function So(e){if(e.length===0)return;let t=t=>e.reduce((e,n)=>e+(t(n)??0),0),n=t(e=>e.input),r=t(e=>e.output),i=t(e=>e.thinking),a=t(e=>e.toolUse),o=t(e=>e.cached),s=t(e=>e.cacheWrite),c=_o(e),l=vo(e),u=yo(e),d=[`input`,`output`],f=d.filter(t=>e.some(e=>e.estimated?.includes(t))),p={};for(let e of d){let n=t(t=>t.unknownMedia?.[e]);n>0&&(p[e]=n)}return{input:n,output:r,...i?{thinking:i}:{},...a?{toolUse:a}:{},...o?{cached:o}:{},...s?{cacheWrite:s}:{},total:n+r,...c?{cost:c}:{},...f.length>0?{estimated:f}:{},...Object.keys(p).length>0?{unknownMedia:p}:{},...l?{byModality:l}:{},...u?{grounding:u}:{}}}var Co=1e3,wo=400,To=new Set([`http_request`,`http_response`,`http_error_body`,`http_throw`]),Eo=new Set([`text`,`image`,`audio`]),Do={completed:`stop`,length:`length`,tool:`tool_call`,filtered:`content_filter`,provider_error:`error`};function Oo(e){let[t]=e.split(`/`);return t===`application`||t===`text`||!t?`document`:t}function ko(e){return e.type===`text`?{type:`text`,...E(e.text)}:`uri`in e?{type:`uri`,modality:e.type,mime_type:e.mimeType,uri:e.uri}:{type:`blob`,modality:e.type,mime_type:e.mimeType,...Be(e.data)}}function Ao(e){let t=K(e).map(ko);if(e.role===`tool`)return{role:`tool`,parts:[{type:`tool_call_response`,...e.tool_call_id?{id:e.tool_call_id}:{},response:E(e.content??``)},...(e.parts??[]).map(ko)]};let n=(e.tool_calls??[]).map(e=>({type:`tool_call`,id:e.id,name:e.function.name,arguments:E(e.function.arguments)}));return{role:e.role,parts:[...t,...n]}}var jo=new WeakMap;function Mo(e){let{conversation:t}=e;if(`previous`in t){let e=jo.get(t.previous),n=[...e?.input??[],...e?.output?[e.output]:[]];return{input:[...n,...t.continuation.map(Ao)],sentFrom:n.length}}let n=t.input.length>0?[{role:`user`,parts:t.input.map(ko)}]:[];return{input:[...t.history.map(Ao),...n]}}var No=class{parts=[];open;calls=new Map;add(e,t){switch(e.type){case`text`:this.appendText(`text`,e.text);return;case`thought`:this.appendText(`reasoning`,e.text);return;case`tool`:this.addTool(e.tool);return;case`structured`:this.push({type:`structured`,content:k(e.structured??null)});return;case`media`:this.push(Lo(e.media));return;case`evidence`:{let{evidence:n}=e;if(n.kind===`input_transcription`||n.kind===`output_transcription`){this.appendText(`text`,e.text??``,n.kind,n.interim);return}let r=Vo(n,t);r&&this.push(r);return}case`tool_draft`:case`structured_draft`:return;default:return}}appendText(e,t,n,r){if(!t)return;let i=`${e}:${n??``}:${r?`interim`:``}`;if(this.open?.key===i){this.open.text+=t,Object.assign(this.open.part,E(this.open.text));return}let a={type:e,...E(t),...Q(`theorem.source`,n),...r?{"theorem.interim":!0}:{}};this.parts.push(a),this.open={key:i,text:t,part:a}}addTool(e){if(e.phase===void 0){let t=Io(e);this.calls.set(e.callId,t),this.push(t);return}let t=this.calls.get(e.callId),n=e.phase===`error`?Po(e.failure):void 0;t&&n!==void 0&&Object.assign(t,{arguments:E(n)})}push(e){this.parts.push(e),this.open=void 0}};function Po(e){let t=Y(e?.details)?.raw;return typeof t==`string`?t:void 0}function Fo(e){return Po(e.failure)??JSON.stringify(e.arguments)}function Io(e){return{type:`tool_call`,id:e.callId,name:e.name,arguments:E(Fo(e))}}function Lo(e){return{type:`blob`,modality:Oo(e.mimeType),mime_type:e.mimeType,...Be(e.data)}}var Ro=`_call`,zo=`_result`;function Bo(e){switch(e.kind){case`code_execution_call`:return{side:`call`,name:`code_execution`,id:e.id};case`code_execution_result`:return{side:`result`,name:`code_execution`,id:e.callId};case`provider_step`:{let{step:t,raw:n}=e;if(t.endsWith(Ro)){let e=typeof n?.id==`string`?n.id:void 0;return{side:`call`,name:t.slice(0,-5),id:e}}if(t.endsWith(zo)){let e=typeof n?.call_id==`string`?n.call_id:void 0;return{side:`result`,name:t.slice(0,-7),id:e}}return}default:return}}function Vo(e,t){let n=Bo(e);if(!n)return;let r={"theorem.observed_end":t,...e.partial?{"theorem.partial":!0}:{}},i={...k(e.raw??{}),type:n.name};return n.side===`call`?{type:`server_tool_call`,...Q(`id`,n.id),name:n.name,server_tool_call:i,...r}:{type:`server_tool_call_response`,...Q(`id`,n.id),server_tool_call_response:i,...r}}function Ho(e){switch(e.type){case`grounding`:{let{searchHtml:t,metadata:n,chunks:r}=e.grounding;return!t&&!n&&!r?void 0:{...t?{search_html:E(t)}:{},...n||r?{raw:k({metadata:n,chunks:r})}:{}}}case`citation`:return{sources:k(e.sources)};case`evidence`:{let{evidence:t}=e;return Bo(t)||t.kind===`input_transcription`||t.kind===`output_transcription`?void 0:{provider:t.provider,...t.raw?{raw:k(t.raw)}:{}}}default:return}}function Uo(e){return{stage:e.stage,trust:e.trust,action:e.action,hits:e.hits.map(e=>({rule:e.rule,severity:e.severity,...e.span?{start:e.span.start,end:e.span.end}:{},...Q(`match`,e.match),...Q(`label`,e.label),...Q(`doc`,e.doc)})),...e.provenance?{provenance:{...e.provenance}}:{},...e.errorInternal?{error:E(e.errorInternal)}:{}}}var Wo={output_stream:`output_delta`,stream_canary:`output_delta`,tool_draft:`tool_call`,live_output:`live_outbound`};function Go(e,t,n,r){return{...n?Uo(n):{stage:r.stage,trust:r.trust,action:`allow`,hits:[]},check:e,duration_ms:t}}function Ko(e){let t={};for(let n of[`input`,`output`])for(let[r,i]of Object.entries(e?.[n]??{})){let e=Eo.has(r)?`gen_ai`:`theorem`;t[`${e}.usage.${r}.${n}_tokens`]=i}return t}function Q(e,t){return t===void 0?{}:{[e]:t}}function qo(e){return{"gen_ai.usage.input_tokens":e.input,"gen_ai.usage.output_tokens":e.output,...Q(`gen_ai.usage.reasoning.output_tokens`,e.thinking),...Q(`gen_ai.usage.cache_read.input_tokens`,e.cached),...Q(`gen_ai.usage.cache_write.input_tokens`,e.cacheWrite),...Q(`theorem.usage.tool_use.input_tokens`,e.toolUse),...Ko(e.byModality),...e.grounding?{"theorem.usage.grounding":e.grounding.map(e=>({type:e.type,count:e.count,...Q(`search_query_count`,e.searchQueryCount)}))}:{},...Q(`theorem.usage.cost_usd`,e.cost?.usd),...Q(`theorem.usage.upstream_cost_usd`,e.cost?.upstreamUsd),...e.cost?.partial?{"theorem.usage.cost_partial":!0}:{},...e.estimated?.length?{"theorem.usage.estimated":[...e.estimated]}:{},...e.unknownMedia?{"theorem.usage.unknown_media":{...e.unknownMedia}}:{}}}function Jo(e){return e===`turn`?`chat`:`generate_content`}function Yo(e){if(e)return e.provider}function Xo(e,t){return t===`live`?`speech`:e.structured?`json`:e.image?`image`:e.speech?`speech`:`text`}function Zo(e,t,n){let r=Yo(t);return{"gen_ai.operation.name":Jo(n),...Q(`gen_ai.provider.name`,r),"gen_ai.request.model":e.apiId,"theorem.model.id":e.model,...Q(`theorem.key_slot`,t?.keySlot),...Q(`gen_ai.request.temperature`,e.temperature),...Q(`gen_ai.request.max_tokens`,e.maxOutputTokens),...Q(`gen_ai.request.reasoning.level`,e.thinking),"gen_ai.system_instructions":[{type:`text`,...E(e.system)}],...e.wireTools?.length?{"gen_ai.tool.definitions":E(JSON.stringify(e.wireTools))}:{},"gen_ai.output.type":Xo(e,n),...Qo(e)}}function Qo(e){let{image:t,speech:n,live:r}=e;return{"theorem.request.builtins":e.builtins.map(e=>e.id),...Q(`theorem.request.summaries`,e.summaries),...Q(`theorem.request.structured`,e.structured?.id),...Q(`theorem.request.session_id`,e.sessionId),...t?{"theorem.request.image":{...Q(`mime_type`,t.mimeType),...Q(`aspect_ratio`,t.aspectRatio),...Q(`resolution`,t.resolution),...Q(`quality`,t.quality),...Q(`background`,t.background),...Q(`n`,t.n),...Q(`seed`,t.seed),...Q(`output_compression`,t.outputCompression),include_text:t.includeText}}:{},...n?{"theorem.request.speech":{...Q(`voice`,n.voice),...Q(`speed`,n.speed),...Q(`format`,n.format)}}:{},...r?{"theorem.request.live":$o(r,e)}:{}}}function $o(e,t){let{vad:n,transcription:r}=e;return{...Q(`voice`,e.voice),...n?{vad:{...Q(`activity_handling`,n.activityHandling),...Q(`start_sensitivity`,n.startSensitivity),...Q(`end_sensitivity`,n.endSensitivity),...Q(`prefix_padding_ms`,n.prefixPaddingMs),...Q(`silence_duration_ms`,n.silenceDurationMs)}}:{},...Q(`session_resumption`,e.sessionResumption),...e.contextCompression?{context_compression:{mechanism:`sliding_window`,...Q(`trigger_tokens`,e.contextCompression.triggerTokens),...Q(`target_tokens`,e.contextCompression.slidingWindow.targetTokens)}}:{},...r?{transcription:{...Q(`input`,r.input),...Q(`output`,r.output)}}:{},resumed:!!t.providerState}}function es(e,t){return!t||typeof t!=`object`?{}:Object.fromEntries(Object.entries(t).map(([t,n])=>[`${e}.${t}`,[String(n)]]))}function ts(e){if(typeof e!=`string`)return{};let t=URL.canParse(e)?new URL(e):void 0;return t?{"server.address":t.hostname,"url.path":t.pathname}:{}}var ns=class{call;tries=0;current;last;lastStatus;awaitingFirstChunk=!1;streamed=!1;constructor(e){this.call=e}row(e){let t=typeof e.eventType==`string`?e.eventType:void 0;return!t||!To.has(t)?(this.firstChunk(),!1):(t===`http_request`?this.open(e):t===`http_response`?this.response(e):t===`http_error_body`?this.errorBody(e):this.thrown(e),!0)}open(e){this.current?.end();let t=this.last?.msSinceEnd();this.current=this.call.child(String(e.method??`GET`),{kind:`CLIENT`,attributes:{"http.request.method":String(e.method??`GET`),...ts(e.url),"http.request.resend_count":this.tries,...typeof e.keySlot==`string`?{"theorem.key_slot":e.keySlot}:{},...Q(`theorem.retry.backoff_ms`,t),...es(`http.request.header`,e.headers)}}),this.tries+=1,this.streamed=Y(e.body)?.stream===!0,this.streamed&&this.call.set({"gen_ai.request.stream":!0}),`body`in e?this.current.event(`theorem.wire.request`,{body:k(e.body)}):typeof e.bodyKind==`string`&&this.current.event(`theorem.wire.request`,{body_kind:e.bodyKind}),typeof e.keySlot==`string`&&this.call.set({"theorem.key_slot":e.keySlot})}response(e){let t=typeof e.status==`number`?e.status:void 0;this.lastStatus=t,this.current?.set({...Q(`http.response.status_code`,t),...es(`http.response.header`,e.headers)}),t!==void 0&&t>=wo?this.current?.set({"error.type":String(t)}):this.awaitingFirstChunk=!0}errorBody(e){this.current?.event(`theorem.upstream.row`,{row:k(e)}),this.close({code:`ERROR`,message:String(this.lastStatus??`error`)})}thrown(e){let t=typeof e.name==`string`?e.name:`Error`;this.current?.event(`exception`,{"exception.type":t,"exception.message":E(String(e.message??``))}),this.current?.set({"error.type":t}),this.close({code:`ERROR`,message:t})}firstChunk(){this.awaitingFirstChunk&&this.current&&(this.awaitingFirstChunk=!1,this.call.set({"gen_ai.response.time_to_first_chunk":this.current.msSinceStart()/Co}))}close(e){this.current&&=(this.current.end(e),this.last=this.current,void 0)}};function rs(e,t,n){return e!==void 0&&e>=wo?{code:`ERROR`,message:String(e)}:n===void 0?t?{code:`UNSET`}:{code:`OK`}:{code:`ERROR`,message:F(n)}}function is(e){return e instanceof Error?e.name:`Error`}function as(e,t){e.event(`exception`,{"exception.type":is(t),"exception.message":E(t instanceof Error?t.message:String(t)),...t instanceof Error&&t.stack?{"exception.stacktrace":E(t.stack)}:{}})}function os(e,t){as(e,t);let n=F(t);e.set({"error.type":n}),e.end({code:`ERROR`,message:n})}function ss(e,t){for(let[n,r]of t)r.decided||e.event(`theorem.guardrail`,{...Go(n,r.ms,void 0,{stage:Wo[n],trust:`untrusted`}),runs:r.runs})}function cs(e){let t=0;for(let n of e.values())t+=n.ms;return t>0?{"theorem.guardrail.stream_ms":t}:{}}var ls=new Set([`cancelled`,`interrupted`]);function us(e,t){let n=e!==void 0&&ls.has(e.kind),r=e&&!n?Do[e.kind]??e.kind:void 0;return t?{stopped:n,finish:r,status:{code:`ERROR`,message:t},attributes:{"error.type":t}}:{stopped:n,finish:r,status:{code:n?`UNSET`:`OK`},attributes:{}}}function ds(e,t,n){let r=t?n===`turn`?{"gen_ai.response.finish_reasons":[t]}:{"gen_ai.response.status":t}:{};return{...Q(`gen_ai.response.id`,e?.id||void 0),...Q(`gen_ai.response.model`,e?.model||void 0),...r}}function fs(e,t){let{req:n,usage:r,transport:i}=t,a=Mo(r),o=e(`${Jo(i)} ${n.apiId}`,{kind:`CLIENT`,attributes:{...Zo(n,t.binding,i),"gen_ai.input.messages":a.input,...Q(`theorem.input.sent_from`,a.sentFrom),"theorem.step":t.step,...Q(`theorem.attempt`,t.attempt)}}),s=new ns(o),c=new No,l=new No,u=[],d,f,p=!1,m=new Map,h;return{span:o,tap:e=>{s.row(e)||o.event(`theorem.upstream.row`,{row:k(e)})},observe:e=>{if(e.type===`evidence`&&e.evidence.kind===`input_transcription`){l.add(e,o.nowUnixNano());return}c.add(e,o.nowUnixNano()),e.type===`text`&&!p&&(p=!0,o.set({"theorem.response.time_to_first_text":o.msSinceStart()/Co}));let t=Ho(e);t&&o.event(`theorem.grounding`,t),e.type===`error`&&u.push(e),e.type===`response`&&(d=e.response),e.type===`done`&&(f=e.stop.native??f)},guardrail:e=>{let t=h?m.get(h):void 0;!(h&&t)||t.decided?o.event(`theorem.guardrail`,Uo(e)):(t.decided=!0,o.event(`theorem.guardrail`,{...Go(h,t.ms,e,{stage:Wo[h],trust:`untrusted`}),runs:t.runs}))},guardTime:(e,t)=>{let n=m.get(e)??{ms:0,runs:0,decided:!1};n.ms+=t,n.runs+=1,m.set(e,n),h=e},end:e=>{for(let e of u)o.event(`exception`,{"exception.type":e.errorKind,"exception.message":E(e.errorInternal??e.error??``)});e.thrown!==void 0&&as(o,e.thrown),ss(o,m);let t=u.at(-1),n=e.thrown===void 0?t?.errorKind:F(e.thrown),a=us(e.stop,n),p={role:`assistant`,parts:c.parts,...Q(`finish_reason`,a.finish)},{input:h}=Mo(r);jo.set(r,{input:h,output:p});let ee=l.parts.length>0?[{role:`user`,parts:l.parts}]:[];s.close(rs(s.lastStatus,a.stopped,e.thrown)),o.set({"gen_ai.input.messages":[...h,...ee],"gen_ai.output.messages":[p],...e.tokens?qo(e.tokens):{},...ds(d,a.stopped?void 0:f,i),...Q(`theorem.stop.kind`,e.stop?.kind),...cs(m),...a.attributes}),o.end(a.status)}}}function ps(e){let t=[...e?.attachments??[],...e?.voice??[]].map(e=>`uri`in e?{type:`uri`,modality:Oo(e.mimeType),mime_type:e.mimeType,uri:e.uri}:{type:`blob`,modality:Oo(e.mimeType),mime_type:e.mimeType,...Be(e.data)}),n=[...e?.text?[{type:`text`,...E(e.text)}]:[],...t];return n.length>0?[{role:`user`,parts:n}]:[]}function ms(e){return(e??[]).map(e=>({traceparent:e.traceparent,attributes:{"theorem.link.kind":e.kind,...Q(`theorem.stop.kind`,e.stop)}}))}function hs(e){return{kind:`INTERNAL`,attributes:{"gen_ai.operation.name":`invoke_agent`,"gen_ai.agent.name":e.profile,...Q(`gen_ai.conversation.id`,e.conversationId),"gen_ai.input.messages":ps(e.input),...Q(`theorem.request.effort`,e.effort),...Q(`theorem.request.model_select`,e.model),...Q(`theorem.project.id`,e.projectId)},links:ms(e.links)}}var gs=new Set([`completed`,`length`,`generation_complete`]);function _s(e,t){let n=bo(t.seen),r=ho(t.seen,e=>e.type===`done`),i=r?.stop.kind,a=ho(t.seen,e=>e.type===`error`),o=a?.error,s=t.thrown!==void 0;s&&as(e,t.thrown);let c=s||i!==void 0&&ao(i),l=s?F(t.thrown):a?.errorKind??i,u={role:`assistant`,parts:t.delivered.parts,...Q(`finish_reason`,us(r?.stop,void 0).finish)};e.set({"gen_ai.output.messages":[u],...n?qo(n):{},...i?{"theorem.stop.kind":i}:{},"theorem.attempts":t.attempts,"theorem.steps":t.calls,...t.seen.some(e=>e.type===`compaction`&&e.outcome===`compacted`)?{"gen_ai.conversation.compacted":!0}:{},...c&&o?{"theorem.error.public":E(o)}:{},...c&&l?{"error.type":l}:{}}),c?e.end({code:`ERROR`,...l?{message:l}:{}}):e.end(i&&!gs.has(i)?{code:`UNSET`}:{code:`OK`})}var vs=w({kind:v(`auth_scope_refused`),slot:S(),requested:y(S()),declared:y(S())}),ys={tool_arguments:`tool_call`,taint:`tool_call`,destination:`tool_call`,tool_result:`tool_result`,tool_failure:`tool_result`,network:`network`,network_request:`network`},bs=new WeakSet;function xs(e,t,n,r){e&&(r&&bs.add(r),e.event(`theorem.guardrail`,Go(t,n,r,{stage:ys[t],trust:`untrusted`})))}function Ss(e){return e?`execute_tool ${e}`:`execute_tool`}function Cs(e){return{"gen_ai.operation.name":`execute_tool`,"gen_ai.tool.name":e.name,"gen_ai.tool.call.id":e.callId,"gen_ai.tool.type":`function`,"gen_ai.tool.call.arguments":E(Fo(e.call)),...Q(`theorem.tool.origin`,e.origin),...Q(`theorem.tool.permission`,e.permission),...Q(`theorem.tool.approved`,e.approved),...Q(`theorem.step`,e.step)}}function ws(e){let t=e.kind===`auth`?e.authChallenge:void 0;return{kind:e.kind,...Q(`permission`,e.permission),...e.summary?{summary:E(e.summary)}:{},...t?{auth:{slot:t.slot,type:t.authType,service:t.service,...Q(`issuer`,t.issuer),...Q(`resource`,t.resource),...Q(`required_scopes`,t.requiredScopes)}}:{}}}var Ts={ok:`OK`,error:`ERROR`,denied:`UNSET`,gated:`UNSET`,paused:`UNSET`,cancelled:`UNSET`};function Es(e,t){let n=e(Ss(t.name),Cs(t));return{span:n,observe:e=>{if(e.type===`guardrail`&&!bs.has(e.guardrail)&&n.event(`theorem.guardrail`,Uo(e.guardrail)),e.type===`tool`&&e.tool.phase===`gate`&&n.event(`theorem.gate`,ws(e.tool.gate)),e.type===`tool`&&e.tool.phase===`progress`){let t=vs.safeParse(e.tool.data);if(t.success){let{slot:e,requested:r,declared:i}=t.data;n.event(`theorem.auth.scope_refused`,{slot:e,requested:r,declared:i})}}if(e.type===`tool`&&e.tool.phase===`warning`){let{code:t,message:r,severity:i}=e.tool.warning;n.event(`theorem.tool.warning`,{code:t,message:E(r),...Q(`severity`,i)})}e.type===`citation`&&n.event(`theorem.grounding`,{sources:k(e.sources)})},end:e=>{e.thrown!==void 0&&as(n,e.thrown);let t=e.outcome===`error`?e.failure?.kind??(e.thrown===void 0?void 0:F(e.thrown)):void 0;n.set({...e.result?{"gen_ai.tool.call.result":E(e.result.text)}:{},...e.result?.parts?.length?{"theorem.tool.call.result.parts":e.result.parts.map(ko)}:{},...e.data?{"theorem.tool.data":k(e.data.value)}:{},"theorem.tool.outcome":e.outcome,...Q(`theorem.tool.failure.code`,e.failure?.code),...Q(`error.type`,t)});let r=Ts[e.outcome];n.end(r===`ERROR`&&t?{code:r,message:t}:{code:r})}}}var Ds=/\{\{?([^{}]*)\}\}?/g,Os=/[\p{Cc}\p{Cf}]/gu,ks=/^-?\d+$/,As=/^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)?$/,js=new Intl.NumberFormat(void 0,{maximumFractionDigits:2}),Ms=new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeZone:`UTC`}),Ns=new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeStyle:`short`,timeZone:`UTC`}),Ps=/^\+\s+/,Fs=/:(?:\s|$)/,Is=/^(\S+) is (?:(not) )?(\S.*)$/;function Ls(e){let t=e.indexOf(`|`);return t<0?{path:e.trim()}:{path:e.slice(0,t).trim(),fallback:e.slice(t+1).trim()}}function Rs(e,t){let n=e.split(`.`),[r,...i]=n;return(r===`input`||r===`output`)&&i.length?[{side:r,keys:i,prefixed:!0}]:t.map(e=>({side:e,keys:n,prefixed:!1}))}function zs(e,t){let n=e;for(let e of t)if(Array.isArray(n)){if(e===`length`)n=n.length;else if(ks.test(e))n=n.at(Number(e));else return}else if(M(n)&&Object.hasOwn(n,e))n=n[e];else return;return n}function Bs(e){let t=As.exec(e);if(!t)return;let[n=0,r=0,i=0,a=0,o=0]=t.slice(1).map(e=>Number(e??0)),s=new Date(Date.UTC(n,r-1,i,a,o));if(!(Number.isNaN(s.getTime())||s.getUTCDate()!==i))return(t[4]===void 0?Ms:Ns).format(s)}function Vs(e){if(typeof e==`number`)return Number.isFinite(e)?js.format(e):void 0;if(typeof e!=`string`)return;let t=e.replace(Os,` `).replace(/\s+/g,` `).trim();return(Bs(t)??t)||void 0}function Hs(e){let t=[];for(let n of e.replace(/\s+/g,` `).split(` and `)){let[,e,r,i]=Is.exec(n.trim())??[];if(!e||!i)return`unreadable`;let a=i.trim();t.push({path:e,negated:!!r,expected:a===`null`?null:a})}return t}function Us(e){let t=Ps.test(e),n=e.replace(Ps,``).trim();if(!/^when(\s|$)/.test(n))return{joined:t,when:[],text:n};let r=n.search(Fs);return r<0?{joined:t,when:`unreadable`,text:``}:{joined:t,when:Hs(n.slice(4,r)),text:n.slice(r+1).trim()}}function Ws(e){let t=typeof e==`string`?[e]:e,n=[];return t.forEach((e,t)=>{let r=Us(e),i=n.at(-1);r.joined&&i?.joined?i.lines.push({line:r,number:t+1}):n.push({joined:r.joined,lines:[{line:r,number:t+1}]})}),n}function Gs(e){let[t]=Rs(e,[`input`]);return t?.side===`input`?t.keys:void 0}function Ks(e,t){let n=Gs(e.path);if(!n)return!1;let r=zs(t,n),i=typeof r==`string`||typeof r==`number`||typeof r==`boolean`;return(e.expected===null?r===null:i&&`${r}`===e.expected)!==e.negated}function qs(e){return e.length<=1?e[0]??``:`${e.slice(0,-1).join(`, `)}${e.length>2?`,`:``} and ${e.at(-1)}`}function Js(e){return e.replace(/([a-z\d])([A-Z])/g,`$1 $2`).replace(/[_-]+/g,` `).trim().toLowerCase()}function Ys(e,t,n){let r=!1,i=e.replace(Ds,(e,i)=>{let{path:a,fallback:o}=Ls(i),s=a?Rs(a,n).map(e=>Vs(zs(t[e.side],e.keys))).find(e=>e!==void 0):void 0;return s===void 0&&o===void 0&&(r=!0),s??o??``}).replace(/\s+/g,` `).trim();return r||!i?void 0:i}function Xs(e,t){if(e===void 0)return;let n=`output`in t?[`input`,`output`]:[`input`];for(let r of Ws(e)){let e=r.lines.flatMap(({line:e})=>{if(e.when===`unreadable`||!e.when.every(e=>Ks(e,t.input)))return[];let r=Ys(e.text,t,n);return r===void 0?[]:[r]});if(e.length)return qs(e)}}var Zs=[`value`,`group`,`flag`,`missing`];function Qs(e){return(Array.isArray(e.type)?e.type:[e.type]).filter(e=>typeof e==`string`&&e!==`null`)}function $s(e){return[e.anyOf,e.oneOf,e.allOf].flatMap(e=>Array.isArray(e)?e.filter(M):[])}function ec(e){let t=Zs.find(t=>e.some(e=>e.holds===t))??`missing`;return{holds:t,instead:e.filter(e=>e.holds===t).flatMap(e=>e.instead??[])}}function tc(e,t){let n=e=>t?`${t}.${e}`:e;if(!M(e))return[];let r=$s(e);return r.length?r.flatMap(e=>tc(e,t)):Qs(e).includes(`array`)?[...nc(e.items,n(`0`)),n(`length`)]:M(e.properties)?Object.entries(e.properties).flatMap(([e,t])=>nc(t,n(e))):[]}function nc(e,t){if(!M(e)||`$ref`in e)return[t];let n=Qs(e);if(n.length&&n.every(e=>e===`boolean`))return[];let r=$s(e),i=r.some(e=>Qs(e).some(e=>e===`array`||e===`object`)),a=n.includes(`array`)||n.includes(`object`)||i;return!a&&r.length?r.every(e=>Qs(e).every(e=>e===`boolean`))?[]:[t]:a?tc(e,t):[t]}function rc(e,t,n){if(!M(e)||`$ref`in e)return{holds:`value`};let r=$s(e);if(r.length)return ec(r.map(e=>rc(e,t,n)));let i=Qs(e),[a,...o]=t;if(a===void 0)return i.length&&i.every(e=>e===`boolean`)?{holds:`flag`}:i.includes(`array`)||i.includes(`object`)?{holds:`group`,instead:tc(e,n)}:{holds:`value`};let s=n?`${n}.${a}`:a,c={holds:`missing`,instead:tc(e,n)};if(i.includes(`array`)){if(a===`length`)return o.length?c:{holds:`value`};if(ks.test(a))return M(e.items)?rc(e.items,o,s):{holds:`value`}}return M(e.properties)?Object.hasOwn(e.properties,a)?rc(e.properties[a],o,s):c:i.length===0||i.includes(`object`)?{holds:`value`}:c}function ic(e){let t=[...new Set(e)].slice(0,4).map(e=>`{${e}}`);return t.length===0?``:` Try ${t.length===1?t[0]:`${t.slice(0,-1).join(`, `)}${t.length>2?`,`:``} or ${t.at(-1)}`}.`}function ac(e,t,n){for(let r of e.matchAll(Ds)){let{path:e}=Ls(r[1]??``);if(!e)return`Put a field name between the braces, like {${tc(t.input,``)[0]??`name`}}.`;let i=Rs(e,n),[a]=i;if(!a)continue;if(a.prefixed&&!n.includes(a.side))return`{${e}} is only there once the call is done; use it in the Done label.`;let o=ec(i.map(({side:e,keys:n,prefixed:r})=>rc(t[e],n,r?e:``)));if(o.holds===`value`)continue;let s=o.instead??[],c=+!!a.prefixed,l=s.filter(e=>e.split(`.`)[c]===a.keys[0]),u={missing:`is not a field of this tool's ${a.prefixed?a.side:n.join(` or `)}.`,group:`is a list or group; a label shows text or a number.`,flag:`is true or false; a label shows text or a number.`}[o.holds],d=a.keys.at(-1),f=e=>e.split(`.`).at(-1)===d?0:1;return`{${e}} ${u}${ic([...l.length?l:s].sort((e,t)=>f(e)-f(t)))}`}}var oc={texts:`any`,nullable:!0};function sc(e){return(Array.isArray(e.type)?e.type:[e.type]).filter(e=>typeof e==`string`)}function cc(e){let t=Array.isArray(e.enum)?e.enum:`const`in e?[e.const]:void 0;if(t)return{texts:t.filter(e=>e!==null).map(e=>`${e}`),nullable:t.includes(null)};let n=sc(e);if(n.length===0)return oc;let r=n.filter(e=>e!==`null`);return{texts:r.every(e=>e===`boolean`)?r.length?[`true`,`false`]:[]:`any`,nullable:n.includes(`null`)}}function lc(e,t){if(!M(e)||`$ref`in e)return[oc];let n=$s(e);if(n.length)return n.flatMap(e=>lc(e,t));let[r,...i]=t;if(r===void 0)return[cc(e)];let a=Qs(e);if(a.includes(`array`)){if(r===`length`)return i.length?[]:[{texts:`any`,nullable:!1}];if(ks.test(r))return lc(e.items,i)}return M(e.properties)?Object.hasOwn(e.properties,r)?lc(e.properties[r],i):[]:a.length===0&&sc(e).length===0?[oc]:[]}function uc(e){if(!M(e))return[];let t=$s(e).flatMap(uc),n=M(e.properties)?Object.keys(e.properties):[];return[...new Set([...n,...t])]}function dc(e){let t=[...new Set(e)].map(e=>`"${e}"`);return t.length<=1?t[0]??``:`${t.slice(0,-1).join(`, `)}${t.length>2?`,`:``} or ${t.at(-1)}`}function fc(e,t){let n=Gs(e.path);if(!n)return`A "when" reads what the model sent; "${e.path}" is only there once the call is done.`;let r=rc(t,n,``);if(r.holds===`missing`){let n=uc(t).slice(0,4),r=n.length?` Try ${dc(n)}.`:``;return`"${e.path}" in the "when" is not a field of this tool's input.${r}`}if(r.holds===`group`)return`"${e.path}" in the "when" is a list or group; a "when" compares text, a number, or true or false.`;let i=lc(t,n);if(e.expected===null)return i.some(e=>e.nullable)?void 0:`"${e.path}" is never null.`;let a=[];for(let e of i){if(e.texts===`any`)return;a.push(...e.texts)}if(a.includes(e.expected))return;let o=a.length?` It is ${dc(a)}.`:``;return`"${e.path}" is never "${e.expected}".${o}`}function pc(e,t,n,r){if(e.when===`unreadable`)return`A line that opens with "when" needs a condition and a colon, like "when status is archived: archiving {name}". A condition uses "is", "is not", "is null", and "and".`;for(let n of e.when){let e=fc(n,t.input);if(e)return e}return!e.text&&(r||e.when.length)?`It has no wording to show.`:ac(e.text,t,n)}function mc(e){if(e.when===`unreadable`||e.when.length)return!1;let t=!1,n=e.text.replace(Ds,(e,n)=>{let{fallback:r}=Ls(n);return r===void 0&&(t=!0),r??``});return!t&&n.trim().length>0}function hc(e){let t=e.map(e=>e.lines.some(({line:e})=>mc(e))),n=t.slice(0,-1).indexOf(!0);if(n>=0)return`Line ${e[n]?.lines.find(({line:e})=>mc(e))?.number} always fits, so the lines below it are never read. Move it to the end.`;if(!t.at(-1))return`The last line must always fit, so every call gets a label: no "when", and a fallback on every {value}, like "saving the item".`}function gc(e,t){let n=`output`in t?[`input`,`output`]:[`input`],r=typeof e!=`string`,i=Ws(e);for(let{line:e,number:a}of i.flatMap(e=>e.lines)){let i=pc(e,t,n,r);if(i)return r?`Line ${a}: ${i}`:i}return r?hc(i):void 0}function _c(e){return e.modelText===void 0?lt(Ii(e.finding,e.data),He):e.modelText}function vc(e){return{finding:`Tool error (${e.code}): ${e.message}`,...e.details===void 0?{}:{data:{details:e.details}}}}function yc(e){return vc({...e,message:lt(e.message,He)})}function bc(e,t){return{type:`tool`,tool:{...t,name:e.name,callId:e.callId,...e.operationId?{operationId:e.operationId}:{},at:Date.now()}}}function xc(e,t,n,r){return Xs(n?.activityFailed,{input:r})??O(`tool.activity_failed`,{tool:Js(e)},t)}function Sc(e){return e.activityFailed??xc(e.name)}function Cc(e,t,n=_c(yc(t))){return bc(e,{phase:`error`,failure:t,readBack:n,activityPast:Sc(e)})}function wc(e,t,{reasoning:n,stepId:r,stepCallCount:i}={}){return{type:`tool`,tool:{name:e.name,callId:e.callId,...e.operationId?{operationId:e.operationId}:{},arguments:t,...n?.length?{reasoning:n}:{},...r?{stepId:r}:{},...i?{stepCallCount:i}:{}}}}function Tc(e){return`call_${e}_${crypto.randomUUID()}`}function Ec(e){return e===void 0?{}:M(e)?e:{value:e}}function Dc(e){return e instanceof Error?e.message:String(e)}function Oc(e,t){return bc(e,{phase:`warning`,warning:{code:`sources_invalid`,message:t,severity:`warning`}})}function*kc(e,t,n){let r;try{r=t(n)}catch(t){yield Oc(e,`sources threw: ${Dc(t)}`);return}if(!Array.isArray(r)){yield Oc(e,`sources must return an array`);return}let i=[],a=[];r.forEach((e,t)=>{let n=zr.safeParse(e);n.success?i.push(n.data):a.push(`[${String(t)}] ${n.error.issues.map(e=>`${e.path.join(`.`)||`source`}: ${e.message}`).join(`; `)}`)}),a.length>0&&(yield Oc(e,`sources not cited: ${a.join(` | `)}`)),i.length>0&&(yield{type:`citation`,sources:i,callId:e.callId})}function Ac(e,t,n,r){let i=n.resume?.edited,a=Xs(e.labels?.activity,{input:t});return bc(r,{phase:`running`,...i?{edited:{from:i.from,to:Ec(t)}}:{},...a?{activity:a}:{}})}async function*jc(e,t,n,r,i){let a=await i?.(t);return Ft(n.signal),yield Ac(e,t,n,r),a}function Mc(e,t,n){Ft(n.signal);let r=e.input.safeParse(t);return r.success?{ok:!0,data:r.data}:{ok:!1,failure:{code:`invalid_input`,kind:`bad_response`,message:O(`tool.input_invalid`,{},n.profile.labels),details:r.error.flatten()}}}function Nc(){return{stage:`network`,trust:`untrusted`,action:`block`,hits:[{rule:ct.blocked,severity:`high`}]}}function*Pc(e,t=Nc()){return yield{type:`guardrail`,guardrail:t},{code:`network_blocked`,kind:`blocked`,message:Dc(e)}}function*Fc(e,t,n){let r=performance.now();try{let i=ga(e,Lc(t));return xs(n,`network`,performance.now()-r,void 0),{ok:!0,url:i}}catch(e){let t=Nc();return xs(n,`network`,performance.now()-r,t),{ok:!1,failure:yield*Pc(e,t)}}}function Ic(e){let t=0,n=!1,r=!1;return{onCheck:e=>{t+=e,n=!0},record:i=>{!r&&n&&(r=!0,xs(e,`network_request`,t,i))}}}function Lc(e){return Qi(e.profile.guardrails).network}function Rc(e,t){return Object.assign(t=>({sign:n=>e(t,n)}),{webSocketHeaders:t})}var zc=S().url().refine(e=>{if(!URL.canParse(e))return!0;let t=new URL(e);return[`http:`,`https:`].includes(t.protocol)&&!t.username&&!t.password&&![...t.searchParams.keys()].some(e=>/key|auth|secret|token|password/i.test(e))},O(`protocol.endpoint_url`));function Bc(){return Rc((e,t)=>t.headers.set(`Authorization`,`Bearer ${e}`),!0)}function Vc(e){return Rc((t,n)=>n.headers.set(e,t),!0)}function Hc(e){return Rc((t,n)=>n.url.searchParams.set(e,t),!1)}var Uc=w({id:S().regex(/^[a-z][a-z0-9-]*$/),name:S().min(1),description:S().min(1),traceName:S().min(1).optional()});function Wc(e){let t=Uc.safeParse(e);if(!t.success||typeof e.serves!=`function`)throw new T(`config`,O(`protocol.definition`,{id:String(e.id),issues:t.success?`serves is required`:Fe(t.error)}));return Object.freeze({...e})}function Gc(e,t){let n=e.serves.find(e=>e.protocol.id===t);if(!n)throw new T(`config`,O(`protocol.not_served`,{provider:e.id,protocol:t}));return n}function Kc(){let e=new Map,t=new Map,n=e=>{let n=[];for(let r=e;r;r=r.base){let e=t.get(r.id);if(e&&e!==r)throw new T(`config`,O(`protocol.id_clash`,{protocol:r.id}));n.push(r)}return n},r=(r,i,a)=>{let o=i.id??r.id;if(!a&&e.has(o))throw new T(`config`,O(`protocol.provider_id_clash`,{provider:o}));let s=r.connection?r.connection.safeParse(i.connection):{success:!0,data:void 0};if(!s.success)throw new T(`config`,O(`protocol.connection`,{provider:o,issues:Fe(s.error)}));if(s.data!==void 0&&an.parse(s.data),i.keySlot!==void 0&&Ha.parse(i.keySlot),i.fallbackKeySlot!==void 0&&Ha.parse(i.fallbackKeySlot),i.keySlot&&i.keySlot===i.fallbackKeySlot)throw new T(`config`,O(`provider.fallback_slot`));if((i.keySlot||i.fallbackKeySlot)&&!r.key)throw new T(`config`,O(`protocol.no_key`,{provider:o}));let c=Object.freeze(r.serves(s.data).map(e=>Object.freeze({...e}))),l=c.flatMap(e=>n(e.protocol)),u=(e,t,n)=>{let{protocol:r}=Gc({id:o,serves:c},typeof e==`string`?e:e.id);return{protocol:r.id,options:Na(r,t,n)}},d=Object.freeze({id:o,definition:r,connection:s.data,...i.keySlot?{keySlot:i.keySlot}:{},...i.fallbackKeySlot?{fallbackKeySlot:i.fallbackKeySlot}:{},serves:c,model(e,t,n={}){let{options:r,...i}=n;return Wa.parse({...i,provider:o,apiId:t,...u(e,t,r)})},decisionModel(e,t,n={}){let{options:r,...i}=n;return Ga.parse({...i,provider:o,apiId:t,...u(e,t,r)})}});for(let e of l)t.set(e.id,e);return e.set(o,d),d};return{register:(e,t={})=>r(e,t,!1),replace:(e,t={})=>r(e,t,!0),get:t=>e.get(t),require(t,n){let r=e.get(t);if(!r)throw new T(`config`,O(`protocol.provider_missing`,{provider:t,apiId:n}));return r},list:()=>[...e.values()],protocols:()=>[...t.values()]}}var qc=[`minimal`,`low`,`medium`,`high`],Jc=[`pcm`],Yc=[`1:1`,`3:2`,`2:3`,`3:4`,`4:3`,`4:5`,`5:4`,`9:16`,`16:9`,`21:9`],Xc=[`1K`,`2K`,`4K`],Zc=[`image/png`,`image/jpeg`],Qc=[{type:`builtin`,name:`googleSearch`,description:`Google Search grounding`,category:`grounding`,access:`read-only`,paths:[`*`],loadTier:`T0`,permission:`auto`},{type:`builtin`,name:`googleMaps`,description:`Google Maps grounding`,category:`grounding`,access:`read-only`,paths:[`*`],loadTier:`T0`,permission:`auto`,conflictsWith:[`googleSearch`,`urlContext`]},{type:`builtin`,name:`urlContext`,description:`Fetch URL context`,category:`grounding`,access:`read-only`,paths:[`*`],loadTier:`T0`,permission:`auto`},{type:`builtin`,name:`codeExecution`,description:`Google code execution`,category:`grounding`,access:`read-only`,paths:[`*`],loadTier:`T0`,permission:`auto`}];function $(e,t,n){return v(e).meta({title:t,description:n})}var $c=i({taskType:g([$(`RETRIEVAL_QUERY`,`Retrieval query`,`Embeddings optimized for general search queries. Pair with Retrieval document for the documents searched.`),$(`RETRIEVAL_DOCUMENT`,`Retrieval document`,`Embeddings optimized for document search, such as indexing articles, books or web pages.`),$(`SEMANTIC_SIMILARITY`,`Semantic similarity`,`Embeddings optimized to assess text similarity, such as for recommendations or duplicate detection.`),$(`CLASSIFICATION`,`Classification`,`Embeddings optimized to classify texts according to preset labels, such as sentiment or spam.`),$(`CLUSTERING`,`Clustering`,`Embeddings optimized to cluster texts based on their similarities.`),$(`QUESTION_ANSWERING`,`Question answering`,`Embeddings for questions, optimized for finding documents that answer them. Pair with Retrieval document.`),$(`FACT_VERIFICATION`,`Fact verification`,`Embeddings for statements to verify, optimized for retrieving evidence that supports or refutes them. Pair with Retrieval document.`),$(`CODE_RETRIEVAL_QUERY`,`Code retrieval query`,`Embeddings optimized for finding code blocks from natural language queries. Pair with Retrieval document for the code.`)]).optional().describe(`What the vectors will be used for, so Google tunes them to it. Only gemini-embedding-001 takes it; later models read the request's task from the text. Absent: no tuning.`),outputDimensionality:g([v(768),v(1536),v(3072)]).optional().describe(`How many numbers each vector holds. A shorter vector is cheaper to store and compare and a little less precise. Absent: the 3072 the model returns.`)}),el=/^(gemini-embedding-001|text-embedding-|embedding-)/,tl={maxInputs:100,media:[{accept:[`image/png`,`image/jpeg`],maxPerInput:6},{accept:[`application/pdf`],maxPerInput:1},{accept:[`audio/mpeg`,`audio/mp3`,`audio/wav`,`audio/x-wav`]},{accept:[`video/mp4`,`video/quicktime`]}]},nl={maxInputs:100,media:[]},rl={query:`RETRIEVAL_QUERY`,document:`RETRIEVAL_DOCUMENT`};function il(e,t){return t===`query`?`task: search result | query: ${e}`:`title: none | text: ${e}`}function al(e,t){let n=typeof e==`string`?[{type:`text`,text:e}]:e.parts,r=n.every(e=>e.type===`text`);return n.map((e,n)=>e.type===`text`?{text:t&&r&&n===0?il(e.text,t):e.text}:e.type===`media`?{inlineData:{mimeType:e.mimeType,data:e.data}}:{fileData:{mimeType:e.mimeType,fileUri:e.uri}})}function ol(e){let t=e.embedding,n=t&&typeof t==`object`?t.values:void 0;return Array.isArray(n)?n.filter(e=>typeof e==`number`):[]}function sl(e,t,n){let r={content:{parts:al(e,n.taskField?void 0:n.task)}},i=n.taskField&&n.task?rl[n.task]:t.taskType;return i&&(r.taskType=i),t.outputDimensionality&&(r.outputDimensionality=t.outputDimensionality),r}var cl=q({id:`geminiEmbedding`,name:`Gemini Embeddings`,description:`Google's embedding API for text and supported media.`,endpoints:{embedding:`/models/{apiId}:embedContent`},options:$c,embeddingLimits:e=>el.test(e)?nl:tl,refusedOptions:e=>el.test(e)?[]:[`taskType`],create(e){return{async embed(t){let n=Na(cl,e.apiId,t.options),r={taskField:el.test(e.apiId),...t.task?{task:t.task}:{}},i=Array.isArray(t.input)?t.input:[t.input],a=i.length===1?sl(i[0],n,r):{requests:i.map(t=>({model:`models/${e.apiId}`,...sl(t,n,r)}))},o=i.length===1?`/models/${encodeURIComponent(e.apiId)}:embedContent`:`/models/${encodeURIComponent(e.apiId)}:batchEmbedContents`,s;for await(let t of e.send(a,{stream:!1,path:o}))s=t;let c=Array.isArray(s?.embeddings)?s.embeddings:s?.embedding?[s.embedding]:[];return{model:e.apiId,embeddings:c.map((e,t)=>({index:t,values:e&&typeof e==`object`?ol({embedding:e}):[],dimensions:e&&typeof e==`object`?ol({embedding:e}).length:0}))}}}}}),ll=i({truncate:_().optional().describe(`What happens to an input longer than the model reads. On, it is cut to fit; off, the call fails. Absent: Ollama cuts it.`),dimensions:x().int().positive().optional().describe(`How many numbers each vector holds, for models that can shorten theirs. Absent: the length the model returns.`)});function ul(e){return(Array.isArray(e)?e:[e]).map(e=>{if(typeof e==`string`)return e;if(e.parts.length!==1||e.parts[0]?.type!==`text`)throw new T(`unsupported`,`The Ollama embedding protocol accepts text only`);return e.parts[0].text})}var dl=q({id:`ollamaEmbedding`,name:`Ollama Embeddings`,description:`Ollama’s local embedding endpoint.`,endpoints:{embedding:`/api/embed`},options:ll,embeddingLimits:()=>({media:[]}),create(e){return{async embed(t){let n=ll.parse(t.options??{}),r=e.send({model:e.apiId,input:ul(t.input),...n.truncate===void 0?{}:{truncate:n.truncate},...n.dimensions===void 0?{}:{dimensions:n.dimensions}},{stream:!1}),i;for await(let e of r)i=e;let a=Array.isArray(i?.embeddings)?i.embeddings:[];return{model:typeof i?.model==`string`?i.model:e.apiId,embeddings:a.map((e,t)=>({index:t,values:Array.isArray(e)?e.filter(e=>typeof e==`number`):[],dimensions:Array.isArray(e)?e.length:0}))}}}}}),fl=i({encodingFormat:b([`float`,`base64`]).optional().describe("How OpenRouter sends each vector back: as a list of numbers (`float`) or packed into a base64 string (`base64`, smaller on the wire). Theorem decodes both to the same numbers. Absent: `float`.")}),pl={media:[{accept:[`image/*`]}]};function ml(e){return typeof e==`string`?e:{content:e.parts.map(e=>e.type===`text`?{type:`text`,text:e.text}:{type:`image_url`,image_url:{url:e.type===`media`?`data:${e.mimeType};base64,${e.data}`:e.uri}})}}function hl(e){if(Array.isArray(e)){if(!e.every(e=>typeof e==`number`&&Number.isFinite(e)))throw Error(`OpenRouter returned an embedding with a non-finite value`);return e}if(typeof e!=`string`)throw Error(`OpenRouter returned an embedding in an unsupported format`);let t=rt(e);if(t.byteLength%Float32Array.BYTES_PER_ELEMENT!==0)throw Error(`OpenRouter returned an invalid base64 embedding length`);return Array.from(new Float32Array(t.buffer,t.byteOffset,t.byteLength/Float32Array.BYTES_PER_ELEMENT))}var gl=q({id:`openRouterEmbedding`,name:`OpenRouter Embeddings`,description:`OpenRouter embedding models, including supported multimodal models.`,endpoints:{embedding:`/embeddings`},options:fl,embeddingLimits:()=>pl,create(e){return{async embed(t){let n=fl.parse(t.options??{}),r=Array.isArray(t.input)?t.input:[t.input],i={model:e.apiId,input:r.length===1&&typeof r[0]==`string`?r[0]:r.map(ml)};n.encodingFormat&&(i.encoding_format=n.encodingFormat);let a;for await(let t of e.send(i,{stream:!1}))a=t;let o=Array.isArray(a?.data)?a.data:[],s=a?.usage&&typeof a.usage==`object`?a.usage:void 0;return{model:typeof a?.model==`string`?a.model:e.apiId,embeddings:o.map((e,t)=>{let n=e&&typeof e==`object`?e:{},r=hl(n.embedding);return{index:typeof n.index==`number`?n.index:t,values:r,dimensions:r.length}}),...typeof s?.prompt_tokens==`number`?{usage:{inputTokens:s.prompt_tokens}}:{}}}}}}),_l=100,vl=599,yl=new Set([`API_KEY_INVALID`]);function bl(e){return Array.isArray(e)&&e.some(e=>{let t=Y(e)?.reason;return typeof t==`string`&&yl.has(t)})}var xl={invalid_request:400,failed_precondition:400,parameter_unknown:400,authentication:401,payment_required:402,permission_denied:403,not_found:404,model_not_found:404,already_exists:409,aborted:409,out_of_range:416,rate_limit_exceeded:429,quota_exceeded:429,too_many_requests:429,api_error:500,unimplemented:501,service_unavailable:503,deadline_exceeded:504,bad_request:400,unauthorized:401,forbidden:403,method_not_allowed:405,request_timeout:408,conflict:409,payload_too_large:413,unprocessable_entity:422,internal_server_error:500,not_implemented:501,bad_gateway:502,gateway_timeout:504},Sl=new Set([`safety`,`recitation`,`language`,`prohibited_content`,`spii`,`blocklist`,`image_safety`,`image_prohibited_content`,`image_recitation`,`image_other`,`content_blocked`]);function Cl(e,t){if(e===`cancelled`)return new T(`cancelled`,t);if(Sl.has(e))return new T(`safety`,t);let n=xl[e];return n===void 0?new T(`bad_response`,t):new T(It(n),t)}function wl(e){let t=Y(e.error);if(!t)return null;let{code:n,message:r,status:i,details:a}=t,o=typeof r!=`string`||r.length===0?`Gemini returned an error.`:typeof i==`string`?`${i}: ${r}`:r;return bl(a)?new T(`auth`,o):typeof n==`number`&&n>=_l&&n<=vl?new T(It(n),o):typeof n==`string`?Cl(n,o):new T(`bad_response`,o)}function Tl(e,t,n){return e?.kind===`auth`?e:new T(It(t),e?.message??n)}var El=i({location:i({latitude:x().min(-90).max(90),longitude:x().min(-180).max(180)})}),Dl=[`googleSearch`,`googleMaps`,`urlContext`,`codeExecution`],Ol={googleSearch:`google_search`,googleMaps:`google_maps`,urlContext:`url_context`,codeExecution:`code_execution`};function kl(e){return e.filter(e=>Dl.includes(e.id))}function Al(e){let t=Dl.find(t=>t===e.id);if(!t)throw new T(`config`,`Builtin '${e.id}' is not a Google tool`);return t}function jl(e){let t=Al(e),n=Ol[t];if(t===`googleMaps`&&e.args){let{location:t}=El.parse(e.args);return{type:n,latitude:t.latitude,longitude:t.longitude}}return{type:n}}function Ml(e){let t=Al(e);if(e.args)throw new T(`unsupported`,`Builtin '${t}' takes no args on Google Live`);return{[t]:{}}}function Nl(e){return{type:`text`,text:`[${e.type}: sent in the next message]`}}function Pl(e){return{type:`text`,text:`Files from ${e.name?`the ${e.name} result`:`a tool result`}:`}}function Fl(e,t){let n=[],r=[],i=()=>{r.length!==0&&(n.push({role:`user`,parts:r}),r=[])};for(let a of e){if(a.role!==`tool`){i(),n.push(a);continue}let e=(a.parts??[]).filter(e=>!t.has(e.type));e.length===0?n.push(a):(n.push({...a,parts:(a.parts??[]).map(e=>t.has(e.type)?e:Nl(e))}),r.push(Pl(a),...e))}return i(),n}function Il(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function Ll(e){if(typeof e==`string`){let t=e.trim();if(t.length===0)return{ok:!0,value:{}};try{let n=JSON.parse(t);return M(n)?{ok:!0,value:n}:{ok:!1,error:`tool arguments JSON must be an object`,raw:e}}catch{return{ok:!1,error:`malformed tool arguments JSON`,raw:e}}}return M(e)?{ok:!0,value:e}:e==null?{ok:!0,value:{}}:{ok:!1,error:`tool arguments must be a JSON object`,raw:String(e)}}function Rl(e){let t=Ll(e);if(!t.ok)throw new T(`bad_response`,t.error);return t.value}function zl(e,t){let n=e.name.trim(),r={name:n,callId:e.id??Tc(n)},i={stepId:e.stepId,stepCallCount:e.stepCallCount};if(!n)return Bl(r,`function call is missing a name`,t,i);let a=Ll(t);return a.ok?[wc(r,a.value,i)]:Bl(r,a.error,a.raw,i)}function Bl(e,t,n,r={}){return[wc(e,{},r),Cc(e,{code:`malformed_arguments`,kind:`bad_response`,message:t,details:{raw:n}})]}function Vl(e){if(e&&!qc.includes(e))throw new T(`unsupported`,`Gemini does not take the '${e}' thinking level (${qc.join(`, `)})`)}function Hl(e){return e.replaceAll(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function Ul(e){if(Array.isArray(e))return e.map(Ul);if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))n===`schema`||n===`parameters`||n===`arguments`?t[Hl(n)]=r:t[Hl(n)]=Ul(r);return t}return e}function Wl(e){return Sa(e)}var Gl=`user_input`;function Kl(e){return{type:Gl,content:e.map(Wl)}}function ql(e){let t=K(e);return t.length>0?t.map(Wl):[{type:`text`,text:``}]}var Jl=new Set([`text`,`image`,`video`]);function Yl(e){let t=K(e);return{type:`function_result`,...Il({name:e.name,call_id:e.tool_call_id}),result:t.length>0?t.map(Wl):[{type:`text`,text:``}]}}function Xl(e,t){let n={type:`function_call`,id:e.id,name:e.function.name,arguments:Rl(e.function.arguments)};return t?[{type:`thought`,signature:t},n]:[n]}var Zl=i({call:x().int().min(0),signature:S().min(1)});function Ql(e,t){for(let n of e.reasoning??[]){let e=Zl.safeParse(n.data);if(e.success&&e.data.call===t)return e.data.signature}}function $l(e,t){return{type:e===`assistant`?`model_output`:`user_input`,content:ql(t)}}function eu(e){if(e.role===`assistant`&&e.tool_calls&&e.tool_calls.length>0){let t=[];K(e).length>0&&t.push($l(`assistant`,e));for(let[n,r]of e.tool_calls.entries())t.push(...Xl(r,Ql(e,n)));return t}return e.role===`assistant`?[$l(`assistant`,e)]:[$l(`user`,e)]}function tu(e){return Fl(e,Jl).flatMap(e=>e.role===`tool`?[Yl(e)]:eu(e))}function nu(e){return[{type:`text`,mimeType:`application/json`,schema:e}]}function ru(e,t){if(e.speech){if(e.image)throw new T(`config`,`cannot mix speech and image response formats`);if(e.structured)throw new T(`config`,`cannot mix speech and structured response formats`);let n=e.speech.format;if(n&&!Jc.includes(n))throw new T(`unsupported`,`Gemini speech returns ${Jc.join(`, `)}, not '${n}'`);t.responseFormat={type:`audio`}}else if(e.image){let n={type:`image`,mimeType:e.image.mimeType};e.image.aspectRatio&&(n.aspectRatio=e.image.aspectRatio),e.image.resolution&&(n.imageSize=e.image.resolution);for(let[t,n]of[[`quality`,e.image.quality],[`background`,e.image.background],[`n`,e.image.n],[`outputCompression`,e.image.outputCompression]])if(n!==void 0)throw new T(`unsupported`,`image.${t} is not supported on Google image models`);t.responseFormat=e.image.includeText?[{type:`text`},n]:n}else e.structured&&(t.responseFormat=nu(e.structured.jsonSchema))}function iu(e,t){if(!e.speech)return;let{voice:n,speed:r}=e.speech;if(r!==void 0)throw new T(`config`,`Gemini Interactions speech has no speed field: set the pace in speech.style`);if(!n)throw new T(`config`,`Gemini speech needs a voice: set speech.voice`);t.speechConfig=[{voice:n}]}var au=new Set([`gemini-3.8-flash-tts`,`gemini-3.8-flash-lite-tts`]);function ou(e,t,n){if(!au.has(n))return{type:Gl,content:[{type:`text`,text:`Read the following aloud. ${t.trim()}\n`},...e.map(Wl)]};let r=[{type:`speech_metadata`,style:t}];return{type:Gl,content:e.map(Wl).map(e=>e.type===`text`?{...e,annotations:r}:e)}}function su(e){return{type:`function`,name:e.name,description:e.description,parameters:e.parameters}}function cu(e){let t=[];for(let n of e.builtins)t.push(jl(n));for(let n of e.wireTools??[])t.push(su(n));return t}function lu(e){let t=new Map;return e.map(e=>{for(let n of e.tool_calls??[])t.set(n.id,n.function.name);if(e.role!==`tool`||e.name||!e.tool_call_id)return e;let n=t.get(e.tool_call_id);return n?{...e,name:n}:e})}function uu(e){if(e.continuation&&e.continuation.length>0)return tu(lu(e.continuation));let t=tu(lu(e.history??[]));if(e.input.length>0||t.length===0){let n=e.speech?.style;t.push(n?ou(e.input,n,e.apiId):Kl(e.input))}return t}function du(e,t){e.store!==void 0&&(t.store=e.store),e.previousInteractionId&&(t.previousInteractionId=e.previousInteractionId),e.system&&(t.systemInstruction=e.system);let n=cu(e);n.length>0&&(t.tools=n)}function fu(e){let t={temperature:e.temperature,maxOutputTokens:e.maxOutputTokens};return e.speech?iu(e,t):(Vl(e.thinking),e.thinking&&(t.thinkingLevel=e.thinking),e.summaries&&(t.thinkingSummaries=e.summaries),e.image?.seed!==void 0&&(t.seed=e.image.seed)),{model:e.apiId,stream:e.stream??!0,input:uu(e),generationConfig:t}}function pu(e){let t=fu(e);return ru(e,t),du(e,t),Ul(t)}var mu=16,hu=new Set([`audio/pcm`,`audio/l16`]);function gu(e,t,n){for(let r=0;r<n.length;r++)e.setUint8(t+r,n.charCodeAt(r))}function _u(e){if(e===void 0||!/^\d+$/.test(e))return;let t=Number(e);return t>0?t:void 0}function vu(e){let[t=``,...n]=e.split(`;`),r=new Map;for(let e of n){let t=e.indexOf(`=`);t>0&&r.set(e.slice(0,t).trim().toLowerCase(),e.slice(t+1).trim())}return{essence:t.trim().toLowerCase(),params:r}}function yu(e){let{essence:t,params:n}=vu(e);if(!hu.has(t))return;let r=_u(n.get(`rate`));if(r===void 0)return;let i=n.has(`channels`)?_u(n.get(`channels`)):1;if(i!==void 0)return{sampleRate:r,channels:i}}function bu(e,t){let{sampleRate:n,channels:r}=t,i=r*mu/8,a=n*i,o=e.length,s=new ArrayBuffer(44+o),c=new DataView(s);return gu(c,0,`RIFF`),c.setUint32(4,36+o,!0),gu(c,8,`WAVE`),gu(c,12,`fmt `),c.setUint32(16,16,!0),c.setUint16(20,1,!0),c.setUint16(22,r,!0),c.setUint32(24,n,!0),c.setUint32(28,a,!0),c.setUint16(32,i,!0),c.setUint16(34,mu,!0),gu(c,36,`data`),c.setUint32(40,o,!0),new Uint8Array(s,44).set(e),new Uint8Array(s)}function xu(e){let t=yu(e.mimeType);if(!t)return e;let n=bu(rt(e.data),t);return{mimeType:`audio/wav`,data:nt(n)}}function Su(e,t){if(!t)return{known:e};let n={...e,...t};return n.id===e?.id&&n.model===e?.model?{known:e}:{known:n,event:{type:`response`,response:n}}}function Cu(e){try{return{type:`structured`,structured:JSON.parse(e)}}catch(e){return I(new T(`bad_response`,`structured output was not valid JSON`,{cause:e}))}}function wu(e){let t=e.name.trim(),n=e.drafted??0;return!(e.id&&t)||e.args.length<=n?[]:(e.drafted=e.args.length,[{type:`tool_draft`,callId:e.id,name:t,text:e.args.slice(n)}])}function Tu(e){if(!e)return[];let{grounding:t,sources:n}=e;return[{type:`grounding`,grounding:t},...n.length>0?[{type:`citation`,sources:n}]:[]]}function Eu(e){let t=X(e.url);if(!t)return;let n=X(e.place_id);return{type:`maps`,uri:t,title:X(e.name)??t,...n?{placeId:n}:{}}}function Du(e){return{maps:{title:e.title,uri:e.uri,...e.placeId?{placeId:e.placeId}:{}}}}function Ou(e){let t=X(e.uri);if(t)return{type:`web`,uri:t,title:X(e.title)??t}}function ku(e,t){t&&(e.some(e=>e.type===t.type?t.placeId&&e.placeId&&t.placeId===e.placeId?!0:e.uri===t.uri:!1)||e.push(t))}function Au(e,t){let n=Y(Y(t)?.maps);if(!n){e.push(t);return}let r=X(n.placeId),i=X(n.uri);e.some(e=>{let t=Y(Y(e)?.maps);if(!t)return!1;let n=X(t.placeId);return r&&n&&r===n?!0:!!(i&&X(t.uri)===i)})||e.push(t)}function ju(e){if(Array.isArray(e))for(let t of e){let e=X(Y(t)?.search_suggestions);if(e)return e}}function Mu(e){let t=Y(e),n=X(t?.url);if(t&&n){if(t.type===`place_citation`){let e=X(t.name)??n,r=X(t.place_id);return{type:`maps`,uri:n,title:e,...r?{placeId:r}:{}}}if(t.type===`url_citation`)return{type:`web`,uri:n,title:X(t.title)??n}}}function Nu(e,t){if(Array.isArray(t))for(let n of t)ku(e,Mu(n))}function Pu(e,t){if(Array.isArray(t))for(let n of t){let t=Y(n)?.places;if(Array.isArray(t))for(let n of t){let t=Y(n),r=t?Eu(t):void 0;r&&ku(e,r)}}}function Fu(e){let t=[];if(Nu(t,e.annotations),Array.isArray(e.content))for(let n of e.content)Nu(t,Y(n)?.annotations);Pu(t,e.result);let n=[];for(let e of t)e.type===`maps`&&Au(n,Du(e));let r=ju(e.result);if(r||t.length!==0)return{grounding:{metadata:e,...n.length>0?{chunks:n}:{},...r?{searchHtml:r}:{}},sources:t}}function Iu(e,t){if(!e)return t;if(!t)return e;let n=[];for(let r of[...e.grounding.chunks??[],...t.grounding.chunks??[]])Au(n,r);let r=[...e.sources];for(let e of t.sources)ku(r,e);let i=t.grounding.searchHtml??e.grounding.searchHtml,a=t.grounding.metadata??e.grounding.metadata;return{grounding:{...a?{metadata:a}:{},...n.length>0?{chunks:n}:{},...i?{searchHtml:i}:{}},sources:r}}function Lu(e){let t=Y(e.delta);return Tu(t?Fu(t):void 0)}function Ru(e){let t;for(let n of e){let e=Y(n);e&&(t=Iu(t,Fu(e)))}return Tu(t)}function zu(e){let t=Y(e);if(!t)return[];let n=Array.isArray(t.groundingChunks)?t.groundingChunks:[],r=[];for(let e of n){let t=Y(Y(e)?.web);t&&ku(r,Ou(t))}let i=X(Y(t.searchEntryPoint)?.renderedContent);return Tu({grounding:{metadata:t,...n.length>0?{chunks:n}:{},...i?{searchHtml:i}:{}},sources:r})}function Bu(e,t){if(!Array.isArray(e))return;let n={};for(let r of e){let e=Y(r),i=Z(e?.[t]);if(typeof e?.modality==`string`&&i!==void 0){let t=e.modality.toLowerCase();n[t]=(n[t]??0)+i}}return Object.keys(n).length>0?n:void 0}function Vu(e,t){if(e||t)return{...e?{input:e}:{},...t?{output:t}:{}}}function Hu(e){if(!Array.isArray(e))return;let t=e.flatMap(e=>{let t=Y(e),n=Z(t?.count);if(typeof t?.type!=`string`||n===void 0)return[];let r=Z(t.search_query_count);return[{type:t.type,count:n,...r===void 0?{}:{searchQueryCount:r}}]});return t.length>0?t:void 0}function Uu(e){let t=Y(e);return t?.type===`text`&&typeof t.text==`string`?t.text:``}function Wu(e){let t=e.mime_type;if(typeof t!=`string`||!t)return;let n=t.toLowerCase(),r=[];return typeof e.sample_rate==`number`&&!/;\s*rate=/.test(n)&&r.push(`rate=${String(e.sample_rate)}`),typeof e.channels==`number`&&!/;\s*channels=/.test(n)&&r.push(`channels=${String(e.channels)}`),r.length>0?`${t}; ${r.join(`; `)}`:t}function Gu(e){let t=Wu(e),{data:n}=e;return!t||typeof n!=`string`||!n?[]:[{type:`media`,media:{mimeType:t,data:n}}]}function Ku(e,t){return t?[{type:e,text:t}]:[]}function qu(e){return e===`code_execution_call`||e===`code_execution_result`}function Ju(e){return e.startsWith(`google_`)||e===`url_context_call`||e===`url_context_result`}function Yu(e){return{type:`evidence`,evidence:{provider:`google`,kind:`provider_step`,step:String(e.type??``),raw:e}}}function Xu(e){if(e.type===`code_execution_result`){let t=X(e.call_id);return{type:`evidence`,evidence:{provider:`google`,kind:`code_execution_result`,raw:e,...typeof e.result==`string`?{result:e.result}:{},...typeof e.is_error==`boolean`?{isError:e.is_error}:{},...t?{callId:t}:{}}}}let t=Y(e.arguments),n=X(e.id);return e.type!==`code_execution_call`||!n||typeof t?.code!=`string`?Yu(e):{type:`evidence`,evidence:{provider:`google`,kind:`code_execution_call`,raw:e,code:t.code,...typeof t.language==`string`?{language:t.language}:{},id:n}}}function Zu(e){let t=Y(e);if(!t)return[];switch(t.type){case`thought_summary`:return Ku(`thought`,Uu(t.content));case`text`:return Ku(`text`,typeof t.text==`string`?t.text:``);case`image`:case`audio`:return Gu(t);default:return[]}}function Qu(e){return(Array.isArray(e.summary)?e.summary:[]).flatMap(e=>Ku(`thought`,Uu(e)))}function $u(e){return(Array.isArray(e.content)?e.content:[]).flatMap(e=>{let t=Y(e);return t?.type===`text`?Ku(`text`,typeof t.text==`string`?t.text:``):t?.type===`image`||t?.type===`audio`?Gu(t):[]})}function ed(e){let t=Y(e);if(!t)return;let n=Z(t.total_output_tokens),r=Z(t.total_thought_tokens)??0,i=Z(t.total_tool_use_tokens)??0,a=Z(t.total_tokens),o=a===void 0?void 0:a-(n??0)-r-i,s=Z(t.total_input_tokens)||(o&&o>0?o:0);return go({input:s?s+i:void 0,output:n===void 0?void 0:n+r,thinking:r,toolUse:i,cached:Z(t.total_cached_tokens),byModality:Vu(Bu(t.input_tokens_by_modality,`tokens`),Bu(t.output_tokens_by_modality,`tokens`)),grounding:Hu(t.grounding_tool_count)})}function td(e){let t=ed(e.usage);if(!t)return;let n=typeof e.id==`string`?e.id:void 0;return{type:`tokens`,tokens:t,...n?{interactionId:n}:{}}}function nd(e){let t=[],n=td(e);n&&t.push(n);let{steps:r}=e;Array.isArray(r)&&t.push(...Ru(r));let i=id(e);return i&&t.push(i),t}function rd(e){let t=X(e.id),n=X(e.model);if(t||n)return{...t?{id:t}:{},...n?{model:n}:{}}}function id(e){let{status:t}=e;if(typeof t==`string`)return{type:`done`,stop:mo(t),...typeof e.id==`string`?{interactionId:e.id}:{}}}function ad(){return{text:``,steps:new Map,sawMedia:!1,sawDone:!1,calls:0}}function od(e){return e===`function_call`||qu(e)||Ju(e)}function sd(e){return typeof e==`string`&&e.length>0?e:void 0}function cd(e,t){let n=sd(e);n&&(t.thoughtSignature=n)}function ld(e,t){let n=sd(e.signature)??t.thoughtSignature;return t.thoughtSignature=void 0,n}function ud(e,t){let n=String(e.type??``);if(n===`function_call`){let n=typeof e.id==`string`?e.id:void 0,r=typeof e.name==`string`?e.name:``,i=ld(e,t),a=t.calls++;return[...i?[{type:`reasoning`,data:{call:a,signature:i},origin:{protocol:`geminiInteractions`}}]:[],...zl({id:n,name:r},e.arguments)]}return qu(n)?[Xu(e)]:Ju(n)?[Yu(e)]:n===`thought`?(cd(e.signature,t),Qu(e)):n===`model_output`?$u(e):[]}function dd(e){return typeof e.index==`number`?e.index:0}function fd(e,t){let n=Y(e.step);if(!n)return;let r=String(n.type??``);r===`thought`&&cd(n.signature,t),od(r)&&t.steps.set(dd(e),{...n})}function pd(e,t){let n=Y(e.delta);if(!n)return[];let r=t.steps.get(dd(e));if(!r)return n.type===`thought_signature`&&cd(n.signature,t),Zu(n);if(n.type===`arguments_delta`){let e=typeof r.arguments==`string`?r.arguments:``,t=e+(typeof n.arguments==`string`?n.arguments:``);return r.arguments=t,r.type===`function_call`?wu({id:sd(r.id),name:typeof r.name==`string`?r.name:``,args:t,drafted:e.length}):[]}return Object.assign(r,n),[]}function md(e,t){let n=dd(e),r=t.steps.get(n);return r?(t.steps.delete(n),ud(r,t)):[]}function hd(e){let t=qu(String(e.type??``))?Xu(e):Yu(e);return{...t,evidence:{...t.evidence,partial:!0}}}function gd(e){let t=[...e.steps.values()].map(hd);return e.steps.clear(),t}function _d(e,t){return e.map(e=>(e.type===`done`&&(t.sawDone=!0),e.type===`text`&&e.text&&(t.text+=e.text),e.type!==`media`||!e.media?e:(t.sawMedia=!0,{...e,media:xu(e.media)})))}function vd(e,t){if(e.eventType===`sse_unparsed`)return[I(new T(`bad_response`,`Interactions stream row was not a JSON object`))];let n=wl(e);if(n)return[I(n)];let r=Lu(e);switch(e.event_type){case`step.start`:fd(e,t);break;case`step.delta`:r.push(...pd(e,t));break;case`step.stop`:r.push(...md(e,t));break;case`interaction.created`:{let n=Y(e.interaction);n&&r.push(...yd(n,t));break}case`interaction.completed`:{let n=Y(e.interaction);n&&r.push(...yd(n,t),...nd(n));break}}return r}function yd(e,t){let n=Su(t.response,rd(e));return t.response=n.known,n.event?[n.event]:[]}function bd(e,t){return _d(vd(e,t),t)}function xd(e,t){let n=(Array.isArray(e.steps)?e.steps:[]).flatMap(e=>{let n=Y(e);return n?ud(n,t):[]});return _d([...yd(e,t),...n,...nd(e)],t)}function*Sd(e,t){e.structured&&t.text&&(yield Cu(t.text))}function Cd(e){return!!e.speech}function wd(e,t){if(!t.sawMedia){if(Cd(e))return I(new T(`bad_response`,`speech audio was not returned by the model`));if(e.image)return I(new T(`bad_response`,`no image returned from image generation`))}}function Td(e){return e.type===`done`?{type:`done`,stop:e.stop,...e.interrupted===void 0?{}:{interrupted:e.interrupted}}:e.type===`tool`?e.tool.phase===void 0?{type:`tool_call`,call:e.tool}:e.tool.phase===`cancel`?{type:`tool_cancel`,callId:e.tool.callId}:e.tool.phase===`error`?{type:`error`,errorKind:`bad_response`}:void 0:e}var Ed=i({interactionId:S().min(1)}),Dd=i({store:_().optional().describe(`Whether Google keeps the interaction. Off, nothing is stored server-side.`),persistViaInteractionId:_().optional().describe(`Continue from the stored interaction instead of sending the conversation again. Needs store.`)}).refine(e=>!e.persistViaInteractionId||e.store!==!1,`persistViaInteractionId needs store`);function Od(e,t){let n=t.history??[],r=e.options.persistViaInteractionId?t.state?.interactionId:void 0,i=kl(t.builtins),a={...t,apiId:e.apiId,history:n,builtins:i,state:void 0,tapUpstream:void 0,store:e.options.store,previousInteractionId:r,continuation:r?[...n.slice(t.stateHistoryLength??0),...t.input.map(e=>({role:`user`,parts:[e]}))]:void 0};return{wire:a,body:L.parse(JSON.parse(JSON.stringify(pu(a)))),wroteTools:i.map(e=>e.id)}}function kd(e,t,n){return e.flatMap(e=>{if(e.type!==`done`){let t=Td(e);return t?[t]:[]}let{interactionId:r,...i}=e;return t.done={...i,...n&&r?{state:{interactionId:r}}:{}},[]})}var Ad=q({id:`geminiInteractions`,name:`Gemini Interactions`,description:`Google's Interactions API for Gemini: text, images and speech at one endpoint.`,endpoints:{text:`/interactions`,image:`/interactions`,speech:`/interactions`},options:Dd,continuation:{version:1,schema:Ed,keyOptions:[`store`,`persistViaInteractionId`]},reasoning:Zl,error(e){let t=Y(e.body);return Tl(t?wl(t):null,e.status,`Gemini HTTP ${e.status}`)},create(e){return{async*complete(t){let{wire:n,body:r,wroteTools:i}=Od(e,t),a=t.stream!==!1,o=!!e.options.persistViaInteractionId,s={fold:ad()},c={stream:a,wroteTools:i,...a?{path:`/interactions?alt=sse`}:{}};for await(let t of e.send(r,c)){let e=wl(t);if(e)throw e;let n=a?bd(t,s.fold):xd(t,s.fold);if(yield*kd(n,s,o),n.some(e=>e.type===`error`)){yield*kd(gd(s.fold),s,o);return}}yield*kd(gd(s.fold),s,o),yield*kd([...Sd(n,s.fold)],s,o);let l=wd(n,s.fold);l&&(yield*kd([l],s,o)),yield s.done??{type:`done`,stop:{kind:`stream_incomplete`}}}}}}),jd=`NON_BLOCKING`;function Md(e){return{name:e.name,description:e.description,behavior:jd,parametersJsonSchema:e.parameters??{type:`object`,properties:{}}}}function Nd(e){let t=[];for(let n of e.builtins)t.push(Ml(n));let n=(e.wireTools??[]).map(Md);return n.length>0&&t.push({functionDeclarations:n}),t}function Pd(e){let t={responseModalities:[`AUDIO`],temperature:e.temperature,maxOutputTokens:e.maxOutputTokens};e.live?.voice&&(t.speechConfig={voiceConfig:{prebuiltVoiceConfig:{voiceName:e.live.voice}}}),Vl(e.thinking);let n={...e.thinking?{thinkingLevel:e.thinking}:{},...e.summaries?{includeThoughts:e.summaries===`auto`}:{}};return Object.keys(n).length>0&&(t.thinkingConfig=n),t}function Fd(e){let{triggerTokens:t}=e,{targetTokens:n}=e.slidingWindow;return{...t===void 0?{}:{triggerTokens:t},slidingWindow:n===void 0?{}:{targetTokens:n}}}function Id(e){let t={};e.startSensitivity!==void 0&&(t.startOfSpeechSensitivity=e.startSensitivity),e.endSensitivity!==void 0&&(t.endOfSpeechSensitivity=e.endSensitivity),e.prefixPaddingMs!==void 0&&(t.prefixPaddingMs=e.prefixPaddingMs),e.silenceDurationMs!==void 0&&(t.silenceDurationMs=e.silenceDurationMs);let n={};return e.activityHandling!==void 0&&(n.activityHandling=e.activityHandling),Object.keys(t).length>0&&(n.automaticActivityDetection=t),Object.keys(n).length>0?n:void 0}function Ld(e){if(e.sessionResumptionHandle)return{handle:e.sessionResumptionHandle};if(e.live?.sessionResumption)return{}}function Rd(e){return e.startsWith(`models/`)?e:`models/${e}`}function zd(e,t){e?.transcription?.input&&(t.inputAudioTranscription={}),e?.transcription?.output&&(t.outputAudioTranscription={})}function Bd(e){let t=e.live,n=t?.vad?Id(t.vad):void 0,r=Nd(e),i=Ld(e),a=!!(e.history&&e.history.length>0),o={model:Rd(e.apiId),generationConfig:Pd(e),systemInstruction:{parts:[{text:e.system}]},...r.length>0?{tools:r}:{},...i?{sessionResumption:i}:{},...t?.contextCompression?{contextWindowCompression:Fd(t.contextCompression)}:{},...a?{historyConfig:{initialHistoryInClientContent:!0}}:{},...n?{realtimeInputConfig:n}:{}};return zd(t,o),{setup:o}}function Vd(e){if(Ca(e))throw new T(`unsupported`,`media references are not supported on geminiLive`);return e}function Hd(e){let t=Vd(e);return{mimeType:t.mimeType,data:t.data}}function Ud(e){return e.type===`text`?{text:e.text}:{inlineData:Hd(e)}}function Wd(e){let t=K(e),n=t.map(e=>e.type===`text`?e.text:``).filter(Boolean).join(`
|
|
4
4
|
`),r=t.filter(e=>e.type!==`text`).map(Ud);return{role:`user`,parts:[{functionResponse:{...Il({id:e.tool_call_id,name:e.name}),response:{result:n},...r.length>0?{parts:r}:{}}}]}}function Gd(e){if(e.role===`tool`)return Wd(e);let t=e.role===`assistant`?`model`:`user`,n=K(e).map(Ud);for(let t of e.role===`assistant`?e.tool_calls??[]:[])n.push({functionCall:{id:t.id,name:t.function.name,args:Rl(t.function.arguments)}});return{role:t,parts:n}}function Kd(e){return!e||e.length===0?null:{clientContent:{turns:e.map(Gd),turnComplete:!0}}}function qd(e){return{clientContent:{turns:[{role:`user`,parts:[{text:e}]}],turnComplete:!1}}}function Jd(e){if(e.type===`text`)return{realtimeInput:{text:e.text}};let t=Vd(e),n={mimeType:t.mimeType,data:t.data};return{realtimeInput:t.type===`audio`?{audio:n}:{video:n}}}function Yd(e){let t=Y(e)?.error;return typeof t==`string`?{error:t}:{result:e}}function Xd(e,t,n,r){return Zd([{id:e,name:t,output:n,parts:r}])}function Zd(e){return{toolResponse:{functionResponses:e.map(({id:e,name:t,output:n,parts:r})=>({id:e,name:t,response:Yd(n),...r?.length?{parts:r.filter(e=>e.type!==`text`).map(Ud)}:{}}))}}}function Qd(e){return{role:`tool`,...typeof e.id==`string`?{tool_call_id:e.id}:{},...typeof e.name==`string`?{name:e.name}:{},content:JSON.stringify(e.response??null)}}function $d(e){return Array.isArray(e)?e.flatMap(e=>{let t=Y(e);return t?[t]:[]}):[]}function ef(e){let t=[],n=[],r=[];for(let i of $d(e.parts)){let e=Y(i.inlineData),a=Y(i.functionCall),o=Y(i.functionResponse);if(typeof i.text==`string`)t.push({type:`text`,text:i.text});else if(e&&typeof e.mimeType==`string`&&typeof e.data==`string`){let n=ta(e.mimeType)??`document`;t.push({type:n,mimeType:e.mimeType,data:e.data})}else a?n.push({id:typeof a.id==`string`?a.id:``,type:`function`,function:{name:String(a.name??``),arguments:JSON.stringify(a.args??{})}}):o&&r.push(Qd(o))}let i=e.role===`model`?`assistant`:`user`;return[...t.length>0||n.length>0?[{role:i,parts:t,...n.length>0?{tool_calls:n}:{}}]:[],...r]}function tf(e){let t=Y(e.realtimeInput);if(t){let e=Y(t.audio),n=Y(t.video),r=e??n;return r&&typeof r.mimeType==`string`&&typeof r.data==`string`?[{role:`user`,parts:[{type:e?`audio`:`video`,mimeType:r.mimeType,data:r.data}]}]:typeof t.text==`string`?[{role:`user`,parts:[{type:`text`,text:t.text}]}]:[]}let n=Y(e.clientContent);if(n)return $d(n.turns).flatMap(ef);let r=Y(e.toolResponse);return r?$d(r.functionResponses).map(Qd):[]}function nf(e){let t=Z(e.promptTokenCount),n=Z(e.responseTokenCount),r=Z(e.thoughtsTokenCount)??0,i=Z(e.toolUsePromptTokenCount)??0;return go({input:t?t+i:void 0,output:n===void 0?void 0:n+r,thinking:r,toolUse:i,cached:Z(e.cachedContentTokenCount),byModality:Vu(Bu(e.promptTokensDetails,`tokenCount`),Bu(e.responseTokensDetails,`tokenCount`))})}function rf(e,t){let n=Y(e.sessionResumptionUpdate);if(!n)return;let r=typeof n.newHandle==`string`&&n.newHandle.length>0?n.newHandle:void 0,i=typeof n.resumable==`boolean`?n.resumable:void 0;(r!==void 0||i!==void 0)&&t.push({type:`evidence`,...r===void 0?{}:{sessionResumptionHandle:r},evidence:{provider:`google`,kind:`session_resumption`,resumable:i??r!==void 0,raw:n}})}function af(){return{calls:new Map}}function of(e,t,n){let r=Y(e.toolCall)?.functionCalls;if(!Array.isArray(r))return;let i=crypto.randomUUID(),a=r.length;for(let e of r){let r=Y(e)??{},o=typeof r.id==`string`&&r.id?r.id:void 0,s=typeof r.name==`string`?r.name:``;o&&s&&t.calls.set(o,s),n.push(...zl({id:o,name:s,stepId:i,stepCallCount:a},r.args))}}function sf(e,t,n){let r=Y(e.toolCallCancellation)?.ids;if(Array.isArray(r))for(let e of r){let r=typeof e==`string`?t.calls.get(e):void 0;typeof e!=`string`||!r?n.push(I(new T(`bad_response`,`Live cancelled a tool call it never issued: ${String(e)}`))):(t.calls.delete(e),n.push(bc({name:r,callId:e},{phase:`cancel`})))}}function cf(e,t){let n=Y(e.voiceActivity);n&&t.push({type:`evidence`,evidence:{provider:`google`,kind:`voice_activity`,raw:n}})}function lf(e){if(typeof e!=`string`)return;let t=/^(\d+(?:\.\d+)?)s$/.exec(e);return t?.[1]?Math.round(Number(t[1])*1e3):void 0}function uf(e,t){let n=Y(e.goAway);if(!n)return;let r=lf(n.timeLeft);t.push({type:`session`,session:{kind:`closing_soon`,...r===void 0?{}:{timeLeftMs:r}}})}function df(e,t){typeof e.text==`string`&&e.text&&t.push({type:e.thought===!0?`thought`:`text`,text:e.text});let n=Y(e.inlineData),r=n?.mimeType,i=n?.data;typeof r==`string`&&r&&typeof i==`string`&&i&&t.push({type:`media`,media:xu({mimeType:r,data:i})});let a=Y(e.codeExecutionResult);a&&t.push(ff(a))}function ff(e){return{type:`evidence`,evidence:{provider:`google`,kind:`code_execution_result`,...typeof e.output==`string`?{result:e.output}:{},...typeof e.outcome==`string`?{isError:e.outcome!==`OUTCOME_OK`}:{},raw:e}}}function pf(e){let t=Y(e)?.text;return typeof t==`string`&&t?t:void 0}function mf(e,t,n,r){let i=pf(e);i&&n.push({type:`evidence`,text:i,evidence:{provider:`google`,kind:t,...r?{interim:!0}:{}}})}function hf(e,t){t.push(...zu(e.groundingMetadata));let n=Y(e.urlContextMetadata);n&&t.push({type:`evidence`,evidence:{provider:`google`,kind:`url_context`,raw:n}})}function gf(e){let t=Y(e.serverContent)?.interactionStatus;if(t===`IN_PROGRESS`||t===`IDLE`)return t}function _f(e,t){let n=gf(e);n&&t.push({type:`session`,session:{kind:n===`IDLE`?`idle`:`working`}})}function vf(e,t){let n=Y(e.serverContent);if(!n)return;n.interrupted===!0&&t.push({type:`done`,interrupted:!0,stop:{kind:`interrupted`}}),n.waitingForInput===!0&&t.push({type:`session`,session:{kind:`waiting_for_input`}}),n.generationComplete===!0&&t.push({type:`done`,stop:{kind:`generation_complete`}}),mf(n.inputTranscription,`input_transcription`,t),mf(n.interimInputTranscription,`input_transcription`,t,!0),mf(n.outputTranscription,`output_transcription`,t);let r=Y(n.modelTurn)?.parts;for(let e of Array.isArray(r)?r:[]){let n=Y(e);n&&df(n,t)}hf(n,t),n.turnComplete===!0&&t.push({type:`session`,session:{kind:`turn_complete`}})}function yf(e,t){let n=Y(e.usageMetadata),r=n?nf(n):void 0;r&&t.push({type:`tokens`,tokens:r})}function bf(e,t){if(!e||typeof e!=`object`)return[];let n=[];return uf(e,n),rf(e,n),of(e,t,n),sf(e,t,n),cf(e,n),vf(e,n),_f(e,n),yf(e,n),n}var xf={1006:`network`,1007:`unsupported`,1008:`unsupported`,1011:`unavailable`,1013:`busy`},Sf=/\bquota\b/i,Cf=/\bAPI key (?:not valid|expired)\b/i;function wf(e){if(Sf.test(e))return`rate_limit`;if(Cf.test(e))return`auth`}function Tf(e,t,n){return new T(wf(t)??xf[e]??`unavailable`,`Gemini Live WebSocket closed during ${n} (${e}: ${t})`)}function Ef(e){let t=ho(e,e=>e.type===`session`&&e.session.kind===`closing_soon`);return t?.session.kind===`closing_soon`?{timeLeftMs:t.session.timeLeftMs}:void 0}function Df(e,t){if(t.some(e=>e.type===`done`&&e.interrupted===!0))return`abort`;let n=gf(e);return n===`IDLE`?`complete`:n===`IN_PROGRESS`?`streaming`:Y(e.serverContent)?.turnComplete===!0?`complete`:`streaming`}var Of=i({liveHandle:S().min(1)}),kf=1e3;function Af(e,t){return e.eventType===`ws_error`?new T(`network`,`Gemini Live WebSocket error during ${t}`):e.eventType===`ws_unparsed`?new T(`bad_response`,`malformed Gemini Live message`):wl(e)??void 0}async function jf(e,t){let n,r=new Promise((e,r)=>{n=setTimeout(()=>r(new T(`timeout`,`Gemini Live setup timed out after ${t.limits.connectTimeoutMs}ms`)),t.limits.connectTimeoutMs)});try{for(;;){let t=await Promise.race([e.next(),r]);if(t.done)throw Tf(1006,``,`setup`);let n=t.value;if(n.eventType===`ws_close`)throw Tf(Number(n.code),String(n.reason??``),`setup`);let i=Af(n,`setup`);if(i)throw i;if(n.setupComplete)return}}finally{clearTimeout(n)}}function Mf(e,t){let n=t.state?.liveHandle,r=t.history??[],i=kl(t.builtins),a={...t,apiId:e.apiId,builtins:i,state:void 0,tapUpstream:void 0,sessionResumptionHandle:n,history:n?r.slice(t.stateHistoryLength??0):r,live:{...t.live,transcription:{...t.live?.transcription,input:!0,output:!0}}};return{wire:a,setup:L.parse(JSON.parse(JSON.stringify(Bd(a)))),wroteTools:i.map(e=>e.id)}}function*Nf(e,t,n){let r=[...e.filter(e=>e.type===`tokens`),...e.filter(e=>e.type!==`tokens`)];for(let e of r){let t=Td(e);t&&(yield t)}if(t===`abort`)return;let i=n?{state:{liveHandle:n}}:{};e.some(e=>e.type===`tool`&&e.tool.phase===void 0)&&(yield{type:`done`,stop:{kind:`tool`},...i}),t===`complete`&&(yield{type:`done`,stop:{kind:`completed`},...i})}function Pf(e,t,n,r){let i=t=>Lf(e,t),a=af(),o=r,s,c;return{closeInfo:()=>c,async*events(){for(;;){let e=await t.next();if(e.done)return;let r=e.value;if(r.eventType===`ws_close`){n.signal?.throwIfAborted();let e=Number(r.code),t=String(r.reason??``);c={code:e,reason:t,...e===kf?{}:{error:Tf(e,t,`session`)},...s?{warning:{...s.timeLeftMs===void 0?{}:{timeLeftMs:s.timeLeftMs},closedAfterMs:Math.round(performance.now()-s.atMs)}}:{}};return}let i=Af(r,`session`);if(i)throw i;if(r.setupComplete)continue;let l=bf(r,a),u=Ef(l);u&&(s={...u,atMs:performance.now()});for(let e of l)e.type===`evidence`&&e.sessionResumptionHandle&&(o=e.sessionResumptionHandle);yield*Nf(l,Df(r,l),o)}},sendText:e=>If(()=>i(Jd({type:`text`,text:e}))),sendAudio:e=>If(()=>i(Jd({type:`audio`,...e}))),sendVideo:e=>If(()=>i(Jd({type:`video`,...e}))),sendContext:e=>If(()=>i(qd(typeof e.server==`string`?e.server:JSON.stringify(e)))),sendToolResult:e=>If(()=>i(Xd(e.callId,e.name,e.text,e.parts))),close:t=>If(()=>e.close(kf,t??`session-closed`))}}var Ff=q({id:`geminiLive`,name:`Gemini Live`,description:`Google's Live API for Gemini: a spoken session over one WebSocket.`,endpoints:{live:`/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent`},options:i({}),continuation:{version:1,schema:Of},create(e){return{async openSession(t){let{wire:n,setup:r,wroteTools:i}=Mf(e,t),a=await e.connect(r,{wroteTools:i}),o=a.frames()[Symbol.asyncIterator](),s=()=>a.close(kf,`aborted`);e.signal?.addEventListener(`abort`,s,{once:!0});try{e.signal?.throwIfAborted(),await jf(o,e)}catch(t){throw e.signal?.removeEventListener(`abort`,s),a.close(kf,`setup-failed`),t}let c=n.history?.length?Kd(n.history):void 0;c&&Lf(a,c);for(let e of n.input)Lf(a,Jd(e));return Pf(a,o,e,n.sessionResumptionHandle)}}}});function If(e){try{return e(),Promise.resolve()}catch(e){return Promise.reject(e)}}function Lf(e,t){e.send(t,tf(t))}var Rf={input:.75,output:4.5,byModality:{input:{audio:3,image:1,video:1},output:{audio:12}}},zf={checked:`2026-10-15`,models:{"gemini-3.8-flash":{input:.75,output:3.75,cachedInput:.075},"gemini-3.6-flash":{input:.75,output:3.75,cachedInput:.075},"gemini-3.8-live":Rf,"gemini-3.8-live-extended-thinking":Rf,"gemini-3.1-flash-live-preview":Rf,"gemini-3.5-flash-lite":{input:.3,output:2.5,cachedInput:.03},"gemini-3.1-flash-lite":{input:.25,output:1.5,cachedInput:.025,byModality:{input:{audio:.5}}},"gemini-3.1-pro-preview":{input:2,output:12,cachedInput:.2,longContext:{above:2e5,input:4,output:18,cachedInput:.4}},"gemini-3.1-flash-lite-image":{input:.25,output:1.5,byModality:{output:{image:30}}},"gemini-3.8-flash-tts":{input:.5,output:9},"gemini-3.8-flash-lite-tts":{input:.5,output:6},"gemini-3.1-flash-tts-preview":{input:1,output:20},"gemini-3-flash-preview":{input:.5,output:3,cachedInput:.05,byModality:{input:{audio:1}}},"gemini-2.5-flash":{input:.3,output:2.5,cachedInput:.03,byModality:{input:{audio:1}}},"gemini-2.5-flash-lite":{input:.1,output:.4,cachedInput:.01,byModality:{input:{audio:.3}}},"gemini-2.5-flash-preview-tts":{input:.5,output:10},"gemini-2.5-flash-image":{input:.3,output:30}}},Bf=Wc({id:`gemini`,name:`Gemini`,description:`Google's models with an API key, from Google AI Studio.`,traceName:`gcp.gemini`,connection:i({host:zc.refine(e=>{let t=new URL(e);return t.pathname===`/`&&!t.search&&!t.hash},O(`protocol.endpoint_host`)).optional().describe(`The API host, by default https://generativelanguage.googleapis.com. Live connects to the same host over wss.`)}).default({}),key:S().trim().min(1),authorize:Vc(`x-goog-api-key`),prices:zf,serves(e){let t=new URL(e.host??`https://generativelanguage.googleapis.com`),n=t.origin,r=`${t.protocol===`http:`?`ws:`:`wss:`}//${t.host}`;return[{protocol:Ad,baseUrl:`${n}/v1beta`},{protocol:cl,baseUrl:`${n}/v1beta`},{protocol:Ff,baseUrl:`${r}/ws`,authorize:Hc(`key`)}]}});function Vf(e){if(Ca(e))throw new T(`unsupported`,`media references are not supported on openAi`)}function Hf(e){let t=`mp3`;return e.mimeType.includes(`wav`)&&(t=`wav`),{type:`input_audio`,input_audio:{data:e.data,format:t}}}function Uf(e){return e.every(e=>e.type===`text`)?e.map(e=>e.type===`text`?e.text:``).filter(Boolean).join(`
|
|
5
|
-
`):e.map(e=>e.type===`text`?{type:`text`,text:e.text}:(Vf(e),e.type===`image`?{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}}:e.type===`audio`?Hf(e):{type:`file`,file:{filename:e.type===`video`?`clip.bin`:`document.bin`,file_data:`data:${e.mimeType};base64,${e.data}`}}))}function Wf(e){let t=Uf(K(e));if(e.role===`tool`)return{role:`tool`,...Il({tool_call_id:e.tool_call_id,name:e.name}),content:t};let n={role:e.role,content:t};return e.tool_calls&&e.tool_calls.length>0&&(n.tool_calls=e.tool_calls.map(e=>({id:e.id,type:`function`,function:{name:e.function.name,arguments:e.function.arguments}}))),e.name&&(n.name=e.name),n}var Gf=new Set([`text`,`image`]);function Kf(e,t){let n=t?.includeSystem!==!1,r=[];n&&e.system&&r.push({role:`system`,content:e.system});for(let t of Fl(e.history??[],Gf))r.push(Wf(t));return e.input.length>0&&r.push({role:`user`,content:Uf(e.input)}),r}function qf(e){if(e&&e.length!==0)return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters}}))}function Jf(e){return e.replace(/[^A-Za-z0-9_-]/g,`_`).slice(0,64)}function Yf(e){if(e)return{type:`json_schema`,json_schema:{name:Jf(e.id),strict:!0,schema:e.jsonSchema}}}function Xf(e){let t=Z(e.cost);if(t===void 0)return;let n=Z(Y(e.cost_details)?.upstream_inference_cost);return{usd:t,...n===void 0?{}:{upstreamUsd:n}}}function Zf(e,t){let n=Object.entries(t).flatMap(([t,n])=>{let r=Z(e?.[t]);return r===void 0?[]:[[n,r]]});return n.length>0?Object.fromEntries(n):void 0}function Qf(e,t){let n=Zf(e,{audio_tokens:`audio`,video_tokens:`video`}),r=Zf(t,{image_tokens:`image`,audio_tokens:`audio`});if(n||r)return{...n?{input:n}:{},...r?{output:r}:{}}}function $f(e){let t=Y(e);if(!t)return;let n=Y(t.prompt_tokens_details)??Y(t.input_tokens_details),r=Y(t.completion_tokens_details);return go({input:Z(t.prompt_tokens)??Z(t.input_tokens),output:Z(t.completion_tokens)??Z(t.output_tokens),thinking:Z(r?.reasoning_tokens),cached:Z(n?.cached_tokens),cacheWrite:Z(n?.cache_write_tokens),cost:Xf(t),byModality:Qf(n,r)})}function ep(e){let t=X(e.id),n=X(e.model);if(t||n)return{...t?{id:t}:{},...n?{model:n}:{}}}function tp(e){return e.flatMap(e=>Td(e)??[])}function np(e,t){let n=t.stream!==!1,r=qf(t.wireTools),i=Yf(t.structured),a={model:e.apiId,messages:Kf(t),stream:n,...n?{stream_options:{include_usage:!0}}:{},...t.temperature===void 0?{}:{temperature:t.temperature},...t.maxOutputTokens===void 0?{}:{max_tokens:t.maxOutputTokens},...t.thinking?{reasoning_effort:t.thinking}:{},...i?{response_format:i}:{},...r?{tools:r}:{}};return JSON.parse(JSON.stringify(a))}function rp(e){let t=Y(e.error);if(!t)return;let n=typeof t.code==`number`?t.code:502,r=typeof t.message==`string`?t.message:JSON.stringify(t);throw new T(It(n),r)}function ip(e,t){let n=(Array.isArray(e.annotations)?e.annotations:[]).flatMap(e=>{let n=Y(Y(e)?.url_citation);return typeof n?.url!=`string`||t.cited.has(n.url)?[]:(t.cited.add(n.url),[{title:typeof n.title==`string`&&n.title?n.title:n.url,uri:n.url,type:`web`}])});return n.length?[{type:`citation`,sources:n}]:[]}function ap(e,t){for(let[n,r]of(Array.isArray(e.tool_calls)?e.tool_calls:[]).entries()){let e=Y(r),i=Y(e?.function),a=typeof e?.index==`number`?e.index:n,o=t.calls.get(a)??{name:``,args:``};typeof e?.id==`string`&&e.id&&(o.id=e.id),typeof i?.name==`string`&&(o.name+=i.name),typeof i?.arguments==`string`&&(o.args+=i.arguments),t.calls.set(a,o)}}function op(e,t,n){let r=[],i=e.reasoning??e.reasoning_content;return typeof i==`string`&&i&&n.summaries!==`none`&&r.push({type:`thought`,text:i}),typeof e.content==`string`&&e.content&&(t.text+=e.content,r.push({type:`text`,text:e.content})),r.push(...ip(e,t)),ap(e,t),r}function sp(e,t,n,r){rp(e);let i=[],a=Su(t.response,ep(e));t.response=a.known,a.event&&i.push(a.event);let o=t.tokens?void 0:$f(e.usage);o&&(t.tokens=!0,i.push({type:`tokens`,tokens:o}));for(let a of Array.isArray(e.choices)?e.choices:[]){let e=Y(a),o=Y(r?e?.delta:e?.message);o&&i.push(...op(o,t,n)),typeof e?.finish_reason==`string`&&(t.finish=e.finish_reason),typeof e?.native_finish_reason==`string`&&(t.native=e.native_finish_reason)}if(r)for(let e of t.calls.values())i.push(...tp(wu(e)));return i}function cp(e,t){let n=[];for(let[t,r]of e.calls)n.push(...tp(zl({...r,id:r.id??`call_${t}`},r.args)));let r=fo(e.finish,e.native);if(t.structured&&e.text&&r.kind===`completed`){let t=tp([Cu(e.text)]);if(n.push(...t),t[0]?.type===`error`)return n}return n.push({type:`done`,stop:r}),n}async function*lp(e,t){let n=t.input.flatMap(e=>e.type===`text`?[e.text]:[]).join(` `).trim();if(!n)throw new T(`request`,`empty text for speech`);let r=t.speech,i={model:e.apiId,input:n,...r?.format?{response_format:r.format}:{},...r?.voice?{voice:r.voice}:{},...r?.speed===void 0?{}:{speed:r.speed},...r?.style?{instructions:r.style}:{}};for await(let t of e.send(i,{stream:!1})){let e=typeof t.mime_type==`string`?t.mime_type:``,n=typeof t.data==`string`?rt(t.data):new Uint8Array;if(!n.length)throw new T(`bad_response`,`no audio returned from speech`);let r=yu(e);yield{type:`media`,media:r?{mimeType:`audio/wav`,data:nt(bu(n,r))}:{mimeType:$i(e)||`application/octet-stream`,data:t.data}},yield{type:`done`,stop:{kind:`completed`}}}}var up=q({id:`openAi`,name:`OpenAI Chat Completions`,description:`The Chat Completions shape that OpenAI and most compatible servers speak.`,endpoints:{text:`/chat/completions`,speech:`/audio/speech`},options:i({}),create(e){return{async*complete(t){if(e.profileType===`speech`){yield*lp(e,t);return}let n=t.stream!==!1,r={text:``,tokens:!1,cited:new Set,calls:new Map};for await(let i of e.send(np(e,t),{stream:n}))yield*sp(i,r,t,n);yield*cp(r,t)}}}}),dp=Wc({id:`local`,name:`Local`,description:`A server that speaks OpenAI's chat API: Ollama, llama.cpp, vLLM, LM Studio.`,traceName:`openai`,connection:i({baseUrl:zc.describe(`Where the server listens, up to and including /v1, e.g. http://localhost:11434/v1.`)}),key:S().trim().min(1).optional(),authorize:Bc(),serves:e=>[{protocol:up,baseUrl:e.baseUrl},{protocol:dl,baseUrl:e.baseUrl,url:({path:t})=>{let n=new URL(e.baseUrl);return n.pathname=n.pathname.replace(/\/v1\/?$/,``)||`/`,new URL(t.replace(/^\/+/,``),n).toString()}}]}),fp=x().int().nonnegative(),pp=w({model:S().min(1),answers:C(S(),a()),usage:w({input_tokens:fp,output_tokens:fp,cost:x().nonnegative().optional()}).optional().catch(void 0)}),mp=i({images:_().optional().describe(`Let a decision hold images and box questions. TypeSafe calls this experimental, and a request that uses either is refused without it.`),longContext:_().optional().describe(`Raise the context window from 64k tokens to 262k. TypeSafe calls this slower and less accurate.`)}),hp=`TypeSafe-Danger-Zone-Images`,gp=`TypeSafe-Danger-Zone-Long-Context`,_p=q({id:`systemOne`,name:`System One`,description:`TypeSafe's decision API: questions about a state, answered in one call.`,endpoints:{decision:`/systemone`},options:mp,create(e){return{async decide(t){let n=Object.values(t.questions).some(({type:e})=>e===`box`),r=n||t.assets&&Object.keys(t.assets).length>0;if(r&&!e.options.images)throw new T(`unsupported`,O(`provider.decision_images_off`));if(n&&/^jev-1\.13(\.|$)/.test(e.apiId))throw new T(`unsupported`,O(`provider.decision_box_model`,{apiId:e.apiId}));let i={};r&&(i[hp]=`true`),e.options.longContext&&(i[gp]=`true`);let a=L.parse({model:e.apiId,state:t.state,questions:t.questions,...t.assets&&Object.keys(t.assets).length?{assets:
|
|
6
|
-
`).trim()}function Ep(e){let t=e.toLowerCase().replace(/^image\//,``);return t===`jpg`?`jpeg`:t===`png`||t===`jpeg`||t===`webp`?t:`png`}var Dp=/^https?:\/\//i;function Op(e){return{type:`image_url`,image_url:{url:Ca(e)?e.uri:`data:${e.mimeType};base64,${e.data}`}}}function kp(e){let t=[];for(let n of e)if(n.type!==`text`){if(n.type!==`image`)throw new T(`unsupported`,`${n.mimeType} input is not supported on /images, which takes image references only`);if(Ca(n)&&!Dp.test(n.uri))throw new T(`unsupported`,`only http(s) media references are supported on /images`);t.push(Op(n))}return t}function Ap(e,t){t.aspectRatio&&(e.aspect_ratio=t.aspectRatio),t.resolution&&(e.resolution=t.resolution),t.mimeType&&(e.output_format=Ep(t.mimeType)),t.quality&&(e.quality=t.quality),t.background&&(e.background=t.background),t.n!==void 0&&(e.n=t.n),t.seed!==void 0&&(e.seed=t.seed),t.outputCompression!==void 0&&(e.output_compression=t.outputCompression)}function jp(e){if(!e.image)throw Error(`buildImagesPayload requires req.image`);let t={model:e.apiId,prompt:Tp(e.input)};Ap(t,e.image);let n=kp(e.input);return n.length>0&&(t.input_references=n),e.stream===!1&&(t.stream=!1),t}function Mp(e){let t={};e.mimeType&&(t.output_format=Ep(e.mimeType)),e.aspectRatio&&(t.aspect_ratio=e.aspectRatio),e.resolution&&(t.resolution=e.resolution),e.quality&&(t.quality=e.quality),e.background&&(t.background=e.background),e.outputCompression!==void 0&&(t.output_compression=e.outputCompression);for(let[t,n]of[[`n`,e.n],[`seed`,e.seed]])if(n!==void 0)throw new T(`unsupported`,`image.${t} is not supported with image.includeText`);return t}function Np(e){return JSON.parse(JSON.stringify(e))}function Pp(e){let t=$f(e.usage);return t?[{type:`tokens`,tokens:t}]:[]}function Fp(){return new T(`bad_response`,`no image returned from image generation`)}async function*Ip(e,t){let n=Np(jp({...t,apiId:e.apiId}));for await(let t of e.send(n,{stream:!1})){let e=Sp(t);if(!e.length)throw Fp();for(let t of e)yield{type:`media`,media:t};yield*Pp(t),yield{type:`done`,stop:{kind:`completed`}}}}async function*Lp(e,t,n){let r=Np({model:e.apiId,stream:!1,provider:{require_parameters:!0},messages:Kf(t),temperature:t.temperature,max_tokens:t.maxOutputTokens,...t.thinking?{reasoning:{effort:t.thinking}}:{},tools:[{type:xp,parameters:Mp(n)}]});for await(let t of e.send(r,{stream:!1,path:`/chat/completions`})){let e=Y(Array.isArray(t.choices)?t.choices[0]:void 0),n=Y(e?.message),r=X(n?.content);r&&(yield{type:`text`,text:r});let i=n?wp(n):[];if(!i.length)throw Fp();for(let e of i)yield{type:`media`,media:e};yield*Pp(t),yield{type:`done`,stop:fo(typeof e?.finish_reason==`string`?e.finish_reason:void 0,typeof e?.native_finish_reason==`string`?e.native_finish_reason:void 0)}}}var Rp=q({id:`openRouterImages`,name:`OpenRouter Images`,description:`OpenRouter's image generation, with or without text beside the picture.`,endpoints:{image:`/images`},options:i({}),create(e){return{complete(t){let n=t.image;if(!n)throw new T(`request`,`missing image response format`);if(!Tp(t.input))throw new T(`request`,`empty text for image generation`);return n.includeText?Lp(e,t,n):Ip(e,t)}}}});function zp(e,t){let n=``;for(let r of Array.isArray(e.choices)?e.choices:[]){if(!M(r))continue;let e=M(r.delta)?r.delta:M(r.message)?r.message:void 0;if(e){typeof e.reasoning==`string`?n+=e.reasoning:typeof e.reasoning_content==`string`&&(n+=e.reasoning_content);for(let n of Array.isArray(e.reasoning_details)?e.reasoning_details:[]){let e=L.parse(n),r=JSON.stringify([e.index??e.id??t.size,e.type]),i=t.get(r),a={...i,...e};for(let t of[`text`,`summary`,`data`])i&&typeof i[t]==`string`&&typeof e[t]==`string`&&(a[t]=i[t]+e[t]);t.set(r,a)}}}return n}var Bp=i({mode:b(Bn).describe("What is cached: the whole request (`automatic`) or the system instruction only (`system`)."),ttl:b(Vn).optional().describe(`How long the cache is kept. Absent: the upstream default.`)}).describe(`Prompt caching, for models that support it.`),Vp=i({details:y(L),content:S().optional()});function Hp(e){return e.ttl?{type:`ephemeral`,ttl:e.ttl}:{type:`ephemeral`}}function Up(e){let t=Y(e)?.tool_calls;return Array.isArray(t)?t.map(e=>String(Y(e)?.id)):[]}function Wp(e,t){for(let n of e){let e=Up(n);if(n.role!==`assistant`||!e.length)continue;let r=(t.find(t=>t.role===`assistant`&&JSON.stringify((t.tool_calls??[]).map(e=>e.id))===JSON.stringify(e))?.reasoning??[]).map(e=>Vp.safeParse(e.data)).find(e=>e.success);r?.success&&(n.reasoning_details=r.data.details,r.data.content&&(n.reasoning=r.data.content))}}function Gp(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function Kp(e){let t=e=>[e?.citations,Y(e?.providerMetadata)?.citations,Y(e?.provider_metadata)?.citations],n=Y(e.openrouter),r=Array.isArray(e.choices)?e.choices.map(Y):[];return[...t(e),...t(n),...t(Y(n?.providerMetadata)),...t(Y(n?.provider_metadata)),...r.flatMap(e=>[...t(Y(e?.message)),...t(Y(e?.delta))])].flatMap(Gp)}function qp(e){let t=Array.isArray(e.choices)?e.choices.map(Y):[];return[e.annotations,Y(e.openrouter)?.annotations,...t.flatMap(e=>[Y(e?.message)?.annotations,Y(e?.delta)?.annotations])].flatMap(e=>Array.isArray(e)?e:[]).filter(e=>Y(e)?.type!==`url_citation`)}function Jp(e){return(Array.isArray(e.choices)?e.choices:[]).map(e=>Y(Y(e)?.delta)?.thinking).filter(e=>typeof e==`string`).join(``)}var Yp=Ba(up,{id:`openRouterOpenAi`,name:`OpenRouter Chat Completions`,description:`Chat Completions with OpenRouter's caching, routing, web search, citations and reasoning.`,options:i({cache:Bp.optional()}),reasoning:Vp,body(e,t){if(t.profileType!==`text`)return{body:e};let n={...e,provider:{require_parameters:!0}};n.reasoning_effort!==void 0&&(n.reasoning={effort:n.reasoning_effort},delete n.reasoning_effort);let r=Array.isArray(n.messages)?n.messages:[],i=t.options.cache;i?.mode===`automatic`&&(n.cache_control=Hp(i)),i?.mode===`system`&&r[0]?.role===`system`&&(r[0]={...r[0],content:[{type:`text`,text:r[0].content??``,cache_control:Hp(i)}]}),Wp(r,t.request?.history??[]),t.request?.sessionId&&(n.session_id=t.request.sessionId);let a=t.builtInTools.includes(`webSearch`);return a&&(n.web_search_options={}),{body:{...n,messages:r},wroteTools:a?[`webSearch`]:[]}},read(e){let t=new Map,n=new Set,r=new Set,i=``;return{row(a){i+=zp(a,t);let o=[],s=Jp(a);s&&e.request?.summaries!==`none`&&o.push({type:`thought`,text:s});let c=Kp(a).filter(e=>!n.has(e)&&n.add(e)).map(e=>({title:e,uri:e,type:`web`}));c.length&&o.push({type:`citation`,sources:c});let l=qp(a).filter(e=>{let t=JSON.stringify(e);return!r.has(t)&&r.add(t)});return l.length&&o.push({type:`evidence`,evidence:{provider:`openrouter`,kind:`provider_step`,step:`annotations`,raw:{annotations:l}}}),{events:o}},finish(){return!t.size&&!i?{}:{events:[{type:`reasoning`,data:{details:[...t.values()],...i?{content:i}:{}}}]}}}}}),Xp=Wc({id:`openrouter`,name:`OpenRouter`,description:`Many labs' models behind one key.`,connection:i({baseUrl:zc.optional().describe(`The API, by default https://openrouter.ai/api/v1.`),decisionUrl:zc.optional().describe(`The decision API, by default https://openrouter.ai/api/alpha/decisions.`),siteUrl:S().trim().min(1).optional().describe(`Sent as HTTP-Referer, for OpenRouter rankings.`),siteName:S().trim().min(1).optional().describe(`Sent as X-Title, for OpenRouter rankings.`)}).default({}),key:S().trim().min(1),authorize:Bc(),serves(e){let t=e.baseUrl??`https://openrouter.ai/api/v1`,n={};e.siteUrl&&(n[`HTTP-Referer`]=e.siteUrl),e.siteName&&(n[`X-Title`]=e.siteName);let r=e.decisionUrl??`https://openrouter.ai/api/alpha/decisions`;return[{protocol:Yp,baseUrl:t,headers:n},{protocol:gl,baseUrl:t,headers:n},{protocol:Rp,baseUrl:t,headers:n},{protocol:bp,baseUrl:r,url:()=>r,headers:n}]}}),Zp=Wc({id:`typesafe`,name:`TypeSafe`,description:`System One decisions, at TypeSafe's own API.`,connection:i({baseUrl:zc.optional().describe(`The API, by default https://api.typesafe.ai/v1.`)}).default({}),key:S().trim().min(1),authorize:Bc(),prices:{checked:`2026-10-19`,models:{"jev-*":{input:.042,output:0}}},serves:e=>[{protocol:_p,baseUrl:e.baseUrl??`https://api.typesafe.ai/v1`}]}),Qp=`local`;function $p(e,t){return!t&&e===`local`}function em(e=`http://localhost:11434`){return`${e.replace(/\/$/,``)}/v1`}var tm=[{id:`gemini`,definition:`gemini`},{id:`openrouter`,definition:`openrouter`},{id:Qp,definition:`local`,connection:{baseUrl:em()}},{id:`typesafe`,definition:`typesafe`}],nm={gemini:{provider:Bf,factory:`geminiProvider`},openrouter:{provider:Xp,factory:`openRouterProvider`},local:{provider:dp,factory:`localProvider`},typesafe:{provider:Zp,factory:`typesafeProvider`}};function rm(e){return e===void 0?void 0:nm[e]?.provider}function im(){return Object.keys(nm)}function am(e){return Object.keys(nm).find(t=>nm[t]?.factory===e)}function om(e){return nm[e]?.factory}function sm(e,t){return e.find(e=>e.id===t)?.definition}function cm(e){return{id:e.id,...e.connection===void 0?{}:{connection:e.connection},...e.keySlot===void 0?{}:{keySlot:e.keySlot},...e.fallbackKeySlot===void 0?{}:{fallbackKeySlot:e.fallbackKeySlot}}}function lm(e,t,n=rm(t.definition),r=`register`){if(!n)throw Error(`The studio does not hold the provider definition '${t.definition}'.`);return e[r](n,cm(t))}function um(e){let t=rm(e);if(!t)return;if(!t.connection)return[];let n=h(t.connection,{io:`input`});return Object.entries(n.properties??{}).map(([e,t])=>({name:e,required:n.required?.includes(e)??!1,url:t.format===`uri`,...t.description?{description:t.description}:{}}))}function dm(e){let t=rm(e);return t===void 0||t.key!==void 0}function fm(e){let t=[];e.id.trim()||t.push({field:`id`,message:`Provider id is required.`});let n=rm(e.definition),r=e.connection??{},i=n?.connection?.safeParse(r);for(let e of i?.error?.issues??[]){if(e.code===`unrecognized_keys`){for(let n of e.keys)t.push({field:`connection.${n}`,message:`This provider takes no '${n}'.`});continue}let n=e.path[0];if(typeof n!=`string`){t.push({message:e.message});continue}let i=n in r?e.message:`${n} is required.`;t.push({field:`connection.${n}`,message:i})}for(let n of[`keySlot`,`fallbackKeySlot`]){let r=e[n];r!==void 0&&!Ha.safeParse(r).success&&t.push({field:n,message:`A key slot is 1 to 32 letters, digits, hyphens, or underscores.`})}return e.keySlot&&e.keySlot===e.fallbackKeySlot&&t.push({field:`fallbackKeySlot`,message:O(`provider.fallback_slot`)}),(e.keySlot||e.fallbackKeySlot)&&n&&!n.key&&t.push({field:`keySlot`,message:O(`protocol.no_key`,{provider:e.id})}),t}function pm(e,t){return Ka(e.find(e=>e.id===t.provider)??{},{...t.keySlot?{keySlot:t.keySlot}:{},...t.fallbackKeySlot?{fallbackKeySlot:t.fallbackKeySlot}:{}})}function mm(e,t){let n=rm(e.definition);if(!n)return;let r;try{r=lm(Kc(),e,n)}catch{return[]}return r.serves.map(e=>e.protocol).filter(e=>t===void 0||e.endpoints[t]!==void 0)}function hm(e,t,n){if(!e)return!1;let r=mm(e,t);return r===void 0?!0:n===void 0?r.length>0:r.some(e=>e.id===n)}function gm(e,t,n){if(!_m(t))throw Error(`Cannot create a model route without a profile type.`);return{profileType:t,protocol:n.protocol,provider:n.provider,definition:sm(e,n.provider),apiId:n.apiId,decision:t===`decision`}}function _m(e){return[`text`,`image`,`speech`,`live`,`decision`,`embedding`].includes(e)}function vm(e,t){let n=ym(h(e.options,{io:`input`,unrepresentable:`any`}),``,!0),r=t?e.refusedOptions?.(t.apiId.trim())??[]:[];return n.filter(e=>{let n=e.path.split(`.`)[0]??e.path;return!r.includes(n)||t?.options[n]!==void 0})}function ym(e,t,n){return Object.entries(e.properties??{}).flatMap(([r,i])=>{let a=t?`${t}.${r}`:r,o=n&&(e.required?.includes(r)??!1);if(i.type===`object`&&i.properties)return ym(i,a,o);let s={path:a,label:bm(r),required:o,...i.description?{description:i.description}:{}},c=i.anyOf?.filter(e=>typeof e.const==`string`||typeof e.const==`number`),l=c?.map(e=>e.const);if(i.enum?.every(e=>typeof e==`string`))return[{...s,kind:`choice`,choices:i.enum.map(e=>({value:e}))}];if(l&&l.length===i.anyOf?.length&&l.length>0){let e=l.every(e=>typeof e==`number`);if(e||l.every(e=>typeof e==`string`))return[{...s,kind:`choice`,choices:(c??[]).map(e=>({value:String(e.const),...e.title?{label:e.title}:{},...e.description?{description:e.description}:{}})),...e?{choiceType:`number`}:{}}]}return i.type===`boolean`?[{...s,kind:`boolean`}]:i.type===`string`?[{...s,kind:`text`}]:i.type===`number`||i.type===`integer`?[{...s,kind:`number`}]:[]})}function bm(e){let t=e.replace(/([a-z0-9])([A-Z])/g,`$1 $2`).toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}function xm(e,t){return t.split(`.`).reduce((e,t)=>e&&typeof e==`object`&&!Array.isArray(e)?e[t]:void 0,e)}function Sm(e,t,n){let[r=``,...i]=t.split(`.`),{[r]:a,...o}=e,s=i.length?Sm(a&&typeof a==`object`&&!Array.isArray(a)?a:{},i.join(`.`),n):n;return s===void 0||typeof s==`object`&&s&&!Array.isArray(s)&&!Object.keys(s).length?o:{...o,[r]:s}}var Cm=`studio`,wm={"observability.writeTo":Cm};function Tm(e){return Object.entries(wm).reduce((e,[t,n])=>Em(e,t.split(`.`),n),e)}function Em(e,[t,...n],r){if(t===void 0||!Object.hasOwn(e,t))return e;let i=e[t];if(!n.length)return i===r?Object.fromEntries(Object.entries(e).filter(([e])=>e!==t)):e;if(typeof i!=`object`||!i||Array.isArray(i))return e;let a=Em(i,n,r);return a===i?e:Object.fromEntries(Object.entries(e).flatMap(([e,n])=>e===t?Object.keys(a).length?[[e,a]]:[]:[[e,n]]))}var Dm=new Set(Qc.map(e=>e.name));function Om(e){return e.protocol===Ad.id||e.protocol===Ff.id}function km(e){return e.protocol===Yp.id||e.protocol===Rp.id}function Am(e){return Dm.has(e)}function jm(e,t,n){return n.mode===`demo`?n.keys.runs(e,t?.definition):hm(t,e)}var Mm={text:`fast`,image:`image`,speech:`voice`,live:`live`,decision:`decision`,embedding:`embedding`};function Nm(e,t){let n=t?.(e)??{...Pm(e===`decision`?`typesafe`:`gemini`,e),apiId:``};return{modelId:Mm[e],...n}}function Pm(e,t){let n=tm.find(t=>t.id===e),r=n&&mm(n,t)?.[0];if(!r)throw Error(`The studio provider '${e}' serves no ${t} agents.`);return{protocol:r.id,provider:e}}function Fm(e,t){return t.mode===`demo`?t.keys.violation(e):t.mode===`local`&&e.provider!==`local`?{field:`provider`,message:`Local runs require local models. Switch the model provider to Local.`}:null}var Im=5,Lm=100,Rm=120;function zm(e){let t=Array.isArray(e.type)?e.type.find(e=>e!==`null`):e.type;return t===`string`||t===`number`||t===`integer`||t===`boolean`||t===`array`?t:t===`object`||A(e.properties)?`object`:Array.isArray(e.enum)?`string`:`unknown`}function Bm(e){return A(e.items)?e.items:void 0}function Vm(e){let t=e?.enum;return Array.isArray(t)&&t.length>0&&t.every(e=>typeof e==`string`)?t:void 0}function Hm(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function Um(e,t){let n=Hm(e,`minimum`),r=Hm(e,`maximum`);return t&&n!==void 0&&r!==void 0&&r>n&&r-n<=Lm?{kind:`range`,min:n,max:r}:{kind:`number`,isInteger:t,...n===void 0?{}:{min:n},...r===void 0?{}:{max:r}}}function Wm(e){if(e.format===`date`)return{kind:`date`};let t=Hm(e,`maxLength`);return{kind:`text`,isLong:t!==void 0&&t>Rm,type:e.format===`email`?`email`:`text`}}function Gm(e){let t=Bm(e),n=Vm(t);if(n)return{kind:`choices`,options:n};let r=t?zm(t):`unknown`;return r===`string`||r===`number`||r===`integer`?{kind:`words`}:t&&r===`object`?{kind:`rows`,item:t}:{kind:`json`}}function Km(e){let t=Vm(e);if(t)return{kind:`choice`,options:t,isMenu:t.length>Im};switch(zm(e)){case`boolean`:return{kind:`switch`};case`number`:return Um(e,!1);case`integer`:return Um(e,!0);case`string`:return Wm(e);case`array`:return Gm(e);case`object`:return A(e.properties)?{kind:`group`,schema:e}:{kind:`json`};default:return{kind:`json`}}}function qm(e){return new Set(Array.isArray(e.required)?e.required.filter(e=>typeof e==`string`):[])}function Jm(e){let t=A(e.properties)?e.properties:{},n=qm(e);return Object.entries(t).flatMap(([e,t])=>A(t)?[{key:e,label:typeof t.title==`string`&&t.title?t.title:Ze(e),...typeof t.description==`string`&&t.description?{description:t.description}:{},isRequired:n.has(e),control:Km(t)}]:[])}function Ym(e){if(Array.isArray(e.examples)&&e.examples.length)return{value:e.examples[0]};if(`default`in e)return{value:e.default};if(`const`in e)return{value:e.const};if(Array.isArray(e.enum)&&e.enum.length)return{value:e.enum[0]}}function Xm(e){let t=Ym(e);if(t)return t.value;switch(zm(e)){case`number`:case`integer`:return Hm(e,`minimum`)??1;case`boolean`:return!0;case`array`:return[];case`object`:return Zm(e);case`string`:case`unknown`:return`example`}}function Zm(e){let t=A(e.properties)?e.properties:{},n=new Set(qm(e)),r={};for(let[e,i]of Object.entries(t))A(i)&&(n.has(e)?r[e]=Xm(i):Array.isArray(i.examples)&&i.examples.length&&(r[e]=i.examples[0]));return r}function Qm(e){return Zm(e)}function $m(e,t,n){let r={...e};return n===void 0||n===``?delete r[t]:r[t]=n,r}function eh(e,t,n=``){return A(t)?Jm(e).flatMap(e=>{let r=t[e.key],i=n?`${n} › ${e.label}`:e.label;return r==null||r===``?e.isRequired?[i]:[]:e.control.kind===`group`?eh(e.control.schema,r,i):[]}):[]}var th=`{
|
|
5
|
+
`):e.map(e=>e.type===`text`?{type:`text`,text:e.text}:(Vf(e),e.type===`image`?{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}}:e.type===`audio`?Hf(e):{type:`file`,file:{filename:e.type===`video`?`clip.bin`:`document.bin`,file_data:`data:${e.mimeType};base64,${e.data}`}}))}function Wf(e){let t=Uf(K(e));if(e.role===`tool`)return{role:`tool`,...Il({tool_call_id:e.tool_call_id,name:e.name}),content:t};let n={role:e.role,content:t};return e.tool_calls&&e.tool_calls.length>0&&(n.tool_calls=e.tool_calls.map(e=>({id:e.id,type:`function`,function:{name:e.function.name,arguments:e.function.arguments}}))),e.name&&(n.name=e.name),n}var Gf=new Set([`text`,`image`]);function Kf(e,t){let n=t?.includeSystem!==!1,r=[];n&&e.system&&r.push({role:`system`,content:e.system});for(let t of Fl(e.history??[],Gf))r.push(Wf(t));return e.input.length>0&&r.push({role:`user`,content:Uf(e.input)}),r}function qf(e){if(e&&e.length!==0)return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters}}))}function Jf(e){return e.replace(/[^A-Za-z0-9_-]/g,`_`).slice(0,64)}function Yf(e){if(e)return{type:`json_schema`,json_schema:{name:Jf(e.id),strict:!0,schema:e.jsonSchema}}}function Xf(e){let t=Z(e.cost);if(t===void 0)return;let n=Z(Y(e.cost_details)?.upstream_inference_cost);return{usd:t,...n===void 0?{}:{upstreamUsd:n}}}function Zf(e,t){let n=Object.entries(t).flatMap(([t,n])=>{let r=Z(e?.[t]);return r===void 0?[]:[[n,r]]});return n.length>0?Object.fromEntries(n):void 0}function Qf(e,t){let n=Zf(e,{audio_tokens:`audio`,video_tokens:`video`}),r=Zf(t,{image_tokens:`image`,audio_tokens:`audio`});if(n||r)return{...n?{input:n}:{},...r?{output:r}:{}}}function $f(e){let t=Y(e);if(!t)return;let n=Y(t.prompt_tokens_details)??Y(t.input_tokens_details),r=Y(t.completion_tokens_details);return go({input:Z(t.prompt_tokens)??Z(t.input_tokens),output:Z(t.completion_tokens)??Z(t.output_tokens),thinking:Z(r?.reasoning_tokens),cached:Z(n?.cached_tokens),cacheWrite:Z(n?.cache_write_tokens),cost:Xf(t),byModality:Qf(n,r)})}function ep(e){let t=X(e.id),n=X(e.model);if(t||n)return{...t?{id:t}:{},...n?{model:n}:{}}}function tp(e){return e.flatMap(e=>Td(e)??[])}function np(e,t){let n=t.stream!==!1,r=qf(t.wireTools),i=Yf(t.structured),a={model:e.apiId,messages:Kf(t),stream:n,...n?{stream_options:{include_usage:!0}}:{},...t.temperature===void 0?{}:{temperature:t.temperature},...t.maxOutputTokens===void 0?{}:{max_tokens:t.maxOutputTokens},...t.thinking?{reasoning_effort:t.thinking}:{},...i?{response_format:i}:{},...r?{tools:r}:{}};return JSON.parse(JSON.stringify(a))}function rp(e){let t=Y(e.error);if(!t)return;let n=typeof t.code==`number`?t.code:502,r=typeof t.message==`string`?t.message:JSON.stringify(t);throw new T(It(n),r)}function ip(e,t){let n=(Array.isArray(e.annotations)?e.annotations:[]).flatMap(e=>{let n=Y(Y(e)?.url_citation);return typeof n?.url!=`string`||t.cited.has(n.url)?[]:(t.cited.add(n.url),[{title:typeof n.title==`string`&&n.title?n.title:n.url,uri:n.url,type:`web`}])});return n.length?[{type:`citation`,sources:n}]:[]}function ap(e,t){for(let[n,r]of(Array.isArray(e.tool_calls)?e.tool_calls:[]).entries()){let e=Y(r),i=Y(e?.function),a=typeof e?.index==`number`?e.index:n,o=t.calls.get(a)??{name:``,args:``};typeof e?.id==`string`&&e.id&&(o.id=e.id),typeof i?.name==`string`&&(o.name+=i.name),typeof i?.arguments==`string`&&(o.args+=i.arguments),t.calls.set(a,o)}}function op(e,t,n){let r=[],i=e.reasoning??e.reasoning_content;return typeof i==`string`&&i&&n.summaries!==`none`&&r.push({type:`thought`,text:i}),typeof e.content==`string`&&e.content&&(t.text+=e.content,r.push({type:`text`,text:e.content})),r.push(...ip(e,t)),ap(e,t),r}function sp(e,t,n,r){rp(e);let i=[],a=Su(t.response,ep(e));t.response=a.known,a.event&&i.push(a.event);let o=t.tokens?void 0:$f(e.usage);o&&(t.tokens=!0,i.push({type:`tokens`,tokens:o}));for(let a of Array.isArray(e.choices)?e.choices:[]){let e=Y(a),o=Y(r?e?.delta:e?.message);o&&i.push(...op(o,t,n)),typeof e?.finish_reason==`string`&&(t.finish=e.finish_reason),typeof e?.native_finish_reason==`string`&&(t.native=e.native_finish_reason)}if(r)for(let e of t.calls.values())i.push(...tp(wu(e)));return i}function cp(e,t){let n=[];for(let[t,r]of e.calls)n.push(...tp(zl({...r,id:r.id??`call_${t}`},r.args)));let r=fo(e.finish,e.native);if(t.structured&&e.text&&r.kind===`completed`){let t=tp([Cu(e.text)]);if(n.push(...t),t[0]?.type===`error`)return n}return n.push({type:`done`,stop:r}),n}async function*lp(e,t){let n=t.input.flatMap(e=>e.type===`text`?[e.text]:[]).join(` `).trim();if(!n)throw new T(`request`,`empty text for speech`);let r=t.speech,i={model:e.apiId,input:n,...r?.format?{response_format:r.format}:{},...r?.voice?{voice:r.voice}:{},...r?.speed===void 0?{}:{speed:r.speed},...r?.style?{instructions:r.style}:{}};for await(let t of e.send(i,{stream:!1})){let e=typeof t.mime_type==`string`?t.mime_type:``,n=typeof t.data==`string`?rt(t.data):new Uint8Array;if(!n.length)throw new T(`bad_response`,`no audio returned from speech`);let r=yu(e);yield{type:`media`,media:r?{mimeType:`audio/wav`,data:nt(bu(n,r))}:{mimeType:$i(e)||`application/octet-stream`,data:t.data}},yield{type:`done`,stop:{kind:`completed`}}}}var up=q({id:`openAi`,name:`OpenAI Chat Completions`,description:`The Chat Completions shape that OpenAI and most compatible servers speak.`,endpoints:{text:`/chat/completions`,speech:`/audio/speech`},options:i({}),create(e){return{async*complete(t){if(e.profileType===`speech`){yield*lp(e,t);return}let n=t.stream!==!1,r={text:``,tokens:!1,cited:new Set,calls:new Map};for await(let i of e.send(np(e,t),{stream:n}))yield*sp(i,r,t,n);yield*cp(r,t)}}}}),dp=Wc({id:`local`,name:`Local`,description:`A server that speaks OpenAI's chat API: Ollama, llama.cpp, vLLM, LM Studio.`,traceName:`openai`,connection:i({baseUrl:zc.describe(`Where the server listens, up to and including /v1, e.g. http://localhost:11434/v1.`)}),key:S().trim().min(1).optional(),authorize:Bc(),serves:e=>[{protocol:up,baseUrl:e.baseUrl},{protocol:dl,baseUrl:e.baseUrl,url:({path:t})=>{let n=new URL(e.baseUrl);return n.pathname=n.pathname.replace(/\/v1\/?$/,``)||`/`,new URL(t.replace(/^\/+/,``),n).toString()}}]}),fp=x().int().nonnegative(),pp=w({model:S().min(1),answers:C(S(),a()),usage:w({input_tokens:fp,output_tokens:fp,cost:x().nonnegative().optional()}).optional().catch(void 0)}),mp=i({images:_().optional().describe(`Let a decision hold images and box questions. TypeSafe calls this experimental, and a request that uses either is refused without it.`),longContext:_().optional().describe(`Raise the context window from 64k tokens to 262k. TypeSafe calls this slower and less accurate.`)}),hp=`TypeSafe-Danger-Zone-Images`,gp=`TypeSafe-Danger-Zone-Long-Context`,_p=q({id:`systemOne`,name:`System One`,description:`TypeSafe's decision API: questions about a state, answered in one call.`,endpoints:{decision:`/systemone`},options:mp,create(e){return{async decide(t){let n=Object.values(t.questions).some(({type:e})=>e===`box`),r=n||t.assets&&Object.keys(t.assets).length>0;if(r&&!e.options.images)throw new T(`unsupported`,O(`provider.decision_images_off`));if(n&&/^jev-1\.13(\.|$)/.test(e.apiId))throw new T(`unsupported`,O(`provider.decision_box_model`,{apiId:e.apiId}));let i={};r&&(i[hp]=`true`),e.options.longContext&&(i[gp]=`true`);let a=L.parse({model:e.apiId,state:t.state,questions:t.questions,...t.assets&&Object.keys(t.assets).length?{assets:bp(t.assets)}:{}});return await vp(`systemOne`,e.send(a,{stream:!1,headers:i}))}}}});async function vp(e,t){for await(let n of t){let t=pp.safeParse(n);if(!t.success)throw new T(`bad_response`,O(`protocol.reply_shape`,{protocol:e,issues:Fe(t.error)}));let{model:r,answers:i,usage:a}=t.data;return{model:r,answers:i,...a?{usage:{inputTokens:a.input_tokens,outputTokens:a.output_tokens,...a.cost===void 0?{}:{costUsd:a.cost}}}:{}}}throw new T(`bad_response`,O(`provider.decision_failed`))}var yp={"image/png":`png`,"image/jpeg":`jpeg`};function bp(e){return Object.fromEntries(Object.entries(e).map(([e,{mimeType:t,data:n}])=>[e,{type:`image`,format:yp[t],data_base64:n}]))}var xp=q({id:`openRouterDecisions`,name:`OpenRouter Decisions`,description:`OpenRouter's decision API: questions about a state, answered in one call.`,endpoints:{decision:`/alpha/decisions`},options:i({}),create(e){return{decide(t){let n=t.assets??{},r=L.parse({model:e.apiId,state:Sp(t.state,n),questions:Object.fromEntries(Object.entries(t.questions).map(([e,t])=>[e,{...t,instructions:Sp(t.instructions,n),...`criteria`in t&&t.criteria!==void 0?{criteria:Sp(t.criteria,n)}:{}}]))});return vp(`openRouterDecisions`,e.send(r,{stream:!1}))}}}});function Sp(e,t){if(typeof e==`string`){let n=t[e];return n?[e,{type:`image_url`,image_url:{url:`data:${n.mimeType};base64,${n.data}`}}]:e}return Array.isArray(e)?e.map(e=>Sp(e,t)):typeof e==`object`&&e?Object.fromEntries(Object.entries(e).map(([e,n])=>[e,Sp(n,t)])):e}var Cp=`openrouter:image_generation`;function wp(e){return(Array.isArray(e.data)?e.data:[]).flatMap(e=>{let t=Y(e),n=X(t?.b64_json),r=X(t?.media_type);return n&&r?[{mimeType:r,data:n}]:[]})}function Tp(e){if(typeof e!=`string`)return;let t=/^data:([^;,]+);base64,(.+)$/s.exec(e);if(t?.[1]&&t[2])return{mimeType:t[1],data:t[2]}}function Ep(e){return(Array.isArray(e.images)?e.images:[]).flatMap(e=>{let t=Tp(Y(Y(e)?.image_url)?.url);return t?[t]:[]})}function Dp(e){return e.filter(e=>e.type===`text`).map(e=>e.type===`text`?e.text:``).join(`
|
|
6
|
+
`).trim()}function Op(e){let t=e.toLowerCase().replace(/^image\//,``);return t===`jpg`?`jpeg`:t===`png`||t===`jpeg`||t===`webp`?t:`png`}var kp=/^https?:\/\//i;function Ap(e){return{type:`image_url`,image_url:{url:Ca(e)?e.uri:`data:${e.mimeType};base64,${e.data}`}}}function jp(e){let t=[];for(let n of e)if(n.type!==`text`){if(n.type!==`image`)throw new T(`unsupported`,`${n.mimeType} input is not supported on /images, which takes image references only`);if(Ca(n)&&!kp.test(n.uri))throw new T(`unsupported`,`only http(s) media references are supported on /images`);t.push(Ap(n))}return t}function Mp(e,t){t.aspectRatio&&(e.aspect_ratio=t.aspectRatio),t.resolution&&(e.resolution=t.resolution),t.mimeType&&(e.output_format=Op(t.mimeType)),t.quality&&(e.quality=t.quality),t.background&&(e.background=t.background),t.n!==void 0&&(e.n=t.n),t.seed!==void 0&&(e.seed=t.seed),t.outputCompression!==void 0&&(e.output_compression=t.outputCompression)}function Np(e){if(!e.image)throw Error(`buildImagesPayload requires req.image`);let t={model:e.apiId,prompt:Dp(e.input)};Mp(t,e.image);let n=jp(e.input);return n.length>0&&(t.input_references=n),e.stream===!1&&(t.stream=!1),t}function Pp(e){let t={};e.mimeType&&(t.output_format=Op(e.mimeType)),e.aspectRatio&&(t.aspect_ratio=e.aspectRatio),e.resolution&&(t.resolution=e.resolution),e.quality&&(t.quality=e.quality),e.background&&(t.background=e.background),e.outputCompression!==void 0&&(t.output_compression=e.outputCompression);for(let[t,n]of[[`n`,e.n],[`seed`,e.seed]])if(n!==void 0)throw new T(`unsupported`,`image.${t} is not supported with image.includeText`);return t}function Fp(e){return JSON.parse(JSON.stringify(e))}function Ip(e){let t=$f(e.usage);return t?[{type:`tokens`,tokens:t}]:[]}function Lp(){return new T(`bad_response`,`no image returned from image generation`)}async function*Rp(e,t){let n=Fp(Np({...t,apiId:e.apiId}));for await(let t of e.send(n,{stream:!1})){let e=wp(t);if(!e.length)throw Lp();for(let t of e)yield{type:`media`,media:t};yield*Ip(t),yield{type:`done`,stop:{kind:`completed`}}}}async function*zp(e,t,n){let r=Fp({model:e.apiId,stream:!1,provider:{require_parameters:!0},messages:Kf(t),temperature:t.temperature,max_tokens:t.maxOutputTokens,...t.thinking?{reasoning:{effort:t.thinking}}:{},tools:[{type:Cp,parameters:Pp(n)}]});for await(let t of e.send(r,{stream:!1,path:`/chat/completions`})){let e=Y(Array.isArray(t.choices)?t.choices[0]:void 0),n=Y(e?.message),r=X(n?.content);r&&(yield{type:`text`,text:r});let i=n?Ep(n):[];if(!i.length)throw Lp();for(let e of i)yield{type:`media`,media:e};yield*Ip(t),yield{type:`done`,stop:fo(typeof e?.finish_reason==`string`?e.finish_reason:void 0,typeof e?.native_finish_reason==`string`?e.native_finish_reason:void 0)}}}var Bp=q({id:`openRouterImages`,name:`OpenRouter Images`,description:`OpenRouter's image generation, with or without text beside the picture.`,endpoints:{image:`/images`},options:i({}),create(e){return{complete(t){let n=t.image;if(!n)throw new T(`request`,`missing image response format`);if(!Dp(t.input))throw new T(`request`,`empty text for image generation`);return n.includeText?zp(e,t,n):Rp(e,t)}}}});function Vp(e,t){let n=``;for(let r of Array.isArray(e.choices)?e.choices:[]){if(!M(r))continue;let e=M(r.delta)?r.delta:M(r.message)?r.message:void 0;if(e){typeof e.reasoning==`string`?n+=e.reasoning:typeof e.reasoning_content==`string`&&(n+=e.reasoning_content);for(let n of Array.isArray(e.reasoning_details)?e.reasoning_details:[]){let e=L.parse(n),r=JSON.stringify([e.index??e.id??t.size,e.type]),i=t.get(r),a={...i,...e};for(let t of[`text`,`summary`,`data`])i&&typeof i[t]==`string`&&typeof e[t]==`string`&&(a[t]=i[t]+e[t]);t.set(r,a)}}}return n}var Hp=i({mode:b(Bn).describe("What is cached: the whole request (`automatic`) or the system instruction only (`system`)."),ttl:b(Vn).optional().describe(`How long the cache is kept. Absent: the upstream default.`)}).describe(`Prompt caching, for models that support it.`),Up=i({details:y(L),content:S().optional()});function Wp(e){return e.ttl?{type:`ephemeral`,ttl:e.ttl}:{type:`ephemeral`}}function Gp(e){let t=Y(e)?.tool_calls;return Array.isArray(t)?t.map(e=>String(Y(e)?.id)):[]}function Kp(e,t){for(let n of e){let e=Gp(n);if(n.role!==`assistant`||!e.length)continue;let r=(t.find(t=>t.role===`assistant`&&JSON.stringify((t.tool_calls??[]).map(e=>e.id))===JSON.stringify(e))?.reasoning??[]).map(e=>Up.safeParse(e.data)).find(e=>e.success);r?.success&&(n.reasoning_details=r.data.details,r.data.content&&(n.reasoning=r.data.content))}}function qp(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function Jp(e){let t=e=>[e?.citations,Y(e?.providerMetadata)?.citations,Y(e?.provider_metadata)?.citations],n=Y(e.openrouter),r=Array.isArray(e.choices)?e.choices.map(Y):[];return[...t(e),...t(n),...t(Y(n?.providerMetadata)),...t(Y(n?.provider_metadata)),...r.flatMap(e=>[...t(Y(e?.message)),...t(Y(e?.delta))])].flatMap(qp)}function Yp(e){let t=Array.isArray(e.choices)?e.choices.map(Y):[];return[e.annotations,Y(e.openrouter)?.annotations,...t.flatMap(e=>[Y(e?.message)?.annotations,Y(e?.delta)?.annotations])].flatMap(e=>Array.isArray(e)?e:[]).filter(e=>Y(e)?.type!==`url_citation`)}function Xp(e){return(Array.isArray(e.choices)?e.choices:[]).map(e=>Y(Y(e)?.delta)?.thinking).filter(e=>typeof e==`string`).join(``)}var Zp=Ba(up,{id:`openRouterOpenAi`,name:`OpenRouter Chat Completions`,description:`Chat Completions with OpenRouter's caching, routing, web search, citations and reasoning.`,options:i({cache:Hp.optional()}),reasoning:Up,body(e,t){if(t.profileType!==`text`)return{body:e};let n={...e,provider:{require_parameters:!0}};n.reasoning_effort!==void 0&&(n.reasoning={effort:n.reasoning_effort},delete n.reasoning_effort);let r=Array.isArray(n.messages)?n.messages:[],i=t.options.cache;i?.mode===`automatic`&&(n.cache_control=Wp(i)),i?.mode===`system`&&r[0]?.role===`system`&&(r[0]={...r[0],content:[{type:`text`,text:r[0].content??``,cache_control:Wp(i)}]}),Kp(r,t.request?.history??[]),t.request?.sessionId&&(n.session_id=t.request.sessionId);let a=t.builtInTools.includes(`webSearch`);return a&&(n.web_search_options={}),{body:{...n,messages:r},wroteTools:a?[`webSearch`]:[]}},read(e){let t=new Map,n=new Set,r=new Set,i=``;return{row(a){i+=Vp(a,t);let o=[],s=Xp(a);s&&e.request?.summaries!==`none`&&o.push({type:`thought`,text:s});let c=Jp(a).filter(e=>!n.has(e)&&n.add(e)).map(e=>({title:e,uri:e,type:`web`}));c.length&&o.push({type:`citation`,sources:c});let l=Yp(a).filter(e=>{let t=JSON.stringify(e);return!r.has(t)&&r.add(t)});return l.length&&o.push({type:`evidence`,evidence:{provider:`openrouter`,kind:`provider_step`,step:`annotations`,raw:{annotations:l}}}),{events:o}},finish(){return!t.size&&!i?{}:{events:[{type:`reasoning`,data:{details:[...t.values()],...i?{content:i}:{}}}]}}}}}),Qp=Wc({id:`openrouter`,name:`OpenRouter`,description:`Many labs' models behind one key.`,connection:i({baseUrl:zc.optional().describe(`The API, by default https://openrouter.ai/api/v1.`),decisionUrl:zc.optional().describe(`The decision API, by default https://openrouter.ai/api/alpha/decisions.`),siteUrl:S().trim().min(1).optional().describe(`Sent as HTTP-Referer, for OpenRouter rankings.`),siteName:S().trim().min(1).optional().describe(`Sent as X-Title, for OpenRouter rankings.`)}).default({}),key:S().trim().min(1),authorize:Bc(),serves(e){let t=e.baseUrl??`https://openrouter.ai/api/v1`,n={};e.siteUrl&&(n[`HTTP-Referer`]=e.siteUrl),e.siteName&&(n[`X-Title`]=e.siteName);let r=e.decisionUrl??`https://openrouter.ai/api/alpha/decisions`;return[{protocol:Zp,baseUrl:t,headers:n},{protocol:gl,baseUrl:t,headers:n},{protocol:Bp,baseUrl:t,headers:n},{protocol:xp,baseUrl:r,url:()=>r,headers:n}]}}),$p=Wc({id:`typesafe`,name:`TypeSafe`,description:`System One decisions, at TypeSafe's own API.`,connection:i({baseUrl:zc.optional().describe(`The API, by default https://api.typesafe.ai/v1.`)}).default({}),key:S().trim().min(1),authorize:Bc(),prices:{checked:`2026-10-19`,models:{"jev-*":{input:.042,output:0}}},serves:e=>[{protocol:_p,baseUrl:e.baseUrl??`https://api.typesafe.ai/v1`}]}),em=`local`;function tm(e,t){return!t&&e===`local`}function nm(e=`http://localhost:11434`){return`${e.replace(/\/$/,``)}/v1`}var rm=[{id:`gemini`,definition:`gemini`},{id:`openrouter`,definition:`openrouter`},{id:em,definition:`local`,connection:{baseUrl:nm()}},{id:`typesafe`,definition:`typesafe`}],im={gemini:{provider:Bf,factory:`geminiProvider`},openrouter:{provider:Qp,factory:`openRouterProvider`},local:{provider:dp,factory:`localProvider`},typesafe:{provider:$p,factory:`typesafeProvider`}};function am(e){return e===void 0?void 0:im[e]?.provider}function om(){return Object.keys(im)}function sm(e){return Object.keys(im).find(t=>im[t]?.factory===e)}function cm(e){return im[e]?.factory}function lm(e,t){return e.find(e=>e.id===t)?.definition}function um(e){return{id:e.id,...e.connection===void 0?{}:{connection:e.connection},...e.keySlot===void 0?{}:{keySlot:e.keySlot},...e.fallbackKeySlot===void 0?{}:{fallbackKeySlot:e.fallbackKeySlot}}}function dm(e,t,n=am(t.definition),r=`register`){if(!n)throw Error(`The studio does not hold the provider definition '${t.definition}'.`);return e[r](n,um(t))}function fm(e){let t=am(e);if(!t)return;if(!t.connection)return[];let n=h(t.connection,{io:`input`});return Object.entries(n.properties??{}).map(([e,t])=>({name:e,required:n.required?.includes(e)??!1,url:t.format===`uri`,...t.description?{description:t.description}:{}}))}function pm(e){let t=am(e);return t===void 0||t.key!==void 0}function mm(e){let t=[];e.id.trim()||t.push({field:`id`,message:`Provider id is required.`});let n=am(e.definition),r=e.connection??{},i=n?.connection?.safeParse(r);for(let e of i?.error?.issues??[]){if(e.code===`unrecognized_keys`){for(let n of e.keys)t.push({field:`connection.${n}`,message:`This provider takes no '${n}'.`});continue}let n=e.path[0];if(typeof n!=`string`){t.push({message:e.message});continue}let i=n in r?e.message:`${n} is required.`;t.push({field:`connection.${n}`,message:i})}for(let n of[`keySlot`,`fallbackKeySlot`]){let r=e[n];r!==void 0&&!Ha.safeParse(r).success&&t.push({field:n,message:`A key slot is 1 to 32 letters, digits, hyphens, or underscores.`})}return e.keySlot&&e.keySlot===e.fallbackKeySlot&&t.push({field:`fallbackKeySlot`,message:O(`provider.fallback_slot`)}),(e.keySlot||e.fallbackKeySlot)&&n&&!n.key&&t.push({field:`keySlot`,message:O(`protocol.no_key`,{provider:e.id})}),t}function hm(e,t){return Ka(e.find(e=>e.id===t.provider)??{},{...t.keySlot?{keySlot:t.keySlot}:{},...t.fallbackKeySlot?{fallbackKeySlot:t.fallbackKeySlot}:{}})}function gm(e,t){let n=am(e.definition);if(!n)return;let r;try{r=dm(Kc(),e,n)}catch{return[]}return r.serves.map(e=>e.protocol).filter(e=>t===void 0||e.endpoints[t]!==void 0)}function _m(e,t,n){if(!e)return!1;let r=gm(e,t);return r===void 0?!0:n===void 0?r.length>0:r.some(e=>e.id===n)}function vm(e,t,n){if(!ym(t))throw Error(`Cannot create a model route without a profile type.`);return{profileType:t,protocol:n.protocol,provider:n.provider,definition:lm(e,n.provider),apiId:n.apiId,decision:t===`decision`}}function ym(e){return[`text`,`image`,`speech`,`live`,`decision`,`embedding`].includes(e)}function bm(e,t){let n=xm(h(e.options,{io:`input`,unrepresentable:`any`}),``,!0),r=t?e.refusedOptions?.(t.apiId.trim())??[]:[];return n.filter(e=>{let n=e.path.split(`.`)[0]??e.path;return!r.includes(n)||t?.options[n]!==void 0})}function xm(e,t,n){return Object.entries(e.properties??{}).flatMap(([r,i])=>{let a=t?`${t}.${r}`:r,o=n&&(e.required?.includes(r)??!1);if(i.type===`object`&&i.properties)return xm(i,a,o);let s={path:a,label:Sm(r),required:o,...i.description?{description:i.description}:{}},c=i.anyOf?.filter(e=>typeof e.const==`string`||typeof e.const==`number`),l=c?.map(e=>e.const);if(i.enum?.every(e=>typeof e==`string`))return[{...s,kind:`choice`,choices:i.enum.map(e=>({value:e}))}];if(l&&l.length===i.anyOf?.length&&l.length>0){let e=l.every(e=>typeof e==`number`);if(e||l.every(e=>typeof e==`string`))return[{...s,kind:`choice`,choices:(c??[]).map(e=>({value:String(e.const),...e.title?{label:e.title}:{},...e.description?{description:e.description}:{}})),...e?{choiceType:`number`}:{}}]}return i.type===`boolean`?[{...s,kind:`boolean`}]:i.type===`string`?[{...s,kind:`text`}]:i.type===`number`||i.type===`integer`?[{...s,kind:`number`}]:[]})}function Sm(e){let t=e.replace(/([a-z0-9])([A-Z])/g,`$1 $2`).toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}function Cm(e,t){return t.split(`.`).reduce((e,t)=>e&&typeof e==`object`&&!Array.isArray(e)?e[t]:void 0,e)}function wm(e,t,n){let[r=``,...i]=t.split(`.`),{[r]:a,...o}=e,s=i.length?wm(a&&typeof a==`object`&&!Array.isArray(a)?a:{},i.join(`.`),n):n;return s===void 0||typeof s==`object`&&s&&!Array.isArray(s)&&!Object.keys(s).length?o:{...o,[r]:s}}var Tm=`studio`,Em={"observability.writeTo":Tm};function Dm(e){return Object.entries(Em).reduce((e,[t,n])=>Om(e,t.split(`.`),n),e)}function Om(e,[t,...n],r){if(t===void 0||!Object.hasOwn(e,t))return e;let i=e[t];if(!n.length)return i===r?Object.fromEntries(Object.entries(e).filter(([e])=>e!==t)):e;if(typeof i!=`object`||!i||Array.isArray(i))return e;let a=Om(i,n,r);return a===i?e:Object.fromEntries(Object.entries(e).flatMap(([e,n])=>e===t?Object.keys(a).length?[[e,a]]:[]:[[e,n]]))}var km=new Set(Qc.map(e=>e.name));function Am(e){return e.protocol===Ad.id||e.protocol===Ff.id}function jm(e){return e.protocol===Zp.id||e.protocol===Bp.id}function Mm(e){return km.has(e)}function Nm(e,t,n){return n.mode===`demo`?n.keys.runs(e,t?.definition):_m(t,e)}var Pm={text:`fast`,image:`image`,speech:`voice`,live:`live`,decision:`decision`,embedding:`embedding`};function Fm(e,t){let n=t?.(e)??{...Im(e===`decision`?`typesafe`:`gemini`,e),apiId:``};return{modelId:Pm[e],...n}}function Im(e,t){let n=rm.find(t=>t.id===e),r=n&&gm(n,t)?.[0];if(!r)throw Error(`The studio provider '${e}' serves no ${t} agents.`);return{protocol:r.id,provider:e}}function Lm(e,t){return t.mode===`demo`?t.keys.violation(e):t.mode===`local`&&e.provider!==`local`?{field:`provider`,message:`Local runs require local models. Switch the model provider to Local.`}:null}var Rm=5,zm=100,Bm=120;function Vm(e){let t=Array.isArray(e.type)?e.type.find(e=>e!==`null`):e.type;return t===`string`||t===`number`||t===`integer`||t===`boolean`||t===`array`?t:t===`object`||A(e.properties)?`object`:Array.isArray(e.enum)?`string`:`unknown`}function Hm(e){return A(e.items)?e.items:void 0}function Um(e){let t=e?.enum;return Array.isArray(t)&&t.length>0&&t.every(e=>typeof e==`string`)?t:void 0}function Wm(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function Gm(e,t){let n=Wm(e,`minimum`),r=Wm(e,`maximum`);return t&&n!==void 0&&r!==void 0&&r>n&&r-n<=zm?{kind:`range`,min:n,max:r}:{kind:`number`,isInteger:t,...n===void 0?{}:{min:n},...r===void 0?{}:{max:r}}}function Km(e){if(e.format===`date`)return{kind:`date`};let t=Wm(e,`maxLength`);return{kind:`text`,isLong:t!==void 0&&t>Bm,type:e.format===`email`?`email`:`text`}}function qm(e){let t=Hm(e),n=Um(t);if(n)return{kind:`choices`,options:n};let r=t?Vm(t):`unknown`;return r===`string`||r===`number`||r===`integer`?{kind:`words`}:t&&r===`object`?{kind:`rows`,item:t}:{kind:`json`}}function Jm(e){let t=Um(e);if(t)return{kind:`choice`,options:t,isMenu:t.length>Rm};switch(Vm(e)){case`boolean`:return{kind:`switch`};case`number`:return Gm(e,!1);case`integer`:return Gm(e,!0);case`string`:return Km(e);case`array`:return qm(e);case`object`:return A(e.properties)?{kind:`group`,schema:e}:{kind:`json`};default:return{kind:`json`}}}function Ym(e){return new Set(Array.isArray(e.required)?e.required.filter(e=>typeof e==`string`):[])}function Xm(e){let t=A(e.properties)?e.properties:{},n=Ym(e);return Object.entries(t).flatMap(([e,t])=>A(t)?[{key:e,label:typeof t.title==`string`&&t.title?t.title:Ze(e),...typeof t.description==`string`&&t.description?{description:t.description}:{},isRequired:n.has(e),control:Jm(t)}]:[])}function Zm(e){if(Array.isArray(e.examples)&&e.examples.length)return{value:e.examples[0]};if(`default`in e)return{value:e.default};if(`const`in e)return{value:e.const};if(Array.isArray(e.enum)&&e.enum.length)return{value:e.enum[0]}}function Qm(e){let t=Zm(e);if(t)return t.value;switch(Vm(e)){case`number`:case`integer`:return Wm(e,`minimum`)??1;case`boolean`:return!0;case`array`:return[];case`object`:return $m(e);case`string`:case`unknown`:return`example`}}function $m(e){let t=A(e.properties)?e.properties:{},n=new Set(Ym(e)),r={};for(let[e,i]of Object.entries(t))A(i)&&(n.has(e)?r[e]=Qm(i):Array.isArray(i.examples)&&i.examples.length&&(r[e]=i.examples[0]));return r}function eh(e){return $m(e)}function th(e,t,n){let r={...e};return n===void 0||n===``?delete r[t]:r[t]=n,r}function nh(e,t,n=``){return A(t)?Xm(e).flatMap(e=>{let r=t[e.key],i=n?`${n} › ${e.label}`:e.label;return r==null||r===``?e.isRequired?[i]:[]:e.control.kind===`group`?nh(e.control.schema,r,i):[]}):[]}var rh=`{
|
|
7
7
|
"type": "object",
|
|
8
8
|
"properties": {
|
|
9
9
|
"query": { "type": "string" }
|
|
10
10
|
},
|
|
11
11
|
"required": ["query"]
|
|
12
|
-
}`,
|
|
12
|
+
}`,ih=`{
|
|
13
13
|
"type": "object",
|
|
14
14
|
"properties": {
|
|
15
15
|
"result": { "type": "string" }
|
|
16
16
|
},
|
|
17
17
|
"required": ["result"]
|
|
18
|
-
}`;function
|
|
18
|
+
}`;function ah(e){return jt(e)}function oh(e){return $m(e)}var sh={"<":`\\u003C`,">":`\\u003E`,"\u2028":`\\u2028`,"\u2029":`\\u2029`};function ch(e){return`'${JSON.stringify(e).slice(1,-1).replaceAll(`\\"`,`"`).replaceAll(`'`,`\\'`).replace(/[<>\u2028\u2029]/g,e=>sh[e]??e)}'`}function lh(e,t=ch){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?e:t(e)}function uh(e,t){let n=e.trim();if(!n)return{ok:!1,error:`${t} JSON Schema is required.`};try{let e=JSON.parse(n);if(!e||typeof e!=`object`||Array.isArray(e))return{ok:!1,error:`${t} JSON Schema must be an object.`};try{ah(e)}catch(e){return{ok:!1,error:`${t} JSON Schema can't be read: ${e.message}.`}}return{ok:!0,schema:e}}catch{return{ok:!1,error:`${t} JSON Schema is not valid JSON.`}}}export{jc as $,vr as $n,Ka as $t,nm as A,Dr as An,Kt as Ar,ms as At,pm as B,ri as Bn,I as Br,Za as Bt,rm as C,Ci as Cn,L as Cr,No as Ct,sm as D,Ei as Dn,rn as Dr,Go as Dt,lm as E,Di as En,Qt as Er,Uo as Et,bm as F,Yr as Fn,Mt as Fr,xo as Ft,Qc as G,Gn,uo as Gt,gl as H,Ln as Hn,ro as Ht,mm as I,pi as In,Nt as Ir,Y as It,Xc as J,sr as Jn,so as Jt,Yc as K,Mn as Kn,lo as Kt,dm as L,vi as Ln,It as Lr,ho as Lt,hm as M,Si as Mn,Vt as Mr,qo as Mt,tm as N,kr as Nn,zt as Nr,bo as Nt,am as O,yi as On,nn as Or,Q as Ot,Cm as P,zr as Pn,F as Pr,So as Pt,Wc as Q,ir as Qn,Ga as Qt,gm as R,jr as Rn,Bt as Rr,to as Rt,em as S,Ui as Sn,cn as Sr,Ss as St,cm as T,Oi as Tn,en as Tr,_s as Tt,dl as U,Rn as Un,ao as Ut,wm as V,or as Vn,Ht as Vr,Qa as Vt,cl as W,Nn as Wn,eo as Wt,qc as X,In as Xn,qa as Xt,Jc as Y,Pn as Yn,oo as Yt,Kc as Z,Fn as Zn,Ya as Zt,Mm as _,Bi as _n,yn as _r,vc as _t,ch as a,wa as an,er as ar,Pc as at,Nm as b,Mi as bn,ln as br,xs as bt,eh as c,ta as cn,Xn as cr,Ic as ct,Xm as d,na as dn,Hn as dr,Ec as dt,Wa as en,Tn as er,xc as et,th as f,aa as fn,cr as fr,wc as ft,jm as g,Vi as gn,wn as gr,_c as gt,Am as h,Yi as hn,fn as hr,yc as ht,uh as i,K as in,En as ir,Dc as it,vm as j,ei as jn,Yt as jr,hs as jt,om as k,ii as kn,tn as kr,fs as kt,nh as l,ea as ln,tr as lr,kc as lt,Im as m,Qi as mn,On as mr,Lc as mt,ih as n,Va as nn,Un as nr,Cc as nt,oh as o,xa as on,nr as or,Nc as ot,Tm as p,$i as pn,Sr as pr,bc as pt,Zc as q,Zn as qn,co as qt,lh as r,q as rn,An as rr,Fc as rt,ah as s,ia as sn,qn as sr,Tc as st,rh as t,Ja as tn,jn as tr,Sc as tt,$m as u,ra as un,$n as ur,Mc as ut,Lm as v,zi as vn,Sn as vr,gc as vt,fm as w,Ti as wn,an as wr,os as wt,Dm as x,Wi as xn,on as xr,Es as xt,Fm as y,Hi as yn,un as yr,Xs as yt,_m as z,Mr as zn,Ft as zr,Xa as zt};
|