@theoremjs/studio 0.3.2 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/package.json +3 -3
  2. package/page/assets/{Banner-BISz3nXA.js → Banner-Buiul23B.js} +2 -2
  3. package/page/assets/{ContextMenu-CBu9H-9H.js → ContextMenu-Dw9_F5b0.js} +2 -2
  4. package/page/assets/{ToolResultCharts-CgshSv9Q.js → ToolResultCharts-CVlI3NkJ.js} +1 -1
  5. package/page/assets/{TraceInspector-_yZiz05W.js → TraceInspector-TusXx3zZ.js} +1 -1
  6. package/page/assets/{TraceOverview-BPO-HIYK.js → TraceOverview-DrHQgMQO.js} +1 -1
  7. package/page/assets/{_virtual_studio-type-sources-ByxqQaOG.js → _virtual_studio-type-sources-BwZOives.js} +39 -11
  8. package/page/assets/browser-engine-BTOR18GA.js +11 -0
  9. package/page/assets/{browser-transport-D-2jDYe7.js → browser-transport-BEFsWdzI.js} +3 -3
  10. package/page/assets/{export-agent-C3yyzXH8.js → export-agent-BnlMWFTv.js} +1 -1
  11. package/page/assets/{guardrail-tester-Gut5xK4a.js → guardrail-tester-DRsOgbwK.js} +1 -1
  12. package/page/assets/{index-CvvmFKgS.js → index-D2T8e_8Q.js} +6 -6
  13. package/page/assets/{live-messages-CnkL4GWi.js → live-messages-BYi31jQk.js} +1 -1
  14. package/page/assets/{reader-BOCCYaRp.js → reader-B0gVhfoZ.js} +1 -1
  15. package/page/assets/{stub-DhdcU_Ew.js → stub-DEZDrr-l.js} +1 -1
  16. package/page/assets/{studio-code-pane-C_SAbcOa.js → studio-code-pane-PndbSO1v.js} +3 -3
  17. package/page/assets/{studio-console-DZwlEsvr.js → studio-console-e6kqu38F.js} +1 -1
  18. package/page/assets/{studio-decision-B0FnCAXA.js → studio-decision-DFM0psog.js} +1 -1
  19. package/page/assets/{studio-embedding-CmA51HVo.js → studio-embedding-4qgdJ4gh.js} +1 -1
  20. package/page/assets/{studio-host-console-By7hqu2l.js → studio-host-console-DajI604W.js} +2 -2
  21. package/page/assets/{studio-live-BrcVQcyV.js → studio-live-B1a0aWbl.js} +1 -1
  22. package/page/assets/{studio-map-B_xSia-z.js → studio-map-CdrEm07d.js} +1 -1
  23. package/page/assets/{studio-type-checker-BOvxudki.js → studio-type-checker-DosSRFbd.js} +1 -1
  24. package/page/assets/tool-schema-BrqSc6vO.js +18 -0
  25. package/page/assets/{tree-DqyAMsbI.js → tree-DeO1319a.js} +1 -1
  26. package/page/assets/{turn-client-Du3Um3Mg.js → turn-client-DwVPS3TX.js} +1 -1
  27. package/page/assets/types-EVrOoUBG.js +1 -0
  28. package/page/assets/{use-one-call-Hcs8YBp1.js → use-one-call-9e3o5vH-.js} +1 -1
  29. package/page/assets/{workspace-DZALqEDX.js → workspace-Ck0o-_fd.js} +1 -1
  30. package/page/index.html +11 -11
  31. package/page/assets/browser-engine-CYq9DQAM.js +0 -9
  32. package/page/assets/tool-schema-idaOe2nI.js +0 -18
  33. package/page/assets/types-BhfXQCLx.js +0 -1
@@ -0,0 +1,18 @@
1
+ import{n as e}from"./rolldown-runtime-hePW80VL.js";import{$ as t,A as n,B as r,C as i,E as a,F as o,G as s,H as c,I as l,J as u,K as d,L as f,M as p,N as m,O as h,P as ee,Q as te,R as ne,S as re,T as g,U as ie,V as ae,W as oe,X as se,Y as ce,Z as le,a as ue,at as de,b as fe,c as pe,ct as me,d as _,et as he,f as ge,ft as _e,g as v,i as ve,it as ye,j as be,k as xe,l as y,lt as Se,m as Ce,n as we,nt as Te,o as b,ot as Ee,p as De,pt as Oe,q as ke,r as Ae,rt as je,st as Me,t as Ne,tt as Pe,ut as Fe,v as x,w as S,x as C,y as w,z as Ie}from"./schemas-BQ9Jydzb.js";import{c as T,s as Le}from"./host-patterns-C9RMP16Q.js";import{$t as Re,A as E,Cn as ze,D,E as O,En as Be,G as Ve,Jt as He,M as Ue,Mn as k,Nt as We,O as A,On as Ge,Qt as Ke,R as qe,Sn as Je,T as Ye,Zt as Xe,_n as Ze,a as Qe,bn as $e,c as j,en as et,fn as tt,j as M,kn as nt,ln as rt,on as it,pn as at,qt as ot,sn as st,vn as ct,yn as lt}from"./shaped-data-BcarWqd5.js";var ut=e({endsWith:()=>xe,gt:()=>n,gte:()=>be,includes:()=>p,length:()=>f,lowercase:()=>ne,lt:()=>Ie,lte:()=>r,maxLength:()=>ae,maxSize:()=>c,mime:()=>ie,minLength:()=>oe,minSize:()=>s,multipleOf:()=>d,negative:()=>ke,nonnegative:()=>u,nonpositive:()=>ce,normalize:()=>se,overwrite:()=>le,positive:()=>te,properties:()=>t,property:()=>he,regex:()=>Pe,size:()=>Te,slugify:()=>je,startsWith:()=>ye,toLowerCase:()=>de,toUpperCase:()=>Ee,trim:()=>Me,uppercase:()=>me}),dt=e({ZodISODate:()=>Ne,ZodISODateTime:()=>we,ZodISODuration:()=>Ae,ZodISOTime:()=>ve,date:()=>pt,datetime:()=>ft,duration:()=>ht,time:()=>mt});function ft(e){return ee(we,e)}function pt(e){return m(Ne,e)}function mt(e){return l(ve,e)}function ht(e){return o(Ae,e)}var N={...re,...ut,iso:dt},gt=new Set(`$schema.$ref.$defs.definitions.$id.id.$comment.$anchor.$vocabulary.$dynamicRef.$dynamicAnchor.type.enum.const.anyOf.oneOf.allOf.not.properties.required.additionalProperties.patternProperties.propertyNames.minProperties.maxProperties.items.prefixItems.additionalItems.minItems.maxItems.uniqueItems.contains.minContains.maxContains.minLength.maxLength.pattern.format.minimum.maximum.exclusiveMinimum.exclusiveMaximum.multipleOf.description.default.contentEncoding.contentMediaType.contentSchema.unevaluatedItems.unevaluatedProperties.if.then.else.dependentSchemas.dependentRequired.nullable.readOnly`.split(`.`));function _t(e,t){let n=e.$schema;return n===`https://json-schema.org/draft/2020-12/schema`?`draft-2020-12`:n===`http://json-schema.org/draft-07/schema#`?`draft-7`:n===`http://json-schema.org/draft-04/schema#`?`draft-4`:t??`draft-2020-12`}function vt(e,t){return e.map((e,n)=>n<t?e:e.optional())}function yt(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}function bt(e,t){if(!e.startsWith(`#`))throw Error(`External $ref is not supported, only local refs (#/...) are allowed`);let n=e.slice(1).split(`/`).filter(Boolean);if(n.length===0)return t.rootSchema;let r=t.version===`draft-2020-12`?`$defs`:`definitions`;if(n[0]===r){let r=n[1]===void 0?void 0:yt(n[1]);if(!r||!t.defs[r])throw Error(`Reference not found: ${e}`);return t.defs[r]}throw Error(`Reference not found: ${e}`)}function xt(e,t){return N.transform(e=>e).check(n=>{let r=n.value;if(typeof r!=`object`||!r||Array.isArray(r))return;let i=Object.getOwnPropertyNames(r);if(t.minProperties!==void 0&&i.length<t.minProperties&&n.issues.push({origin:`object`,code:`too_small`,minimum:t.minProperties,inclusive:!0,message:`Too small: expected object to have >=${t.minProperties} properties`,input:r,inst:e,continue:!0}),t.maxProperties!==void 0&&i.length>t.maxProperties&&n.issues.push({origin:`object`,code:`too_big`,maximum:t.maxProperties,inclusive:!0,message:`Too big: expected object to have <=${t.maxProperties} properties`,input:r,inst:e,continue:!0}),t.keySchema)for(let e of i){let r=t.keySchema.safeParse(e);r.success||n.issues.push({code:`invalid_key`,origin:`record`,issues:r.error.issues,input:e,path:[e],continue:!0})}}).pipe(e)}function St(e,t){if(e===null)return`z`;let n=typeof e;if(n!==`object`){if(n===`number`&&Number.isNaN(e))return null;let t=String(e);return`${n[0]}${t.length}:${t}`}if(t.has(e))return null;t.add(e);try{if(Array.isArray(e)){let n=[];for(let r of e){let e=St(r,t);if(e===null)return null;n.push(e)}return`a${n.length}:[${n.join(`,`)}]`}let n=Object.keys(e).sort(),r=[];for(let i of n){let n=St(e[i],t);if(n===null)return null;r.push(`${i.length}:${i}=${n}`)}return`o${r.length}:{${r.join(`,`)}}`}finally{t.delete(e)}}var Ct=new Set([`items`,`prefixItems`,`additionalItems`,`additionalProperties`,`contains`,`propertyNames`,`not`,`if`,`then`,`else`,`allOf`,`anyOf`,`oneOf`,`unevaluatedItems`,`unevaluatedProperties`,`contentSchema`]),wt=new Set([`properties`,`patternProperties`,`dependentSchemas`,`dependencies`,`$defs`,`definitions`]);function Tt(e){return typeof e!=`object`||!e?!1:Array.isArray(e)?e.some(Tt):typeof e.$ref==`string`||Object.entries(e).some(([e,t])=>Ct.has(e)?Tt(t):!wt.has(e)||typeof t!=`object`||!t?!1:Object.values(t).some(Tt))}function Et(e){return e===1?`element`:`elements`}function Dt(e,t){return N.transform(e=>e).check(e=>{let n=e.value;if(Array.isArray(n)){if(t.uniqueItems===!0){let t=new Map;for(let r=0;r<n.length;r++){let i=St(n[r],new Set);if(i===null)continue;let a=t.get(i);a===void 0?t.set(i,r):e.issues.push({code:`custom`,message:`Array items must be unique: element at index ${r} duplicates the one at index ${a}`,input:n,path:[r],continue:!0})}}if(t.containsSchema){let r=t.minContains??1,i=t.maxContains===void 0?1/0:t.maxContains+1,a=0;for(let e of n)if(t.containsSchema.safeParse(e).success&&++a>=i)break;a<r&&e.issues.push({code:`custom`,message:`Array must contain at least ${r} matching ${Et(r)}; found ${a}`,input:n,continue:!0}),t.maxContains!==void 0&&a>t.maxContains&&e.issues.push({code:`custom`,message:`Array must contain at most ${t.maxContains} matching ${Et(t.maxContains)}`,input:n,continue:!0})}}}).pipe(e)}function Ot(e,t){if(e!==!1)return e===void 0||e===!0?N.any():P(e,t)}var kt=/^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;function At(e,t){if(e.not!==void 0){if(typeof e.not==`object`&&Object.keys(e.not).length===0)return N.never();throw Error(`not is not supported in Zod (except { not: {} } for never)`)}if(e.unevaluatedItems!==void 0)throw Error(`unevaluatedItems is not supported`);if(e.unevaluatedProperties!==void 0)throw Error(`unevaluatedProperties is not supported`);if(e.if!==void 0||e.then!==void 0||e.else!==void 0)throw Error(`Conditional schemas (if/then/else) are not supported`);if(e.dependentSchemas!==void 0||e.dependentRequired!==void 0)throw Error(`dependentSchemas and dependentRequired are not supported`);if(e.$ref){let n=e.$ref;if(t.refs.has(n))return t.refs.get(n);if(t.processing.has(n))return N.lazy(()=>{if(!t.refs.has(n))throw Error(`Circular reference not resolved: ${n}`);return t.refs.get(n)});t.processing.add(n);let r=P(bt(n,t),t);return t.refs.set(n,r),t.processing.delete(n),r}if(e.enum!==void 0){let n=e.enum;if(t.version===`openapi-3.0`&&e.nullable===!0&&n.length===1&&n[0]===null)return N.null();if(n.length===0)return N.never();if(n.length===1)return N.literal(n[0]);if(n.every(e=>typeof e==`string`))return N.enum(n);let r=n.map(e=>N.literal(e));return r.length<2?r[0]:N.union([r[0],r[1],...r.slice(2)])}if(e.const!==void 0)return N.literal(e.const);let n=e.type;if(Array.isArray(n)){let r=n.map(n=>At({...e,type:n},t));return r.length===0?N.never():r.length===1?r[0]:N.union(r)}if(!n)return N.any();let r;switch(n){case`string`:{let t=N.string();if(e.format){let n=e.format;n===`email`?t=t.check(N.email()):n===`uri`||n===`uri-reference`?t=t.check(N.url()):n===`uuid`||n===`guid`?t=t.check(N.uuid()):n===`date-time`?t=t.check(N.iso.datetime({offset:!0})):n===`date`?t=t.check(N.iso.date()):n===`time`?t=t.check(N.regex(kt)):n===`duration`?t=t.check(N.iso.duration()):n===`hostname`?t=t.check(N.hostname()):n===`ipv4`?t=t.check(N.ipv4()):n===`ipv6`?t=t.check(N.ipv6()):n===`mac`?t=t.check(N.mac()):n===`cidr`?t=t.check(N.cidrv4()):n===`cidr-v6`?t=t.check(N.cidrv6()):n===`base64`?t=t.check(N.base64()):n===`base64url`?t=t.check(N.base64url()):n===`e164`?t=t.check(N.e164()):n===`credit_card`?t=t.check(N.creditCard()):n===`iban`?t=t.check(N.iban()):n===`jwt`?t=t.check(N.jwt()):n===`emoji`?t=t.check(N.emoji()):n===`nanoid`?t=t.check(N.nanoid()):n===`cuid`?t=t.check(N.cuid()):n===`cuid2`?t=t.check(N.cuid2()):n===`ulid`?t=t.check(N.ulid()):n===`xid`?t=t.check(N.xid()):n===`ksuid`&&(t=t.check(N.ksuid()))}typeof e.minLength==`number`&&(t=t.min(e.minLength)),typeof e.maxLength==`number`&&(t=t.max(e.maxLength)),e.pattern&&(t=t.regex(new RegExp(e.pattern))),r=t;break}case`number`:case`integer`:{let t=n===`integer`?N.number().int():N.number();typeof e.minimum==`number`&&e.exclusiveMinimum!==!0&&(t=t.min(e.minimum)),typeof e.maximum==`number`&&e.exclusiveMaximum!==!0&&(t=t.max(e.maximum)),typeof e.exclusiveMinimum==`number`?t=t.gt(e.exclusiveMinimum):e.exclusiveMinimum===!0&&typeof e.minimum==`number`&&(t=t.gt(e.minimum)),typeof e.exclusiveMaximum==`number`?t=t.lt(e.exclusiveMaximum):e.exclusiveMaximum===!0&&typeof e.maximum==`number`&&(t=t.lt(e.maximum)),typeof e.multipleOf==`number`&&(t=t.multipleOf(e.multipleOf)),r=t;break}case`boolean`:r=N.boolean();break;case`null`:r=N.null();break;case`object`:{let n={},i=e.properties||{},a=new Set(e.required||[]),o=typeof e.additionalProperties==`object`?P(e.additionalProperties,t):void 0;for(let[e,r]of Object.entries(i)){let i=P(r,t);_e(n,e,a.has(e)?i:i.optional())}if(e.patternProperties){let i=e.patternProperties,a=Object.keys(i),o=[];for(let e of a){let n=P(i[e],t),r=N.string().regex(new RegExp(e));o.push(N.looseRecord(r,n))}let s=[];if(Object.keys(n).length>0&&s.push(N.object(n).passthrough()),s.push(...o),s.length===0)r=N.object({}).passthrough();else if(s.length===1)r=s[0];else{let e=N.intersection(s[0],s[1]);for(let t=2;t<s.length;t++)e=N.intersection(e,s[t]);r=e}if(e.additionalProperties===!1){let e=Object.keys(n),t=a.map(e=>new RegExp(e)),i=r;r=r.check(n=>{if(!Oe(n.value))return;let r=[];for(let i of Object.keys(n.value))e.includes(i)||t.some(e=>e.test(i))||r.push(i);r.length&&n.issues.push({code:`unrecognized_keys`,keys:r,input:n.value,inst:i})})}}else{let t=N.object(n);r=e.additionalProperties===!1?t.strict():o?t.catchall(o):t.passthrough()}let s=e.propertyNames!==void 0&&e.propertyNames!==!0,c=typeof e.minProperties==`number`?e.minProperties:void 0,l=typeof e.maxProperties==`number`?e.maxProperties:void 0;if(s||c!==void 0||l!==void 0){let n;s&&(n=P(typeof e.propertyNames==`object`&&e.propertyNames.type===void 0?{type:`string`,...e.propertyNames}:e.propertyNames,t)),r=xt(r,{keySchema:n,minProperties:c,maxProperties:l})}break}case`array`:{let n=e.prefixItems,i=e.items;if(n&&Array.isArray(n)){let a=typeof e.minItems==`number`?e.minItems:0,o=vt(n.map(e=>P(e,t)),a),s=Array.isArray(i)?void 0:Ot(i,t),c=N.tuple(o);r=s?c.rest(s):c,typeof e.minItems==`number`&&(r=r.check(N.minLength(e.minItems))),typeof e.maxItems==`number`&&(r=r.check(N.maxLength(e.maxItems)))}else if(Array.isArray(i)){let n=typeof e.minItems==`number`?e.minItems:0,a=vt(i.map(e=>P(e,t)),n),o=Ot(e.additionalItems,t),s=N.tuple(a);r=o?s.rest(o):s,typeof e.minItems==`number`&&(r=r.check(N.minLength(e.minItems))),typeof e.maxItems==`number`&&(r=r.check(N.maxLength(e.maxItems)))}else if(i!==void 0){let n=P(i,t),a=N.array(n);typeof e.minItems==`number`&&(a=a.min(e.minItems)),typeof e.maxItems==`number`&&(a=a.max(e.maxItems)),r=a}else r=N.array(N.any());(e.uniqueItems===!0||e.contains!==void 0)&&(r=Dt(r,{uniqueItems:e.uniqueItems===!0,containsSchema:e.contains===void 0?void 0:P(e.contains,t),minContains:typeof e.minContains==`number`?e.minContains:void 0,maxContains:typeof e.maxContains==`number`?e.maxContains:void 0}));break}default:throw Error(`Unsupported type: ${n}`)}return r}function P(e,t){if(typeof e==`boolean`)return e?N.any():N.never();let n=At(e,t),r=e.type||e.enum!==void 0||e.const!==void 0;if(e.anyOf&&Array.isArray(e.anyOf)){let i=e.anyOf.map(e=>P(e,t)),a=N.union(i);n=r?N.intersection(n,a):a}if(e.oneOf&&Array.isArray(e.oneOf)){let i=e.oneOf.map(e=>P(e,t)),a=N.xor(i);n=r?N.intersection(n,a):a}if(e.allOf&&Array.isArray(e.allOf)){if(e.allOf.length===0)n=r?n:N.any();else{let i=r?n:P(e.allOf[0],t),a=+!r;for(let n=a;n<e.allOf.length;n++)i=N.intersection(i,P(e.allOf[n],t));n=i}}e.nullable===!0&&t.version===`openapi-3.0`&&(n=N.nullable(n)),e.readOnly===!0&&(n=N.readonly(n)),e.default!==void 0&&(n=n.default(e.default));let i={};for(let t of[`$id`,`id`,`$comment`,`$anchor`,`$vocabulary`,`$dynamicRef`,`$dynamicAnchor`])t in e&&(i[t]=e[t]);for(let t of[`contentEncoding`,`contentMediaType`,`contentSchema`])t in e&&(i[t]=e[t]);if(e.type===`object`&&e.$ref===void 0){e.propertyNames!==void 0&&!Tt(e.propertyNames)&&(i.propertyNames=e.propertyNames);for(let t of[`minProperties`,`maxProperties`])e[t]!==void 0&&(i[t]=e[t])}if(e.type===`array`&&e.$ref===void 0){e.contains!==void 0&&!Tt(e.contains)&&(i.contains=e.contains);for(let t of[`uniqueItems`,`minContains`,`maxContains`])e[t]!==void 0&&(i[t]=e[t])}for(let t of Object.keys(e))gt.has(t)||_e(i,t,e[t]);return Object.keys(i).length>0&&t.registry.add(n,i),e.description&&(n=n.describe(e.description)),n}function jt(e,t){if(typeof e==`boolean`)return e?N.any():N.never();let n;try{n=JSON.parse(JSON.stringify(e))}catch{throw Error(`fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas`)}let r={version:_t(n,t?.defaultTarget),defs:n.$defs||n.definitions||{},refs:new Map,processing:new Set,rootSchema:n,registry:t?.registry??Se};return P(n,r)}function Mt(e){return Pt(e)===`AbortError`}function Nt(e){return Pt(e)===`TimeoutError`}function Pt(e){return e&&typeof e==`object`?e.name:void 0}function Ft(e){if(!e?.aborted)return;let{reason:t}=e;throw t instanceof T||Mt(t)||Nt(t)?t:new DOMException(`The operation was aborted.`,`AbortError`)}function F(e){return e instanceof T?e.kind:Nt(e)?`timeout`:Mt(e)?`cancelled`:`internal`}function It(e){return e===401||e===402||e===403?`auth`:e===408||e===504||e===524?`timeout`:e===429?`rate_limit`:e===503||e===529?`busy`:e>=500?`unavailable`:`unsupported`}function Lt(e,t,n){return k(`error.${e}`,n,t)}function Rt(e,t,n){return t?zt(t,n):Lt(e,n)}function zt(e,t){return(`key`in e?[e]:e).map(e=>k(e.key,e.params,t)).join(`
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=Be(Ke,e=>Re[e].doc);function ur(e,t){if(Xe[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,Ke,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:Re.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}=Xe[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,Ke,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 ot){let r=`guardrails.detect.${n}`;t.push([r,e(`DetectAction | DetectorConfig`,`${Xe[n].doc} Set one action, or ${hr(n)}.`)]),Xe[n].allow&&t.push(...ur(r,n)),Xe[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 He[n]){let a=Re[et[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(nt,n))return{...r,doc:nt[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/)})).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(!Ue([t],n))return{action:`allow`,hits:[],value:e};let i=We(e);if(i.unscannable)return{action:`block`,hits:[{rule:ct.unscannable,severity:`high`}]};let a=E(i.text,t,n,r);if(a.action!==`redact`)return{action:a.action,hits:a.hits,value:e};let o=rt(e,e=>E(e,t,n,r).text??``),s=E(We(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=E(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`?M(n,{action:s.length>0?`flag`:`allow`,hits:s}):M(n,a),o?M(`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 k(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=k(`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 k(e===`high`?`advisory.notice_high`:`advisory.notice_elevated`,{},t)}function Ii(e,t){if(t===void 0)return e;let n=We(t);return n.unscannable?e:`${e}\n${n.text}`}var Li={action:`allow`,hits:[]};function Ri(e,t,n,r){return t?E(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===Ze.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,Ve(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?M(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=M(r,i,t);return{...i.action===`block`?{}:{value:i.value},...a?{event:a}:{}}}function Hi(e,t,n,r,i={}){if(!(r&&Ue([r],n.detect)))return{args:e};let a=e=>{let n=M(r,{action:`block`,hits:e},t);return n?{event:n}:{}},o=We(e);if(o.unscannable)return a([{rule:ct.unscannable,severity:`high`}]);let s=E(o.text,r,n.detect,i);if(s.action===`block`)return a(s.hits);let c=M(r,s,t);if(s.action!==`redact`)return{args:e,...c?{event:c}:{}};let l=rt(e,e=>E(e,r,n.detect,i).text??``),u=E(We(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?$e.steeredTurn:$e.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=k(a?`taint.reason_steered`:`taint.reason_tainted`,{},r);return{action:`block`,hits:o,rejection:k(`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:st(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`,k(`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`,k(`protocol.part_schema`,{protocol:e.id,kind:t}));let i=n.safeParse(r);if(!i.success)throw new T(`bad_response`,k(`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
+ `):Fe(i.error);throw new T(`config`,k(`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`,k(`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`,k(`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`,k(`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`,k(`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`,k(`provider.model_fallback_slot`));if((t.keySlot||t.fallbackKeySlot)&&!e.definition.key)throw new T(`config`,k(`protocol.no_key`,{provider:e.id}));let c=i.authorize??e.definition.authorize;if(n===`live`&&c?.webSocketHeaders&&!r.webSocketHeaders)throw new T(`unsupported`,k(`protocol.ws_headers`,{provider:e.id}));return{...t,options:o}}var Xa=[`text`],Za=Gn,Qa=[`length`,`stream_incomplete`],$a=1500,eo=new Set(Gn);function to(e){return eo.has(e)}new Set(Za);var no=new Set([`provider_error`,`stream_incomplete`]);function ro(e){return no.has(e)}function io(e){return typeof e==`object`&&e.reason?{kind:`cancelled`,native:e.reason}:{kind:`cancelled`}}function ao(e,t){return!e||!to(e.kind)?!1:(t?.autoContinue??Qa).includes(e.kind)}function oo(e){if(e.type!==`live`)return e.turnBehaviour?.resumption}function so(e){return e.type===`text`&&e.turnBehaviour?.allowSteering!==!1}function co(e){return e.type===`text`||e.type===`live`?e.turnBehaviour?.allowSteering!==!1:!1}function lo(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}:uo((e||``).toLowerCase(),r,n):{kind:`stream_incomplete`,native:n}}function uo(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 fo(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 po(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 A(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 mo(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 ho(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 go(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 _o(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 vo(e){return bo(e.flatMap(e=>e.type===`tokens`?[e.tokens]:[]))}function yo(e){return bo(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 bo(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=ho(e),l=go(e),u=_o(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 xo=1e3,So=400,Co=new Set([`http_request`,`http_response`,`http_error_body`,`http_throw`]),wo=new Set([`text`,`image`,`audio`]),To={completed:`stop`,length:`length`,tool:`tool_call`,filtered:`content_filter`,provider_error:`error`};function Eo(e){let[t]=e.split(`/`);return t===`application`||t===`text`||!t?`document`:t}function Do(e){return e.type===`text`?{type:`text`,...O(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,...Ye(e.data)}}function Oo(e){let t=K(e).map(Do);if(e.role===`tool`)return{role:`tool`,parts:[{type:`tool_call_response`,...e.tool_call_id?{id:e.tool_call_id}:{},response:O(e.content??``)},...(e.parts??[]).map(Do)]};let n=(e.tool_calls??[]).map(e=>({type:`tool_call`,id:e.id,name:e.function.name,arguments:O(e.function.arguments)}));return{role:e.role,parts:[...t,...n]}}var ko=new WeakMap;function Ao(e){let{conversation:t}=e;if(`previous`in t){let e=ko.get(t.previous),n=[...e?.input??[],...e?.output?[e.output]:[]];return{input:[...n,...t.continuation.map(Oo)],sentFrom:n.length}}let n=t.input.length>0?[{role:`user`,parts:t.input.map(Do)}]:[];return{input:[...t.history.map(Oo),...n]}}var jo=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:D(e.structured??null)});return;case`media`:this.push(Fo(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=zo(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,O(this.open.text));return}let a={type:e,...O(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=Po(e);this.calls.set(e.callId,t),this.push(t);return}let t=this.calls.get(e.callId),n=e.phase===`error`?Mo(e.failure):void 0;t&&n!==void 0&&Object.assign(t,{arguments:O(n)})}push(e){this.parts.push(e),this.open=void 0}};function Mo(e){let t=Y(e?.details)?.raw;return typeof t==`string`?t:void 0}function No(e){return Mo(e.failure)??JSON.stringify(e.arguments)}function Po(e){return{type:`tool_call`,id:e.callId,name:e.name,arguments:O(No(e))}}function Fo(e){return{type:`blob`,modality:Eo(e.mimeType),mime_type:e.mimeType,...Ye(e.data)}}var Io=`_call`,Lo=`_result`;function Ro(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(Io)){let e=typeof n?.id==`string`?n.id:void 0;return{side:`call`,name:t.slice(0,-5),id:e}}if(t.endsWith(Lo)){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 zo(e,t){let n=Ro(e);if(!n)return;let r={"theorem.observed_end":t,...e.partial?{"theorem.partial":!0}:{}},i={...D(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 Bo(e){switch(e.type){case`grounding`:{let{searchHtml:t,metadata:n,chunks:r}=e.grounding;return!t&&!n&&!r?void 0:{...t?{search_html:O(t)}:{},...n||r?{raw:D({metadata:n,chunks:r})}:{}}}case`citation`:return{sources:D(e.sources)};case`evidence`:{let{evidence:t}=e;return Ro(t)||t.kind===`input_transcription`||t.kind===`output_transcription`?void 0:{provider:t.provider,...t.raw?{raw:D(t.raw)}:{}}}default:return}}function Vo(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:O(e.errorInternal)}:{}}}var Ho={output_stream:`output_delta`,stream_canary:`output_delta`,tool_draft:`tool_call`,live_output:`live_outbound`};function Uo(e,t,n,r){return{...n?Vo(n):{stage:r.stage,trust:r.trust,action:`allow`,hits:[]},check:e,duration_ms:t}}function Wo(e){let t={};for(let n of[`input`,`output`])for(let[r,i]of Object.entries(e?.[n]??{})){let e=wo.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 Go(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),...Wo(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 Ko(e){return e===`turn`?`chat`:`generate_content`}function qo(e){if(e)return e.provider}function Jo(e,t){return t===`live`?`speech`:e.structured?`json`:e.image?`image`:e.speech?`speech`:`text`}function Yo(e,t,n){let r=qo(t);return{"gen_ai.operation.name":Ko(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`,...O(e.system)}],...e.wireTools?.length?{"gen_ai.tool.definitions":O(JSON.stringify(e.wireTools))}:{},"gen_ai.output.type":Jo(e,n),...Xo(e)}}function Xo(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":Zo(r,e)}:{}}}function Zo(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 Qo(e,t){return!t||typeof t!=`object`?{}:Object.fromEntries(Object.entries(t).map(([t,n])=>[`${e}.${t}`,[String(n)]]))}function $o(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 es=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||!Co.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`),...$o(e.url),"http.request.resend_count":this.tries,...typeof e.keySlot==`string`?{"theorem.key_slot":e.keySlot}:{},...Q(`theorem.retry.backoff_ms`,t),...Qo(`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:D(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),...Qo(`http.response.header`,e.headers)}),t!==void 0&&t>=So?this.current?.set({"error.type":String(t)}):this.awaitingFirstChunk=!0}errorBody(e){this.current?.event(`theorem.upstream.row`,{row:D(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":O(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()/xo}))}close(e){this.current&&=(this.current.end(e),this.last=this.current,void 0)}};function ts(e,t,n){return e!==void 0&&e>=So?{code:`ERROR`,message:String(e)}:n===void 0?t?{code:`UNSET`}:{code:`OK`}:{code:`ERROR`,message:F(n)}}function ns(e){return e instanceof Error?e.name:`Error`}function rs(e,t){e.event(`exception`,{"exception.type":ns(t),"exception.message":O(t instanceof Error?t.message:String(t)),...t instanceof Error&&t.stack?{"exception.stacktrace":O(t.stack)}:{}})}function is(e,t){rs(e,t);let n=F(t);e.set({"error.type":n}),e.end({code:`ERROR`,message:n})}function as(e,t){for(let[n,r]of t)r.decided||e.event(`theorem.guardrail`,{...Uo(n,r.ms,void 0,{stage:Ho[n],trust:`untrusted`}),runs:r.runs})}function os(e){let t=0;for(let n of e.values())t+=n.ms;return t>0?{"theorem.guardrail.stream_ms":t}:{}}var ss=new Set([`cancelled`,`interrupted`]);function cs(e,t){let n=e!==void 0&&ss.has(e.kind),r=e&&!n?To[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 ls(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 us(e,t){let{req:n,usage:r,transport:i}=t,a=Ao(r),o=e(`${Ko(i)} ${n.apiId}`,{kind:`CLIENT`,attributes:{...Yo(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 es(o),c=new jo,l=new jo,u=[],d,f,p=!1,m=new Map,h;return{span:o,tap:e=>{s.row(e)||o.event(`theorem.upstream.row`,{row:D(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()/xo}));let t=Bo(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`,Vo(e)):(t.decided=!0,o.event(`theorem.guardrail`,{...Uo(h,t.ms,e,{stage:Ho[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":O(e.errorInternal??e.error??``)});e.thrown!==void 0&&rs(o,e.thrown),as(o,m);let t=u.at(-1),n=e.thrown===void 0?t?.errorKind:F(e.thrown),a=cs(e.stop,n),p={role:`assistant`,parts:c.parts,...Q(`finish_reason`,a.finish)},{input:h}=Ao(r);ko.set(r,{input:h,output:p});let ee=l.parts.length>0?[{role:`user`,parts:l.parts}]:[];s.close(ts(s.lastStatus,a.stopped,e.thrown)),o.set({"gen_ai.input.messages":[...h,...ee],"gen_ai.output.messages":[p],...e.tokens?Go(e.tokens):{},...ls(d,a.stopped?void 0:f,i),...Q(`theorem.stop.kind`,e.stop?.kind),...os(m),...a.attributes}),o.end(a.status)}}}function ds(e){let t=[...e?.attachments??[],...e?.voice??[]].map(e=>`uri`in e?{type:`uri`,modality:Eo(e.mimeType),mime_type:e.mimeType,uri:e.uri}:{type:`blob`,modality:Eo(e.mimeType),mime_type:e.mimeType,...Ye(e.data)}),n=[...e?.text?[{type:`text`,...O(e.text)}]:[],...t];return n.length>0?[{role:`user`,parts:n}]:[]}function fs(e){return(e??[]).map(e=>({traceparent:e.traceparent,attributes:{"theorem.link.kind":e.kind,...Q(`theorem.stop.kind`,e.stop)}}))}function ps(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":ds(e.input),...Q(`theorem.request.effort`,e.effort),...Q(`theorem.request.model_select`,e.model),...Q(`theorem.project.id`,e.projectId)},links:fs(e.links)}}var ms=new Set([`completed`,`length`,`generation_complete`]);function hs(e,t){let n=vo(t.seen),r=po(t.seen,e=>e.type===`done`),i=r?.stop.kind,a=po(t.seen,e=>e.type===`error`),o=a?.error,s=t.thrown!==void 0;s&&rs(e,t.thrown);let c=s||i!==void 0&&ro(i),l=s?F(t.thrown):a?.errorKind??i,u={role:`assistant`,parts:t.delivered.parts,...Q(`finish_reason`,cs(r?.stop,void 0).finish)};e.set({"gen_ai.output.messages":[u],...n?Go(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":O(o)}:{},...c&&l?{"error.type":l}:{}}),c?e.end({code:`ERROR`,...l?{message:l}:{}}):e.end(i&&!ms.has(i)?{code:`UNSET`}:{code:`OK`})}var gs=w({kind:v(`auth_scope_refused`),slot:S(),requested:y(S()),declared:y(S())}),_s={tool_arguments:`tool_call`,taint:`tool_call`,destination:`tool_call`,tool_result:`tool_result`,tool_failure:`tool_result`,network:`network`,network_request:`network`},vs=new WeakSet;function ys(e,t,n,r){e&&(r&&vs.add(r),e.event(`theorem.guardrail`,Uo(t,n,r,{stage:_s[t],trust:`untrusted`})))}function bs(e){return e?`execute_tool ${e}`:`execute_tool`}function xs(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":O(No(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 Ss(e){let t=e.kind===`auth`?e.authChallenge:void 0;return{kind:e.kind,...Q(`permission`,e.permission),...e.summary?{summary:O(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 Cs={ok:`OK`,error:`ERROR`,denied:`UNSET`,gated:`UNSET`,paused:`UNSET`,cancelled:`UNSET`};function ws(e,t){let n=e(bs(t.name),xs(t));return{span:n,observe:e=>{if(e.type===`guardrail`&&!vs.has(e.guardrail)&&n.event(`theorem.guardrail`,Vo(e.guardrail)),e.type===`tool`&&e.tool.phase===`gate`&&n.event(`theorem.gate`,Ss(e.tool.gate)),e.type===`tool`&&e.tool.phase===`progress`){let t=gs.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:O(r),...Q(`severity`,i)})}e.type===`citation`&&n.event(`theorem.grounding`,{sources:D(e.sources)})},end:e=>{e.thrown!==void 0&&rs(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":O(e.result.text)}:{},...e.result?.parts?.length?{"theorem.tool.call.result.parts":e.result.parts.map(Do)}:{},...e.data?{"theorem.tool.data":D(e.data.value)}:{},"theorem.tool.outcome":e.outcome,...Q(`theorem.tool.failure.code`,e.failure?.code),...Q(`error.type`,t)});let r=Cs[e.outcome];n.end(r===`ERROR`&&t?{code:r,message:t}:{code:r})}}}var Ts=/\{\{?([^{}]*)\}\}?/g,Es=/[\p{Cc}\p{Cf}]/gu,Ds=/^-?\d+$/,Os=/^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)?$/,ks=new Intl.NumberFormat(void 0,{maximumFractionDigits:2}),As=new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeZone:`UTC`}),js=new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeStyle:`short`,timeZone:`UTC`}),Ms=/^\+\s+/,Ns=/:(?:\s|$)/,Ps=/^(\S+) is (?:(not) )?(\S.*)$/;function Fs(e){let t=e.indexOf(`|`);return t<0?{path:e.trim()}:{path:e.slice(0,t).trim(),fallback:e.slice(t+1).trim()}}function Is(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 Ls(e,t){let n=e;for(let e of t)if(Array.isArray(n)){if(e===`length`)n=n.length;else if(Ds.test(e))n=n.at(Number(e));else return}else if(A(n)&&Object.hasOwn(n,e))n=n[e];else return;return n}function Rs(e){let t=Os.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?As:js).format(s)}function zs(e){if(typeof e==`number`)return Number.isFinite(e)?ks.format(e):void 0;if(typeof e!=`string`)return;let t=e.replace(Es,` `).replace(/\s+/g,` `).trim();return(Rs(t)??t)||void 0}function Bs(e){let t=[];for(let n of e.replace(/\s+/g,` `).split(` and `)){let[,e,r,i]=Ps.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 Vs(e){let t=Ms.test(e),n=e.replace(Ms,``).trim();if(!/^when(\s|$)/.test(n))return{joined:t,when:[],text:n};let r=n.search(Ns);return r<0?{joined:t,when:`unreadable`,text:``}:{joined:t,when:Bs(n.slice(4,r)),text:n.slice(r+1).trim()}}function Hs(e){let t=typeof e==`string`?[e]:e,n=[];return t.forEach((e,t)=>{let r=Vs(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 Us(e){let[t]=Is(e,[`input`]);return t?.side===`input`?t.keys:void 0}function Ws(e,t){let n=Us(e.path);if(!n)return!1;let r=Ls(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 Gs(e){return e.length<=1?e[0]??``:`${e.slice(0,-1).join(`, `)}${e.length>2?`,`:``} and ${e.at(-1)}`}function Ks(e){return e.replace(/([a-z\d])([A-Z])/g,`$1 $2`).replace(/[_-]+/g,` `).trim().toLowerCase()}function qs(e,t,n){let r=!1,i=e.replace(Ts,(e,i)=>{let{path:a,fallback:o}=Fs(i),s=a?Is(a,n).map(e=>zs(Ls(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 Js(e,t){if(e===void 0)return;let n=`output`in t?[`input`,`output`]:[`input`];for(let r of Hs(e)){let e=r.lines.flatMap(({line:e})=>{if(e.when===`unreadable`||!e.when.every(e=>Ws(e,t.input)))return[];let r=qs(e.text,t,n);return r===void 0?[]:[r]});if(e.length)return Gs(e)}}var Ys=[`value`,`group`,`flag`,`missing`];function Xs(e){return(Array.isArray(e.type)?e.type:[e.type]).filter(e=>typeof e==`string`&&e!==`null`)}function Zs(e){return[e.anyOf,e.oneOf,e.allOf].flatMap(e=>Array.isArray(e)?e.filter(A):[])}function Qs(e){let t=Ys.find(t=>e.some(e=>e.holds===t))??`missing`;return{holds:t,instead:e.filter(e=>e.holds===t).flatMap(e=>e.instead??[])}}function $s(e,t){let n=e=>t?`${t}.${e}`:e;if(!A(e))return[];let r=Zs(e);return r.length?r.flatMap(e=>$s(e,t)):Xs(e).includes(`array`)?ec(e.items,n(`0`)):A(e.properties)?Object.entries(e.properties).flatMap(([e,t])=>ec(t,n(e))):[]}function ec(e,t){if(!A(e)||`$ref`in e)return[t];let n=Xs(e);if(n.length&&n.every(e=>e===`boolean`))return[];let r=Zs(e),i=r.some(e=>Xs(e).some(e=>e===`array`||e===`object`)),a=n.includes(`array`)||n.includes(`object`)||i;return!a&&r.length?r.every(e=>Xs(e).every(e=>e===`boolean`))?[]:[t]:a?$s(e,t):[t]}function tc(e,t,n){if(!A(e)||`$ref`in e)return{holds:`value`};let r=Zs(e);if(r.length)return Qs(r.map(e=>tc(e,t,n)));let i=Xs(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:$s(e,n)}:{holds:`value`};let s=n?`${n}.${a}`:a,c={holds:`missing`,instead:$s(e,n)};if(i.includes(`array`)){if(a===`length`)return o.length?c:{holds:`value`};if(Ds.test(a))return A(e.items)?tc(e.items,o,s):{holds:`value`}}return A(e.properties)?Object.hasOwn(e.properties,a)?tc(e.properties[a],o,s):c:i.length===0||i.includes(`object`)?{holds:`value`}:c}function nc(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 rc(e,t,n){for(let r of e.matchAll(Ts)){let{path:e}=Fs(r[1]??``);if(!e)return`Put a field name between the braces, like {${$s(t.input,``)[0]??`name`}}.`;let i=Is(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=Qs(i.map(({side:e,keys:n,prefixed:r})=>tc(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]);return`{${e}} ${{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]}${nc(l.length?l:s)}`}}var ic={texts:`any`,nullable:!0};function ac(e){return(Array.isArray(e.type)?e.type:[e.type]).filter(e=>typeof e==`string`)}function oc(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=ac(e);if(n.length===0)return ic;let r=n.filter(e=>e!==`null`);return{texts:r.every(e=>e===`boolean`)?r.length?[`true`,`false`]:[]:`any`,nullable:n.includes(`null`)}}function sc(e,t){if(!A(e)||`$ref`in e)return[ic];let n=Zs(e);if(n.length)return n.flatMap(e=>sc(e,t));let[r,...i]=t;if(r===void 0)return[oc(e)];let a=Xs(e);if(a.includes(`array`)){if(r===`length`)return i.length?[]:[{texts:`any`,nullable:!1}];if(Ds.test(r))return sc(e.items,i)}return A(e.properties)?Object.hasOwn(e.properties,r)?sc(e.properties[r],i):[]:a.length===0&&ac(e).length===0?[ic]:[]}function cc(e){if(!A(e))return[];let t=Zs(e).flatMap(cc),n=A(e.properties)?Object.keys(e.properties):[];return[...new Set([...n,...t])]}function lc(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 uc(e,t){let n=Us(e.path);if(!n)return`A "when" reads what the model sent; "${e.path}" is only there once the call is done.`;let r=tc(t,n,``);if(r.holds===`missing`){let n=cc(t).slice(0,4),r=n.length?` Try ${lc(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=sc(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 ${lc(a)}.`:``;return`"${e.path}" is never "${e.expected}".${o}`}function dc(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=uc(n,t.input);if(e)return e}return!e.text&&(r||e.when.length)?`It has no wording to show.`:rc(e.text,t,n)}function fc(e){if(e.when===`unreadable`||e.when.length)return!1;let t=!1,n=e.text.replace(Ts,(e,n)=>{let{fallback:r}=Fs(n);return r===void 0&&(t=!0),r??``});return!t&&n.trim().length>0}function pc(e){let t=e.map(e=>e.lines.some(({line:e})=>fc(e))),n=t.slice(0,-1).indexOf(!0);if(n>=0)return`Line ${e[n]?.lines.find(({line:e})=>fc(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 mc(e,t){let n=`output`in t?[`input`,`output`]:[`input`],r=typeof e!=`string`,i=Hs(e);for(let{line:e,number:a}of i.flatMap(e=>e.lines)){let i=dc(e,t,n,r);if(i)return r?`Line ${a}: ${i}`:i}return r?pc(i):void 0}function hc(e){return e.modelText===void 0?qe(Ii(e.finding,e.data),ot):e.modelText}function gc(e){return{finding:`Tool error (${e.code}): ${e.message}`,...e.details===void 0?{}:{data:{details:e.details}}}}function _c(e){return gc({...e,message:qe(e.message,ot)})}function vc(e,t){return{type:`tool`,tool:{...t,name:e.name,callId:e.callId,...e.operationId?{operationId:e.operationId}:{},at:Date.now()}}}function yc(e,t,n,r){return Js(n?.activityFailed,{input:r})??k(`tool.activity_failed`,{tool:Ks(e)},t)}function bc(e){return e.activityFailed??yc(e.name)}function xc(e,t,n=hc(_c(t))){return vc(e,{phase:`error`,failure:t,readBack:n,activityPast:bc(e)})}function Sc(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 Cc(e){return`call_${e}_${crypto.randomUUID()}`}function wc(e){return e===void 0?{}:A(e)?e:{value:e}}function Tc(e){return e instanceof Error?e.message:String(e)}function Ec(e,t){return vc(e,{phase:`warning`,warning:{code:`sources_invalid`,message:t,severity:`warning`}})}function*Dc(e,t,n){let r;try{r=t(n)}catch(t){yield Ec(e,`sources threw: ${Tc(t)}`);return}if(!Array.isArray(r)){yield Ec(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 Ec(e,`sources not cited: ${a.join(` | `)}`)),i.length>0&&(yield{type:`citation`,sources:i,callId:e.callId})}function Oc(e,t,n,r){let i=n.resume?.edited,a=Js(e.labels?.activity,{input:t});return vc(r,{phase:`running`,...i?{edited:{from:i.from,to:wc(t)}}:{},...a?{activity:a}:{}})}async function*kc(e,t,n,r,i){let a=await i?.(t);return Ft(n.signal),yield Oc(e,t,n,r),a}function Ac(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:k(`tool.input_invalid`,{},n.profile.labels),details:r.error.flatten()}}}function jc(){return{stage:`network`,trust:`untrusted`,action:`block`,hits:[{rule:lt.blocked,severity:`high`}]}}function*Mc(e,t=jc()){return yield{type:`guardrail`,guardrail:t},{code:`network_blocked`,kind:`blocked`,message:Tc(e)}}function*Nc(e,t,n){let r=performance.now();try{let i=ga(e,Fc(t));return ys(n,`network`,performance.now()-r,void 0),{ok:!0,url:i}}catch(e){let t=jc();return ys(n,`network`,performance.now()-r,t),{ok:!1,failure:yield*Mc(e,t)}}}function Pc(e){let t=0,n=!1,r=!1;return{onCheck:e=>{t+=e,n=!0},record:i=>{!r&&n&&(r=!0,ys(e,`network_request`,t,i))}}}function Fc(e){return Qi(e.profile.guardrails).network}function Ic(e,t){return Object.assign(t=>({sign:n=>e(t,n)}),{webSocketHeaders:t})}var Lc=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))},k(`protocol.endpoint_url`));function Rc(){return Ic((e,t)=>t.headers.set(`Authorization`,`Bearer ${e}`),!0)}function zc(e){return Ic((t,n)=>n.headers.set(e,t),!0)}function Bc(e){return Ic((t,n)=>n.url.searchParams.set(e,t),!1)}var Vc=w({id:S().regex(/^[a-z][a-z0-9-]*$/),name:S().min(1),description:S().min(1),traceName:S().min(1).optional()});function Hc(e){let t=Vc.safeParse(e);if(!t.success||typeof e.serves!=`function`)throw new T(`config`,k(`protocol.definition`,{id:String(e.id),issues:t.success?`serves is required`:Fe(t.error)}));return Object.freeze({...e})}function Uc(e,t){let n=e.serves.find(e=>e.protocol.id===t);if(!n)throw new T(`config`,k(`protocol.not_served`,{provider:e.id,protocol:t}));return n}function Wc(){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`,k(`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`,k(`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`,k(`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`,k(`provider.fallback_slot`));if((i.keySlot||i.fallbackKeySlot)&&!r.key)throw new T(`config`,k(`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}=Uc({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`,k(`protocol.provider_missing`,{provider:t,apiId:n}));return r},list:()=>[...e.values()],protocols:()=>[...t.values()]}}var Gc=[`minimal`,`low`,`medium`,`high`],Kc=[`pcm`],qc=[`1:1`,`3:2`,`2:3`,`3:4`,`4:3`,`4:5`,`5:4`,`9:16`,`16:9`,`21:9`],Jc=[`1K`,`2K`,`4K`],Yc=[`image/png`,`image/jpeg`],Xc=[{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 Zc=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.`)}),Qc=/^(gemini-embedding-001|text-embedding-|embedding-)/,$c={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`]}]},el={maxInputs:100,media:[]},tl={query:`RETRIEVAL_QUERY`,document:`RETRIEVAL_DOCUMENT`};function nl(e,t){return t===`query`?`task: search result | query: ${e}`:`title: none | text: ${e}`}function rl(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?nl(e.text,t):e.text}:e.type===`media`?{inlineData:{mimeType:e.mimeType,data:e.data}}:{fileData:{mimeType:e.mimeType,fileUri:e.uri}})}function il(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 al(e,t,n){let r={content:{parts:rl(e,n.taskField?void 0:n.task)}},i=n.taskField&&n.task?tl[n.task]:t.taskType;return i&&(r.taskType=i),t.outputDimensionality&&(r.outputDimensionality=t.outputDimensionality),r}var ol=q({id:`geminiEmbedding`,name:`Gemini Embeddings`,description:`Google's embedding API for text and supported media.`,endpoints:{embedding:`/models/{apiId}:embedContent`},options:Zc,embeddingLimits:e=>Qc.test(e)?el:$c,refusedOptions:e=>Qc.test(e)?[]:[`taskType`],create(e){return{async embed(t){let n=Na(ol,e.apiId,t.options),r={taskField:Qc.test(e.apiId),...t.task?{task:t.task}:{}},i=Array.isArray(t.input)?t.input:[t.input],a=i.length===1?al(i[0],n,r):{requests:i.map(t=>({model:`models/${e.apiId}`,...al(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`?il({embedding:e}):[],dimensions:e&&typeof e==`object`?il({embedding:e}).length:0}))}}}}}),sl=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 cl(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 ll=q({id:`ollamaEmbedding`,name:`Ollama Embeddings`,description:`Ollama’s local embedding endpoint.`,endpoints:{embedding:`/api/embed`},options:sl,embeddingLimits:()=>({media:[]}),create(e){return{async embed(t){let n=sl.parse(t.options??{}),r=e.send({model:e.apiId,input:cl(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}))}}}}}),ul=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`.")}),dl={media:[{accept:[`image/*`]}]};function fl(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 pl(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=tt(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 ml=q({id:`openRouterEmbedding`,name:`OpenRouter Embeddings`,description:`OpenRouter embedding models, including supported multimodal models.`,endpoints:{embedding:`/embeddings`},options:ul,embeddingLimits:()=>dl,create(e){return{async embed(t){let n=ul.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(fl)};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=pl(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}}:{}}}}}}),hl=100,gl=599,_l=new Set([`API_KEY_INVALID`]);function vl(e){return Array.isArray(e)&&e.some(e=>{let t=Y(e)?.reason;return typeof t==`string`&&_l.has(t)})}var yl={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},bl=new Set([`safety`,`recitation`,`language`,`prohibited_content`,`spii`,`blocklist`,`image_safety`,`image_prohibited_content`,`image_recitation`,`image_other`,`content_blocked`]);function xl(e,t){if(e===`cancelled`)return new T(`cancelled`,t);if(bl.has(e))return new T(`safety`,t);let n=yl[e];return n===void 0?new T(`bad_response`,t):new T(It(n),t)}function Sl(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 vl(a)?new T(`auth`,o):typeof n==`number`&&n>=hl&&n<=gl?new T(It(n),o):typeof n==`string`?xl(n,o):new T(`bad_response`,o)}function Cl(e,t,n){return e?.kind===`auth`?e:new T(It(t),e?.message??n)}var wl=i({location:i({latitude:x().min(-90).max(90),longitude:x().min(-180).max(180)})}),Tl=[`googleSearch`,`googleMaps`,`urlContext`,`codeExecution`],El={googleSearch:`google_search`,googleMaps:`google_maps`,urlContext:`url_context`,codeExecution:`code_execution`};function Dl(e){return e.filter(e=>Tl.includes(e.id))}function Ol(e){let t=Tl.find(t=>t===e.id);if(!t)throw new T(`config`,`Builtin '${e.id}' is not a Google tool`);return t}function kl(e){let t=Ol(e),n=El[t];if(t===`googleMaps`&&e.args){let{location:t}=wl.parse(e.args);return{type:n,latitude:t.latitude,longitude:t.longitude}}return{type:n}}function Al(e){let t=Ol(e);if(e.args)throw new T(`unsupported`,`Builtin '${t}' takes no args on Google Live`);return{[t]:{}}}function jl(e){return{type:`text`,text:`[${e.type}: sent in the next message]`}}function Ml(e){return{type:`text`,text:`Files from ${e.name?`the ${e.name} result`:`a tool result`}:`}}function Nl(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:jl(e))}),r.push(Ml(a),...e))}return i(),n}function Pl(e){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=r);return t}function Fl(e){if(typeof e==`string`){let t=e.trim();if(t.length===0)return{ok:!0,value:{}};try{let n=JSON.parse(t);return A(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 A(e)?{ok:!0,value:e}:e==null?{ok:!0,value:{}}:{ok:!1,error:`tool arguments must be a JSON object`,raw:String(e)}}function Il(e){let t=Fl(e);if(!t.ok)throw new T(`bad_response`,t.error);return t.value}function Ll(e,t){let n=e.name.trim(),r={name:n,callId:e.id??Cc(n)},i={stepId:e.stepId,stepCallCount:e.stepCallCount};if(!n)return Rl(r,`function call is missing a name`,t,i);let a=Fl(t);return a.ok?[Sc(r,a.value,i)]:Rl(r,a.error,a.raw,i)}function Rl(e,t,n,r={}){return[Sc(e,{},r),xc(e,{code:`malformed_arguments`,kind:`bad_response`,message:t,details:{raw:n}})]}function zl(e){if(e&&!Gc.includes(e))throw new T(`unsupported`,`Gemini does not take the '${e}' thinking level (${Gc.join(`, `)})`)}function Bl(e){return e.replaceAll(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}function Vl(e){if(Array.isArray(e))return e.map(Vl);if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))n===`schema`||n===`parameters`||n===`arguments`?t[Bl(n)]=r:t[Bl(n)]=Vl(r);return t}return e}function Hl(e){return Sa(e)}var Ul=`user_input`;function Wl(e){return{type:Ul,content:e.map(Hl)}}function Gl(e){let t=K(e);return t.length>0?t.map(Hl):[{type:`text`,text:``}]}var Kl=new Set([`text`,`image`,`video`]);function ql(e){let t=K(e);return{type:`function_result`,...Pl({name:e.name,call_id:e.tool_call_id}),result:t.length>0?t.map(Hl):[{type:`text`,text:``}]}}function Jl(e,t){let n={type:`function_call`,id:e.id,name:e.function.name,arguments:Il(e.function.arguments)};return t?[{type:`thought`,signature:t},n]:[n]}var Yl=i({call:x().int().min(0),signature:S().min(1)});function Xl(e,t){for(let n of e.reasoning??[]){let e=Yl.safeParse(n.data);if(e.success&&e.data.call===t)return e.data.signature}}function Zl(e,t){return{type:e===`assistant`?`model_output`:`user_input`,content:Gl(t)}}function Ql(e){if(e.role===`assistant`&&e.tool_calls&&e.tool_calls.length>0){let t=[];K(e).length>0&&t.push(Zl(`assistant`,e));for(let[n,r]of e.tool_calls.entries())t.push(...Jl(r,Xl(e,n)));return t}return e.role===`assistant`?[Zl(`assistant`,e)]:[Zl(`user`,e)]}function $l(e){return Nl(e,Kl).flatMap(e=>e.role===`tool`?[ql(e)]:Ql(e))}function eu(e){return[{type:`text`,mimeType:`application/json`,schema:e}]}function tu(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&&!Kc.includes(n))throw new T(`unsupported`,`Gemini speech returns ${Kc.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=eu(e.structured.jsonSchema))}function nu(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 ru=new Set([`gemini-3.8-flash-tts`,`gemini-3.8-flash-lite-tts`]);function iu(e,t,n){if(!ru.has(n))return{type:Ul,content:[{type:`text`,text:`Read the following aloud. ${t.trim()}\n`},...e.map(Hl)]};let r=[{type:`speech_metadata`,style:t}];return{type:Ul,content:e.map(Hl).map(e=>e.type===`text`?{...e,annotations:r}:e)}}function au(e){return{type:`function`,name:e.name,description:e.description,parameters:e.parameters}}function ou(e){let t=[];for(let n of e.builtins)t.push(kl(n));for(let n of e.wireTools??[])t.push(au(n));return t}function su(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 cu(e){if(e.continuation&&e.continuation.length>0)return $l(su(e.continuation));let t=$l(su(e.history??[]));if(e.input.length>0||t.length===0){let n=e.speech?.style;t.push(n?iu(e.input,n,e.apiId):Wl(e.input))}return t}function lu(e,t){e.store!==void 0&&(t.store=e.store),e.previousInteractionId&&(t.previousInteractionId=e.previousInteractionId),e.system&&(t.systemInstruction=e.system);let n=ou(e);n.length>0&&(t.tools=n)}function uu(e){let t={temperature:e.temperature,maxOutputTokens:e.maxOutputTokens};return e.speech?nu(e,t):(zl(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:cu(e),generationConfig:t}}function du(e){let t=uu(e);return tu(e,t),lu(e,t),Vl(t)}var fu=16,pu=new Set([`audio/pcm`,`audio/l16`]);function mu(e,t,n){for(let r=0;r<n.length;r++)e.setUint8(t+r,n.charCodeAt(r))}function hu(e){if(e===void 0||!/^\d+$/.test(e))return;let t=Number(e);return t>0?t:void 0}function gu(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 _u(e){let{essence:t,params:n}=gu(e);if(!pu.has(t))return;let r=hu(n.get(`rate`));if(r===void 0)return;let i=n.has(`channels`)?hu(n.get(`channels`)):1;if(i!==void 0)return{sampleRate:r,channels:i}}function vu(e,t){let{sampleRate:n,channels:r}=t,i=r*fu/8,a=n*i,o=e.length,s=new ArrayBuffer(44+o),c=new DataView(s);return mu(c,0,`RIFF`),c.setUint32(4,36+o,!0),mu(c,8,`WAVE`),mu(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,fu,!0),mu(c,36,`data`),c.setUint32(40,o,!0),new Uint8Array(s,44).set(e),new Uint8Array(s)}function yu(e){let t=_u(e.mimeType);if(!t)return e;let n=vu(tt(e.data),t);return{mimeType:`audio/wav`,data:at(n)}}function bu(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 xu(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 Su(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 Cu(e){if(!e)return[];let{grounding:t,sources:n}=e;return[{type:`grounding`,grounding:t},...n.length>0?[{type:`citation`,sources:n}]:[]]}function wu(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 Tu(e){return{maps:{title:e.title,uri:e.uri,...e.placeId?{placeId:e.placeId}:{}}}}function Eu(e){let t=X(e.uri);if(t)return{type:`web`,uri:t,title:X(e.title)??t}}function Du(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 Ou(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 ku(e){if(Array.isArray(e))for(let t of e){let e=X(Y(t)?.search_suggestions);if(e)return e}}function Au(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 ju(e,t){if(Array.isArray(t))for(let n of t)Du(e,Au(n))}function Mu(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?wu(t):void 0;r&&Du(e,r)}}}function Nu(e){let t=[];if(ju(t,e.annotations),Array.isArray(e.content))for(let n of e.content)ju(t,Y(n)?.annotations);Mu(t,e.result);let n=[];for(let e of t)e.type===`maps`&&Ou(n,Tu(e));let r=ku(e.result);if(r||t.length!==0)return{grounding:{metadata:e,...n.length>0?{chunks:n}:{},...r?{searchHtml:r}:{}},sources:t}}function Pu(e,t){if(!e)return t;if(!t)return e;let n=[];for(let r of[...e.grounding.chunks??[],...t.grounding.chunks??[]])Ou(n,r);let r=[...e.sources];for(let e of t.sources)Du(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 Fu(e){let t=Y(e.delta);return Cu(t?Nu(t):void 0)}function Iu(e){let t;for(let n of e){let e=Y(n);e&&(t=Pu(t,Nu(e)))}return Cu(t)}function Lu(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&&Du(r,Eu(t))}let i=X(Y(t.searchEntryPoint)?.renderedContent);return Cu({grounding:{metadata:t,...n.length>0?{chunks:n}:{},...i?{searchHtml:i}:{}},sources:r})}function Ru(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 zu(e,t){if(e||t)return{...e?{input:e}:{},...t?{output:t}:{}}}function Bu(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 Vu(e){let t=Y(e);return t?.type===`text`&&typeof t.text==`string`?t.text:``}function Hu(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 Uu(e){let t=Hu(e),{data:n}=e;return!t||typeof n!=`string`||!n?[]:[{type:`media`,media:{mimeType:t,data:n}}]}function Wu(e,t){return t?[{type:e,text:t}]:[]}function Gu(e){return e===`code_execution_call`||e===`code_execution_result`}function Ku(e){return e.startsWith(`google_`)||e===`url_context_call`||e===`url_context_result`}function qu(e){return{type:`evidence`,evidence:{provider:`google`,kind:`provider_step`,step:String(e.type??``),raw:e}}}function Ju(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`?qu(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 Yu(e){let t=Y(e);if(!t)return[];switch(t.type){case`thought_summary`:return Wu(`thought`,Vu(t.content));case`text`:return Wu(`text`,typeof t.text==`string`?t.text:``);case`image`:case`audio`:return Uu(t);default:return[]}}function Xu(e){return(Array.isArray(e.summary)?e.summary:[]).flatMap(e=>Wu(`thought`,Vu(e)))}function Zu(e){return(Array.isArray(e.content)?e.content:[]).flatMap(e=>{let t=Y(e);return t?.type===`text`?Wu(`text`,typeof t.text==`string`?t.text:``):t?.type===`image`||t?.type===`audio`?Uu(t):[]})}function Qu(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 mo({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:zu(Ru(t.input_tokens_by_modality,`tokens`),Ru(t.output_tokens_by_modality,`tokens`)),grounding:Bu(t.grounding_tool_count)})}function $u(e){let t=Qu(e.usage);if(!t)return;let n=typeof e.id==`string`?e.id:void 0;return{type:`tokens`,tokens:t,...n?{interactionId:n}:{}}}function ed(e){let t=[],n=$u(e);n&&t.push(n);let{steps:r}=e;Array.isArray(r)&&t.push(...Iu(r));let i=nd(e);return i&&t.push(i),t}function td(e){let t=X(e.id),n=X(e.model);if(t||n)return{...t?{id:t}:{},...n?{model:n}:{}}}function nd(e){let{status:t}=e;if(typeof t==`string`)return{type:`done`,stop:fo(t),...typeof e.id==`string`?{interactionId:e.id}:{}}}function rd(){return{text:``,steps:new Map,sawMedia:!1,sawDone:!1,calls:0}}function id(e){return e===`function_call`||Gu(e)||Ku(e)}function ad(e){return typeof e==`string`&&e.length>0?e:void 0}function od(e,t){let n=ad(e);n&&(t.thoughtSignature=n)}function sd(e,t){let n=ad(e.signature)??t.thoughtSignature;return t.thoughtSignature=void 0,n}function cd(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=sd(e,t),a=t.calls++;return[...i?[{type:`reasoning`,data:{call:a,signature:i},origin:{protocol:`geminiInteractions`}}]:[],...Ll({id:n,name:r},e.arguments)]}return Gu(n)?[Ju(e)]:Ku(n)?[qu(e)]:n===`thought`?(od(e.signature,t),Xu(e)):n===`model_output`?Zu(e):[]}function ld(e){return typeof e.index==`number`?e.index:0}function ud(e,t){let n=Y(e.step);if(!n)return;let r=String(n.type??``);r===`thought`&&od(n.signature,t),id(r)&&t.steps.set(ld(e),{...n})}function dd(e,t){let n=Y(e.delta);if(!n)return[];let r=t.steps.get(ld(e));if(!r)return n.type===`thought_signature`&&od(n.signature,t),Yu(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`?Su({id:ad(r.id),name:typeof r.name==`string`?r.name:``,args:t,drafted:e.length}):[]}return Object.assign(r,n),[]}function fd(e,t){let n=ld(e),r=t.steps.get(n);return r?(t.steps.delete(n),cd(r,t)):[]}function pd(e){let t=Gu(String(e.type??``))?Ju(e):qu(e);return{...t,evidence:{...t.evidence,partial:!0}}}function md(e){let t=[...e.steps.values()].map(pd);return e.steps.clear(),t}function hd(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:yu(e.media)})))}function gd(e,t){if(e.eventType===`sse_unparsed`)return[I(new T(`bad_response`,`Interactions stream row was not a JSON object`))];let n=Sl(e);if(n)return[I(n)];let r=Fu(e);switch(e.event_type){case`step.start`:ud(e,t);break;case`step.delta`:r.push(...dd(e,t));break;case`step.stop`:r.push(...fd(e,t));break;case`interaction.created`:{let n=Y(e.interaction);n&&r.push(..._d(n,t));break}case`interaction.completed`:{let n=Y(e.interaction);n&&r.push(..._d(n,t),...ed(n));break}}return r}function _d(e,t){let n=bu(t.response,td(e));return t.response=n.known,n.event?[n.event]:[]}function vd(e,t){return hd(gd(e,t),t)}function yd(e,t){let n=(Array.isArray(e.steps)?e.steps:[]).flatMap(e=>{let n=Y(e);return n?cd(n,t):[]});return hd([..._d(e,t),...n,...ed(e)],t)}function*bd(e,t){e.structured&&t.text&&(yield xu(t.text))}function xd(e){return!!e.speech}function Sd(e,t){if(!t.sawMedia){if(xd(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 Cd(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 wd=i({interactionId:S().min(1)}),Td=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 Ed(e,t){let n=t.history??[],r=e.options.persistViaInteractionId?t.state?.interactionId:void 0,i=Dl(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(du(a)))),wroteTools:i.map(e=>e.id)}}function Dd(e,t,n){return e.flatMap(e=>{if(e.type!==`done`){let t=Cd(e);return t?[t]:[]}let{interactionId:r,...i}=e;return t.done={...i,...n&&r?{state:{interactionId:r}}:{}},[]})}var Od=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:Td,continuation:{version:1,schema:wd,keyOptions:[`store`,`persistViaInteractionId`]},reasoning:Yl,error(e){let t=Y(e.body);return Cl(t?Sl(t):null,e.status,`Gemini HTTP ${e.status}`)},create(e){return{async*complete(t){let{wire:n,body:r,wroteTools:i}=Ed(e,t),a=t.stream!==!1,o=!!e.options.persistViaInteractionId,s={fold:rd()},c={stream:a,wroteTools:i,...a?{path:`/interactions?alt=sse`}:{}};for await(let t of e.send(r,c)){let e=Sl(t);if(e)throw e;let n=a?vd(t,s.fold):yd(t,s.fold);if(yield*Dd(n,s,o),n.some(e=>e.type===`error`)){yield*Dd(md(s.fold),s,o);return}}yield*Dd(md(s.fold),s,o),yield*Dd([...bd(n,s.fold)],s,o);let l=Sd(n,s.fold);l&&(yield*Dd([l],s,o)),yield s.done??{type:`done`,stop:{kind:`stream_incomplete`}}}}}}),kd=`NON_BLOCKING`;function Ad(e){return{name:e.name,description:e.description,behavior:kd,parametersJsonSchema:e.parameters??{type:`object`,properties:{}}}}function jd(e){let t=[];for(let n of e.builtins)t.push(Al(n));let n=(e.wireTools??[]).map(Ad);return n.length>0&&t.push({functionDeclarations:n}),t}function Md(e){let t={responseModalities:[`AUDIO`],temperature:e.temperature,maxOutputTokens:e.maxOutputTokens};e.live?.voice&&(t.speechConfig={voiceConfig:{prebuiltVoiceConfig:{voiceName:e.live.voice}}}),zl(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 Nd(e){let{triggerTokens:t}=e,{targetTokens:n}=e.slidingWindow;return{...t===void 0?{}:{triggerTokens:t},slidingWindow:n===void 0?{}:{targetTokens:n}}}function Pd(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 Fd(e){if(e.sessionResumptionHandle)return{handle:e.sessionResumptionHandle};if(e.live?.sessionResumption)return{}}function Id(e){return e.startsWith(`models/`)?e:`models/${e}`}function Ld(e,t){e?.transcription?.input&&(t.inputAudioTranscription={}),e?.transcription?.output&&(t.outputAudioTranscription={})}function Rd(e){let t=e.live,n=t?.vad?Pd(t.vad):void 0,r=jd(e),i=Fd(e),a=!!(e.history&&e.history.length>0),o={model:Id(e.apiId),generationConfig:Md(e),systemInstruction:{parts:[{text:e.system}]},...r.length>0?{tools:r}:{},...i?{sessionResumption:i}:{},...t?.contextCompression?{contextWindowCompression:Nd(t.contextCompression)}:{},...a?{historyConfig:{initialHistoryInClientContent:!0}}:{},...n?{realtimeInputConfig:n}:{}};return Ld(t,o),{setup:o}}function zd(e){if(Ca(e))throw new T(`unsupported`,`media references are not supported on geminiLive`);return e}function Bd(e){let t=zd(e);return{mimeType:t.mimeType,data:t.data}}function Vd(e){return e.type===`text`?{text:e.text}:{inlineData:Bd(e)}}function Hd(e){let t=K(e),n=t.map(e=>e.type===`text`?e.text:``).filter(Boolean).join(`
4
+ `),r=t.filter(e=>e.type!==`text`).map(Vd);return{role:`user`,parts:[{functionResponse:{...Pl({id:e.tool_call_id,name:e.name}),response:{result:n},...r.length>0?{parts:r}:{}}}]}}function Ud(e){if(e.role===`tool`)return Hd(e);let t=e.role===`assistant`?`model`:`user`,n=K(e).map(Vd);for(let t of e.role===`assistant`?e.tool_calls??[]:[])n.push({functionCall:{id:t.id,name:t.function.name,args:Il(t.function.arguments)}});return{role:t,parts:n}}function Wd(e){return!e||e.length===0?null:{clientContent:{turns:e.map(Ud),turnComplete:!0}}}function Gd(e){return{clientContent:{turns:[{role:`user`,parts:[{text:e}]}],turnComplete:!1}}}function Kd(e){if(e.type===`text`)return{realtimeInput:{text:e.text}};let t=zd(e),n={mimeType:t.mimeType,data:t.data};return{realtimeInput:t.type===`audio`?{audio:n}:{video:n}}}function qd(e){let t=Y(e)?.error;return typeof t==`string`?{error:t}:{result:e}}function Jd(e,t,n,r){return Yd([{id:e,name:t,output:n,parts:r}])}function Yd(e){return{toolResponse:{functionResponses:e.map(({id:e,name:t,output:n,parts:r})=>({id:e,name:t,response:qd(n),...r?.length?{parts:r.filter(e=>e.type!==`text`).map(Vd)}:{}}))}}}function Xd(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 Zd(e){return Array.isArray(e)?e.flatMap(e=>{let t=Y(e);return t?[t]:[]}):[]}function Qd(e){let t=[],n=[],r=[];for(let i of Zd(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(Xd(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 $d(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 Zd(n.turns).flatMap(Qd);let r=Y(e.toolResponse);return r?Zd(r.functionResponses).map(Xd):[]}function ef(e){let t=Z(e.promptTokenCount),n=Z(e.responseTokenCount),r=Z(e.thoughtsTokenCount)??0,i=Z(e.toolUsePromptTokenCount)??0;return mo({input:t?t+i:void 0,output:n===void 0?void 0:n+r,thinking:r,toolUse:i,cached:Z(e.cachedContentTokenCount),byModality:zu(Ru(e.promptTokensDetails,`tokenCount`),Ru(e.responseTokensDetails,`tokenCount`))})}function tf(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 nf(){return{calls:new Map}}function rf(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(...Ll({id:o,name:s,stepId:i,stepCallCount:a},r.args))}}function af(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(vc({name:r,callId:e},{phase:`cancel`})))}}function of(e,t){let n=Y(e.voiceActivity);n&&t.push({type:`evidence`,evidence:{provider:`google`,kind:`voice_activity`,raw:n}})}function sf(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 cf(e,t){let n=Y(e.goAway);if(!n)return;let r=sf(n.timeLeft);t.push({type:`session`,session:{kind:`closing_soon`,...r===void 0?{}:{timeLeftMs:r}}})}function lf(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:yu({mimeType:r,data:i})});let a=Y(e.codeExecutionResult);a&&t.push(uf(a))}function uf(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 df(e){let t=Y(e)?.text;return typeof t==`string`&&t?t:void 0}function ff(e,t,n,r){let i=df(e);i&&n.push({type:`evidence`,text:i,evidence:{provider:`google`,kind:t,...r?{interim:!0}:{}}})}function pf(e,t){t.push(...Lu(e.groundingMetadata));let n=Y(e.urlContextMetadata);n&&t.push({type:`evidence`,evidence:{provider:`google`,kind:`url_context`,raw:n}})}function mf(e){let t=Y(e.serverContent)?.interactionStatus;if(t===`IN_PROGRESS`||t===`IDLE`)return t}function hf(e,t){let n=mf(e);n&&t.push({type:`session`,session:{kind:n===`IDLE`?`idle`:`working`}})}function gf(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`}}),ff(n.inputTranscription,`input_transcription`,t),ff(n.interimInputTranscription,`input_transcription`,t,!0),ff(n.outputTranscription,`output_transcription`,t);let r=Y(n.modelTurn)?.parts;for(let e of Array.isArray(r)?r:[]){let n=Y(e);n&&lf(n,t)}pf(n,t),n.turnComplete===!0&&t.push({type:`session`,session:{kind:`turn_complete`}})}function _f(e,t){let n=Y(e.usageMetadata),r=n?ef(n):void 0;r&&t.push({type:`tokens`,tokens:r})}function vf(e,t){if(!e||typeof e!=`object`)return[];let n=[];return cf(e,n),tf(e,n),rf(e,t,n),af(e,t,n),of(e,n),gf(e,n),hf(e,n),_f(e,n),n}var yf={1006:`network`,1007:`unsupported`,1008:`unsupported`,1011:`unavailable`,1013:`busy`},bf=/\bquota\b/i,xf=/\bAPI key (?:not valid|expired)\b/i;function Sf(e){if(bf.test(e))return`rate_limit`;if(xf.test(e))return`auth`}function Cf(e,t,n){return new T(Sf(t)??yf[e]??`unavailable`,`Gemini Live WebSocket closed during ${n} (${e}: ${t})`)}function wf(e){let t=po(e,e=>e.type===`session`&&e.session.kind===`closing_soon`);return t?.session.kind===`closing_soon`?{timeLeftMs:t.session.timeLeftMs}:void 0}function Tf(e,t){if(t.some(e=>e.type===`done`&&e.interrupted===!0))return`abort`;let n=mf(e);return n===`IDLE`?`complete`:n===`IN_PROGRESS`?`streaming`:Y(e.serverContent)?.turnComplete===!0?`complete`:`streaming`}var Ef=i({liveHandle:S().min(1)}),Df=1e3;function Of(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`):Sl(e)??void 0}async function kf(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 Cf(1006,``,`setup`);let n=t.value;if(n.eventType===`ws_close`)throw Cf(Number(n.code),String(n.reason??``),`setup`);let i=Of(n,`setup`);if(i)throw i;if(n.setupComplete)return}}finally{clearTimeout(n)}}function Af(e,t){let n=t.state?.liveHandle,r=t.history??[],i=Dl(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(Rd(a)))),wroteTools:i.map(e=>e.id)}}function*jf(e,t,n){let r=[...e.filter(e=>e.type===`tokens`),...e.filter(e=>e.type!==`tokens`)];for(let e of r){let t=Cd(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 Mf(e,t,n,r){let i=t=>Ff(e,t),a=nf(),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===Df?{}:{error:Cf(e,t,`session`)},...s?{warning:{...s.timeLeftMs===void 0?{}:{timeLeftMs:s.timeLeftMs},closedAfterMs:Math.round(performance.now()-s.atMs)}}:{}};return}let i=Of(r,`session`);if(i)throw i;if(r.setupComplete)continue;let l=vf(r,a),u=wf(l);u&&(s={...u,atMs:performance.now()});for(let e of l)e.type===`evidence`&&e.sessionResumptionHandle&&(o=e.sessionResumptionHandle);yield*jf(l,Tf(r,l),o)}},sendText:e=>Pf(()=>i(Kd({type:`text`,text:e}))),sendAudio:e=>Pf(()=>i(Kd({type:`audio`,...e}))),sendVideo:e=>Pf(()=>i(Kd({type:`video`,...e}))),sendContext:e=>Pf(()=>i(Gd(typeof e.server==`string`?e.server:JSON.stringify(e)))),sendToolResult:e=>Pf(()=>i(Jd(e.callId,e.name,e.text,e.parts))),close:t=>Pf(()=>e.close(Df,t??`session-closed`))}}var Nf=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:Ef},create(e){return{async openSession(t){let{wire:n,setup:r,wroteTools:i}=Af(e,t),a=await e.connect(r,{wroteTools:i}),o=a.frames()[Symbol.asyncIterator](),s=()=>a.close(Df,`aborted`);e.signal?.addEventListener(`abort`,s,{once:!0});try{e.signal?.throwIfAborted(),await kf(o,e)}catch(t){throw e.signal?.removeEventListener(`abort`,s),a.close(Df,`setup-failed`),t}let c=n.history?.length?Wd(n.history):void 0;c&&Ff(a,c);for(let e of n.input)Ff(a,Kd(e));return Mf(a,o,e,n.sessionResumptionHandle)}}}});function Pf(e){try{return e(),Promise.resolve()}catch(e){return Promise.reject(e)}}function Ff(e,t){e.send(t,$d(t))}var If={input:.75,output:4.5,byModality:{input:{audio:3,image:1,video:1},output:{audio:12}}},Lf={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":If,"gemini-3.8-live-extended-thinking":If,"gemini-3.1-flash-live-preview":If,"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}}},Rf=Hc({id:`gemini`,name:`Gemini`,description:`Google's models with an API key, from Google AI Studio.`,traceName:`gcp.gemini`,connection:i({host:Lc.refine(e=>{let t=new URL(e);return t.pathname===`/`&&!t.search&&!t.hash},k(`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:zc(`x-goog-api-key`),prices:Lf,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:Od,baseUrl:`${n}/v1beta`},{protocol:ol,baseUrl:`${n}/v1beta`},{protocol:Nf,baseUrl:`${r}/ws`,authorize:Bc(`key`)}]}});function zf(e){if(Ca(e))throw new T(`unsupported`,`media references are not supported on openAi`)}function Bf(e){let t=`mp3`;return e.mimeType.includes(`wav`)&&(t=`wav`),{type:`input_audio`,input_audio:{data:e.data,format:t}}}function Vf(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}:(zf(e),e.type===`image`?{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}}:e.type===`audio`?Bf(e):{type:`file`,file:{filename:e.type===`video`?`clip.bin`:`document.bin`,file_data:`data:${e.mimeType};base64,${e.data}`}}))}function Hf(e){let t=Vf(K(e));if(e.role===`tool`)return{role:`tool`,...Pl({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 Uf=new Set([`text`,`image`]);function Wf(e,t){let n=t?.includeSystem!==!1,r=[];n&&e.system&&r.push({role:`system`,content:e.system});for(let t of Nl(e.history??[],Uf))r.push(Hf(t));return e.input.length>0&&r.push({role:`user`,content:Vf(e.input)}),r}function Gf(e){if(e&&e.length!==0)return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:e.parameters}}))}function Kf(e){return e.replace(/[^A-Za-z0-9_-]/g,`_`).slice(0,64)}function qf(e){if(e)return{type:`json_schema`,json_schema:{name:Kf(e.id),strict:!0,schema:e.jsonSchema}}}function Jf(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 Yf(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 Xf(e,t){let n=Yf(e,{audio_tokens:`audio`,video_tokens:`video`}),r=Yf(t,{image_tokens:`image`,audio_tokens:`audio`});if(n||r)return{...n?{input:n}:{},...r?{output:r}:{}}}function Zf(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 mo({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:Jf(t),byModality:Xf(n,r)})}function Qf(e){let t=X(e.id),n=X(e.model);if(t||n)return{...t?{id:t}:{},...n?{model:n}:{}}}function $f(e){return e.flatMap(e=>Cd(e)??[])}function ep(e,t){let n=t.stream!==!1,r=Gf(t.wireTools),i=qf(t.structured),a={model:e.apiId,messages:Wf(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 tp(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 np(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 rp(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 ip(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(...np(e,t)),rp(e,t),r}function ap(e,t,n,r){tp(e);let i=[],a=bu(t.response,Qf(e));t.response=a.known,a.event&&i.push(a.event);let o=t.tokens?void 0:Zf(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(...ip(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(...$f(Su(e)));return i}function op(e,t){let n=[];for(let[t,r]of e.calls)n.push(...$f(Ll({...r,id:r.id??`call_${t}`},r.args)));let r=lo(e.finish,e.native);if(t.structured&&e.text&&r.kind===`completed`){let t=$f([xu(e.text)]);if(n.push(...t),t[0]?.type===`error`)return n}return n.push({type:`done`,stop:r}),n}async function*sp(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`?tt(t.data):new Uint8Array;if(!n.length)throw new T(`bad_response`,`no audio returned from speech`);let r=_u(e);yield{type:`media`,media:r?{mimeType:`audio/wav`,data:at(vu(n,r))}:{mimeType:$i(e)||`application/octet-stream`,data:t.data}},yield{type:`done`,stop:{kind:`completed`}}}}var cp=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*sp(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(ep(e,t),{stream:n}))yield*ap(i,r,t,n);yield*op(r,t)}}}}),lp=Hc({id:`local`,name:`Local`,description:`A server that speaks OpenAI's chat API: Ollama, llama.cpp, vLLM, LM Studio.`,traceName:`openai`,connection:i({baseUrl:Lc.describe(`Where the server listens, up to and including /v1, e.g. http://localhost:11434/v1.`)}),key:S().trim().min(1).optional(),authorize:Rc(),serves:e=>[{protocol:cp,baseUrl:e.baseUrl},{protocol:ll,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()}}]}),up=`openrouter:image_generation`;function dp(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 fp(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 pp(e){return(Array.isArray(e.images)?e.images:[]).flatMap(e=>{let t=fp(Y(Y(e)?.image_url)?.url);return t?[t]:[]})}function mp(e){return e.filter(e=>e.type===`text`).map(e=>e.type===`text`?e.text:``).join(`
6
+ `).trim()}function hp(e){let t=e.toLowerCase().replace(/^image\//,``);return t===`jpg`?`jpeg`:t===`png`||t===`jpeg`||t===`webp`?t:`png`}var gp=/^https?:\/\//i;function _p(e){return{type:`image_url`,image_url:{url:Ca(e)?e.uri:`data:${e.mimeType};base64,${e.data}`}}}function vp(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)&&!gp.test(n.uri))throw new T(`unsupported`,`only http(s) media references are supported on /images`);t.push(_p(n))}return t}function yp(e,t){t.aspectRatio&&(e.aspect_ratio=t.aspectRatio),t.resolution&&(e.resolution=t.resolution),t.mimeType&&(e.output_format=hp(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 bp(e){if(!e.image)throw Error(`buildImagesPayload requires req.image`);let t={model:e.apiId,prompt:mp(e.input)};yp(t,e.image);let n=vp(e.input);return n.length>0&&(t.input_references=n),e.stream===!1&&(t.stream=!1),t}function xp(e){let t={};e.mimeType&&(t.output_format=hp(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 Sp(e){return JSON.parse(JSON.stringify(e))}function Cp(e){let t=Zf(e.usage);return t?[{type:`tokens`,tokens:t}]:[]}function wp(){return new T(`bad_response`,`no image returned from image generation`)}async function*Tp(e,t){let n=Sp(bp({...t,apiId:e.apiId}));for await(let t of e.send(n,{stream:!1})){let e=dp(t);if(!e.length)throw wp();for(let t of e)yield{type:`media`,media:t};yield*Cp(t),yield{type:`done`,stop:{kind:`completed`}}}}async function*Ep(e,t,n){let r=Sp({model:e.apiId,stream:!1,provider:{require_parameters:!0},messages:Wf(t),temperature:t.temperature,max_tokens:t.maxOutputTokens,...t.thinking?{reasoning:{effort:t.thinking}}:{},tools:[{type:up,parameters:xp(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?pp(n):[];if(!i.length)throw wp();for(let e of i)yield{type:`media`,media:e};yield*Cp(t),yield{type:`done`,stop:lo(typeof e?.finish_reason==`string`?e.finish_reason:void 0,typeof e?.native_finish_reason==`string`?e.native_finish_reason:void 0)}}}var Dp=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(!mp(t.input))throw new T(`request`,`empty text for image generation`);return n.includeText?Ep(e,t,n):Tp(e,t)}}}});function Op(e,t){let n=``;for(let r of Array.isArray(e.choices)?e.choices:[]){if(!A(r))continue;let e=A(r.delta)?r.delta:A(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 kp=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.`),Ap=i({details:y(L),content:S().optional()});function jp(e){return e.ttl?{type:`ephemeral`,ttl:e.ttl}:{type:`ephemeral`}}function Mp(e){let t=Y(e)?.tool_calls;return Array.isArray(t)?t.map(e=>String(Y(e)?.id)):[]}function Np(e,t){for(let n of e){let e=Mp(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=>Ap.safeParse(e.data)).find(e=>e.success);r?.success&&(n.reasoning_details=r.data.details,r.data.content&&(n.reasoning=r.data.content))}}function Pp(e){return Array.isArray(e)?e.filter(e=>typeof e==`string`):[]}function Fp(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(Pp)}function Ip(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 Lp(e){return(Array.isArray(e.choices)?e.choices:[]).map(e=>Y(Y(e)?.delta)?.thinking).filter(e=>typeof e==`string`).join(``)}var Rp=Ba(cp,{id:`openRouter`,name:`OpenRouter Chat Completions`,description:`Chat Completions with OpenRouter's caching, routing, web search, citations and reasoning.`,options:i({cache:kp.optional()}),reasoning:Ap,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=jp(i)),i?.mode===`system`&&r[0]?.role===`system`&&(r[0]={...r[0],content:[{type:`text`,text:r[0].content??``,cache_control:jp(i)}]}),Np(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+=Op(a,t);let o=[],s=Lp(a);s&&e.request?.summaries!==`none`&&o.push({type:`thought`,text:s});let c=Fp(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=Ip(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}:{}}}]}}}}}),zp=x().int().nonnegative(),Bp=w({model:S().min(1),answers:C(S(),a()),usage:w({input_tokens:zp,output_tokens:zp,cost:x().nonnegative().optional()}).optional().catch(void 0)}),Vp=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`,Up=`TypeSafe-Danger-Zone-Long-Context`,Wp=q({id:`systemOne`,name:`System One`,description:`TypeSafe's decision API: questions about a state, answered in one call.`,endpoints:{decision:`/systemone`},options:Vp,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`,k(`provider.decision_images_off`));if(n&&/^jev-1\.13(\.|$)/.test(e.apiId))throw new T(`unsupported`,k(`provider.decision_box_model`,{apiId:e.apiId}));let i={};r&&(i[Hp]=`true`),e.options.longContext&&(i[Up]=`true`);let a=L.parse({model:e.apiId,state:t.state,questions:t.questions,...t.assets&&Object.keys(t.assets).length?{assets:Kp(t.assets)}:{}});for await(let t of e.send(a,{stream:!1,headers:i})){let e=Bp.safeParse(t);if(!e.success)throw new T(`bad_response`,k(`protocol.reply_shape`,{protocol:`systemOne`,issues:Fe(e.error)}));let{model:n,answers:r,usage:i}=e.data;return{model:n,answers:r,...i?{usage:{inputTokens:i.input_tokens,outputTokens:i.output_tokens,...i.cost===void 0?{}:{costUsd:i.cost}}}:{}}}throw new T(`bad_response`,k(`provider.decision_failed`))}}}}),Gp={"image/png":`png`,"image/jpeg":`jpeg`};function Kp(e){return Object.fromEntries(Object.entries(e).map(([e,{mimeType:t,data:n}])=>[e,{type:`image`,format:Gp[t],data_base64:n}]))}var qp=Hc({id:`openrouter`,name:`OpenRouter`,description:`Many labs' models behind one key.`,connection:i({baseUrl:Lc.optional().describe(`The API, by default https://openrouter.ai/api/v1.`),decisionUrl:Lc.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:Rc(),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:Rp,baseUrl:t,headers:n},{protocol:ml,baseUrl:t,headers:n},{protocol:Dp,baseUrl:t,headers:n},{protocol:Wp,baseUrl:r,url:()=>r,headers:n}]}}),Jp=Hc({id:`typesafe`,name:`TypeSafe`,description:`System One decisions, at TypeSafe's own API.`,connection:i({baseUrl:Lc.optional().describe(`The API, by default https://api.typesafe.ai/v1.`)}).default({}),key:S().trim().min(1),authorize:Rc(),prices:{checked:`2026-10-19`,models:{"jev-*":{input:.042,output:0}}},serves:e=>[{protocol:Wp,baseUrl:e.baseUrl??`https://api.typesafe.ai/v1`}]}),Yp=`local`;function Xp(e,t){return!t&&e===`local`}function Zp(e=`http://localhost:11434`){return`${e.replace(/\/$/,``)}/v1`}var Qp=[{id:`gemini`,definition:`gemini`},{id:`openrouter`,definition:`openrouter`},{id:Yp,definition:`local`,connection:{baseUrl:Zp()}},{id:`typesafe`,definition:`typesafe`}],$p={gemini:{provider:Rf,factory:`geminiProvider`},openrouter:{provider:qp,factory:`openRouterProvider`},local:{provider:lp,factory:`localProvider`},typesafe:{provider:Jp,factory:`typesafeProvider`}};function em(e){return e===void 0?void 0:$p[e]?.provider}function tm(){return Object.keys($p)}function nm(e){return Object.keys($p).find(t=>$p[t]?.factory===e)}function rm(e){return $p[e]?.factory}function im(e,t){return e.find(e=>e.id===t)?.definition}function am(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 om(e,t,n=em(t.definition),r=`register`){if(!n)throw Error(`The studio does not hold the provider definition '${t.definition}'.`);return e[r](n,am(t))}function sm(e){let t=em(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 cm(e){let t=em(e);return t===void 0||t.key!==void 0}function lm(e){let t=[];e.id.trim()||t.push({field:`id`,message:`Provider id is required.`});let n=em(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:k(`provider.fallback_slot`)}),(e.keySlot||e.fallbackKeySlot)&&n&&!n.key&&t.push({field:`keySlot`,message:k(`protocol.no_key`,{provider:e.id})}),t}function um(e,t){return Ka(e.find(e=>e.id===t.provider)??{},{...t.keySlot?{keySlot:t.keySlot}:{},...t.fallbackKeySlot?{fallbackKeySlot:t.fallbackKeySlot}:{}})}function dm(e,t){let n=em(e.definition);if(!n)return;let r;try{r=om(Wc(),e,n)}catch{return[]}return r.serves.map(e=>e.protocol).filter(e=>t===void 0||e.endpoints[t]!==void 0)}function fm(e,t,n){if(!e)return!1;let r=dm(e,t);return r===void 0?!0:n===void 0?r.length>0:r.some(e=>e.id===n)}function pm(e,t,n){if(!mm(t))throw Error(`Cannot create a model route without a profile type.`);return{profileType:t,protocol:n.protocol,provider:n.provider,definition:im(e,n.provider),apiId:n.apiId,decision:t===`decision`}}function mm(e){return[`text`,`image`,`speech`,`live`,`decision`,`embedding`].includes(e)}function hm(e,t){let n=gm(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 gm(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 gm(i,a,o);let s={path:a,label:_m(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 _m(e){let t=e.replace(/([a-z0-9])([A-Z])/g,`$1 $2`).toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}function vm(e,t){return t.split(`.`).reduce((e,t)=>e&&typeof e==`object`&&!Array.isArray(e)?e[t]:void 0,e)}function ym(e,t,n){let[r=``,...i]=t.split(`.`),{[r]:a,...o}=e,s=i.length?ym(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 bm=`studio`,xm={"observability.writeTo":bm};function Sm(e){return Object.entries(xm).reduce((e,[t,n])=>Cm(e,t.split(`.`),n),e)}function Cm(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=Cm(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 wm=new Set(Xc.map(e=>e.name));function Tm(e){return e.protocol===Od.id||e.protocol===Nf.id}function Em(e){return e.protocol===Rp.id||e.protocol===Dp.id}function Dm(e){return wm.has(e)}function Om(e,t,n){return n.mode===`demo`?n.keys.runs(e,t?.definition):fm(t,e)}var km={text:`fast`,image:`image`,speech:`voice`,live:`live`,decision:`decision`,embedding:`embedding`};function Am(e,t){let n=t?.(e)??{...jm(e===`decision`?`typesafe`:`gemini`,e),apiId:``};return{modelId:km[e],...n}}function jm(e,t){let n=Qp.find(t=>t.id===e),r=n&&dm(n,t)?.[0];if(!r)throw Error(`The studio provider '${e}' serves no ${t} agents.`);return{protocol:r.id,provider:e}}function Mm(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 Nm=5,Pm=100,Fm=120;function Im(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`||j(e.properties)?`object`:Array.isArray(e.enum)?`string`:`unknown`}function Lm(e){return j(e.items)?e.items:void 0}function Rm(e){let t=e?.enum;return Array.isArray(t)&&t.length>0&&t.every(e=>typeof e==`string`)?t:void 0}function zm(e,t){let n=e[t];return typeof n==`number`&&Number.isFinite(n)?n:void 0}function Bm(e,t){let n=zm(e,`minimum`),r=zm(e,`maximum`);return t&&n!==void 0&&r!==void 0&&r>n&&r-n<=Pm?{kind:`range`,min:n,max:r}:{kind:`number`,isInteger:t,...n===void 0?{}:{min:n},...r===void 0?{}:{max:r}}}function Vm(e){if(e.format===`date`)return{kind:`date`};let t=zm(e,`maxLength`);return{kind:`text`,isLong:t!==void 0&&t>Fm,type:e.format===`email`?`email`:`text`}}function Hm(e){let t=Lm(e),n=Rm(t);if(n)return{kind:`choices`,options:n};let r=t?Im(t):`unknown`;return r===`string`||r===`number`||r===`integer`?{kind:`words`}:t&&r===`object`?{kind:`rows`,item:t}:{kind:`json`}}function Um(e){let t=Rm(e);if(t)return{kind:`choice`,options:t,isMenu:t.length>Nm};switch(Im(e)){case`boolean`:return{kind:`switch`};case`number`:return Bm(e,!1);case`integer`:return Bm(e,!0);case`string`:return Vm(e);case`array`:return Hm(e);case`object`:return j(e.properties)?{kind:`group`,schema:e}:{kind:`json`};default:return{kind:`json`}}}function Wm(e){return new Set(Array.isArray(e.required)?e.required.filter(e=>typeof e==`string`):[])}function Gm(e){let t=j(e.properties)?e.properties:{},n=Wm(e);return Object.entries(t).flatMap(([e,t])=>j(t)?[{key:e,label:typeof t.title==`string`&&t.title?t.title:Qe(e),...typeof t.description==`string`&&t.description?{description:t.description}:{},isRequired:n.has(e),control:Um(t)}]:[])}function Km(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=Km(e);if(t)return t.value;switch(Im(e)){case`number`:case`integer`:return zm(e,`minimum`)??1;case`boolean`:return!0;case`array`:return[];case`object`:return Jm(e);case`string`:case`unknown`:return`example`}}function Jm(e){let t=j(e.properties)?e.properties:{},n=new Set(Wm(e)),r={};for(let[e,i]of Object.entries(t))j(i)&&(n.has(e)?r[e]=qm(i):Array.isArray(i.examples)&&i.examples.length&&(r[e]=i.examples[0]));return r}function Ym(e){return Jm(e)}function Xm(e,t,n){let r={...e};return n===void 0||n===``?delete r[t]:r[t]=n,r}function Zm(e,t,n=``){return j(t)?Gm(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`?Zm(e.control.schema,r,i):[]}):[]}var Qm=`{
7
+ "type": "object",
8
+ "properties": {
9
+ "query": { "type": "string" }
10
+ },
11
+ "required": ["query"]
12
+ }`,$m=`{
13
+ "type": "object",
14
+ "properties": {
15
+ "result": { "type": "string" }
16
+ },
17
+ "required": ["result"]
18
+ }`;function eh(e){return jt(e)}function th(e){return Jm(e)}var nh={"<":`\\u003C`,">":`\\u003E`,"\u2028":`\\u2028`,"\u2029":`\\u2029`};function rh(e){return`'${JSON.stringify(e).slice(1,-1).replaceAll(`\\"`,`"`).replaceAll(`'`,`\\'`).replace(/[<>\u2028\u2029]/g,e=>nh[e]??e)}'`}function ih(e,t=rh){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?e:t(e)}function ah(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{eh(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{kc as $,Tn as $n,Wa as $t,Zp as A,ei as An,Yt as Ar,fs as At,cm as B,or as Bn,Ht as Br,Za as Bt,Qp as C,Ti as Cn,an as Cr,jo as Ct,nm as D,yi as Dn,nn as Dr,Uo as Dt,im as E,Ei as En,rn as Er,Vo as Et,hm as F,pi as Fn,Nt as Fr,yo as Ft,Xc as G,Mn as Gn,so as Gt,ml as H,Rn as Hn,to as Ht,lm as I,vi as In,It as Ir,Y as It,Jc as J,Pn as Jn,io as Jt,qc as K,Zn as Kn,oo as Kt,om as L,jr as Ln,Bt as Lr,po as Lt,um as M,kr as Mn,zt as Mr,Go as Mt,Xp as N,zr as Nn,F as Nr,vo as Nt,em as O,ii as On,tn as Or,Q as Ot,vm as P,Yr as Pn,Mt as Pr,bo as Pt,Hc as Q,vr as Qn,Ka as Qt,dm as R,Mr as Rn,Ft as Rr,$a as Rt,Yp as S,Ci as Sn,L as Sr,bs as St,rm as T,Di as Tn,Qt as Tr,hs as Tt,ll as U,Nn as Un,ro as Ut,ym as V,Ln as Vn,Qa as Vt,ol as W,Gn as Wn,co as Wt,Gc as X,Fn as Xn,Ya as Xt,Kc as Y,In as Yn,qa as Yt,Wc as Z,ir as Zn,Ga as Zt,Dm as _,zi as _n,Sn as _r,gc as _t,rh as a,xa as an,nr as ar,Mc as at,Om as b,Wi as bn,on as br,ys as bt,Ym as c,ea as cn,tr as cr,Pc as ct,Gm as d,aa as dn,cr as dr,wc as dt,Ja as en,jn as er,yc as et,Xm as f,$i as fn,Sr as fr,Sc as ft,Em as g,Bi as gn,yn as gr,hc as gt,Tm as h,Vi as hn,wn as hr,_c as ht,ah as i,wa as in,er as ir,Tc as it,pm as j,Si as jn,Vt as jr,ps as jt,tm as k,Dr as kn,Kt as kr,us as kt,Zm as l,ra as ln,$n as lr,Dc as lt,jm as m,Yi as mn,fn as mr,Fc as mt,$m as n,q as nn,An as nr,xc as nt,th as o,ia as on,qn as or,jc as ot,bm as p,Qi as pn,On as pr,vc as pt,Yc as q,sr as qn,ao as qt,ih as r,K as rn,En as rr,Nc as rt,eh as s,ta as sn,Xn as sr,Cc as st,Qm as t,Va as tn,Un as tr,bc as tt,Jm as u,na as un,Hn as ur,Ac as ut,Mm as v,Hi as vn,un as vr,mc as vt,sm as w,Oi as wn,en as wr,is as wt,Sm as x,Ui as xn,cn as xr,ws as xt,Am as y,Mi as yn,ln as yr,Js as yt,fm as z,ri as zn,I as zr,Xa as zt};
@@ -1,3 +1,3 @@
1
- import{$n as e,C as t,M as n,Wt as r,_r as i,cn as a,cr as o,h as ee,ir as s,j as c,mr as l,n as u,p as d,pn as te,qn as ne,sr as re,t as ie,y as f,z as ae,zt as p}from"./tool-schema-idaOe2nI.js";import{En as m,Sn as h,qt as g,rn as oe,tn as se}from"./shaped-data-BcarWqd5.js";import{a as ce,r as _}from"./live-ingress-lDUGPwth.js";var le=[{id:`identity`,profilePath:`identity`,role:`root`,optional:!1,editor:`structural`,label:`Identity`,ownsFields:[`profile.id`,`profile.type`]},{id:`models`,profilePath:`models`,role:`spine`,optional:!1,editor:`structural`,label:`Models`,ownsFields:[`profile.defaultModel`,`profile.allowModelSelect`,`profile.maxSteps`,`providerContinuation`]},{id:`modelBinding`,profilePath:`models.*`,role:`branch`,parent:`models`,optional:!1,editor:`structural`,label:`Model binding`},{id:`decision`,profilePath:`decision`,role:`spine`,optional:!1,editor:`structural`,label:`Decision`,ownsFields:[`inputs`]},{id:`image`,profilePath:`image`,role:`spine`,optional:!1,editor:`structural`,label:`Image`},{id:`speech`,profilePath:`speech`,role:`spine`,optional:!1,editor:`structural`,label:`Speech`},{id:`live`,profilePath:`live`,role:`spine`,optional:!1,editor:`structural`,label:`Live`},{id:`tools`,profilePath:`tools`,role:`spine`,optional:!1,editor:`structural`,label:`Tools`},{id:`toolSpec`,profilePath:`tools.allow`,role:`branch`,parent:`tools`,optional:!0,editor:`structural`,label:`Tool`},{id:`inputs`,profilePath:`inputs`,role:`spine`,optional:!1,editor:`structural`,label:`Inputs`},{id:`outputs`,profilePath:`outputs`,role:`spine`,optional:!0,editor:`structural`,label:`Outputs`},{id:`turnBehaviour`,profilePath:`turnBehaviour`,role:`spine`,optional:!0,editor:`structural`,label:`Turn behaviour`},{id:`guardrails`,profilePath:`guardrails`,role:`spine`,optional:!0,editor:`structural`,label:`Guardrails`},{id:`observability`,profilePath:`observability`,role:`spine`,optional:!0,editor:`structural`,label:`Observability`},{id:`labels`,profilePath:`labels`,role:`spine`,optional:!0,editor:`structural`,label:`Labels`}],ue={identity:l,inputs:i(`inputs`).filter(e=>e!==`decision`)},v=le.map(e=>({...e,profileTypes:ue[e.id]??i(e.profilePath)}));function de(e){return v.find(t=>t.id===e)}function fe(e){return e.modelBindings.length>1}function pe(e){return e.modelBindings.some(t=>t.provider!==`local`&&!n(e.providers,t).keySlot)}function me(e,t){let r={provider:t.provider,keySlot:t.keySlot||e.models.key,fallbackKeySlot:t.fallbackKeySlot||e.models.fallbackKey},i=n(e.providers,r);return{...i,given:{keySlot:!!i.keySlot&&!r.keySlot,fallbackKeySlot:!!i.fallbackKeySlot&&!r.fallbackKeySlot}}}function he(e){let t=e.efforts.map(({alias:e})=>e.trim()).filter(Boolean);return new Set(t).size>1}function ge(e){return e.attachmentsAccept.length>0||e.voiceAccept.length>0}var y=e,b={compactMaxTokens:32e3,compactAt:.75,compactKeep:4},x={"continue.instruction":`turnBehaviour`,"canary.bind_note":`guardrails`,"quota.exhausted":`guardrails`,"repair.default_guidance":`outputs`,"egress.default_repair_guidance":`guardrails`,"egress.refusal":`guardrails`};function S(e){return`${e}-${crypto.randomUUID().slice(0,8)}`}function C(e){return{key:S(`model`),modelId:`fast`,protocol:`openRouter`,provider:`openrouter`,apiId:``,options:{},timeoutMs:null,efforts:[],defaultEffort:``,allowEffortSelect:!1,summaries:null,maxOutputTokens:null,temperature:null,builtInTools:[],...e}}var w=`Studio stub tool — returns a fixed result.`;function T(e){return{key:S(`tool`),toolName:`my_tool`,toolType:`function`,description:w,category:`studio`,access:s[0],permission:o[0],loadTier:re[0],paths:[`*`],inputJson:ie,outputJson:u,...e}}function E(e,t,n){return(!e.description.trim()||e.description===w)&&n?{agentKey:t,description:`Asks ${n} and returns its answer.`}:{agentKey:t}}function D(){return{name:``,kind:`words`,pattern:``,flags:``,words:[]}}function O(){return{key:``,label:``,at:m(h,()=>`ignore`),patterns:[D()],hint:``}}function k(){let e=te(void 0);return{canaryBindNote:``,detect:m(g,t=>({...e.detect[t]})),sources:Object.fromEntries(se.map(e=>[e,{theorem:!0,patterns:[],hint:``}])),own:[],quotaEnabled:!1,quotaPerDay:null,quotaMessage:``,allow:{ungiven_images:{hosts:[],fromTools:!0},ungiven_links:{hosts:[],fromTools:!0}},innocentNames:[],blockedReplyOnBlock:``,blockedReplyMaxRetries:null,egressRepairGuidance:``,egressRefusal:``,allowPrivateNetworks:!1,allowedHosts:[],allowedSchemes:[],taintAfterRemoteRead:``,taintRemoteDestination:``}}function A(){let e=ce({});return{writeTo:d,destination:d,sampleRate:e.sampleRate,include:{...e.include},scrub:{sensitive:!!e.scrub.sensitive,injection:!!e.scrub.injection,canary:!!e.scrub.canary},retainForDays:null,rotateAfterMiB:null,resourceJson:``}}function j(e){return e.map(([e,t])=>({key:S(`criterion`),label:e,text:t}))}function M(){return{contract:`guardrails.tool_call.v1`,maxStateBytes:null,questions:[{key:S(`question`),id:`verdict`,type:`choice`,instructions:`Given what the user asked for and what the call would do, should it run?`,criteria:j([[`allow`,`Safe, and what the user asked for.`],[`flag`,`Probably fine, but unusual or sensitive enough for a person to look first.`],[`block`,`Harmful, or clearly beyond what the user asked for.`]])},{key:S(`question`),id:`risk`,type:`score`,instructions:`How much harm would this call do if it were wrong?`,criteria:j([[``,`Low: reversible, and affects only the user.`],[``,`High: hard to undo, or affects other people or money.`]])}],images:[]}}var N=JSON.stringify({context:`The user asked the agent to tidy up old screenshots on their desktop.`,tool_call:{name:`delete_files`,path:`~/Documents`,recursive:!0},outcome:`Would delete 1,284 files, including tax_return_2025.pdf.`},null,2),P=JSON.stringify(`The user asked to tidy screenshots. The proposed call recursively deletes 1,284 files, including a tax return.`),F=`To clear your desktop, select the screenshots and move them to the Trash. Empty the Trash to delete them for good.(Screen captures save to the desktop by default. You can change where they go in the Screenshot app's Options menu.(Press Command-Shift-5 to record the screen or capture a window. Recordings are saved as movie files next to your screenshots.(Stacks group desktop files by kind, date or tag, so a cluttered desktop folds into a few piles you can open one at a time.(Deleted files stay in the Trash for 30 days. Drag a file out of the Trash to put it back where it was.(When your disk is almost full, open Storage settings and review the largest files. Old downloads and installers are safe to remove.(Offloading unused apps frees space and keeps their documents. Reinstalling an app brings its data back.(Photos you have backed up can be optimised so the originals live in the cloud and smaller copies stay on the device.(Your plan renews on the same date each month. You can see the next charge under Billing, then Upcoming invoices.(To get a refund, open the invoice and choose Request refund. Charges from the last 14 days are refunded in full.(Update your card under Billing, then Payment methods. The new card is used for the next renewal, not for past invoices.(Annual plans cost two months less than paying monthly. Switching mid-term credits the unused months to the new plan.(Invoices are emailed as PDFs and list your company name and tax number. Edit those details before the invoice is issued.(Turn on two-step verification under Security. You will be asked for a code from your authenticator app each time you sign in on a new device.(If you forget your password, choose Forgot password on the sign-in page. The reset link expires after one hour.(Review signed-in devices under Security and sign out any you don't recognise. This ends their sessions immediately.(Passkeys replace your password with your fingerprint or face. Create one under Security, then Passkeys.(To close your account, export your data first. Closing deletes your workspace after a 30-day grace period.(Share a folder by choosing Share, then entering an email address. Viewers can read; editors can change and delete.(Public links work for anyone who has them. Set an expiry date, or turn the link off to stop sharing at once.(Transfer ownership of a folder before you leave a team, or its contents will be archived with your account.(Lisbon has mild, wet winters and warm, dry summers. Expect highs near 28 °C in August.(The best months for the Algarve coast are May, June and September, when the beaches are warm and the crowds are thin.(Trams in Lisbon climb the steep hills of Alfama and Graça. Line 28 is the famous one, and the busiest.(For a crisp pizza base, preheat the oven and the baking tray together at the highest setting for at least thirty minutes.(Rest steak for five minutes after cooking so the juices settle back into the meat instead of running onto the board.`.split(`(`).join(`
1
+ import{$n as e,C as t,M as n,Wt as r,_r as i,cn as a,cr as o,h as ee,ir as s,j as c,mr as l,n as u,p as d,pn as te,qn as ne,sr as re,t as ie,y as f,z as ae,zt as p}from"./tool-schema-BrqSc6vO.js";import{En as m,Sn as h,qt as g,rn as oe,tn as se}from"./shaped-data-BcarWqd5.js";import{a as ce,r as _}from"./live-ingress-lDUGPwth.js";var le=[{id:`identity`,profilePath:`identity`,role:`root`,optional:!1,editor:`structural`,label:`Identity`,ownsFields:[`profile.id`,`profile.type`]},{id:`models`,profilePath:`models`,role:`spine`,optional:!1,editor:`structural`,label:`Models`,ownsFields:[`profile.defaultModel`,`profile.allowModelSelect`,`profile.maxSteps`,`providerContinuation`]},{id:`modelBinding`,profilePath:`models.*`,role:`branch`,parent:`models`,optional:!1,editor:`structural`,label:`Model binding`},{id:`decision`,profilePath:`decision`,role:`spine`,optional:!1,editor:`structural`,label:`Decision`,ownsFields:[`inputs`]},{id:`image`,profilePath:`image`,role:`spine`,optional:!1,editor:`structural`,label:`Image`},{id:`speech`,profilePath:`speech`,role:`spine`,optional:!1,editor:`structural`,label:`Speech`},{id:`live`,profilePath:`live`,role:`spine`,optional:!1,editor:`structural`,label:`Live`},{id:`tools`,profilePath:`tools`,role:`spine`,optional:!1,editor:`structural`,label:`Tools`},{id:`toolSpec`,profilePath:`tools.allow`,role:`branch`,parent:`tools`,optional:!0,editor:`structural`,label:`Tool`},{id:`inputs`,profilePath:`inputs`,role:`spine`,optional:!1,editor:`structural`,label:`Inputs`},{id:`outputs`,profilePath:`outputs`,role:`spine`,optional:!0,editor:`structural`,label:`Outputs`},{id:`turnBehaviour`,profilePath:`turnBehaviour`,role:`spine`,optional:!0,editor:`structural`,label:`Turn behaviour`},{id:`guardrails`,profilePath:`guardrails`,role:`spine`,optional:!0,editor:`structural`,label:`Guardrails`},{id:`observability`,profilePath:`observability`,role:`spine`,optional:!0,editor:`structural`,label:`Observability`},{id:`labels`,profilePath:`labels`,role:`spine`,optional:!0,editor:`structural`,label:`Labels`}],ue={identity:l,inputs:i(`inputs`).filter(e=>e!==`decision`)},v=le.map(e=>({...e,profileTypes:ue[e.id]??i(e.profilePath)}));function de(e){return v.find(t=>t.id===e)}function fe(e){return e.modelBindings.length>1}function pe(e){return e.modelBindings.some(t=>t.provider!==`local`&&!n(e.providers,t).keySlot)}function me(e,t){let r={provider:t.provider,keySlot:t.keySlot||e.models.key,fallbackKeySlot:t.fallbackKeySlot||e.models.fallbackKey},i=n(e.providers,r);return{...i,given:{keySlot:!!i.keySlot&&!r.keySlot,fallbackKeySlot:!!i.fallbackKeySlot&&!r.fallbackKeySlot}}}function he(e){let t=e.efforts.map(({alias:e})=>e.trim()).filter(Boolean);return new Set(t).size>1}function ge(e){return e.attachmentsAccept.length>0||e.voiceAccept.length>0}var y=e,b={compactMaxTokens:32e3,compactAt:.75,compactKeep:4},x={"continue.instruction":`turnBehaviour`,"canary.bind_note":`guardrails`,"quota.exhausted":`guardrails`,"repair.default_guidance":`outputs`,"egress.default_repair_guidance":`guardrails`,"egress.refusal":`guardrails`};function S(e){return`${e}-${crypto.randomUUID().slice(0,8)}`}function C(e){return{key:S(`model`),modelId:`fast`,protocol:`openRouter`,provider:`openrouter`,apiId:``,options:{},timeoutMs:null,efforts:[],defaultEffort:``,allowEffortSelect:!1,summaries:null,maxOutputTokens:null,temperature:null,builtInTools:[],...e}}var w=`Studio stub tool — returns a fixed result.`;function T(e){return{key:S(`tool`),toolName:`my_tool`,toolType:`function`,description:w,category:`studio`,access:s[0],permission:o[0],loadTier:re[0],paths:[`*`],inputJson:ie,outputJson:u,...e}}function E(e,t,n){return(!e.description.trim()||e.description===w)&&n?{agentKey:t,description:`Asks ${n} and returns its answer.`}:{agentKey:t}}function D(){return{name:``,kind:`words`,pattern:``,flags:``,words:[]}}function O(){return{key:``,label:``,at:m(h,()=>`ignore`),patterns:[D()],hint:``}}function k(){let e=te(void 0);return{canaryBindNote:``,detect:m(g,t=>({...e.detect[t]})),sources:Object.fromEntries(se.map(e=>[e,{theorem:!0,patterns:[],hint:``}])),own:[],quotaEnabled:!1,quotaPerDay:null,quotaMessage:``,allow:{ungiven_images:{hosts:[],fromTools:!0},ungiven_links:{hosts:[],fromTools:!0}},innocentNames:[],blockedReplyOnBlock:``,blockedReplyMaxRetries:null,egressRepairGuidance:``,egressRefusal:``,allowPrivateNetworks:!1,allowedHosts:[],allowedSchemes:[],taintAfterRemoteRead:``,taintRemoteDestination:``}}function A(){let e=ce({});return{writeTo:d,destination:d,sampleRate:e.sampleRate,include:{...e.include},scrub:{sensitive:!!e.scrub.sensitive,injection:!!e.scrub.injection,canary:!!e.scrub.canary},retainForDays:null,rotateAfterMiB:null,resourceJson:``}}function j(e){return e.map(([e,t])=>({key:S(`criterion`),label:e,text:t}))}function M(){return{contract:`guardrails.tool_call.v1`,maxStateBytes:null,questions:[{key:S(`question`),id:`verdict`,type:`choice`,instructions:`Given what the user asked for and what the call would do, should it run?`,criteria:j([[`allow`,`Safe, and what the user asked for.`],[`flag`,`Probably fine, but unusual or sensitive enough for a person to look first.`],[`block`,`Harmful, or clearly beyond what the user asked for.`]])},{key:S(`question`),id:`risk`,type:`score`,instructions:`How much harm would this call do if it were wrong?`,criteria:j([[``,`Low: reversible, and affects only the user.`],[``,`High: hard to undo, or affects other people or money.`]])}],images:[]}}var N=JSON.stringify({context:`The user asked the agent to tidy up old screenshots on their desktop.`,tool_call:{name:`delete_files`,path:`~/Documents`,recursive:!0},outcome:`Would delete 1,284 files, including tax_return_2025.pdf.`},null,2),P=JSON.stringify(`The user asked to tidy screenshots. The proposed call recursively deletes 1,284 files, including a tax return.`),F=`To clear your desktop, select the screenshots and move them to the Trash. Empty the Trash to delete them for good.(Screen captures save to the desktop by default. You can change where they go in the Screenshot app's Options menu.(Press Command-Shift-5 to record the screen or capture a window. Recordings are saved as movie files next to your screenshots.(Stacks group desktop files by kind, date or tag, so a cluttered desktop folds into a few piles you can open one at a time.(Deleted files stay in the Trash for 30 days. Drag a file out of the Trash to put it back where it was.(When your disk is almost full, open Storage settings and review the largest files. Old downloads and installers are safe to remove.(Offloading unused apps frees space and keeps their documents. Reinstalling an app brings its data back.(Photos you have backed up can be optimised so the originals live in the cloud and smaller copies stay on the device.(Your plan renews on the same date each month. You can see the next charge under Billing, then Upcoming invoices.(To get a refund, open the invoice and choose Request refund. Charges from the last 14 days are refunded in full.(Update your card under Billing, then Payment methods. The new card is used for the next renewal, not for past invoices.(Annual plans cost two months less than paying monthly. Switching mid-term credits the unused months to the new plan.(Invoices are emailed as PDFs and list your company name and tax number. Edit those details before the invoice is issued.(Turn on two-step verification under Security. You will be asked for a code from your authenticator app each time you sign in on a new device.(If you forget your password, choose Forgot password on the sign-in page. The reset link expires after one hour.(Review signed-in devices under Security and sign out any you don't recognise. This ends their sessions immediately.(Passkeys replace your password with your fingerprint or face. Create one under Security, then Passkeys.(To close your account, export your data first. Closing deletes your workspace after a 30-day grace period.(Share a folder by choosing Share, then entering an email address. Viewers can read; editors can change and delete.(Public links work for anyone who has them. Set an expiry date, or turn the link off to stop sharing at once.(Transfer ownership of a folder before you leave a team, or its contents will be archived with your account.(Lisbon has mild, wet winters and warm, dry summers. Expect highs near 28 °C in August.(The best months for the Algarve coast are May, June and September, when the beaches are warm and the crowds are thin.(Trams in Lisbon climb the steep hills of Alfama and Graça. Line 28 is the famous one, and the busiest.(For a crisp pizza base, preheat the oven and the baking tray together at the highest setting for at least thirty minutes.(Rest steak for five minutes after cooking so the juices settle back into the meat instead of running onto the board.`.split(`(`).join(`
2
2
 
3
3
  `),I=`How do I delete every screenshot on my desktop?`;function L(e,t=`choice`){let n=K(`question`,e.decision.questions.map(e=>e.id),e=>`question_${e}`);return{key:S(`question`),id:n,type:t,instructions:``,criteria:z(t)}}function R(e,t,n){let r=t.replace(/\.[^.]*$/,``).toLowerCase().replace(/[^a-z0-9]+/g,`_`).replace(/^_|_$/g,``)||`image`,i=K(r,e.decision.images.map(e=>e.name),e=>`${r}_${e}`);return{key:S(`image`),name:i,...n}}function z(e){return e===`noul`||e===`box`?[]:j(e===`choice`?[[`yes`,``],[`no`,``]]:[[``,``],[``,``]])}function _e(){return{identity:{agentId:``,profileType:``,handle:``,system:``,systemByRoleJson:``},included:[`observability`,`labels`],models:{defaultModel:``,allowModelSelect:!1,maxSteps:null,key:``},modelBindings:[],providers:[...t],tools:{t2Loader:``,parallel:!1},toolSpecs:[],inputs:{text:!0,attachmentsAccept:[],voiceAccept:[],maxFiles:null,maxBytes:null,maxTurnBytes:null,limitsByMimeJson:``,slotsJson:``,contextFrom:[],contextMaxChars:null},outputs:{mode:`text`,schemaId:``,schemaJson:``,streamMode:``,streamThoughts:!0,validationEnabled:!1,maxRetries:null,itemRules:{},repairGuidance:``},turnBehaviour:{resumeEnabled:!1,allowContinue:[],autoContinue:[],maxContinues:null,continueInstruction:``,allowSteering:r({type:`text`}),atStepLimit:`stop`},guardrails:k(),observability:A(),image:{aspectRatio:``,resolution:``,mimeType:``,quality:``,background:``,n:null,seed:null,outputCompression:null,includeText:!1,references:[]},speech:{voice:``,style:``,speed:null,format:``},live:{ingressAudio:_(`audio`),ingressVideo:_(`video`),ingressText:_(`text`),voice:``,sessionResumption:!1,greeting:``,resumedPrompt:``,resumedAfterMs:null,contextCompression:!1,compressionTriggerTokens:null,compressionTargetTokens:null,transcriptionInput:!1,transcriptionOutput:!1,vadActivityHandling:``,vadStartSensitivity:``,vadEndSensitivity:``,vadPrefixPaddingMs:null,vadSilenceDurationMs:null},decision:M(),labels:{}}}var ve=new Set([`guardrails`]);function B(e,t){return e.profileTypes.includes(t)&&!(t===`decision`&&ve.has(e.id))}function V(e){let t=e.identity.profileType;if(!t)return[`identity`];let n=new Set(e.included);return v.filter(e=>e.role!==`branch`&&B(e,t)&&(!e.optional||n.has(e.id))).map(e=>e.id)}function H(e,t){let n=e.identity.profileType;return n!==``&&i(t).includes(n)}function ye(e){return H(e,`identity.system`)&&oe(e.guardrails.detect,`canary_leak`)}function be(e){let t=e.identity.profileType;return t!==``&&p.includes(t)}function U(e){let t=e.identity.profileType;return t?v.filter(n=>n.role===`spine`&&n.optional&&B(n,t)&&!e.included.includes(n.id)).map(e=>e.id):[]}function xe(e){return{...e,attachmentsAccept:e.attachmentsAccept.filter(e=>a(ne,e)),voiceAccept:[]}}function Se(e,t,n){let r=e.modelBindings.find(e=>e.key===t);return r?{...e,models:n.modelId!==void 0&&e.models.defaultModel===r.modelId?{...e.models,defaultModel:n.modelId}:e.models,modelBindings:e.modelBindings.map(e=>e.key===t?{...e,...n}:e)}:e}function W(e,t){if(t.some(t=>t.modelId===e))return e;let[n,...r]=t;return n&&!r.length?n.modelId:``}function Ce(e,t){if(!e.modelBindings.find(e=>e.key===t))return e;let n=e.modelBindings.filter(e=>e.key!==t);return{...e,models:{...e.models,defaultModel:W(e.models.defaultModel,n)},modelBindings:n}}function G(e,t){let n=e.identity.profileType,r=n&&n!==`host`?n:`text`,i=e.modelBindings.map(e=>e.modelId),a=f(r,t),o=K(a.modelId,i,e=>`${a.modelId}${e}`);return C({...a,modelId:o})}function we(e){return T({toolName:K(`my_tool`,e.toolSpecs.map(e=>e.toolName),e=>`my_tool_${e}`)})}function K(e,t,n){let r=new Set(t),i=e;for(let e=2;r.has(i);e++)i=n(e);return i}function Te(e,t,n){if(t===`host`)return{...e,identity:{...e.identity,profileType:t}};let r=e.modelBindings.filter(r=>{let i=c(e.providers,t,r),a=e.providers.find(e=>e.id===r.provider);return ae(a,t,r.protocol)&&!Oe(n,t,i)}),i={...e,identity:{...e.identity,profileType:t},modelBindings:r},a=r.length?r:[G(i,n?.start)],o=!e.models.key&&pe({...i,modelBindings:a}),s=t===`speech`&&!e.speech.voice.trim()&&a.some(n=>ee(c(e.providers,t,n)));return{...i,inputs:t===`image`?xe(e.inputs):e.inputs,...s?{speech:{...e.speech,voice:Ee}}:{},models:{...e.models,defaultModel:W(e.models.defaultModel,a),key:o?ke:e.models.key},modelBindings:a}}var Ee=`Kore`,De=[`text`,`image`,`speech`,`live`,`decision`];function Oe(e,t,n){if(!e)return!1;let r=t=>e.models(t,n.definition).some(e=>e.id===n.apiId.trim());return!r(t)&&De.some(e=>e!==t&&r(e))}var ke=`slot_a`;function Ae(e,t){return U(e).includes(t)?{...e,included:[...e.included,t]}:e}function je(e,t){return{...e,included:e.included.filter(e=>e!==t)}}function q(e){return`modelBinding:${e}`}var J=`toolSpec:`;function Y(e){return`${J}${e}`}function X(e){return e.startsWith(J)?e.slice(9):void 0}var Z=`provider:`;function Me(e){return`${Z}${e}`}function Ne(e){return e.startsWith(Z)?e.slice(9):void 0}var Pe=new Map(v.map(e=>[e.id,e.label]));function Q(e){return Pe.get(e)??e}function Fe(e,t){let[n,r]=t.split(`:`,2);if(n===`modelBinding`&&r!==void 0)return e.modelBindings.some(e=>e.key===r)?{facet:n,key:r}:void 0;let i=X(t);if(i!==void 0)return e.toolSpecs.some(e=>e.key===i)?{facet:`toolSpec`,key:i}:void 0;let a=V(e);if(r===void 0&&a.includes(t))return{facet:t}}function Ie(e,t){return t===`models`?e.modelBindings.map(e=>({id:q(e.key),ref:{facet:`modelBinding`,key:e.key},label:e.modelId.trim()||Q(`modelBinding`),children:[]})):t===`tools`?$(e.toolSpecs):[]}function $(e){return e.map(e=>({id:Y(e.key),ref:{facet:`toolSpec`,key:e.key},label:e.toolName.trim()||Q(`toolSpec`),children:[]}))}function Le(e){let t=V(e).filter(e=>e!==`identity`).map(t=>({id:t,ref:{facet:t},label:Q(t),children:Ie(e,t)}));return{id:`identity`,ref:{facet:`identity`},label:e.identity.agentId.trim()||Q(`identity`),children:t}}export{G as A,he as B,je as C,z as D,Ae as E,Ce as F,ge as H,Te as I,be as L,D as M,we as N,R as O,ye as P,Se as R,S,U as T,v as U,fe as V,de as W,_e as _,Le as a,H as b,$ as c,I as d,F as f,E as g,y as h,Fe as i,O as j,L as k,b as l,x as m,Ne as n,X as o,P as p,Me as r,Y as s,q as t,N as u,C as v,K as w,V as x,T as y,me as z};